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// ---------------- the device seam ----------------
78
79/// The 7 device ops the cache needs — nothing more. Implemented by the engine (and by
80/// any future backend); all ops are stream-ordered on the implementor's worker stream.
81pub trait KvDev {
82    fn zeros(&self, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>>;
83    fn uninit(&self, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>>;
84    fn alloc_u8(&self, n: usize) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>>;
85    fn htod_i32(&self, v: &[i32]) -> Result<CudaSlice<i32>, Box<dyn std::error::Error>>;
86    fn clone_dtod(&self, src: &CudaSlice<f32>) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>>;
87    fn copy_into(&self, dst: &mut CudaSlice<f32>, off: usize, src: &CudaSlice<f32>, len: usize)
88                 -> Result<(), Box<dyn std::error::Error>>;
89    fn set_i32_one(&self, d: &mut CudaSlice<i32>, v: i32) -> Result<(), Box<dyn std::error::Error>>;
90}
91
92use memra_gguf::config::{LayerKind, ModelConfig};
93use cudarc::driver::CudaSlice;
94
95/// Per-full-attn-layer growing KV cache, resident on GPU. QUANTIZED (KVQUANT-PLAN §B):
96/// K stored q8_0 (34 B/32 elem), V stored q5_1 (24 B/32 elem). Per-token byte layout keeps the
97/// [token, kv_head, dim] element order so a 32-block never straddles a head (assert head_dim%32==0).
98/// Element-within-token index = kv_head*head_dim + d; block = idx/32; lane = idx%32.
99pub struct KvLayer {
100    pub k: CudaSlice<u8>,   // q8_0 packed, capacity max_ctx*k_tok_bytes
101    pub v: CudaSlice<u8>,   // q5_1 packed, capacity max_ctx*v_tok_bytes
102    pub kv_dim_k: usize,    // head_dim_k * n_head_kv  (K elements per token)
103    pub kv_dim_v: usize,    // head_dim_v * n_head_kv  (V elements per token)
104    pub k_tok_bytes: usize, // (kv_dim_k/32)*34
105    pub v_tok_bytes: usize, // (kv_dim_v/32)*24
106    pub len: usize,
107    /// Device-resident mirror of `len` (CUDA-GRAPH-PLAN Phase 2). Holds the KV write SLOT for the
108    /// append-dc kernel (old len, before this step's append); after `inc_seqlen` it holds the new
109    /// len == t_kv for fa_decode_dc. Kept in lock-step with the host `len`. i32[1].
110    pub len_d: CudaSlice<i32>,
111}
112
113/// Per-linear-attn-layer fixed recurrent state.
114/// conv_state and ssm_state are BOTH kept RESIDENT on GPU — the conv ring assemble + roll runs
115/// on-device (conv_assemble_and_roll), so there is no per-step dtoh/htod for either.
116pub struct RecurLayer {
117    pub conv_state: CudaSlice<f32>, // GPU [conv_dim, d_conv-1] (channel c, tap j at c*pad + j)
118    pub ssm_state: CudaSlice<f32>,  // GPU [d_state, d_state, num_v] transposed M[col][i]
119    /// PERSISTENT second SSM-state buffer for the gdn-scan double buffer (DECODE DETERMINISM FIX).
120    /// gdn_scan needs DISTINCT in/out state buffers. The old eager path allocated a fresh
121    /// `state_scratch` via `e.uninit` every step and swapped its pointer into `ssm_state`; that
122    /// per-step alloc/free churned the stream-ordered async pool, and the freed prior `ssm_state`
123    /// block was recycled by the next step's scratch while a kernel referencing the swapped-in state
124    /// was still in flight — a use-after-reuse that produced RUN-TO-RUN nondeterministic decode
125    /// (two identical prompt primes diverged). We instead PING-PONG between two STABLE resident
126    /// buffers (no per-step alloc/free, no pool churn): step writes into the spare, then swaps the
127    /// two owned buffers in place. Stable pointers, identical math. Sized like `ssm_state`.
128    pub ssm_state_alt: CudaSlice<f32>,
129}
130
131pub struct Cache {
132    pub kv: Vec<Option<KvLayer>>,
133    pub recur: Vec<Option<RecurLayer>>,
134    pub pos: usize,
135    pub max_ctx: usize,
136    /// BATCHED-TICK increment 2 component 3 (lean logits, 2026-08-01): device-side park of
137    /// this session's LAST logits row. Device-sampled rows in the batched serving tick skip
138    /// the [n_vocab] logits D2H entirely; the tick instead dtod-copies the row here (device
139    /// bandwidth, ~µs) so the ONE consumer that truly needs the final row — the KV-reuse
140    /// pool's park-at-retire (an empty-suffix resume samples from parked last_logits) —
141    /// can D2H it once at retire. Lazily allocated on the first lean tick; None on every
142    /// non-lean path (zero cost). Travels with the Cache into the reuse pool.
143    pub last_logits_dev: Option<CudaSlice<f32>>,
144    /// DFlash tap sink (dflash lane, 2026-07-13): when armed, the gemma4 verify/prime
145    /// trunks copy the residual stream AFTER each tapped layer into `buf` rows
146    /// ([t, n_taps*hidden] row-major — the drafter fc input layout). None on every
147    /// non-dflash path (zero cost).
148    pub dflash_taps: Option<DflashTapSink>,
149}
150
151/// See [`Cache::dflash_taps`]. Armed per forward by the dflash round (t = that forward's
152/// row count); the trunk writes tap slot s of row r at buf[r*n_taps*hidden + s*hidden ..].
153pub struct DflashTapSink {
154    pub layer_ids: Vec<usize>,
155    pub buf: CudaSlice<f32>,
156    pub hidden: usize,
157    pub t: usize,
158}
159
160/// Snapshot of the dual cache taken BEFORE a spec-decode draft+verify round (MTP-PLAN §C/§D.4).
161/// - Full-attn KV: only the per-layer `len` is recorded; rollback truncates (append-only,
162///   position-addressed — no copy). C.1.
163/// - Linear-attn conv/ssm: real device-to-device COPIES of the recurrent state, because those
164///   buffers are mutated IN PLACE by the verify pass and have no position index to truncate. C.2.
165///   (CudaSlice::clone is an Arc refcount, NOT a buffer copy — so we alloc fresh + memcpy_dtod.)
166pub struct CacheSnapshot {
167    pub kv_len: Vec<Option<usize>>, // per layer (Some for full-attn layers)
168    pub conv: Vec<Option<CudaSlice<f32>>>, // per layer (Some for linear-attn layers, D2D copy)
169    pub ssm: Vec<Option<CudaSlice<f32>>>,
170    pub pos: usize,
171}
172
173impl Cache {
174    /// Allocate GPU-resident caches sized by arch + max context.
175    pub fn new(
176        e: &impl KvDev,
177        cfg: &ModelConfig,
178        max_ctx: usize,
179    ) -> Result<Self, Box<dyn std::error::Error>> {
180        Self::new_inner(&|_| e, cfg, max_ctx)
181    }
182
183    /// M1-PP2 increment 2 (stage-owned KV): layers [0, split) allocate through `dev0`,
184    /// layers [split, n) through `dev1` — each pipeline stage's cache lives on the
185    /// device that runs the stage. With dev0 == dev1 this is byte-for-byte `new`
186    /// (the single-device plumbing gate). Sizing math is IDENTICAL either way.
187    pub fn new_pp2(
188        dev0: &dyn KvDev,
189        dev1: &dyn KvDev,
190        split: usize,
191        cfg: &ModelConfig,
192        max_ctx: usize,
193    ) -> Result<Self, Box<dyn std::error::Error>> {
194        Self::new_inner(&|il| if il < split { dev0 } else { dev1 }, cfg, max_ctx)
195    }
196
197    /// M2 N-stage twin of `new_pp2`: `fence` is the stage map from `memra_engine::pp::
198    /// pp_cuts` ([0, c1, .., n_trunk]); layer il allocates through the engine of the
199    /// stage that runs it. Layers at/beyond the fence end (MTP/NextN blocks) allocate
200    /// through the LAST stage. Sizing math is IDENTICAL to `new` — only the allocating
201    /// device varies.
202    pub fn new_ppn<'a>(
203        devs: &[&'a dyn KvDev],
204        fence: &[usize],
205        cfg: &ModelConfig,
206        max_ctx: usize,
207    ) -> Result<Self, Box<dyn std::error::Error>> {
208        assert_eq!(devs.len() + 1, fence.len(), "ppn cache: devs vs fence mismatch");
209        let pick = |il: usize| -> &dyn KvDev {
210            let s = match fence[1..fence.len() - 1].binary_search(&il) {
211                Ok(k) => k + 1,
212                Err(k) => k,
213            };
214            devs[s.min(devs.len() - 1)]
215        };
216        Self::new_inner(&pick, cfg, max_ctx)
217    }
218
219    /// Shared allocation walk: `pick(il)` supplies the device that OWNS layer il's
220    /// cache state (always the same device outside the pp2 door).
221    fn new_inner<'a>(
222        pick: &dyn Fn(usize) -> &'a dyn KvDev,
223        cfg: &ModelConfig,
224        max_ctx: usize,
225    ) -> Result<Self, Box<dyn std::error::Error>> {
226        let n = cfg.n_layer as usize;
227        let mut kv = Vec::with_capacity(n);
228        let mut recur = Vec::with_capacity(n);
229        let n_head_kv = cfg.n_head_kv as usize;
230        let head_dim_k = cfg.head_dim_k as usize;
231        let head_dim_v = cfg.head_dim_v as usize;
232        assert!(head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
233                "KVQUANT requires head_dim_k%32==0 && head_dim_v%32==0 (got k={head_dim_k} v={head_dim_v})");
234        let kv_dim_k = head_dim_k * n_head_kv;
235        let kv_dim_v = head_dim_v * n_head_kv;
236        // per-block bytes follow the env-selected KV formats (kvbytes lane; default q8_0/q5_1
237        // = 34/24 — MUST match the flash fatbin Engine::new loaded, both read the same env).
238        let (kbb, vbb) = kv_blk_bytes();
239        let (conv_dim, d_state, num_v, d_conv) = if let Some(s) = &cfg.ssm {
240            let num_k = s.group_count as usize;
241            let num_v = s.time_step_rank as usize;
242            let ds = s.state_size as usize;
243            (
244                ds * num_k * 2 + ds * num_v,
245                ds,
246                num_v,
247                s.conv_kernel as usize,
248            )
249        } else {
250            (0, 0, 0, 0)
251        };
252        for il in 0..cfg.n_layer {
253            // stage-owned allocation (pp2): the device that runs this layer allocates it.
254            let e = pick(il as usize);
255            // gemma4 R5: per-layer KV geometry (SWA 256hd x 8kv = 2048 / global 512hd x 2kv = 1024).
256            let (kv_dim_k, kv_dim_v) = match &cfg.gemma4 {
257                Some(g) => {
258                    let hd = if g.swa_pattern[il as usize] {
259                        g.key_length_swa
260                    } else {
261                        g.key_length_global
262                    } as usize;
263                    // E4B ships a SCALAR head_count_kv (per-layer vec empty; scalar = 2 in
264                    // the gguf, landing in cfg.n_head_kv): kv_dim = hd * 2 for BOTH kinds —
265                    // swa 2x256 = 512, global 2x512 = 1024. The old fallback used
266                    // key_length_global (512) for both, which HALVED the global layers' K/V
267                    // (the attn writes wk.out_features = 1024 rows): every E4B global layer
268                    // stored/attended half its K/V and the batched append read row strides
269                    // wrong — THE cross-mode maxdiff-30 root (2026-07-12 bisect, il=5 slot-1
270                    // byte forensics). 26B/31B keep the per-layer vec.
271                    let d = match g.head_count_kv.get(il as usize) {
272                        Some(n) => hd * *n as usize,
273                        None => hd * n_head_kv,
274                    };
275                    (d, d)
276                }
277                None => (kv_dim_k, kv_dim_v),
278            };
279            // E4B KV-SHARING: the trailing shared_kv_layers have no k/v of their own — they
280            // attend an earlier layer's cache (hybrid_forward resolves the target). No KvLayer
281            // here: any accidental use is a loud unwrap at bring-up, and rewind/len loops
282            // (iter_mut().flatten()) skip None naturally.
283            let g4_shared = cfg.gemma4.as_ref().map(|g| g.shared_kv_layers).unwrap_or(0);
284            if g4_shared > 0 && il >= cfg.n_layer - g4_shared {
285                kv.push(None);
286                recur.push(None);
287                continue;
288            }
289            // FP8-GLOBALS (gemma, 2026-07-11): global (hd512) layers hold e4m3 K/V (32B/32elem
290            // both planes — the dequant-latency arc); windowed layers keep the default pair.
291            let g4_global_fp8 = gkv_on()
292                && cfg
293                    .gemma4
294                    .as_ref()
295                    .is_some_and(|g| !g.swa_pattern[il as usize]);
296            let g4_windowed_fp8 = wkv_on()
297                && cfg
298                    .gemma4
299                    .as_ref()
300                    .is_some_and(|g| g.swa_pattern[il as usize]);
301            // QWEN FP8-KV (MEMRA_KV_FP8, bring-up): non-gemma full-attn layers, uniform class.
302            let qwen_fp8 = kv_fp8_on() && cfg.gemma4.is_none();
303            let (kbb_l, vbb_l) = if g4_global_fp8 || g4_windowed_fp8 || qwen_fp8 {
304                (32, 32)
305            } else {
306                (kbb, vbb)
307            };
308            let k_tok_bytes = (kv_dim_k / 32) * kbb_l;
309            let v_tok_bytes = (kv_dim_v / 32) * vbb_l;
310            match cfg.layer_kind(il) {
311                LayerKind::FullAttention => {
312                    kv.push(Some(KvLayer {
313                        // +8B tail pad: the v4 stage's aligned funnelshift window reads up to
314                        // 4B past the final block (PR #3's finding, adopted pad-style — the
315                        // expert-dot precedent; zero hot-loop branches, values discarded).
316                        k: e.alloc_u8(max_ctx * k_tok_bytes + 8)?,
317                        v: e.alloc_u8(max_ctx * v_tok_bytes + 8)?,
318                        kv_dim_k,
319                        kv_dim_v,
320                        k_tok_bytes,
321                        v_tok_bytes,
322                        len: 0,
323                        len_d: e.htod_i32(&[0])?,
324                    }));
325                    recur.push(None);
326                }
327                LayerKind::LinearAttention => {
328                    kv.push(None);
329                    recur.push(Some(RecurLayer {
330                        conv_state: e.zeros(conv_dim * (d_conv - 1))?,
331                        ssm_state: e.zeros(d_state * d_state * num_v)?,
332                        ssm_state_alt: e.zeros(d_state * d_state * num_v)?,
333                    }));
334                }
335            }
336        }
337        Ok(Cache { kv, recur, pos: 0, max_ctx, dflash_taps: None, last_logits_dev: None })
338    }
339
340    /// Snapshot the dual cache before a spec-decode draft+verify round (MTP-PLAN §C/§D.4).
341    /// Records each full-attn `len` (cheap) and makes a REAL device copy of each linear-attn
342    /// conv_state/ssm_state (a fresh alloc + memcpy_dtod — NOT an Arc clone).
343    pub fn snapshot(&self, e: &impl KvDev) -> Result<CacheSnapshot, Box<dyn std::error::Error>> {
344        let n = self.kv.len();
345        let mut kv_len = Vec::with_capacity(n);
346        let mut conv = Vec::with_capacity(n);
347        let mut ssm = Vec::with_capacity(n);
348        for il in 0..n {
349            match &self.kv[il] {
350                Some(kvl) => kv_len.push(Some(kvl.len)),
351                None => kv_len.push(None),
352            }
353            match &self.recur[il] {
354                Some(rl) => {
355                    conv.push(Some(e.clone_dtod(&rl.conv_state)?));
356                    ssm.push(Some(e.clone_dtod(&rl.ssm_state)?));
357                }
358                None => {
359                    conv.push(None);
360                    ssm.push(None);
361                }
362            }
363        }
364        Ok(CacheSnapshot {
365            kv_len,
366            conv,
367            ssm,
368            pos: self.pos,
369        })
370    }
371
372    /// PERSISTENT-BUFFER snapshot (spec-decode hot loop): refresh `snap` IN PLACE — same values as
373    /// `snapshot()` but the conv/ssm device buffers are reused across rounds (D2D copy-into, ZERO
374    /// allocations vs 2 fresh clones per linear layer per round). `snap` must come from a prior
375    /// `snapshot()` of THIS cache (same layer shapes).
376    pub fn snapshot_into(
377        &self,
378        e: &impl KvDev,
379        snap: &mut CacheSnapshot,
380    ) -> Result<(), Box<dyn std::error::Error>> {
381        let n = self.kv.len();
382        for il in 0..n {
383            snap.kv_len[il] = self.kv[il].as_ref().map(|kvl| kvl.len);
384            if let Some(rl) = &self.recur[il] {
385                let dc = snap.conv[il]
386                    .as_mut()
387                    .expect("snapshot_into: shape mismatch (conv)");
388                let ds = snap.ssm[il]
389                    .as_mut()
390                    .expect("snapshot_into: shape mismatch (ssm)");
391                let (cn, sn) = (rl.conv_state.len(), rl.ssm_state.len());
392                e.copy_into(dc, 0, &rl.conv_state, cn)?;
393                e.copy_into(ds, 0, &rl.ssm_state, sn)?;
394            }
395        }
396        snap.pos = self.pos;
397        Ok(())
398    }
399
400    /// Roll the cache back to exactly `snap.pos + accept_len` committed tokens (MTP-PLAN §C).
401    /// - Full-attn KV (C.1): set len = snapshot_len + accept_len (truncate, no copy).
402    /// - Linear-attn (C.2): RESTORE the snapshot conv/ssm (real D2D copy back into the resident
403    ///   buffers). The caller must then REPLAY the `accept_len` committed tokens through the full
404    ///   T=1 decode path to rebuild the recurrent state for those positions. We restore (not
405    ///   replay here) because replay needs the model; this only resets state to the pre-round value.
406    /// `cache.pos` is set to `snap.pos` so the caller's replay advances it back to the commit point.
407    pub fn rollback(
408        &mut self,
409        e: &impl KvDev,
410        snap: &CacheSnapshot,
411        accept_len: usize,
412    ) -> Result<(), Box<dyn std::error::Error>> {
413        for il in 0..self.kv.len() {
414            if let (Some(kvl), Some(saved)) = (self.kv[il].as_mut(), snap.kv_len[il]) {
415                kvl.len = saved + accept_len;
416                // keep the device mirror in lock-step (CUDA-GRAPH-PLAN Phase 2). Set IN PLACE
417                // (stable pointer): a fresh htod_i32 would reallocate len_d, but its old pointer is
418                // baked into the captured decode graph's append/inc/fa_decode kernels — replacing it
419                // strands the graph on a freed buffer (stale-pointer hazard). memcpy_htod in place.
420                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
421            }
422            if let Some(rl) = self.recur[il].as_mut() {
423                if let Some(c) = &snap.conv[il] {
424                    e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
425                }
426                if let Some(s) = &snap.ssm[il] {
427                    e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
428                }
429            }
430        }
431        self.pos = snap.pos;
432        Ok(())
433    }
434}