Skip to main content

memra_engine/
gemma_spec.rs

1//! gemma4 MTP spec-decode: the "gemma4-assistant" drafter (4-layer, Q-only attention over the
2//! MAIN model's KV cache — no draft KV, no trims) + the greedy draft/verify loop.
3//!
4//! Wiring verified from llama gemma4-assistant.cpp + llama-model.cpp:2162 (HANDOVER "GEMMA4 MTP
5//! DRAFTER — VERIFIED WIRING"): per draft token, x = MAIN tok_embd(token) * sqrt(2816);
6//! xh = concat(x, h[2816]) -> pre_proj [5632->1024]; 4 gemma-style blocks whose attention
7//! projects Q ONLY and attends the main cache (SWA layers 0..2 -> main layer n-2 = 28 windowed;
8//! global layer 3 -> main layer n-1 = 29 full); dense GELU_PAR ffn; final output_norm ->
9//! TIED 1024-dim head (no softcap); h_next = post_proj [1024->2816].
10
11use crate::Engine;
12use crate::cache::Cache;
13use crate::hybrid::HybridModel;
14use crate::model::GpuTensor;
15use cudarc::driver::CudaSlice;
16use memra_gguf::GgufFile;
17use memra_gguf::source::{GgufSource, TensorSource};
18
19pub struct GemmaDraftLayer {
20    pub attn_norm: GpuTensor,
21    pub wq: GpuTensor,
22    pub wo: GpuTensor,
23    pub q_norm: GpuTensor,
24    pub post_attn_norm: GpuTensor,
25    pub ffn_norm: GpuTensor,
26    pub ffn_gate: GpuTensor,
27    pub ffn_up: GpuTensor,
28    pub ffn_down: GpuTensor,
29    pub ffn_post_norm: GpuTensor,
30    pub out_scale: f32,
31    pub swa: bool,
32    pub hd: usize,
33    pub nh: usize,
34}
35
36pub struct GemmaDraft {
37    pub layers: Vec<GemmaDraftLayer>,
38    pub pre_proj: GpuTensor,  // [5632 -> 1024]
39    pub post_proj: GpuTensor, // [1024 -> 2816]
40    pub output_norm: GpuTensor,
41    pub head: GpuTensor, // tied drafter token_embd [1024, n_vocab] (or FR-trimmed rows)
42    /// FR-Spec trim map: draft-row index -> target token id (None = full head, identity).
43    pub d2t: Option<Vec<u32>>,
44    /// Device copy of `d2t` — the async round translates each drafted trim-idx in place
45    /// (u32_map_k) before it seeds the next draft step or meets the verify argmax.
46    pub d2t_dev: Option<CudaSlice<u32>>,
47    /// Adaptive trim (coverage escapes are the entire trim cost — oracle-proven +2% on the
48    /// cell the static trim lost by 17%, jsonl 2026-07-19): spare head slots learned at
49    /// serve time from the prompt's own ids and verify-correction tokens.
50    pub trim_adapt: Option<TrimAdapt>,
51    pub rope_freqs: CudaSlice<f32>,
52    pub ones: CudaSlice<f32>, // weightless-norm weight (max hd 512)
53    pub n_embd: usize,        // 1024
54    pub n_backbone: usize,    // 2816
55    pub rope_base_global: f32,
56    pub rope_base_swa: f32,
57    pub sliding_window: usize,
58}
59
60/// Serve-time adaptive trim (MEMRA_GEMMA_TRIM_ADAPT=<spare slots>): the static FR trim's whole
61/// loss is coverage escapes — tokens the base emits that the trim can't propose (guaranteed
62/// rejections; the oracle control that injected the exact escapees flipped a -17% cell to +2%
63/// at identical acceptance, jsonl 2026-07-19). Every escape self-identifies at serve time: it
64/// arrives as a verify CORRECTION token (and its cousins ride in with the prompt), so the head
65/// keeps `n_spare` extra rows and learns them — prompt ids up front, corrections as they land.
66/// First miss pays one rejected round; every recurrence after is proposable. Rows are written
67/// into the existing device buffers (no realloc — captured graphs keep their baked addresses).
68pub struct TrimAdapt {
69    /// full-vocab head rows (host copy) — the gather source for learned rows.
70    src_rows: Vec<u8>,
71    row_bytes: usize,
72    n_vocab: usize,
73    /// trim-set membership by token id (ranked + learned).
74    present: Vec<bool>,
75    /// spare slots live at [spare_base, spare_base + n_spare) in the gathered head.
76    spare_base: usize,
77    n_spare: usize,
78    used: usize,
79    logged_full: bool,
80}
81
82impl TrimAdapt {
83    /// Add `tok`'s head row to the trim set if absent and a spare slot is free.
84    fn maybe_add(
85        &mut self,
86        e: &Engine,
87        tok: u32,
88        head: &mut GpuTensor,
89        d2t: &mut [u32],
90        d2t_dev: &mut CudaSlice<u32>,
91    ) -> Result<bool, Box<dyn std::error::Error>> {
92        let t = tok as usize;
93        if t >= self.n_vocab || self.present[t] {
94            return Ok(false);
95        }
96        if self.used == self.n_spare {
97            if !self.logged_full {
98                self.logged_full = true;
99                eprintln!(
100                    "[trim-adapt] spare slots exhausted ({}) — later escapes stay unproposable",
101                    self.n_spare
102                );
103            }
104            return Ok(false);
105        }
106        let slot = self.spare_base + self.used;
107        self.used += 1;
108        self.present[t] = true;
109        if let GpuTensor::Quant { bytes, .. } = head {
110            e.htod_u8_into(
111                bytes,
112                slot * self.row_bytes,
113                &self.src_rows[t * self.row_bytes..(t + 1) * self.row_bytes],
114            )?;
115        }
116        d2t[slot] = tok;
117        e.u32_set_k(d2t_dev, tok, slot)?;
118        Ok(true)
119    }
120}
121
122/// Union `toks` into the adaptive trim set (no-op when the draft has no adaptive state).
123/// Split-borrow helper: the fields move together or not at all.
124fn trim_adapt_learn(
125    e: &Engine,
126    d: &mut GemmaDraft,
127    toks: &[u32],
128) -> Result<(), Box<dyn std::error::Error>> {
129    let GemmaDraft {
130        trim_adapt,
131        head,
132        d2t,
133        d2t_dev,
134        ..
135    } = d;
136    let (Some(ta), Some(d2t), Some(d2t_dev)) =
137        (trim_adapt.as_mut(), d2t.as_mut(), d2t_dev.as_mut())
138    else {
139        return Ok(());
140    };
141    for &tok in toks {
142        ta.maybe_add(e, tok, head, d2t, d2t_dev)?;
143    }
144    Ok(())
145}
146
147impl GemmaDraft {
148    /// Adaptive-trim stats: (slots used, slot budget). None when adaptation is off.
149    pub fn trim_adapt_stats(&self) -> Option<(usize, usize)> {
150        self.trim_adapt.as_ref().map(|ta| (ta.used, ta.n_spare))
151    }
152
153    /// Persist the learned trim rows: append ids not yet in the sidecar to
154    /// `<ranks>.learned` (the load path pre-fills spare slots from it, so a distribution's
155    /// escapes pay their first-miss round ONCE across the serve lifetime, not per request).
156    pub fn trim_adapt_save(&self) -> std::io::Result<usize> {
157        let (Some(ta), Some(d2t), Some(path)) = (
158            self.trim_adapt.as_ref(),
159            self.d2t.as_ref(),
160            self.trim_learned_path(),
161        ) else {
162            return Ok(0);
163        };
164        let prior: std::collections::HashSet<u32> = std::fs::read_to_string(&path)
165            .map(|t| t.lines().filter_map(|l| l.trim().parse().ok()).collect())
166            .unwrap_or_default();
167        let fresh: Vec<u32> = d2t[ta.spare_base..ta.spare_base + ta.used]
168            .iter()
169            .copied()
170            .filter(|id| !prior.contains(id))
171            .collect();
172        if !fresh.is_empty() {
173            use std::io::Write;
174            let mut f = std::fs::OpenOptions::new()
175                .create(true)
176                .append(true)
177                .open(&path)?;
178            for id in &fresh {
179                writeln!(f, "{id}")?;
180            }
181        }
182        Ok(fresh.len())
183    }
184
185    fn trim_learned_path(&self) -> Option<String> {
186        std::env::var("MEMRA_GEMMA_DRAFT_RANKS")
187            .ok()
188            .map(|p| format!("{p}.learned"))
189    }
190}
191
192fn load_t(
193    e: &Engine,
194    src: &dyn TensorSource,
195    name: &str,
196) -> Result<GpuTensor, Box<dyn std::error::Error>> {
197    GpuTensor::load_from_source(e, src, name)
198}
199
200impl GemmaDraft {
201    pub fn load(e: &Engine, g: &GgufFile) -> Result<Self, Box<dyn std::error::Error>> {
202        // two published spellings of the same arch: the 26B/31B drafters ship
203        // "gemma4-assistant", the E4B assistant ships "gemma4_assistant" — the metadata
204        // key prefix follows the arch string verbatim.
205        let arch = match g.arch() {
206            Some(a @ ("gemma4-assistant" | "gemma4_assistant")) => a.to_string(),
207            other => panic!("not a gemma4-assistant drafter (arch {other:?})"),
208        };
209        let src = GgufSource(g);
210        let meta_u = |k: &str| -> u32 {
211            g.metadata
212                .get(&format!("{arch}.{k}"))
213                .and_then(|v| v.as_u64())
214                .unwrap_or(0) as u32
215        };
216        let meta_f = |k: &str, d: f32| -> f32 {
217            match g.metadata.get(&format!("{arch}.{k}")) {
218                Some(memra_gguf::MetaValue::F32(v)) => *v,
219                Some(memra_gguf::MetaValue::F64(v)) => *v as f32,
220                _ => d,
221            }
222        };
223        let n_layer = meta_u("block_count") as usize;
224        let n_embd = meta_u("embedding_length") as usize;
225        // 26B/31B carry the target width as embedding_length_out; the E4B assistant as
226        // n_embd_backbone.
227        let n_backbone = match meta_u("embedding_length_out") as usize {
228            0 => meta_u("n_embd_backbone") as usize,
229            v => v,
230        };
231        let hd_g = meta_u("attention.key_length") as usize;
232        let hd_s = meta_u("attention.key_length_swa") as usize;
233        let swa_pat: Vec<bool> = match g
234            .metadata
235            .get(&format!("{arch}.attention.sliding_window_pattern"))
236        {
237            Some(memra_gguf::MetaValue::Array(a)) => a
238                .iter()
239                .filter_map(|v| v.as_u64().map(|x| x != 0))
240                .collect(),
241            _ => return Err("drafter missing sliding_window_pattern".into()),
242        };
243
244        let mut layers = Vec::with_capacity(n_layer);
245        for il in 0..n_layer {
246            let p = |n: &str| format!("blk.{il}.{n}");
247            let swa = swa_pat[il];
248            let out_scale = {
249                let t = src
250                    .find(&p("layer_output_scale.weight"))
251                    .ok_or("missing layer_output_scale")?;
252                memra_gguf::dequant::dequantize(t.ggml_type, &t.bytes, 1)[0]
253            };
254            let hd = if swa { hd_s } else { hd_g };
255            let wq = load_t(e, &src, &p("attn_q.weight"))?;
256            // heads per layer from the projection shape (the E4B assistant keeps 4 heads on
257            // BOTH classes — hd differs — while 26B/31B are uniform; the shape is the truth).
258            let nh = wq.out_features() / hd;
259            layers.push(GemmaDraftLayer {
260                attn_norm: load_t(e, &src, &p("attn_norm.weight"))?,
261                wq,
262                wo: load_t(e, &src, &p("attn_output.weight"))?,
263                q_norm: load_t(e, &src, &p("attn_q_norm.weight"))?,
264                post_attn_norm: load_t(e, &src, &p("post_attention_norm.weight"))?,
265                ffn_norm: load_t(e, &src, &p("ffn_norm.weight"))?,
266                ffn_gate: load_t(e, &src, &p("ffn_gate.weight"))?,
267                ffn_up: load_t(e, &src, &p("ffn_up.weight"))?,
268                ffn_down: load_t(e, &src, &p("ffn_down.weight"))?,
269                ffn_post_norm: load_t(e, &src, &p("post_ffw_norm.weight"))?,
270                out_scale,
271                swa,
272                hd,
273                nh,
274            });
275        }
276        let rope_freqs = {
277            let t = src
278                .find("rope_freqs.weight")
279                .ok_or("drafter missing rope_freqs")?;
280            e.htod(&memra_gguf::dequant::dequantize(
281                t.ggml_type,
282                &t.bytes,
283                t.ne.iter().product::<u64>() as usize,
284            ))?
285        };
286        // FR-Spec head trim (MEMRA_GEMMA_DRAFT_RANKS=<ids file, rank order>): gather the ranked
287        // rows of the drafter head + d2t map. (Top-N-IDS truncation measured NEGATIVE — id
288        // order is not frequency; the CORPUS-ranked gather is the real FR-Spec.)
289        // MEMRA_GEMMA_TRIM_ADAPT=<n> (default 512 when ranks are set, 0 = off) appends n spare
290        // rows the serve loop fills from prompt ids + verify corrections (see TrimAdapt).
291        let (head, d2t, trim_adapt) = {
292            let t = src
293                .find("token_embd.weight")
294                .ok_or("drafter missing token_embd")?;
295            let in_f = t.ne[0] as usize;
296            let n_vocab = t.ne[1] as usize;
297            match std::env::var("MEMRA_GEMMA_DRAFT_RANKS").ok() {
298                Some(path) => {
299                    // row gather is layout-agnostic given the per-row byte stride: Q4_0 (26B
300                    // drafter) and Q8_0 (31B drafter) both ship 32-elem blocks row-major.
301                    // (qtype, elems/block, bytes/block) — the gather is stride-agnostic.
302                    let (qtype, blk_e, blk_b) = match t.ggml_type {
303                        memra_gguf::GgmlType::Q4_0 => (crate::QT_Q4_0, 32, 18),
304                        memra_gguf::GgmlType::Q8_0 => (crate::QT_Q8_0, 32, 34),
305                        memra_gguf::GgmlType::Q6_K => (crate::QT_Q6_K, 256, 210),
306                        other => panic!("drafter head trim: unsupported head type {other:?}"),
307                    };
308                    let ids: Vec<u32> = std::fs::read_to_string(&path)?
309                        .lines()
310                        .filter_map(|l| l.trim().parse().ok())
311                        .filter(|&id| (id as usize) < n_vocab)
312                        .collect();
313                    let n_spare: usize = std::env::var("MEMRA_GEMMA_TRIM_ADAPT")
314                        .ok()
315                        .and_then(|v| v.parse().ok())
316                        .unwrap_or(512);
317                    let row_bytes = in_f / blk_e * blk_b;
318                    let mut gathered = Vec::with_capacity((ids.len() + n_spare) * row_bytes);
319                    for &id in &ids {
320                        let off = id as usize * row_bytes;
321                        gathered.extend_from_slice(&t.bytes[off..off + row_bytes]);
322                    }
323                    // spare slots start as copies of row ids[0] mapping to ids[0] — a real,
324                    // already-present token, so however the argmax resolves the duplicate-
325                    // logit tie, the d2t translation lands on the same token id.
326                    for _ in 0..n_spare {
327                        let off = ids[0] as usize * row_bytes;
328                        gathered.extend_from_slice(&t.bytes[off..off + row_bytes]);
329                    }
330                    eprintln!(
331                        "[gemma-draft] FR head trim: {} rows + {} adaptive ({} MB vs {} MB full)",
332                        ids.len(),
333                        n_spare,
334                        (ids.len() + n_spare) * row_bytes / 1_000_000,
335                        n_vocab * row_bytes / 1_000_000
336                    );
337                    let mut trim_adapt = (n_spare > 0).then(|| {
338                        let mut present = vec![false; n_vocab];
339                        for &id in &ids {
340                            present[id as usize] = true;
341                        }
342                        TrimAdapt {
343                            src_rows: t.bytes.to_vec(),
344                            row_bytes,
345                            n_vocab,
346                            present,
347                            spare_base: ids.len(),
348                            n_spare,
349                            used: 0,
350                            logged_full: false,
351                        }
352                    });
353                    let mut d2t = ids;
354                    let spare_fill = d2t[0];
355                    d2t.extend(std::iter::repeat_n(spare_fill, n_spare));
356                    // pre-fill spare slots from the learned sidecar (trim_adapt_save):
357                    // prior serves' escapes are proposable from round 1 of THIS serve.
358                    if let Some(ta) = trim_adapt.as_mut() {
359                        let learned: Vec<u32> = std::fs::read_to_string(format!("{path}.learned"))
360                            .map(|t| t.lines().filter_map(|l| l.trim().parse().ok()).collect())
361                            .unwrap_or_default();
362                        let mut n_pre = 0usize;
363                        for id in learned {
364                            let i = id as usize;
365                            if i < n_vocab && !ta.present[i] && ta.used < ta.n_spare {
366                                let slot = ta.spare_base + ta.used;
367                                ta.used += 1;
368                                ta.present[i] = true;
369                                let off = i * row_bytes;
370                                gathered[slot * row_bytes..(slot + 1) * row_bytes]
371                                    .copy_from_slice(&t.bytes[off..off + row_bytes]);
372                                d2t[slot] = id;
373                                n_pre += 1;
374                            }
375                        }
376                        if n_pre > 0 {
377                            eprintln!(
378                                "[trim-adapt] {n_pre} learned rows pre-filled from {path}.learned"
379                            );
380                        }
381                    }
382                    // upload AFTER the sidecar pre-fill wrote its rows into `gathered`.
383                    let bytes = e.htod_bytes(&gathered)?;
384                    (
385                        GpuTensor::Quant {
386                            bytes,
387                            qtype,
388                            row_bytes,
389                            ne: vec![in_f as u64, d2t.len() as u64],
390                            scale: 1.0,
391                            rp: false,
392                            #[cfg(memra_cutlass)]
393                            cutlass: None,
394                            fp8: None,
395                            blk: None,
396                            rp4: None,
397                            f16: None,
398                        },
399                        Some(d2t),
400                        trim_adapt,
401                    )
402                }
403                None => (load_t(e, &src, "token_embd.weight")?, None, None),
404            }
405        };
406        // Q4_0 split-plane decode mirrors (MEMRA_Q4RP, same as the main trunk — see hybrid.rs):
407        // the draft chain is 3 serial mmvq trips/round; the head alone is ~137MB/draft.
408        // projection tensor prefix: 26B/31B "nextn.", the E4B assistant "mtp.".
409        let proj_prefix = if src.find("nextn.pre_projection.weight").is_some() {
410            "nextn"
411        } else {
412            "mtp"
413        };
414        let (mut pre_proj, mut post_proj) = (
415            load_t(e, &src, &format!("{proj_prefix}.pre_projection.weight"))?,
416            load_t(e, &src, &format!("{proj_prefix}.post_projection.weight"))?,
417        );
418        let mut head = head;
419        let mut layers = layers;
420        if crate::Engine::q4rp_enabled() {
421            // adaptive-trim heads skip the split-plane mirror: the mmvq _rp twins read the
422            // MIRROR, so an in-place row learn on `bytes` would be invisible to the matmul.
423            let head_ws: &mut [&mut GpuTensor] = if trim_adapt.is_some() {
424                &mut [&mut pre_proj, &mut post_proj]
425            } else {
426                &mut [&mut pre_proj, &mut post_proj, &mut head]
427            };
428            for w in head_ws.iter_mut() {
429                e.build_q4_rp4(w)?;
430            }
431            for l in layers.iter_mut() {
432                for w in [
433                    &mut l.wq,
434                    &mut l.wo,
435                    &mut l.ffn_gate,
436                    &mut l.ffn_up,
437                    &mut l.ffn_down,
438                ] {
439                    e.build_q4_rp4(w)?;
440                }
441            }
442        }
443        let d2t_dev = match &d2t {
444            Some(m) => Some(e.stream().clone_htod(&m[..])?),
445            None => None,
446        };
447        Ok(GemmaDraft {
448            layers,
449            pre_proj,
450            post_proj,
451            output_norm: load_t(e, &src, "output_norm.weight")?,
452            head,
453            d2t,
454            d2t_dev,
455            trim_adapt,
456            rope_freqs,
457            ones: e.htod(&[1.0f32; 512])?,
458            n_embd,
459            n_backbone,
460            rope_base_global: meta_f("rope.freq_base", 1e6),
461            rope_base_swa: meta_f("rope.freq_base_swa", 1e4),
462            sliding_window: meta_u("attention.sliding_window") as usize,
463        })
464    }
465}
466
467impl HybridModel {
468    /// The MAIN layer whose KV cache a drafter layer attends (llama-model.cpp:2139):
469    /// the last OWN-KV layer of the class — `boundary - 2` windowed / `boundary - 1`
470    /// global, where boundary = n_layer - shared_kv_layers. Shared across every
471    /// gemma4-assistant drafter (26B/31B: boundary = n_layer; E4B: 24).
472    pub(crate) fn gemma4_draft_kv_target(&self, swa: bool) -> usize {
473        let shared = self
474            .cfg
475            .gemma4
476            .as_ref()
477            .map(|g| g.shared_kv_layers as usize)
478            .unwrap_or(0);
479        let boundary = self.layers.len() - shared;
480        boundary - if swa { 2 } else { 1 }
481    }
482
483    /// One drafter step: (token, h[2816 device]) at absolute position `pos` over the FROZEN main
484    /// cache. Returns (draft logits host [n_vocab], h_next [2816 device]).
485    pub fn gemma4_draft_step(
486        &self,
487        e: &Engine,
488        d: &GemmaDraft,
489        token: u32,
490        h: &CudaSlice<f32>,
491        pos: usize,
492        cache: &Cache,
493    ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
494        let (hn, h_next) = self.gemma4_draft_trunk(e, d, token, h, pos, cache)?;
495        let logits = e.dtoh(&e.matmul(&d.head, &hn, 1)?)?;
496        Ok((logits, h_next))
497    }
498
499    /// Drafter trunk with the token in DEVICE memory (a 1-elem view of the round's batch
500    /// buffer) — zero host traffic.
501    fn gemma4_draft_trunk_dev(
502        &self,
503        e: &Engine,
504        d: &GemmaDraft,
505        tok_v: &cudarc::driver::CudaView<u32>,
506        h: &CudaSlice<f32>,
507        pos_d: &CudaSlice<i32>,
508        cache: &Cache,
509        dc_bucket: Option<usize>,
510    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
511        let nb = d.n_backbone;
512        let embd_gpu = self
513            .embd_gpu
514            .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload"));
515        let (qt, rb) = self.embd.qt_and_row_bytes(nb);
516        let mut xs = e.embed_gather_device_tv(embd_gpu, tok_v, 1, nb, qt, rb)?;
517        e.scale_inplace(&mut xs, (nb as f32).sqrt(), nb)?;
518        self.gemma4_draft_trunk_from_x(e, d, &xs, h, pos_d, cache, dc_bucket)
519    }
520
521    /// Drafter trunk: returns (post-output_norm hidden [1024], h_next [2816]).
522    fn gemma4_draft_trunk(
523        &self,
524        e: &Engine,
525        d: &GemmaDraft,
526        token: u32,
527        h: &CudaSlice<f32>,
528        pos: usize,
529        cache: &Cache,
530    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
531        let nb = d.n_backbone;
532        let mut xs = e.htod(&self.embd.gather(nb, &[token]))?;
533        e.scale_inplace(&mut xs, (nb as f32).sqrt(), nb)?;
534        let pos_d = e.htod_i32(&[pos as i32])?;
535        return self.gemma4_draft_trunk_from_x(e, d, &xs, h, &pos_d, cache, None);
536    }
537
538    /// Trunk body from the pre-scaled main-embed row.
539    fn gemma4_draft_trunk_from_x(
540        &self,
541        e: &Engine,
542        d: &GemmaDraft,
543        xs: &CudaSlice<f32>,
544        h: &CudaSlice<f32>,
545        pos_d: &CudaSlice<i32>,
546        cache: &Cache,
547        dc_bucket: Option<usize>,
548    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
549        // pos rides a DEVICE slot (burst-arc step a, 2026-07-12): the round fills persistent
550        // slots via set_i32_one (kernel-arg stores — no per-step htod/alloc) and the chain
551        // becomes graph-capturable (an in-graph i32_copy_add can feed the slots later).
552        let eps = self.cfg.rms_eps;
553        let ne = d.n_embd;
554
555        // xh = concat(x, h) [2*n_backbone]
556        let nb = d.n_backbone;
557        let mut xh = e.uninit(2 * nb)?;
558        e.copy_into(&mut xh, 0, xs, nb)?;
559        e.copy_into(&mut xh, nb, h, nb)?;
560
561        let mut cur = e.matmul(&d.pre_proj, &xh, 1)?; // [1024]
562
563        for (_il, dl) in d.layers.iter().enumerate() {
564            // attention over the shared MAIN KV: swa -> the last OWN-KV windowed layer,
565            // global -> the last OWN-KV global layer (llama-model.cpp:2139 rule). Plain
566            // 26B/31B trunks have no shared tail, so this is n-2 / n-1 there; E4B's 18
567            // KV-shared tail layers move the boundary to 24 -> targets 22 (swa) / 23.
568            let main_il = self.gemma4_draft_kv_target(dl.swa);
569            let kvl = cache.kv[main_il].as_ref().unwrap();
570            let (hd, nhh) = (dl.hd, dl.nh);
571            let nkv = kvl.kv_dim_k / hd;
572            let base = if dl.swa {
573                d.rope_base_swa
574            } else {
575                d.rope_base_global
576            };
577
578            let mut hn = e.uninit(ne)?;
579            e.rms_norm(&cur, dl.attn_norm.float_data(), &mut hn, ne, 1, eps)?;
580            let q0 = e.matmul(&dl.wq, &hn, 1)?;
581            let mut q = e.uninit(nhh * hd)?;
582            e.rms_norm(&q0, dl.q_norm.float_data(), &mut q, hd, nhh, eps)?;
583            if dl.swa {
584                e.rope_neox(&mut q, pos_d, hd, hd, nhh, 1, base, 1.0)?;
585            } else {
586                e.rope_neox_ff(&mut q, pos_d, hd, hd, nhh, 1, base, 1.0, &d.rope_freqs)?;
587            }
588            let avail = kvl.len;
589            let win = d.sliding_window;
590            let mut attn = e.uninit(nhh * hd)?;
591            // drafter attends the MAIN cache — its format follows the main layer's class
592            // (windowed L28 = wkv arm, global L29 = gkv arm; gkv routing is hd-keyed inside).
593            // DEVICE-LEN arms (burst arc): the length rides the main layer's len_d counter
594            // so the chain is replay-correct across rounds. dc_bucket = the RUNG the round
595            // derived (power-of-2, shared by eager and captured replays — same n_splits,
596            // same combine order; the main graph arc's bucket lesson). None = host-len arm.
597            if let Some(bucket) = dc_bucket {
598                let k_view = e.view_u8(&kvl.k, kvl.k.len());
599                let v_view = e.view_u8(&kvl.v, kvl.v.len());
600                if dl.swa && avail > win {
601                    e.fa_decode_rows_w(
602                        &q,
603                        &k_view,
604                        &v_view,
605                        &mut attn,
606                        hd,
607                        nhh,
608                        nkv,
609                        &kvl.len_d,
610                        -1,
611                        1,
612                        1.0,
613                        win,
614                        kvl.k_tok_bytes,
615                        kvl.v_tok_bytes,
616                        None,
617                    )?;
618                } else {
619                    e.fa_decode_dc(
620                        &q,
621                        &k_view,
622                        &v_view,
623                        &mut attn,
624                        hd,
625                        nhh,
626                        nkv,
627                        &kvl.len_d,
628                        bucket,
629                        1.0,
630                        kvl.k_tok_bytes,
631                        kvl.v_tok_bytes,
632                        dl.swa && crate::Engine::wkv_on(),
633                    )?;
634                }
635            } else {
636                let (off_tok, t_kv) = if dl.swa && avail > win {
637                    (avail - win, win)
638                } else {
639                    (0, avail)
640                };
641                let k_view = e.view_u8_range(
642                    &kvl.k,
643                    off_tok * kvl.k_tok_bytes,
644                    (off_tok + t_kv) * kvl.k_tok_bytes,
645                );
646                let v_view = e.view_u8_range(
647                    &kvl.v,
648                    off_tok * kvl.v_tok_bytes,
649                    (off_tok + t_kv) * kvl.v_tok_bytes,
650                );
651                e.fa_decode_kvmod(
652                    &q,
653                    &k_view,
654                    &v_view,
655                    &mut attn,
656                    hd,
657                    nhh,
658                    nkv,
659                    t_kv,
660                    1.0,
661                    kvl.k_tok_bytes,
662                    kvl.v_tok_bytes,
663                    dl.swa && crate::Engine::wkv_on(),
664                )?;
665            }
666            let o = e.matmul(&dl.wo, &attn, 1)?;
667
668            let mut post = e.uninit(ne)?;
669            e.rms_norm(&o, dl.post_attn_norm.float_data(), &mut post, ne, 1, eps)?;
670            let mut attn_out = e.uninit(ne)?;
671            e.add(&post, &cur, &mut attn_out, ne)?;
672
673            let mut z = e.uninit(ne)?;
674            e.rms_norm(&attn_out, dl.ffn_norm.float_data(), &mut z, ne, 1, eps)?;
675            let n_ff = dl.ffn_gate.out_features();
676            let gate = e.matmul(&dl.ffn_gate, &z, 1)?;
677            let up = e.matmul(&dl.ffn_up, &z, 1)?;
678            let mut act = e.uninit(n_ff)?;
679            e.gelu_tanh_mul(&gate, &up, &mut act, n_ff)?;
680            let f0 = e.matmul(&dl.ffn_down, &act, 1)?;
681            let mut fpost = e.uninit(ne)?;
682            e.rms_norm(&f0, dl.ffn_post_norm.float_data(), &mut fpost, ne, 1, eps)?;
683            let mut xn = e.uninit(ne)?;
684            e.add_scale(&fpost, &attn_out, dl.out_scale, &mut xn, ne)?;
685            cur = xn;
686        }
687
688        let mut hn = e.uninit(ne)?;
689        e.rms_norm(&cur, d.output_norm.float_data(), &mut hn, ne, 1, eps)?;
690        let h_next = e.matmul(&d.post_proj, &hn, 1)?; // [2816]; head applied by callers (NO softcap)
691        Ok((hn, h_next))
692    }
693
694    /// Greedy draft step: like gemma4_draft_step but the token argmax stays on device —
695    /// host sees 4 bytes (no 1MB logits dtoh per draft). Returns (token, h_next).
696    pub fn gemma4_draft_step_greedy(
697        &self,
698        e: &Engine,
699        d: &GemmaDraft,
700        token: u32,
701        h: &CudaSlice<f32>,
702        pos: usize,
703        cache: &Cache,
704    ) -> Result<(u32, CudaSlice<f32>), Box<dyn std::error::Error>> {
705        let (hn, h_next) = self.gemma4_draft_trunk(e, d, token, h, pos, cache)?;
706        let ld = e.matmul(&d.head, &hn, 1)?;
707        let tok_d = e.argmax_token_device(&ld, d.head.out_features())?;
708        let idx = e.dtoh_u32(&tok_d)?[0];
709        let tok = match &d.d2t {
710            Some(map) => map[idx as usize],
711            None => idx,
712        };
713        Ok((tok, h_next))
714    }
715}
716
717impl HybridModel {
718    /// gemma4 MTP greedy spec loop: prime the prompt, then rounds of (chained K-token draft
719    /// over the frozen main cache) + (ONE batched verify) + longest-prefix accept + KV rollback.
720    /// Returns generated tokens; prints acceptance stats.
721    #[allow(clippy::too_many_arguments)]
722    pub fn generate_spec_gemma(
723        &self,
724        e: &Engine,
725        d: &mut GemmaDraft,
726        prompt: &[u32],
727        max_new: usize,
728        k: usize,
729        eos: &[u32],
730    ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
731        let n_embd = self.cfg.n_embd as usize;
732        let eps = self.cfg.rms_eps;
733        let mut cache = Cache::new(e, &self.cfg, prompt.len() + max_new + k + 8)?;
734
735        // Adaptive trim, learn point 1: the PROMPT's own ids — the measured escapees are the
736        // prompt's domain content words echoed back (▁oceans, clouds, Explain...), so the
737        // prompt is the cheapest predictor of what the trim is about to miss.
738        trim_adapt_learn(e, d, prompt)?;
739
740        let t_prime = std::time::Instant::now();
741        // short prompts fall below prime_cache's T floor — the batched verify IS a prime.
742        let (pl, h_seed) = if prompt.len() >= crate::hybrid_forward::PRIME_MIN_T {
743            let (l, hs, _hh) = self.prime_cache(e, prompt, &mut cache, 0)?;
744            (l, hs)
745        } else if self.is_gemma4_e4b() {
746            // E4B short-prompt prime: TOKENWISE — the batched e4b trunk at base_len==0
747            // rides the PRIME-FA f32 arm (a different numerics class from the plain arm's
748            // tokenwise prime), and the class skew flipped near-tie streams (3/64,
749            // 2026-07-13). decode_step_h is the same chain the plain arm primes with.
750            let n_embd_ = self.cfg.n_embd as usize;
751            let mut ll = Vec::new();
752            let mut hx = e.zeros(n_embd_)?;
753            for &tok in prompt {
754                let (l, hh) = self.gemma4_e4b_decode_step_h(e, tok, &mut cache)?;
755                ll = l;
756                hx = hh;
757            }
758            // decode_step_h returns the PRE-output_norm hidden; the short-prompt arm's
759            // h convention below is POST-norm — norm here.
760            let mut hp = e.uninit(n_embd_)?;
761            e.rms_norm(&hx, self.output_norm.float_data(), &mut hp, n_embd_, 1, eps)?;
762            (ll, hp)
763        } else {
764            let n_vocab = self.output.out_features();
765            let (lv, hv) = self.gemma4_decode_step_t_h(e, prompt, 0, &mut cache)?;
766            let t = prompt.len();
767            let last = lv[(t - 1) * n_vocab..t * n_vocab].to_vec();
768            // NOTE hv rows are POST-output_norm; h_seed convention below expects PRE-norm and
769            // re-norms — so recover a pre-norm-free path: use the post-norm row DIRECTLY.
770            let hvv = e.view(&hv, t * n_embd);
771            let row = hvv.slice((t - 1) * n_embd..t * n_embd);
772            let mut hrow = e.uninit(n_embd)?;
773            e.copy_view_into(&mut hrow, 0, &row, n_embd)?;
774            // mark: already post-norm — skip the re-norm below via the flag
775            (last, hrow)
776        };
777        e.stream().synchronize()?;
778        crate::PRIME_NANOS.store(
779            t_prime.elapsed().as_nanos() as u64,
780            std::sync::atomic::Ordering::Relaxed,
781        );
782        // drafter h = POST-output_norm hidden (llama h_nextn); prime returns PRE-norm h_seed,
783        // the short-prompt verify path already returns post-norm rows.
784        let mut h = if prompt.len() >= crate::hybrid_forward::PRIME_MIN_T {
785            let mut hh = e.uninit(n_embd)?;
786            e.rms_norm(
787                &h_seed,
788                self.output_norm.float_data(),
789                &mut hh,
790                n_embd,
791                1,
792                eps,
793            )?;
794            hh
795        } else {
796            h_seed
797        };
798
799        let mut last = crate::forward::argmax(&pl) as u32;
800        // MEMRA_PROFILE_SPEC=2: capture starts at the ROUND LOOP (prime excluded) — pair
801        // with `nsys -c cudaProfilerApi` (the qwen loop's pattern, spec.rs).
802        if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
803            unsafe extern "C" {
804                fn cudaProfilerStart() -> i32;
805            }
806            unsafe {
807                cudaProfilerStart();
808            }
809        }
810        let mut out: Vec<u32> = Vec::with_capacity(max_new);
811        let (mut drafted, mut accepted, mut rounds) = (0usize, 0usize, 0usize);
812        // per-position accept histogram (MEMRA_SPEC_STATS): [attempted, accepted] per slot —
813        // the depth-K policy statistic (deep slots' marginal accept decides fixed-cap vs deep).
814        let mut pos_att = [0usize; 16];
815        let mut pos_acc = [0usize; 16];
816
817        // ASYNC ROUND v2 (dc class): the whole draft chain + verify enqueue with ZERO host
818        // syncs — token seeds via kernel-arg store (u32_set_k, no host-memory transfer), draft
819        // argmaxes land in the batch buffer, verify argmaxes in vam_d; ONE pack + ONE dtoh of
820        // (k drafts + k+1 vam) closes the round. (v1 with memcpy_htod seeding measured
821        // NEGATIVE — the pageable-copy sync; this is the retry with the sync removed.)
822        let mut batch_d = e.stream().alloc_zeros::<u32>(k + 1)?;
823        let mut packed = e.stream().alloc_zeros::<u32>(2 * k + 1)?;
824        // confidence-adaptive depth (MEMRA_SPEC_PMIN, default 0 = off): per-draft probs.
825        let pmin: f32 = std::env::var("MEMRA_SPEC_PMIN")
826            .ok()
827            .and_then(|v| v.parse().ok())
828            .unwrap_or(0.0);
829        // IN-ROUND confidence cut (2026-07-28): llama's draft-mtp stops drafting the
830        // moment a draft's top-1 prob falls below p-min; our MEMRA_SPEC_PMIN is one round
831        // LATE by design (zero-sync round). This arm pays one small dtoh sync per draft
832        // step (steps ~150µs; sync ~15µs) to cut the chain mid-round and verify at the
833        // shrunk width. Eager arm only — burst/graph arms draft fixed depth.
834        // DEFAULT is SELF-KEYED: active at depth (pos >= floor_ctx) and only in rounds
835        // following a MISS — measured: depth cells with sub-0.9 acceptance win (26B
836        // +1.4-3.2% @ 0.868-0.882 accept, 31B +2% @ 0.845-0.883), chat cells and the
837        // 0.95-accept 12B depth lose under an ALWAYS-on cut (-0.9 to -6%) but their
838        // rounds are mostly full-accept so the self-key idles there. Explicit
839        // MEMRA_SPEC_PMIN_INROUND pins the cut at every position/round; =0 disables.
840        let pmin_ir_env: Option<f32> = std::env::var("MEMRA_SPEC_PMIN_INROUND")
841            .ok()
842            .and_then(|v| v.parse().ok());
843        const PMIN_IR_DEFAULT: f32 = 0.7;
844        let mut prev_full = true; // round 1: no miss evidence yet — draft at full depth
845        let mut p_d = e.stream().alloc_zeros::<f32>(k.max(1))?;
846
847        // ADAPTIVE DRAFT LENGTH (default ON 2026-07-10; MEMRA_SPEC_ADAPT=0 reverts): llama's
848        // draft-mtp reaches 0.64-0.70 acceptance on the SAME drafter (ours fixed-K: 0.52) by
849        // drafting fewer tokens when unconfident (p-min gate). Zero-sync host proxy: next
850        // round's depth = last round's accepted run + 1, clamped to [floor=1, k] — rounds
851        // after a miss shrink, streaks re-deepen. The round's ONE dtoh already carries the
852        // acceptance; no new syncs. Policy sweep (short chat, N=1 each): floor1/cap3 239.2
853        // vs fixed-K3 231.1 (+3.5%, accept .52->.58); floor2 and cap4/5 all worse.
854        let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() != Ok("0");
855        // ADAPTIVE FLOOR default is per-model (MEMRA_SPEC_ADAPT_FLOOR overrides): the floor-1
856        // policy collapses to shallow drafts after any miss and pays a slow re-deepen; on
857        // models with an expensive verify step the deep-draft upside dwarfs the wasted-draft
858        // cost. Measured 2026-07-25 (chat cell, own-gen trim; peak grids both models):
859        // 31B K=5 floor=4 120.2 vs floor=1 103.8 (+15.7%, N=3; floor 5-6 falls off);
860        // 12B K=4-5 floor=4 240.5-240.8 vs floor=1 200.6 (+20%, floor 5+ falls off).
861        // The floor clamps to k_cap, so shallow-K callers are unaffected.
862        // 26B tier (2026-07-26 re-sweep under the f16pv spec flip): floor=2 wins BOTH its
863        // cells — short 329.5 vs 307.0 floor1 (+7%, best at every K), depth 329.7 vs ~318
864        // (the 2026-07-10 "floor2 worse" verdict predates the flip and is superseded).
865        // E4B (n_embd < 2500) keeps floor=1 — unmeasured, cheap verify.
866        let adapt_floor_default: usize = if self.cfg.n_embd >= 3500 {
867            4
868        } else if self.cfg.n_embd >= 2500 {
869            2
870        } else {
871            1
872        };
873        // (stream-k spec key lives in HybridModel::load_from_source_impl — it must be set
874        // before the PRIME's GEMMs autotune, not here.)
875        let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
876            .ok()
877            .and_then(|v| v.parse().ok());
878        let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
879        // POSITION KEY (2026-07-26): the HIGH floor is a SHORT-CTX win. At depth the
880        // per-position acceptance is lower and FORCED-DEEP drafts turn net-negative:
881        // 31B d1736 floor4 99-101 and floor2 97.4-99.8 @ 0.758-0.778 vs floor1
882        // 103.8-104.2 @ 0.817 (two perf-ci batteries + flip-tree N=2 — floor2 is a REAL
883        // small loss there, not noise), while its chat cell holds +15-20% under floor4.
884        // The 26B is the opposite at depth: its mild floor2 WINS (304-305 vs ~297).
885        // Default: full floor while pos < floor_ctx; past it HIGH-floor models (>=4)
886        // relax to 1, MILD-floor models keep their floor. MEMRA_SPEC_FLOOR_CTX overrides
887        // the boundary; an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
888        let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
889            .ok()
890            .and_then(|v| v.parse().ok())
891            .unwrap_or(1024);
892        let floor_at = |pos: usize| -> usize {
893            if adapt_floor_env.is_some() || pos < floor_ctx {
894                adapt_floor
895            } else if adapt_floor >= 4 {
896                1
897            } else {
898                adapt_floor
899            }
900        };
901        // cap ceiling 7 by default; MEMRA_SPEC_CAPMAX opens the b16 verify tier (t=9..16).
902        // The historical cap>=8 "crash" was two host bugs, both fixed 2026-07-12: round 1
903        // ran UNCLAMPED (`kc = k` — verify t=K+1 entered the b16 tier while it was gated)
904        // and the b16 dispatch requested _r2 twins that were never compiled (mcols==16 now
905        // forces the base variant). Stream gates arbitrate any raised cap.
906        let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
907            .ok()
908            .and_then(|v| v.parse().ok())
909            .unwrap_or(7);
910        let k_cap = k.min(cap_max).max(1);
911        // DRAFT-CHAIN GRAPHS (burst-arc step c, MEMRA_GEMMA_DRAFT_GRAPH=1): the whole k-step
912        // draft chain replays as ONE captured graph — position slots fill in-graph,
913        // the seed hidden rides the persistent g_seed buffer, KV lengths ride len_d (step b).
914        // Keyed on (kr, rung, over_win): a new depth/rung/window regime captures lazily.
915        let graph_on = std::env::var("MEMRA_GEMMA_DRAFT_GRAPH").as_deref() == Ok("1");
916        let mut draft_graphs: std::collections::HashMap<
917            (usize, usize, bool),
918            (
919                cudarc::driver::CudaGraph,
920                Vec<Box<dyn std::any::Any + Send>>,
921            ),
922        > = Default::default();
923        let mut g_seed = e.zeros(n_embd)?;
924        // seed len_d before round 1 (prime went through the host-len path).
925        for kvl in cache.kv.iter_mut().flatten() {
926            e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
927        }
928        // persistent per-step rope-pos slots (device; filled by set_i32_one kernel-arg stores).
929        let mut pos_slots: Vec<CudaSlice<i32>> = (0..k_cap.max(1))
930            .map(|_| e.htod_i32(&[0]))
931            .collect::<Result<_, _>>()?;
932        // clamp round 1 too (the leak above).
933        let mut kc = k_cap;
934        // BURST (MEMRA_GEMMA_SPEC_BURST=M, default off): pre-issue M full rounds — draft-graph
935        // replay + verify-stream + device accept/seed/rollback/ring-commit — with ONE host
936        // sync per M rounds (the ring drain). The draft(N+1)-overlapping-verify(N) window this
937        // opens is the burst arc's whole prize (~14% of a round; launch tax alone is hidden
938        // at 96.7% busy). Requires the draft graphs (step c) and a regime-stable horizon.
939        let burst_m: usize = std::env::var("MEMRA_GEMMA_SPEC_BURST")
940            .ok()
941            .and_then(|v| v.parse().ok())
942            .unwrap_or(0);
943        let mut burst_state: Option<(
944            crate::round_stream::StreamBufs,
945            CudaSlice<f32>,
946            CudaSlice<u64>,
947            crate::hybrid_forward::VerifyStreamScratch,
948        )> = None;
949        let win_main = self
950            .cfg
951            .gemma4
952            .as_ref()
953            .map(|g| g.sliding_window as usize)
954            .unwrap_or(0);
955        let g4_shared = self
956            .cfg
957            .gemma4
958            .as_ref()
959            .map(|g| g.shared_kv_layers)
960            .unwrap_or(0);
961        'outer: while out.len() < max_new {
962            // burst gate first (see the BURST ARM below): a burst round drafts at FULL depth
963            // (kr = k_cap — the captured chain replays a fixed K; adaptation is host logic).
964            let horizon = burst_m * (k_cap + 1);
965            let burst_ok = burst_m >= 1 && pmin == 0.0 && g4_shared == 0
966                && (cache.pos + horizon + k_cap + 4 < win_main || cache.pos > win_main)
967                // fa512 crossover: the whole horizon on one side (the stream verify's global
968                // arm picks per-row-dc vs rows by hint; straddling rounds stay eager).
969                && (cache.pos + horizon + k_cap + 4 < crate::fa512_min_tkv()
970                    || cache.pos + 1 >= crate::fa512_min_tkv())
971                && e.fa_rows_eligible(cache.pos, 256)
972                && cache.pos + horizon + k_cap + 2 <= cache.max_ctx
973                && out.len() + horizon <= max_new;
974            let mut kr = if burst_ok {
975                k_cap
976            } else if adapt {
977                kc
978            } else {
979                k_cap
980            };
981            // power-of-2 rung bucket for the dc arms (shared by eager and captured replays);
982            // MEMRA_GEMMA_DRAFT_DC=0 reverts to the host-len kvmod arm.
983            let dc_bucket: Option<usize> = {
984                static DC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
985                if *DC.get_or_init(|| std::env::var("MEMRA_GEMMA_DRAFT_DC").as_deref() != Ok("0")) {
986                    let ml = cache
987                        .kv
988                        .iter()
989                        .flatten()
990                        .map(|kv| kv.len)
991                        .max()
992                        .unwrap_or(1);
993                    // burst rounds size the rung for the WHOLE horizon: the captured chain
994                    // replays M rounds between host looks, so the grid must cover the last
995                    // round's len too (a per-round rung undersizes past its pow2 boundary).
996                    let slack = if burst_ok { horizon } else { 0 };
997                    Some((ml + slack + k_cap + 2).next_power_of_two().max(512))
998                } else {
999                    None
1000                }
1001            };
1002            e.u32_set_k(&mut batch_d, last, 0)?;
1003            e.copy_into(&mut g_seed, 0, &h, n_embd)?;
1004            // the draft chain, step j: reads g_seed via the hc chain, pos from pos_slots[j]
1005            // (eager: host-filled; graph: filled in-graph).
1006            let run_chain = |e: &Engine,
1007                             d: &GemmaDraft,
1008                             batch_d: &mut CudaSlice<u32>,
1009                             p_d: &mut CudaSlice<f32>,
1010                             g_seed: &CudaSlice<f32>,
1011                             pos_slots: &Vec<CudaSlice<i32>>,
1012                             inround: f32|
1013             -> Result<usize, Box<dyn std::error::Error>> {
1014                // uninit+copy (NOT clone_dtod): clone_dtod's internal alloc bypasses the
1015                // capture-retain hooks — its address got pool-reused between replays and the
1016                // replayed chain read a corrupted seed (accept 0.52 vs 0.76).
1017                let mut hc = e.uninit(n_embd)?;
1018                e.copy_into(&mut hc, 0, g_seed, n_embd)?;
1019                for j in 0..kr {
1020                    let tv = batch_d.slice(j..j + 1);
1021                    let (hn, h_next) = self.gemma4_draft_trunk_dev(
1022                        e,
1023                        d,
1024                        &tv,
1025                        &hc,
1026                        &pos_slots[j],
1027                        &cache,
1028                        dc_bucket,
1029                    )?;
1030                    let ld = e.matmul(&d.head, &hn, 1)?;
1031                    e.argmax_token_device_col(&ld, 0, d.head.out_features(), batch_d, j + 1)?;
1032                    // confidence-adaptive depth (MEMRA_SPEC_PMIN): TRIM-space prob before d2t.
1033                    if pmin > 0.0 || inround > 0.0 {
1034                        e.prob_of_token_device_col(
1035                            &ld,
1036                            batch_d,
1037                            j + 1,
1038                            p_d,
1039                            j,
1040                            d.head.out_features(),
1041                        )?;
1042                    }
1043                    // FR-trimmed head: translate the trim-space argmax to the vocab id.
1044                    if let Some(map) = &d.d2t_dev {
1045                        e.u32_map_k(batch_d, map, j + 1)?;
1046                    }
1047                    hc = h_next;
1048                    // IN-ROUND cut: one small dtoh sync per step; stop drafting the moment
1049                    // confidence falls below the gate and verify at the shrunk width.
1050                    // (A DSpark-class marginal-rate window — S_{j+1}*T(j) > E[tok](j)*t_d
1051                    // with profiled t_draft/t_verify EMAs — measured FLAT here 2026-07-30:
1052                    // never cuts at accept >= 0.8, par-to-noise on 26B/31B depth x3
1053                    // interleaved; arm removed per flags doctrine, jsonl row is the record.)
1054                    if inround > 0.0 && j + 1 < kr {
1055                        let ph = e.dtoh(p_d)?;
1056                        if ph[j] < inround {
1057                            return Ok(j + 1);
1058                        }
1059                    }
1060                }
1061                Ok(kr)
1062            };
1063            let over_win = {
1064                let win = d.sliding_window;
1065                d.layers.iter().any(|dl| {
1066                    dl.swa
1067                        && cache.kv[self.gemma4_draft_kv_target(true)]
1068                            .as_ref()
1069                            .is_some_and(|kv| kv.len > win)
1070                })
1071            };
1072            // ---- ROUND-GRAPH ARM ---- (MEMRA_GEMMA_ROUND_GRAPH=1): the WHOLE round —
1073            // draft chain + stream verify + device accept/seed/rollback/commit + the
1074            // device adaptive-depth update — captured ONCE per (k_cap, rung, over_win)
1075            // regime and replayed as ONE graph launch per round (the llama round-cost
1076            // mechanism: ~600 per-round enqueues collapse to 1). The round is SELF-FEEDING
1077            // (pos_ctr/pend/brk/g_seed all advance in-graph), so the capture warmups are
1078            // simply two SERVED rounds — their tokens land in the ring and drain normally
1079            // (no snapshot/rollback needed, unlike the E4B token door).
1080            // Adaptive K rides brk[0] via spec_adapt_k: drafts always run k_cap deep (the
1081            // drafter is cheap) but the accept walk depth follows the host policy exactly.
1082            let round_graph_on = std::env::var("MEMRA_GEMMA_ROUND_GRAPH").as_deref() == Ok("1");
1083            if round_graph_on
1084                && burst_m == 0
1085                && dc_bucket.is_some()
1086                && pmin == 0.0
1087                && g4_shared == 0
1088                && !self.is_gemma4_e4b()
1089                && (cache.pos + 2 * (k_cap + 1) + k_cap + 4 < win_main || cache.pos > win_main)
1090                && (cache.pos + 2 * (k_cap + 1) + k_cap + 4 < crate::fa512_min_tkv()
1091                    || cache.pos + 1 >= crate::fa512_min_tkv())
1092                && e.fa_rows_eligible(cache.pos, 256)
1093                && cache.pos + 2 * (k_cap + 1) + k_cap + 2 <= cache.max_ctx
1094            {
1095                if burst_state.is_none() {
1096                    // ring sized for the capture warmups (2 rounds) + the live round.
1097                    let bufs = crate::round_stream::StreamBufs::new(e, k_cap, 3)?;
1098                    let fill_dummy = e.zeros(n_embd)?;
1099                    let ptrs =
1100                        crate::round_stream::kv_len_ptr_table(e, &cache, Some(&bufs.pos_ctr))?;
1101                    let scr = self.verify_stream_scratch(e, k_cap + 1)?;
1102                    burst_state = Some((bufs, fill_dummy, ptrs, scr));
1103                }
1104                // entry: `last` is the pending token (emitted at drain), h is the seed.
1105                let (bufs, fill_dummy, ptrs, scr) = burst_state.as_mut().unwrap();
1106                let n_rows = cache.kv.len() + 1;
1107                e.set_i32_one(&mut bufs.pos_ctr, cache.pos as i32)?;
1108                e.u32_set_k(&mut bufs.ring_d, 0, 0)?;
1109                e.u32_set_k(&mut bufs.pend_d, last, 0)?;
1110                e.u32_set_k(&mut bufs.brk_d, (if adapt { kc } else { k_cap }) as u32, 0)?;
1111                e.u32_set_k(&mut bufs.brk_d, 1, 1)?;
1112                e.copy_into(&mut g_seed, 0, &h, n_embd)?;
1113                // entry pend is emitted host-side (the ring only carries accepted drafts
1114                // + bonuses — the burst-arm contract).
1115                out.push(last);
1116                if eos.contains(&last) {
1117                    break 'outer;
1118                }
1119                if out.len() >= max_new {
1120                    break 'outer;
1121                }
1122                let key = (usize::MAX - k_cap, dc_bucket.unwrap(), over_win);
1123                let mut fresh_rounds = 1usize; // rounds executed by this iteration
1124                // `hint` is the verify stream's ARM-GATING upper bound — it must sit on
1125                // the SAME side of every crossover as the live lengths this capture
1126                // serves, INCLUDING the arms' own margins (`hint + t < f512` gates the
1127                // global scalar arm; `hint + 1 >= win` gates rows_w), or the captured
1128                // verify bakes a different kernel class than the eager reference
1129                // (107-vs-106 / 4-64 drifts; the regime gate above guarantees the live
1130                // side with the same margins).
1131                let hint = if cache.pos > win_main {
1132                    dc_bucket.unwrap() + k_cap + 2 // over-window: rows_w regime
1133                } else if cache.pos + 1 >= crate::fa512_min_tkv() {
1134                    win_main - 2 // above f512, under window
1135                } else {
1136                    crate::fa512_min_tkv().saturating_sub(k_cap + 5) // under both
1137                };
1138                let bufs_ptr: *mut crate::round_stream::StreamBufs = &mut *bufs;
1139                let scr_ptr: *mut crate::hybrid_forward::VerifyStreamScratch = &mut *scr;
1140                let cache_ptr: *mut Cache = &mut cache;
1141                let batch_ptr: *mut CudaSlice<u32> = &mut batch_d;
1142                let seed_ptr: *mut CudaSlice<f32> = &mut g_seed;
1143                let slots_ptr: *mut Vec<CudaSlice<i32>> = &mut pos_slots;
1144                let mut round_body = |e: &Engine| -> Result<(), Box<dyn std::error::Error>> {
1145                    // SAFETY: single-threaded round body; the raw pointers alias the outer
1146                    // &mut only within this closure (no overlapping borrows).
1147                    let (bufs, scr, cache, batch_d, g_seed, pos_slots) = unsafe {
1148                        (
1149                            &mut *bufs_ptr,
1150                            &mut *scr_ptr,
1151                            &mut *cache_ptr,
1152                            &mut *batch_ptr,
1153                            &mut *seed_ptr,
1154                            &mut *slots_ptr,
1155                        )
1156                    };
1157                    e.i32_copy_add(&bufs.pos_ctr, &mut bufs.pos_start_d, 0)?;
1158                    e.u32_copy(&bufs.pend_d, batch_d)?;
1159                    for (j, slot) in pos_slots.iter_mut().take(k_cap).enumerate() {
1160                        e.i32_copy_add(&bufs.pos_ctr, slot, j as i32)?;
1161                    }
1162                    let mut hc = e.uninit(n_embd)?;
1163                    e.copy_into(&mut hc, 0, g_seed, n_embd)?;
1164                    for j in 0..k_cap {
1165                        let tv = batch_d.slice(j..j + 1);
1166                        let (hn, h_next) = self.gemma4_draft_trunk_dev(
1167                            e,
1168                            d,
1169                            &tv,
1170                            &hc,
1171                            &pos_slots[j],
1172                            cache,
1173                            dc_bucket,
1174                        )?;
1175                        let ld = e.matmul(&d.head, &hn, 1)?;
1176                        e.argmax_token_device_col(&ld, 0, d.head.out_features(), batch_d, j + 1)?;
1177                        if let Some(map) = &d.d2t_dev {
1178                            e.u32_map_k(batch_d, map, j + 1)?;
1179                        }
1180                        hc = h_next;
1181                    }
1182                    let (vam_d, vh) = self.gemma4_verify_t_am_stream(
1183                        e,
1184                        batch_d,
1185                        k_cap + 1,
1186                        &bufs.pos_ctr,
1187                        hint,
1188                        cache,
1189                        scr,
1190                    )?;
1191                    e.spec_accept_greedy_dc(
1192                        &vam_d,
1193                        batch_d,
1194                        &bufs.last_pred_d,
1195                        &bufs.brk_d,
1196                        &mut bufs.acc_d,
1197                    )?;
1198                    if std::env::var("MEMRA_DEBUG_SPEC").as_deref() == Ok("1")
1199                        && std::env::var("MEMRA_ROUND_GRAPH_CHECK").as_deref() == Ok("1")
1200                    {
1201                        let vhh = e.dtoh(&vh)?;
1202                        let nrm = |r: usize| {
1203                            vhh[r * n_embd..(r + 1) * n_embd]
1204                                .iter()
1205                                .map(|x| x * x)
1206                                .sum::<f32>()
1207                                .sqrt()
1208                        };
1209                        let vamh = e.dtoh_u32(&vam_d)?;
1210                        eprintln!(
1211                            "[rg-vh] |row0|={:.3} |row1|={:.3} |row2|={:.3} vam={:?}",
1212                            nrm(0),
1213                            nrm(1),
1214                            nrm(2),
1215                            &vamh[..(k_cap + 1).min(7)]
1216                        );
1217                    }
1218                    e.spec_seed_gather(&vh, fill_dummy, &bufs.acc_d, g_seed, 1, n_embd)?;
1219                    e.spec_rollback_stream(ptrs, &bufs.pos_start_d, &bufs.acc_d, 1, n_rows)?;
1220                    e.spec_ring_commit(
1221                        batch_d,
1222                        &bufs.acc_d,
1223                        &bufs.brk_d,
1224                        &mut bufs.ring_d,
1225                        &mut bufs.pend_d,
1226                    )?;
1227                    e.spec_adapt_k(&bufs.acc_d, &mut bufs.brk_d, floor_at(cache.pos), k_cap)?;
1228                    Ok(())
1229                };
1230                // MEMRA_ROUND_GRAPH_CHECK=1: run the body EAGERLY (no capture/replay) —
1231                // splits "body semantics wrong" from "replay mechanics wrong".
1232                let body_check = std::env::var("MEMRA_ROUND_GRAPH_CHECK").as_deref() == Ok("1");
1233                if body_check {
1234                    round_body(e)?;
1235                    if std::env::var("MEMRA_DEBUG_SPEC").as_deref() == Ok("1") {
1236                        let acc = e.dtoh_u32(&bufs.acc_d)?;
1237                        let brk = e.dtoh_u32(&bufs.brk_d)?;
1238                        let bt = e.dtoh_u32(&batch_d)?;
1239                        let tgt = self.gemma4_draft_kv_target(true);
1240                        let ld = e.dtoh_i32(&cache.kv[tgt].as_ref().unwrap().len_d)?[0];
1241                        let gs = e.dtoh(&g_seed)?;
1242                        let gn: f32 = gs.iter().map(|x| x * x).sum::<f32>().sqrt();
1243                        eprintln!(
1244                            "[rg-check] pos0={} batch={bt:?} n_acc={} bonus={} brk_next={:?} len_d[L{tgt}]={ld} |g_seed|={gn:.3}",
1245                            cache.pos, acc[0], acc[1], brk
1246                        );
1247                    }
1248                } else {
1249                    if !draft_graphs.contains_key(&key) {
1250                        let g = e.capture_graph_retained(&mut round_body)?;
1251                        draft_graphs.insert(key, g);
1252                        fresh_rounds += 2; // the capture warmups were served rounds
1253                    }
1254                    draft_graphs.get(&key).unwrap().0.launch()?;
1255                }
1256                // drain: ONE host sync per iteration (warmup rounds included on capture).
1257                let toks = bufs.drain_ring(e)?;
1258                let posh = e.dtoh_i32(&bufs.pos_ctr)?[0] as usize;
1259                if std::env::var("MEMRA_DEBUG_SPEC").as_deref() == Ok("1") {
1260                    eprintln!(
1261                        "[round-graph] fresh={fresh_rounds} drained={} posh={posh} toks={:?}",
1262                        toks.len(),
1263                        &toks[..toks.len().min(12)]
1264                    );
1265                }
1266                drafted += fresh_rounds * k_cap;
1267                rounds += fresh_rounds;
1268                accepted += toks.len().saturating_sub(fresh_rounds);
1269                let mut ended = false;
1270                for &tk in &toks[..toks.len() - 1] {
1271                    out.push(tk);
1272                    if eos.contains(&tk) || out.len() >= max_new {
1273                        ended = true;
1274                        break;
1275                    }
1276                }
1277                last = *toks.last().unwrap();
1278                cache.pos = posh;
1279                for kvl in cache.kv.iter_mut().flatten() {
1280                    kvl.len = posh;
1281                }
1282                // NO allocation between replays: a pool alloc here can land on a baked
1283                // transient address and corrupt the next replay (the draft-graph lesson).
1284                // g_seed already holds the next seed (in-graph gather); copy INTO the
1285                // existing h buffer for the (possible) eager-arm handoff.
1286                e.copy_into(&mut h, 0, &g_seed, n_embd)?;
1287                kc = k_cap; // device brk owns the walk depth; host kc only seeds entry
1288                // learn point 2 (round-graph drain): ring = accepted drafts + bonuses; only
1289                // bonuses can be escapes, and the present-bitmap check skips the rest cheap.
1290                trim_adapt_learn(e, d, &toks)?;
1291                if ended {
1292                    break 'outer;
1293                }
1294                continue 'outer;
1295            }
1296            // ---- BURST ARM ---- (gate computed at the loop top; needs dc arms too)
1297            if burst_ok && dc_bucket.is_some() {
1298                if burst_state.is_none() {
1299                    let bufs = crate::round_stream::StreamBufs::new(e, k_cap, burst_m)?;
1300                    let fill_dummy = e.zeros(n_embd)?; // spec_seed_gather j>=1 always: unread
1301                    let ptrs =
1302                        crate::round_stream::kv_len_ptr_table(e, &cache, Some(&bufs.pos_ctr))?;
1303                    let scr = self.verify_stream_scratch(e, k_cap + 1)?;
1304                    burst_state = Some((bufs, fill_dummy, ptrs, scr));
1305                }
1306                // the loop-top dc_bucket already carries the horizon slack on burst rounds,
1307                // so the key below matches the rung the captured chain actually launches with.
1308                let key = (k_cap, dc_bucket.unwrap(), over_win);
1309                if std::env::var("MEMRA_GEMMA_BURST_GRAPH").as_deref() == Ok("1")
1310                    && !draft_graphs.contains_key(&key)
1311                {
1312                    let g = e.capture_graph_retained(|e| {
1313                        run_chain(e, d, &mut batch_d, &mut p_d, &g_seed, &pos_slots, 0.0)
1314                            .map(|_| ())
1315                    })?;
1316                    draft_graphs.insert(key, g);
1317                }
1318                // entry: `last` is the not-yet-emitted pending token (the ring only ever
1319                // carries accepted drafts + bonuses; the entry pend is emitted host-side).
1320                out.push(last);
1321                if eos.contains(&last) {
1322                    break 'outer;
1323                }
1324                if out.len() >= max_new {
1325                    break 'outer;
1326                }
1327                let (bufs, fill_dummy, ptrs, scr) = burst_state.as_mut().unwrap();
1328                let n_rows = cache.kv.len() + 1; // + the pos counter row
1329                e.set_i32_one(&mut bufs.pos_ctr, cache.pos as i32)?;
1330                e.u32_set_k(&mut bufs.ring_d, 0, 0)?;
1331                e.u32_set_k(&mut bufs.pend_d, last, 0)?;
1332                e.u32_set_k(&mut bufs.brk_d, k_cap as u32, 0)?; // k_used = K (no p-min cut)
1333                e.u32_set_k(&mut bufs.brk_d, 1, 1)?; // base = 1 (pend always set)
1334                e.copy_into(&mut g_seed, 0, &h, n_embd)?;
1335                let pos0 = cache.pos;
1336                for r in 0..burst_m {
1337                    // every op below is ENQUEUED; nothing reads back until the drain.
1338                    e.i32_copy_add(&bufs.pos_ctr, &mut bufs.pos_start_d, 0)?;
1339                    e.u32_copy(&bufs.pend_d, &mut batch_d)?; // batch_d[0] <- pend
1340                    for (j, slot) in pos_slots.iter_mut().take(k_cap).enumerate() {
1341                        e.i32_copy_add(&bufs.pos_ctr, slot, j as i32)?;
1342                    }
1343                    // the chain enqueues ZERO-SYNC with device pos slots — the captured-graph
1344                    // replay is measured EXPENSIVE (26B eager 379 -> 253 with replay), so the
1345                    // burst runs the chain eagerly by default; MEMRA_GEMMA_BURST_GRAPH=1 keeps
1346                    // the replay door for A/B.
1347                    if std::env::var("MEMRA_GEMMA_BURST_GRAPH").as_deref() == Ok("1") {
1348                        draft_graphs.get(&key).unwrap().0.launch()?;
1349                    } else {
1350                        // run_chain's body inlined: the closure holds &cache for the loop's
1351                        // lifetime and collides with the verify's &mut cache borrow.
1352                        let mut hc = e.uninit(n_embd)?;
1353                        e.copy_into(&mut hc, 0, &g_seed, n_embd)?;
1354                        for j in 0..k_cap {
1355                            let tv = batch_d.slice(j..j + 1);
1356                            let (hn, h_next) = self.gemma4_draft_trunk_dev(
1357                                e,
1358                                d,
1359                                &tv,
1360                                &hc,
1361                                &pos_slots[j],
1362                                &cache,
1363                                dc_bucket,
1364                            )?;
1365                            let ld = e.matmul(&d.head, &hn, 1)?;
1366                            e.argmax_token_device_col(
1367                                &ld,
1368                                0,
1369                                d.head.out_features(),
1370                                &mut batch_d,
1371                                j + 1,
1372                            )?;
1373                            if let Some(map) = &d.d2t_dev {
1374                                e.u32_map_k(&mut batch_d, map, j + 1)?;
1375                            }
1376                            hc = h_next;
1377                        }
1378                    }
1379                    // host UPPER bound on this round's base (full-accept growth): sizes the
1380                    // stream verify's splits + window-arm gate; device len is the true bound.
1381                    let hint = pos0 + (r + 1) * (k_cap + 1) + 2;
1382                    let (vam_d, vh) = self.gemma4_verify_t_am_stream(
1383                        e,
1384                        &batch_d,
1385                        k_cap + 1,
1386                        &bufs.pos_ctr,
1387                        hint,
1388                        &mut cache,
1389                        scr,
1390                    )?;
1391                    e.spec_accept_greedy_dc(
1392                        &vam_d,
1393                        &batch_d,
1394                        &bufs.last_pred_d,
1395                        &bufs.brk_d,
1396                        &mut bufs.acc_d,
1397                    )?;
1398                    e.spec_seed_gather(&vh, fill_dummy, &bufs.acc_d, &mut g_seed, 1, n_embd)?;
1399                    e.spec_rollback_stream(ptrs, &bufs.pos_start_d, &bufs.acc_d, 1, n_rows)?;
1400                    e.spec_ring_commit(
1401                        &batch_d,
1402                        &bufs.acc_d,
1403                        &bufs.brk_d,
1404                        &mut bufs.ring_d,
1405                        &mut bufs.pend_d,
1406                    )?;
1407                }
1408                // drain: THE one sync per M rounds. Ring = [acc..., bonus] per round; the
1409                // final element is the next pending token (eager pushes it next round).
1410                let toks = bufs.drain_ring(e)?;
1411                let posh = e.dtoh_i32(&bufs.pos_ctr)?[0] as usize;
1412                drafted += burst_m * k_cap;
1413                rounds += burst_m;
1414                accepted += toks.len().saturating_sub(burst_m); // each round adds n_acc + 1
1415                let mut ended = false;
1416                for &tk in &toks[..toks.len() - 1] {
1417                    out.push(tk);
1418                    if eos.contains(&tk) || out.len() >= max_new {
1419                        ended = true;
1420                        break;
1421                    }
1422                }
1423                last = *toks.last().unwrap();
1424                // host mirrors re-sync (device counters are already correct from rollback).
1425                cache.pos = posh;
1426                for kvl in cache.kv.iter_mut().flatten() {
1427                    kvl.len = posh;
1428                }
1429                // next seed hidden = g_seed (the final round's device gather).
1430                let mut hrow = e.uninit(n_embd)?;
1431                e.copy_into(&mut hrow, 0, &g_seed, n_embd)?;
1432                h = hrow;
1433                kc = k_cap;
1434                // learn point 2 (burst drain): same contract as the round-graph drain.
1435                trim_adapt_learn(e, d, &toks)?;
1436                if ended {
1437                    break 'outer;
1438                }
1439                continue 'outer;
1440            }
1441            if graph_on && dc_bucket.is_some() {
1442                let key = (kr, dc_bucket.unwrap(), over_win);
1443                if !draft_graphs.contains_key(&key) {
1444                    // chain-only capture; pos slots are graph INPUTS (filled eagerly before
1445                    // each launch, like g_seed — the in-graph copy_add fills replayed one
1446                    // round stale, see jsonl).
1447                    let g = e.capture_graph_retained(|e| {
1448                        run_chain(e, d, &mut batch_d, &mut p_d, &g_seed, &pos_slots, 0.0)
1449                            .map(|_| ())
1450                    })?;
1451                    draft_graphs.insert(key, g);
1452                }
1453                for (j, slot) in pos_slots.iter_mut().take(kr).enumerate() {
1454                    e.set_i32_one(slot, (cache.pos + j) as i32)?;
1455                }
1456                draft_graphs.get(&key).unwrap().0.launch()?;
1457                // MEMRA_DRAFT_GRAPH_CHECK=1: re-run the chain eagerly from the same state and
1458                // diff the drafted slots (replay-vs-eager divergence bisect).
1459                if std::env::var("MEMRA_DRAFT_GRAPH_CHECK").as_deref() == Ok("1") {
1460                    // NON-DESTRUCTIVE: compare, then restore the graph's tokens so the round
1461                    // proceeds exactly as it would without the check.
1462                    let gtoks = e.dtoh_u32(&batch_d)?;
1463                    for (j, slot) in pos_slots.iter_mut().take(kr).enumerate() {
1464                        e.set_i32_one(slot, (cache.pos + j) as i32)?;
1465                    }
1466                    run_chain(e, d, &mut batch_d, &mut p_d, &g_seed, &pos_slots, 0.0)?;
1467                    let etoks = e.dtoh_u32(&batch_d)?;
1468                    if gtoks[..=kr] != etoks[..=kr] {
1469                        eprintln!(
1470                            "[draft-graph] DIVERGE round={rounds} graph={:?} eager={:?}",
1471                            &gtoks[..=kr],
1472                            &etoks[..=kr]
1473                        );
1474                    }
1475                    for (j, &t) in gtoks.iter().enumerate().take(kr + 1) {
1476                        e.u32_set_k(&mut batch_d, t, j)?;
1477                    }
1478                }
1479            } else {
1480                for (j, slot) in pos_slots.iter_mut().take(kr).enumerate() {
1481                    e.set_i32_one(slot, (cache.pos + j) as i32)?;
1482                }
1483                let ir_now = match pmin_ir_env {
1484                    Some(p) => p, // explicit pin (0 disables)
1485                    None if cache.pos >= floor_ctx && !prev_full => PMIN_IR_DEFAULT,
1486                    None => 0.0,
1487                };
1488                kr = run_chain(e, d, &mut batch_d, &mut p_d, &g_seed, &pos_slots, ir_now)?;
1489            }
1490            drafted += kr;
1491            rounds += 1;
1492            let pos0 = cache.pos;
1493            // MEMRA_BURST_VCHECK=1: run the STREAM verify first on the same batch/state and
1494            // diff its argmaxes against the eager verify (bisect harness — the stream append
1495            // writes the same rows the eager append then overwrites, so state is untouched).
1496            let vcheck = std::env::var("MEMRA_BURST_VCHECK").as_deref() == Ok("1");
1497            let kvsum = |e: &Engine,
1498                         cache: &Cache|
1499             -> Result<Vec<(u64, u64)>, Box<dyn std::error::Error>> {
1500                let mut out = Vec::new();
1501                for kvl in cache.kv.iter().flatten() {
1502                    let kb = e.dtoh_u8(&kvl.k)?;
1503                    let vb = e.dtoh_u8(&kvl.v)?;
1504                    let lo = pos0 * kvl.k_tok_bytes;
1505                    let hi = (pos0 + kr + 1) * kvl.k_tok_bytes;
1506                    let lov = pos0 * kvl.v_tok_bytes;
1507                    let hiv = (pos0 + kr + 1) * kvl.v_tok_bytes;
1508                    out.push((
1509                        kb[lo..hi].iter().map(|&b| b as u64).sum(),
1510                        vb[lov..hiv].iter().map(|&b| b as u64).sum(),
1511                    ));
1512                }
1513                Ok(out)
1514            };
1515            let vam_s = if vcheck && !self.is_gemma4_e4b() {
1516                let mut ctr = e.htod_i32(&[pos0 as i32])?;
1517                e.set_i32_one(&mut ctr, pos0 as i32)?;
1518                let mut scr0 = self.verify_stream_scratch(e, kr + 1)?;
1519                let (vs, vhs) = self.gemma4_verify_t_am_stream(
1520                    e,
1521                    &batch_d,
1522                    kr + 1,
1523                    &ctr,
1524                    pos0 + kr + 3,
1525                    &mut cache,
1526                    &mut scr0,
1527                )?;
1528                let ss = kvsum(e, &cache)?;
1529                Some((e.dtoh_u32(&vs)?, ss, e.dtoh(&vhs)?))
1530            } else {
1531                None
1532            };
1533            let (vam_d, vh) = if self.is_gemma4_e4b() {
1534                self.gemma4_e4b_decode_step_t_am_dev(e, &batch_d, kr + 1, pos0, &mut cache)?
1535            } else {
1536                self.gemma4_decode_step_t_am_dev(e, &batch_d, kr + 1, pos0, &mut cache)?
1537            };
1538            if let Some((vs, ss, vhs)) = vam_s {
1539                let vhe = e.dtoh(&vh)?;
1540                for r in 0..kr + 1 {
1541                    let md = vhs[r * n_embd..(r + 1) * n_embd]
1542                        .iter()
1543                        .zip(&vhe[r * n_embd..(r + 1) * n_embd])
1544                        .map(|(a, b)| (a - b).abs())
1545                        .fold(0.0f32, f32::max);
1546                    if md > 1e-3 {
1547                        eprintln!("[vcheck-vh] round={rounds} row={r} maxdiff={md:.3e}");
1548                    }
1549                }
1550                let se = kvsum(e, &cache)?;
1551                for (il, (a, b)) in ss.iter().zip(&se).enumerate() {
1552                    if a != b {
1553                        eprintln!("[vcheck-kv] round={rounds} il={il} stream={a:?} eager={b:?}");
1554                    }
1555                }
1556                let ve = e.dtoh_u32(&vam_d)?;
1557                if vs[..kr + 1] != ve[..kr + 1] {
1558                    eprintln!(
1559                        "[vcheck] DIVERGE round={rounds} pos0={pos0} stream={:?} eager={:?}",
1560                        &vs[..kr + 1],
1561                        &ve[..kr + 1]
1562                    );
1563                } else {
1564                    eprintln!("[vcheck] match round={rounds} pos0={pos0}");
1565                }
1566            }
1567            e.u32_pack2(&batch_d, 1, kr, &vam_d, kr + 1, &mut packed)?;
1568            let host = e.dtoh_u32(&packed)?; // the round's ONE sync
1569            let k = kr;
1570            let dtoks: Vec<u32> = host[..k].to_vec();
1571            let vam: Vec<u32> = host[k..2 * k + 1].to_vec();
1572            // longest accepted prefix: d_i accepted iff d_i == argmax(verify[i-1])
1573            // (trimmed heads: batch_d slots were d2t-translated in the draft loop, so dtoks
1574            // are full-vocab ids here — the 2026-07-10 async rewrite silently dropped this
1575            // and the trim probes read accept=0.000 through it.)
1576            let mut m = 0usize;
1577            while m < k {
1578                if dtoks[m] == vam[m] {
1579                    m += 1;
1580                } else {
1581                    break;
1582                }
1583            }
1584            prev_full = m == k; // feeds the self-keyed in-round cut (miss → next round cuts)
1585            if std::env::var("MEMRA_DEBUG_SPEC").as_deref() == Ok("1") {
1586                let l0 = cache
1587                    .kv
1588                    .iter()
1589                    .flatten()
1590                    .next()
1591                    .map(|kv| kv.len)
1592                    .unwrap_or(0);
1593                let hh = e.dtoh(&h)?;
1594                let hn: f32 = hh.iter().map(|x| x * x).sum::<f32>().sqrt();
1595                eprintln!(
1596                    "[round {rounds}] pos0={pos0} post_pos={} kv0_len={l0} last={last} dtoks={dtoks:?} vam={vam:?} m={m} |h_in|={hn:.3}",
1597                    cache.pos
1598                );
1599            }
1600            accepted += m;
1601            for j in 0..k.min(16) {
1602                pos_att[j] += 1;
1603                if j < m {
1604                    pos_acc[j] += 1;
1605                }
1606            }
1607            // emit last + accepted drafts; the correction token comes from verify row m.
1608            out.push(last);
1609            if eos.contains(&last) {
1610                break 'outer;
1611            }
1612            for &dt in &dtoks[..m] {
1613                out.push(dt);
1614                if eos.contains(&dt) {
1615                    break 'outer;
1616                }
1617                if out.len() >= max_new {
1618                    break 'outer;
1619                }
1620            }
1621            let next = vam[m];
1622            // roll back rejected rows: batch appended k+1 rows; keep m+1 (positions of
1623            // last + accepted drafts). SWA layers cap t_kv by the window view, so a plain
1624            // len rewind is safe for every layer.
1625            let keep = m + 1;
1626            for kvl in cache.kv.iter_mut().flatten() {
1627                kvl.len -= (k + 1) - keep;
1628                // keep len_d in lockstep: the drafter's device-len attention arms read it
1629                // (the gemma round appends via the HOST-len path, which doesn't maintain
1630                // the counter — stale len_d gutted acceptance to 0.059 on the dc probe).
1631                e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
1632            }
1633            cache.pos -= (k + 1) - keep;
1634            // h for the next round = main hidden at the LAST KEPT position (verify row m).
1635            let hv = e.view(&vh, (k + 1) * n_embd);
1636            let row = hv.slice(m * n_embd..(m + 1) * n_embd);
1637            let mut hrow = e.uninit(n_embd)?;
1638            e.copy_view_into(&mut hrow, 0, &row, n_embd)?;
1639            h = hrow;
1640            last = next;
1641            // Adaptive trim, learn point 2: ALL verify argmaxes — vam[m] is the emitted
1642            // correction (the only emitted token that can sit outside the trim set; accepted
1643            // drafts are trim members by construction), and vam[i>m] are main-model
1644            // predictions for positions never reached this round: next round usually wants
1645            // exactly those tokens, so learning them here lets the draft propose them
1646            // BEFORE any miss is paid (prose escapes are first-occurrence-dominated —
1647            // corrections-only learning measured +0.5 acceptance pts, jsonl 2026-07-19).
1648            trim_adapt_learn(e, d, &vam)?;
1649            if adapt {
1650                let fl_now = floor_at(cache.pos);
1651                kc = (m + 1).clamp(fl_now.min(k_cap), k_cap);
1652                // confidence cut (MEMRA_SPEC_PMIN > 0): next round drafts no deeper than one
1653                // past the first low-confidence draft of THIS round (llama's p-min class,
1654                // one round late — the zero-sync enqueue stays intact). One extra tiny dtoh.
1655                if pmin > 0.0 {
1656                    let ph = e.dtoh(&p_d)?;
1657                    if let Some(fl) = ph[..kr].iter().position(|&p| p < pmin) {
1658                        kc = kc.min((fl + 1).max(fl_now.min(k_cap)));
1659                    }
1660                }
1661            }
1662        }
1663        eprintln!(
1664            "[gemma-spec] rounds={rounds} drafted={drafted} accepted={accepted}                    accept-rate={:.3} tok/round={:.2}",
1665            accepted as f64 / drafted.max(1) as f64,
1666            out.len() as f64 / rounds.max(1) as f64
1667        );
1668        if let Some((used, budget)) = d.trim_adapt_stats() {
1669            eprintln!("[trim-adapt] {used}/{budget} spare slots learned");
1670            match d.trim_adapt_save() {
1671                Ok(n) if n > 0 => {
1672                    eprintln!("[trim-adapt] {n} new ids appended to the .learned sidecar")
1673                }
1674                Ok(_) => {}
1675                Err(err) => eprintln!("[trim-adapt] sidecar save failed: {err}"),
1676            }
1677        }
1678        if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
1679            let hist: Vec<String> = (0..16)
1680                .filter(|&j| pos_att[j] > 0)
1681                .map(|j| format!("p{j}:{}/{}", pos_acc[j], pos_att[j]))
1682                .collect();
1683            eprintln!("[gemma-spec] per-position accept: {}", hist.join(" "));
1684        }
1685        Ok(out)
1686    }
1687}
1688
1689impl HybridModel {
1690    /// PLAIN-DECODE CUDA-GRAPH loop (gemma4, greedy): one captured verify-trunk step
1691    /// (t=1, device tokens/pos/lens) replayed per token — the launch-gap eraser the
1692    /// decode decomposition demanded (2026-07-23: ~2.3ms/token idle at 128 launches).
1693    /// Self-feeding: argmax -> tok_d -> next embed; counters advance in-graph via
1694    /// spec_rollback_stream(base=1, acc=0). Tokens land in a device ring; ONE host sync
1695    /// per drain window. Captures are keyed on the (rung, window-side, f512-side) regime
1696    /// (the round-graph hint law); regime-crossing stretches run the same body eagerly.
1697    /// Caller guarantees: gemma4, greedy, shared_kv_layers == 0, prompt already primed
1698    /// (cache.pos = prompt len, host kvl.len mirrors set).
1699    pub fn gemma4_generate_plain_graph(
1700        &self,
1701        e: &Engine,
1702        cache: &mut Cache,
1703        last: u32,
1704        max_new: usize,
1705        eos: &[u32],
1706    ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
1707        const RING: usize = 64;
1708        const DRAIN: usize = 32; // replays per host sync
1709        let win_main = self
1710            .cfg
1711            .gemma4
1712            .as_ref()
1713            .map(|g| g.sliding_window as usize)
1714            .unwrap_or(0);
1715        let n_rows = cache.kv.len() + 1;
1716
1717        let was_tracking = e.ctx().is_event_tracking();
1718        if was_tracking {
1719            unsafe {
1720                e.ctx().disable_event_tracking();
1721            }
1722        }
1723        let r = self
1724            .gemma4_plain_graph_inner(e, cache, last, max_new, eos, RING, DRAIN, win_main, n_rows);
1725        if was_tracking {
1726            unsafe {
1727                e.ctx().enable_event_tracking();
1728            }
1729        }
1730        r
1731    }
1732
1733    #[allow(clippy::too_many_arguments)]
1734    fn gemma4_plain_graph_inner(
1735        &self,
1736        e: &Engine,
1737        cache: &mut Cache,
1738        last: u32,
1739        max_new: usize,
1740        eos: &[u32],
1741        ring_cap: usize,
1742        drain: usize,
1743        win_main: usize,
1744        n_rows: usize,
1745    ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
1746        let mut scr = self.verify_stream_scratch(e, 1)?;
1747        let mut tok_d = e.stream().alloc_zeros::<u32>(1)?;
1748        e.u32_set_k(&mut tok_d, last, 0)?;
1749        let pos_ctr = e.htod_i32(&[cache.pos as i32])?;
1750        let mut pos_start_d = e.htod_i32(&[cache.pos as i32])?;
1751        let acc0 = e.stream().alloc_zeros::<u32>(2)?; // acc[0] = 0 -> counters +1
1752        let mut ring = e.stream().alloc_zeros::<u32>(ring_cap)?;
1753        let ptrs = crate::round_stream::kv_len_ptr_table(e, cache, Some(&pos_ctr))?;
1754        for kvl in cache.kv.iter_mut().flatten() {
1755            e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
1756        }
1757        let ring_base = cache.pos; // baked into every capture
1758
1759        let mut graphs: std::collections::HashMap<
1760            (usize, bool, bool),
1761            (
1762                cudarc::driver::CudaGraph,
1763                Vec<Box<dyn std::any::Any + Send>>,
1764            ),
1765        > = Default::default();
1766
1767        let mut out: Vec<u32> = Vec::with_capacity(max_new);
1768        let mut drained = 0usize; // tokens read off the ring
1769
1770        // hint law (round-graph): the arm-gating bound must sit on the SAME side of every
1771        // crossover as the live lengths this capture serves, with the arms' own margins.
1772        let hint_for = |pos: usize| -> usize {
1773            if pos > win_main {
1774                pos + drain + 2
1775            } else if pos + 1 >= crate::fa512_min_tkv() {
1776                win_main.saturating_sub(2)
1777            } else {
1778                crate::fa512_min_tkv().saturating_sub(5)
1779            }
1780        };
1781        let regime_key = |pos: usize| -> (usize, bool, bool) {
1782            let rung = (pos + drain + 2).next_power_of_two().max(512);
1783            (rung, pos > win_main, pos + 1 >= crate::fa512_min_tkv())
1784        };
1785        // the whole [pos, pos+n) stretch must share one regime for a captured replay run.
1786        let stable_for = |pos: usize, n: usize| -> bool {
1787            regime_key(pos) == regime_key(pos + n)
1788                && (pos > win_main || pos + n + 2 < win_main)
1789                && (pos + 1 >= crate::fa512_min_tkv() || pos + n + 2 < crate::fa512_min_tkv())
1790        };
1791
1792        while out.len() < max_new {
1793            let pos = cache.pos;
1794            let hint = hint_for(pos);
1795            let scr_ptr: *mut crate::hybrid_forward::VerifyStreamScratch = &mut scr;
1796            let cache_ptr: *mut Cache = cache as *mut Cache;
1797            let tok_ptr: *mut CudaSlice<u32> = &mut tok_d;
1798            let ring_ptr: *mut CudaSlice<u32> = &mut ring;
1799            let start_ptr: *mut CudaSlice<i32> = &mut pos_start_d;
1800            let step = |e: &Engine| -> Result<(), Box<dyn std::error::Error>> {
1801                // SAFETY: single-threaded body; raw pointers alias the outer &mut only here.
1802                let (scr, cache, tok_d, ring, pos_start_d) = unsafe {
1803                    (
1804                        &mut *scr_ptr,
1805                        &mut *cache_ptr,
1806                        &mut *tok_ptr,
1807                        &mut *ring_ptr,
1808                        &mut *start_ptr,
1809                    )
1810                };
1811                e.i32_copy_add(&pos_ctr, pos_start_d, 0)?;
1812                let (vam, _hn) =
1813                    self.gemma4_verify_t_am_stream(e, tok_d, 1, &pos_ctr, hint, cache, scr)?;
1814                e.u32_copy(&vam, tok_d)?;
1815                e.plain_tok_ring(&vam, pos_start_d, ring_base, ring)?;
1816                e.spec_rollback_stream(&ptrs, pos_start_d, &acc0, 1, n_rows)?;
1817                Ok(())
1818            };
1819
1820            let n_left = max_new - out.len();
1821            let burst = drain.min(n_left);
1822            // MEMRA_G4PLAIN_EAGER=1: run the body eagerly every step (no capture/replay) —
1823            // splits "body semantics wrong" from "replay mechanics wrong" (round-graph law).
1824            let force_eager = std::env::var("MEMRA_G4PLAIN_EAGER").as_deref() == Ok("1");
1825            let steps_done = if !force_eager && burst >= 4 && stable_for(pos, burst + 3) {
1826                let key = regime_key(pos);
1827                if !graphs.contains_key(&key) {
1828                    // capture cost = 3 SERVED steps (2 warmups + the captured run itself):
1829                    // the loop is self-feeding, so they are real tokens in the ring.
1830                    let g = e.capture_graph_retained(step)?;
1831                    graphs.insert(key, g);
1832                    3
1833                } else {
1834                    let (g, _keep) = graphs.get(&key).unwrap();
1835                    for _ in 0..burst {
1836                        g.launch()?;
1837                    }
1838                    burst
1839                }
1840            } else {
1841                step(e)?; // eager fallback (same body)
1842                1
1843            };
1844
1845            // host mirrors + drain
1846            cache.pos += steps_done;
1847            for kvl in cache.kv.iter_mut().flatten() {
1848                kvl.len = cache.pos;
1849            }
1850            e.stream().synchronize()?;
1851            let ringh = e.dtoh_u32(&ring)?;
1852            let total = cache.pos - ring_base;
1853            while drained < total && out.len() < max_new {
1854                let t = ringh[drained % ring_cap];
1855                out.push(t);
1856                drained += 1;
1857                if eos.contains(&t) {
1858                    return Ok(out);
1859                }
1860            }
1861        }
1862        Ok(out)
1863    }
1864}