[Core] flat VRAM: SWA KV ring + fixed global KV + bounded scratch bucketing (reviewer p1+p2)

Punto 2: the 40 SWA pools now store a circular ring of swa_win+SWA_CHUNK_CAP(512)
=1536 positions (slot=pos%seq) instead of the whole 32768 context (~5GiB wasted);
the 8 global pools keep a linear max_context cache allocated ONCE. KV capacities
are fixed per layer kind => no drop+realloc when a session crosses a 4096 multiple.
kv_store{,_f16,_f16_batched} write pos%seq; flash decode/prefill/prefill_wmma read
p%seq (global seq>pos => identity). snapshot/restore map the window onto ring slots
with 1 or 2 pitched copies (wrap). serve clamps prefill chunk to SWA_CHUNK_CAP so
ring>=swa_win+chunk holds. proofs/prefix_cache.lean Part E (0 sorryAx): slot_inj,
window_slots_distinct, ring_no_clobber, global_slot_id. New GPU swa_ring_kv_parity
(R=1536, P=2000) vs an independent host LINEAR oracle: 1.48e-5.
Punto 1: BUF_POOL buckets pooled allocs in (4KiB,64MiB] to a power of two so variable
batch tails / future speculative B converge to a closed size set (no hipMalloc/Free
churn); larger allocs stay exact. Weight uploads (load_raw/load_bf16_as_f32/expert
matrix/arena) switched to alloc_unpooled: resident, exact, never pooled (rounding
them had added ~11GiB).
MEASURED gfx1150 FP16 KV chunk256: READY ~21.0GB; multi-turn 2048->13000->2048->5000
vram flat ~23.1-23.7GB (only bounded cap-8 checkpoint turnover, no KV resize);
prefill 2048 ~12.2s, 13000 ~78.6s (~6ms/tok). Suite GREEN hip37 ld23 gw4, CPU23, Lean6.
This commit is contained in:
adm committed 2026-12-02 19:59:11 +01:00
1 parent a4752953fb
commit ca3a6b0e15
6 files changed
+210 -55

No files matched your search

