From ca3a6b0e15e33ccb9c73adea0e2fb7f3752bb172 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Wed, 2 Dec 2026 19:59:11 +0100 Subject: [PATCH] [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. --- crates/vetta-infer-gw/src/serve.rs | 27 ++++------ crates/vetta-infer-hip/src/lib.rs | 67 +++++++++++++++++++++++-- crates/vetta-infer-ld/src/layer.rs | 41 ++++++++++++--- crates/vetta-infer-ld/src/packer.rs | 16 +++--- kernels/hip/vetta_kernels.hip | 36 ++++++------- proofs/prefix_cache.lean | 78 +++++++++++++++++++++++++++++ 6 files changed, 210 insertions(+), 55 deletions(-) diff --git a/crates/vetta-infer-gw/src/serve.rs b/crates/vetta-infer-gw/src/serve.rs index 58cf44b..575a163 100644 --- a/crates/vetta-infer-gw/src/serve.rs +++ b/crates/vetta-infer-gw/src/serve.rs @@ -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>>, - states_cap: Cell, /// 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 = g.ids[..start].to_vec(); history.reserve(n_prompt - start + effective_max_new); let mut logits: Option = 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 diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 8655d5d..5b08f14 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -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 { 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 = (0..n_head * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.04).collect(); + let kval: Vec = (0..(p + 1) * n_kv * hd).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect(); + let vraw: Vec = (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 { let group = n_head / n_kv; let mut out = vec![0f32; n_head * hd]; diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index dc10b91..fc89bbf 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -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 { 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::, _>>()?; @@ -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 = 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 { @@ -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) { diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs index ac3f7b7..45b3eda 100644 --- a/crates/vetta-infer-ld/src/packer.rs +++ b/crates/vetta-infer-ld/src/packer.rs @@ -13,7 +13,7 @@ pub fn load_raw(ar: &SafetensorsArchive, name: &str) -> Result Result = 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 = if mxfp8 { vec![1.0; n_exp] diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index a9b323b..fda7193 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -270,7 +270,7 @@ __global__ void k_flash_gqa_decode(const float* __restrict__ q, float lmax = -INFINITY; for (int s = tid; s < seq; s += nt) { - const float* ks = kh + (size_t)s * hd; + const float* ks = kh + (size_t)(s % seq) * hd; float dot = 0.f; for (int d = 0; d < hd; ++d) dot += qh[d] * ks[d]; dot *= scale; @@ -304,7 +304,7 @@ __global__ void k_flash_gqa_decode(const float* __restrict__ q, float* oh = out + (size_t)h * hd; for (int d = tid; d < hd; d += nt) { float acc = 0.f; - for (int s = 0; s < seq; ++s) acc += scores[s] * inv * vh[(size_t)s * hd + d]; + for (int s = 0; s < seq; ++s) acc += scores[s] * inv * vh[(size_t)(s % seq) * hd + d]; oh[d] = acc; } } @@ -358,7 +358,7 @@ __global__ void k_flash_swa_gqa_decode(const float* __restrict__ q, float lmax = sink; for (int p = tid; p < n_win; p += nt) { const int s = k_start + p; - const float* ks = kh + (size_t)s * hd; + const float* ks = kh + (size_t)(s % seq) * hd; float dot = 0.f; for (int d = 0; d < hd; ++d) dot += qh[d] * ks[d]; dot *= scale; @@ -397,7 +397,7 @@ __global__ void k_flash_swa_gqa_decode(const float* __restrict__ q, float acc = 0.f; for (int p = 0; p < n_win; ++p) { const int s = k_start + p; - acc += scores[p] * inv * vh[(size_t)s * hd + d]; + acc += scores[p] * inv * vh[(size_t)(s % seq) * hd + d]; } if (gate) acc *= 1.f / (1.f + __expf(-gate[(size_t)h * hd + d])); oh[d] = acc; @@ -411,7 +411,7 @@ extern "C" int vetta_flash_swa_gqa_decode(const float* q, const float* k, const const float* sink_logit, const float* gate, float* scores_scratch, vetta_stream_t stream) { if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd <= 0 || (n_head % n_kv) != 0) return 1; - if (cur_pos < 0 || cur_pos >= seq) return 1; + if (cur_pos < 0) return 1; const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0; const int n_win = cur_pos - k_start + 1; const int nt = 256; @@ -456,7 +456,7 @@ __global__ void k_flash_swa_gqa_decode_f16(const float* __restrict__ q, float lmax = sink; for (int p = tid; p < n_win; p += nt) { const int s = k_start + p; - const uint16_t* ks = kh + (size_t)s * hd; + const uint16_t* ks = kh + (size_t)(s % seq) * hd; float dot = 0.f; for (int d = 0; d < hd; ++d) dot += qh[d] * f16_to_f32(ks[d]); dot *= scale; @@ -495,7 +495,7 @@ __global__ void k_flash_swa_gqa_decode_f16(const float* __restrict__ q, float acc = 0.f; for (int p = 0; p < n_win; ++p) { const int s = k_start + p; - acc += scores[p] * inv * f16_to_f32(vh[(size_t)s * hd + d]); + acc += scores[p] * inv * f16_to_f32(vh[(size_t)(s % seq) * hd + d]); } if (gate) acc *= 1.f / (1.f + __expf(-gate[(size_t)h * hd + d])); oh[d] = acc; @@ -509,7 +509,7 @@ extern "C" int vetta_flash_swa_gqa_decode_f16(const float* q, const uint16_t* k, const float* sink_logit, const float* gate, float* scores_scratch, vetta_stream_t stream) { if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd <= 0 || (n_head % n_kv) != 0) return 1; - if (cur_pos < 0 || cur_pos >= seq) return 1; + if (cur_pos < 0) return 1; const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0; const int n_win = cur_pos - k_start + 1; const int nt = 256; @@ -561,7 +561,7 @@ __global__ void k_flash_swa_gqa_prefill_f16(const float* __restrict__ q, float lmax = sink; for (int p = tid; p < n_win; p += nt) { const int s = k_start + p; - const uint16_t* ks = kh + (size_t)s * hd; + const uint16_t* ks = kh + (size_t)(s % seq) * hd; float dot = 0.f; for (int d = 0; d < hd; ++d) dot += qh[d] * f16_to_f32(ks[d]); dot *= scale; @@ -601,7 +601,7 @@ __global__ void k_flash_swa_gqa_prefill_f16(const float* __restrict__ q, float acc = 0.f; for (int p = 0; p < n_win; ++p) { const int s = k_start + p; - acc += scores[p] * inv * f16_to_f32(vh[(size_t)s * hd + d]); + acc += scores[p] * inv * f16_to_f32(vh[(size_t)(s % seq) * hd + d]); } if (gh) acc *= 1.f / (1.f + __expf(-gh[d])); oh[d] = acc; @@ -1896,7 +1896,7 @@ __global__ void k_kv_store(const float* __restrict__ k_in, const float* __restri if (tid == 0) fac_s = rsqrtf(red[0] / (float)hd + rms_eps); __syncthreads(); if (tid < hd) { - const size_t off = (size_t)h * seq * hd + (size_t)pos * hd + tid; + const size_t off = (size_t)h * seq * hd + (size_t)(pos % seq) * hd + tid; k_cache[off] = kv[tid]; v_cache[off] = v * fac_s; } @@ -1905,7 +1905,7 @@ __global__ void k_kv_store(const float* __restrict__ k_in, const float* __restri extern "C" int vetta_kv_store(const float* k_in, const float* v_in, float* k_cache, float* v_cache, int pos, int n_kv, int hd, int seq, float rms_eps, vetta_stream_t stream) { - if (n_kv <= 0 || hd <= 0 || hd > 256 || seq <= 0 || pos < 0 || pos >= seq) return 1; + if (n_kv <= 0 || hd <= 0 || hd > 256 || seq <= 0 || pos < 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_kv_store<<>>(k_in, v_in, k_cache, v_cache, pos, n_kv, hd, seq, rms_eps); HIP_CHECK(hipGetLastError()); @@ -1933,7 +1933,7 @@ __global__ void k_kv_store_f16(const float* __restrict__ k_in, const float* __re if (tid == 0) fac_s = rsqrtf(red[0] / (float)hd + rms_eps); __syncthreads(); if (tid < hd) { - const size_t off = (size_t)h * seq * hd + (size_t)pos * hd + tid; + const size_t off = (size_t)h * seq * hd + (size_t)(pos % seq) * hd + tid; k_cache[off] = __half_as_ushort(__float2half_rn(kv[tid])); v_cache[off] = __half_as_ushort(__float2half_rn(v * fac_s)); } @@ -1942,7 +1942,7 @@ __global__ void k_kv_store_f16(const float* __restrict__ k_in, const float* __re extern "C" int vetta_kv_store_f16(const float* k_in, const float* v_in, uint16_t* k_cache, uint16_t* v_cache, int pos, int n_kv, int hd, int seq, float rms_eps, vetta_stream_t stream) { - if (n_kv <= 0 || hd <= 0 || hd > 256 || seq <= 0 || pos < 0 || pos >= seq) return 1; + if (n_kv <= 0 || hd <= 0 || hd > 256 || seq <= 0 || pos < 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; k_kv_store_f16<<>>(k_in, v_in, k_cache, v_cache, pos, n_kv, hd, seq, rms_eps); HIP_CHECK(hipGetLastError()); @@ -1973,7 +1973,7 @@ __global__ void k_kv_store_f16_batched(const float* __restrict__ k_in, const flo if (tid == 0) fac_s = rsqrtf(red[0] / (float)hd + rms_eps); __syncthreads(); if (tid < hd) { - const size_t off = (size_t)h * seq * hd + (size_t)pos[m] * hd + tid; + const size_t off = (size_t)h * seq * hd + (size_t)(pos[m] % seq) * hd + tid; k_cache[off] = __half_as_ushort(__float2half_rn(kv[tid])); v_cache[off] = __half_as_ushort(__float2half_rn(v * fac_s)); } @@ -2588,8 +2588,8 @@ __global__ void __launch_bounds__(128) k_flash_swa_gqa_prefill_wmma( const int r = idx >> 5, c4 = idx & 31; const int kp = kb + r; uint16_t* dst = &kv.sK[r * FQ_LDK + c4 * 4]; - if (kp <= q_max_pos && kp < seq) { - *reinterpret_cast(dst) = *reinterpret_cast(k + ((size_t)kvh * seq + kp) * hd + c4 * 4); + if (kp <= q_max_pos) { + *reinterpret_cast(dst) = *reinterpret_cast(k + ((size_t)kvh * seq + (kp % seq)) * hd + c4 * 4); } else { *reinterpret_cast(dst) = make_uint2(0u, 0u); } } __syncthreads(); @@ -2655,7 +2655,7 @@ __global__ void __launch_bounds__(128) k_flash_swa_gqa_prefill_wmma( for (int idx = tid; idx < FQ_HD * FQ_BK; idx += 128) { const int d = idx >> 6, c = idx & 63; const int kp = kb + c; - kv.sVt[d * FQ_LDV + c] = (kp <= q_max_pos && kp < seq) ? v[((size_t)kvh * seq + kp) * hd + d] : (uint16_t)0; + kv.sVt[d * FQ_LDV + c] = (kp <= q_max_pos) ? v[((size_t)kvh * seq + (kp % seq)) * hd + d] : (uint16_t)0; } __syncthreads(); // 3E. O[16,128] += P[16,64] @ V[64,128] (4 kt x 8 d-tiles) diff --git a/proofs/prefix_cache.lean b/proofs/prefix_cache.lean index 683b3c4..694174c 100644 --- a/proofs/prefix_cache.lean +++ b/proofs/prefix_cache.lean @@ -306,4 +306,82 @@ theorem kvStart_full (n w : Nat) (h : n ≤ w) : kvStart w n = 0 := by have : min n w = n := Nat.min_eq_left h omega +/-! + Part E — SWA KV ring (2026-12-02). The 40 SWA pools store a circular ring of + `R = swa_win + chunk_cap` positions (`slot R p = p % R`); the 8 global pools keep + a linear cache of `MAX_CONTEXT` positions, where `p < R` makes `%` the identity + (`global_slot_id`). Correctness of the ring rests on three facts, proved here + BEFORE the kernel/`LayerState` change (AGENTS.md invariant 6): + E1 `slot_inj` / `window_slots_distinct`: a causal window spans ≤ R positions, so + its slots are pairwise distinct (a read never aliases two logical positions). + E2 `ring_no_clobber`: with `R ≥ swa_win + chunk`, the writes of one batched chunk + (`[c, c+chunk)`) cannot overwrite a slot still needed by an earlier token's + window read (`[c-swa_win, c+chunk)`), except the same logical position. + E3 `global_slot_id`: below the ring length the modulo is the identity, so the + global (linear) pools and all small-seq parity tests are unaffected. +-/ + +/-- Ring slot of logical position `p` in a ring of `R` positions. -/ +def slot (R p : Nat) : Nat := p % R + +/-- E1 core: two positions at distance < R with the same slot are equal. -/ +theorem slot_inj (R x y : Nat) (_hR : 0 < R) (hxy : x ≤ y) (hlt : y - x < R) + (h : x % R = y % R) : x = y := by + have hx := Nat.mod_add_div x R + have hy := Nat.mod_add_div y R + rw [h] at hx + have hq : x / R ≤ y / R := Nat.div_le_div_right hxy + have hAB : R * (x / R) ≤ R * (y / R) := Nat.mul_le_mul_left R hq + have hyx : y - x = R * (y / R) - R * (x / R) := by omega + have h2 : y - x = R * (y / R - x / R) := by + rw [← Nat.mul_sub_left_distrib] at hyx + exact hyx + have hd : y / R - x / R = 0 := by + cases Nat.eq_zero_or_pos (y / R - x / R) with + | inl h0 => exact h0 + | inr hpos => + have h1d : 1 ≤ y / R - x / R := by omega + have hge : R ≤ R * (y / R - x / R) := by + simpa [Nat.mul_one] using Nat.mul_le_mul_left R h1d + omega + rw [hd, Nat.mul_zero] at h2 + omega + +/-- E1: within any half-open interval of length ≤ R the ring slot is injective, + so a causal window (span ≤ swa_win < R) never reads one slot as two positions. -/ +theorem window_slots_distinct (R a b p q : Nat) (hR : 0 < R) (hb : b ≤ R) + (hp : a ≤ p) (hp' : p < a + b) (hq : a ≤ q) (hq' : q < a + b) + (h : slot R p = slot R q) : p = q := by + unfold slot at h + have hlt : p - q < R := by omega + have hlt' : q - p < R := by omega + cases Nat.le_total p q with + | inl hle => exact slot_inj R p q hR hle (by omega) h + | inr hle => exact (slot_inj R q p hR hle (by omega) h.symm).symm + +/-- E2: a batched chunk's KV writes cannot clobber a slot an earlier token of the + same chunk still reads, provided `R ≥ swa_win + chunk`. `w` ranges over the + chunk's writes `[c, c+chunk)`, `r` over the union of window reads + `[c-swa_win, c+chunk)`; equal slots force `w = r` (the causal same-position + write-then-read, which is ordered by the kernel). -/ +theorem ring_no_clobber (R win chunk c w r : Nat) (hR : 0 < R) + (hcap : win + chunk ≤ R) + (hw : c ≤ w) (hw' : w < c + chunk) + (hr : c - win ≤ r) (hr' : r < c + chunk) + (h : slot R w = slot R r) : w = r := by + unfold slot at h + cases Nat.le_total w r with + | inl hle => + have hlt : r - w < R := by omega + exact slot_inj R w r hR hle hlt h + | inr hle => + have hlt : w - r < R := by omega + exact (slot_inj R r w hR hle hlt h.symm).symm + +/-- E3: below the ring length the modulo is the identity — global (linear) pools + and every small-`seq` parity test behave exactly as before the ring. -/ +theorem global_slot_id (R p : Nat) (h : p < R) : slot R p = p := by + unfold slot + exact Nat.mod_eq_of_lt h + end VettaPrefixCache \ No newline at end of file