Skip to main content

memra_kv/
lib.rs

1//! memra-kv — the dual KV/recurrent cache, extracted (Phase D, ARCHITECTURE-H100.md §5).
2//!
3//! Moved VERBATIM from memra-engine/src/cache.rs behind the `KvDev` seam: the cache only
4//! ever needed 7 device ops (alloc/copy/set), so the trait is that surface and nothing
5//! more. The append/dequant KERNELS stay in the engine fatbins — this crate owns the
6//! structure, sizing math, and the KV format policy (env-selected, shared by the engine's
7//! fatbin router and every cache consumer). memra-engine re-exports this as `cache` so
8//! call sites are unchanged.
9
10
11// ---------------- KV format policy (env-selected; moved from memra-engine) ----------------
12
13/// Env-selected KV cache formats (MEMRA_KV_K / MEMRA_KV_V). The engine's flash-fatbin router
14/// and the cache sizing below MUST agree — both read this one function.
15pub fn kv_cache_formats() -> (&'static str, &'static str) {
16    static F: std::sync::OnceLock<(&'static str, &'static str)> = std::sync::OnceLock::new();
17    *F.get_or_init(|| {
18        let k = match std::env::var("MEMRA_KV_K").as_deref() {
19            Ok("fp8") => "fp8",
20            Ok("q8_0") | Ok("") | Err(_) => "q8_0",
21            Ok(o) => panic!("MEMRA_KV_K={o} unsupported (q8_0 | fp8)"),
22        };
23        let v = match std::env::var("MEMRA_KV_V").as_deref() {
24            Ok("q4_0") => "q4_0",
25            Ok("fp8") => "fp8",
26            Ok("q5_1") | Ok("") | Err(_) => "q5_1",
27            Ok(o) => panic!("MEMRA_KV_V={o} unsupported (q5_1 | q4_0 | fp8)"),
28        };
29        if (k, v) != ("q8_0", "q5_1") {
30            eprintln!("[memra] KV cache format: K={k} V={v} (non-default — new numeric config)");
31        }
32        (k, v)
33    })
34}
35
36/// Per-32-element block bytes for the selected (K, V) formats.
37pub fn kv_blk_bytes() -> (usize, usize) {
38    let (k, v) = kv_cache_formats();
39    let kb = match k { "fp8" => 32, _ => 34 };
40    let vb = match v { "q4_0" => 18, "fp8" => 32, _ => 24 };
41    (kb, vb)
42}
43
44/// FP8-GLOBALS switch (MEMRA_GEMMA_GKV, default ON): gemma global (hd512) layers keep
45/// their KV in e4m3 — the dequant-latency arc (HANDOVER). Windowed layers stay q8_0/q5_1.
46pub fn gkv_on() -> bool {
47    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
48    *ON.get_or_init(|| std::env::var("MEMRA_GEMMA_GKV").map(|v| v != "0").unwrap_or(true))
49}
50
51/// FP8-WINDOWED switch (MEMRA_GEMMA_WKV; serving-mode default): SPEC serving (MEMRA_DRAFT
52/// set) -> OFF, plain -> ON — the acceptance-vs-depth record lives on the engine-side
53/// history of `Engine::wkv_on` (git). Explicit env always wins.
54pub fn wkv_on() -> bool {
55    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
56    *ON.get_or_init(|| std::env::var("MEMRA_GEMMA_WKV").map(|v| v != "0")
57        .unwrap_or_else(|_| std::env::var("MEMRA_DRAFT").is_err()))
58}
59
60/// Per-model FP8-KV door (-1 = unset → env/default off; 0 = off; 1 = on). Set at qwen
61/// model load: the 2026-07-12 arc closed per-model — 9B +0.7-4% scaling with depth,
62/// 27B flat (weight-bound), 35B −2% (fp8 format-gates its v3 dp4a lane off). Explicit
63/// MEMRA_KV_FP8 wins. 9B adoption attempt REVERTED by measurement 2026-07-29 (−1% at 12k
64/// on the then-current build) — loaders currently store 0.
65pub static KV_FP8_FORCE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
66
67/// QWEN FP8-KV switch (MEMRA_KV_FP8 explicit; else the per-model KV_FP8_FORCE door set
68/// at model load; else OFF). Non-gemma full-attn layers hold e4m3 K/V via the kf8vf8
69/// module.
70pub fn kv_fp8_on() -> bool {
71    static ENV: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
72    if let Some(v) = *ENV.get_or_init(|| std::env::var("MEMRA_KV_FP8").ok()
73        .map(|v| v == "1")) { return v; }
74    matches!(KV_FP8_FORCE.load(std::sync::atomic::Ordering::Relaxed), 1)
75}
76
77/// Step35 SWA-ring experiment (default OFF). The first cut is deliberately architecture-scoped:
78/// Gemma4's row-0-addressed window kernels cannot consume a rebased ring view.
79pub fn swa_ring_on() -> bool {
80    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
81    *ON.get_or_init(|| std::env::var("MEMRA_SWA_RING").as_deref() == Ok("1"))
82}
83
84/// With the SWA-ring door open, `prime_chunk_tokens` caps every legal chunk at this bound. The
85/// ring carries one whole maximum-size prime chunk in addition to the reader's window.
86pub const PRIME_CHUNK_MAX_TOKENS: usize = 4096;
87const SWA_VIEW_ALIGNMENT_ROWS: usize = 32;
88
89/// Physical rows required by the Step35 SWA reader contract. Prime starts at
90/// `(base_len - (window - 1)) & !31`, so at most 31 masked rows precede the live window.
91pub fn swa_ring_rows(window: usize, max_ctx: usize) -> usize {
92    max_ctx.min(window + PRIME_CHUNK_MAX_TOKENS + (SWA_VIEW_ALIGNMENT_ROWS - 1))
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub struct KvRing {
97    rows: usize,
98    window: usize,
99    base: usize,
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum KvRingAppend {
104    Contiguous {
105        write_row: usize,
106    },
107    Rebase {
108        src_row: usize,
109        keep_rows: usize,
110        new_base: usize,
111        write_row: usize,
112    },
113}
114
115impl KvRing {
116    pub fn new(rows: usize, window: usize) -> Self {
117        assert!(window > 0 && rows > 0, "invalid SWA ring geometry");
118        Self { rows, window, base: 0 }
119    }
120
121    pub fn rows(&self) -> usize { self.rows }
122    pub fn base(&self) -> usize { self.base }
123    pub fn window(&self) -> usize { self.window }
124
125    /// Plan a contiguous physical append. When the tail would wrap, retain the caller's exact
126    /// aligned read prefix at row zero; the following read remains one contiguous CUDA view.
127    pub fn append_plan(
128        &self,
129        len: usize,
130        retain_from: usize,
131        append_rows: usize,
132    ) -> Result<KvRingAppend, String> {
133        if len < self.base || retain_from < self.base || retain_from > len {
134            return Err(format!(
135                "SWA ring lapped required rows (base {}, retain {retain_from}, len {len})",
136                self.base
137            ));
138        }
139        let used = len - self.base;
140        if used > self.rows {
141            return Err(format!("SWA ring state exceeds capacity ({used} > {})", self.rows));
142        }
143        if used.saturating_add(append_rows) <= self.rows {
144            return Ok(KvRingAppend::Contiguous {
145                write_row: used % self.rows,
146            });
147        }
148
149        let keep_rows = len - retain_from;
150        if keep_rows.saturating_add(append_rows) > self.rows {
151            return Err(format!(
152                "SWA ring append does not fit (keep {keep_rows} + append {append_rows} > {})",
153                self.rows
154            ));
155        }
156        Ok(KvRingAppend::Rebase {
157            src_row: retain_from - self.base,
158            keep_rows,
159            new_base: retain_from,
160            write_row: keep_rows,
161        })
162    }
163
164    pub fn apply_rebase(&mut self, new_base: usize) {
165        debug_assert!(new_base >= self.base);
166        self.base = new_base;
167    }
168
169    pub fn physical_range(
170        &self,
171        start: usize,
172        end: usize,
173    ) -> Result<std::ops::Range<usize>, String> {
174        if start < self.base || end < start || end - self.base > self.rows {
175            return Err(format!(
176                "SWA ring view [{start},{end}) is outside resident [{},{})",
177                self.base,
178                self.base + self.rows
179            ));
180        }
181        let start_row = (start - self.base) % self.rows;
182        let len = end - start;
183        debug_assert!(start_row + len <= self.rows, "ring view must be contiguous after rebase");
184        Ok(start_row..start_row + len)
185    }
186
187    /// A rewind is usable only when the next aligned Step35 window view is still resident.
188    pub fn can_rewind_to(&self, len: usize) -> bool {
189        let raw = len.saturating_sub(self.window - 1);
190        let view_start = raw & !(SWA_VIEW_ALIGNMENT_ROWS - 1);
191        view_start >= self.base
192    }
193}
194
195// ---------------- the device seam ----------------
196
197/// The 7 device ops the cache needs — nothing more. Implemented by the engine (and by
198/// any future backend); all ops are stream-ordered on the implementor's worker stream.
199pub trait KvDev {
200    fn zeros(&self, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>>;
201    fn uninit(&self, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>>;
202    fn alloc_u8(&self, n: usize) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>>;
203    fn htod_i32(&self, v: &[i32]) -> Result<CudaSlice<i32>, Box<dyn std::error::Error>>;
204    fn clone_dtod(&self, src: &CudaSlice<f32>) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>>;
205    fn copy_into(&self, dst: &mut CudaSlice<f32>, off: usize, src: &CudaSlice<f32>, len: usize)
206                 -> Result<(), Box<dyn std::error::Error>>;
207    fn set_i32_one(&self, d: &mut CudaSlice<i32>, v: i32) -> Result<(), Box<dyn std::error::Error>>;
208}
209
210use memra_gguf::config::{LayerKind, ModelConfig};
211use cudarc::driver::CudaSlice;
212
213/// Per-full-attn-layer growing KV cache, resident on GPU. QUANTIZED (KVQUANT-PLAN §B):
214/// K stored q8_0 (34 B/32 elem), V stored q5_1 (24 B/32 elem). Per-token byte layout keeps the
215/// [token, kv_head, dim] element order so a 32-block never straddles a head (assert head_dim%32==0).
216/// Element-within-token index = kv_head*head_dim + d; block = idx/32; lane = idx%32.
217pub struct KvLayer {
218    pub k: CudaSlice<u8>,   // q8_0 packed, capacity max_ctx*k_tok_bytes
219    pub v: CudaSlice<u8>,   // q5_1 packed, capacity max_ctx*v_tok_bytes
220    pub kv_dim_k: usize,    // head_dim_k * n_head_kv  (K elements per token)
221    pub kv_dim_v: usize,    // head_dim_v * n_head_kv  (V elements per token)
222    pub k_tok_bytes: usize, // (kv_dim_k/32)*34
223    pub v_tok_bytes: usize, // (kv_dim_v/32)*24
224    pub len: usize,
225    /// Step35 SWA physical-row state. `len` remains absolute; `None` keeps the original flat
226    /// `[0, max_ctx)` addressing contract.
227    pub ring: Option<KvRing>,
228    /// Device-resident mirror of `len` (CUDA-GRAPH-PLAN Phase 2). Holds the KV write SLOT for the
229    /// append-dc kernel (old len, before this step's append); after `inc_seqlen` it holds the new
230    /// len == t_kv for fa_decode_dc. Kept in lock-step with the host `len`. i32[1].
231    pub len_d: CudaSlice<i32>,
232}
233
234impl KvLayer {
235    pub fn physical_rows(
236        &self,
237        start: usize,
238        end: usize,
239    ) -> Result<std::ops::Range<usize>, String> {
240        match &self.ring {
241            Some(ring) => ring.physical_range(start, end),
242            None => Ok(start..end),
243        }
244    }
245}
246
247/// Per-linear-attn-layer fixed recurrent state.
248/// conv_state and ssm_state are BOTH kept RESIDENT on GPU — the conv ring assemble + roll runs
249/// on-device (conv_assemble_and_roll), so there is no per-step dtoh/htod for either.
250pub struct RecurLayer {
251    pub conv_state: CudaSlice<f32>, // GPU [conv_dim, d_conv-1] (channel c, tap j at c*pad + j)
252    pub ssm_state: CudaSlice<f32>,  // GPU [d_state, d_state, num_v] transposed M[col][i]
253    /// PERSISTENT second SSM-state buffer for the gdn-scan double buffer (DECODE DETERMINISM FIX).
254    /// gdn_scan needs DISTINCT in/out state buffers. The old eager path allocated a fresh
255    /// `state_scratch` via `e.uninit` every step and swapped its pointer into `ssm_state`; that
256    /// per-step alloc/free churned the stream-ordered async pool, and the freed prior `ssm_state`
257    /// block was recycled by the next step's scratch while a kernel referencing the swapped-in state
258    /// was still in flight — a use-after-reuse that produced RUN-TO-RUN nondeterministic decode
259    /// (two identical prompt primes diverged). We instead PING-PONG between two STABLE resident
260    /// buffers (no per-step alloc/free, no pool churn): step writes into the spare, then swaps the
261    /// two owned buffers in place. Stable pointers, identical math. Sized like `ssm_state`.
262    pub ssm_state_alt: CudaSlice<f32>,
263}
264
265pub struct Cache {
266    pub kv: Vec<Option<KvLayer>>,
267    pub recur: Vec<Option<RecurLayer>>,
268    pub pos: usize,
269    pub max_ctx: usize,
270    /// BATCHED-TICK increment 2 component 3 (lean logits, 2026-08-01): device-side park of
271    /// this session's LAST logits row. Device-sampled rows in the batched serving tick skip
272    /// the [n_vocab] logits D2H entirely; the tick instead dtod-copies the row here (device
273    /// bandwidth, ~µs) so the ONE consumer that truly needs the final row — the KV-reuse
274    /// pool's park-at-retire (an empty-suffix resume samples from parked last_logits) —
275    /// can D2H it once at retire. Lazily allocated on the first lean tick; None on every
276    /// non-lean path (zero cost). Travels with the Cache into the reuse pool.
277    pub last_logits_dev: Option<CudaSlice<f32>>,
278    /// DFlash tap sink (dflash lane, 2026-07-13): when armed, the gemma4 verify/prime
279    /// trunks copy the residual stream AFTER each tapped layer into `buf` rows
280    /// ([t, n_taps*hidden] row-major — the drafter fc input layout). None on every
281    /// non-dflash path (zero cost).
282    pub dflash_taps: Option<DflashTapSink>,
283}
284
285/// The context-linear K/V layout for one full-attention layer. This is the single sizing source
286/// used by both `Cache::new_inner` and `cache_bytes_per_token`: admission must never reimplement
287/// Gemma's per-layer geometry or the active KV-format doors independently from the allocator.
288fn full_attention_kv_layout(cfg: &ModelConfig, il: u32) -> (usize, usize, usize, usize) {
289    debug_assert_eq!(cfg.layer_kind(il), LayerKind::FullAttention);
290    let n_head_kv = cfg.n_head_kv as usize;
291    let (kv_dim_k, kv_dim_v) = match &cfg.gemma4 {
292        Some(g) => {
293            let hd = if g.swa_pattern[il as usize] {
294                g.key_length_swa
295            } else {
296                g.key_length_global
297            } as usize;
298            // E4B ships a SCALAR head_count_kv (per-layer vec empty; scalar = 2 in
299            // the gguf, landing in cfg.n_head_kv): kv_dim = hd * 2 for BOTH kinds —
300            // swa 2x256 = 512, global 2x512 = 1024. The old fallback used
301            // key_length_global (512) for both, which HALVED the global layers' K/V
302            // (the attn writes wk.out_features = 1024 rows): every E4B global layer
303            // stored/attended half its K/V and the batched append read row strides
304            // wrong — THE cross-mode maxdiff-30 root (2026-07-12 bisect, il=5 slot-1
305            // byte forensics). 26B/31B keep the per-layer vec.
306            let d = match g.head_count_kv.get(il as usize) {
307                Some(n) => hd * *n as usize,
308                None => hd * n_head_kv,
309            };
310            (d, d)
311        }
312        None => (
313            cfg.head_dim_k as usize * n_head_kv,
314            cfg.head_dim_v as usize * n_head_kv,
315        ),
316    };
317    assert!(
318        kv_dim_k % 32 == 0 && kv_dim_v % 32 == 0,
319        "KVQUANT requires per-layer kv_dim_k%32==0 && kv_dim_v%32==0 \
320         (layer {il}: k={kv_dim_k} v={kv_dim_v})"
321    );
322    let (kbb, vbb) = kv_blk_bytes();
323    let g4_global_fp8 = gkv_on()
324        && cfg
325            .gemma4
326            .as_ref()
327            .is_some_and(|g| !g.swa_pattern[il as usize]);
328    let g4_windowed_fp8 = wkv_on()
329        && cfg
330            .gemma4
331            .as_ref()
332            .is_some_and(|g| g.swa_pattern[il as usize]);
333    let qwen_fp8 = kv_fp8_on() && cfg.gemma4.is_none();
334    let (kbb_l, vbb_l) = if g4_global_fp8 || g4_windowed_fp8 || qwen_fp8 {
335        (32, 32)
336    } else {
337        (kbb, vbb)
338    };
339    (kv_dim_k, kv_dim_v, kbb_l, vbb_l)
340}
341
342fn kv_plane_allocation_bytes(rows: usize, token_bytes: usize) -> usize {
343    rows * token_bytes + 8
344}
345
346/// Context-linear bytes allocated by one trunk cache token.
347///
348/// Fixed allocations (the 8-byte plane tail pads, `len_d`, recurrent state, and optional lazy
349/// buffers) are deliberately excluded. Admission adds their measured high-water residual as a
350/// request-independent activation term; multiplying this coefficient by the request's own
351/// `ctx_cap` exactly mirrors the context-scaled allocations in `Cache::new_inner`.
352pub fn cache_bytes_per_token(cfg: &ModelConfig) -> usize {
353    cache_bytes_per_token_for_layers(cfg, 0, cfg.n_layer as usize)
354}
355
356/// Context-linear cache bytes per token owned by layers in `[lo, hi)`. PP admission uses the
357/// same layer ranges as `Cache::new_ppn`, so each device is charged for exactly the cache planes
358/// it allocates rather than for the aggregate model geometry.
359pub fn cache_bytes_per_token_for_layers(cfg: &ModelConfig, lo: usize, hi: usize) -> usize {
360    assert!(lo <= hi && hi <= cfg.n_layer as usize, "cache layer range out of bounds");
361    let shared = cfg.gemma4.as_ref().map(|g| g.shared_kv_layers).unwrap_or(0);
362    (lo as u32..hi as u32)
363        .filter(|&il| cfg.layer_kind(il) == LayerKind::FullAttention)
364        .filter(|&il| shared == 0 || il < cfg.n_layer - shared)
365        .map(|il| {
366            let (kv_dim_k, kv_dim_v, kbb, vbb) = full_attention_kv_layout(cfg, il);
367            (kv_dim_k / 32) * kbb + (kv_dim_v / 32) * vbb
368        })
369        .sum()
370}
371
372/// Portion of [`cache_bytes_per_token`] whose physical row count is capped by the Step35 SWA
373/// ring. Zero with the flag off and for every non-Step35 architecture.
374pub fn cache_ring_bytes_per_token(cfg: &ModelConfig) -> usize {
375    cache_ring_bytes_per_token_for_layers(cfg, 0, cfg.n_layer as usize)
376}
377
378/// Ring-capped portion of [`cache_bytes_per_token_for_layers`] for `[lo, hi)`.
379pub fn cache_ring_bytes_per_token_for_layers(
380    cfg: &ModelConfig,
381    lo: usize,
382    hi: usize,
383) -> usize {
384    assert!(lo <= hi && hi <= cfg.n_layer as usize, "cache layer range out of bounds");
385    if !swa_ring_on() || !cfg.arch.is_step35() {
386        return 0;
387    }
388    let shared = cfg.gemma4.as_ref().map(|g| g.shared_kv_layers).unwrap_or(0);
389    (lo as u32..hi as u32)
390        .filter(|&il| cfg.layer_kind(il) == LayerKind::FullAttention)
391        .filter(|&il| shared == 0 || il < cfg.n_layer - shared)
392        .filter(|&il| cfg.layer_geometry(il).is_some_and(|geometry| geometry.window.is_some()))
393        .map(|il| {
394            let (kv_dim_k, kv_dim_v, kbb, vbb) = full_attention_kv_layout(cfg, il);
395            (kv_dim_k / 32) * kbb + (kv_dim_v / 32) * vbb
396        })
397        .sum()
398}
399
400/// Physical row cap shared by the Step35 SWA trunk and MTP scratch; zero when no ring is active.
401pub fn cache_ring_row_cap(cfg: &ModelConfig) -> usize {
402    if !swa_ring_on() || !cfg.arch.is_step35() {
403        return 0;
404    }
405    cfg.geometry
406        .as_ref()
407        .and_then(|table| table.classes().iter().find_map(|geometry| geometry.window))
408        .map(|window| swa_ring_rows(window as usize, usize::MAX))
409        .unwrap_or(0)
410}
411
412/// See [`Cache::dflash_taps`]. Armed per forward by the dflash round (t = that forward's
413/// row count); the trunk writes tap slot s of row r at buf[r*n_taps*hidden + s*hidden ..].
414pub struct DflashTapSink {
415    pub layer_ids: Vec<usize>,
416    pub buf: CudaSlice<f32>,
417    pub hidden: usize,
418    pub t: usize,
419}
420
421/// Snapshot of the dual cache taken BEFORE a spec-decode draft+verify round (MTP-PLAN §C/§D.4).
422/// - Full-attn KV: only the per-layer `len` is recorded; rollback truncates (append-only,
423///   position-addressed — no copy). C.1.
424/// - Linear-attn conv/ssm: real device-to-device COPIES of the recurrent state, because those
425///   buffers are mutated IN PLACE by the verify pass and have no position index to truncate. C.2.
426///   (CudaSlice::clone is an Arc refcount, NOT a buffer copy — so we alloc fresh + memcpy_dtod.)
427pub struct CacheSnapshot {
428    pub kv_len: Vec<Option<usize>>, // per layer (Some for full-attn layers)
429    pub conv: Vec<Option<CudaSlice<f32>>>, // per layer (Some for linear-attn layers, D2D copy)
430    pub ssm: Vec<Option<CudaSlice<f32>>>,
431    pub pos: usize,
432}
433
434impl Cache {
435    /// Allocate GPU-resident caches sized by arch + max context.
436    pub fn new(
437        e: &impl KvDev,
438        cfg: &ModelConfig,
439        max_ctx: usize,
440    ) -> Result<Self, Box<dyn std::error::Error>> {
441        Self::new_inner(&|_| e, cfg, max_ctx)
442    }
443
444    /// M1-PP2 increment 2 (stage-owned KV): layers [0, split) allocate through `dev0`,
445    /// layers [split, n) through `dev1` — each pipeline stage's cache lives on the
446    /// device that runs the stage. With dev0 == dev1 this is byte-for-byte `new`
447    /// (the single-device plumbing gate). Sizing math is IDENTICAL either way.
448    pub fn new_pp2(
449        dev0: &dyn KvDev,
450        dev1: &dyn KvDev,
451        split: usize,
452        cfg: &ModelConfig,
453        max_ctx: usize,
454    ) -> Result<Self, Box<dyn std::error::Error>> {
455        Self::new_inner(&|il| if il < split { dev0 } else { dev1 }, cfg, max_ctx)
456    }
457
458    /// M2 N-stage twin of `new_pp2`: `fence` is the stage map from `memra_engine::pp::
459    /// pp_cuts` ([0, c1, .., n_trunk]); layer il allocates through the engine of the
460    /// stage that runs it. Layers at/beyond the fence end (MTP/NextN blocks) allocate
461    /// through the LAST stage. Sizing math is IDENTICAL to `new` — only the allocating
462    /// device varies.
463    pub fn new_ppn<'a>(
464        devs: &[&'a dyn KvDev],
465        fence: &[usize],
466        cfg: &ModelConfig,
467        max_ctx: usize,
468    ) -> Result<Self, Box<dyn std::error::Error>> {
469        assert_eq!(devs.len() + 1, fence.len(), "ppn cache: devs vs fence mismatch");
470        let pick = |il: usize| -> &dyn KvDev {
471            let s = match fence[1..fence.len() - 1].binary_search(&il) {
472                Ok(k) => k + 1,
473                Err(k) => k,
474            };
475            devs[s.min(devs.len() - 1)]
476        };
477        Self::new_inner(&pick, cfg, max_ctx)
478    }
479
480    /// Shared allocation walk: `pick(il)` supplies the device that OWNS layer il's
481    /// cache state (always the same device outside the pp2 door).
482    fn new_inner<'a>(
483        pick: &dyn Fn(usize) -> &'a dyn KvDev,
484        cfg: &ModelConfig,
485        max_ctx: usize,
486    ) -> Result<Self, Box<dyn std::error::Error>> {
487        let n = cfg.n_layer as usize;
488        let mut kv = Vec::with_capacity(n);
489        let mut recur = Vec::with_capacity(n);
490        let head_dim_k = cfg.head_dim_k as usize;
491        let head_dim_v = cfg.head_dim_v as usize;
492        assert!(head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
493                "KVQUANT requires head_dim_k%32==0 && head_dim_v%32==0 (got k={head_dim_k} v={head_dim_v})");
494        let (conv_dim, d_state, num_v, d_conv) = if let Some(s) = &cfg.ssm {
495            let num_k = s.group_count as usize;
496            let num_v = s.time_step_rank as usize;
497            let ds = s.state_size as usize;
498            (
499                ds * num_k * 2 + ds * num_v,
500                ds,
501                num_v,
502                s.conv_kernel as usize,
503            )
504        } else {
505            (0, 0, 0, 0)
506        };
507        for il in 0..cfg.n_layer {
508            // stage-owned allocation (pp2): the device that runs this layer allocates it.
509            let e = pick(il as usize);
510            // E4B KV-SHARING: the trailing shared_kv_layers have no k/v of their own — they
511            // attend an earlier layer's cache (hybrid_forward resolves the target). No KvLayer
512            // here: any accidental use is a loud unwrap at bring-up, and rewind/len loops
513            // (iter_mut().flatten()) skip None naturally.
514            let g4_shared = cfg.gemma4.as_ref().map(|g| g.shared_kv_layers).unwrap_or(0);
515            if g4_shared > 0 && il >= cfg.n_layer - g4_shared {
516                kv.push(None);
517                recur.push(None);
518                continue;
519            }
520            match cfg.layer_kind(il) {
521                LayerKind::FullAttention => {
522                    // Gemma per-layer geometry and every KV-format door are resolved by the same
523                    // helper admission uses for its analytic byte coefficient.
524                    let (kv_dim_k, kv_dim_v, kbb_l, vbb_l) =
525                        full_attention_kv_layout(cfg, il);
526                    let k_tok_bytes = (kv_dim_k / 32) * kbb_l;
527                    let v_tok_bytes = (kv_dim_v / 32) * vbb_l;
528                    let ring = if swa_ring_on() && cfg.arch.is_step35() {
529                        cfg.layer_geometry(il)
530                            .and_then(|geometry| geometry.window)
531                            .map(|window| {
532                                let window = window as usize;
533                                KvRing::new(swa_ring_rows(window, max_ctx), window)
534                            })
535                    } else {
536                        None
537                    };
538                    let alloc_rows = ring.as_ref().map(KvRing::rows).unwrap_or(max_ctx);
539                    kv.push(Some(KvLayer {
540                        // +8B tail pad: the v4 stage's aligned funnelshift window reads up to
541                        // 4B past the final block (PR #3's finding, adopted pad-style — the
542                        // expert-dot precedent; zero hot-loop branches, values discarded).
543                        k: e.alloc_u8(kv_plane_allocation_bytes(alloc_rows, k_tok_bytes))?,
544                        v: e.alloc_u8(kv_plane_allocation_bytes(alloc_rows, v_tok_bytes))?,
545                        kv_dim_k,
546                        kv_dim_v,
547                        k_tok_bytes,
548                        v_tok_bytes,
549                        len: 0,
550                        ring,
551                        len_d: e.htod_i32(&[0])?,
552                    }));
553                    recur.push(None);
554                }
555                LayerKind::LinearAttention => {
556                    kv.push(None);
557                    recur.push(Some(RecurLayer {
558                        conv_state: e.zeros(conv_dim * (d_conv - 1))?,
559                        ssm_state: e.zeros(d_state * d_state * num_v)?,
560                        ssm_state_alt: e.zeros(d_state * d_state * num_v)?,
561                    }));
562                }
563            }
564        }
565        Ok(Cache { kv, recur, pos: 0, max_ctx, dflash_taps: None, last_logits_dev: None })
566    }
567
568    pub fn has_swa_ring(&self) -> bool {
569        self.kv.iter().flatten().any(|layer| layer.ring.is_some())
570    }
571
572    pub fn can_rollback(&self, snap: &CacheSnapshot, accept_len: usize) -> bool {
573        self.kv.iter().zip(&snap.kv_len).all(|(layer, saved)| {
574            match (layer, saved) {
575                (Some(layer), Some(saved)) => layer
576                    .ring
577                    .as_ref()
578                    .is_none_or(|ring| ring.can_rewind_to(saved + accept_len)),
579                _ => true,
580            }
581        })
582    }
583
584    /// Snapshot the dual cache before a spec-decode draft+verify round (MTP-PLAN §C/§D.4).
585    /// Records each full-attn `len` (cheap) and makes a REAL device copy of each linear-attn
586    /// conv_state/ssm_state (a fresh alloc + memcpy_dtod — NOT an Arc clone).
587    pub fn snapshot(&self, e: &impl KvDev) -> Result<CacheSnapshot, Box<dyn std::error::Error>> {
588        let n = self.kv.len();
589        let mut kv_len = Vec::with_capacity(n);
590        let mut conv = Vec::with_capacity(n);
591        let mut ssm = Vec::with_capacity(n);
592        for il in 0..n {
593            match &self.kv[il] {
594                Some(kvl) => kv_len.push(Some(kvl.len)),
595                None => kv_len.push(None),
596            }
597            match &self.recur[il] {
598                Some(rl) => {
599                    conv.push(Some(e.clone_dtod(&rl.conv_state)?));
600                    ssm.push(Some(e.clone_dtod(&rl.ssm_state)?));
601                }
602                None => {
603                    conv.push(None);
604                    ssm.push(None);
605                }
606            }
607        }
608        Ok(CacheSnapshot {
609            kv_len,
610            conv,
611            ssm,
612            pos: self.pos,
613        })
614    }
615
616    /// PERSISTENT-BUFFER snapshot (spec-decode hot loop): refresh `snap` IN PLACE — same values as
617    /// `snapshot()` but the conv/ssm device buffers are reused across rounds (D2D copy-into, ZERO
618    /// allocations vs 2 fresh clones per linear layer per round). `snap` must come from a prior
619    /// `snapshot()` of THIS cache (same layer shapes).
620    pub fn snapshot_into(
621        &self,
622        e: &impl KvDev,
623        snap: &mut CacheSnapshot,
624    ) -> Result<(), Box<dyn std::error::Error>> {
625        let n = self.kv.len();
626        for il in 0..n {
627            snap.kv_len[il] = self.kv[il].as_ref().map(|kvl| kvl.len);
628            if let Some(rl) = &self.recur[il] {
629                let dc = snap.conv[il]
630                    .as_mut()
631                    .expect("snapshot_into: shape mismatch (conv)");
632                let ds = snap.ssm[il]
633                    .as_mut()
634                    .expect("snapshot_into: shape mismatch (ssm)");
635                let (cn, sn) = (rl.conv_state.len(), rl.ssm_state.len());
636                e.copy_into(dc, 0, &rl.conv_state, cn)?;
637                e.copy_into(ds, 0, &rl.ssm_state, sn)?;
638            }
639        }
640        snap.pos = self.pos;
641        Ok(())
642    }
643
644    /// Roll the cache back to exactly `snap.pos + accept_len` committed tokens (MTP-PLAN §C).
645    /// - Full-attn KV (C.1): set len = snapshot_len + accept_len (truncate, no copy).
646    /// - Linear-attn (C.2): RESTORE the snapshot conv/ssm (real D2D copy back into the resident
647    ///   buffers). The caller must then REPLAY the `accept_len` committed tokens through the full
648    ///   T=1 decode path to rebuild the recurrent state for those positions. We restore (not
649    ///   replay here) because replay needs the model; this only resets state to the pre-round value.
650    /// `cache.pos` is set to `snap.pos` so the caller's replay advances it back to the commit point.
651    pub fn rollback(
652        &mut self,
653        e: &impl KvDev,
654        snap: &CacheSnapshot,
655        accept_len: usize,
656    ) -> Result<(), Box<dyn std::error::Error>> {
657        if !self.can_rollback(snap, accept_len) {
658            return Err("SWA ring rewind checkpoint has been lapped; full re-prime required".into());
659        }
660        for il in 0..self.kv.len() {
661            if let (Some(kvl), Some(saved)) = (self.kv[il].as_mut(), snap.kv_len[il]) {
662                kvl.len = saved + accept_len;
663                // keep the device mirror in lock-step (CUDA-GRAPH-PLAN Phase 2). Set IN PLACE
664                // (stable pointer): a fresh htod_i32 would reallocate len_d, but its old pointer is
665                // baked into the captured decode graph's append/inc/fa_decode kernels — replacing it
666                // strands the graph on a freed buffer (stale-pointer hazard). memcpy_htod in place.
667                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
668            }
669            if let Some(rl) = self.recur[il].as_mut() {
670                if let Some(c) = &snap.conv[il] {
671                    e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
672                }
673                if let Some(s) = &snap.ssm[il] {
674                    e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
675                }
676            }
677        }
678        self.pos = snap.pos;
679        Ok(())
680    }
681}
682
683#[cfg(test)]
684mod swa_ring_tests {
685    use super::{kv_plane_allocation_bytes, swa_ring_rows, KvRing, KvRingAppend};
686
687    #[test]
688    fn allocation_rows_cover_window_max_prime_and_alignment_slack() {
689        assert_eq!(swa_ring_rows(512, 262_144), 512 + 4096 + 31);
690        assert_eq!(swa_ring_rows(512, 4096), 4096);
691        assert_eq!(
692            kv_plane_allocation_bytes(4639, 1088),
693            4639 * 1088 + 8,
694            "the Step35 session plane allocates ring rows plus the existing tail pad",
695        );
696    }
697
698    #[test]
699    fn ring_matches_flat_bytes_before_wrap() {
700        let ring = KvRing::new(swa_ring_rows(512, 262_144), 512);
701        let flat: Vec<u32> = (0..1024).collect();
702        let mut physical = vec![u32::MAX; ring.rows()];
703        let KvRingAppend::Contiguous { write_row } = ring.append_plan(0, 0, flat.len()).unwrap()
704        else { panic!("first append unexpectedly wrapped") };
705        physical[write_row..write_row + flat.len()].copy_from_slice(&flat);
706        let view = ring.physical_range(0, flat.len()).unwrap();
707        assert_eq!(&physical[view], flat.as_slice());
708    }
709
710    #[test]
711    fn wrap_rebases_the_exact_aligned_prime_view() {
712        let mut ring = KvRing::new(swa_ring_rows(512, 262_144), 512);
713        let flat: Vec<u32> = (0..8192).collect();
714        let mut physical = vec![u32::MAX; ring.rows()];
715        let KvRingAppend::Contiguous { write_row } = ring.append_plan(0, 0, 4096).unwrap()
716        else { panic!("first prime chunk unexpectedly wrapped") };
717        physical[write_row..write_row + 4096].copy_from_slice(&flat[..4096]);
718
719        let off = (4096usize - (512 - 1)) & !31usize;
720        let KvRingAppend::Rebase {
721            src_row,
722            keep_rows,
723            new_base,
724            write_row,
725        } = ring.append_plan(4096, off, 4096).unwrap()
726        else { panic!("second prime chunk did not wrap") };
727        let retained = physical[src_row..src_row + keep_rows].to_vec();
728        physical[..keep_rows].copy_from_slice(&retained);
729        ring.apply_rebase(new_base);
730        physical[write_row..write_row + 4096].copy_from_slice(&flat[4096..8192]);
731
732        let view = ring.physical_range(off, 8192).unwrap();
733        assert_eq!(&physical[view], &flat[off..8192]);
734        assert_eq!(ring.base(), off);
735    }
736
737    #[test]
738    fn rewind_declines_once_the_required_window_was_lapped() {
739        let mut ring = KvRing::new(swa_ring_rows(512, 262_144), 512);
740        let KvRingAppend::Rebase { new_base, .. } =
741            ring.append_plan(4096, 3584, 4096).unwrap()
742        else { panic!("expected wrap") };
743        ring.apply_rebase(new_base);
744        assert!(ring.can_rewind_to(4095));
745        assert!(!ring.can_rewind_to(4094));
746        assert!(!ring.can_rewind_to(0));
747    }
748}