[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

+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];