Skip to main content

cortiq_engine/
fcd.rs

1//! FCD polish trainer — native Rust quality-polish for O(1)-converted
2//! models (docs/RUST_FCD.md). Removes the last Python dependency from
3//! the `cortiq convert --o1` pipeline.
4//!
5//! Certified recipe (torch reference `nystrom_fcd_full2_06b.py`,
6//! Qwen3-0.6B 28/28): train ONLY the LN gains + FFN of the converted
7//! layers, loss = (1−0.7)·CE + 0.7·KL(teacher‖student), AdamW 5e-5
8//! (torch defaults), grad clip 1.0, batch 2×512 fresh random windows,
9//! quick deterministic val every 25 steps, restore the best checkpoint.
10//!
11//! Structure:
12//! - the whole model is dequantized to f32 once; teacher and student
13//!   SHARE the frozen set, trainables get separate master copies (the
14//!   KL anchor never drifts);
15//! - layer-level activation checkpointing: the forward keeps only each
16//!   layer's input hidden; the backward re-runs one layer at a time;
17//! - converted layers use the certified matrix form of the Nyström
18//!   joint kernel in f64 (fcd_ops), M constant in backward;
19//! - GDN (GatedDeltaNet) layers of Qwen3.5-class hybrids run frozen in
20//!   BOTH teacher and student, with a true BPTT through-backward
21//!   (fcd_ops::gdn_*) so trainable layers BELOW them still learn;
22//!   vmf_phase linear layers are refused (no backward yet).
23
24use crate::fcd_ops::{self as ops, NysCfg};
25use crate::nystrom::{O1Cfg, O1Layers};
26use crate::pipeline::{DenseFfn, FfnKind, Pipeline};
27use crate::pool::Pool;
28use crate::qtensor::QTensor;
29use crate::sampler::{SamplerConfig, SplitMix64};
30use cortiq_core::{CmfModel, LayerType, NormStyle, TensorDtype};
31use std::sync::Arc;
32
33/// Position-chunk size for the tied-head loss (never materializes the
34/// full [B·T, vocab] logits of teacher AND student together).
35const LM_CHUNK: usize = 32;
36
37/// AdamW hyper-parameters — torch defaults, part of the certified recipe.
38const ADAM_B1: f64 = 0.9;
39const ADAM_B2: f64 = 0.999;
40const ADAM_EPS: f64 = 1e-8;
41const ADAM_WD: f64 = 0.01;
42
43/// Training hyper-parameters (defaults = the certified recipe).
44#[derive(Clone, Debug)]
45pub struct FcdHyper {
46    pub steps: usize,
47    pub lr: f64,
48    pub kl_w: f64,
49    pub eval_every: usize,
50    pub bs: usize,
51    pub seq: usize,
52    pub seed: u64,
53}
54
55impl Default for FcdHyper {
56    fn default() -> Self {
57        Self {
58            steps: 300,
59            lr: 5e-5,
60            kl_w: 0.7,
61            eval_every: 25,
62            bs: 2,
63            seq: 512,
64            seed: 0,
65        }
66    }
67}
68
69/// What the polish measured — written into `provenance.fcd` and
70/// reported by the CLI.
71#[derive(Clone, Debug)]
72pub struct FcdReport {
73    pub converted: Vec<usize>,
74    /// Teacher (exact attention) quick-val ppl — the anchor.
75    pub teacher_ppl: f64,
76    /// Student quick-val ppl BEFORE training (zero-shot o1 damage).
77    pub ppl_start: f64,
78    /// Best quick-val ppl during training (the restored checkpoint).
79    pub ppl_best: f64,
80    pub best_step: usize,
81    /// Final val ppl of the restored checkpoint on the wider window set.
82    pub ppl_final: f64,
83    pub steps_run: usize,
84    pub sec_per_step: f64,
85    /// Per-step (ce, kl) — the training trajectory, unweighted.
86    pub losses: Vec<(f64, f64)>,
87    /// Generation-gate record (None = ppl-only selection).
88    pub gate: Option<GateReport>,
89}
90
91/// What the generation gate saw and decided.
92#[derive(Clone, Debug)]
93pub struct GateReport {
94    /// Zero-shot (step-0) loop scores per prompt — the baseline.
95    pub baseline: Vec<f64>,
96    /// Per eval checkpoint: (step, val ppl, loop scores, passed).
97    pub evals: Vec<(usize, f64, Vec<f64>, bool)>,
98    /// Step whose params were restored (None = identity: the polish
99    /// was rejected, the artifact carries the zero-shot state).
100    pub chosen: Option<usize>,
101}
102
103// ───────────────────── generation gate (claim 13) ─────────────────────
104
105/// Loopiness of a generated id sequence: 1 − unique 4-grams / total.
106/// 0 = no repeated 4-gram; near 1 = a tight loop.
107pub fn loop_score(ids: &[u32]) -> f64 {
108    if ids.len() < 5 {
109        return 0.0;
110    }
111    let grams: std::collections::HashSet<&[u32]> = ids.windows(4).collect();
112    1.0 - grams.len() as f64 / ids.windows(4).count() as f64
113}
114
115/// Generation-gate configuration (Patent 16 draft, claim 13:
116/// checkpoint selection gated on generation-behavior metrics measured
117/// through the SERVED kernel, not on the training objective alone).
118#[derive(Clone, Debug)]
119pub struct GenGateCfg {
120    /// Fixed long-context prompts (token ids), greedy-decoded at every
121    /// eval checkpoint.
122    pub prompts: Vec<Vec<u32>>,
123    pub gen_tokens: usize,
124    /// A checkpoint fails if ANY prompt's loop score exceeds this.
125    pub threshold: f64,
126    /// …or exceeds its zero-shot baseline by more than this.
127    pub baseline_slack: f64,
128}
129
130impl GenGateCfg {
131    /// The standard 3-prompt probe of the torch reference: 400-token
132    /// windows at L/10, L/2, 8L/10 of the val stream, greedy 60.
133    pub fn standard(va: &[u32]) -> Option<Self> {
134        let l = va.len().saturating_sub(500);
135        if l < 400 {
136            return None;
137        }
138        let prompts = [l / 10, l / 2, 8 * l / 10]
139            .iter()
140            .map(|&off| va[off..off + 400].to_vec())
141            .collect();
142        Some(Self {
143            prompts,
144            gen_tokens: 60,
145            threshold: 0.35,
146            baseline_slack: 0.10,
147        })
148    }
149}
150
151/// Gate predicate (Patent 16 draft, claim 13): a checkpoint PASSES iff
152/// no prompt's loop score exceeds `threshold` AND none exceeds its
153/// zero-shot baseline by more than `slack` — boundary values pass.
154pub fn gate_pass(scores: &[f64], baseline: &[f64], threshold: f64, slack: f64) -> bool {
155    scores
156        .iter()
157        .zip(baseline)
158        .all(|(&s, &b)| s <= threshold && s <= b + slack)
159}
160
161/// Checkpoint selection: lowest val ppl AMONG GATE-PASSING checkpoints
162/// (ties → earliest). None = nothing passed → the caller must restore
163/// the zero-shot state (identity polish): the stage must never make
164/// generation worse than conversion alone. (Patent 16 draft, claim 13.)
165pub fn select_checkpoint(
166    evals: &[(usize, f64, Vec<f64>)],
167    baseline: &[f64],
168    threshold: f64,
169    slack: f64,
170) -> Option<usize> {
171    let mut best: Option<usize> = None;
172    for (i, (_, ppl, scores)) in evals.iter().enumerate() {
173        if !gate_pass(scores, baseline, threshold, slack) {
174            continue;
175        }
176        if best.map(|b| *ppl < evals[b].1).unwrap_or(true) {
177            best = Some(i);
178        }
179    }
180    best
181}
182
183// ───────────────────────── model container ─────────────────────────
184
185
186/// Wall-clock phase counters for the bake profiler (CMF_BAKE_PROF=1
187/// prints them). Written from worker threads, so atomics; nanoseconds.
188pub mod prof {
189    use std::sync::atomic::{AtomicU64, Ordering};
190    pub static ATTN_FWD: AtomicU64 = AtomicU64::new(0);
191    pub static FFN_FWD: AtomicU64 = AtomicU64::new(0);
192    pub static BWD: AtomicU64 = AtomicU64::new(0);
193    pub static GEMM: AtomicU64 = AtomicU64::new(0);
194    pub static GEMM_CALLS: AtomicU64 = AtomicU64::new(0);
195    #[inline]
196    pub fn add(c: &AtomicU64, t: std::time::Instant) {
197        c.fetch_add(t.elapsed().as_nanos() as u64, Ordering::Relaxed);
198    }
199    /// Read and reset, in seconds.
200    pub fn take(c: &AtomicU64) -> f64 {
201        c.swap(0, Ordering::Relaxed) as f64 / 1e9
202    }
203
204    use std::sync::Mutex;
205    /// (n, k, m) → (calls, ns). A handful of shapes dominate a training
206    /// step; naming them decides which ones are worth a GPU submit and
207    /// which are cheaper computed in place.
208    pub static SHAPES: Mutex<Vec<((usize, usize, usize), (u64, u64))>> = Mutex::new(Vec::new());
209    pub fn gemm_shape(n: usize, k: usize, m: usize, t0: std::time::Instant) {
210        let ns = t0.elapsed().as_nanos() as u64;
211        let mut g = SHAPES.lock().unwrap();
212        match g.iter_mut().find(|(s, _)| *s == (n, k, m)) {
213            Some((_, (c, tt))) => {
214                *c += 1;
215                *tt += ns;
216            }
217            None => g.push(((n, k, m), (1, ns))),
218        }
219    }
220    pub fn shape_report(top: usize) -> String {
221        let mut g = SHAPES.lock().unwrap();
222        g.sort_by_key(|(_, (_, ns))| std::cmp::Reverse(*ns));
223        let out = g
224            .iter()
225            .take(top)
226            .map(|((n, k, m), (c, ns))| {
227                format!(
228                    "    [{n}x{k}x{m}] {c} calls, {:.1}s total, {:.1} ms/call",
229                    *ns as f64 / 1e9,
230                    *ns as f64 / 1e6 / *c as f64
231                )
232            })
233            .collect::<Vec<_>>()
234            .join("\n");
235        g.clear();
236        out
237    }
238}
239
240/// Frozen attention operator of one layer — the per-layer dispatch
241/// point for through-backwards (docs/RUST_FCD.md §3).
242enum FcdAttn {
243    Full {
244        /// The projections live in the streamed `LayerMats`, not here:
245        /// eagerly resident weights are what made a 4 B bake swap a
246        /// laptop. Only the small per-head metadata stays.
247        qrows: usize,
248        q_norm: Option<Vec<f32>>,
249        k_norm: Option<Vec<f32>>,
250        bias: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
251        /// (bq|bk|bv) concatenated once at build: the device chain binds
252        /// it by a STABLE address, which is what keeps the fingerprinted
253        /// const cache from minting an entry per call.
254        bias_cat: Option<Vec<f32>>,
255        /// Qwen3.5: wq rows = 2·nh·hd, per-head [q; gate]; the head
256        /// outputs are multiplied by σ(gate) before o_proj.
257        output_gate: bool,
258    },
259    /// GatedDeltaNet (Qwen3.5 hybrids): never converted, never trained;
260    /// through-backward = BPTT over the window (fcd_ops::gdn_*).
261    Gdn {
262        wqkv: Vec<f32>,
263        wz: Vec<f32>,
264        wa: Vec<f32>,
265        wb: Vec<f32>,
266        conv: Vec<f32>,
267        a_log: Vec<f32>,
268        dt_bias: Vec<f32>,
269        norm: Vec<f32>,
270        wout: Vec<f32>,
271    },
272}
273
274pub(crate) struct FcdLayer {
275    attn: FcdAttn,
276    pub(crate) inter: usize,
277    // Frozen originals: the teacher's LN (small, eager). The big FFN
278    // matrices stream through `LayerMats`.
279    pub(crate) iln: Vec<f32>,
280    pub(crate) pln: Vec<f32>,
281}
282
283/// GDN geometry shared by every linear layer (arch.linear_* fields).
284#[derive(Clone, Copy)]
285struct GdnDims {
286    nv: usize,
287    nk: usize,
288    dk: usize,
289    dv: usize,
290    kk: usize,
291}
292
293impl GdnDims {
294    fn c_dim(&self) -> usize {
295        2 * self.nk * self.dk + self.nv * self.dv
296    }
297    fn vd(&self) -> usize {
298        self.nv * self.dv
299    }
300}
301
302/// The f32 training replica of a .cmf model (≤ 1B targets).
303pub struct FcdModel {
304    pub hidden: usize,
305    pub nh: usize,
306    pub nkv: usize,
307    pub hd: usize,
308    pub nl: usize,
309    pub vocab: usize,
310    pub(crate) eps: f64,
311    pub(crate) gemma: bool,
312    rotary_dim: usize,
313    inv_freq: Vec<f64>,
314    /// [vocab, hidden]; also the tied head when `lm_head` is None.
315    pub(crate) embed: Vec<f32>,
316    pub(crate) lm_head: Option<Vec<f32>>,
317    pub(crate) final_norm: Vec<f32>,
318    pub(crate) layers: Vec<FcdLayer>,
319    /// The container the replica came from — the streaming mats
320    /// dequantize from its mmap on demand.
321    pub(crate) src: std::sync::Arc<CmfModel>,
322    /// Per-layer big-matrix cache: filled on touch, evicted outside the
323    /// window. The f32 replica used to hold every matrix of every layer
324    /// eagerly — 16.7 GB for a 4 B model before the fused concats, ~25
325    /// after — which a 24 GB laptop answered with ten minutes of swap.
326    mats_cache: Vec<std::sync::Mutex<Option<std::sync::Arc<LayerMats>>>>,
327    /// cos/sin table for the device attention chain, keyed by t. Arc so
328    /// the underlying address stays STABLE across calls — the GPU const
329    /// cache dedups uploads by (pointer, fingerprint).
330    rope_tab: std::sync::Mutex<Option<(usize, std::sync::Arc<Vec<f32>>)>>,
331    /// How many layers stay resident (0 = all, big machines).
332    mats_window: usize,
333    /// Which layers run the Nyström kernel in the student forward.
334    o1_flags: Vec<bool>,
335    nys: NysCfg,
336    /// GDN geometry (present when the model has linear layers).
337    gdn: Option<GdnDims>,
338    /// Looped Transformer: how many times the layer stack runs per
339    /// token, and whether a final_norm is inserted at each loop
340    /// boundary. A replica that ignores these computes a DIFFERENT
341    /// model — on Nanbeige 4.2 (22 layers x 2 loops) the single-pass
342    /// forward measured perplexity 4773 where the engine reads 16.5,
343    /// and every gradient taken through it was fitted to that fiction.
344    pub(crate) loops: usize,
345    pub(crate) loop_norm: bool,
346    pub(crate) pool: Option<Arc<Pool>>,
347}
348
349fn deq(model: &CmfModel, name: &str) -> Result<Vec<f32>, String> {
350    let e = model
351        .tensor(name)
352        .ok_or_else(|| format!("tensor '{name}' not found"))?;
353    let mut out = vec![0f32; e.n_elems()];
354    cortiq_core::quant::dequant_tensor(e, model.entry_bytes(e), &mut out)?;
355    Ok(out)
356}
357
358
359
360/// Physical RAM total, for the hard replica ceiling.
361fn physical_total_bytes() -> Option<u64> {
362    #[cfg(target_os = "macos")]
363    {
364        let out = std::process::Command::new("sysctl")
365            .args(["-n", "hw.memsize"])
366            .output()
367            .ok()?;
368        return String::from_utf8_lossy(&out.stdout).trim().parse().ok();
369    }
370    #[cfg(target_os = "linux")]
371    {
372        let mem = std::fs::read_to_string("/proc/meminfo").ok()?;
373        let kb: u64 = mem
374            .lines()
375            .find(|l| l.starts_with("MemTotal:"))?
376            .split_whitespace()
377            .nth(1)?
378            .parse()
379            .ok()?;
380        return Some(kb * 1024);
381    }
382    #[allow(unreachable_code)]
383    None
384}
385
386/// AVAILABLE RAM in bytes, best effort — used only to refuse a bake
387/// whose f32 replica would swap instead of run.
388fn available_ram_bytes() -> Option<u64> {
389    #[cfg(target_os = "macos")]
390    {
391        // free% × total from the same counters the memory-pressure
392        // subsystem uses; hw.memsize alone lied by whatever the other
393        // apps were holding.
394        let total: u64 = {
395            let out = std::process::Command::new("sysctl")
396                .args(["-n", "hw.memsize"])
397                .output()
398                .ok()?;
399            String::from_utf8_lossy(&out.stdout).trim().parse().ok()?
400        };
401        let out = std::process::Command::new("memory_pressure")
402            .arg("-Q")
403            .output()
404            .ok()?;
405        let text = String::from_utf8_lossy(&out.stdout);
406        let pct: u64 = text
407            .lines()
408            .find(|l| l.contains("free percentage"))?
409            .split(':')
410            .nth(1)?
411            .trim()
412            .trim_end_matches('%')
413            .parse()
414            .ok()?;
415        return Some(total / 100 * pct);
416    }
417    #[cfg(target_os = "linux")]
418    {
419        let mem = std::fs::read_to_string("/proc/meminfo").ok()?;
420        let kb: u64 = mem
421            .lines()
422            .find(|l| l.starts_with("MemAvailable:"))?
423            .split_whitespace()
424            .nth(1)?
425            .parse()
426            .ok()?;
427        return Some(kb * 1024);
428    }
429    #[allow(unreachable_code)]
430    None
431}
432
433
434/// `deq` for sibling modules (the bake's Phase-B masters dequant once,
435/// straight from the source container).
436pub(crate) fn deq_pub(model: &CmfModel, name: &str) -> Result<Vec<f32>, String> {
437    deq(model, name)
438}
439
440/// The four big matrices the hot path reads for one layer, dequantized
441/// together: the fused attention projection, the attention output, the
442/// fused FFN gate+up, and the FFN down. Everything else a layer owns —
443/// norms, biases, GDN cores — is small and stays eagerly resident.
444pub(crate) struct LayerMats {
445    pub(crate) wqkv: Vec<f32>,
446    pub(crate) wo: Vec<f32>,
447    pub(crate) gu: Vec<f32>,
448    pub(crate) down: Vec<f32>,
449}
450
451impl FcdModel {
452    /// The layer's big matrices, dequantized on first touch. Sequential
453    /// sweeps (forward 0..nl, backward nl..0) hit the same physical
454    /// layer at most twice per virtual pass, so a small window streams
455    /// a model far bigger than RAM without swapping.
456    pub(crate) fn mats(&self, li: usize) -> Result<std::sync::Arc<LayerMats>, String> {
457        {
458            let slot = self.mats_cache[li].lock().unwrap();
459            if let Some(m) = slot.as_ref() {
460                return Ok(m.clone());
461            }
462        }
463        let p = format!("model.layers.{li}.");
464        let d = |name: String| -> Result<Vec<f32>, String> { deq(&self.src, &name) };
465        let built = if matches!(self.layers[li].attn, FcdAttn::Full { .. }) {
466            let wq = d(format!("{p}self_attn.q_proj.weight"))?;
467            let wk = d(format!("{p}self_attn.k_proj.weight"))?;
468            let wv = d(format!("{p}self_attn.v_proj.weight"))?;
469            let mut wqkv = Vec::with_capacity(wq.len() + wk.len() + wv.len());
470            wqkv.extend_from_slice(&wq);
471            wqkv.extend_from_slice(&wk);
472            wqkv.extend_from_slice(&wv);
473            let gate = d(format!("{p}mlp.gate_proj.weight"))?;
474            let up = d(format!("{p}mlp.up_proj.weight"))?;
475            let mut gu = Vec::with_capacity(gate.len() + up.len());
476            gu.extend_from_slice(&gate);
477            gu.extend_from_slice(&up);
478            LayerMats {
479                wqkv,
480                wo: d(format!("{p}self_attn.o_proj.weight"))?,
481                gu,
482                down: d(format!("{p}mlp.down_proj.weight"))?,
483            }
484        } else {
485            // GDN layers keep their attention core eagerly; only the FFN
486            // streams.
487            let gate = d(format!("{p}mlp.gate_proj.weight"))?;
488            let up = d(format!("{p}mlp.up_proj.weight"))?;
489            let mut gu = Vec::with_capacity(gate.len() + up.len());
490            gu.extend_from_slice(&gate);
491            gu.extend_from_slice(&up);
492            LayerMats {
493                wqkv: Vec::new(),
494                wo: Vec::new(),
495                gu,
496                down: d(format!("{p}mlp.down_proj.weight"))?,
497            }
498        };
499        let arc = std::sync::Arc::new(built);
500        *self.mats_cache[li].lock().unwrap() = Some(arc.clone());
501        // Evict outside the window — cheap, and the access pattern is
502        // sequential, so the evicted slots are exactly the cold ones.
503        if self.mats_window > 0 {
504            let w = self.mats_window;
505            for (j, slot) in self.mats_cache.iter().enumerate() {
506                let dist = li.abs_diff(j).min(self.layers.len() - li.abs_diff(j));
507                if dist > w {
508                    *slot.lock().unwrap() = None;
509                }
510            }
511        }
512        Ok(arc)
513    }
514}
515
516impl FcdModel {
517    /// Dequantize a model into the f32 training replica. Refuses what
518    /// the backward cannot honestly differentiate yet (loud, not silent).
519    pub fn from_cmf(model: &std::sync::Arc<CmfModel>, o1: &O1Cfg) -> Result<Self, String> {
520        let arch = model.arch().clone();
521        if arch.hidden_act != "silu" {
522            return Err(format!(
523                "fcd/skill-bake: hidden_act '{}' not supported yet (SiLU only)",
524                arch.hidden_act
525            ));
526        }
527        let has_linear = arch
528            .layer_types
529            .iter()
530            .any(|t| matches!(t, LayerType::LinearAttention));
531        let gdn = if has_linear {
532            let lc = arch
533                .linear_core
534                .as_ref()
535                .ok_or_else(|| "model has linear layers but no arch.linear_core".to_string())?;
536            if lc.kind != "gated_delta_net" {
537                return Err(format!(
538                    "linear core '{}' has no FCD backward (only gated_delta_net)",
539                    lc.kind
540                ));
541            }
542            Some(GdnDims {
543                nv: lc.num_heads,
544                nk: arch
545                    .linear_num_key_heads
546                    .ok_or("linear core needs arch.linear_num_key_heads")?,
547                dk: arch
548                    .linear_key_head_dim
549                    .ok_or("linear core needs arch.linear_key_head_dim")?,
550                dv: lc.value_head_dim,
551                kk: arch
552                    .linear_conv_kernel_dim
553                    .ok_or("linear core needs arch.linear_conv_kernel_dim")?,
554            })
555        } else {
556            None
557        };
558        let (nh, nkv, hd, h) = (
559            arch.num_attention_heads,
560            arch.num_kv_heads,
561            arch.head_dim,
562            arch.hidden_size,
563        );
564        let embed = deq(model, "model.embed_tokens.weight")?;
565        let lm_head = if model.tensor("lm_head.weight").is_some() {
566            Some(deq(model, "lm_head.weight")?)
567        } else if arch.tie_word_embeddings {
568            None
569        } else {
570            return Err("no lm_head.weight and tie_word_embeddings is false".into());
571        };
572        let final_norm = deq(model, "model.norm.weight")?;
573
574        let mut layers = Vec::with_capacity(arch.num_layers);
575        for li in 0..arch.num_layers {
576            let p = format!("model.layers.{li}.");
577            if model.tensor(&format!("{p}mlp.gate.weight")).is_some() {
578                return Err(format!(
579                    "layer {li} is MoE — FCD polish supports dense FFN only"
580                ));
581            }
582            let attn = match arch.layer_types.get(li) {
583                Some(LayerType::LinearAttention) => {
584                    let la = |n: &str| deq(model, &format!("{p}linear_attn.{n}"));
585                    FcdAttn::Gdn {
586                        wqkv: la("in_proj_qkv.weight")?,
587                        wz: la("in_proj_z.weight")?,
588                        wa: la("in_proj_a.weight")?,
589                        wb: la("in_proj_b.weight")?,
590                        conv: la("conv1d.weight")?,
591                        a_log: la("A_log")?,
592                        dt_bias: la("dt_bias")?,
593                        norm: la("norm.weight")?,
594                        wout: la("out_proj.weight")?,
595                    }
596                }
597                _ => {
598                    let wq = deq(model, &format!("{p}self_attn.q_proj.weight"))?;
599                    let output_gate = wq.len() == 2 * nh * hd * h;
600                    let opt = |n: &str| -> Option<Vec<f32>> {
601                        model
602                            .tensor(&format!("{p}self_attn.{n}"))
603                            .and_then(|_| deq(model, &format!("{p}self_attn.{n}")).ok())
604                    };
605                    let bias = match (opt("q_proj.bias"), opt("k_proj.bias"), opt("v_proj.bias")) {
606                        (Some(a), Some(b), Some(c)) => Some((a, b, c)),
607                        _ => None,
608                    };
609                    let qrows = wq.len() / h;
610                    drop(wq);
611                    let bias_cat = bias.as_ref().map(|(bq, bk, bv)| {
612                        let mut v = Vec::with_capacity(bq.len() + bk.len() + bv.len());
613                        v.extend_from_slice(bq);
614                        v.extend_from_slice(bk);
615                        v.extend_from_slice(bv);
616                        v
617                    });
618                    FcdAttn::Full {
619                        qrows,
620                        q_norm: opt("q_norm.weight"),
621                        k_norm: opt("k_norm.weight"),
622                        bias,
623                        bias_cat,
624                        output_gate,
625                    }
626                }
627            };
628            let gate = deq(model, &format!("{p}mlp.gate_proj.weight"))?;
629            let inter = gate.len() / h;
630            drop(gate);
631            layers.push(FcdLayer {
632                attn,
633                inter,
634                iln: deq(model, &format!("{p}input_layernorm.weight"))?,
635                pln: deq(model, &format!("{p}post_attention_layernorm.weight"))?,
636            });
637        }
638
639        let rotary_dim = ((hd as f32 * arch.partial_rotary_factor) as usize)
640            .max(2)
641            .min(hd);
642        let base = arch.rope_theta;
643        let inv_freq: Vec<f64> = (0..rotary_dim / 2)
644            .map(|i| 1.0 / base.powf(2.0 * i as f64 / rotary_dim as f64))
645            .collect();
646        let loops = arch.num_loops.max(1);
647        let loop_norm = arch.loop_final_norm;
648        let mut flags = o1.layer_flags(arch.num_layers);
649        flags.resize(arch.num_layers, false);
650        // Only full-attention layers are o1-convertible (same rule as
651        // Pipeline::set_o1) — a GDN layer keeps its own operator.
652        for (li, f) in flags.iter_mut().enumerate() {
653            if *f && !matches!(layers[li].attn, FcdAttn::Full { .. }) {
654                *f = false;
655            }
656        }
657        // Streaming window: how many layers' big matrices stay resident.
658        // Sized from available memory; CMF_BAKE_MATS_LAYERS overrides.
659        // 0 = everything resident (big machines keep today's speed).
660        let per_layer: u64 = layers
661            .first()
662            .map(|_| {
663                let qrows = match layers[0].attn {
664                    FcdAttn::Full { qrows, .. } => qrows,
665                    _ => 0,
666                };
667                ((qrows + 2 * (nkv * hd)) as u64 * h as u64      // wqkv
668                    + (h as u64 * nh as u64 * hd as u64)          // wo
669                    + 3 * (layers[0].inter as u64 * h as u64))    // gu + down
670                    * 4
671            })
672            .unwrap_or(0);
673        let mats_window = if let Ok(v) = std::env::var("CMF_BAKE_MATS_LAYERS") {
674            v.parse().unwrap_or(0)
675        } else {
676            let avail = available_ram_bytes().unwrap_or(u64::MAX);
677            let cap = physical_total_bytes()
678                .map(|t| t / 5 * 3)
679                .unwrap_or(u64::MAX)
680                .min(avail.saturating_sub(avail / 10));
681            let all = per_layer.saturating_mul(arch.num_layers as u64);
682            if all + 4 * 1024 * 1024 * 1024 <= cap {
683                0 // everything fits with headroom — stay eager-equivalent
684            } else {
685                let w = (cap.saturating_sub(3 * 1024 * 1024 * 1024) / per_layer.max(1))
686                    .clamp(2, arch.num_layers as u64) as usize;
687                tracing::info!(
688                    "fcd replica: streaming {w} of {} layers (~{:.1} GB resident of ~{:.1} GB total)",
689                    arch.num_layers,
690                    (w as u64 * per_layer) as f64 / 1e9,
691                    all as f64 / 1e9,
692                );
693                w
694            }
695        };
696        let mats_cache = (0..arch.num_layers)
697            .map(|_| std::sync::Mutex::new(None))
698            .collect();
699        Ok(Self {
700            src: model.clone(),
701            mats_cache,
702            rope_tab: std::sync::Mutex::new(None),
703            mats_window,
704            hidden: h,
705            nh,
706            nkv,
707            hd,
708            nl: arch.num_layers,
709            vocab: arch.vocab_size.min(embed.len() / h),
710            eps: arch.rms_norm_eps,
711            gemma: matches!(arch.norm_style, NormStyle::Gemma),
712            rotary_dim,
713            inv_freq,
714            embed,
715            lm_head,
716            final_norm,
717            layers,
718            o1_flags: flags,
719            // prefill: None = half the window, the same seal point
720            // `cortiq ppl --o1` defaults to (see NysCfg::prefill).
721            nys: NysCfg {
722                m: o1.m,
723                w: o1.w,
724                sink: o1.sink,
725                prefill: None,
726            },
727            gdn,
728            loops,
729            loop_norm,
730            pool: Pool::from_env(),
731        })
732    }
733
734    /// Converted (trainable) layer indices.
735    pub fn converted(&self) -> Vec<usize> {
736        (0..self.nl).filter(|&i| self.o1_flags[i]).collect()
737    }
738
739    fn head_weight(&self) -> &[f32] {
740        self.lm_head.as_deref().unwrap_or(&self.embed)
741    }
742}
743
744// ───────────────────────── trainable state ─────────────────────────
745
746/// Per converted layer, in this fixed order.
747const PARAMS_PER_LAYER: usize = 5; // iln, pln, gate, up, down
748
749/// Master copies + grads + AdamW moments of the trainable tensors.
750pub struct TrainState {
751    pub layers: Vec<usize>,
752    /// layers.len()·5 tensors, layer-major, [iln, pln, gate, up, down].
753    pub data: Vec<Vec<f32>>,
754    grad: Vec<Vec<f32>>,
755    m1: Vec<Vec<f32>>,
756    m2: Vec<Vec<f32>>,
757    step_t: u64,
758}
759
760impl TrainState {
761    pub fn new(fm: &FcdModel) -> Self {
762        let layers = fm.converted();
763        let mut data = Vec::with_capacity(layers.len() * PARAMS_PER_LAYER);
764        for &li in &layers {
765            let l = &fm.layers[li];
766            let p = format!("model.layers.{li}.");
767            data.push(l.iln.clone());
768            data.push(l.pln.clone());
769            // Trained masters dequant once, straight from the source —
770            // the streamed cache holds only the fused hot-path concats.
771            data.push(deq(&fm.src, &format!("{p}mlp.gate_proj.weight")).expect("gate"));
772            data.push(deq(&fm.src, &format!("{p}mlp.up_proj.weight")).expect("up"));
773            data.push(deq(&fm.src, &format!("{p}mlp.down_proj.weight")).expect("down"));
774        }
775        let zeros: Vec<Vec<f32>> = data.iter().map(|d| vec![0f32; d.len()]).collect();
776        Self {
777            layers,
778            grad: zeros.clone(),
779            m1: zeros.clone(),
780            m2: zeros,
781            data,
782            step_t: 0,
783        }
784    }
785
786    fn slot(&self, li: usize) -> Option<usize> {
787        self.layers.iter().position(|&x| x == li)
788    }
789
790    /// Read access to the accumulated gradients (gradcheck harness).
791    #[doc(hidden)]
792    pub fn grads(&self) -> &[Vec<f32>] {
793        &self.grad
794    }
795
796    fn zero_grad(&mut self) {
797        for g in &mut self.grad {
798            for v in g.iter_mut() {
799                *v = 0.0;
800            }
801        }
802    }
803
804    /// Global-norm clip (1.0) + one AdamW step (torch defaults,
805    /// decoupled weight decay).
806    fn clip_and_step(&mut self, lr: f64) -> f64 {
807        let mut sq = 0f64;
808        for g in &self.grad {
809            for &v in g {
810                sq += (v as f64) * (v as f64);
811            }
812        }
813        let gn = sq.sqrt();
814        let scale = if gn > 1.0 { 1.0 / (gn + 1e-6) } else { 1.0 };
815        self.step_t += 1;
816        let bc1 = 1.0 - ADAM_B1.powi(self.step_t as i32);
817        let bc2 = 1.0 - ADAM_B2.powi(self.step_t as i32);
818        for p in 0..self.data.len() {
819            let (d, g, m, v) = (
820                &mut self.data[p],
821                &self.grad[p],
822                &mut self.m1[p],
823                &mut self.m2[p],
824            );
825            for i in 0..d.len() {
826                let gi = g[i] as f64 * scale;
827                let mi = ADAM_B1 * m[i] as f64 + (1.0 - ADAM_B1) * gi;
828                let vi = ADAM_B2 * v[i] as f64 + (1.0 - ADAM_B2) * gi * gi;
829                m[i] = mi as f32;
830                v[i] = vi as f32;
831                let upd = (mi / bc1) / ((vi / bc2).sqrt() + ADAM_EPS) + ADAM_WD * d[i] as f64;
832                d[i] = (d[i] as f64 - lr * upd) as f32;
833            }
834        }
835        gn
836    }
837}
838
839/// LN/FFN weight view of one layer — frozen originals for the teacher
840/// (and non-converted student layers), master copies for trainables.
841#[derive(Clone, Copy)]
842pub(crate) struct LnFfn<'a> {
843    pub(crate) iln: &'a [f32],
844    pub(crate) pln: &'a [f32],
845    pub(crate) gate: &'a [f32],
846    pub(crate) up: &'a [f32],
847    pub(crate) down: &'a [f32],
848    /// `[gate; up]` rows concatenated — one GEMM submit instead of two.
849    /// `None` for Phase-B trained copies, whose rows move every step;
850    /// the frozen majority carries the concat prebuilt at load.
851    pub(crate) gu: Option<&'a [f32]>,
852}
853
854fn ln_ffn<'a>(fm: &'a FcdModel, ts: Option<&'a TrainState>, li: usize, mats: &'a LayerMats) -> LnFfn<'a> {
855    if let Some(t) = ts {
856        if let Some(s) = t.slot(li) {
857            let b = s * PARAMS_PER_LAYER;
858            return LnFfn {
859                iln: &t.data[b],
860                pln: &t.data[b + 1],
861                gate: &t.data[b + 2],
862                up: &t.data[b + 3],
863                down: &t.data[b + 4],
864                gu: None,
865            };
866        }
867    }
868    let l = &fm.layers[li];
869    LnFfn {
870        iln: &l.iln,
871        pln: &l.pln,
872        // The fused concat carries both projections; the fallback slots
873        // are never read while `gu` is Some.
874        gate: &[],
875        up: &[],
876        down: &mats.down,
877        gu: Some(&mats.gu),
878    }
879}
880
881// ───────────────────── layer forward (+ recompute) ─────────────────────
882
883/// Intra-layer activations rebuilt during the checkpointed backward.
884enum AttnActs {
885    Full {
886        qpre: Vec<f32>,
887        kpre: Vec<f32>,
888        vproj: Vec<f32>,
889        qrot: Vec<f32>,
890        krot: Vec<f32>,
891        qinv: Vec<f32>,
892        kinv: Vec<f32>,
893        /// Pre-gate per-head attention outputs (needed for the output
894        /// gate's backward); always kept — transient per layer.
895        ao: Vec<f32>,
896        /// Raw gate half of q_proj (empty without an output gate).
897        gate_pre: Vec<f32>,
898    },
899    /// Raw projection streams — the GDN backward replays conv + the
900    /// recurrence from these.
901    Gdn {
902        qkv: Vec<f32>,
903        z: Vec<f32>,
904        a: Vec<f32>,
905        b: Vec<f32>,
906    },
907}
908
909pub(crate) struct LayerActs {
910    inv1: Vec<f32>,
911    attn: AttnActs,
912    pub(crate) h1: Vec<f32>,
913    pub(crate) n2: Vec<f32>,
914    pub(crate) inv2: Vec<f32>,
915    pub(crate) gpre: Vec<f32>,
916    pub(crate) upre: Vec<f32>,
917    pub(crate) act: Vec<f32>,
918}
919
920/// Disjoint-write pointer for pooled per-head scatter (pipeline pattern).
921struct SendMut<T>(*mut T);
922unsafe impl<T> Send for SendMut<T> {}
923unsafe impl<T> Sync for SendMut<T> {}
924impl<T> SendMut<T> {
925    #[inline]
926    unsafe fn at(&self, i: usize) -> *mut T {
927        unsafe { self.0.add(i) }
928    }
929}
930
931impl FcdModel {
932    /// Per-head RMS-norm (qk-norm) + partial RoPE for all rows of a
933    /// projection buffer. `heads` per row, `x` is `[n, heads·hd]`.
934    /// Saves the per-(row, head) rms inv when a norm gain is present.
935    fn qk_norm_rope(
936        &self,
937        x: &mut [f32],
938        norm: Option<&[f32]>,
939        heads: usize,
940        t: usize,
941        inv_out: &mut [f32],
942    ) {
943        let hd = self.hd;
944        let n = x.len() / (heads * hd);
945        for r in 0..n {
946            let pos = r % t;
947            for hh in 0..heads {
948                let s = (r * heads + hh) * hd;
949                let head = &mut x[s..s + hd];
950                if let Some(w) = norm {
951                    let mut inv = [0f32; 1];
952                    let mut y = [0f32; 256];
953                    debug_assert!(hd <= 256);
954                    ops::rmsnorm_fwd(head, w, self.eps, self.gemma, &mut y[..hd], &mut inv);
955                    head.copy_from_slice(&y[..hd]);
956                    inv_out[r * heads + hh] = inv[0];
957                }
958                ops::rope_fwd(&mut head[..self.rotary_dim], pos, &self.inv_freq);
959            }
960        }
961    }
962
963    /// One layer forward over `b` sequences of length `t` (rows are
964    /// b-major). `nystrom` switches converted (Full) student layers to
965    /// the certified matrix kernel (f64 per head); exact heads run in
966    /// f32; GDN layers run the frozen BPTT-capable operator. Returns
967    /// (h_out, intra-layer activations when `want_acts`).
968    #[allow(clippy::too_many_arguments)]
969    fn layer_forward(
970        &self,
971        li: usize,
972        h_in: &[f32],
973        b: usize,
974        t: usize,
975        wts: &LnFfn,
976        nystrom: bool,
977        want_acts: bool,
978    ) -> (Vec<f32>, Option<LayerActs>) {
979        self.layer_forward_scaled(li, h_in, b, t, wts, nystrom, want_acts, None)
980    }
981
982    /// `layer_forward` with an optional per-neuron FFN activation scale
983    /// (the DTG-MA mask σ(m), Patent 2): `act·scale` feeds down_proj.
984    /// `LayerActs.act` stays PRE-scale so the mask backward can read it.
985    #[allow(clippy::too_many_arguments)]
986    pub(crate) fn layer_forward_scaled(
987        &self,
988        li: usize,
989        h_in: &[f32],
990        b: usize,
991        t: usize,
992        wts: &LnFfn,
993        nystrom: bool,
994        want_acts: bool,
995        ffn_scale: Option<&[f32]>,
996    ) -> (Vec<f32>, Option<LayerActs>) {
997        let hsz = self.hidden;
998        let n = b * t;
999        let l = &self.layers[li];
1000        let pool = self.pool.as_deref();
1001
1002        let mut n1 = vec![0f32; n * hsz];
1003        let mut inv1 = vec![0f32; n];
1004        ops::rmsnorm_fwd(h_in, wts.iln, self.eps, self.gemma, &mut n1, &mut inv1);
1005
1006        let mats = self.mats(li).expect("layer mats");
1007        let t_attn = std::time::Instant::now();
1008        let (attn_out, attn_acts) = match &l.attn {
1009            FcdAttn::Full { .. } => self.full_attn_fwd(&l.attn, &mats, &n1, b, t, nystrom),
1010            FcdAttn::Gdn { .. } => self.gdn_attn_fwd(&l.attn, &n1, b, t),
1011        };
1012        prof::add(&prof::ATTN_FWD, t_attn);
1013        let t_ffn = std::time::Instant::now();
1014
1015        let mut h1 = h_in.to_vec();
1016        for (a, &x) in h1.iter_mut().zip(&attn_out) {
1017            *a += x;
1018        }
1019
1020        let mut n2 = vec![0f32; n * hsz];
1021        let mut inv2 = vec![0f32; n];
1022        ops::rmsnorm_fwd(&h1, wts.pln, self.eps, self.gemma, &mut n2, &mut inv2);
1023
1024        let inter = l.inter;
1025        let mut gpre = vec![0f32; n * inter];
1026        let mut upre = vec![0f32; n * inter];
1027        let mut act = vec![0f32; n * inter];
1028        let mut ffn = vec![0f32; n * hsz];
1029        // The frozen fused-gu FFN rides the whole chain on the device when
1030        // the tensor-core arm is up: one submit, and the gate+up plane
1031        // only crosses PCIe when the backward pass will need it. An eval
1032        // call moves three matrices and reads back one.
1033        let mut fused = false;
1034        #[cfg(feature = "gpu")]
1035        if let Some(gu) = wts.gu {
1036            if crate::gpu::enabled_here() {
1037                let mut both = want_acts.then(|| vec![0f32; n * 2 * inter]);
1038                if crate::gpu_wgpu::ffn_chain_f32(
1039                    &n2,
1040                    gu,
1041                    wts.down,
1042                    ffn_scale,
1043                    both.as_deref_mut(),
1044                    want_acts.then_some(li),
1045                    &mut ffn,
1046                    n,
1047                    hsz,
1048                    inter,
1049                ) {
1050                    fused = true;
1051                    if let Some(b) = &both {
1052                        for r in 0..n {
1053                            let row = &b[r * 2 * inter..(r + 1) * 2 * inter];
1054                            gpre[r * inter..(r + 1) * inter].copy_from_slice(&row[..inter]);
1055                            upre[r * inter..(r + 1) * inter].copy_from_slice(&row[inter..]);
1056                        }
1057                        // PRE-scale, as the mask backward expects.
1058                        for i in 0..n * inter {
1059                            act[i] = ops::silu(gpre[i]) * upre[i];
1060                        }
1061                    }
1062                }
1063            }
1064        }
1065        if !fused {
1066            if let Some(gu) = wts.gu {
1067                // One submit; split back so everything downstream is
1068                // byte-identical to the two-call path.
1069                let mut both = vec![0f32; n * 2 * inter];
1070                ops::gemm_nt(&n2, gu, &mut both, n, hsz, 2 * inter, pool);
1071                for r in 0..n {
1072                    let row = &both[r * 2 * inter..(r + 1) * 2 * inter];
1073                    gpre[r * inter..(r + 1) * inter].copy_from_slice(&row[..inter]);
1074                    upre[r * inter..(r + 1) * inter].copy_from_slice(&row[inter..]);
1075                }
1076            } else {
1077                ops::gemm_nt(&n2, wts.gate, &mut gpre, n, hsz, inter, pool);
1078                ops::gemm_nt(&n2, wts.up, &mut upre, n, hsz, inter, pool);
1079            }
1080            for i in 0..n * inter {
1081                act[i] = ops::silu(gpre[i]) * upre[i];
1082            }
1083            match ffn_scale {
1084                Some(g) => {
1085                    debug_assert_eq!(g.len(), inter);
1086                    let mut act2 = act.clone();
1087                    for r in 0..n {
1088                        for (a, &gv) in act2[r * inter..(r + 1) * inter].iter_mut().zip(g) {
1089                            *a *= gv;
1090                        }
1091                    }
1092                    ops::gemm_nt(&act2, wts.down, &mut ffn, n, inter, hsz, pool);
1093                }
1094                None => ops::gemm_nt(&act, wts.down, &mut ffn, n, inter, hsz, pool),
1095            }
1096        }
1097        let mut h2 = h1.clone();
1098        for (a, &x) in h2.iter_mut().zip(&ffn) {
1099            *a += x;
1100        }
1101
1102        let acts = want_acts.then_some(LayerActs {
1103            inv1,
1104            attn: attn_acts,
1105            h1,
1106            n2,
1107            inv2,
1108            gpre,
1109            upre,
1110            act,
1111        });
1112        prof::add(&prof::FFN_FWD, t_ffn);
1113        (h2, acts)
1114    }
1115
1116    /// Full-attention forward: projections (+optional biases), optional
1117    /// per-head [q; gate] split (Qwen3.5 output gate), qk-norm + RoPE,
1118    /// per-head exact-or-Nyström attention, σ(gate) multiply, o_proj.
1119    fn full_attn_fwd(
1120        &self,
1121        attn: &FcdAttn,
1122        mats: &LayerMats,
1123        n1: &[f32],
1124        b: usize,
1125        t: usize,
1126        nystrom: bool,
1127    ) -> (Vec<f32>, AttnActs) {
1128        let (wqkv, wo) = (&mats.wqkv[..], &mats.wo[..]);
1129        let FcdAttn::Full {
1130            qrows: _,
1131            q_norm,
1132            k_norm,
1133            bias,
1134            bias_cat,
1135            output_gate,
1136        } = attn
1137        else {
1138            unreachable!("full_attn_fwd on a non-Full layer");
1139        };
1140        let (hsz, nh, nkv, hd) = (self.hidden, self.nh, self.nkv, self.hd);
1141        let n = b * t;
1142        let pool = self.pool.as_deref();
1143        let qdim = nh * hd;
1144        let kvdim = nkv * hd;
1145        let rep = nh / nkv;
1146        let qrows = if *output_gate { 2 * qdim } else { qdim };
1147
1148        let fused = qrows + 2 * kvdim;
1149        // ── device chain: the whole attention forward in one submit ──
1150        // Declines in strict-f32 mode, on Nyström layers (their kernel is
1151        // certified f64 and stays host), and wherever a shape steps
1152        // outside the kernels; the host path below is the fallback and
1153        // the reference.
1154        #[cfg(feature = "gpu")]
1155        if !nystrom && crate::gpu::enabled_here() {
1156            let want_acts = true; // the caller always builds acts today
1157            let rope = {
1158                let mut rt = self.rope_tab.lock().unwrap();
1159                match rt.as_ref() {
1160                    Some((tt, arc)) if *tt == t => arc.clone(),
1161                    _ => {
1162                        let half = self.rotary_dim / 2;
1163                        let mut tab = Vec::with_capacity(t * half * 2);
1164                        for pos in 0..t {
1165                            for (_i, &freq) in self.inv_freq.iter().enumerate() {
1166                                let a = pos as f64 * freq;
1167                                tab.push(a.cos() as f32);
1168                                tab.push(a.sin() as f32);
1169                            }
1170                        }
1171                        let arc = std::sync::Arc::new(tab);
1172                        *rt = Some((t, arc.clone()));
1173                        arc
1174                    }
1175                }
1176            };
1177            let cfg = crate::gpu_wgpu::AttnChainCfg {
1178                wqkv,
1179                wo,
1180                q_norm: q_norm.as_deref(),
1181                k_norm: k_norm.as_deref(),
1182                bias: bias_cat.as_deref(),
1183                output_gate: *output_gate,
1184                gemma: self.gemma,
1185                eps: self.eps as f32,
1186                rotary_half: self.rotary_dim / 2,
1187                rope: &rope,
1188                b,
1189                t,
1190                nh,
1191                nkv,
1192                hd,
1193                hsz: self.hidden,
1194            };
1195            let mut attn_out = vec![0f32; n * self.hidden];
1196            if let Some(ch) = crate::gpu_wgpu::attn_chain_f32(n1, &cfg, &mut attn_out, want_acts)
1197            {
1198                // Rebuild the host-visible acts from the raw plane, with
1199                // exactly the host split's bias/gate arithmetic.
1200                let mut qraw = vec![0f32; n * qrows];
1201                let mut kpre = vec![0f32; n * kvdim];
1202                let mut vproj = vec![0f32; n * kvdim];
1203                for r in 0..n {
1204                    let row = &ch.qkv_plane[r * fused..(r + 1) * fused];
1205                    qraw[r * qrows..(r + 1) * qrows].copy_from_slice(&row[..qrows]);
1206                    kpre[r * kvdim..(r + 1) * kvdim]
1207                        .copy_from_slice(&row[qrows..qrows + kvdim]);
1208                    vproj[r * kvdim..(r + 1) * kvdim].copy_from_slice(&row[qrows + kvdim..]);
1209                }
1210                if let Some((bq, bk, bv)) = bias {
1211                    for r in 0..n {
1212                        for (x, bb) in qraw[r * qrows..(r + 1) * qrows].iter_mut().zip(bq) {
1213                            *x += bb;
1214                        }
1215                        for (x, bb) in kpre[r * kvdim..(r + 1) * kvdim].iter_mut().zip(bk) {
1216                            *x += bb;
1217                        }
1218                        for (x, bb) in vproj[r * kvdim..(r + 1) * kvdim].iter_mut().zip(bv) {
1219                            *x += bb;
1220                        }
1221                    }
1222                }
1223                let (qpre, gate_pre) = if *output_gate {
1224                    let mut qh = vec![0f32; n * qdim];
1225                    let mut gp = vec![0f32; n * qdim];
1226                    for r in 0..n {
1227                        for h in 0..nh {
1228                            let src = r * qrows + 2 * h * hd;
1229                            let dst = r * qdim + h * hd;
1230                            qh[dst..dst + hd].copy_from_slice(&qraw[src..src + hd]);
1231                            gp[dst..dst + hd].copy_from_slice(&qraw[src + hd..src + 2 * hd]);
1232                        }
1233                    }
1234                    (qh, gp)
1235                } else {
1236                    (qraw, Vec::new())
1237                };
1238                return (
1239                    attn_out,
1240                    AttnActs::Full {
1241                        qpre,
1242                        kpre,
1243                        vproj,
1244                        qrot: ch.qrot,
1245                        krot: ch.krot,
1246                        qinv: ch.qinv,
1247                        kinv: ch.kinv,
1248                        ao: ch.ao,
1249                        gate_pre,
1250                    },
1251                );
1252            }
1253        }
1254
1255        // One fused submit; the split back into three buffers is a
1256        // memcpy that costs microseconds and keeps everything below
1257        // this line byte-identical to the unfused path.
1258        let mut qkv = vec![0f32; n * fused];
1259        ops::gemm_nt(n1, wqkv, &mut qkv, n, hsz, fused, pool);
1260        let mut qraw = vec![0f32; n * qrows];
1261        let mut kpre = vec![0f32; n * kvdim];
1262        let mut vproj = vec![0f32; n * kvdim];
1263        for r in 0..n {
1264            let row = &qkv[r * fused..(r + 1) * fused];
1265            qraw[r * qrows..(r + 1) * qrows].copy_from_slice(&row[..qrows]);
1266            kpre[r * kvdim..(r + 1) * kvdim].copy_from_slice(&row[qrows..qrows + kvdim]);
1267            vproj[r * kvdim..(r + 1) * kvdim].copy_from_slice(&row[qrows + kvdim..]);
1268        }
1269        if let Some((bq, bk, bv)) = bias {
1270            for r in 0..n {
1271                for (x, bb) in qraw[r * qrows..(r + 1) * qrows].iter_mut().zip(bq) {
1272                    *x += bb;
1273                }
1274                for (x, bb) in kpre[r * kvdim..(r + 1) * kvdim].iter_mut().zip(bk) {
1275                    *x += bb;
1276                }
1277                for (x, bb) in vproj[r * kvdim..(r + 1) * kvdim].iter_mut().zip(bv) {
1278                    *x += bb;
1279                }
1280            }
1281        }
1282        // Gate split: per-head [q(hd); gate(hd)] (runtime convention).
1283        let (qpre, gate_pre) = if *output_gate {
1284            let mut qh = vec![0f32; n * qdim];
1285            let mut gp = vec![0f32; n * qdim];
1286            for r in 0..n {
1287                for h in 0..nh {
1288                    let src = r * qrows + 2 * h * hd;
1289                    let dst = r * qdim + h * hd;
1290                    qh[dst..dst + hd].copy_from_slice(&qraw[src..src + hd]);
1291                    gp[dst..dst + hd].copy_from_slice(&qraw[src + hd..src + 2 * hd]);
1292                }
1293            }
1294            (qh, gp)
1295        } else {
1296            (qraw, Vec::new())
1297        };
1298
1299        let mut qrot = qpre.clone();
1300        let mut krot = kpre.clone();
1301        let mut qinv = vec![0f32; n * nh];
1302        let mut kinv = vec![0f32; n * nkv];
1303        self.qk_norm_rope(&mut qrot, q_norm.as_deref(), nh, t, &mut qinv);
1304        self.qk_norm_rope(&mut krot, k_norm.as_deref(), nkv, t, &mut kinv);
1305
1306        // ── attention heads: parallel over (sequence, head) ──
1307        let mut ao = vec![0f32; n * qdim];
1308        {
1309            let units = b * nh;
1310            let aop = SendMut(ao.as_mut_ptr());
1311            let qr = &qrot;
1312            let kr = &krot;
1313            let vr = &vproj;
1314            let nys = self.nys;
1315            let run_unit = |u: usize| {
1316                let (bi, h) = (u / nh, u % nh);
1317                let g = h / rep;
1318                if nystrom {
1319                    // Certified matrix kernel in f64 (docs/RUST_FCD.md §2.2).
1320                    let mut q64 = vec![0f64; t * hd];
1321                    let mut k64 = vec![0f64; t * hd];
1322                    let mut v64 = vec![0f64; t * hd];
1323                    for p in 0..t {
1324                        let r = bi * t + p;
1325                        for c in 0..hd {
1326                            q64[p * hd + c] = qr[r * qdim + h * hd + c] as f64;
1327                            k64[p * hd + c] = kr[r * kvdim + g * hd + c] as f64;
1328                            v64[p * hd + c] = vr[r * kvdim + g * hd + c] as f64;
1329                        }
1330                    }
1331                    let mut o64 = vec![0f64; t * hd];
1332                    ops::nystrom_head_fwd(&q64, &k64, &v64, t, hd, hd, &nys, &mut o64);
1333                    for p in 0..t {
1334                        let r = bi * t + p;
1335                        for c in 0..hd {
1336                            // SAFETY: (row, head) slices are disjoint per unit.
1337                            unsafe {
1338                                *aop.at(r * qdim + h * hd + c) = o64[p * hd + c] as f32;
1339                            }
1340                        }
1341                    }
1342                } else {
1343                    let mut q32 = vec![0f32; t * hd];
1344                    let mut k32 = vec![0f32; t * hd];
1345                    let mut v32 = vec![0f32; t * hd];
1346                    for p in 0..t {
1347                        let r = bi * t + p;
1348                        q32[p * hd..(p + 1) * hd]
1349                            .copy_from_slice(&qr[r * qdim + h * hd..r * qdim + (h + 1) * hd]);
1350                        k32[p * hd..(p + 1) * hd]
1351                            .copy_from_slice(&kr[r * kvdim + g * hd..r * kvdim + (g + 1) * hd]);
1352                        v32[p * hd..(p + 1) * hd]
1353                            .copy_from_slice(&vr[r * kvdim + g * hd..r * kvdim + (g + 1) * hd]);
1354                    }
1355                    let mut o32 = vec![0f32; t * hd];
1356                    ops::attn_head_fwd(&q32, &k32, &v32, t, hd, hd, &mut o32);
1357                    for p in 0..t {
1358                        let r = bi * t + p;
1359                        for c in 0..hd {
1360                            // SAFETY: disjoint (row, head) slices per unit.
1361                            unsafe {
1362                                *aop.at(r * qdim + h * hd + c) = o32[p * hd + c];
1363                            }
1364                        }
1365                    }
1366                }
1367            };
1368            match pool {
1369                Some(p) if units > 1 => p.run(&|widx, nw| {
1370                    for u in (widx..units).step_by(nw) {
1371                        run_unit(u);
1372                    }
1373                }),
1374                _ => {
1375                    for u in 0..units {
1376                        run_unit(u);
1377                    }
1378                }
1379            }
1380        }
1381
1382        // Output gate: multiply the head outputs by σ(gate) before o_proj.
1383        let ao_eff: Vec<f32> = if *output_gate {
1384            ao.iter()
1385                .zip(&gate_pre)
1386                .map(|(&a, &g)| a * (1.0 / (1.0 + (-g).exp())))
1387                .collect()
1388        } else {
1389            ao.clone()
1390        };
1391        let mut attn_out = vec![0f32; n * hsz];
1392        ops::gemm_nt(&ao_eff, wo, &mut attn_out, n, qdim, hsz, pool);
1393        (
1394            attn_out,
1395            AttnActs::Full {
1396                qpre,
1397                kpre,
1398                vproj,
1399                qrot,
1400                krot,
1401                qinv,
1402                kinv,
1403                ao,
1404                gate_pre,
1405            },
1406        )
1407    }
1408
1409    /// GDN forward (frozen operator, teacher AND student): batched
1410    /// projections → f64 conv+SiLU per sequence → pooled per-(seq,
1411    /// k-head) delta-rule recurrence → out_proj. Matches the runtime
1412    /// `gdn_forward` (parity-tested in fcd_gradcheck).
1413    fn gdn_attn_fwd(&self, attn: &FcdAttn, n1: &[f32], b: usize, t: usize) -> (Vec<f32>, AttnActs) {
1414        let FcdAttn::Gdn {
1415            wqkv,
1416            wz,
1417            wa,
1418            wb,
1419            conv,
1420            a_log,
1421            dt_bias,
1422            norm,
1423            wout,
1424        } = attn
1425        else {
1426            unreachable!("gdn_attn_fwd on a non-GDN layer");
1427        };
1428        let d = self.gdn.expect("gdn layer without gdn dims");
1429        let (hsz, n) = (self.hidden, b * t);
1430        let pool = self.pool.as_deref();
1431        let (c_dim, vd, nv) = (d.c_dim(), d.vd(), d.nv);
1432
1433        let mut qkv = vec![0f32; n * c_dim];
1434        ops::gemm_nt(n1, wqkv, &mut qkv, n, hsz, c_dim, pool);
1435        let mut z = vec![0f32; n * vd];
1436        ops::gemm_nt(n1, wz, &mut z, n, hsz, vd, pool);
1437        let mut a = vec![0f32; n * nv];
1438        ops::gemm_nt(n1, wa, &mut a, n, hsz, nv, pool);
1439        let mut bstr = vec![0f32; n * nv];
1440        ops::gemm_nt(n1, wb, &mut bstr, n, hsz, nv, pool);
1441
1442        let cfg = ops::GdnSeqCfg {
1443            nv: d.nv,
1444            nk: d.nk,
1445            dk: d.dk,
1446            dv: d.dv,
1447            kk: d.kk,
1448            rms_eps: self.eps,
1449            conv,
1450            a_log,
1451            dt_bias,
1452            norm,
1453        };
1454        // f64 streams (runtime-precision recurrence) + per-seq conv.
1455        let qkv64: Vec<f64> = qkv.iter().map(|&v| v as f64).collect();
1456        let z64: Vec<f64> = z.iter().map(|&v| v as f64).collect();
1457        let a64: Vec<f64> = a.iter().map(|&v| v as f64).collect();
1458        let b64: Vec<f64> = bstr.iter().map(|&v| v as f64).collect();
1459        let mut pre64 = vec![0f64; n * c_dim];
1460        let mut cq64 = vec![0f64; n * c_dim];
1461        for bi in 0..b {
1462            let r = bi * t * c_dim..(bi + 1) * t * c_dim;
1463            ops::gdn_conv_fwd(
1464                &qkv64[r.clone()],
1465                t,
1466                c_dim,
1467                d.kk,
1468                conv,
1469                &mut pre64[r.clone()],
1470                &mut cq64[r],
1471            );
1472        }
1473        let mut of = vec![0f32; n * vd];
1474        {
1475            let units = b * d.nk;
1476            let rep_v = d.nv / d.nk;
1477            let ofp = SendMut(of.as_mut_ptr());
1478            let (cqr, zr, ar, br) = (&cq64, &z64, &a64, &b64);
1479            let cfg_ref = &cfg;
1480            let run_unit = |u: usize| {
1481                let (bi, ko) = (u / d.nk, u % d.nk);
1482                let mut local = vec![0f64; t * vd];
1483                ops::gdn_group_fwd(
1484                    &cqr[bi * t * c_dim..(bi + 1) * t * c_dim],
1485                    &zr[bi * t * vd..(bi + 1) * t * vd],
1486                    &ar[bi * t * nv..(bi + 1) * t * nv],
1487                    &br[bi * t * nv..(bi + 1) * t * nv],
1488                    t,
1489                    cfg_ref,
1490                    ko,
1491                    &mut local,
1492                );
1493                for hh in 0..rep_v {
1494                    let h = ko * rep_v + hh;
1495                    for p in 0..t {
1496                        for dj in 0..d.dv {
1497                            // SAFETY: v-head columns are exclusive per unit.
1498                            unsafe {
1499                                *ofp.at((bi * t + p) * vd + h * d.dv + dj) =
1500                                    local[p * vd + h * d.dv + dj] as f32;
1501                            }
1502                        }
1503                    }
1504                }
1505            };
1506            match pool {
1507                Some(p) if units > 1 => p.run(&|widx, nw| {
1508                    for u in (widx..units).step_by(nw) {
1509                        run_unit(u);
1510                    }
1511                }),
1512                _ => {
1513                    for u in 0..units {
1514                        run_unit(u);
1515                    }
1516                }
1517            }
1518        }
1519        let mut attn_out = vec![0f32; n * hsz];
1520        ops::gemm_nt(&of, wout, &mut attn_out, n, vd, hsz, pool);
1521        (attn_out, AttnActs::Gdn { qkv, z, a, b: bstr })
1522    }
1523
1524    /// One layer backward (docs/RUST_FCD.md §2.3 chain), given the
1525    /// recomputed `acts`. Accumulates trainable grads when `grads` is
1526    /// Some; always produces the through-grad dh_in.
1527    #[allow(clippy::too_many_arguments)]
1528    fn layer_backward(
1529        &self,
1530        li: usize,
1531        h_in: &[f32],
1532        b: usize,
1533        t: usize,
1534        wts: &LnFfn,
1535        nystrom: bool,
1536        acts: &LayerActs,
1537        dh2: &[f32],
1538        mut grads: Option<&mut [Vec<f32>]>,
1539    ) -> Vec<f32> {
1540        let hsz = self.hidden;
1541        let n = b * t;
1542        let l = &self.layers[li];
1543        let pool = self.pool.as_deref();
1544        let inter = l.inter;
1545
1546        // ── FFN backward ──
1547        let mut dn2 = vec![0f32; n * hsz];
1548        // A frozen layer (no weight grads wanted) rides the device chain
1549        // fed by the plane its forward parked: only dh2 goes down and dn2
1550        // comes back, where the host path uploads the 80 MB dgu concat.
1551        let mut bwd_fused = false;
1552        #[cfg(feature = "gpu")]
1553        if grads.is_none() {
1554            if let Some(gu) = wts.gu {
1555                if crate::gpu::enabled_here()
1556                    && crate::gpu_wgpu::ffn_bwd_chain_f32(
1557                        dh2, wts.down, gu, li, &mut dn2, n, hsz, inter,
1558                    )
1559                {
1560                    bwd_fused = true;
1561                }
1562            }
1563        }
1564        if !bwd_fused {
1565            let mut dact = vec![0f32; n * inter];
1566            ops::gemm_dx(dh2, wts.down, &mut dact, n, inter, hsz, pool);
1567            if let Some(g) = grads.as_deref_mut() {
1568                ops::gemm_dw(dh2, &acts.act, &mut g[4], n, inter, hsz, pool);
1569            }
1570            let mut dg = vec![0f32; n * inter];
1571            let mut du = vec![0f32; n * inter];
1572            for i in 0..n * inter {
1573                dg[i] = dact[i] * acts.upre[i] * ops::silu_bwd(acts.gpre[i]);
1574                du[i] = dact[i] * ops::silu(acts.gpre[i]);
1575            }
1576            // Fused when the frozen concat exists (its gate/up slots are
1577            // empty by design); trained masters keep the two-call path.
1578            if let Some(gu) = wts.gu {
1579                let mut dgu = vec![0f32; n * 2 * inter];
1580                for r in 0..n {
1581                    let row = &mut dgu[r * 2 * inter..(r + 1) * 2 * inter];
1582                    row[..inter].copy_from_slice(&dg[r * inter..(r + 1) * inter]);
1583                    row[inter..].copy_from_slice(&du[r * inter..(r + 1) * inter]);
1584                }
1585                ops::gemm_dx(&dgu, gu, &mut dn2, n, hsz, 2 * inter, pool);
1586            } else {
1587                ops::gemm_dx(&dg, wts.gate, &mut dn2, n, hsz, inter, pool);
1588                ops::gemm_dx(&du, wts.up, &mut dn2, n, hsz, inter, pool);
1589            }
1590            if let Some(g) = grads.as_deref_mut() {
1591                ops::gemm_dw(&dg, &acts.n2, &mut g[2], n, hsz, inter, pool);
1592                ops::gemm_dw(&du, &acts.n2, &mut g[3], n, hsz, inter, pool);
1593            }
1594        }
1595
1596        let mut dh1 = dh2.to_vec();
1597        ops::rmsnorm_bwd(
1598            &acts.h1,
1599            wts.pln,
1600            &acts.inv2,
1601            &dn2,
1602            self.gemma,
1603            &mut dh1,
1604            grads.as_deref_mut().map(|g| &mut g[1][..]),
1605        );
1606
1607        // ── attention backward (dispatch) → dn1 ──
1608        let mats = self.mats(li).expect("layer mats");
1609        let dn1 = match &l.attn {
1610            FcdAttn::Full { .. } => {
1611                self.full_attn_bwd(&l.attn, &mats, &acts.attn, &dh1, b, t, nystrom)
1612            }
1613            FcdAttn::Gdn { .. } => self.gdn_attn_bwd(&l.attn, &acts.attn, &dh1, b, t),
1614        };
1615
1616        let mut dh_in = dh1.clone();
1617        ops::rmsnorm_bwd(
1618            h_in,
1619            wts.iln,
1620            &acts.inv1,
1621            &dn1,
1622            self.gemma,
1623            &mut dh_in,
1624            grads.map(|g| &mut g[0][..]),
1625        );
1626        dh_in
1627    }
1628
1629    /// Full-attention through-backward: o_proj → output gate →
1630    /// per-head attention (exact / Nyström-frozen-M) → RoPE → qk-norm →
1631    /// projections. Frozen weights: dX only.
1632    fn full_attn_bwd(
1633        &self,
1634        attn: &FcdAttn,
1635        mats: &LayerMats,
1636        acts: &AttnActs,
1637        dattn: &[f32],
1638        b: usize,
1639        t: usize,
1640        nystrom: bool,
1641    ) -> Vec<f32> {
1642        let (wqkv, wo) = (&mats.wqkv[..], &mats.wo[..]);
1643        let FcdAttn::Full {
1644            qrows: _,
1645            q_norm,
1646            k_norm,
1647            output_gate,
1648            ..
1649        } = attn
1650        else {
1651            unreachable!("full_attn_bwd on a non-Full layer");
1652        };
1653        let AttnActs::Full {
1654            qpre,
1655            kpre,
1656            vproj,
1657            qrot,
1658            krot,
1659            qinv,
1660            kinv,
1661            ao,
1662            gate_pre,
1663        } = acts
1664        else {
1665            unreachable!("acts mismatch");
1666        };
1667        let (hsz, nh, nkv, hd) = (self.hidden, self.nh, self.nkv, self.hd);
1668        let n = b * t;
1669        let pool = self.pool.as_deref();
1670        let qdim = nh * hd;
1671        let kvdim = nkv * hd;
1672        let rep = nh / nkv;
1673        let qrows = if *output_gate { 2 * qdim } else { qdim };
1674
1675        let mut dao_eff = vec![0f32; n * qdim];
1676        ops::gemm_dx(dattn, wo, &mut dao_eff, n, qdim, hsz, pool);
1677        // Output gate: ao_eff = ao·σ(g) → dao = d·σ(g), dg = d·ao·σ′(g).
1678        let (dao, dgate) = if *output_gate {
1679            let mut dao = vec![0f32; n * qdim];
1680            let mut dgp = vec![0f32; n * qdim];
1681            for i in 0..n * qdim {
1682                let sig = 1.0 / (1.0 + (-gate_pre[i]).exp());
1683                dao[i] = dao_eff[i] * sig;
1684                dgp[i] = dao_eff[i] * ao[i] * sig * (1.0 - sig);
1685            }
1686            (dao, dgp)
1687        } else {
1688            (dao_eff, Vec::new())
1689        };
1690
1691        let mut dqrot = vec![0f32; n * qdim];
1692        let mut dkrot = vec![0f32; n * kvdim];
1693        let mut dvproj = vec![0f32; n * kvdim];
1694        {
1695            // Parallel over (sequence, kv-group): a unit owns the dk/dv
1696            // slices of its group and the dq slices of its rep Q heads.
1697            let units = b * nkv;
1698            let dqp = SendMut(dqrot.as_mut_ptr());
1699            let dkp = SendMut(dkrot.as_mut_ptr());
1700            let dvp = SendMut(dvproj.as_mut_ptr());
1701            let (qr, kr, vr) = (qrot, krot, vproj);
1702            let daor = &dao;
1703            let nys = self.nys;
1704            let run_unit = |u: usize| {
1705                let (bi, g) = (u / nkv, u % nkv);
1706                let mut k64 = vec![0f64; t * hd];
1707                let mut v64 = vec![0f64; t * hd];
1708                for p in 0..t {
1709                    let r = bi * t + p;
1710                    for c in 0..hd {
1711                        k64[p * hd + c] = kr[r * kvdim + g * hd + c] as f64;
1712                        v64[p * hd + c] = vr[r * kvdim + g * hd + c] as f64;
1713                    }
1714                }
1715                let mut dk64 = vec![0f64; t * hd];
1716                let mut dv64 = vec![0f64; t * hd];
1717                let mut q64 = vec![0f64; t * hd];
1718                let mut do64 = vec![0f64; t * hd];
1719                let mut dq64 = vec![0f64; t * hd];
1720                for hh in 0..rep {
1721                    let h = g * rep + hh;
1722                    for p in 0..t {
1723                        let r = bi * t + p;
1724                        for c in 0..hd {
1725                            q64[p * hd + c] = qr[r * qdim + h * hd + c] as f64;
1726                            do64[p * hd + c] = daor[r * qdim + h * hd + c] as f64;
1727                        }
1728                    }
1729                    for v in dq64.iter_mut() {
1730                        *v = 0.0;
1731                    }
1732                    if nystrom {
1733                        ops::nystrom_head_bwd(
1734                            &q64, &k64, &v64, &do64, t, hd, hd, &nys, &mut dq64, &mut dk64,
1735                            &mut dv64,
1736                        );
1737                    } else {
1738                        ops::attn_head_bwd(
1739                            &q64, &k64, &v64, &do64, t, hd, hd, &mut dq64, &mut dk64, &mut dv64,
1740                        );
1741                    }
1742                    for p in 0..t {
1743                        let r = bi * t + p;
1744                        for c in 0..hd {
1745                            // SAFETY: disjoint (row, head) slices per unit.
1746                            unsafe {
1747                                *dqp.at(r * qdim + h * hd + c) = dq64[p * hd + c] as f32;
1748                            }
1749                        }
1750                    }
1751                }
1752                for p in 0..t {
1753                    let r = bi * t + p;
1754                    for c in 0..hd {
1755                        // SAFETY: disjoint (row, group) slices per unit.
1756                        unsafe {
1757                            *dkp.at(r * kvdim + g * hd + c) = dk64[p * hd + c] as f32;
1758                            *dvp.at(r * kvdim + g * hd + c) = dv64[p * hd + c] as f32;
1759                        }
1760                    }
1761                }
1762            };
1763            match pool {
1764                Some(p) if units > 1 => p.run(&|widx, nw| {
1765                    for u in (widx..units).step_by(nw) {
1766                        run_unit(u);
1767                    }
1768                }),
1769                _ => {
1770                    for u in 0..units {
1771                        run_unit(u);
1772                    }
1773                }
1774            }
1775        }
1776
1777        // qk-norm + RoPE through-grads (frozen gains → no dw).
1778        let mut dqpre = vec![0f32; n * qdim];
1779        let mut dkpre = vec![0f32; n * kvdim];
1780        for r in 0..n {
1781            let pos = r % t;
1782            for h in 0..nh {
1783                let s = r * qdim + h * hd;
1784                ops::rope_bwd(&mut dqrot[s..s + self.rotary_dim], pos, &self.inv_freq);
1785                match q_norm {
1786                    Some(w) => ops::rmsnorm_bwd(
1787                        &qpre[s..s + hd],
1788                        w,
1789                        &qinv[r * nh + h..r * nh + h + 1],
1790                        &dqrot[s..s + hd],
1791                        self.gemma,
1792                        &mut dqpre[s..s + hd],
1793                        None,
1794                    ),
1795                    None => dqpre[s..s + hd].copy_from_slice(&dqrot[s..s + hd]),
1796                }
1797            }
1798            for g in 0..nkv {
1799                let s = r * kvdim + g * hd;
1800                ops::rope_bwd(&mut dkrot[s..s + self.rotary_dim], pos, &self.inv_freq);
1801                match k_norm {
1802                    Some(w) => ops::rmsnorm_bwd(
1803                        &kpre[s..s + hd],
1804                        w,
1805                        &kinv[r * nkv + g..r * nkv + g + 1],
1806                        &dkrot[s..s + hd],
1807                        self.gemma,
1808                        &mut dkpre[s..s + hd],
1809                        None,
1810                    ),
1811                    None => dkpre[s..s + hd].copy_from_slice(&dkrot[s..s + hd]),
1812                }
1813            }
1814        }
1815
1816        // Re-interleave [dq; dgate] per head for gated projections.
1817        let dqraw: Vec<f32> = if *output_gate {
1818            let mut dq = vec![0f32; n * qrows];
1819            for r in 0..n {
1820                for h in 0..nh {
1821                    let dst = r * qrows + 2 * h * hd;
1822                    let src = r * qdim + h * hd;
1823                    dq[dst..dst + hd].copy_from_slice(&dqpre[src..src + hd]);
1824                    dq[dst + hd..dst + 2 * hd].copy_from_slice(&dgate[src..src + hd]);
1825                }
1826            }
1827            dq
1828        } else {
1829            dqpre
1830        };
1831
1832        // Projections (frozen weights → dX only; bias add is identity).
1833        // One fused submit: wqkv's row layout is exactly what gemm_dx
1834        // wants, so the sum dq·Wq + dk·Wk + dv·Wv is a concat of the
1835        // gradients and a single call.
1836        let fused = qrows + 2 * kvdim;
1837        let mut dqkv = vec![0f32; n * fused];
1838        for r in 0..n {
1839            let row = &mut dqkv[r * fused..(r + 1) * fused];
1840            row[..qrows].copy_from_slice(&dqraw[r * qrows..(r + 1) * qrows]);
1841            row[qrows..qrows + kvdim].copy_from_slice(&dkpre[r * kvdim..(r + 1) * kvdim]);
1842            row[qrows + kvdim..].copy_from_slice(&dvproj[r * kvdim..(r + 1) * kvdim]);
1843        }
1844        let mut dn1 = vec![0f32; n * hsz];
1845        ops::gemm_dx(&dqkv, wqkv, &mut dn1, n, hsz, fused, pool);
1846        dn1
1847    }
1848
1849    /// GDN through-backward: out_proj → pooled per-(seq, k-head) BPTT
1850    /// (fcd_ops::gdn_group_bwd) → conv backward → projections. Frozen
1851    /// weights: dX only.
1852    fn gdn_attn_bwd(
1853        &self,
1854        attn: &FcdAttn,
1855        acts: &AttnActs,
1856        dattn: &[f32],
1857        b: usize,
1858        t: usize,
1859    ) -> Vec<f32> {
1860        let FcdAttn::Gdn {
1861            wqkv,
1862            wz,
1863            wa,
1864            wb,
1865            conv,
1866            a_log,
1867            dt_bias,
1868            norm,
1869            wout,
1870        } = attn
1871        else {
1872            unreachable!("gdn_attn_bwd on a non-GDN layer");
1873        };
1874        let AttnActs::Gdn { qkv, z, a, b: bstr } = acts else {
1875            unreachable!("acts mismatch");
1876        };
1877        let d = self.gdn.expect("gdn layer without gdn dims");
1878        let (hsz, n) = (self.hidden, b * t);
1879        let pool = self.pool.as_deref();
1880        let (c_dim, vd, nv) = (d.c_dim(), d.vd(), d.nv);
1881
1882        let mut dof = vec![0f32; n * vd];
1883        ops::gemm_dx(dattn, wout, &mut dof, n, vd, hsz, pool);
1884
1885        let cfg = ops::GdnSeqCfg {
1886            nv: d.nv,
1887            nk: d.nk,
1888            dk: d.dk,
1889            dv: d.dv,
1890            kk: d.kk,
1891            rms_eps: self.eps,
1892            conv,
1893            a_log,
1894            dt_bias,
1895            norm,
1896        };
1897        let qkv64: Vec<f64> = qkv.iter().map(|&v| v as f64).collect();
1898        let z64: Vec<f64> = z.iter().map(|&v| v as f64).collect();
1899        let a64: Vec<f64> = a.iter().map(|&v| v as f64).collect();
1900        let b64: Vec<f64> = bstr.iter().map(|&v| v as f64).collect();
1901        let dof64: Vec<f64> = dof.iter().map(|&v| v as f64).collect();
1902        let mut pre64 = vec![0f64; n * c_dim];
1903        let mut cq64 = vec![0f64; n * c_dim];
1904        for bi in 0..b {
1905            let r = bi * t * c_dim..(bi + 1) * t * c_dim;
1906            ops::gdn_conv_fwd(
1907                &qkv64[r.clone()],
1908                t,
1909                c_dim,
1910                d.kk,
1911                conv,
1912                &mut pre64[r.clone()],
1913                &mut cq64[r],
1914            );
1915        }
1916
1917        let mut dcq64 = vec![0f64; n * c_dim];
1918        let mut dz64 = vec![0f64; n * vd];
1919        let mut da64 = vec![0f64; n * nv];
1920        let mut db64 = vec![0f64; n * nv];
1921        {
1922            let units = b * d.nk;
1923            let rep_v = d.nv / d.nk;
1924            let kd = d.nk * d.dk;
1925            let dcqp = SendMut(dcq64.as_mut_ptr());
1926            let dzp = SendMut(dz64.as_mut_ptr());
1927            let dap = SendMut(da64.as_mut_ptr());
1928            let dbp = SendMut(db64.as_mut_ptr());
1929            let (cqr, zr, ar, br, dor) = (&cq64, &z64, &a64, &b64, &dof64);
1930            let cfg_ref = &cfg;
1931            let run_unit = |u: usize| {
1932                let (bi, ko) = (u / d.nk, u % d.nk);
1933                // Full-width locals — the group only fills its own
1934                // channels; the scatter below copies exactly those.
1935                let mut dcq_l = vec![0f64; t * c_dim];
1936                let mut dz_l = vec![0f64; t * vd];
1937                let mut da_l = vec![0f64; t * nv];
1938                let mut db_l = vec![0f64; t * nv];
1939                ops::gdn_group_bwd(
1940                    &cqr[bi * t * c_dim..(bi + 1) * t * c_dim],
1941                    &zr[bi * t * vd..(bi + 1) * t * vd],
1942                    &ar[bi * t * nv..(bi + 1) * t * nv],
1943                    &br[bi * t * nv..(bi + 1) * t * nv],
1944                    t,
1945                    cfg_ref,
1946                    ko,
1947                    &dor[bi * t * vd..(bi + 1) * t * vd],
1948                    &mut dcq_l,
1949                    &mut dz_l,
1950                    &mut da_l,
1951                    &mut db_l,
1952                );
1953                // SAFETY of every store below: the written channel /
1954                // column ranges are exclusively owned by (bi, ko).
1955                for p in 0..t {
1956                    let row = (bi * t + p) * c_dim;
1957                    for c in ko * d.dk..(ko + 1) * d.dk {
1958                        unsafe {
1959                            *dcqp.at(row + c) = dcq_l[p * c_dim + c];
1960                            *dcqp.at(row + kd + c) = dcq_l[p * c_dim + kd + c];
1961                        }
1962                    }
1963                    for hh in 0..rep_v {
1964                        let h = ko * rep_v + hh;
1965                        for dj in 0..d.dv {
1966                            unsafe {
1967                                *dcqp.at(row + 2 * kd + h * d.dv + dj) =
1968                                    dcq_l[p * c_dim + 2 * kd + h * d.dv + dj];
1969                                *dzp.at((bi * t + p) * vd + h * d.dv + dj) =
1970                                    dz_l[p * vd + h * d.dv + dj];
1971                            }
1972                        }
1973                        unsafe {
1974                            *dap.at((bi * t + p) * nv + h) = da_l[p * nv + h];
1975                            *dbp.at((bi * t + p) * nv + h) = db_l[p * nv + h];
1976                        }
1977                    }
1978                }
1979            };
1980            match pool {
1981                Some(p) if units > 1 => p.run(&|widx, nw| {
1982                    for u in (widx..units).step_by(nw) {
1983                        run_unit(u);
1984                    }
1985                }),
1986                _ => {
1987                    for u in 0..units {
1988                        run_unit(u);
1989                    }
1990                }
1991            }
1992        }
1993
1994        let mut dqkv64 = vec![0f64; n * c_dim];
1995        for bi in 0..b {
1996            let r = bi * t * c_dim..(bi + 1) * t * c_dim;
1997            ops::gdn_conv_bwd(
1998                &pre64[r.clone()],
1999                t,
2000                c_dim,
2001                d.kk,
2002                conv,
2003                &dcq64[r.clone()],
2004                &mut dqkv64[r],
2005            );
2006        }
2007        let to32 = |v: &[f64]| -> Vec<f32> { v.iter().map(|&x| x as f32).collect() };
2008        let (dqkv, dz, da, db) = (to32(&dqkv64), to32(&dz64), to32(&da64), to32(&db64));
2009
2010        let mut dn1 = vec![0f32; n * hsz];
2011        ops::gemm_dx(&dqkv, wqkv, &mut dn1, n, hsz, c_dim, pool);
2012        ops::gemm_dx(&dz, wz, &mut dn1, n, hsz, vd, pool);
2013        ops::gemm_dx(&da, wa, &mut dn1, n, hsz, nv, pool);
2014        ops::gemm_dx(&db, wb, &mut dn1, n, hsz, nv, pool);
2015        dn1
2016    }
2017
2018    /// Full forward: embeddings → layers → final hidden [b·t, hidden].
2019    /// `student` switches converted layers to the Nyström kernel and
2020    /// reads trainable weights from `ts`; `keep` collects each layer's
2021    /// input hidden for the checkpointed backward.
2022    fn forward_hidden(
2023        &self,
2024        ids: &[u32],
2025        b: usize,
2026        t: usize,
2027        ts: Option<&TrainState>,
2028        student: bool,
2029        mut keep: Option<&mut Vec<Vec<f32>>>,
2030    ) -> Vec<f32> {
2031        let hsz = self.hidden;
2032        let mut h = vec![0f32; b * t * hsz];
2033        for (r, &id) in ids.iter().enumerate() {
2034            let src = (id as usize).min(self.embed.len() / hsz - 1) * hsz;
2035            h[r * hsz..(r + 1) * hsz].copy_from_slice(&self.embed[src..src + hsz]);
2036        }
2037        for li in 0..self.nl {
2038            if let Some(k) = keep.as_deref_mut() {
2039                k.push(h.clone());
2040            }
2041            let mats = self.mats(li).expect("layer mats");
2042            let wts = ln_ffn(self, if student { ts } else { None }, li, &mats);
2043            let nys = student && self.o1_flags[li];
2044            h = self.layer_forward(li, &h, b, t, &wts, nys, false).0;
2045        }
2046        h
2047    }
2048
2049    /// Loss head: chunked tied-lm_head CE+KL against the teacher hidden,
2050    /// returning (ce_mean, kl_mean, dHidden_student).
2051    fn loss_and_dhidden(
2052        &self,
2053        hs: &[f32],
2054        ht: &[f32],
2055        targets: &[u32],
2056        kl_w: f64,
2057    ) -> (f64, f64, Vec<f32>) {
2058        let hsz = self.hidden;
2059        let n = targets.len();
2060        let pool = self.pool.as_deref();
2061        let wh = self.head_weight();
2062        let vs = self.vocab;
2063
2064        let mut ns = vec![0f32; n * hsz];
2065        let mut invs = vec![0f32; n];
2066        ops::rmsnorm_fwd(
2067            hs,
2068            &self.final_norm,
2069            self.eps,
2070            self.gemma,
2071            &mut ns,
2072            &mut invs,
2073        );
2074        let mut nt = vec![0f32; n * hsz];
2075        let mut invt = vec![0f32; n];
2076        ops::rmsnorm_fwd(
2077            ht,
2078            &self.final_norm,
2079            self.eps,
2080            self.gemma,
2081            &mut nt,
2082            &mut invt,
2083        );
2084
2085        let inv_n = 1.0 / n as f64;
2086        let mut ce_sum = 0f64;
2087        let mut kl_sum = 0f64;
2088        let mut dns = vec![0f32; n * hsz];
2089        let mut ls = vec![0f32; LM_CHUNK * vs];
2090        let mut lt = vec![0f32; LM_CHUNK * vs];
2091        let mut dlg = vec![0f32; LM_CHUNK * vs];
2092        let mut r0 = 0usize;
2093        while r0 < n {
2094            let r1 = (r0 + LM_CHUNK).min(n);
2095            let c = r1 - r0;
2096            ops::gemm_nt(
2097                &ns[r0 * hsz..r1 * hsz],
2098                wh,
2099                &mut ls[..c * vs],
2100                c,
2101                hsz,
2102                vs,
2103                pool,
2104            );
2105            ops::gemm_nt(
2106                &nt[r0 * hsz..r1 * hsz],
2107                wh,
2108                &mut lt[..c * vs],
2109                c,
2110                hsz,
2111                vs,
2112                pool,
2113            );
2114            for r in 0..c {
2115                let (ce, kl) = ops::ce_kl_position(
2116                    &ls[r * vs..(r + 1) * vs],
2117                    &lt[r * vs..(r + 1) * vs],
2118                    targets[r0 + r] as usize,
2119                    kl_w,
2120                    inv_n,
2121                    &mut dlg[r * vs..(r + 1) * vs],
2122                );
2123                ce_sum += ce;
2124                kl_sum += kl;
2125            }
2126            ops::gemm_dx(
2127                &dlg[..c * vs],
2128                wh,
2129                &mut dns[r0 * hsz..r1 * hsz],
2130                c,
2131                hsz,
2132                vs,
2133                pool,
2134            );
2135            r0 = r1;
2136        }
2137
2138        let mut dhs = vec![0f32; n * hsz];
2139        ops::rmsnorm_bwd(
2140            hs,
2141            &self.final_norm,
2142            &invs,
2143            &dns,
2144            self.gemma,
2145            &mut dhs,
2146            None,
2147        );
2148        (ce_sum * inv_n, kl_sum * inv_n, dhs)
2149    }
2150
2151    /// Checkpointed backward: per layer, recompute the intra-layer
2152    /// activations and differentiate.
2153    fn backward(
2154        &self,
2155        b: usize,
2156        t: usize,
2157        keep: &[Vec<f32>],
2158        dh_last: Vec<f32>,
2159        ts: &mut TrainState,
2160    ) {
2161        // Split-borrow: the weight view reads `data`, the grads write
2162        // `grad` — disjoint fields of TrainState.
2163        let TrainState {
2164            layers, data, grad, ..
2165        } = ts;
2166        let mut dh = dh_last;
2167        for li in (0..self.nl).rev() {
2168            let h_in = &keep[li];
2169            let nys = self.o1_flags[li];
2170            let slot = layers.iter().position(|&x| x == li);
2171            let mats_hold = self.mats(li).expect("layer mats");
2172            let wts = match slot {
2173                Some(s) => {
2174                    let bi = s * PARAMS_PER_LAYER;
2175                    LnFfn {
2176                        iln: &data[bi],
2177                        pln: &data[bi + 1],
2178                        gate: &data[bi + 2],
2179                        up: &data[bi + 3],
2180                        down: &data[bi + 4],
2181                        gu: None,
2182                    }
2183                }
2184                None => {
2185                    let l = &self.layers[li];
2186                    LnFfn {
2187                        iln: &l.iln,
2188                        pln: &l.pln,
2189                        gate: &[],
2190                        up: &[],
2191                        down: &mats_hold.down,
2192                        gu: Some(&mats_hold.gu),
2193                    }
2194                }
2195            };
2196            let (_, acts) = self.layer_forward(li, h_in, b, t, &wts, nys, true);
2197            let acts = acts.expect("want_acts");
2198            dh = match slot {
2199                Some(s) => {
2200                    let gb = s * PARAMS_PER_LAYER;
2201                    let gr = &mut grad[gb..gb + PARAMS_PER_LAYER];
2202                    self.layer_backward(li, h_in, b, t, &wts, nys, &acts, &dh, Some(gr))
2203                }
2204                None => self.layer_backward(li, h_in, b, t, &wts, nys, &acts, &dh, None),
2205            };
2206        }
2207    }
2208
2209    /// Test-only: one full training-graph evaluation — teacher forward,
2210    /// student forward, CE+KL loss, checkpointed backward into the
2211    /// grads. Returns the weighted total loss. The block-level
2212    /// gradcheck runs finite differences over trainable weights through
2213    /// this, which exercises EVERY through-grad in the graph (layer-0
2214    /// gains flow through all attention/rope/qk-norm/GQA paths above).
2215    #[doc(hidden)]
2216    pub fn loss_and_grads_for_test(
2217        &self,
2218        ids: &[u32],
2219        tgt: &[u32],
2220        b: usize,
2221        t: usize,
2222        ts: &mut TrainState,
2223        kl_w: f64,
2224    ) -> f64 {
2225        let ht = self.forward_hidden(ids, b, t, None, false, None);
2226        let mut keep = Vec::with_capacity(self.nl);
2227        let hs = self.forward_hidden(ids, b, t, Some(ts), true, Some(&mut keep));
2228        let (ce, kl, dhs) = self.loss_and_dhidden(&hs, &ht, tgt, kl_w);
2229        ts.zero_grad();
2230        self.backward(b, t, &keep, dhs, ts);
2231        (1.0 - kl_w) * ce + kl_w * kl
2232    }
2233
2234    /// Teacher-forced CE perplexity on deterministic evenly-spaced val
2235    /// windows (`heal_hybridk_06b.py::val_ppl` discipline — random
2236    /// windows made gate comparisons ride ±15% noise).
2237    pub fn val_ppl(
2238        &self,
2239        va: &[u32],
2240        ts: Option<&TrainState>,
2241        student: bool,
2242        bs: usize,
2243        nrounds: usize,
2244        seq: usize,
2245    ) -> f64 {
2246        let nwin = nrounds * bs;
2247        if va.len() < seq + 2 || nwin == 0 {
2248            return f64::NAN;
2249        }
2250        let stride = (va.len() - seq - 1) / nwin;
2251        let hsz = self.hidden;
2252        let wh = self.head_weight();
2253        let vs = self.vocab;
2254        let pool = self.pool.as_deref();
2255        let mut nll = 0f64;
2256        let mut cnt = 0usize;
2257        for j in 0..nrounds {
2258            let mut ids = Vec::with_capacity(bs * seq);
2259            let mut tgt = Vec::with_capacity(bs * seq);
2260            for bi in 0..bs {
2261                let off = ((j * bs + bi) * stride.max(1)).min(va.len() - seq - 1);
2262                ids.extend_from_slice(&va[off..off + seq]);
2263                tgt.extend_from_slice(&va[off + 1..off + seq + 1]);
2264            }
2265            let h = self.forward_hidden(&ids, bs, seq, ts, student, None);
2266            let n = bs * seq;
2267            let mut ns = vec![0f32; n * hsz];
2268            let mut inv = vec![0f32; n];
2269            ops::rmsnorm_fwd(
2270                &h,
2271                &self.final_norm,
2272                self.eps,
2273                self.gemma,
2274                &mut ns,
2275                &mut inv,
2276            );
2277            let mut lg = vec![0f32; LM_CHUNK * vs];
2278            let mut r0 = 0usize;
2279            while r0 < n {
2280                let r1 = (r0 + LM_CHUNK).min(n);
2281                let c = r1 - r0;
2282                ops::gemm_nt(
2283                    &ns[r0 * hsz..r1 * hsz],
2284                    wh,
2285                    &mut lg[..c * vs],
2286                    c,
2287                    hsz,
2288                    vs,
2289                    pool,
2290                );
2291                for r in 0..c {
2292                    let row = &lg[r * vs..(r + 1) * vs];
2293                    let target = tgt[r0 + r] as usize;
2294                    let mut mx = f64::NEG_INFINITY;
2295                    for &v in row {
2296                        mx = mx.max(v as f64);
2297                    }
2298                    let mut s = 0f64;
2299                    for &v in row {
2300                        s += (v as f64 - mx).exp();
2301                    }
2302                    nll += mx + s.ln() - row[target.min(vs - 1)] as f64;
2303                    cnt += 1;
2304                }
2305                r0 = r1;
2306            }
2307        }
2308        (nll / cnt.max(1) as f64).exp()
2309    }
2310}
2311
2312// ─────────────────────────── training loop ───────────────────────────
2313
2314/// Run the full certified polish: train, early-stop/restore-best, and
2315/// write `<out>` (source tensors byte-copied, polished LN/FFN as f32).
2316///
2317/// With `gate` (Patent 16 draft, claim 13), every eval checkpoint is
2318/// additionally scored by greedy generation through the REAL streaming
2319/// O(1) runtime, and the restored checkpoint is the lowest-ppl one
2320/// AMONG GATE-PASSERS; if none passes, the zero-shot state is restored
2321/// (identity polish) — the stage never makes generation worse than
2322/// conversion alone.
2323pub fn run_polish(
2324    model: &Arc<CmfModel>,
2325    o1: &O1Cfg,
2326    hp: &FcdHyper,
2327    tr: &[u32],
2328    va: &[u32],
2329    out: &std::path::Path,
2330    gate: Option<&GenGateCfg>,
2331) -> Result<FcdReport, String> {
2332    if tr.len() < hp.seq + 2 {
2333        return Err(format!(
2334            "train corpus too small: {} tokens < seq+2 = {}",
2335            tr.len(),
2336            hp.seq + 2
2337        ));
2338    }
2339    let fm = FcdModel::from_cmf(model, o1)?;
2340    let converted = fm.converted();
2341    if converted.is_empty() {
2342        return Err("no converted layers under this --o1 spec (nothing to polish)".into());
2343    }
2344    tracing::info!(
2345        "fcd: {} layers converted ({} trainable tensors), m={} w={} sink={}, \
2346         corpus train {} / val {} tokens",
2347        converted.len(),
2348        converted.len() * PARAMS_PER_LAYER,
2349        fm.nys.m,
2350        fm.nys.w,
2351        fm.nys.sink,
2352        tr.len(),
2353        va.len()
2354    );
2355
2356    let mut ts = TrainState::new(&fm);
2357    let teacher_ppl = fm.val_ppl(va, None, false, hp.bs, 2, hp.seq);
2358    let ppl_start = fm.val_ppl(va, Some(&ts), true, hp.bs, 2, hp.seq);
2359    tracing::info!(
2360        "fcd: quick-val teacher ppl {teacher_ppl:.2} | zero-shot o1 student ppl {ppl_start:.2}"
2361    );
2362
2363    // ── generation gate (claim 13): baseline at step 0 ──
2364    let mut gate_state: Option<(Pipeline, Vec<f64>)> = match gate {
2365        Some(g) if !g.prompts.is_empty() => {
2366            let greedy = SamplerConfig {
2367                temperature: 0.0,
2368                top_p: 1.0,
2369                top_k: 0,
2370                repetition_penalty: 1.0,
2371                min_p: 0.0,
2372                seed: Some(0),
2373                suppress_tokens: Vec::new(),
2374            };
2375            let mut pipe = Pipeline::from_model(model, greedy)
2376                .map_err(|e| format!("gen-gate pipeline: {e}"))?;
2377            pipe.set_o1(Some(o1.clone()));
2378            apply_trainables(&mut pipe, &fm, &ts);
2379            let base = gate_gen_scores(&mut pipe, g)?;
2380            tracing::info!("fcd gen-gate baseline loop-scores: {base:?}");
2381            Some((pipe, base))
2382        }
2383        Some(_) => {
2384            tracing::warn!("fcd gen-gate requested but val stream too short — gate off");
2385            None
2386        }
2387        None => None,
2388    };
2389    // Identity fallback: the pre-training master copies.
2390    let init_snapshot: Option<Vec<Vec<f32>>> = gate_state.is_some().then(|| ts.data.clone());
2391    let mut gate_evals: Vec<(usize, f64, Vec<f64>, bool)> = Vec::new();
2392
2393    let mut rng = SplitMix64::new(hp.seed);
2394    let mut best: (f64, Option<Vec<Vec<f32>>>, usize) = (f64::INFINITY, None, 0);
2395    let mut losses: Vec<(f64, f64)> = Vec::with_capacity(hp.steps);
2396    let t0 = std::time::Instant::now();
2397    let n_per_step = hp.bs * hp.seq;
2398    for st in 1..=hp.steps {
2399        // Fresh random windows each step (the recipe; indices need not
2400        // match the torch RNG — the distribution does).
2401        let mut ids = Vec::with_capacity(n_per_step);
2402        let mut tgt = Vec::with_capacity(n_per_step);
2403        for _ in 0..hp.bs {
2404            let off = (rng.next_u64() as usize) % (tr.len() - hp.seq - 1);
2405            ids.extend_from_slice(&tr[off..off + hp.seq]);
2406            tgt.extend_from_slice(&tr[off + 1..off + hp.seq + 1]);
2407        }
2408
2409        let ht = fm.forward_hidden(&ids, hp.bs, hp.seq, None, false, None);
2410        let mut keep: Vec<Vec<f32>> = Vec::with_capacity(fm.nl);
2411        let hs = fm.forward_hidden(&ids, hp.bs, hp.seq, Some(&ts), true, Some(&mut keep));
2412        let (ce, kl, dhs) = fm.loss_and_dhidden(&hs, &ht, &tgt, hp.kl_w);
2413        ts.zero_grad();
2414        fm.backward(hp.bs, hp.seq, &keep, dhs, &mut ts);
2415        let gn = ts.clip_and_step(hp.lr);
2416        losses.push((ce, kl));
2417
2418        let el = t0.elapsed().as_secs_f64();
2419        tracing::info!(
2420            "fcd step {st}/{}: ce {ce:.3} kl {kl:.3} |g| {gn:.3} ({:.1}s/step)",
2421            hp.steps,
2422            el / st as f64
2423        );
2424        if hp.eval_every > 0 && st % hp.eval_every == 0 {
2425            let p = fm.val_ppl(va, Some(&ts), true, hp.bs, 2, hp.seq);
2426            match (&mut gate_state, gate) {
2427                (Some((pipe, base)), Some(g)) => {
2428                    apply_trainables(pipe, &fm, &ts);
2429                    let scores = gate_gen_scores(pipe, g)?;
2430                    let pass = gate_pass(&scores, base, g.threshold, g.baseline_slack);
2431                    let tag = if pass && p < best.0 {
2432                        best = (p, Some(ts.data.clone()), st);
2433                        " *best*"
2434                    } else {
2435                        ""
2436                    };
2437                    tracing::info!(
2438                        "fcd eval step {st}: val ppl {p:.2} | gen-gate {}                          (loop-scores {scores:?}){tag}",
2439                        if pass { "PASS" } else { "FAIL" }
2440                    );
2441                    gate_evals.push((st, p, scores, pass));
2442                }
2443                _ => {
2444                    let tag = if p < best.0 {
2445                        best = (p, Some(ts.data.clone()), st);
2446                        " *best*"
2447                    } else {
2448                        ""
2449                    };
2450                    tracing::info!("fcd eval step {st}: val ppl {p:.2}{tag}");
2451                }
2452            }
2453        }
2454    }
2455
2456    // Early stop: restore the best checkpoint (certified: best was step
2457    // 150 of 300 in the torch run). Under the gate, `best` only ever
2458    // held GATE-PASSING checkpoints; none passing → identity restore.
2459    let mut gate_chosen: Option<usize> = None;
2460    if let Some(snap) = best.1.take() {
2461        ts.data = snap;
2462        gate_chosen = Some(best.2);
2463        tracing::info!(
2464            "fcd: restored best checkpoint from step {} (val ppl {:.2})",
2465            best.2,
2466            best.0
2467        );
2468    } else if let Some(init) = init_snapshot {
2469        ts.data = init;
2470        tracing::info!(
2471            "fcd: polish rejected by generation gate — identity artifact              (zero-shot state written; claim 13 floor)"
2472        );
2473    }
2474    let ppl_final = fm.val_ppl(va, Some(&ts), true, hp.bs, 6, hp.seq);
2475    let report = FcdReport {
2476        converted: converted.clone(),
2477        teacher_ppl,
2478        ppl_start,
2479        ppl_best: best.0.min(ppl_final),
2480        best_step: best.2,
2481        ppl_final,
2482        steps_run: hp.steps,
2483        sec_per_step: t0.elapsed().as_secs_f64() / hp.steps.max(1) as f64,
2484        losses,
2485        gate: gate_state.map(|(_, base)| GateReport {
2486            baseline: base,
2487            evals: gate_evals,
2488            chosen: gate_chosen,
2489        }),
2490    };
2491    save_polished(model, out, &fm, &ts, o1, hp, &report)?;
2492    Ok(report)
2493}
2494
2495/// Hot-swap the trainable LN/FFN master copies into a runtime Pipeline
2496/// (frozen tensors stay mmap-backed — this reproduces the artifact the
2497/// polish would write, without writing it).
2498fn apply_trainables(pipe: &mut Pipeline, fm: &FcdModel, ts: &TrainState) {
2499    let hidden = fm.hidden;
2500    for (slot, &li) in ts.layers.iter().enumerate() {
2501        let b = slot * PARAMS_PER_LAYER;
2502        let inter = fm.layers[li].inter;
2503        let lw = &mut pipe.weights.layers[li];
2504        lw.input_norm = ts.data[b].clone();
2505        lw.post_norm = ts.data[b + 1].clone();
2506        lw.ffn = FfnKind::Dense(DenseFfn {
2507            gate_proj: QTensor::from_f32(ts.data[b + 2].clone(), inter, hidden),
2508            up_proj: QTensor::from_f32(ts.data[b + 3].clone(), inter, hidden),
2509            down_proj: QTensor::from_f32(ts.data[b + 4].clone(), hidden, inter),
2510            act: crate::pipeline::Act::Silu,
2511        });
2512    }
2513}
2514
2515/// Greedy loop-score probe through the streaming runtime.
2516fn gate_gen_scores(pipe: &mut Pipeline, g: &GenGateCfg) -> Result<Vec<f64>, String> {
2517    g.prompts
2518        .iter()
2519        .map(|p| {
2520            pipe.generate_from_ids(p, g.gen_tokens, None, None)
2521                .map(|r| loop_score(&r.token_ids))
2522        })
2523        .collect()
2524}
2525
2526/// Write the polished container: every source tensor byte-copied except
2527/// the converted layers' LN/FFN, which become f32 (per-tensor dtypes
2528/// are first-class in the directory — no requant noise on fresh
2529/// weights). Adds `provenance.o1_attn` + `provenance.fcd`.
2530fn save_polished(
2531    model: &CmfModel,
2532    out: &std::path::Path,
2533    fm: &FcdModel,
2534    ts: &TrainState,
2535    o1: &O1Cfg,
2536    hp: &FcdHyper,
2537    report: &FcdReport,
2538) -> Result<(), String> {
2539    use cortiq_core::format::TensorSpec;
2540    let mut replace: std::collections::HashMap<String, (usize, usize)> =
2541        std::collections::HashMap::new(); // name → (slot, param idx)
2542    for (s, &li) in ts.layers.iter().enumerate() {
2543        let p = format!("model.layers.{li}.");
2544        for (k, suffix) in [
2545            (0usize, "input_layernorm.weight"),
2546            (1, "post_attention_layernorm.weight"),
2547            (2, "mlp.gate_proj.weight"),
2548            (3, "mlp.up_proj.weight"),
2549            (4, "mlp.down_proj.weight"),
2550        ] {
2551            replace.insert(format!("{p}{suffix}"), (s, k));
2552        }
2553    }
2554    let mut specs = Vec::with_capacity(model.tensors.len());
2555    for t in &model.tensors {
2556        if let Some(&(s, k)) = replace.get(&t.name) {
2557            let data = &ts.data[s * PARAMS_PER_LAYER + k];
2558            let mut bytes = Vec::with_capacity(data.len() * 4);
2559            for v in data {
2560                bytes.extend_from_slice(&v.to_le_bytes());
2561            }
2562            specs.push(TensorSpec {
2563                name: t.name.clone(),
2564                dtype: TensorDtype::F32,
2565                shape: t.shape.clone(),
2566                data: bytes,
2567            });
2568        } else {
2569            specs.push(TensorSpec {
2570                name: t.name.clone(),
2571                dtype: t.dtype,
2572                shape: t.shape.clone(),
2573                data: model.entry_bytes(t).to_vec(),
2574            });
2575        }
2576    }
2577
2578    let mut header = model.header.clone();
2579    let mut prov = match header.provenance.take() {
2580        Some(serde_json::Value::Object(m)) => m,
2581        _ => serde_json::Map::new(),
2582    };
2583    let layers_json = match &o1.layers {
2584        O1Layers::All => serde_json::json!("all"),
2585        O1Layers::Deep(n) => serde_json::json!(format!("deep{n}")),
2586        O1Layers::List(v) => serde_json::json!(v),
2587    };
2588    prov.insert(
2589        "o1_attn".into(),
2590        serde_json::json!({
2591            "layers": layers_json, "m": o1.m, "w": o1.w, "sink": o1.sink
2592        }),
2593    );
2594    prov.insert(
2595        "fcd".into(),
2596        serde_json::json!({
2597            "steps": hp.steps, "lr": hp.lr, "kl_w": hp.kl_w,
2598            "bs": hp.bs, "seq": hp.seq,
2599            "teacher_ppl": report.teacher_ppl,
2600            "ppl_start": report.ppl_start,
2601            "ppl_final": report.ppl_final,
2602            "best_step": report.best_step,
2603            "converted_layers": report.converted,
2604        }),
2605    );
2606    header.provenance = Some(serde_json::Value::Object(prov));
2607    let _ = fm; // geometry only used for validation today
2608
2609    let masks = if model.masks.masks.is_empty() {
2610        None
2611    } else {
2612        Some(&model.masks)
2613    };
2614    CmfModel::write(out, &header, &specs, masks, model.vocab.as_deref())
2615        .map_err(|e| format!("writing polished cmf: {e}"))
2616}
2617
2618#[cfg(test)]
2619mod tests {
2620    use super::*;
2621
2622    /// Claim-13 selection: lowest ppl AMONG PASSING, not global lowest.
2623    #[test]
2624    fn gate_selects_lowest_ppl_among_passing() {
2625        let base = vec![0.10, 0.00, 0.20];
2626        let evals = vec![
2627            (25usize, 21.0, vec![0.10, 0.05, 0.20]), // pass
2628            (50, 18.0, vec![0.40, 0.00, 0.10]),      // fail: 0.40 > threshold
2629            (75, 19.0, vec![0.15, 0.05, 0.25]),      // pass — best passing
2630            (100, 18.5, vec![0.20, 0.30, 0.20]),     // fail: 0.30 > base+0.10
2631        ];
2632        let sel = select_checkpoint(&evals, &base, 0.35, 0.10);
2633        assert_eq!(sel, Some(2), "step 75 is the lowest-ppl PASSING checkpoint");
2634    }
2635
2636    /// All checkpoints fail → identity (None): the polish must never
2637    /// make generation worse than conversion alone.
2638    #[test]
2639    fn gate_all_fail_is_identity() {
2640        let base = vec![0.0, 0.0, 0.0];
2641        let evals = vec![
2642            (25usize, 15.0, vec![0.50, 0.0, 0.0]),
2643            (50, 14.0, vec![0.0, 0.36, 0.0]),
2644            (75, 13.0, vec![0.0, 0.0, 0.11]), // 0.11 > 0 + 0.10 slack
2645        ];
2646        assert_eq!(select_checkpoint(&evals, &base, 0.35, 0.10), None);
2647    }
2648
2649    /// Boundary discipline: scores AT the threshold / AT base+slack pass
2650    /// ("exceeds" is strict); ties in ppl resolve to the earliest step.
2651    #[test]
2652    fn gate_boundaries_and_tie_break() {
2653        let base = vec![0.25];
2654        assert!(gate_pass(&[0.35], &base, 0.35, 0.10), "== threshold passes");
2655        assert!(
2656            gate_pass(&[0.35], &[0.25], 0.35, 0.10),
2657            "== base+slack passes"
2658        );
2659        assert!(!gate_pass(&[0.351], &base, 0.35, 0.10));
2660        assert!(!gate_pass(&[0.30], &[0.10], 0.35, 0.10), "0.30 > 0.10+0.10");
2661        let evals = vec![(25usize, 20.0, vec![0.10]), (50, 20.0, vec![0.10])];
2662        assert_eq!(
2663            select_checkpoint(&evals, &base, 0.35, 0.10),
2664            Some(0),
2665            "equal ppl → earliest checkpoint"
2666        );
2667    }
2668}