+10 -17
View File
@@ -16,7 +16,7 @@
//! is callable from an integration test without spawning the binary.
use std::io::{self, BufRead, Write};
use std::cell::{Cell, RefCell};
use std::cell::RefCell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc};
use std::time::Instant;
@@ -123,10 +123,11 @@ impl PrefixCache {
// request (same cap + pass count); restore overwrites its KV
// prefix + hist rings. The stale KV tail beyond seq_len is never
// read (causal attention), so reuse is exact (restore_equiv).
let want = if is_swa(ip) { vetta_infer_ld::layer::swa_ring(d) } else { max_seq };
let reuse = states[ip].as_ref()
.map_or(false, |st| st.max_seq == max_seq && st.k_cache.len() == s.k_cache.len());
.map_or(false, |st| st.max_seq == want && st.k_cache.len() == s.k_cache.len());
if !reuse {
states[ip] = Some(new_state(d, max_seq, s.k_cache.len())?);
states[ip] = Some(new_state(d, want, s.k_cache.len())?);
}
states[ip].as_mut().unwrap().restore(d, s)?;
}
@@ -178,7 +179,6 @@ pub struct InklingEngine {
/// `states_cap` (a 4096-bucket >= prompt+max_new). Eliminates the per-request
/// ~3.75 GB alloc/free VRAM sawtooth; grown only when a request crosses a bucket.
states: RefCell<Vec<Option<LayerState>>>,
states_cap: Cell<usize>,
/// Resident context window (advertised in READY). Defaults to MAX_CONTEXT;
/// VETTA_MAX_CONTEXT / `--max-context` raise it (like strata) for longer agents.
max_context: usize,
@@ -237,7 +237,6 @@ impl InklingEngine {
cap: t.final_logit_softcapping as f32,
prefix: RefCell::new(PrefixCache::new()),
states: RefCell::new(Vec::new()),
states_cap: Cell::new(0),
max_context,
})
}
@@ -315,19 +314,13 @@ pub fn serve_gen(
emit_all(emit, sess.on_error("prompt exceeds context window"));
return;
};
let max_seq = (n_prompt + effective_max_new + 2).min(max_context);
// Persistent KV states: size once to a 4096-bucket cap >= max_seq and reuse
// across requests (no per-request ~3.75 GB alloc/free sawtooth). Grow only when
// a request crosses the bucket.
let need = max_seq.next_multiple_of(4096).min(max_context);
if eng.states_cap.get() < need || eng.states.borrow().len() != eng.n_layers {
// KV capacities are FIXED per layer kind (SWA ring = swa_win+chunk_cap, global
// = max_context), allocated once and never resized across requests: no
// drop+realloc when a session crosses a 4096 multiple (reviewer punto 2).
if eng.states.borrow().len() != eng.n_layers {
*eng.states.borrow_mut() = (0..eng.n_layers).map(|_| None).collect();
eng.states_cap.set(need);
}
// KV stride = the PERSISTENT cap, which may exceed this request's bucket after
// a longer session. Reuse it (restore/forward take this, not `need`) so returning
// from a long context to a short one does NOT reallocate the KV from scratch.
let cap = eng.states_cap.get();
let cap = max_context;
let mut states = eng.states.borrow_mut();
// Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore
@@ -385,7 +378,7 @@ pub fn serve_gen(
let mut history: Vec<i32> = g.ids[..start].to_vec();
history.reserve(n_prompt - start + effective_max_new);
let mut logits: Option<DeviceBuf> = None;
let chunk = prefill_chunk_size();
let chunk = prefill_chunk_size().min(vetta_infer_ld::layer::SWA_CHUNK_CAP);
let suffix = &g.ids[start..];
let mut done = 0usize;
// Monotonic 512-grid threshold: split a chunk exactly on the next grid boundary
+63 -4
View File
@@ -288,13 +288,21 @@ fn raw_alloc(bytes: usize) -> Result<*mut std::os::raw::c_void, String> {
impl DeviceBuf {
pub fn alloc(bytes: usize) -> Result<Self, String> {
ensure_sync_init();
// Bucket pooled allocations in (4KiB, 64MiB] to a power of two so variable
// batch tails (bu = suffix % chunk, and tomorrow speculative B=2..16)
// converge to a closed set of sizes instead of churning distinct HashMap
// keys / hipMalloc-hipFree (reviewer punto 1). Kernels stride by the logical
// size, never read the slack. Larger allocations (resident weight tensors /
// expert arenas) stay EXACT: rounding them to a power of two would nearly
// double weight VRAM. KV (alloc_unpooled) stays exact too.
let cap = if bytes > 4096 && bytes <= 64 * 1024 * 1024 { bytes.next_power_of_two() } else { bytes };
if pool_enabled() {
if let Some(ptr) = BUF_POOL.with(|p| p.borrow_mut().get_mut(&bytes).and_then(|v| v.pop())) {
POOL_BYTES.with(|c| c.set(c.get().saturating_sub(bytes)));
return Ok(Self { ptr, bytes, pooled: true });
if let Some(ptr) = BUF_POOL.with(|p| p.borrow_mut().get_mut(&cap).and_then(|v| v.pop())) {
POOL_BYTES.with(|c| c.set(c.get().saturating_sub(cap)));
return Ok(Self { ptr, bytes: cap, pooled: true });
}
}
Ok(Self { ptr: raw_alloc(bytes)?, bytes, pooled: true })
Ok(Self { ptr: raw_alloc(cap)?, bytes: cap, pooled: true })
}
/// Allocate a buffer that is ALWAYS `hipFree`'d on drop (never pooled). For
/// large per-request buffers whose size varies between requests (the KV
@@ -1144,6 +1152,57 @@ mod gpu_tests {
}
}
/// SWA KV ring (proofs/prefix_cache.lean Part E): KV stride R=1536 but logical
/// cur_pos P=2000 (> R). kv_store writes window [P-1023..P] at slot p%R; flash
/// decode reads p%R. Independent oracle: a host LINEAR cache of size P+1 holding
/// the same per-position values (V RMS-normalized exactly as kv_store does).
/// If the ring write/read wrap were wrong the window would alias and diverge.
#[test]
#[ignore]
fn swa_ring_kv_parity() {
let (n_head, n_kv, hd, r, p, win) = (8usize, 2usize, 128usize, 1536usize, 2000usize, 1024i32);
let eps = 1e-6f32;
let scale = 1.0f32 / (hd as f32).sqrt();
let q: Vec<f32> = (0..n_head * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.04).collect();
let kval: Vec<f32> = (0..(p + 1) * n_kv * hd).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect();
let vraw: Vec<f32> = (0..(p + 1) * n_kv * hd).map(|i| ((i % 37) as f32 - 18.0) * 0.02).collect();
// host linear oracle caches (V normalized per head exactly like kv_store)
let mut kr = vec![0f32; (p + 1) * n_kv * hd];
let mut vr = vec![0f32; (p + 1) * n_kv * hd];
for pos in 0..=p {
for h in 0..n_kv {
let base = (pos * n_kv + h) * hd;
let dst = (h * (p + 1) + pos) * hd; // head-major [n_kv, seq, hd]
let mut ss = 0f32;
for d in 0..hd { ss += vraw[base + d] * vraw[base + d]; }
let fac = 1.0f32 / (ss / hd as f32 + eps).sqrt();
for d in 0..hd {
kr[dst + d] = kval[base + d];
vr[dst + d] = vraw[base + d] * fac;
}
}
}
let dk = DeviceBuf::alloc_unpooled(n_kv * r * hd * 4).unwrap(); dk.zero_async().unwrap();
let dv = DeviceBuf::alloc_unpooled(n_kv * r * hd * 4).unwrap(); dv.zero_async().unwrap();
let dki = DeviceBuf::alloc(n_kv * hd * 4).unwrap();
let dvi = DeviceBuf::alloc(n_kv * hd * 4).unwrap();
for pos in (p as i32 - win + 1)..=(p as i32) {
let base = (pos as usize * n_kv) * hd;
dki.h2d(&kval[base..base + n_kv * hd]).unwrap();
dvi.h2d(&vraw[base..base + n_kv * hd]).unwrap();
kv_store(&dki, &dvi, &dk, &dv, pos, n_kv as i32, hd as i32, r as i32, eps).unwrap();
}
let dq = DeviceBuf::alloc(q.len() * 4).unwrap(); dq.h2d(&q).unwrap();
let dout = DeviceBuf::alloc(n_head * hd * 4).unwrap();
flash_swa_gqa_decode(&dq, &dk, &dv, &dout, n_head as i32, n_kv as i32, r as i32, hd as i32, scale, win, p as i32, None, 0, None, None).unwrap();
let mut got = vec![0f32; n_head * hd]; dout.d2h(&mut got).unwrap();
let want = cpu_swa_attn(&q, &kr, &vr, n_head, n_kv, p + 1, hd, scale, win, p as i32, None, 0, None, None);
let mut max_rel = 0f32;
for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); }
eprintln!("swa_ring R={r} P={p} win={win} max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-4, "swa ring KV parity failed: {max_rel}");
}
fn cpu_attn(q: &[f32], k: &[f32], v: &[f32], n_head: usize, n_kv: usize, seq: usize, hd: usize, scale: f32) -> Vec<f32> {
let group = n_head / n_kv;
let mut out = vec![0f32; n_head * hd];
+33 -8
View File
@@ -297,11 +297,19 @@ impl LayerState {
let es = if f16_kv() { 2 } else { 4 };
let win = if swa { seq_len.min(d.swa_win.max(0) as usize) } else { seq_len };
let kv_start = seq_len - win;
// Ring-aware source slots: the window [kv_start, seq_len) maps to
// [kv_start % r, ..) in the SWA ring (r = self.max_seq); it wraps at most
// once because win <= swa_win < r. Global pools have kv_start = 0, no wrap.
let r = self.max_seq;
let s0 = kv_start % r;
let first = win.min(r - s0);
let row = win * d.hd * es;
let src_off = kv_start * d.hd * es;
let snap_kv = |src: &DeviceBuf| -> Result<DeviceBuf, String> {
let b = DeviceBuf::alloc_unpooled(d.n_kv * row)?;
b.copy2d_at(0, src, src_off, row, self.max_seq * d.hd * es, row, d.n_kv)?;
b.copy2d_at(0, src, s0 * d.hd * es, row, r * d.hd * es, first * d.hd * es, d.n_kv)?;
if win > first {
b.copy2d_at(first * d.hd * es, src, 0, row, r * d.hd * es, (win - first) * d.hd * es, d.n_kv)?;
}
Ok(b)
};
let k_cache = self.k_cache.iter().map(snap_kv).collect::<Result<Vec<_>, _>>()?;
@@ -326,13 +334,21 @@ impl LayerState {
pub fn restore(&mut self, d: &Dims, snap: &LayerSnapshot) -> Result<(), String> {
let es = if f16_kv() { 2 } else { 4 };
let win = snap.seq_len - snap.kv_start;
let r = self.max_seq;
let s0 = snap.kv_start % r;
let first = win.min(r - s0);
let row = win * d.hd * es;
let dst_off = snap.kv_start * d.hd * es;
for (dst, src) in self.k_cache.iter().zip(&snap.k_cache) {
dst.copy2d_at(dst_off, src, 0, self.max_seq * d.hd * es, row, row, d.n_kv)?;
dst.copy2d_at(s0 * d.hd * es, src, 0, r * d.hd * es, row, first * d.hd * es, d.n_kv)?;
if win > first {
dst.copy2d_at(0, src, first * d.hd * es, r * d.hd * es, row, (win - first) * d.hd * es, d.n_kv)?;
}
}
for (dst, src) in self.v_cache.iter().zip(&snap.v_cache) {
dst.copy2d_at(dst_off, src, 0, self.max_seq * d.hd * es, row, row, d.n_kv)?;
dst.copy2d_at(s0 * d.hd * es, src, 0, r * d.hd * es, row, first * d.hd * es, d.n_kv)?;
if win > first {
dst.copy2d_at(0, src, first * d.hd * es, r * d.hd * es, row, (win - first) * d.hd * es, d.n_kv)?;
}
}
for i in 0..3 {
self.hist_k[i].copy_from(&snap.hist_k[i], snap.hist_k[i].bytes)?;
@@ -693,7 +709,7 @@ pub fn forward_swa_layers(
let mut blocks: Vec<DeviceBuf> = Vec::new();
for &ip in schedule {
let w = cache.swa_layer(ip)?;
let mut st = new_state(d, max_seq, 1)?;
let mut st = new_state(d, swa_ring(d), 1)?;
layer_forward_swa(cache, &w, &mut st, d, &cur, &mut blocks, pos, 0, None)?;
}
Ok((cur, blocks))
@@ -702,6 +718,15 @@ pub fn forward_swa_layers(
/// Full-attention physical layers (the rest are sliding-window).
pub fn is_swa(ip: usize) -> bool { !matches!(ip, 5 | 11 | 17 | 23) }
/// Max batched-prefill chunk the SWA ring is sized for. The ring invariant
/// (proofs/prefix_cache.lean Part E `ring_no_clobber`) requires
/// `ring >= swa_win + chunk`; serve clamps the chunk to this cap.
pub const SWA_CHUNK_CAP: usize = 512;
/// Circular KV capacity of a SWA pool: `swa_win + SWA_CHUNK_CAP` positions instead
/// of the whole context (the causal window never reads older rows). Global pools
/// keep a linear `max_context` cache. Sized once, never resized across requests.
pub fn swa_ring(d: &Dims) -> usize { d.swa_win.max(0) as usize + SWA_CHUNK_CAP }
/// Build the stacked cross-pass msg_queries [4, hidden] for a core layer ip:
/// [q_cp[2i], kv_cp[2i], kv_cp[2i+1], q_cp[2i+1]] with i = ip - core_start.
fn load_msg_queries(cache: &WeightCache, ip: usize, hidden: usize) -> Result<DeviceBuf, String> {
@@ -853,7 +878,7 @@ fn run_layer(
if states[ip].is_none() {
// Core layers run 3 loop passes (3 distinct KV pools); prelude/coda run 1.
let n_passes = if (6..18).contains(&ip) { 3 } else { 1 };
states[ip] = Some(new_state(d, max_seq, n_passes)?);
states[ip] = Some(new_state(d, if is_swa(ip) { swa_ring(d) } else { max_seq }, n_passes)?);
}
let st = states[ip].as_mut().unwrap();
let r = if is_swa(ip) {
@@ -976,7 +1001,7 @@ fn run_layer_batched(
) -> Result<(), String> {
if states[ip].is_none() {
let n_passes = if (6..18).contains(&ip) { 3 } else { 1 };
states[ip] = Some(new_state(d, max_seq, n_passes)?);
states[ip] = Some(new_state(d, if is_swa(ip) { swa_ring(d) } else { max_seq }, n_passes)?);
}
let st = states[ip].as_mut().unwrap();
if is_swa(ip) {
+8 -8
View File
@@ -13,7 +13,7 @@ pub fn load_raw(ar: &SafetensorsArchive, name: &str) -> Result<DeviceBuf, String
let bytes = info.byte_len() as usize;
let mut host = vec![0u8; bytes];
ar.read_slice(name, 0, &mut host)?;
let buf = DeviceBuf::alloc(bytes)?;
let buf = DeviceBuf::alloc_unpooled(bytes)?;
buf.h2d_bytes(&host)?;
Ok(buf)
}
@@ -29,7 +29,7 @@ pub fn load_bf16_as_f32(ar: &SafetensorsArchive, name: &str) -> Result<DeviceBuf
let mut host = vec![0u8; bytes];
ar.read_slice(name, 0, &mut host)?;
let f: Vec<f32> = host.chunks_exact(2).map(|c| bf16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect();
let buf = DeviceBuf::alloc(f.len() * 4)?;
let buf = DeviceBuf::alloc_unpooled(f.len() * 4)?;
buf.h2d(&f)?;
Ok(buf)
}
@@ -70,8 +70,8 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat:
ar.read_slice(&wname, (e * w_per_e) as u64, &mut wbytes)?;
let mut sbytes = vec![0u8; s_per_e];
ar.read_slice(&sname, (e * s_per_e) as u64, &mut sbytes)?;
let packed = DeviceBuf::alloc(w_per_e)?; packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc(s_per_e)?; scales.h2d_bytes(&sbytes)?;
let packed = DeviceBuf::alloc_unpooled(w_per_e)?; packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc_unpooled(s_per_e)?; scales.h2d_bytes(&sbytes)?;
return Ok(ExpertMatrix { packed, scales, outer: 1.0, n, k, mxfp8: true });
}
@@ -99,9 +99,9 @@ pub fn load_expert_matrix(ar: &SafetensorsArchive, layer: usize, e: usize, mat:
};
let outer = amax / den;
let packed = DeviceBuf::alloc(w_per_e)?;
let packed = DeviceBuf::alloc_unpooled(w_per_e)?;
packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc(s_per_e)?;
let scales = DeviceBuf::alloc_unpooled(s_per_e)?;
scales.h2d_bytes(&sbytes)?;
Ok(ExpertMatrix { packed, scales, outer, n, k, mxfp8: false })
}
@@ -169,8 +169,8 @@ pub fn load_expert_arena(ar: &SafetensorsArchive, layer: usize, mat: &str) -> Re
ar.read_slice(&wname, 0, &mut wbytes)?;
let mut sbytes = vec![0u8; n_exp * s_per_e];
ar.read_slice(&sname, 0, &mut sbytes)?;
let packed = DeviceBuf::alloc(wbytes.len())?; packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc(sbytes.len())?; scales.h2d_bytes(&sbytes)?;
let packed = DeviceBuf::alloc_unpooled(wbytes.len())?; packed.h2d_bytes(&wbytes)?;
let scales = DeviceBuf::alloc_unpooled(sbytes.len())?; scales.h2d_bytes(&sbytes)?;
let outer_h: Vec<f32> = if mxfp8 {
vec![1.0; n_exp]