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, FfnAct, 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    /// Polish WITHOUT converting attention: the `--o1` spec then only
54    /// names which layers are trainable, and both teacher and student
55    /// keep exact attention. This is the shape the notebook's FCD
56    /// correction has — restore accuracy a compression already cost by
57    /// training the last layers on real text — and it is what a
58    /// narrowed FFN needs, where the damage is in the FFN, not in the
59    /// attention kernel.
60    pub polish_only: bool,
61}
62
63impl Default for FcdHyper {
64    fn default() -> Self {
65        Self {
66            steps: 300,
67            lr: 5e-5,
68            kl_w: 0.7,
69            eval_every: 25,
70            bs: 2,
71            seq: 512,
72            seed: 0,
73            polish_only: false,
74        }
75    }
76}
77
78/// A training or validation token stream for the polish.
79///
80/// `weight[i]` scales the loss of predicting `ids[i]` (0 = context only),
81/// so an answer-only loss is a stream whose prompt tokens weigh 0.
82/// `starts` marks record boundaries (ascending, `starts[0] == 0`): a window
83/// then begins inside one record and nothing past that record's end is
84/// scored, so one prompt's answer is never trained on another's context.
85/// Without either, the stream is plain text and every position counts —
86/// exactly the original corpus behaviour.
87#[derive(Clone, Copy, Debug)]
88pub struct FcdStream<'a> {
89    pub ids: &'a [u32],
90    pub weight: Option<&'a [f32]>,
91    pub starts: Option<&'a [usize]>,
92}
93
94impl<'a> FcdStream<'a> {
95    pub fn plain(ids: &'a [u32]) -> Self {
96        Self { ids, weight: None, starts: None }
97    }
98
99    fn is_plain(&self) -> bool {
100        self.weight.is_none() && self.starts.is_none()
101    }
102
103    fn w(&self, i: usize) -> f32 {
104        self.weight.map_or(1.0, |w| w[i])
105    }
106
107    /// Records that carry any loss: `(start, end, first scored target,
108    /// last scored target + 1)`. A plain stream is one record.
109    fn scored_records(&self) -> Vec<(usize, usize, usize, usize)> {
110        let n = self.ids.len();
111        let whole = [0usize];
112        let starts = self.starts.unwrap_or(&whole);
113        let mut out = Vec::new();
114        for (r, &st) in starts.iter().enumerate() {
115            let en = starts.get(r + 1).copied().unwrap_or(n).min(n);
116            let mut first = None;
117            let mut last = 0;
118            for i in st + 1..en {
119                if self.w(i) > 0.0 {
120                    first.get_or_insert(i);
121                    last = i + 1;
122                }
123            }
124            if let Some(f) = first {
125                out.push((st, en, f, last));
126            }
127        }
128        out
129    }
130
131    /// Window start for record `rec` that keeps target `p` in view:
132    /// a record that fits starts at its own first token (the whole prompt
133    /// is context), a longer one at a uniform offset around `p`.
134    fn window_start(&self, rec: (usize, usize, usize, usize), p: usize, seq: usize, jitter: u64) -> usize {
135        let (st, en, _, _) = rec;
136        let max_off = self.ids.len() - seq - 1;
137        if en - st <= seq + 1 {
138            return st.min(max_off);
139        }
140        let lo = st.max(p.saturating_sub(seq));
141        let hi = (p - 1).min(max_off).max(lo);
142        (lo + (jitter as usize) % (hi - lo + 1)).min(max_off)
143    }
144
145    /// Loss weights of the `seq` targets of the window at `off` (targets
146    /// outside the window's own record weigh 0).
147    fn target_weights(&self, off: usize, seq: usize, rec: (usize, usize, usize, usize)) -> Vec<f32> {
148        let (st, en, _, _) = rec;
149        (0..seq)
150            .map(|t| {
151                let i = off + 1 + t;
152                if i > st && i < en { self.w(i) } else { 0.0 }
153            })
154            .collect()
155    }
156}
157
158/// Input of [`FcdModel::forward_span`].
159enum SpanIn<'a> {
160    Ids(&'a [u32]),
161    Hidden(Vec<f32>),
162}
163
164/// What the polish measured — written into `provenance.fcd` and
165/// reported by the CLI.
166#[derive(Clone, Debug)]
167pub struct FcdReport {
168    pub converted: Vec<usize>,
169    /// Teacher (exact attention) quick-val ppl — the anchor.
170    pub teacher_ppl: f64,
171    /// Student quick-val ppl BEFORE training (zero-shot o1 damage).
172    pub ppl_start: f64,
173    /// Best quick-val ppl during training (the restored checkpoint).
174    pub ppl_best: f64,
175    pub best_step: usize,
176    /// Final val ppl of the restored checkpoint on the wider window set.
177    pub ppl_final: f64,
178    pub steps_run: usize,
179    pub sec_per_step: f64,
180    /// Per-step (ce, kl) — the training trajectory, unweighted.
181    pub losses: Vec<(f64, f64)>,
182    /// Generation-gate record (None = ppl-only selection).
183    pub gate: Option<GateReport>,
184}
185
186/// What the generation gate saw and decided.
187#[derive(Clone, Debug)]
188pub struct GateReport {
189    /// Zero-shot (step-0) loop scores per prompt — the baseline.
190    pub baseline: Vec<f64>,
191    /// Per eval checkpoint: (step, val ppl, loop scores, passed).
192    pub evals: Vec<(usize, f64, Vec<f64>, bool)>,
193    /// Step whose params were restored (None = identity: the polish
194    /// was rejected, the artifact carries the zero-shot state).
195    pub chosen: Option<usize>,
196}
197
198// ───────────────────── generation gate (claim 13) ─────────────────────
199
200/// Loopiness of a generated id sequence: 1 − unique 4-grams / total.
201/// 0 = no repeated 4-gram; near 1 = a tight loop.
202pub fn loop_score(ids: &[u32]) -> f64 {
203    if ids.len() < 5 {
204        return 0.0;
205    }
206    let grams: std::collections::HashSet<&[u32]> = ids.windows(4).collect();
207    1.0 - grams.len() as f64 / ids.windows(4).count() as f64
208}
209
210/// Generation-gate configuration (Patent 16 draft, claim 13:
211/// checkpoint selection gated on generation-behavior metrics measured
212/// through the SERVED kernel, not on the training objective alone).
213#[derive(Clone, Debug)]
214pub struct GenGateCfg {
215    /// Fixed long-context prompts (token ids), greedy-decoded at every
216    /// eval checkpoint.
217    pub prompts: Vec<Vec<u32>>,
218    pub gen_tokens: usize,
219    /// A checkpoint fails if ANY prompt's loop score exceeds this.
220    pub threshold: f64,
221    /// …or exceeds its zero-shot baseline by more than this.
222    pub baseline_slack: f64,
223}
224
225impl GenGateCfg {
226    /// The standard 3-prompt probe of the torch reference: 400-token
227    /// windows at L/10, L/2, 8L/10 of the val stream, greedy 60.
228    pub fn standard(va: &[u32]) -> Option<Self> {
229        let l = va.len().saturating_sub(500);
230        if l < 400 {
231            return None;
232        }
233        let prompts = [l / 10, l / 2, 8 * l / 10]
234            .iter()
235            .map(|&off| va[off..off + 400].to_vec())
236            .collect();
237        Some(Self {
238            prompts,
239            gen_tokens: 60,
240            threshold: 0.35,
241            baseline_slack: 0.10,
242        })
243    }
244}
245
246/// Gate predicate (Patent 16 draft, claim 13): a checkpoint PASSES iff
247/// no prompt's loop score exceeds `threshold` AND none exceeds its
248/// zero-shot baseline by more than `slack` — boundary values pass.
249pub fn gate_pass(scores: &[f64], baseline: &[f64], threshold: f64, slack: f64) -> bool {
250    scores
251        .iter()
252        .zip(baseline)
253        .all(|(&s, &b)| s <= threshold && s <= b + slack)
254}
255
256/// Checkpoint selection: lowest val ppl AMONG GATE-PASSING checkpoints
257/// (ties → earliest). None = nothing passed → the caller must restore
258/// the zero-shot state (identity polish): the stage must never make
259/// generation worse than conversion alone. (Patent 16 draft, claim 13.)
260pub fn select_checkpoint(
261    evals: &[(usize, f64, Vec<f64>)],
262    baseline: &[f64],
263    threshold: f64,
264    slack: f64,
265) -> Option<usize> {
266    let mut best: Option<usize> = None;
267    for (i, (_, ppl, scores)) in evals.iter().enumerate() {
268        if !gate_pass(scores, baseline, threshold, slack) {
269            continue;
270        }
271        if best.map(|b| *ppl < evals[b].1).unwrap_or(true) {
272            best = Some(i);
273        }
274    }
275    best
276}
277
278// ───────────────────────── model container ─────────────────────────
279
280/// Wall-clock phase counters for the bake profiler (CMF_BAKE_PROF=1
281/// prints them). Written from worker threads, so atomics; nanoseconds.
282pub mod prof {
283    use std::sync::atomic::{AtomicU64, Ordering};
284    pub static ATTN_FWD: AtomicU64 = AtomicU64::new(0);
285    pub static FFN_FWD: AtomicU64 = AtomicU64::new(0);
286    /// Inside FFN_FWD: the device chain call, the plane split + host
287    /// activation, and the host (unfused) GEMM path.
288    pub static FFN_CHAIN: AtomicU64 = AtomicU64::new(0);
289    pub static FFN_ACT: AtomicU64 = AtomicU64::new(0);
290    pub static FFN_HOST: AtomicU64 = AtomicU64::new(0);
291    /// Before the chain (residual add, post-norm, buffers) and after it
292    /// (residual add, acts struct).
293    pub static FFN_PRE: AtomicU64 = AtomicU64::new(0);
294    pub static FFN_POST: AtomicU64 = AtomicU64::new(0);
295    /// Inside ATTN_FWD: the device chain call.
296    pub static ATTN_CHAIN: AtomicU64 = AtomicU64::new(0);
297    pub static BWD: AtomicU64 = AtomicU64::new(0);
298    /// The GDN operator itself (conv + recurrence, forward and BPTT), wherever it runs.
299    pub static GDN: AtomicU64 = AtomicU64::new(0);
300    /// Named sections (`CMF_BAKE_PROF=1`): seconds by label, printed by the bake.
301    pub static NAMED: std::sync::Mutex<Vec<(&'static str, u64)>> = std::sync::Mutex::new(Vec::new());
302    pub fn tick(name: &'static str, t: std::time::Instant) {
303        let ns = t.elapsed().as_nanos() as u64;
304        let mut g = NAMED.lock().unwrap();
305        match g.iter_mut().find(|(n, _)| *n == name) {
306            Some((_, v)) => *v += ns,
307            None => g.push((name, ns)),
308        }
309    }
310    pub fn named_report() -> String {
311        let mut g = NAMED.lock().unwrap();
312        let out = g.iter().map(|(n, v)| format!("{n} {:.2}s", *v as f64 / 1e9)).collect::<Vec<_>>().join(" | ");
313        g.clear();
314        out
315    }
316    pub static GEMM: AtomicU64 = AtomicU64::new(0);
317    pub static GEMM_CALLS: AtomicU64 = AtomicU64::new(0);
318    #[inline]
319    pub fn add(c: &AtomicU64, t: std::time::Instant) {
320        c.fetch_add(t.elapsed().as_nanos() as u64, Ordering::Relaxed);
321    }
322    /// Read and reset, in seconds.
323    pub fn take(c: &AtomicU64) -> f64 {
324        c.swap(0, Ordering::Relaxed) as f64 / 1e9
325    }
326
327    use std::sync::Mutex;
328    /// (n, k, m) → (calls, ns). A handful of shapes dominate a training
329    /// step; naming them decides which ones are worth a GPU submit and
330    /// which are cheaper computed in place.
331    pub static SHAPES: Mutex<Vec<((usize, usize, usize), (u64, u64))>> = Mutex::new(Vec::new());
332    pub fn gemm_shape(n: usize, k: usize, m: usize, t0: std::time::Instant) {
333        let ns = t0.elapsed().as_nanos() as u64;
334        let mut g = SHAPES.lock().unwrap();
335        match g.iter_mut().find(|(s, _)| *s == (n, k, m)) {
336            Some((_, (c, tt))) => {
337                *c += 1;
338                *tt += ns;
339            }
340            None => g.push(((n, k, m), (1, ns))),
341        }
342    }
343    pub fn shape_report(top: usize) -> String {
344        let mut g = SHAPES.lock().unwrap();
345        g.sort_by_key(|(_, (_, ns))| std::cmp::Reverse(*ns));
346        let out = g
347            .iter()
348            .take(top)
349            .map(|((n, k, m), (c, ns))| {
350                format!(
351                    "    [{n}x{k}x{m}] {c} calls, {:.1}s total, {:.1} ms/call",
352                    *ns as f64 / 1e9,
353                    *ns as f64 / 1e6 / *c as f64
354                )
355            })
356            .collect::<Vec<_>>()
357            .join("\n");
358        g.clear();
359        out
360    }
361}
362
363/// Frozen attention operator of one layer — the per-layer dispatch
364/// point for through-backwards (docs/RUST_FCD.md §3).
365enum FcdAttn {
366    Full {
367        /// The projections live in the streamed `LayerMats`, not here:
368        /// eagerly resident weights are what made a 4 B bake swap a
369        /// laptop. Only the small per-head metadata stays.
370        qrows: usize,
371        q_norm: Option<Vec<f32>>,
372        k_norm: Option<Vec<f32>>,
373        bias: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
374        /// (bq|bk|bv) concatenated once at build: the device chain binds
375        /// it by a STABLE address, which is what keeps the fingerprinted
376        /// const cache from minting an entry per call.
377        bias_cat: Option<Vec<f32>>,
378        /// Qwen3.5: wq rows = 2·nh·hd, per-head [q; gate]; the head
379        /// outputs are multiplied by σ(gate) before o_proj.
380        output_gate: bool,
381        /// Spark-X2.5: `self_attn.g_proj` [nh, hidden] — one sigmoid gain
382        /// per Q head from the layer's normed input, multiplied into that
383        /// head's output before o_proj (`attention::apply_projected_gate`).
384        head_gate: Option<Vec<f32>>,
385        /// Sliding-window layer: a query sees its last `w` keys only.
386        window: Option<usize>,
387        /// Local layers rotate with their own table (`inv_freq_local`,
388        /// `rotary_dim_local`) — Gemma-3 / Spark-X2.5 geometry.
389        local_rope: bool,
390    },
391    /// GatedDeltaNet (Qwen3.5 hybrids): never converted, never trained;
392    /// through-backward = BPTT over the window (fcd_ops::gdn_*).
393    Gdn {
394        wqkv: Vec<f32>,
395        wz: Vec<f32>,
396        wa: Vec<f32>,
397        wb: Vec<f32>,
398        conv: Vec<f32>,
399        a_log: Vec<f32>,
400        dt_bias: Vec<f32>,
401        norm: Vec<f32>,
402        wout: Vec<f32>,
403    },
404}
405
406pub(crate) struct FcdLayer {
407    attn: FcdAttn,
408    pub(crate) inter: usize,
409    // Frozen originals: the teacher's LN (small, eager). The big FFN
410    // matrices stream through `LayerMats`.
411    pub(crate) iln: Vec<f32>,
412    pub(crate) pln: Vec<f32>,
413}
414
415/// GDN geometry shared by every linear layer (arch.linear_* fields).
416#[derive(Clone, Copy)]
417struct GdnDims {
418    nv: usize,
419    nk: usize,
420    dk: usize,
421    dv: usize,
422    kk: usize,
423}
424
425impl GdnDims {
426    fn c_dim(&self) -> usize {
427        2 * self.nk * self.dk + self.nv * self.dv
428    }
429    fn vd(&self) -> usize {
430        self.nv * self.dv
431    }
432}
433
434/// The f32 training replica of a .cmf model (≤ 1B targets).
435pub struct FcdModel {
436    pub hidden: usize,
437    pub nh: usize,
438    pub nkv: usize,
439    pub hd: usize,
440    pub nl: usize,
441    pub vocab: usize,
442    pub(crate) eps: f64,
443    pub(crate) gemma: bool,
444    rotary_dim: usize,
445    inv_freq: Vec<f64>,
446    /// Sliding (local) layers' own RoPE geometry when the arch declares
447    /// one (`rope_local_base_freq` / `local_partial_rotary_factor`).
448    rotary_dim_local: Option<usize>,
449    inv_freq_local: Option<Vec<f64>>,
450    /// The FFN gate activation every forward and backward in this file
451    /// and in `skillbake` differentiate.
452    pub(crate) act: FfnAct,
453    /// Keep the per-layer attention activations (needed only by the
454    /// through-attention backward of `cortiq fcd`); the skill bake turns
455    /// this off and the device chain then reads back attn_out alone.
456    pub(crate) attn_acts: bool,
457    /// [vocab, hidden]; also the tied head when `lm_head` is None.
458    pub(crate) embed: Vec<f32>,
459    pub(crate) lm_head: Option<Vec<f32>>,
460    pub(crate) final_norm: Vec<f32>,
461    pub(crate) layers: Vec<FcdLayer>,
462    /// The container the replica came from — the streaming mats
463    /// dequantize from its mmap on demand.
464    pub(crate) src: std::sync::Arc<CmfModel>,
465    /// Per-layer big-matrix cache: filled on touch, evicted outside the
466    /// window. The f32 replica used to hold every matrix of every layer
467    /// eagerly — 16.7 GB for a 4 B model before the fused concats, ~25
468    /// after — which a 24 GB laptop answered with ten minutes of swap.
469    mats_cache: Vec<std::sync::Mutex<Option<std::sync::Arc<LayerMats>>>>,
470    /// cos/sin table for the device attention chain, keyed by t. Arc so
471    /// the underlying address stays STABLE across calls — the GPU const
472    /// cache dedups uploads by (pointer, fingerprint).
473    rope_tab: std::sync::Mutex<Option<((usize, bool), std::sync::Arc<Vec<f32>>)>>,
474    /// How many layers stay resident (0 = all, big machines).
475    mats_window: usize,
476    /// Which layers run the Nyström kernel in the student forward.
477    o1_flags: Vec<bool>,
478    nys: NysCfg,
479    /// GDN geometry (present when the model has linear layers).
480    gdn: Option<GdnDims>,
481    /// Looped Transformer: how many times the layer stack runs per
482    /// token, and whether a final_norm is inserted at each loop
483    /// boundary. A replica that ignores these computes a DIFFERENT
484    /// model — on Nanbeige 4.2 (22 layers x 2 loops) the single-pass
485    /// forward measured perplexity 4773 where the engine reads 16.5,
486    /// and every gradient taken through it was fitted to that fiction.
487    pub(crate) loops: usize,
488    pub(crate) loop_norm: bool,
489    pub(crate) pool: Option<Arc<Pool>>,
490    /// Train the flagged layers WITHOUT switching their attention to the
491    /// Nyström kernel — see `FcdHyper::polish_only`.
492    pub polish_only: bool,
493}
494
495fn deq(model: &CmfModel, name: &str) -> Result<Vec<f32>, String> {
496    let e = model
497        .tensor(name)
498        .ok_or_else(|| format!("tensor '{name}' not found"))?;
499    let mut out = vec![0f32; e.n_elems()];
500    cortiq_core::quant::dequant_tensor(e, model.entry_bytes(e), &mut out)?;
501    Ok(out)
502}
503
504/// Physical RAM total, for the hard replica ceiling.
505/// The container's own memory ceiling, when it has one.
506///
507/// `/proc/meminfo` reports the HOST inside a container. On a rented box
508/// that is the difference between the 944 GB `free` prints and the
509/// 117 GB the cgroup will actually hand out, and believing the larger
510/// number is an OOM kill one allocation later — which is exactly how a
511/// 27B bake died: it read 944 GB, concluded the f32 replica fit with
512/// room to spare, and never streamed a single layer.
513#[cfg(target_os = "linux")]
514fn cgroup_limit_bytes() -> Option<u64> {
515    let read =
516        |p: &str| -> Option<u64> { std::fs::read_to_string(p).ok()?.trim().parse::<u64>().ok() };
517    // v2 first, then v1. An unlimited v2 cgroup holds the word "max",
518    // which fails to parse; an unlimited v1 holds a huge sentinel.
519    read("/sys/fs/cgroup/memory.max")
520        .or_else(|| read("/sys/fs/cgroup/memory/memory.limit_in_bytes"))
521        .filter(|&v| v < u64::MAX / 2)
522}
523
524/// Which flagged layers survive.
525///
526/// For an O(1) conversion only full-attention layers are eligible — a
527/// GDN layer keeps its own operator. Under `polish_only` the flag means
528/// "train this layer's FFN and norms", which any layer supports, so the
529/// filter must not run: on a hybrid it silently shrank `--o1 deep8` to
530/// the two or three full-attention layers that happened to fall in the
531/// window, and 48 of Qwen3.8-27B's 64 layers are GDN.
532pub(crate) fn apply_layer_eligibility(flags: &mut [bool], is_full: &[bool], polish_only: bool) {
533    if polish_only {
534        return;
535    }
536    for (li, f) in flags.iter_mut().enumerate() {
537        if *f && !is_full.get(li).copied().unwrap_or(false) {
538            *f = false;
539        }
540    }
541}
542
543/// The lower of what the host reports and what the container will hand
544/// out. Pure so the decision can be tested without a cgroup to hand.
545pub(crate) fn effective_total(host: u64, cgroup_limit: Option<u64>) -> u64 {
546    match cgroup_limit {
547        Some(l) => host.min(l),
548        None => host,
549    }
550}
551
552/// Headroom: inside a cgroup it is the limit minus what the cgroup
553/// already holds, never whatever the host happens to have free.
554pub(crate) fn effective_available(host: u64, limit: Option<u64>, used: Option<u64>) -> u64 {
555    match (limit, used) {
556        (Some(l), Some(u)) => host.min(l.saturating_sub(u)),
557        (Some(l), None) => host.min(l),
558        _ => host,
559    }
560}
561
562/// Bytes this cgroup is already holding, for the same reason.
563#[cfg(target_os = "linux")]
564fn cgroup_used_bytes() -> Option<u64> {
565    let read =
566        |p: &str| -> Option<u64> { std::fs::read_to_string(p).ok()?.trim().parse::<u64>().ok() };
567    read("/sys/fs/cgroup/memory.current")
568        .or_else(|| read("/sys/fs/cgroup/memory/memory.usage_in_bytes"))
569}
570
571/// Physical RAM total — the cgroup's limit when the container has a lower
572/// one. Also the ceiling `quantize-gptq` plans its Hessian RAM against.
573pub fn physical_total_bytes() -> Option<u64> {
574    #[cfg(target_os = "macos")]
575    {
576        let out = std::process::Command::new("sysctl")
577            .args(["-n", "hw.memsize"])
578            .output()
579            .ok()?;
580        return String::from_utf8_lossy(&out.stdout).trim().parse().ok();
581    }
582    #[cfg(target_os = "linux")]
583    {
584        let mem = std::fs::read_to_string("/proc/meminfo").ok()?;
585        let kb: u64 = mem
586            .lines()
587            .find(|l| l.starts_with("MemTotal:"))?
588            .split_whitespace()
589            .nth(1)?
590            .parse()
591            .ok()?;
592        return Some(effective_total(kb * 1024, cgroup_limit_bytes()));
593    }
594    #[allow(unreachable_code)]
595    None
596}
597
598/// AVAILABLE RAM in bytes, best effort — used only to refuse a bake
599/// whose f32 replica would swap instead of run.
600pub(crate) fn available_ram_bytes() -> Option<u64> {
601    #[cfg(target_os = "macos")]
602    {
603        // free% × total from the same counters the memory-pressure
604        // subsystem uses; hw.memsize alone lied by whatever the other
605        // apps were holding.
606        let total: u64 = {
607            let out = std::process::Command::new("sysctl")
608                .args(["-n", "hw.memsize"])
609                .output()
610                .ok()?;
611            String::from_utf8_lossy(&out.stdout).trim().parse().ok()?
612        };
613        let out = std::process::Command::new("memory_pressure")
614            .arg("-Q")
615            .output()
616            .ok()?;
617        let text = String::from_utf8_lossy(&out.stdout);
618        let pct: u64 = text
619            .lines()
620            .find(|l| l.contains("free percentage"))?
621            .split(':')
622            .nth(1)?
623            .trim()
624            .trim_end_matches('%')
625            .parse()
626            .ok()?;
627        return Some(total / 100 * pct);
628    }
629    #[cfg(target_os = "linux")]
630    {
631        let mem = std::fs::read_to_string("/proc/meminfo").ok()?;
632        let kb: u64 = mem
633            .lines()
634            .find(|l| l.starts_with("MemAvailable:"))?
635            .split_whitespace()
636            .nth(1)?
637            .parse()
638            .ok()?;
639        // Inside a cgroup, headroom is the limit minus what it already
640        // holds, not whatever the host happens to have free.
641        return Some(effective_available(
642            kb * 1024,
643            cgroup_limit_bytes(),
644            cgroup_used_bytes(),
645        ));
646    }
647    #[allow(unreachable_code)]
648    None
649}
650
651/// `deq` for sibling modules (the bake's Phase-B masters dequant once,
652/// straight from the source container).
653pub(crate) fn deq_pub(model: &CmfModel, name: &str) -> Result<Vec<f32>, String> {
654    deq(model, name)
655}
656
657/// The four big matrices the hot path reads for one layer, dequantized
658/// together: the fused attention projection, the attention output, the
659/// fused FFN gate+up, and the FFN down. Everything else a layer owns —
660/// norms, biases, GDN cores — is small and stays eagerly resident.
661pub(crate) struct LayerMats {
662    pub(crate) wqkv: Vec<f32>,
663    pub(crate) wo: Vec<f32>,
664    pub(crate) gu: Vec<f32>,
665    pub(crate) down: Vec<f32>,
666}
667
668impl FcdModel {
669    /// The layer's big matrices, dequantized on first touch. Sequential
670    /// sweeps (forward 0..nl, backward nl..0) hit the same physical
671    /// layer at most twice per virtual pass, so a small window streams
672    /// a model far bigger than RAM without swapping.
673    pub(crate) fn mats(&self, li: usize) -> Result<std::sync::Arc<LayerMats>, String> {
674        {
675            let slot = self.mats_cache[li].lock().unwrap();
676            if let Some(m) = slot.as_ref() {
677                return Ok(m.clone());
678            }
679        }
680        let p = format!("model.layers.{li}.");
681        let d = |name: String| -> Result<Vec<f32>, String> { deq(&self.src, &name) };
682        let built = if matches!(self.layers[li].attn, FcdAttn::Full { .. }) {
683            let wq = d(format!("{p}self_attn.q_proj.weight"))?;
684            let wk = d(format!("{p}self_attn.k_proj.weight"))?;
685            let wv = d(format!("{p}self_attn.v_proj.weight"))?;
686            let mut wqkv = Vec::with_capacity(wq.len() + wk.len() + wv.len());
687            wqkv.extend_from_slice(&wq);
688            wqkv.extend_from_slice(&wk);
689            wqkv.extend_from_slice(&wv);
690            let gate = d(format!("{p}mlp.gate_proj.weight"))?;
691            let up = d(format!("{p}mlp.up_proj.weight"))?;
692            let mut gu = Vec::with_capacity(gate.len() + up.len());
693            gu.extend_from_slice(&gate);
694            gu.extend_from_slice(&up);
695            LayerMats {
696                wqkv,
697                wo: d(format!("{p}self_attn.o_proj.weight"))?,
698                gu,
699                down: d(format!("{p}mlp.down_proj.weight"))?,
700            }
701        } else {
702            // GDN layers keep their attention core eagerly; only the FFN
703            // streams.
704            let gate = d(format!("{p}mlp.gate_proj.weight"))?;
705            let up = d(format!("{p}mlp.up_proj.weight"))?;
706            let mut gu = Vec::with_capacity(gate.len() + up.len());
707            gu.extend_from_slice(&gate);
708            gu.extend_from_slice(&up);
709            LayerMats {
710                wqkv: Vec::new(),
711                wo: Vec::new(),
712                gu,
713                down: d(format!("{p}mlp.down_proj.weight"))?,
714            }
715        };
716        let arc = std::sync::Arc::new(built);
717        *self.mats_cache[li].lock().unwrap() = Some(arc.clone());
718        // Evict outside the window — cheap, and the access pattern is
719        // sequential, so the evicted slots are exactly the cold ones.
720        if self.mats_window > 0 {
721            let w = self.mats_window;
722            for (j, slot) in self.mats_cache.iter().enumerate() {
723                let dist = li.abs_diff(j).min(self.layers.len() - li.abs_diff(j));
724                if dist > w {
725                    *slot.lock().unwrap() = None;
726                }
727            }
728        }
729        Ok(arc)
730    }
731}
732
733impl FcdModel {
734    /// Dequantize a model into the f32 training replica. Refuses what
735    /// the backward cannot honestly differentiate yet (loud, not silent).
736    pub fn from_cmf(
737        model: &std::sync::Arc<CmfModel>,
738        o1: &O1Cfg,
739        polish_only: bool,
740    ) -> Result<Self, String> {
741        let arch = model.arch().clone();
742        let act = FfnAct::from_arch(&arch.hidden_act).ok_or_else(|| {
743            format!(
744                "fcd/skill-bake: hidden_act '{}' not supported yet (silu | gelu)",
745                arch.hidden_act
746            )
747        })?;
748        let has_linear = arch
749            .layer_types
750            .iter()
751            .any(|t| matches!(t, LayerType::LinearAttention));
752        let gdn = if has_linear {
753            let lc = arch
754                .linear_core
755                .as_ref()
756                .ok_or_else(|| "model has linear layers but no arch.linear_core".to_string())?;
757            if lc.kind != "gated_delta_net" {
758                return Err(format!(
759                    "linear core '{}' has no FCD backward (only gated_delta_net)",
760                    lc.kind
761                ));
762            }
763            Some(GdnDims {
764                nv: lc.num_heads,
765                nk: arch
766                    .linear_num_key_heads
767                    .ok_or("linear core needs arch.linear_num_key_heads")?,
768                dk: arch
769                    .linear_key_head_dim
770                    .ok_or("linear core needs arch.linear_key_head_dim")?,
771                dv: lc.value_head_dim,
772                kk: arch
773                    .linear_conv_kernel_dim
774                    .ok_or("linear core needs arch.linear_conv_kernel_dim")?,
775            })
776        } else {
777            None
778        };
779        let (nh, nkv, hd, h) = (
780            arch.num_attention_heads,
781            arch.num_kv_heads,
782            arch.head_dim,
783            arch.hidden_size,
784        );
785        let embed = deq(model, "model.embed_tokens.weight")?;
786        let lm_head = if model.tensor("lm_head.weight").is_some() {
787            Some(deq(model, "lm_head.weight")?)
788        } else if arch.tie_word_embeddings {
789            None
790        } else {
791            return Err("no lm_head.weight and tie_word_embeddings is false".into());
792        };
793        let final_norm = deq(model, "model.norm.weight")?;
794
795        let mut layers = Vec::with_capacity(arch.num_layers);
796        for li in 0..arch.num_layers {
797            let p = format!("model.layers.{li}.");
798            if model.tensor(&format!("{p}mlp.gate.weight")).is_some() {
799                return Err(format!(
800                    "layer {li} is MoE — FCD polish supports dense FFN only"
801                ));
802            }
803            let attn = match arch.layer_types.get(li) {
804                Some(LayerType::LinearAttention) => {
805                    let la = |n: &str| deq(model, &format!("{p}linear_attn.{n}"));
806                    FcdAttn::Gdn {
807                        wqkv: la("in_proj_qkv.weight")?,
808                        wz: la("in_proj_z.weight")?,
809                        wa: la("in_proj_a.weight")?,
810                        wb: la("in_proj_b.weight")?,
811                        conv: la("conv1d.weight")?,
812                        a_log: la("A_log")?,
813                        dt_bias: la("dt_bias")?,
814                        norm: la("norm.weight")?,
815                        wout: la("out_proj.weight")?,
816                    }
817                }
818                _ => {
819                    let wq = deq(model, &format!("{p}self_attn.q_proj.weight"))?;
820                    let output_gate = wq.len() == 2 * nh * hd * h;
821                    let opt = |n: &str| -> Option<Vec<f32>> {
822                        model
823                            .tensor(&format!("{p}self_attn.{n}"))
824                            .and_then(|_| deq(model, &format!("{p}self_attn.{n}")).ok())
825                    };
826                    let bias = match (opt("q_proj.bias"), opt("k_proj.bias"), opt("v_proj.bias")) {
827                        (Some(a), Some(b), Some(c)) => Some((a, b, c)),
828                        _ => None,
829                    };
830                    let qrows = wq.len() / h;
831                    drop(wq);
832                    let bias_cat = bias.as_ref().map(|(bq, bk, bv)| {
833                        let mut v = Vec::with_capacity(bq.len() + bk.len() + bv.len());
834                        v.extend_from_slice(bq);
835                        v.extend_from_slice(bk);
836                        v.extend_from_slice(bv);
837                        v
838                    });
839                    // A projected output gate rides in one form: one row
840                    // per Q head with a sigmoid (Spark-X2.5). A per-element
841                    // or softplus gate has no trainer path yet — loud.
842                    let head_gate = match opt("g_proj.weight") {
843                        None => None,
844                        Some(g) if g.len() == nh * h => Some(g),
845                        Some(g) => {
846                            return Err(format!(
847                                "layer {li}: self_attn.g_proj has {} values; only a per-head gate (nh·hidden = {}) is supported",
848                                g.len(),
849                                nh * h
850                            ));
851                        }
852                    };
853                    let sliding = matches!(arch.layer_types.get(li), Some(LayerType::SlidingAttention));
854                    let window = if sliding {
855                        Some(arch.sliding_window.ok_or_else(|| {
856                            format!("layer {li} is SlidingAttention but arch.sliding_window is unset")
857                        })?)
858                    } else {
859                        None
860                    };
861                    FcdAttn::Full {
862                        qrows,
863                        q_norm: opt("q_norm.weight"),
864                        k_norm: opt("k_norm.weight"),
865                        bias,
866                        bias_cat,
867                        output_gate,
868                        head_gate,
869                        window,
870                        local_rope: sliding,
871                    }
872                }
873            };
874            let gate = deq(model, &format!("{p}mlp.gate_proj.weight"))?;
875            let inter = gate.len() / h;
876            drop(gate);
877            layers.push(FcdLayer {
878                attn,
879                inter,
880                iln: deq(model, &format!("{p}input_layernorm.weight"))?,
881                pln: deq(model, &format!("{p}post_attention_layernorm.weight"))?,
882            });
883        }
884
885        let rotary_dim = ((hd as f32 * arch.partial_rotary_factor) as usize)
886            .max(2)
887            .min(hd);
888        let base = arch.rope_theta;
889        let inv_freq: Vec<f64> = (0..rotary_dim / 2)
890            .map(|i| 1.0 / base.powf(2.0 * i as f64 / rotary_dim as f64))
891            .collect();
892        // Local (sliding) layers: the runtime's rule (`loader.rs`) — their
893        // rotary width follows `local_partial_rotary_factor` (else the
894        // global factor) and their table `rope_local_base_freq` when set.
895        let any_sliding = arch
896            .layer_types
897            .iter()
898            .any(|t| matches!(t, LayerType::SlidingAttention));
899        let rotary_dim_local = any_sliding.then(|| {
900            ((hd as f32 * arch.local_partial_rotary_factor.unwrap_or(arch.partial_rotary_factor))
901                as usize)
902                .max(2)
903                .min(hd)
904        });
905        let inv_freq_local = match (rotary_dim_local, arch.rope_local_base_freq) {
906            (Some(rd), Some(lb)) => Some(
907                (0..rd / 2)
908                    .map(|i| 1.0 / lb.powf(2.0 * i as f64 / rd as f64))
909                    .collect::<Vec<f64>>(),
910            ),
911            _ => None,
912        };
913        let loops = arch.num_loops.max(1);
914        let loop_norm = arch.loop_final_norm;
915        let mut flags = o1.layer_flags(arch.num_layers);
916        flags.resize(arch.num_layers, false);
917        // Only full-attention layers are o1-convertible (same rule as
918        // Pipeline::set_o1) — a GDN layer keeps its own operator. Under
919        // `polish_only` the flag means "train this layer's FFN and
920        // norms", which a GDN layer supports like any other: its own
921        // operator stays frozen and the backward already carries the
922        // through-gradient. Excluding them there would silently shrink
923        // `--o1 deep8` on a hybrid to the two or three full-attention
924        // layers that happen to fall in the window.
925        {
926            let is_full: Vec<bool> = layers
927                .iter()
928                .map(|l| matches!(l.attn, FcdAttn::Full { .. }))
929                .collect();
930            apply_layer_eligibility(&mut flags, &is_full, polish_only);
931        }
932        // Streaming window: how many layers' big matrices stay resident.
933        // Sized from available memory; CMF_BAKE_MATS_LAYERS overrides.
934        // 0 = everything resident (big machines keep today's speed).
935        let per_layer: u64 = layers
936            .first()
937            .map(|_| {
938                let qrows = match layers[0].attn {
939                    FcdAttn::Full { qrows, .. } => qrows,
940                    _ => 0,
941                };
942                ((qrows + 2 * (nkv * hd)) as u64 * h as u64      // wqkv
943                    + (h as u64 * nh as u64 * hd as u64)          // wo
944                    + 3 * (layers[0].inter as u64 * h as u64))    // gu + down
945                    * 4
946            })
947            .unwrap_or(0);
948        let mats_window = if let Ok(v) = std::env::var("CMF_BAKE_MATS_LAYERS") {
949            v.parse().unwrap_or(0)
950        } else {
951            let avail = available_ram_bytes().unwrap_or(u64::MAX);
952            let cap = physical_total_bytes()
953                .map(|t| t / 5 * 3)
954                .unwrap_or(u64::MAX)
955                .min(avail.saturating_sub(avail / 10));
956            let all = per_layer.saturating_mul(arch.num_layers as u64);
957            if all + 4 * 1024 * 1024 * 1024 <= cap {
958                0 // everything fits with headroom — stay eager-equivalent
959            } else {
960                let w = (cap.saturating_sub(3 * 1024 * 1024 * 1024) / per_layer.max(1))
961                    .clamp(2, arch.num_layers as u64) as usize;
962                tracing::info!(
963                    "fcd replica: streaming {w} of {} layers (~{:.1} GB resident of ~{:.1} GB total)",
964                    arch.num_layers,
965                    (w as u64 * per_layer) as f64 / 1e9,
966                    all as f64 / 1e9,
967                );
968                w
969            }
970        };
971        let mats_cache = (0..arch.num_layers)
972            .map(|_| std::sync::Mutex::new(None))
973            .collect();
974        Ok(Self {
975            src: model.clone(),
976            mats_cache,
977            rope_tab: std::sync::Mutex::new(None),
978            mats_window,
979            hidden: h,
980            nh,
981            nkv,
982            hd,
983            nl: arch.num_layers,
984            vocab: arch.vocab_size.min(embed.len() / h),
985            eps: arch.rms_norm_eps,
986            gemma: matches!(arch.norm_style, NormStyle::Gemma),
987            rotary_dim,
988            inv_freq,
989            rotary_dim_local,
990            inv_freq_local,
991            act,
992            attn_acts: true,
993            embed,
994            lm_head,
995            final_norm,
996            layers,
997            o1_flags: flags,
998            // prefill: None = half the window, the same seal point
999            // `cortiq ppl --o1` defaults to (see NysCfg::prefill).
1000            nys: NysCfg {
1001                m: o1.m,
1002                w: o1.w,
1003                sink: o1.sink,
1004                prefill: None,
1005            },
1006            gdn,
1007            loops,
1008            loop_norm,
1009            pool: Pool::from_env(),
1010            polish_only: false,
1011        })
1012    }
1013
1014    /// Converted (trainable) layer indices.
1015    pub fn converted(&self) -> Vec<usize> {
1016        (0..self.nl).filter(|&i| self.o1_flags[i]).collect()
1017    }
1018
1019    fn head_weight(&self) -> &[f32] {
1020        self.lm_head.as_deref().unwrap_or(&self.embed)
1021    }
1022}
1023
1024// ───────────────────────── trainable state ─────────────────────────
1025
1026/// Per converted layer, in this fixed order.
1027const PARAMS_PER_LAYER: usize = 5; // iln, pln, gate, up, down
1028
1029/// Master copies + grads + AdamW moments of the trainable tensors.
1030pub struct TrainState {
1031    pub layers: Vec<usize>,
1032    /// layers.len()·5 tensors, layer-major, [iln, pln, gate, up, down].
1033    pub data: Vec<Vec<f32>>,
1034    grad: Vec<Vec<f32>>,
1035    m1: Vec<Vec<f32>>,
1036    m2: Vec<Vec<f32>>,
1037    step_t: u64,
1038}
1039
1040impl TrainState {
1041    pub fn new(fm: &FcdModel) -> Self {
1042        let layers = fm.converted();
1043        let mut data = Vec::with_capacity(layers.len() * PARAMS_PER_LAYER);
1044        for &li in &layers {
1045            let l = &fm.layers[li];
1046            let p = format!("model.layers.{li}.");
1047            data.push(l.iln.clone());
1048            data.push(l.pln.clone());
1049            // Trained masters dequant once, straight from the source —
1050            // the streamed cache holds only the fused hot-path concats.
1051            data.push(deq(&fm.src, &format!("{p}mlp.gate_proj.weight")).expect("gate"));
1052            data.push(deq(&fm.src, &format!("{p}mlp.up_proj.weight")).expect("up"));
1053            data.push(deq(&fm.src, &format!("{p}mlp.down_proj.weight")).expect("down"));
1054        }
1055        let zeros: Vec<Vec<f32>> = data.iter().map(|d| vec![0f32; d.len()]).collect();
1056        Self {
1057            layers,
1058            grad: zeros.clone(),
1059            m1: zeros.clone(),
1060            m2: zeros,
1061            data,
1062            step_t: 0,
1063        }
1064    }
1065
1066    fn slot(&self, li: usize) -> Option<usize> {
1067        self.layers.iter().position(|&x| x == li)
1068    }
1069
1070    /// Read access to the accumulated gradients (gradcheck harness).
1071    #[doc(hidden)]
1072    pub fn grads(&self) -> &[Vec<f32>] {
1073        &self.grad
1074    }
1075
1076    fn zero_grad(&mut self) {
1077        for g in &mut self.grad {
1078            for v in g.iter_mut() {
1079                *v = 0.0;
1080            }
1081        }
1082    }
1083
1084    /// Global-norm clip (1.0) + one AdamW step (torch defaults,
1085    /// decoupled weight decay).
1086    fn clip_and_step(&mut self, lr: f64) -> f64 {
1087        let mut sq = 0f64;
1088        for g in &self.grad {
1089            for &v in g {
1090                sq += (v as f64) * (v as f64);
1091            }
1092        }
1093        let gn = sq.sqrt();
1094        let scale = if gn > 1.0 { 1.0 / (gn + 1e-6) } else { 1.0 };
1095        self.step_t += 1;
1096        let bc1 = 1.0 - ADAM_B1.powi(self.step_t as i32);
1097        let bc2 = 1.0 - ADAM_B2.powi(self.step_t as i32);
1098        for p in 0..self.data.len() {
1099            let (d, g, m, v) = (
1100                &mut self.data[p],
1101                &self.grad[p],
1102                &mut self.m1[p],
1103                &mut self.m2[p],
1104            );
1105            for i in 0..d.len() {
1106                let gi = g[i] as f64 * scale;
1107                let mi = ADAM_B1 * m[i] as f64 + (1.0 - ADAM_B1) * gi;
1108                let vi = ADAM_B2 * v[i] as f64 + (1.0 - ADAM_B2) * gi * gi;
1109                m[i] = mi as f32;
1110                v[i] = vi as f32;
1111                let upd = (mi / bc1) / ((vi / bc2).sqrt() + ADAM_EPS) + ADAM_WD * d[i] as f64;
1112                d[i] = (d[i] as f64 - lr * upd) as f32;
1113            }
1114        }
1115        gn
1116    }
1117}
1118
1119/// LN/FFN weight view of one layer — frozen originals for the teacher
1120/// (and non-converted student layers), master copies for trainables.
1121#[derive(Clone, Copy)]
1122pub(crate) struct LnFfn<'a> {
1123    pub(crate) iln: &'a [f32],
1124    pub(crate) pln: &'a [f32],
1125    pub(crate) gate: &'a [f32],
1126    pub(crate) up: &'a [f32],
1127    pub(crate) down: &'a [f32],
1128    /// `[gate; up]` rows concatenated — one GEMM submit instead of two.
1129    /// `None` for Phase-B trained copies, whose rows move every step;
1130    /// the frozen majority carries the concat prebuilt at load.
1131    pub(crate) gu: Option<&'a [f32]>,
1132}
1133
1134fn ln_ffn<'a>(
1135    fm: &'a FcdModel,
1136    ts: Option<&'a TrainState>,
1137    li: usize,
1138    mats: &'a LayerMats,
1139) -> LnFfn<'a> {
1140    if let Some(t) = ts {
1141        if let Some(s) = t.slot(li) {
1142            let b = s * PARAMS_PER_LAYER;
1143            return LnFfn {
1144                iln: &t.data[b],
1145                pln: &t.data[b + 1],
1146                gate: &t.data[b + 2],
1147                up: &t.data[b + 3],
1148                down: &t.data[b + 4],
1149                gu: None,
1150            };
1151        }
1152    }
1153    let l = &fm.layers[li];
1154    LnFfn {
1155        iln: &l.iln,
1156        pln: &l.pln,
1157        // The fused concat carries both projections; the fallback slots
1158        // are never read while `gu` is Some.
1159        gate: &[],
1160        up: &[],
1161        down: &mats.down,
1162        gu: Some(&mats.gu),
1163    }
1164}
1165
1166// ───────────────────── layer forward (+ recompute) ─────────────────────
1167
1168/// Intra-layer activations rebuilt during the checkpointed backward.
1169enum AttnActs {
1170    Full {
1171        qpre: Vec<f32>,
1172        kpre: Vec<f32>,
1173        vproj: Vec<f32>,
1174        qrot: Vec<f32>,
1175        krot: Vec<f32>,
1176        qinv: Vec<f32>,
1177        kinv: Vec<f32>,
1178        /// Pre-gate per-head attention outputs (needed for the output
1179        /// gate's backward); always kept — transient per layer.
1180        ao: Vec<f32>,
1181        /// Raw gate half of q_proj (empty without an output gate).
1182        gate_pre: Vec<f32>,
1183        /// Per-(row, head) sigmoid gains of a projected head gate (empty
1184        /// without one). Frozen weights: the backward scales by the gain
1185        /// and does not chase the gate's own input.
1186        head_gain: Vec<f32>,
1187    },
1188    /// Raw projection streams — the GDN backward replays conv + the
1189    /// recurrence from these.
1190    Gdn {
1191        qkv: Vec<f32>,
1192        z: Vec<f32>,
1193        a: Vec<f32>,
1194        b: Vec<f32>,
1195    },
1196}
1197
1198/// Trained attention weights of a full-layer FCD layer, in place of the
1199/// frozen `LayerMats`/head gate for one forward.
1200#[derive(Clone, Copy)]
1201pub(crate) struct AttnW<'a> {
1202    pub(crate) wqkv: &'a [f32],
1203    pub(crate) wo: &'a [f32],
1204    pub(crate) head_gate: Option<&'a [f32]>,
1205}
1206
1207pub(crate) struct LayerActs {
1208    pub(crate) inv1: Vec<f32>,
1209    attn: AttnActs,
1210    pub(crate) h1: Vec<f32>,
1211    pub(crate) n2: Vec<f32>,
1212    pub(crate) inv2: Vec<f32>,
1213    pub(crate) gpre: Vec<f32>,
1214    pub(crate) upre: Vec<f32>,
1215    pub(crate) act: Vec<f32>,
1216}
1217
1218impl LayerActs {
1219    /// The full-attention activations a full-layer FCD backward needs:
1220    /// (qrot, krot, vproj, ao, head_gain) — None for GDN layers or when
1221    /// the forward did not keep them.
1222    pub(crate) fn attn_full(&self) -> Option<(&[f32], &[f32], &[f32], &[f32], &[f32])> {
1223        match &self.attn {
1224            AttnActs::Full {
1225                qrot,
1226                krot,
1227                vproj,
1228                ao,
1229                head_gain,
1230                ..
1231            } if !qrot.is_empty() => Some((qrot, krot, vproj, ao, head_gain)),
1232            _ => None,
1233        }
1234    }
1235}
1236
1237/// Disjoint-write pointer for pooled per-head scatter (pipeline pattern).
1238struct SendMut<T>(*mut T);
1239unsafe impl<T> Send for SendMut<T> {}
1240unsafe impl<T> Sync for SendMut<T> {}
1241impl<T> SendMut<T> {
1242    #[inline]
1243    unsafe fn at(&self, i: usize) -> *mut T {
1244        unsafe { self.0.add(i) }
1245    }
1246}
1247
1248
1249/// Split `[0, n)` into one contiguous range per pool worker and run `f(lo, hi)`
1250/// on each — the shape of every row-wise host op below (norms, residual adds,
1251/// plane copies), which were single-threaded memory walks over hundreds of MB.
1252pub(crate) fn pooled_rows(n: usize, pool: Option<&Pool>, f: &(dyn Fn(usize, usize) + Sync)) {
1253    match pool {
1254        Some(p) if n >= 64 => p.run(&|w, nw| {
1255            let lo = n * w / nw;
1256            let hi = n * (w + 1) / nw;
1257            if hi > lo {
1258                f(lo, hi);
1259            }
1260        }),
1261        _ => f(0, n),
1262    }
1263}
1264
1265/// `ops::rmsnorm_fwd` over row ranges in parallel.
1266pub(crate) fn rmsnorm_fwd_pooled(
1267    x: &[f32],
1268    w: &[f32],
1269    eps: f64,
1270    gemma: bool,
1271    y: &mut [f32],
1272    inv: &mut [f32],
1273    pool: Option<&Pool>,
1274) {
1275    let d = w.len();
1276    let n = x.len() / d;
1277    let yp = SendMut(y.as_mut_ptr());
1278    let ip = SendMut(inv.as_mut_ptr());
1279    pooled_rows(n, pool, &|lo, hi| {
1280        // SAFETY: disjoint row ranges per worker.
1281        let (yr, ir) = unsafe {
1282            (
1283                std::slice::from_raw_parts_mut(yp.at(lo * d), (hi - lo) * d),
1284                std::slice::from_raw_parts_mut(ip.at(lo), hi - lo),
1285            )
1286        };
1287        ops::rmsnorm_fwd(&x[lo * d..hi * d], w, eps, gemma, yr, ir);
1288    });
1289}
1290
1291/// `ops::rmsnorm_bwd` (through-grad only, frozen gain) over row ranges in parallel.
1292pub(crate) fn rmsnorm_bwd_pooled(
1293    x: &[f32],
1294    w: &[f32],
1295    inv: &[f32],
1296    dy: &[f32],
1297    gemma: bool,
1298    dx: &mut [f32],
1299    pool: Option<&Pool>,
1300) {
1301    let d = w.len();
1302    let n = x.len() / d;
1303    let dp = SendMut(dx.as_mut_ptr());
1304    pooled_rows(n, pool, &|lo, hi| {
1305        // SAFETY: disjoint row ranges per worker.
1306        let dxr = unsafe { std::slice::from_raw_parts_mut(dp.at(lo * d), (hi - lo) * d) };
1307        ops::rmsnorm_bwd(&x[lo * d..hi * d], w, &inv[lo..hi], &dy[lo * d..hi * d], gemma, dxr, None);
1308    });
1309}
1310
1311/// `a += b`, elementwise, in parallel.
1312pub(crate) fn add_into_pooled(a: &mut [f32], b: &[f32], pool: Option<&Pool>) {
1313    let n = a.len().min(b.len());
1314    let ap = SendMut(a.as_mut_ptr());
1315    const CHUNK: usize = 4096;
1316    let chunks = n.div_ceil(CHUNK);
1317    pooled_rows(chunks, pool, &|lo, hi| {
1318        let (s, e) = (lo * CHUNK, (hi * CHUNK).min(n));
1319        // SAFETY: disjoint element ranges per worker.
1320        let ar = unsafe { std::slice::from_raw_parts_mut(ap.at(s), e - s) };
1321        for (x, &y) in ar.iter_mut().zip(&b[s..e]) {
1322            *x += y;
1323        }
1324    });
1325}
1326
1327/// `act[r] = f(gpre[r]) ⊙ upre[r]` over `n` rows of `inter`, pooled: the
1328/// erf GELU is not free (63 M elements per 4 B training step), and one
1329/// thread walking it was the slowest link of a Spark bake.
1330/// The bake's frozen FFN chain on the device: CUDA's (`gpu_cuda::bake_ffn_fwd`)
1331/// when that is the backend, else wgpu's (`gpu_wgpu::ffn_chain_f32`).
1332#[cfg(feature = "gpu")]
1333#[allow(clippy::too_many_arguments)]
1334pub(crate) fn bake_ffn_chain(
1335    n2: &[f32],
1336    gu: &[f32],
1337    down: &[f32],
1338    scale: Option<&[f32]>,
1339    both_out: Option<&mut [f32]>,
1340    plane: Option<usize>,
1341    ffn: &mut [f32],
1342    n: usize,
1343    hsz: usize,
1344    inter: usize,
1345    act: FfnAct,
1346) -> bool {
1347    #[cfg(feature = "cuda")]
1348    if crate::gpu::cuda_active() {
1349        return crate::gpu_cuda::bake_ffn_fwd(n2, gu, down, scale, both_out, plane, ffn, n, hsz, inter, act);
1350    }
1351    crate::gpu_wgpu::ffn_chain_f32(n2, gu, down, scale, both_out, plane, ffn, n, hsz, inter, act)
1352}
1353
1354/// The backward twin of [`bake_ffn_chain`] from the plane its forward kept.
1355#[cfg(feature = "gpu")]
1356#[allow(clippy::too_many_arguments)]
1357pub(crate) fn bake_ffn_bwd_chain(
1358    dh2: &[f32],
1359    down: &[f32],
1360    gu: &[f32],
1361    li: usize,
1362    dn2: &mut [f32],
1363    n: usize,
1364    hsz: usize,
1365    inter: usize,
1366    act: FfnAct,
1367    scale: Option<&[f32]>,
1368    dmask: Option<&mut [f32]>,
1369) -> bool {
1370    #[cfg(feature = "cuda")]
1371    if crate::gpu::cuda_active() {
1372        return crate::gpu_cuda::bake_ffn_bwd(dh2, down, gu, li, dn2, n, hsz, inter, act, scale, dmask);
1373    }
1374    crate::gpu_wgpu::ffn_bwd_chain_f32(dh2, down, gu, li, dn2, n, hsz, inter, act, scale, dmask)
1375}
1376
1377pub(crate) fn act_mul_rows(
1378    f: FfnAct,
1379    gpre: &[f32],
1380    upre: &[f32],
1381    act: &mut [f32],
1382    n: usize,
1383    inter: usize,
1384    pool: Option<&Pool>,
1385) {
1386    let row = |r: usize, out: &mut [f32]| {
1387        let g = &gpre[r * inter..(r + 1) * inter];
1388        let u = &upre[r * inter..(r + 1) * inter];
1389        for ((o, &gv), &uv) in out.iter_mut().zip(g).zip(u) {
1390            *o = f.fwd(gv) * uv;
1391        }
1392    };
1393    match pool {
1394        Some(p) if n > 1 => {
1395            let ap = SendMut(act.as_mut_ptr());
1396            p.run(&|w, nw| {
1397                for r in (w..n).step_by(nw) {
1398                    // SAFETY: disjoint row slices per worker.
1399                    let out = unsafe { std::slice::from_raw_parts_mut(ap.at(r * inter), inter) };
1400                    row(r, out);
1401                }
1402            });
1403        }
1404        _ => {
1405            for r in 0..n {
1406                row(r, &mut act[r * inter..(r + 1) * inter]);
1407            }
1408        }
1409    }
1410}
1411
1412/// The backward of `act_mul_rows` with an optional per-neuron scale `s`
1413/// (the DTG-MA gate the forward multiplied in after the activation):
1414/// `dg = dact·s·u·f′(g)`, `du = dact·s·f(g)`. Pooled like the forward.
1415#[allow(clippy::too_many_arguments)]
1416pub(crate) fn act_bwd_rows(
1417    f: FfnAct,
1418    gpre: &[f32],
1419    upre: &[f32],
1420    dact: &[f32],
1421    scale: Option<&[f32]>,
1422    dg: &mut [f32],
1423    du: &mut [f32],
1424    n: usize,
1425    inter: usize,
1426    pool: Option<&Pool>,
1427) {
1428    let row = |r: usize, dg: &mut [f32], du: &mut [f32]| {
1429        let base = r * inter;
1430        for j in 0..inter {
1431            let i = base + j;
1432            let da = dact[i] * scale.map(|s| s[j]).unwrap_or(1.0);
1433            dg[j] = da * upre[i] * f.bwd(gpre[i]);
1434            du[j] = da * f.fwd(gpre[i]);
1435        }
1436    };
1437    match pool {
1438        Some(p) if n > 1 => {
1439            let gp = SendMut(dg.as_mut_ptr());
1440            let up = SendMut(du.as_mut_ptr());
1441            p.run(&|w, nw| {
1442                for r in (w..n).step_by(nw) {
1443                    // SAFETY: disjoint row slices per worker.
1444                    let (dgr, dur) = unsafe {
1445                        (
1446                            std::slice::from_raw_parts_mut(gp.at(r * inter), inter),
1447                            std::slice::from_raw_parts_mut(up.at(r * inter), inter),
1448                        )
1449                    };
1450                    row(r, dgr, dur);
1451                }
1452            });
1453        }
1454        _ => {
1455            for r in 0..n {
1456                let (dgr, dur) = (&mut dg[r * inter..(r + 1) * inter], &mut du[r * inter..(r + 1) * inter]);
1457                row(r, dgr, dur);
1458            }
1459        }
1460    }
1461}
1462
1463impl FcdModel {
1464    /// Per-head RMS-norm (qk-norm) + partial RoPE for all rows of a
1465    /// projection buffer. `heads` per row, `x` is `[n, heads·hd]`.
1466    /// Saves the per-(row, head) rms inv when a norm gain is present.
1467    /// (window, local-RoPE) of a full-attention layer — None for GDN.
1468    pub(crate) fn attn_geometry(&self, li: usize) -> Option<(Option<usize>, bool)> {
1469        match &self.layers[li].attn {
1470            FcdAttn::Full {
1471                window, local_rope, ..
1472            } => Some((*window, *local_rope)),
1473            _ => None,
1474        }
1475    }
1476
1477    /// The frozen per-head gate projection of a layer (Spark-X2.5), if any.
1478    pub(crate) fn head_gate_weights(&self, li: usize) -> Option<&[f32]> {
1479        match &self.layers[li].attn {
1480            FcdAttn::Full { head_gate, .. } => head_gate.as_deref(),
1481            _ => None,
1482        }
1483    }
1484
1485    /// The RoPE geometry of a layer: local layers may own a table.
1486    /// A whole Phase-A step of the skill bake on CUDA (`gpu_cuda::bake_phase_a`):
1487    /// `ffn` the layers' norms and FFN weights with their mask gains (the
1488    /// caller's `LnFfn`, physical order), `mats` the layers' matrices. None
1489    /// when the stack has something the resident step does not take (a loop,
1490    /// projection biases, a projected head gate) or the card declines — the
1491    /// layer-by-layer path then runs as before.
1492    #[cfg(feature = "cuda")]
1493    pub(crate) fn resident_step(
1494        &self,
1495        ids: &[u32],
1496        b: usize,
1497        ffn: &[(LnFfn<'_>, Vec<f32>)],
1498        mats: &[std::sync::Arc<LayerMats>],
1499        targets: &[usize],
1500        scale: f32,
1501        grad: bool,
1502    ) -> Option<crate::gpu_cuda::BkOut> {
1503        use crate::gpu_cuda::{BakeGdn, BakeGdnW, BkAttn, BkFull, BkLayer, BkStep};
1504        if !crate::gpu::cuda_active() || self.loops > 1 || ffn.len() != self.layers.len() || mats.len() != self.layers.len() || b == 0 {
1505            return None;
1506        }
1507        if std::env::var("CMF_BAKE_RESIDENT").as_deref() == Ok("0") {
1508            return None;
1509        }
1510        let t = ids.len() / b;
1511        // the rope tables a full layer reads, [t][half][2] (cos, sin), by locality
1512        let tab = |local: bool| -> Vec<f32> {
1513            let (rd, inv_freq) = self.layer_rope(local);
1514            let half = rd / 2;
1515            let mut v = Vec::with_capacity(t * half * 2);
1516            for pos in 0..t {
1517                for &fq in &inv_freq[..half] {
1518                    let a = pos as f64 * fq;
1519                    v.push(a.cos() as f32);
1520                    v.push(a.sin() as f32);
1521                }
1522            }
1523            v
1524        };
1525        let (tab_g, tab_l) = (tab(false), tab(true));
1526        let mut layers = Vec::with_capacity(self.layers.len());
1527        for (li, l) in self.layers.iter().enumerate() {
1528            let (w, gain) = (&ffn[li].0, &ffn[li].1);
1529            let gu = w.gu?;
1530            let attn = match &l.attn {
1531                FcdAttn::Gdn { wqkv, wz, wa, wb, conv, a_log, dt_bias, norm, wout } => {
1532                    let d = self.gdn?;
1533                    BkAttn::Gdn(
1534                        BakeGdn { nv: d.nv, nk: d.nk, dk: d.dk, dv: d.dv, kk: d.kk, eps: self.eps as f32, conv, a_log, dt_bias, norm },
1535                        BakeGdnW { wqkv, wz, wa, wb, wout, hsz: self.hidden },
1536                    )
1537                }
1538                FcdAttn::Full { q_norm, k_norm, bias, output_gate, head_gate, window, local_rope, .. } => {
1539                    if bias.is_some() || head_gate.is_some() {
1540                        return None;
1541                    }
1542                    let (rd, _) = self.layer_rope(*local_rope);
1543                    BkAttn::Full(BkFull {
1544                        wqkv: &mats[li].wqkv,
1545                        wo: &mats[li].wo,
1546                        q_norm: q_norm.as_deref(),
1547                        k_norm: k_norm.as_deref(),
1548                        gated: *output_gate,
1549                        nh: self.nh,
1550                        nkv: self.nkv,
1551                        hd: self.hd,
1552                        rope: if *local_rope { &tab_l } else { &tab_g },
1553                        half: rd / 2,
1554                        window: *window,
1555                    })
1556                }
1557            };
1558            layers.push(BkLayer { iln: w.iln, pln: w.pln, attn, gu, down: w.down, inter: l.inter, gain });
1559        }
1560        let step = BkStep {
1561            layers,
1562            ids,
1563            b,
1564            t,
1565            hsz: self.hidden,
1566            eps: self.eps as f32,
1567            gemma: self.gemma,
1568            act: self.act,
1569            embed: &self.embed,
1570            final_norm: &self.final_norm,
1571            lm: self.lm_head.as_deref().unwrap_or(&self.embed),
1572            targets,
1573            scale,
1574            grad,
1575        };
1576        crate::gpu_cuda::bake_phase_a(&step)
1577    }
1578
1579    pub(crate) fn layer_rope(&self, local: bool) -> (usize, &[f64]) {
1580        if local {
1581            (
1582                self.rotary_dim_local.unwrap_or(self.rotary_dim),
1583                self.inv_freq_local.as_deref().unwrap_or(&self.inv_freq),
1584            )
1585        } else {
1586            (self.rotary_dim, &self.inv_freq)
1587        }
1588    }
1589
1590    fn qk_norm_rope(
1591        &self,
1592        x: &mut [f32],
1593        norm: Option<&[f32]>,
1594        heads: usize,
1595        t: usize,
1596        local: bool,
1597        inv_out: &mut [f32],
1598    ) {
1599        let hd = self.hd;
1600        let (rotary_dim, inv_freq) = self.layer_rope(local);
1601        let n = x.len() / (heads * hd);
1602        for r in 0..n {
1603            let pos = r % t;
1604            for hh in 0..heads {
1605                let s = (r * heads + hh) * hd;
1606                let head = &mut x[s..s + hd];
1607                if let Some(w) = norm {
1608                    let mut inv = [0f32; 1];
1609                    let mut y = [0f32; 256];
1610                    debug_assert!(hd <= 256);
1611                    ops::rmsnorm_fwd(head, w, self.eps, self.gemma, &mut y[..hd], &mut inv);
1612                    head.copy_from_slice(&y[..hd]);
1613                    inv_out[r * heads + hh] = inv[0];
1614                }
1615                ops::rope_fwd(&mut head[..rotary_dim], pos, inv_freq);
1616            }
1617        }
1618    }
1619
1620    /// One layer forward over `b` sequences of length `t` (rows are
1621    /// b-major). `nystrom` switches converted (Full) student layers to
1622    /// the certified matrix kernel (f64 per head); exact heads run in
1623    /// f32; GDN layers run the frozen BPTT-capable operator. Returns
1624    /// (h_out, intra-layer activations when `want_acts`).
1625    #[allow(clippy::too_many_arguments)]
1626    fn layer_forward(
1627        &self,
1628        li: usize,
1629        h_in: &[f32],
1630        b: usize,
1631        t: usize,
1632        wts: &LnFfn,
1633        nystrom: bool,
1634        want_acts: bool,
1635    ) -> (Vec<f32>, Option<LayerActs>) {
1636        self.layer_forward_scaled(li, h_in, b, t, wts, nystrom, want_acts, None, true, None, false)
1637    }
1638
1639    /// `layer_forward` with an optional per-neuron FFN activation scale
1640    /// (the DTG-MA mask σ(m), Patent 2): `act·scale` feeds down_proj.
1641    /// `LayerActs.act` stays PRE-scale so the mask backward can read it.
1642    #[allow(clippy::too_many_arguments)]
1643    pub(crate) fn layer_forward_scaled(
1644        &self,
1645        li: usize,
1646        h_in: &[f32],
1647        b: usize,
1648        t: usize,
1649        wts: &LnFfn,
1650        nystrom: bool,
1651        want_acts: bool,
1652        ffn_scale: Option<&[f32]>,
1653        ffn_planes_to_host: bool,
1654        attn_w: Option<AttnW<'_>>,
1655        want_attn_acts: bool,
1656    ) -> (Vec<f32>, Option<LayerActs>) {
1657        // Polish-only: the flags select what to TRAIN, not what to convert.
1658        let nystrom = nystrom && !self.polish_only;
1659        let hsz = self.hidden;
1660        let n = b * t;
1661        let l = &self.layers[li];
1662        let pool = self.pool.as_deref();
1663
1664        let mut n1 = vec![0f32; n * hsz];
1665        let mut inv1 = vec![0f32; n];
1666        rmsnorm_fwd_pooled(h_in, wts.iln, self.eps, self.gemma, &mut n1, &mut inv1, pool);
1667
1668        let mats = self.mats(li).expect("layer mats");
1669        let t_attn = std::time::Instant::now();
1670        let (attn_out, attn_acts) = match &l.attn {
1671            FcdAttn::Full { .. } => {
1672                self.full_attn_fwd(&l.attn, &mats, &n1, b, t, nystrom, attn_w, want_attn_acts)
1673            }
1674            FcdAttn::Gdn { .. } => self.gdn_attn_fwd(&l.attn, &n1, b, t, self.attn_acts || want_attn_acts),
1675        };
1676        prof::add(&prof::ATTN_FWD, t_attn);
1677        prof::tick(if matches!(l.attn, FcdAttn::Gdn { .. }) { "attn-gdn-layers" } else { "attn-full-layers" }, t_attn);
1678        let t_ffn = std::time::Instant::now();
1679
1680        let mut h1 = h_in.to_vec();
1681        add_into_pooled(&mut h1, &attn_out, pool);
1682
1683        let mut n2 = vec![0f32; n * hsz];
1684        let mut inv2 = vec![0f32; n];
1685        rmsnorm_fwd_pooled(&h1, wts.pln, self.eps, self.gemma, &mut n2, &mut inv2, pool);
1686
1687        let inter = l.inter;
1688        // The gate/up/act planes are allocated only by the path that fills
1689        // them: zero-filling three n×inter buffers per layer that the device
1690        // chain never touches cost more than the chain itself (48 s of a
1691        // 73 s FFN forward on a 1.7 B smoke bake).
1692        let mut gpre: Vec<f32> = Vec::new();
1693        let mut upre: Vec<f32> = Vec::new();
1694        let mut act: Vec<f32> = Vec::new();
1695        let mut ffn = vec![0f32; n * hsz];
1696        prof::add(&prof::FFN_PRE, t_ffn);
1697        // The frozen fused-gu FFN rides the whole chain on the device when
1698        // the tensor-core arm is up: one submit, and the gate+up plane
1699        // only crosses PCIe when the backward pass will need it. An eval
1700        // call moves three matrices and reads back one.
1701        let mut fused = false;
1702        #[cfg(feature = "gpu")]
1703        if let Some(gu) = wts.gu {
1704            if crate::gpu::enabled_here() {
1705                // A training call whose backward runs on the card leaves the
1706                // plane there: nothing of n×2·inter crosses PCIe.
1707                let mut both = (want_acts && ffn_planes_to_host).then(|| vec![0f32; n * 2 * inter]);
1708                let t_chain = std::time::Instant::now();
1709                let chained = bake_ffn_chain(
1710                    &n2,
1711                    gu,
1712                    wts.down,
1713                    ffn_scale,
1714                    both.as_deref_mut(),
1715                    want_acts.then_some(li),
1716                    &mut ffn,
1717                    n,
1718                    hsz,
1719                    inter,
1720                    self.act,
1721                );
1722                prof::add(&prof::FFN_CHAIN, t_chain);
1723                if chained {
1724                    fused = true;
1725                    if let Some(b) = &both {
1726                        let t_act = std::time::Instant::now();
1727                        gpre.reserve_exact(n * inter);
1728                        upre.reserve_exact(n * inter);
1729                        for r in 0..n {
1730                            let row = &b[r * 2 * inter..(r + 1) * 2 * inter];
1731                            gpre.extend_from_slice(&row[..inter]);
1732                            upre.extend_from_slice(&row[inter..]);
1733                        }
1734                        act = vec![0f32; n * inter];
1735                        // PRE-scale, as the mask backward expects.
1736                        act_mul_rows(self.act, &gpre, &upre, &mut act, n, inter, pool);
1737                        prof::add(&prof::FFN_ACT, t_act);
1738                    }
1739                }
1740            }
1741        }
1742        let t_host = std::time::Instant::now();
1743        if !fused {
1744            gpre = vec![0f32; n * inter];
1745            upre = vec![0f32; n * inter];
1746            act = vec![0f32; n * inter];
1747            if let Some(gu) = wts.gu {
1748                // One submit; split back so everything downstream is
1749                // byte-identical to the two-call path.
1750                let mut both = vec![0f32; n * 2 * inter];
1751                ops::gemm_nt(&n2, gu, &mut both, n, hsz, 2 * inter, pool);
1752                for r in 0..n {
1753                    let row = &both[r * 2 * inter..(r + 1) * 2 * inter];
1754                    gpre[r * inter..(r + 1) * inter].copy_from_slice(&row[..inter]);
1755                    upre[r * inter..(r + 1) * inter].copy_from_slice(&row[inter..]);
1756                }
1757            } else {
1758                ops::gemm_nt(&n2, wts.gate, &mut gpre, n, hsz, inter, pool);
1759                ops::gemm_nt(&n2, wts.up, &mut upre, n, hsz, inter, pool);
1760            }
1761            act_mul_rows(self.act, &gpre, &upre, &mut act, n, inter, pool);
1762            match ffn_scale {
1763                Some(g) => {
1764                    debug_assert_eq!(g.len(), inter);
1765                    let mut act2 = act.clone();
1766                    for r in 0..n {
1767                        for (a, &gv) in act2[r * inter..(r + 1) * inter].iter_mut().zip(g) {
1768                            *a *= gv;
1769                        }
1770                    }
1771                    ops::gemm_nt(&act2, wts.down, &mut ffn, n, inter, hsz, pool);
1772                }
1773                None => ops::gemm_nt(&act, wts.down, &mut ffn, n, inter, hsz, pool),
1774            }
1775        }
1776        prof::add(&prof::FFN_HOST, t_host);
1777        let t_post = std::time::Instant::now();
1778        // The acts keep h1; without them the residual add runs in place.
1779        let mut h2 = if want_acts { h1.clone() } else { std::mem::take(&mut h1) };
1780        add_into_pooled(&mut h2, &ffn, pool);
1781        prof::add(&prof::FFN_POST, t_post);
1782
1783        let acts = want_acts.then_some(LayerActs {
1784            inv1,
1785            attn: attn_acts,
1786            h1,
1787            n2,
1788            inv2,
1789            gpre,
1790            upre,
1791            act,
1792        });
1793        prof::add(&prof::FFN_FWD, t_ffn);
1794        (h2, acts)
1795    }
1796
1797    /// Full-attention forward: projections (+optional biases), optional
1798    /// per-head [q; gate] split (Qwen3.5 output gate), qk-norm + RoPE,
1799    /// per-head exact-or-Nyström attention, σ(gate) multiply, o_proj.
1800    #[allow(clippy::too_many_arguments)]
1801    fn full_attn_fwd(
1802        &self,
1803        attn: &FcdAttn,
1804        mats: &LayerMats,
1805        n1: &[f32],
1806        b: usize,
1807        t: usize,
1808        nystrom: bool,
1809        attn_w: Option<AttnW<'_>>,
1810        want_attn_acts: bool,
1811    ) -> (Vec<f32>, AttnActs) {
1812        // Trained copies (full-layer FCD) stand in for the frozen mats.
1813        let (wqkv, wo) = match attn_w {
1814            Some(w) => (w.wqkv, w.wo),
1815            None => (&mats.wqkv[..], &mats.wo[..]),
1816        };
1817        let FcdAttn::Full {
1818            qrows: _,
1819            q_norm,
1820            k_norm,
1821            bias,
1822            bias_cat,
1823            output_gate,
1824            head_gate,
1825            window,
1826            local_rope,
1827        } = attn
1828        else {
1829            unreachable!("full_attn_fwd on a non-Full layer");
1830        };
1831
1832        let (hsz, nh, nkv, hd) = (self.hidden, self.nh, self.nkv, self.hd);
1833        let n = b * t;
1834        let pool = self.pool.as_deref();
1835        let qdim = nh * hd;
1836        let kvdim = nkv * hd;
1837        let rep = nh / nkv;
1838        let qrows = if *output_gate { 2 * qdim } else { qdim };
1839
1840        let fused = qrows + 2 * kvdim;
1841        // Projected head gate (Spark-X2.5): gain_h = σ(g_proj_h · n1) per
1842        // row, applied to the whole head — the runtime's
1843        // `apply_projected_gate(per_head = true, sigmoid = true)`. Computed
1844        // once here; both the device chain and the host path consume it.
1845        let head_gate_w: Option<&[f32]> = attn_w.and_then(|w| w.head_gate).or(head_gate.as_deref());
1846        let head_gain: Vec<f32> = match head_gate_w {
1847            Some(gw) => {
1848                let mut graw = vec![0f32; n * nh];
1849                ops::gemm_nt(n1, gw, &mut graw, n, hsz, nh, pool);
1850                for v in graw.iter_mut() {
1851                    *v = 1.0 / (1.0 + (-*v).exp());
1852                }
1853                graw
1854            }
1855            None => Vec::new(),
1856        };
1857        let (rotary_dim, inv_freq) = self.layer_rope(*local_rope);
1858        // ── device chain: the whole attention forward in one submit ──
1859        // Declines in strict-f32 mode, on Nyström layers (their kernel is
1860        // certified f64 and stays host), and wherever a shape steps
1861        // outside the kernels; the host path below is the fallback and
1862        // the reference.
1863        #[cfg(feature = "gpu")]
1864        if !nystrom && crate::gpu::enabled_here() {
1865            let want_acts = self.attn_acts || want_attn_acts;
1866            let rope = {
1867                let mut rt = self.rope_tab.lock().unwrap();
1868                match rt.as_ref() {
1869                    Some((key, arc)) if *key == (t, *local_rope) => arc.clone(),
1870                    _ => {
1871                        let half = rotary_dim / 2;
1872                        let mut tab = Vec::with_capacity(t * half * 2);
1873                        for pos in 0..t {
1874                            for &freq in inv_freq.iter() {
1875                                let a = pos as f64 * freq;
1876                                tab.push(a.cos() as f32);
1877                                tab.push(a.sin() as f32);
1878                            }
1879                        }
1880                        let arc = std::sync::Arc::new(tab);
1881                        *rt = Some(((t, *local_rope), arc.clone()));
1882                        arc
1883                    }
1884                }
1885            };
1886            let cfg = crate::gpu_wgpu::AttnChainCfg {
1887                wqkv,
1888                wo,
1889                q_norm: q_norm.as_deref(),
1890                k_norm: k_norm.as_deref(),
1891                bias: bias_cat.as_deref(),
1892                output_gate: *output_gate,
1893                head_gain: (!head_gain.is_empty()).then_some(&head_gain[..]),
1894                window: *window,
1895                gemma: self.gemma,
1896                eps: self.eps as f32,
1897                rotary_half: rotary_dim / 2,
1898                rope: &rope,
1899                b,
1900                t,
1901                nh,
1902                nkv,
1903                hd,
1904                hsz: self.hidden,
1905            };
1906            let mut attn_out = vec![0f32; n * self.hidden];
1907            let t_chain = std::time::Instant::now();
1908            let chained = crate::gpu_wgpu::attn_chain_f32(n1, &cfg, &mut attn_out, want_acts);
1909            prof::add(&prof::ATTN_CHAIN, t_chain);
1910            if let Some(ch) = chained {
1911                if !want_acts {
1912                    return (
1913                        attn_out,
1914                        AttnActs::Full {
1915                            qpre: Vec::new(),
1916                            kpre: Vec::new(),
1917                            vproj: Vec::new(),
1918                            qrot: Vec::new(),
1919                            krot: Vec::new(),
1920                            qinv: Vec::new(),
1921                            kinv: Vec::new(),
1922                            ao: Vec::new(),
1923                            gate_pre: Vec::new(),
1924                            head_gain,
1925                        },
1926                    );
1927                }
1928                // Rebuild the host-visible acts from the raw plane, with
1929                // exactly the host split's bias/gate arithmetic.
1930                let mut qraw = vec![0f32; n * qrows];
1931                let mut kpre = vec![0f32; n * kvdim];
1932                let mut vproj = vec![0f32; n * kvdim];
1933                for r in 0..n {
1934                    let row = &ch.qkv_plane[r * fused..(r + 1) * fused];
1935                    qraw[r * qrows..(r + 1) * qrows].copy_from_slice(&row[..qrows]);
1936                    kpre[r * kvdim..(r + 1) * kvdim].copy_from_slice(&row[qrows..qrows + kvdim]);
1937                    vproj[r * kvdim..(r + 1) * kvdim].copy_from_slice(&row[qrows + kvdim..]);
1938                }
1939                if let Some((bq, bk, bv)) = bias {
1940                    for r in 0..n {
1941                        for (x, bb) in qraw[r * qrows..(r + 1) * qrows].iter_mut().zip(bq) {
1942                            *x += bb;
1943                        }
1944                        for (x, bb) in kpre[r * kvdim..(r + 1) * kvdim].iter_mut().zip(bk) {
1945                            *x += bb;
1946                        }
1947                        for (x, bb) in vproj[r * kvdim..(r + 1) * kvdim].iter_mut().zip(bv) {
1948                            *x += bb;
1949                        }
1950                    }
1951                }
1952                let (qpre, gate_pre) = if *output_gate {
1953                    let mut qh = vec![0f32; n * qdim];
1954                    let mut gp = vec![0f32; n * qdim];
1955                    for r in 0..n {
1956                        for h in 0..nh {
1957                            let src = r * qrows + 2 * h * hd;
1958                            let dst = r * qdim + h * hd;
1959                            qh[dst..dst + hd].copy_from_slice(&qraw[src..src + hd]);
1960                            gp[dst..dst + hd].copy_from_slice(&qraw[src + hd..src + 2 * hd]);
1961                        }
1962                    }
1963                    (qh, gp)
1964                } else {
1965                    (qraw, Vec::new())
1966                };
1967                return (
1968                    attn_out,
1969                    AttnActs::Full {
1970                        qpre,
1971                        kpre,
1972                        vproj,
1973                        qrot: ch.qrot,
1974                        krot: ch.krot,
1975                        qinv: ch.qinv,
1976                        kinv: ch.kinv,
1977                        ao: ch.ao,
1978                        gate_pre,
1979                        head_gain,
1980                    },
1981                );
1982            }
1983        }
1984
1985        // One fused submit; the split back into three buffers is a
1986        // memcpy that costs microseconds and keeps everything below
1987        // this line byte-identical to the unfused path.
1988        let t_q = std::time::Instant::now();
1989        let mut qkv = vec![0f32; n * fused];
1990        ops::gemm_nt(n1, wqkv, &mut qkv, n, hsz, fused, pool);
1991        prof::tick("full-qkv-gemm", t_q);
1992        let mut qraw = vec![0f32; n * qrows];
1993        let mut kpre = vec![0f32; n * kvdim];
1994        let mut vproj = vec![0f32; n * kvdim];
1995        for r in 0..n {
1996            let row = &qkv[r * fused..(r + 1) * fused];
1997            qraw[r * qrows..(r + 1) * qrows].copy_from_slice(&row[..qrows]);
1998            kpre[r * kvdim..(r + 1) * kvdim].copy_from_slice(&row[qrows..qrows + kvdim]);
1999            vproj[r * kvdim..(r + 1) * kvdim].copy_from_slice(&row[qrows + kvdim..]);
2000        }
2001        if let Some((bq, bk, bv)) = bias {
2002            for r in 0..n {
2003                for (x, bb) in qraw[r * qrows..(r + 1) * qrows].iter_mut().zip(bq) {
2004                    *x += bb;
2005                }
2006                for (x, bb) in kpre[r * kvdim..(r + 1) * kvdim].iter_mut().zip(bk) {
2007                    *x += bb;
2008                }
2009                for (x, bb) in vproj[r * kvdim..(r + 1) * kvdim].iter_mut().zip(bv) {
2010                    *x += bb;
2011                }
2012            }
2013        }
2014        // Gate split: per-head [q(hd); gate(hd)] (runtime convention).
2015        let (qpre, gate_pre) = if *output_gate {
2016            let mut qh = vec![0f32; n * qdim];
2017            let mut gp = vec![0f32; n * qdim];
2018            for r in 0..n {
2019                for h in 0..nh {
2020                    let src = r * qrows + 2 * h * hd;
2021                    let dst = r * qdim + h * hd;
2022                    qh[dst..dst + hd].copy_from_slice(&qraw[src..src + hd]);
2023                    gp[dst..dst + hd].copy_from_slice(&qraw[src + hd..src + 2 * hd]);
2024                }
2025            }
2026            (qh, gp)
2027        } else {
2028            (qraw, Vec::new())
2029        };
2030
2031        let t_nr = std::time::Instant::now();
2032        let mut qrot = qpre.clone();
2033        let mut krot = kpre.clone();
2034        let mut qinv = vec![0f32; n * nh];
2035        let mut kinv = vec![0f32; n * nkv];
2036        self.qk_norm_rope(&mut qrot, q_norm.as_deref(), nh, t, *local_rope, &mut qinv);
2037        self.qk_norm_rope(&mut krot, k_norm.as_deref(), nkv, t, *local_rope, &mut kinv);
2038        prof::tick("full-qk-norm-rope", t_nr);
2039        let t_core = std::time::Instant::now();
2040
2041        // ── attention heads: parallel over (sequence, head) ──
2042        let mut ao = vec![0f32; n * qdim];
2043        // The exact core on the card on CUDA (`gpu_cuda::bake_attn_fwd`).
2044        #[cfg(feature = "cuda")]
2045        let ao_dev = !nystrom
2046            && crate::gpu::cuda_active()
2047            && crate::gpu_cuda::bake_attn_fwd(&qrot, &krot, &vproj, b, t, nh, nkv, hd, *window, &mut ao);
2048        #[cfg(not(feature = "cuda"))]
2049        let ao_dev = false;
2050        if !ao_dev {
2051            let units = b * nh;
2052            let aop = SendMut(ao.as_mut_ptr());
2053            let qr = &qrot;
2054            let kr = &krot;
2055            let vr = &vproj;
2056            let nys = self.nys;
2057            let run_unit = |u: usize| {
2058                let (bi, h) = (u / nh, u % nh);
2059                let g = h / rep;
2060                if nystrom {
2061                    // Certified matrix kernel in f64 (docs/RUST_FCD.md §2.2).
2062                    let mut q64 = vec![0f64; t * hd];
2063                    let mut k64 = vec![0f64; t * hd];
2064                    let mut v64 = vec![0f64; t * hd];
2065                    for p in 0..t {
2066                        let r = bi * t + p;
2067                        for c in 0..hd {
2068                            q64[p * hd + c] = qr[r * qdim + h * hd + c] as f64;
2069                            k64[p * hd + c] = kr[r * kvdim + g * hd + c] as f64;
2070                            v64[p * hd + c] = vr[r * kvdim + g * hd + c] as f64;
2071                        }
2072                    }
2073                    let mut o64 = vec![0f64; t * hd];
2074                    ops::nystrom_head_fwd(&q64, &k64, &v64, t, hd, hd, &nys, &mut o64);
2075                    for p in 0..t {
2076                        let r = bi * t + p;
2077                        for c in 0..hd {
2078                            // SAFETY: (row, head) slices are disjoint per unit.
2079                            unsafe {
2080                                *aop.at(r * qdim + h * hd + c) = o64[p * hd + c] as f32;
2081                            }
2082                        }
2083                    }
2084                } else {
2085                    let mut q32 = vec![0f32; t * hd];
2086                    let mut k32 = vec![0f32; t * hd];
2087                    let mut v32 = vec![0f32; t * hd];
2088                    for p in 0..t {
2089                        let r = bi * t + p;
2090                        q32[p * hd..(p + 1) * hd]
2091                            .copy_from_slice(&qr[r * qdim + h * hd..r * qdim + (h + 1) * hd]);
2092                        k32[p * hd..(p + 1) * hd]
2093                            .copy_from_slice(&kr[r * kvdim + g * hd..r * kvdim + (g + 1) * hd]);
2094                        v32[p * hd..(p + 1) * hd]
2095                            .copy_from_slice(&vr[r * kvdim + g * hd..r * kvdim + (g + 1) * hd]);
2096                    }
2097                    let mut o32 = vec![0f32; t * hd];
2098                    ops::attn_head_fwd_window(&q32, &k32, &v32, t, hd, hd, *window, &mut o32);
2099                    for p in 0..t {
2100                        let r = bi * t + p;
2101                        for c in 0..hd {
2102                            // SAFETY: disjoint (row, head) slices per unit.
2103                            unsafe {
2104                                *aop.at(r * qdim + h * hd + c) = o32[p * hd + c];
2105                            }
2106                        }
2107                    }
2108                }
2109            };
2110            match pool {
2111                Some(p) if units > 1 => p.run(&|widx, nw| {
2112                    for u in (widx..units).step_by(nw) {
2113                        run_unit(u);
2114                    }
2115                }),
2116                _ => {
2117                    for u in 0..units {
2118                        run_unit(u);
2119                    }
2120                }
2121            }
2122        }
2123
2124        // Output gate: multiply the head outputs by σ(gate) before o_proj.
2125        let mut ao_eff: Vec<f32> = if *output_gate {
2126            ao.iter()
2127                .zip(&gate_pre)
2128                .map(|(&a, &g)| a * (1.0 / (1.0 + (-g).exp())))
2129                .collect()
2130        } else {
2131            ao.clone()
2132        };
2133        // The projected head gate's gains (computed above) scale each head.
2134        if !head_gain.is_empty() {
2135            for r in 0..n {
2136                for h in 0..nh {
2137                    let gain = head_gain[r * nh + h];
2138                    for a in &mut ao_eff[r * qdim + h * hd..r * qdim + (h + 1) * hd] {
2139                        *a *= gain;
2140                    }
2141                }
2142            }
2143        }
2144        prof::tick("full-core+gate", t_core);
2145        let t_wo = std::time::Instant::now();
2146        let mut attn_out = vec![0f32; n * hsz];
2147        ops::gemm_nt(&ao_eff, wo, &mut attn_out, n, qdim, hsz, pool);
2148        prof::tick("full-wo", t_wo);
2149        (
2150            attn_out,
2151            AttnActs::Full {
2152                qpre,
2153                kpre,
2154                vproj,
2155                qrot,
2156                krot,
2157                qinv,
2158                kinv,
2159                ao,
2160                gate_pre,
2161                head_gain,
2162            },
2163        )
2164    }
2165
2166    /// GDN forward (frozen operator, teacher AND student): batched
2167    /// projections → f64 conv+SiLU per sequence → pooled per-(seq,
2168    /// k-head) delta-rule recurrence → out_proj. Matches the runtime
2169    /// `gdn_forward` (parity-tested in fcd_gradcheck).
2170    fn gdn_attn_fwd(&self, attn: &FcdAttn, n1: &[f32], b: usize, t: usize, want_streams: bool) -> (Vec<f32>, AttnActs) {
2171        let FcdAttn::Gdn {
2172            wqkv,
2173            wz,
2174            wa,
2175            wb,
2176            conv,
2177            a_log,
2178            dt_bias,
2179            norm,
2180            wout,
2181        } = attn
2182        else {
2183            unreachable!("gdn_attn_fwd on a non-GDN layer");
2184        };
2185        let d = self.gdn.expect("gdn layer without gdn dims");
2186        let (hsz, n) = (self.hidden, b * t);
2187        let pool = self.pool.as_deref();
2188        let (c_dim, vd, nv) = (d.c_dim(), d.vd(), d.nv);
2189
2190        // CUDA: the whole layer on the card, n1 up and attn_out down; the
2191        // projection streams come back only for a backward through it.
2192        #[cfg(feature = "cuda")]
2193        if crate::gpu::cuda_active() {
2194            let g = crate::gpu_cuda::BakeGdn {
2195                nv: d.nv,
2196                nk: d.nk,
2197                dk: d.dk,
2198                dv: d.dv,
2199                kk: d.kk,
2200                eps: self.eps as f32,
2201                conv,
2202                a_log,
2203                dt_bias,
2204                norm,
2205            };
2206            let w = crate::gpu_cuda::BakeGdnW { wqkv, wz, wa, wb, wout, hsz };
2207            if crate::gpu_cuda::bake_gdn_ok(&g) {
2208                let t_gdn = std::time::Instant::now();
2209                let done = crate::gpu_cuda::bake_gdn_layer_fwd(n1, &w, &g, b, t, want_streams);
2210                prof::tick("gdn-layer-chain", t_gdn);
2211                if let Some((attn_out, streams)) = done {
2212                    let (qkv, z, a, bstr) = streams.unwrap_or_default();
2213                    return (attn_out, AttnActs::Gdn { qkv, z, a, b: bstr });
2214                }
2215            }
2216        }
2217        let t_proj = std::time::Instant::now();
2218        let mut qkv = vec![0f32; n * c_dim];
2219        ops::gemm_nt(n1, wqkv, &mut qkv, n, hsz, c_dim, pool);
2220        let mut z = vec![0f32; n * vd];
2221        ops::gemm_nt(n1, wz, &mut z, n, hsz, vd, pool);
2222        prof::tick("gdn-proj-qkvz", t_proj);
2223        let t_proj = std::time::Instant::now();
2224        let mut a = vec![0f32; n * nv];
2225        ops::gemm_nt(n1, wa, &mut a, n, hsz, nv, pool);
2226        let mut bstr = vec![0f32; n * nv];
2227        ops::gemm_nt(n1, wb, &mut bstr, n, hsz, nv, pool);
2228        prof::tick("gdn-proj-ab", t_proj);
2229
2230        let cfg = ops::GdnSeqCfg {
2231            nv: d.nv,
2232            nk: d.nk,
2233            dk: d.dk,
2234            dv: d.dv,
2235            kk: d.kk,
2236            rms_eps: self.eps,
2237            conv,
2238            a_log,
2239            dt_bias,
2240            norm,
2241        };
2242        // The card's f32 operator (`gpu_cuda::bake_gdn_fwd`) on CUDA.
2243        #[cfg(feature = "cuda")]
2244        if crate::gpu::cuda_active() {
2245            let g = crate::gpu_cuda::BakeGdn {
2246                nv: d.nv,
2247                nk: d.nk,
2248                dk: d.dk,
2249                dv: d.dv,
2250                kk: d.kk,
2251                eps: self.eps as f32,
2252                conv,
2253                a_log,
2254                dt_bias,
2255                norm,
2256            };
2257            if crate::gpu_cuda::bake_gdn_ok(&g) {
2258                let t_gdn = std::time::Instant::now();
2259                let done = crate::gpu_cuda::bake_gdn_fwd(&qkv, &z, &a, &bstr, b, t, &g);
2260                prof::add(&prof::GDN, t_gdn);
2261                if let Some(of) = done {
2262                    let t_out = std::time::Instant::now();
2263                    let mut attn_out = vec![0f32; n * hsz];
2264                    ops::gemm_nt(&of, wout, &mut attn_out, n, vd, hsz, pool);
2265                    prof::tick("gdn-out", t_out);
2266                    return (attn_out, AttnActs::Gdn { qkv, z, a, b: bstr });
2267                }
2268            }
2269        }
2270        // f64 streams (runtime-precision recurrence) + per-seq conv.
2271        let qkv64: Vec<f64> = qkv.iter().map(|&v| v as f64).collect();
2272        let z64: Vec<f64> = z.iter().map(|&v| v as f64).collect();
2273        let a64: Vec<f64> = a.iter().map(|&v| v as f64).collect();
2274        let b64: Vec<f64> = bstr.iter().map(|&v| v as f64).collect();
2275        let mut pre64 = vec![0f64; n * c_dim];
2276        let mut cq64 = vec![0f64; n * c_dim];
2277        for bi in 0..b {
2278            let r = bi * t * c_dim..(bi + 1) * t * c_dim;
2279            ops::gdn_conv_fwd(
2280                &qkv64[r.clone()],
2281                t,
2282                c_dim,
2283                d.kk,
2284                conv,
2285                &mut pre64[r.clone()],
2286                &mut cq64[r],
2287            );
2288        }
2289        let mut of = vec![0f32; n * vd];
2290        {
2291            let units = b * d.nk;
2292            let rep_v = d.nv / d.nk;
2293            let ofp = SendMut(of.as_mut_ptr());
2294            let (cqr, zr, ar, br) = (&cq64, &z64, &a64, &b64);
2295            let cfg_ref = &cfg;
2296            let run_unit = |u: usize| {
2297                let (bi, ko) = (u / d.nk, u % d.nk);
2298                let mut local = vec![0f64; t * vd];
2299                ops::gdn_group_fwd(
2300                    &cqr[bi * t * c_dim..(bi + 1) * t * c_dim],
2301                    &zr[bi * t * vd..(bi + 1) * t * vd],
2302                    &ar[bi * t * nv..(bi + 1) * t * nv],
2303                    &br[bi * t * nv..(bi + 1) * t * nv],
2304                    t,
2305                    cfg_ref,
2306                    ko,
2307                    &mut local,
2308                );
2309                for hh in 0..rep_v {
2310                    let h = ko * rep_v + hh;
2311                    for p in 0..t {
2312                        for dj in 0..d.dv {
2313                            // SAFETY: v-head columns are exclusive per unit.
2314                            unsafe {
2315                                *ofp.at((bi * t + p) * vd + h * d.dv + dj) =
2316                                    local[p * vd + h * d.dv + dj] as f32;
2317                            }
2318                        }
2319                    }
2320                }
2321            };
2322            match pool {
2323                Some(p) if units > 1 => p.run(&|widx, nw| {
2324                    for u in (widx..units).step_by(nw) {
2325                        run_unit(u);
2326                    }
2327                }),
2328                _ => {
2329                    for u in 0..units {
2330                        run_unit(u);
2331                    }
2332                }
2333            }
2334        }
2335        let mut attn_out = vec![0f32; n * hsz];
2336        ops::gemm_nt(&of, wout, &mut attn_out, n, vd, hsz, pool);
2337        (attn_out, AttnActs::Gdn { qkv, z, a, b: bstr })
2338    }
2339
2340    /// One layer backward (docs/RUST_FCD.md §2.3 chain), given the
2341    /// recomputed `acts`. Accumulates trainable grads when `grads` is
2342    /// Some; always produces the through-grad dh_in.
2343    #[allow(clippy::too_many_arguments)]
2344    fn layer_backward(
2345        &self,
2346        li: usize,
2347        h_in: &[f32],
2348        b: usize,
2349        t: usize,
2350        wts: &LnFfn,
2351        nystrom: bool,
2352        acts: &LayerActs,
2353        dh2: &[f32],
2354        mut grads: Option<&mut [Vec<f32>]>,
2355    ) -> Vec<f32> {
2356        let nystrom = nystrom && !self.polish_only;
2357        let hsz = self.hidden;
2358        let n = b * t;
2359        let l = &self.layers[li];
2360        let pool = self.pool.as_deref();
2361        let inter = l.inter;
2362
2363        // ── FFN backward ──
2364        let mut dn2 = vec![0f32; n * hsz];
2365        // A frozen layer (no weight grads wanted) rides the device chain
2366        // fed by the plane its forward parked: only dh2 goes down and dn2
2367        // comes back, where the host path uploads the 80 MB dgu concat.
2368        let mut bwd_fused = false;
2369        #[cfg(feature = "gpu")]
2370        if grads.is_none() {
2371            if let Some(gu) = wts.gu {
2372                if crate::gpu::enabled_here()
2373                    && bake_ffn_bwd_chain(dh2, wts.down, gu, li, &mut dn2, n, hsz, inter, self.act, None, None)
2374                {
2375                    bwd_fused = true;
2376                }
2377            }
2378        }
2379        if !bwd_fused {
2380            let mut dact = vec![0f32; n * inter];
2381            ops::gemm_dx(dh2, wts.down, &mut dact, n, inter, hsz, pool);
2382            if let Some(g) = grads.as_deref_mut() {
2383                ops::gemm_dw(dh2, &acts.act, &mut g[4], n, inter, hsz, pool);
2384            }
2385            let mut dg = vec![0f32; n * inter];
2386            let mut du = vec![0f32; n * inter];
2387            act_bwd_rows(self.act, &acts.gpre, &acts.upre, &dact, None, &mut dg, &mut du, n, inter, pool);
2388            // Fused when the frozen concat exists (its gate/up slots are
2389            // empty by design); trained masters keep the two-call path.
2390            if let Some(gu) = wts.gu {
2391                let mut dgu = vec![0f32; n * 2 * inter];
2392                for r in 0..n {
2393                    let row = &mut dgu[r * 2 * inter..(r + 1) * 2 * inter];
2394                    row[..inter].copy_from_slice(&dg[r * inter..(r + 1) * inter]);
2395                    row[inter..].copy_from_slice(&du[r * inter..(r + 1) * inter]);
2396                }
2397                ops::gemm_dx(&dgu, gu, &mut dn2, n, hsz, 2 * inter, pool);
2398            } else {
2399                ops::gemm_dx(&dg, wts.gate, &mut dn2, n, hsz, inter, pool);
2400                ops::gemm_dx(&du, wts.up, &mut dn2, n, hsz, inter, pool);
2401            }
2402            if let Some(g) = grads.as_deref_mut() {
2403                ops::gemm_dw(&dg, &acts.n2, &mut g[2], n, hsz, inter, pool);
2404                ops::gemm_dw(&du, &acts.n2, &mut g[3], n, hsz, inter, pool);
2405            }
2406        }
2407
2408        let mut dh1 = dh2.to_vec();
2409        ops::rmsnorm_bwd(
2410            &acts.h1,
2411            wts.pln,
2412            &acts.inv2,
2413            &dn2,
2414            self.gemma,
2415            &mut dh1,
2416            grads.as_deref_mut().map(|g| &mut g[1][..]),
2417        );
2418
2419        // ── attention backward (dispatch) → dn1 ──
2420        let mats = self.mats(li).expect("layer mats");
2421        let dn1 = match &l.attn {
2422            FcdAttn::Full { .. } => {
2423                self.full_attn_bwd(&l.attn, &mats, &acts.attn, &dh1, b, t, nystrom)
2424            }
2425            FcdAttn::Gdn { .. } => self.gdn_attn_bwd(&l.attn, &acts.attn, &dh1, b, t),
2426        };
2427
2428        let mut dh_in = dh1.clone();
2429        ops::rmsnorm_bwd(
2430            h_in,
2431            wts.iln,
2432            &acts.inv1,
2433            &dn1,
2434            self.gemma,
2435            &mut dh_in,
2436            grads.map(|g| &mut g[0][..]),
2437        );
2438        dh_in
2439    }
2440
2441    /// Full-attention through-backward: o_proj → output gate →
2442    /// per-head attention (exact / Nyström-frozen-M) → RoPE → qk-norm →
2443    /// projections. Frozen weights: dX only.
2444    fn full_attn_bwd(
2445        &self,
2446        attn: &FcdAttn,
2447        mats: &LayerMats,
2448        acts: &AttnActs,
2449        dattn: &[f32],
2450        b: usize,
2451        t: usize,
2452        nystrom: bool,
2453    ) -> Vec<f32> {
2454        let (wqkv, wo) = (&mats.wqkv[..], &mats.wo[..]);
2455        let FcdAttn::Full {
2456            qrows: _,
2457            q_norm,
2458            k_norm,
2459            output_gate,
2460            local_rope,
2461            window,
2462            ..
2463        } = attn
2464        else {
2465            unreachable!("full_attn_bwd on a non-Full layer");
2466        };
2467        let AttnActs::Full {
2468            qpre,
2469            kpre,
2470            vproj,
2471            qrot,
2472            krot,
2473            qinv,
2474            kinv,
2475            ao,
2476            gate_pre,
2477            head_gain,
2478        } = acts
2479        else {
2480            unreachable!("acts mismatch");
2481        };
2482        let (rotary_dim, inv_freq) = self.layer_rope(*local_rope);
2483        let (hsz, nh, nkv, hd) = (self.hidden, self.nh, self.nkv, self.hd);
2484        let n = b * t;
2485        let pool = self.pool.as_deref();
2486        let qdim = nh * hd;
2487        let kvdim = nkv * hd;
2488        let rep = nh / nkv;
2489        let qrows = if *output_gate { 2 * qdim } else { qdim };
2490
2491        let mut dao_eff = vec![0f32; n * qdim];
2492        ops::gemm_dx(dattn, wo, &mut dao_eff, n, qdim, hsz, pool);
2493        // Projected head gate: the gain multiplies the whole head, so the
2494        // gradient scales by it; the gate's weights are frozen and its
2495        // input path is not chased (FCD policy: attention is closed-form).
2496        if !head_gain.is_empty() {
2497            for r in 0..n {
2498                for h in 0..nh {
2499                    let gain = head_gain[r * nh + h];
2500                    for d in &mut dao_eff[r * qdim + h * hd..r * qdim + (h + 1) * hd] {
2501                        *d *= gain;
2502                    }
2503                }
2504            }
2505        }
2506        // Output gate: ao_eff = ao·σ(g) → dao = d·σ(g), dg = d·ao·σ′(g).
2507        let (dao, dgate) = if *output_gate {
2508            let mut dao = vec![0f32; n * qdim];
2509            let mut dgp = vec![0f32; n * qdim];
2510            for i in 0..n * qdim {
2511                let sig = 1.0 / (1.0 + (-gate_pre[i]).exp());
2512                dao[i] = dao_eff[i] * sig;
2513                dgp[i] = dao_eff[i] * ao[i] * sig * (1.0 - sig);
2514            }
2515            (dao, dgp)
2516        } else {
2517            (dao_eff, Vec::new())
2518        };
2519
2520        let mut dqrot = vec![0f32; n * qdim];
2521        let mut dkrot = vec![0f32; n * kvdim];
2522        let mut dvproj = vec![0f32; n * kvdim];
2523        #[cfg(feature = "cuda")]
2524        let core_dev = !nystrom
2525            && crate::gpu::cuda_active()
2526            && crate::gpu_cuda::bake_attn_bwd(qrot, krot, vproj, &dao, b, t, nh, nkv, hd, *window, &mut dqrot, &mut dkrot, &mut dvproj);
2527        #[cfg(not(feature = "cuda"))]
2528        let core_dev = false;
2529        if !core_dev {
2530            // Parallel over (sequence, kv-group): a unit owns the dk/dv
2531            // slices of its group and the dq slices of its rep Q heads.
2532            let units = b * nkv;
2533            let dqp = SendMut(dqrot.as_mut_ptr());
2534            let dkp = SendMut(dkrot.as_mut_ptr());
2535            let dvp = SendMut(dvproj.as_mut_ptr());
2536            let (qr, kr, vr) = (qrot, krot, vproj);
2537            let daor = &dao;
2538            let nys = self.nys;
2539            let run_unit = |u: usize| {
2540                let (bi, g) = (u / nkv, u % nkv);
2541                let mut k64 = vec![0f64; t * hd];
2542                let mut v64 = vec![0f64; t * hd];
2543                for p in 0..t {
2544                    let r = bi * t + p;
2545                    for c in 0..hd {
2546                        k64[p * hd + c] = kr[r * kvdim + g * hd + c] as f64;
2547                        v64[p * hd + c] = vr[r * kvdim + g * hd + c] as f64;
2548                    }
2549                }
2550                let mut dk64 = vec![0f64; t * hd];
2551                let mut dv64 = vec![0f64; t * hd];
2552                let mut q64 = vec![0f64; t * hd];
2553                let mut do64 = vec![0f64; t * hd];
2554                let mut dq64 = vec![0f64; t * hd];
2555                for hh in 0..rep {
2556                    let h = g * rep + hh;
2557                    for p in 0..t {
2558                        let r = bi * t + p;
2559                        for c in 0..hd {
2560                            q64[p * hd + c] = qr[r * qdim + h * hd + c] as f64;
2561                            do64[p * hd + c] = daor[r * qdim + h * hd + c] as f64;
2562                        }
2563                    }
2564                    for v in dq64.iter_mut() {
2565                        *v = 0.0;
2566                    }
2567                    if nystrom {
2568                        ops::nystrom_head_bwd(
2569                            &q64, &k64, &v64, &do64, t, hd, hd, &nys, &mut dq64, &mut dk64,
2570                            &mut dv64,
2571                        );
2572                    } else {
2573                        ops::attn_head_bwd_window(
2574                            &q64, &k64, &v64, &do64, t, hd, hd, *window, &mut dq64, &mut dk64,
2575                            &mut dv64,
2576                        );
2577                    }
2578                    for p in 0..t {
2579                        let r = bi * t + p;
2580                        for c in 0..hd {
2581                            // SAFETY: disjoint (row, head) slices per unit.
2582                            unsafe {
2583                                *dqp.at(r * qdim + h * hd + c) = dq64[p * hd + c] as f32;
2584                            }
2585                        }
2586                    }
2587                }
2588                for p in 0..t {
2589                    let r = bi * t + p;
2590                    for c in 0..hd {
2591                        // SAFETY: disjoint (row, group) slices per unit.
2592                        unsafe {
2593                            *dkp.at(r * kvdim + g * hd + c) = dk64[p * hd + c] as f32;
2594                            *dvp.at(r * kvdim + g * hd + c) = dv64[p * hd + c] as f32;
2595                        }
2596                    }
2597                }
2598            };
2599            match pool {
2600                Some(p) if units > 1 => p.run(&|widx, nw| {
2601                    for u in (widx..units).step_by(nw) {
2602                        run_unit(u);
2603                    }
2604                }),
2605                _ => {
2606                    for u in 0..units {
2607                        run_unit(u);
2608                    }
2609                }
2610            }
2611        }
2612
2613        // qk-norm + RoPE through-grads (frozen gains → no dw).
2614        let mut dqpre = vec![0f32; n * qdim];
2615        let mut dkpre = vec![0f32; n * kvdim];
2616        for r in 0..n {
2617            let pos = r % t;
2618            for h in 0..nh {
2619                let s = r * qdim + h * hd;
2620                ops::rope_bwd(&mut dqrot[s..s + rotary_dim], pos, inv_freq);
2621                match q_norm {
2622                    Some(w) => ops::rmsnorm_bwd(
2623                        &qpre[s..s + hd],
2624                        w,
2625                        &qinv[r * nh + h..r * nh + h + 1],
2626                        &dqrot[s..s + hd],
2627                        self.gemma,
2628                        &mut dqpre[s..s + hd],
2629                        None,
2630                    ),
2631                    None => dqpre[s..s + hd].copy_from_slice(&dqrot[s..s + hd]),
2632                }
2633            }
2634            for g in 0..nkv {
2635                let s = r * kvdim + g * hd;
2636                ops::rope_bwd(&mut dkrot[s..s + rotary_dim], pos, inv_freq);
2637                match k_norm {
2638                    Some(w) => ops::rmsnorm_bwd(
2639                        &kpre[s..s + hd],
2640                        w,
2641                        &kinv[r * nkv + g..r * nkv + g + 1],
2642                        &dkrot[s..s + hd],
2643                        self.gemma,
2644                        &mut dkpre[s..s + hd],
2645                        None,
2646                    ),
2647                    None => dkpre[s..s + hd].copy_from_slice(&dkrot[s..s + hd]),
2648                }
2649            }
2650        }
2651
2652        // Re-interleave [dq; dgate] per head for gated projections.
2653        let dqraw: Vec<f32> = if *output_gate {
2654            let mut dq = vec![0f32; n * qrows];
2655            for r in 0..n {
2656                for h in 0..nh {
2657                    let dst = r * qrows + 2 * h * hd;
2658                    let src = r * qdim + h * hd;
2659                    dq[dst..dst + hd].copy_from_slice(&dqpre[src..src + hd]);
2660                    dq[dst + hd..dst + 2 * hd].copy_from_slice(&dgate[src..src + hd]);
2661                }
2662            }
2663            dq
2664        } else {
2665            dqpre
2666        };
2667
2668        // Projections (frozen weights → dX only; bias add is identity).
2669        // One fused submit: wqkv's row layout is exactly what gemm_dx
2670        // wants, so the sum dq·Wq + dk·Wk + dv·Wv is a concat of the
2671        // gradients and a single call.
2672        let fused = qrows + 2 * kvdim;
2673        let mut dqkv = vec![0f32; n * fused];
2674        for r in 0..n {
2675            let row = &mut dqkv[r * fused..(r + 1) * fused];
2676            row[..qrows].copy_from_slice(&dqraw[r * qrows..(r + 1) * qrows]);
2677            row[qrows..qrows + kvdim].copy_from_slice(&dkpre[r * kvdim..(r + 1) * kvdim]);
2678            row[qrows + kvdim..].copy_from_slice(&dvproj[r * kvdim..(r + 1) * kvdim]);
2679        }
2680        let mut dn1 = vec![0f32; n * hsz];
2681        ops::gemm_dx(&dqkv, wqkv, &mut dn1, n, hsz, fused, pool);
2682        dn1
2683    }
2684
2685    /// GDN through-backward: out_proj → pooled per-(seq, k-head) BPTT
2686    /// (fcd_ops::gdn_group_bwd) → conv backward → projections. Frozen
2687    /// weights: dX only.
2688    fn gdn_attn_bwd(
2689        &self,
2690        attn: &FcdAttn,
2691        acts: &AttnActs,
2692        dattn: &[f32],
2693        b: usize,
2694        t: usize,
2695    ) -> Vec<f32> {
2696        let FcdAttn::Gdn {
2697            wqkv,
2698            wz,
2699            wa,
2700            wb,
2701            conv,
2702            a_log,
2703            dt_bias,
2704            norm,
2705            wout,
2706        } = attn
2707        else {
2708            unreachable!("gdn_attn_bwd on a non-GDN layer");
2709        };
2710        let AttnActs::Gdn { qkv, z, a, b: bstr } = acts else {
2711            unreachable!("acts mismatch");
2712        };
2713        let d = self.gdn.expect("gdn layer without gdn dims");
2714        let (hsz, n) = (self.hidden, b * t);
2715        let pool = self.pool.as_deref();
2716        let (c_dim, vd, nv) = (d.c_dim(), d.vd(), d.nv);
2717
2718        let mut dof = vec![0f32; n * vd];
2719        ops::gemm_dx(dattn, wout, &mut dof, n, vd, hsz, pool);
2720
2721        let cfg = ops::GdnSeqCfg {
2722            nv: d.nv,
2723            nk: d.nk,
2724            dk: d.dk,
2725            dv: d.dv,
2726            kk: d.kk,
2727            rms_eps: self.eps,
2728            conv,
2729            a_log,
2730            dt_bias,
2731            norm,
2732        };
2733        #[cfg(feature = "cuda")]
2734        if crate::gpu::cuda_active() {
2735            let g = crate::gpu_cuda::BakeGdn {
2736                nv: d.nv,
2737                nk: d.nk,
2738                dk: d.dk,
2739                dv: d.dv,
2740                kk: d.kk,
2741                eps: self.eps as f32,
2742                conv,
2743                a_log,
2744                dt_bias,
2745                norm,
2746            };
2747            if crate::gpu_cuda::bake_gdn_ok(&g) {
2748                let t_gdn = std::time::Instant::now();
2749                let done = crate::gpu_cuda::bake_gdn_bwd(qkv, z, a, bstr, &dof, b, t, &g);
2750                prof::add(&prof::GDN, t_gdn);
2751                if let Some((dqkv, dz, da, db)) = done {
2752                    let mut dn1 = vec![0f32; n * hsz];
2753                    ops::gemm_dx(&dqkv, wqkv, &mut dn1, n, hsz, c_dim, pool);
2754                    ops::gemm_dx(&dz, wz, &mut dn1, n, hsz, vd, pool);
2755                    ops::gemm_dx(&da, wa, &mut dn1, n, hsz, nv, pool);
2756                    ops::gemm_dx(&db, wb, &mut dn1, n, hsz, nv, pool);
2757                    return dn1;
2758                }
2759            }
2760        }
2761        let qkv64: Vec<f64> = qkv.iter().map(|&v| v as f64).collect();
2762        let z64: Vec<f64> = z.iter().map(|&v| v as f64).collect();
2763        let a64: Vec<f64> = a.iter().map(|&v| v as f64).collect();
2764        let b64: Vec<f64> = bstr.iter().map(|&v| v as f64).collect();
2765        let dof64: Vec<f64> = dof.iter().map(|&v| v as f64).collect();
2766        let mut pre64 = vec![0f64; n * c_dim];
2767        let mut cq64 = vec![0f64; n * c_dim];
2768        for bi in 0..b {
2769            let r = bi * t * c_dim..(bi + 1) * t * c_dim;
2770            ops::gdn_conv_fwd(
2771                &qkv64[r.clone()],
2772                t,
2773                c_dim,
2774                d.kk,
2775                conv,
2776                &mut pre64[r.clone()],
2777                &mut cq64[r],
2778            );
2779        }
2780
2781        let mut dcq64 = vec![0f64; n * c_dim];
2782        let mut dz64 = vec![0f64; n * vd];
2783        let mut da64 = vec![0f64; n * nv];
2784        let mut db64 = vec![0f64; n * nv];
2785        {
2786            let units = b * d.nk;
2787            let rep_v = d.nv / d.nk;
2788            let kd = d.nk * d.dk;
2789            let dcqp = SendMut(dcq64.as_mut_ptr());
2790            let dzp = SendMut(dz64.as_mut_ptr());
2791            let dap = SendMut(da64.as_mut_ptr());
2792            let dbp = SendMut(db64.as_mut_ptr());
2793            let (cqr, zr, ar, br, dor) = (&cq64, &z64, &a64, &b64, &dof64);
2794            let cfg_ref = &cfg;
2795            let run_unit = |u: usize| {
2796                let (bi, ko) = (u / d.nk, u % d.nk);
2797                // Full-width locals — the group only fills its own
2798                // channels; the scatter below copies exactly those.
2799                let mut dcq_l = vec![0f64; t * c_dim];
2800                let mut dz_l = vec![0f64; t * vd];
2801                let mut da_l = vec![0f64; t * nv];
2802                let mut db_l = vec![0f64; t * nv];
2803                ops::gdn_group_bwd(
2804                    &cqr[bi * t * c_dim..(bi + 1) * t * c_dim],
2805                    &zr[bi * t * vd..(bi + 1) * t * vd],
2806                    &ar[bi * t * nv..(bi + 1) * t * nv],
2807                    &br[bi * t * nv..(bi + 1) * t * nv],
2808                    t,
2809                    cfg_ref,
2810                    ko,
2811                    &dor[bi * t * vd..(bi + 1) * t * vd],
2812                    &mut dcq_l,
2813                    &mut dz_l,
2814                    &mut da_l,
2815                    &mut db_l,
2816                );
2817                // SAFETY of every store below: the written channel /
2818                // column ranges are exclusively owned by (bi, ko).
2819                for p in 0..t {
2820                    let row = (bi * t + p) * c_dim;
2821                    for c in ko * d.dk..(ko + 1) * d.dk {
2822                        unsafe {
2823                            *dcqp.at(row + c) = dcq_l[p * c_dim + c];
2824                            *dcqp.at(row + kd + c) = dcq_l[p * c_dim + kd + c];
2825                        }
2826                    }
2827                    for hh in 0..rep_v {
2828                        let h = ko * rep_v + hh;
2829                        for dj in 0..d.dv {
2830                            unsafe {
2831                                *dcqp.at(row + 2 * kd + h * d.dv + dj) =
2832                                    dcq_l[p * c_dim + 2 * kd + h * d.dv + dj];
2833                                *dzp.at((bi * t + p) * vd + h * d.dv + dj) =
2834                                    dz_l[p * vd + h * d.dv + dj];
2835                            }
2836                        }
2837                        unsafe {
2838                            *dap.at((bi * t + p) * nv + h) = da_l[p * nv + h];
2839                            *dbp.at((bi * t + p) * nv + h) = db_l[p * nv + h];
2840                        }
2841                    }
2842                }
2843            };
2844            match pool {
2845                Some(p) if units > 1 => p.run(&|widx, nw| {
2846                    for u in (widx..units).step_by(nw) {
2847                        run_unit(u);
2848                    }
2849                }),
2850                _ => {
2851                    for u in 0..units {
2852                        run_unit(u);
2853                    }
2854                }
2855            }
2856        }
2857
2858        let mut dqkv64 = vec![0f64; n * c_dim];
2859        for bi in 0..b {
2860            let r = bi * t * c_dim..(bi + 1) * t * c_dim;
2861            ops::gdn_conv_bwd(
2862                &pre64[r.clone()],
2863                t,
2864                c_dim,
2865                d.kk,
2866                conv,
2867                &dcq64[r.clone()],
2868                &mut dqkv64[r],
2869            );
2870        }
2871        let to32 = |v: &[f64]| -> Vec<f32> { v.iter().map(|&x| x as f32).collect() };
2872        let (dqkv, dz, da, db) = (to32(&dqkv64), to32(&dz64), to32(&da64), to32(&db64));
2873
2874        let mut dn1 = vec![0f32; n * hsz];
2875        ops::gemm_dx(&dqkv, wqkv, &mut dn1, n, hsz, c_dim, pool);
2876        ops::gemm_dx(&dz, wz, &mut dn1, n, hsz, vd, pool);
2877        ops::gemm_dx(&da, wa, &mut dn1, n, hsz, nv, pool);
2878        ops::gemm_dx(&db, wb, &mut dn1, n, hsz, nv, pool);
2879        dn1
2880    }
2881
2882    /// Full forward: embeddings → layers → final hidden [b·t, hidden].
2883    /// `student` switches converted layers to the Nyström kernel and
2884    /// reads trainable weights from `ts`; `keep` collects each layer's
2885    /// input hidden for the checkpointed backward.
2886    fn forward_hidden(
2887        &self,
2888        ids: &[u32],
2889        b: usize,
2890        t: usize,
2891        ts: Option<&TrainState>,
2892        student: bool,
2893        keep: Option<&mut Vec<Vec<f32>>>,
2894    ) -> Vec<f32> {
2895        self.forward_span(SpanIn::Ids(ids), 0, self.nl, b, t, ts, student, keep)
2896    }
2897
2898    /// Layers `from..to` on the token embeddings of `ids` or on a hidden
2899    /// state entering layer `from`; `keep` collects each layer's input.
2900    #[allow(clippy::too_many_arguments)]
2901    fn forward_span(
2902        &self,
2903        input: SpanIn,
2904        from: usize,
2905        to: usize,
2906        b: usize,
2907        t: usize,
2908        ts: Option<&TrainState>,
2909        student: bool,
2910        mut keep: Option<&mut Vec<Vec<f32>>>,
2911    ) -> Vec<f32> {
2912        let hsz = self.hidden;
2913        let mut h = match input {
2914            SpanIn::Hidden(h) => h,
2915            SpanIn::Ids(ids) => {
2916                let mut h = vec![0f32; b * t * hsz];
2917                for (r, &id) in ids.iter().enumerate() {
2918                    let src = (id as usize).min(self.embed.len() / hsz - 1) * hsz;
2919                    h[r * hsz..(r + 1) * hsz].copy_from_slice(&self.embed[src..src + hsz]);
2920                }
2921                h
2922            }
2923        };
2924        for li in from..to {
2925            if let Some(k) = keep.as_deref_mut() {
2926                k.push(h.clone());
2927            }
2928            let mats = self.mats(li).expect("layer mats");
2929            let wts = ln_ffn(self, if student { ts } else { None }, li, &mats);
2930            let nys = student && self.o1_flags[li];
2931            h = self.layer_forward(li, &h, b, t, &wts, nys, false).0;
2932        }
2933        h
2934    }
2935
2936    /// The vocabulary head of [`Self::loss_and_dhidden`] over normed rows:
2937    /// (Σ w·ce, Σ w·kl, dNormed). `inv_w` is 1/Σw of the whole batch.
2938    #[allow(clippy::too_many_arguments)]
2939    fn head_core(
2940        &self,
2941        ns: &[f32],
2942        nt: &[f32],
2943        targets: &[u32],
2944        kl_w: f64,
2945        weights: Option<&[f32]>,
2946        inv_w: f64,
2947    ) -> (f64, f64, Vec<f32>) {
2948        let hsz = self.hidden;
2949        let n = targets.len();
2950        let pos_w = |i: usize| weights.map_or(1.0, |w| w[i] as f64);
2951        let pool = self.pool.as_deref();
2952        let wh = self.head_weight();
2953        let vs = self.vocab;
2954        let mut ce_sum = 0f64;
2955        let mut kl_sum = 0f64;
2956        let mut dns = vec![0f32; n * hsz];
2957        let mut ls = vec![0f32; LM_CHUNK * vs];
2958        let mut lt = vec![0f32; LM_CHUNK * vs];
2959        let mut dlg = vec![0f32; LM_CHUNK * vs];
2960        let mut r0 = 0usize;
2961        let nth = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4);
2962        while r0 < n {
2963            let r1 = (r0 + LM_CHUNK).min(n);
2964            let c = r1 - r0;
2965            // a chunk with nothing scored adds no loss and no gradient
2966            if weights.is_some_and(|w| w[r0..r1].iter().all(|&x| x == 0.0)) {
2967                r0 = r1;
2968                continue;
2969            }
2970            ops::gemm_nt(
2971                &ns[r0 * hsz..r1 * hsz],
2972                wh,
2973                &mut ls[..c * vs],
2974                c,
2975                hsz,
2976                vs,
2977                pool,
2978            );
2979            ops::gemm_nt(
2980                &nt[r0 * hsz..r1 * hsz],
2981                wh,
2982                &mut lt[..c * vs],
2983                c,
2984                hsz,
2985                vs,
2986                pool,
2987            );
2988            // Rows are independent (each writes only its own gradient row):
2989            // the vocabulary-wide softmaxes run on all cores.
2990            let per = c.div_ceil(nth.min(c)).max(1);
2991            let parts: Vec<(f64, f64)> = std::thread::scope(|sc| {
2992                let (ls, lt, pos_w) = (&ls, &lt, &pos_w);
2993                let hs: Vec<_> = dlg[..c * vs]
2994                    .chunks_mut(per * vs)
2995                    .enumerate()
2996                    .map(|(ti, dchunk)| {
2997                        sc.spawn(move || {
2998                            let mut acc = (0f64, 0f64);
2999                            for (k, drow) in dchunk.chunks_mut(vs).enumerate() {
3000                                let r = ti * per + k;
3001                                let w = pos_w(r0 + r);
3002                                if w == 0.0 {
3003                                    drow.fill(0.0);
3004                                    continue;
3005                                }
3006                                let (ce, kl) = ops::ce_kl_position(
3007                                    &ls[r * vs..(r + 1) * vs],
3008                                    &lt[r * vs..(r + 1) * vs],
3009                                    targets[r0 + r] as usize,
3010                                    kl_w,
3011                                    w * inv_w,
3012                                    drow,
3013                                );
3014                                acc.0 += w * ce;
3015                                acc.1 += w * kl;
3016                            }
3017                            acc
3018                        })
3019                    })
3020                    .collect();
3021                hs.into_iter().map(|h| h.join().expect("ce/kl worker")).collect()
3022            });
3023            for (ce, kl) in parts {
3024                ce_sum += ce;
3025                kl_sum += kl;
3026            }
3027            ops::gemm_dx(
3028                &dlg[..c * vs],
3029                wh,
3030                &mut dns[r0 * hsz..r1 * hsz],
3031                c,
3032                hsz,
3033                vs,
3034                pool,
3035            );
3036            r0 = r1;
3037        }
3038
3039        (ce_sum, kl_sum, dns)
3040    }
3041
3042    /// Loss head: chunked tied-lm_head CE+KL against the teacher hidden,
3043    /// returning (ce_mean, kl_mean, dHidden_student). `weights` scales each
3044    /// position (the means are then weighted means; a 0 position adds
3045    /// nothing and gets no gradient).
3046    fn loss_and_dhidden(
3047        &self,
3048        hs: &[f32],
3049        ht: &[f32],
3050        targets: &[u32],
3051        kl_w: f64,
3052        weights: Option<&[f32]>,
3053    ) -> (f64, f64, Vec<f32>) {
3054        let hsz = self.hidden;
3055        let n = targets.len();
3056        let wsum: f64 = weights.map_or(n as f64, |w| w.iter().map(|&v| v as f64).sum());
3057        let inv_w = if wsum > 0.0 { 1.0 / wsum } else { 0.0 };
3058
3059        let mut ns = vec![0f32; n * hsz];
3060        let mut invs = vec![0f32; n];
3061        ops::rmsnorm_fwd(
3062            hs,
3063            &self.final_norm,
3064            self.eps,
3065            self.gemma,
3066            &mut ns,
3067            &mut invs,
3068        );
3069        let mut nt = vec![0f32; n * hsz];
3070        let mut invt = vec![0f32; n];
3071        ops::rmsnorm_fwd(
3072            ht,
3073            &self.final_norm,
3074            self.eps,
3075            self.gemma,
3076            &mut nt,
3077            &mut invt,
3078        );
3079
3080        // Only scored rows reach the head (vocabulary GEMMs + softmaxes, the
3081        // dearest part of a step): an answer-only loss scores about half of
3082        // a window's positions.
3083        let (ce_sum, kl_sum, dns) = match weights {
3084            Some(w) if w.iter().any(|&x| x == 0.0) => {
3085                let rows: Vec<usize> = (0..n).filter(|&i| w[i] > 0.0).collect();
3086                let gather = |src: &[f32]| -> Vec<f32> {
3087                    rows.iter().flat_map(|&r| src[r * hsz..(r + 1) * hsz].iter().copied()).collect()
3088                };
3089                let (nsc, ntc) = (gather(&ns), gather(&nt));
3090                let tgc: Vec<u32> = rows.iter().map(|&r| targets[r]).collect();
3091                let wc: Vec<f32> = rows.iter().map(|&r| w[r]).collect();
3092                let (ce, kl, dnc) = self.head_core(&nsc, &ntc, &tgc, kl_w, Some(&wc), inv_w);
3093                let mut dns = vec![0f32; n * hsz];
3094                for (k, &r) in rows.iter().enumerate() {
3095                    dns[r * hsz..(r + 1) * hsz].copy_from_slice(&dnc[k * hsz..(k + 1) * hsz]);
3096                }
3097                (ce, kl, dns)
3098            }
3099            _ => self.head_core(&ns, &nt, targets, kl_w, weights, inv_w),
3100        };
3101        let mut dhs = vec![0f32; n * hsz];
3102        ops::rmsnorm_bwd(
3103            hs,
3104            &self.final_norm,
3105            &invs,
3106            &dns,
3107            self.gemma,
3108            &mut dhs,
3109            None,
3110        );
3111        (ce_sum * inv_w, kl_sum * inv_w, dhs)
3112    }
3113
3114    /// Checkpointed backward: per layer, recompute the intra-layer
3115    /// activations and differentiate.
3116    fn backward(
3117        &self,
3118        b: usize,
3119        t: usize,
3120        keep: &[Vec<f32>],
3121        dh_last: Vec<f32>,
3122        ts: &mut TrainState,
3123    ) {
3124        self.backward_from(0, b, t, keep, dh_last, ts)
3125    }
3126
3127    /// [`Self::backward`] down to layer `from` only (`keep[i]` is the input
3128    /// of layer `from + i`): below the lowest trainable layer there is
3129    /// nothing to differentiate.
3130    fn backward_from(
3131        &self,
3132        from: usize,
3133        b: usize,
3134        t: usize,
3135        keep: &[Vec<f32>],
3136        dh_last: Vec<f32>,
3137        ts: &mut TrainState,
3138    ) {
3139        // Split-borrow: the weight view reads `data`, the grads write
3140        // `grad` — disjoint fields of TrainState.
3141        let TrainState {
3142            layers, data, grad, ..
3143        } = ts;
3144        let mut dh = dh_last;
3145        for li in (from..self.nl).rev() {
3146            let h_in = &keep[li - from];
3147            let nys = self.o1_flags[li];
3148            let slot = layers.iter().position(|&x| x == li);
3149            let mats_hold = self.mats(li).expect("layer mats");
3150            let wts = match slot {
3151                Some(s) => {
3152                    let bi = s * PARAMS_PER_LAYER;
3153                    LnFfn {
3154                        iln: &data[bi],
3155                        pln: &data[bi + 1],
3156                        gate: &data[bi + 2],
3157                        up: &data[bi + 3],
3158                        down: &data[bi + 4],
3159                        gu: None,
3160                    }
3161                }
3162                None => {
3163                    let l = &self.layers[li];
3164                    LnFfn {
3165                        iln: &l.iln,
3166                        pln: &l.pln,
3167                        gate: &[],
3168                        up: &[],
3169                        down: &mats_hold.down,
3170                        gu: Some(&mats_hold.gu),
3171                    }
3172                }
3173            };
3174            let (_, acts) = self.layer_forward(li, h_in, b, t, &wts, nys, true);
3175            let acts = acts.expect("want_acts");
3176            dh = match slot {
3177                Some(s) => {
3178                    let gb = s * PARAMS_PER_LAYER;
3179                    let gr = &mut grad[gb..gb + PARAMS_PER_LAYER];
3180                    self.layer_backward(li, h_in, b, t, &wts, nys, &acts, &dh, Some(gr))
3181                }
3182                None => self.layer_backward(li, h_in, b, t, &wts, nys, &acts, &dh, None),
3183            };
3184        }
3185    }
3186
3187    /// Test-only: one full training-graph evaluation — teacher forward,
3188    /// student forward, CE+KL loss, checkpointed backward into the
3189    /// grads. Returns the weighted total loss. The block-level
3190    /// gradcheck runs finite differences over trainable weights through
3191    /// this, which exercises EVERY through-grad in the graph (layer-0
3192    /// gains flow through all attention/rope/qk-norm/GQA paths above).
3193    #[doc(hidden)]
3194    pub fn loss_and_grads_for_test(
3195        &self,
3196        ids: &[u32],
3197        tgt: &[u32],
3198        b: usize,
3199        t: usize,
3200        ts: &mut TrainState,
3201        kl_w: f64,
3202    ) -> f64 {
3203        let ht = self.forward_hidden(ids, b, t, None, false, None);
3204        let mut keep = Vec::with_capacity(self.nl);
3205        let hs = self.forward_hidden(ids, b, t, Some(ts), true, Some(&mut keep));
3206        let (ce, kl, dhs) = self.loss_and_dhidden(&hs, &ht, tgt, kl_w, None);
3207        ts.zero_grad();
3208        self.backward(b, t, &keep, dhs, ts);
3209        (1.0 - kl_w) * ce + kl_w * kl
3210    }
3211
3212    /// Teacher-forced CE perplexity on deterministic evenly-spaced val
3213    /// windows (`heal_hybridk_06b.py::val_ppl` discipline — random
3214    /// windows made gate comparisons ride ±15% noise).
3215    pub fn val_ppl(
3216        &self,
3217        va: &[u32],
3218        ts: Option<&TrainState>,
3219        student: bool,
3220        bs: usize,
3221        nrounds: usize,
3222        seq: usize,
3223    ) -> f64 {
3224        let nwin = nrounds * bs;
3225        if va.len() < seq + 2 || nwin == 0 {
3226            return f64::NAN;
3227        }
3228        let stride = (va.len() - seq - 1) / nwin;
3229        let hsz = self.hidden;
3230        let wh = self.head_weight();
3231        let vs = self.vocab;
3232        let pool = self.pool.as_deref();
3233        let mut nll = 0f64;
3234        let mut cnt = 0usize;
3235        for j in 0..nrounds {
3236            let mut ids = Vec::with_capacity(bs * seq);
3237            let mut tgt = Vec::with_capacity(bs * seq);
3238            for bi in 0..bs {
3239                let off = ((j * bs + bi) * stride.max(1)).min(va.len() - seq - 1);
3240                ids.extend_from_slice(&va[off..off + seq]);
3241                tgt.extend_from_slice(&va[off + 1..off + seq + 1]);
3242            }
3243            let h = self.forward_hidden(&ids, bs, seq, ts, student, None);
3244            let n = bs * seq;
3245            let mut ns = vec![0f32; n * hsz];
3246            let mut inv = vec![0f32; n];
3247            ops::rmsnorm_fwd(
3248                &h,
3249                &self.final_norm,
3250                self.eps,
3251                self.gemma,
3252                &mut ns,
3253                &mut inv,
3254            );
3255            let mut lg = vec![0f32; LM_CHUNK * vs];
3256            let mut r0 = 0usize;
3257            while r0 < n {
3258                let r1 = (r0 + LM_CHUNK).min(n);
3259                let c = r1 - r0;
3260                ops::gemm_nt(
3261                    &ns[r0 * hsz..r1 * hsz],
3262                    wh,
3263                    &mut lg[..c * vs],
3264                    c,
3265                    hsz,
3266                    vs,
3267                    pool,
3268                );
3269                for r in 0..c {
3270                    let row = &lg[r * vs..(r + 1) * vs];
3271                    let target = tgt[r0 + r] as usize;
3272                    let mut mx = f64::NEG_INFINITY;
3273                    for &v in row {
3274                        mx = mx.max(v as f64);
3275                    }
3276                    let mut s = 0f64;
3277                    for &v in row {
3278                        s += (v as f64 - mx).exp();
3279                    }
3280                    nll += mx + s.ln() - row[target.min(vs - 1)] as f64;
3281                    cnt += 1;
3282                }
3283                r0 = r1;
3284            }
3285        }
3286        (nll / cnt.max(1) as f64).exp()
3287    }
3288
3289    /// [`Self::val_ppl`] over an [`FcdStream`]: a plain stream takes the
3290    /// original evenly-spaced windows; a record stream scores up to
3291    /// `4·nrounds·bs` records, evenly spaced, each window at its record's
3292    /// start (or centred on its first scored token when the prompt is
3293    /// longer than half a window), weighted by the stream's loss weights.
3294    pub fn val_ppl_stream(
3295        &self,
3296        va: &FcdStream,
3297        ts: Option<&TrainState>,
3298        student: bool,
3299        bs: usize,
3300        nrounds: usize,
3301        seq: usize,
3302    ) -> f64 {
3303        if va.is_plain() {
3304            return self.val_ppl(va.ids, ts, student, bs, nrounds, seq);
3305        }
3306        if va.ids.len() < seq + 2 || bs == 0 {
3307            return f64::NAN;
3308        }
3309        let recs = va.scored_records();
3310        let want = (4 * nrounds * bs).min(recs.len());
3311        if want == 0 {
3312            return f64::NAN;
3313        }
3314        let picks: Vec<(usize, Vec<f32>)> = (0..want)
3315            .map(|j| {
3316                let rec = recs[j * recs.len() / want];
3317                let (st, _, f, _) = rec;
3318                let max_off = va.ids.len() - seq - 1;
3319                let off = if f - st < seq / 2 { st } else { f - seq / 2 }.min(max_off);
3320                (off, va.target_weights(off, seq, rec))
3321            })
3322            .collect();
3323        let hsz = self.hidden;
3324        let wh = self.head_weight();
3325        let vs = self.vocab;
3326        let pool = self.pool.as_deref();
3327        let (mut nll, mut wsum) = (0f64, 0f64);
3328        for group in picks.chunks(bs) {
3329            let b = group.len();
3330            let mut ids = Vec::with_capacity(b * seq);
3331            let mut tgt = Vec::with_capacity(b * seq);
3332            let mut tw = Vec::with_capacity(b * seq);
3333            for (off, w) in group {
3334                ids.extend_from_slice(&va.ids[*off..*off + seq]);
3335                tgt.extend_from_slice(&va.ids[*off + 1..*off + seq + 1]);
3336                tw.extend_from_slice(w);
3337            }
3338            let h = self.forward_hidden(&ids, b, seq, ts, student, None);
3339            let n = b * seq;
3340            let mut ns = vec![0f32; n * hsz];
3341            let mut inv = vec![0f32; n];
3342            ops::rmsnorm_fwd(&h, &self.final_norm, self.eps, self.gemma, &mut ns, &mut inv);
3343            let mut lg = vec![0f32; LM_CHUNK * vs];
3344            let mut r0 = 0usize;
3345            while r0 < n {
3346                let r1 = (r0 + LM_CHUNK).min(n);
3347                let c = r1 - r0;
3348                ops::gemm_nt(&ns[r0 * hsz..r1 * hsz], wh, &mut lg[..c * vs], c, hsz, vs, pool);
3349                for r in 0..c {
3350                    let w = tw[r0 + r] as f64;
3351                    if w == 0.0 {
3352                        continue;
3353                    }
3354                    let row = &lg[r * vs..(r + 1) * vs];
3355                    let target = tgt[r0 + r] as usize;
3356                    let mx = row.iter().fold(f64::NEG_INFINITY, |m, &v| m.max(v as f64));
3357                    let s: f64 = row.iter().map(|&v| (v as f64 - mx).exp()).sum();
3358                    nll += w * (mx + s.ln() - row[target.min(vs - 1)] as f64);
3359                    wsum += w;
3360                }
3361                r0 = r1;
3362            }
3363        }
3364        if wsum == 0.0 { f64::NAN } else { (nll / wsum).exp() }
3365    }
3366
3367    /// Weighted NLL of `tgt` under final hidden `h` (rows of `tgt.len()`):
3368    /// (Σ w·nll, Σ w).
3369    fn nll_on(&self, h: &[f32], tgt: &[u32], w: &[f32]) -> (f64, f64) {
3370        let hsz = self.hidden;
3371        let wh = self.head_weight();
3372        let vs = self.vocab;
3373        let pool = self.pool.as_deref();
3374        let n = tgt.len();
3375        let mut ns = vec![0f32; n * hsz];
3376        let mut inv = vec![0f32; n];
3377        ops::rmsnorm_fwd(h, &self.final_norm, self.eps, self.gemma, &mut ns, &mut inv);
3378        let mut lg = vec![0f32; LM_CHUNK * vs];
3379        let (mut nll, mut wsum) = (0f64, 0f64);
3380        let mut r0 = 0usize;
3381        while r0 < n {
3382            let r1 = (r0 + LM_CHUNK).min(n);
3383            let c = r1 - r0;
3384            if w[r0..r1].iter().any(|&x| x > 0.0) {
3385                ops::gemm_nt(&ns[r0 * hsz..r1 * hsz], wh, &mut lg[..c * vs], c, hsz, vs, pool);
3386                let lg = &lg;
3387                let parts: Vec<(f64, f64)> = std::thread::scope(|sc| {
3388                    let hs: Vec<_> = (0..c)
3389                        .map(|r| {
3390                            sc.spawn(move || {
3391                                let wr = w[r0 + r] as f64;
3392                                if wr == 0.0 {
3393                                    return (0.0, 0.0);
3394                                }
3395                                let row = &lg[r * vs..(r + 1) * vs];
3396                                let mx = row.iter().fold(f64::NEG_INFINITY, |m, &v| m.max(v as f64));
3397                                let se: f64 = row.iter().map(|&v| (v as f64 - mx).exp()).sum();
3398                                (wr * (mx + se.ln() - row[(tgt[r0 + r] as usize).min(vs - 1)] as f64), wr)
3399                            })
3400                        })
3401                        .collect();
3402                    hs.into_iter().map(|h| h.join().expect("nll worker")).collect()
3403                });
3404                for (a, b) in parts {
3405                    nll += a;
3406                    wsum += b;
3407                }
3408            }
3409            r0 = r1;
3410        }
3411        (nll, wsum)
3412    }
3413}
3414
3415/// One fixed training/validation window of a record stream.
3416struct Slot {
3417    off: usize,
3418    w: Vec<f32>,
3419    wsum: f64,
3420}
3421
3422/// Fixed windows over a record stream: a record that fits is one window
3423/// at its start; a longer one is covered by windows at half-window steps
3424/// (the last flush with its end). Windows without scored targets are left
3425/// out. Fixed windows are what lets the teacher and the frozen prefix be
3426/// computed once.
3427fn record_slots(s: &FcdStream, seq: usize, val: bool) -> Vec<Slot> {
3428    let max_off = s.ids.len() - seq - 1;
3429    let mut out = Vec::new();
3430    for rec in s.scored_records() {
3431        let (st, en, f, _) = rec;
3432        let offs: Vec<usize> = if en - st <= seq + 1 {
3433            vec![st.min(max_off)]
3434        } else if val {
3435            // one window per record, centred on the start of the answer
3436            vec![if f - st < seq / 2 { st } else { f - seq / 2 }.min(en - seq - 1).min(max_off)]
3437        } else {
3438            let last = (en - seq - 1).min(max_off);
3439            let mut v: Vec<usize> = (st..=last).step_by((seq / 2).max(1)).collect();
3440            if v.last() != Some(&last) {
3441                v.push(last);
3442            }
3443            v
3444        };
3445        for off in offs {
3446            let w = s.target_weights(off, seq, rec);
3447            let wsum: f64 = w.iter().map(|&x| x as f64).sum();
3448            if wsum > 0.0 {
3449                out.push(Slot { off, w, wsum });
3450            }
3451        }
3452    }
3453    out
3454}
3455
3456// ─────────────────────────── training loop ───────────────────────────
3457
3458/// Run the full certified polish: train, early-stop/restore-best, and
3459/// write `<out>` (source tensors byte-copied, polished LN/FFN as f32).
3460///
3461/// With `gate` (Patent 16 draft, claim 13), every eval checkpoint is
3462/// additionally scored by greedy generation through the REAL streaming
3463/// O(1) runtime, and the restored checkpoint is the lowest-ppl one
3464/// AMONG GATE-PASSERS; if none passes, the zero-shot state is restored
3465/// (identity polish) — the stage never makes generation worse than
3466/// conversion alone.
3467/// Polish `model`, optionally distilling from a SEPARATE `teacher` file.
3468///
3469/// Without a teacher the KL anchor is the model's own frozen state,
3470/// which is right for an O(1) conversion (the weights are the same, only
3471/// the attention kernel moved) and useless for a compression: the anchor
3472/// is then the damage itself, and `--kl 0` is the only sane setting.
3473/// Pointing `teacher` at the UNCOMPRESSED file makes the anchor what the
3474/// model is supposed to do, everywhere — not just on the training text.
3475/// The two files share embeddings and head (a narrowing rewrites FFN
3476/// tensors only), so one loss head serves both exactly.
3477pub fn run_polish_distilled(
3478    model: &Arc<CmfModel>,
3479    teacher: Option<&Arc<CmfModel>>,
3480    o1: &O1Cfg,
3481    hp: &FcdHyper,
3482    tr: &[u32],
3483    va: &[u32],
3484    out: &std::path::Path,
3485    gate: Option<&GenGateCfg>,
3486) -> Result<FcdReport, String> {
3487    run_polish_stream(
3488        model,
3489        teacher,
3490        o1,
3491        hp,
3492        FcdStream::plain(tr),
3493        FcdStream::plain(va),
3494        out,
3495        gate,
3496        None,
3497    )
3498}
3499
3500/// Files the record path runs through the runtime to build its window
3501/// cache, when they differ from the training files: e.g. q8_2f copies of
3502/// the teacher and the student, which the device executes, where an f16
3503/// file is expanded to f32 and runs on the host.
3504#[derive(Clone, Copy)]
3505pub struct CacheModels<'a> {
3506    pub teacher: &'a Arc<CmfModel>,
3507    pub student: &'a Arc<CmfModel>,
3508}
3509
3510/// [`run_polish_distilled`] over [`FcdStream`]s: per-token loss weights
3511/// (answer-only distillation) and record-bounded windows. Plain streams
3512/// reproduce the corpus behaviour exactly.
3513#[allow(clippy::too_many_arguments)]
3514pub fn run_polish_stream(
3515    model: &Arc<CmfModel>,
3516    teacher: Option<&Arc<CmfModel>>,
3517    o1: &O1Cfg,
3518    hp: &FcdHyper,
3519    tr: FcdStream,
3520    va: FcdStream,
3521    out: &std::path::Path,
3522    gate: Option<&GenGateCfg>,
3523    cache_models: Option<CacheModels>,
3524) -> Result<FcdReport, String> {
3525    if tr.ids.len() < hp.seq + 2 {
3526        return Err(format!(
3527            "train corpus too small: {} tokens < seq+2 = {}",
3528            tr.ids.len(),
3529            hp.seq + 2
3530        ));
3531    }
3532    let tr_recs = tr.scored_records();
3533    if tr_recs.is_empty() {
3534        return Err("train stream has no scored positions".into());
3535    }
3536    // Records drawn in proportion to their scored targets, so every scored
3537    // token is equally likely to be trained on.
3538    let tr_cum: Vec<f64> = tr_recs
3539        .iter()
3540        .scan(0f64, |acc, &(_, _, f, l)| {
3541            *acc += (l - f) as f64;
3542            Some(*acc)
3543        })
3544        .collect();
3545    let mut fm = FcdModel::from_cmf(model, o1, hp.polish_only)?;
3546    fm.polish_only = hp.polish_only;
3547    let fm = fm;
3548    if !tr.is_plain() {
3549        // the record path never builds an f32 teacher replica: the runtime
3550        // computes the teacher's hidden states once per window
3551        let converted = fm.converted();
3552        if converted.is_empty() {
3553            return Err("no converted layers under this --o1 spec (nothing to polish)".into());
3554        }
3555        return polish_records(model, fm, teacher, converted, o1, hp, tr, va, out, gate, cache_models);
3556    }
3557    let tfm: Option<FcdModel> = match teacher {
3558        Some(t) => {
3559            let off = O1Cfg {
3560                layers: O1Layers::List(Vec::new()),
3561                m: o1.m,
3562                w: o1.w,
3563                sink: o1.sink,
3564                rect: o1.rect,
3565            };
3566            let mut t = FcdModel::from_cmf(t, &off, true)?;
3567            t.polish_only = true;
3568            if t.hidden != fm.hidden || t.nl != fm.nl {
3569                return Err(format!(
3570                    "teacher geometry differs: hidden {}/{} layers {}/{}",
3571                    t.hidden, fm.hidden, t.nl, fm.nl
3572                ));
3573            }
3574            tracing::info!("fcd: distilling from a separate teacher file");
3575            Some(t)
3576        }
3577        None => None,
3578    };
3579    let converted = fm.converted();
3580    if converted.is_empty() {
3581        return Err("no converted layers under this --o1 spec (nothing to polish)".into());
3582    }
3583    tracing::info!(
3584        "fcd: {} layers converted ({} trainable tensors), m={} w={} sink={}, \
3585         corpus train {} / val {} tokens",
3586        converted.len(),
3587        converted.len() * PARAMS_PER_LAYER,
3588        fm.nys.m,
3589        fm.nys.w,
3590        fm.nys.sink,
3591        tr.ids.len(),
3592        va.ids.len()
3593    );
3594
3595    let mut ts = TrainState::new(&fm);
3596    let teacher_ppl = match &tfm {
3597        Some(t) => t.val_ppl_stream(&va, None, false, hp.bs, 2, hp.seq),
3598        None => fm.val_ppl_stream(&va, None, false, hp.bs, 2, hp.seq),
3599    };
3600    let ppl_start = fm.val_ppl_stream(&va, Some(&ts), true, hp.bs, 2, hp.seq);
3601    tracing::info!(
3602        "fcd: quick-val teacher ppl {teacher_ppl:.2} | zero-shot o1 student ppl {ppl_start:.2}"
3603    );
3604
3605    // ── generation gate (claim 13): baseline at step 0 ──
3606    let mut gate_state: Option<(Pipeline, Vec<f64>)> = match gate {
3607        Some(g) if !g.prompts.is_empty() => {
3608            let greedy = SamplerConfig {
3609                temperature: 0.0,
3610                top_p: 1.0,
3611                presence_penalty: 0.0,
3612                top_k: 0,
3613                repetition_penalty: 1.0,
3614                min_p: 0.0,
3615                seed: Some(0),
3616                suppress_tokens: Vec::new(),
3617                penalty_window: 0,
3618                loop_stop: false,
3619            };
3620            let mut pipe = Pipeline::from_model(model, greedy)
3621                .map_err(|e| format!("gen-gate pipeline: {e}"))?;
3622            if !hp.polish_only {
3623                pipe.set_o1(Some(o1.clone()));
3624            }
3625            apply_trainables(&mut pipe, &fm, &ts);
3626            let base = gate_gen_scores(&mut pipe, g)?;
3627            tracing::info!("fcd gen-gate baseline loop-scores: {base:?}");
3628            Some((pipe, base))
3629        }
3630        Some(_) => {
3631            tracing::warn!("fcd gen-gate requested but val stream too short — gate off");
3632            None
3633        }
3634        None => None,
3635    };
3636    // Identity fallback: the pre-training master copies.
3637    let init_snapshot: Option<Vec<Vec<f32>>> = gate_state.is_some().then(|| ts.data.clone());
3638    let mut gate_evals: Vec<(usize, f64, Vec<f64>, bool)> = Vec::new();
3639
3640    let mut rng = SplitMix64::new(hp.seed);
3641    let mut best: (f64, Option<Vec<Vec<f32>>>, usize) = (f64::INFINITY, None, 0);
3642    let mut losses: Vec<(f64, f64)> = Vec::with_capacity(hp.steps);
3643    let t0 = std::time::Instant::now();
3644    let n_per_step = hp.bs * hp.seq;
3645    for st in 1..=hp.steps {
3646        // Fresh random windows each step (the recipe; indices need not
3647        // match the torch RNG — the distribution does).
3648        let mut ids = Vec::with_capacity(n_per_step);
3649        let mut tgt = Vec::with_capacity(n_per_step);
3650        let mut tw: Vec<f32> = Vec::with_capacity(n_per_step);
3651        for _ in 0..hp.bs {
3652            let off = if tr.is_plain() {
3653                (rng.next_u64() as usize) % (tr.ids.len() - hp.seq - 1)
3654            } else {
3655                let total = *tr_cum.last().unwrap();
3656                let u = (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64 * total;
3657                let r = tr_cum.partition_point(|&c| c <= u).min(tr_recs.len() - 1);
3658                let rec = tr_recs[r];
3659                let p = rec.2 + (rng.next_u64() as usize) % (rec.3 - rec.2);
3660                let off = tr.window_start(rec, p, hp.seq, rng.next_u64());
3661                tw.extend(tr.target_weights(off, hp.seq, rec));
3662                off
3663            };
3664            ids.extend_from_slice(&tr.ids[off..off + hp.seq]);
3665            tgt.extend_from_slice(&tr.ids[off + 1..off + hp.seq + 1]);
3666        }
3667
3668        let ht = match &tfm {
3669            Some(t) => t.forward_hidden(&ids, hp.bs, hp.seq, None, false, None),
3670            None => fm.forward_hidden(&ids, hp.bs, hp.seq, None, false, None),
3671        };
3672        let mut keep: Vec<Vec<f32>> = Vec::with_capacity(fm.nl);
3673        let hs = fm.forward_hidden(&ids, hp.bs, hp.seq, Some(&ts), true, Some(&mut keep));
3674        let (ce, kl, dhs) =
3675            fm.loss_and_dhidden(&hs, &ht, &tgt, hp.kl_w, (!tr.is_plain()).then_some(&tw[..]));
3676        ts.zero_grad();
3677        fm.backward(hp.bs, hp.seq, &keep, dhs, &mut ts);
3678        let gn = ts.clip_and_step(hp.lr);
3679        losses.push((ce, kl));
3680
3681        let el = t0.elapsed().as_secs_f64();
3682        tracing::info!(
3683            "fcd step {st}/{}: ce {ce:.3} kl {kl:.3} |g| {gn:.3} ({:.1}s/step)",
3684            hp.steps,
3685            el / st as f64
3686        );
3687        if hp.eval_every > 0 && st % hp.eval_every == 0 {
3688            let p = fm.val_ppl_stream(&va, Some(&ts), true, hp.bs, 2, hp.seq);
3689            match (&mut gate_state, gate) {
3690                (Some((pipe, base)), Some(g)) => {
3691                    apply_trainables(pipe, &fm, &ts);
3692                    let scores = gate_gen_scores(pipe, g)?;
3693                    let pass = gate_pass(&scores, base, g.threshold, g.baseline_slack);
3694                    let tag = if pass && p < best.0 {
3695                        best = (p, Some(ts.data.clone()), st);
3696                        " *best*"
3697                    } else {
3698                        ""
3699                    };
3700                    tracing::info!(
3701                        "fcd eval step {st}: val ppl {p:.2} | gen-gate {}                          (loop-scores {scores:?}){tag}",
3702                        if pass { "PASS" } else { "FAIL" }
3703                    );
3704                    gate_evals.push((st, p, scores, pass));
3705                }
3706                _ => {
3707                    let tag = if p < best.0 {
3708                        best = (p, Some(ts.data.clone()), st);
3709                        " *best*"
3710                    } else {
3711                        ""
3712                    };
3713                    tracing::info!("fcd eval step {st}: val ppl {p:.2}{tag}");
3714                }
3715            }
3716        }
3717    }
3718
3719    // Early stop: restore the best checkpoint (certified: best was step
3720    // 150 of 300 in the torch run). Under the gate, `best` only ever
3721    // held GATE-PASSING checkpoints; none passing → identity restore.
3722    let mut gate_chosen: Option<usize> = None;
3723    if let Some(snap) = best.1.take() {
3724        ts.data = snap;
3725        gate_chosen = Some(best.2);
3726        tracing::info!(
3727            "fcd: restored best checkpoint from step {} (val ppl {:.2})",
3728            best.2,
3729            best.0
3730        );
3731    } else if let Some(init) = init_snapshot {
3732        ts.data = init;
3733        tracing::info!(
3734            "fcd: polish rejected by generation gate — identity artifact              (zero-shot state written; claim 13 floor)"
3735        );
3736    }
3737    let ppl_final = fm.val_ppl_stream(&va, Some(&ts), true, hp.bs, 6, hp.seq);
3738    let report = FcdReport {
3739        converted: converted.clone(),
3740        teacher_ppl,
3741        ppl_start,
3742        ppl_best: best.0.min(ppl_final),
3743        best_step: best.2,
3744        ppl_final,
3745        steps_run: hp.steps,
3746        sec_per_step: t0.elapsed().as_secs_f64() / hp.steps.max(1) as f64,
3747        losses,
3748        gate: gate_state.map(|(_, base)| GateReport {
3749            baseline: base,
3750            evals: gate_evals,
3751            chosen: gate_chosen,
3752        }),
3753    };
3754    save_polished(model, out, &fm, &ts, o1, hp, &report)?;
3755    Ok(report)
3756}
3757
3758/// The polish over a record stream (`FcdStream` with record starts): fixed
3759/// windows, so the teacher's final hidden state and the student's hidden
3760/// state entering its lowest trainable layer are computed once per window
3761/// (the frozen prefix and the teacher never change) — the teacher is freed
3762/// before training — and every step runs and differentiates only the
3763/// trainable tail.
3764#[allow(clippy::too_many_arguments)]
3765fn polish_records(
3766    model: &Arc<CmfModel>,
3767    fm: FcdModel,
3768    teacher: Option<&Arc<CmfModel>>,
3769    converted: Vec<usize>,
3770    o1: &O1Cfg,
3771    hp: &FcdHyper,
3772    tr: FcdStream,
3773    va: FcdStream,
3774    out: &std::path::Path,
3775    gate: Option<&GenGateCfg>,
3776    cache_models: Option<CacheModels>,
3777) -> Result<FcdReport, String> {
3778    let (t, hsz) = (hp.seq, fm.hidden);
3779    let mut ts = TrainState::new(&fm);
3780    let from = *ts.layers.iter().min().ok_or("no trainable layers")?;
3781    let tr_slots = record_slots(&tr, t, false);
3782    let mut va_slots = record_slots(&va, t, true);
3783    if va_slots.len() > 64 {
3784        // 64 val windows, evenly spaced over the records
3785        let k = va_slots.len();
3786        let keep: std::collections::HashSet<usize> = (0..64).map(|j| j * k / 64).collect();
3787        va_slots = va_slots.into_iter().enumerate().filter(|(i, _)| keep.contains(i)).map(|(_, s)| s).collect();
3788    }
3789    if tr_slots.is_empty() || va_slots.is_empty() {
3790        return Err("record streams have no scored windows".into());
3791    }
3792    let n_slots = tr_slots.len() + va_slots.len();
3793    let cache_bytes = n_slots as f64 * t as f64 * hsz as f64 * 4.0 * if from > 0 { 2.0 } else { 1.0 };
3794    tracing::info!(
3795        "fcd: {} train + {} val windows of {t}; trainable layers {}..{} — caching the teacher and the frozen prefix ({:.2} GB)",
3796        tr_slots.len(),
3797        va_slots.len(),
3798        from,
3799        fm.nl - 1,
3800        cache_bytes / 1e9
3801    );
3802    // ── the fixed parts of every window, computed once ──
3803    let t_cache = std::time::Instant::now();
3804    // The fixed parts come from the runtime's batched prefill (one window at
3805    // a time, the device where there is one): the teacher's final hidden
3806    // state and the student's state entering layer `from`. The training
3807    // replica's own forward is the fallback for an architecture without a
3808    // batched prefill.
3809    let runtime = |m: &Arc<CmfModel>| -> Option<Pipeline> {
3810        let mut p = Pipeline::from_model(m, SamplerConfig::default()).ok()?;
3811        p.set_confidence(false);
3812        p.can_prefill_batched().then_some(p)
3813    };
3814    let (t_file, s_file) = match cache_models {
3815        Some(c) => (c.teacher, c.student),
3816        None => (teacher.unwrap_or(model), model),
3817    };
3818    let mut t_rt = runtime(t_file);
3819    let mut s_rt = if from > 0 { runtime(s_file) } else { None };
3820    let fill = |s: &FcdStream, slots: &[Slot], label: &str, t_rt: &mut Option<Pipeline>, s_rt: &mut Option<Pipeline>| -> Result<(Vec<Vec<f32>>, Vec<Vec<f32>>), String> {
3821        let (mut pre, mut th) = (Vec::with_capacity(slots.len()), Vec::with_capacity(slots.len()));
3822        let tc = std::time::Instant::now();
3823        for (k, sl) in slots.iter().enumerate() {
3824            let ids = &s.ids[sl.off..sl.off + t];
3825            let h = match t_rt.as_mut() {
3826                Some(p) => p.final_hidden_rows(ids)?,
3827                None => fm.forward_hidden(ids, 1, t, None, false, None),
3828            };
3829            let p = if from == 0 {
3830                Vec::new()
3831            } else {
3832                match s_rt.as_mut() {
3833                    Some(p) => p.calib_window_span(ids, None, 0, from, from)?,
3834                    None => fm.forward_span(SpanIn::Ids(ids), 0, from, 1, t, None, true, None),
3835                }
3836            };
3837            if h.len() != t * hsz || (from > 0 && p.len() != t * hsz) {
3838                return Err(format!("window cache: hidden of {} / {} values, expected {}", h.len(), p.len(), t * hsz));
3839            }
3840            pre.push(p);
3841            th.push(h);
3842            if k % 64 == 63 {
3843                tracing::info!("fcd: {label} cache {}/{} windows ({:.0}s)", k + 1, slots.len(), tc.elapsed().as_secs_f64());
3844            }
3845        }
3846        Ok((pre, th))
3847    };
3848    // the whole-stack prefill must reproduce the span walk it replaces
3849    if let (Some(p), Some(sl)) = (t_rt.as_mut(), tr_slots.first()) {
3850        let ids = &tr.ids[sl.off..sl.off + t];
3851        let a = p.final_hidden_rows(ids)?;
3852        let b = p.calib_window_span(ids, None, 0, fm.nl, fm.nl)?;
3853        let num: f64 = a.iter().zip(&b).map(|(x, y)| ((x - y) as f64).powi(2)).sum();
3854        let den: f64 = b.iter().map(|y| (*y as f64).powi(2)).sum();
3855        tracing::info!("fcd: teacher prefill vs span walk, relative difference {:.2e}", (num / den.max(1e-30)).sqrt());
3856    }
3857    // Val windows are scored at every evaluation: all of them up front.
3858    // Train windows are drawn at random, steps×bs of them with repeats: each
3859    // is computed when first drawn and kept, so the cache holds only what
3860    // the run uses (a fraction of a long-record data set).
3861    let (va_pre, va_th) = fill(&va, &va_slots, "val", &mut t_rt, &mut s_rt)?;
3862    let mut tr_pre: Vec<Option<Vec<f32>>> = vec![None; tr_slots.len()];
3863    let mut tr_th: Vec<Option<Vec<f32>>> = vec![None; tr_slots.len()];
3864    tracing::info!("fcd: val window cache built in {:.0}s; train windows are cached as they are drawn", t_cache.elapsed().as_secs_f64());
3865
3866    let gather = |s: &FcdStream, slots: &[Slot], pre: &[Vec<f32>], th: &[Vec<f32>], pick: &[usize]| {
3867        let mut ids = Vec::with_capacity(pick.len() * t);
3868        let mut tgt = Vec::with_capacity(pick.len() * t);
3869        let mut w = Vec::with_capacity(pick.len() * t);
3870        let mut h0 = Vec::with_capacity(if from > 0 { pick.len() * t * hsz } else { 0 });
3871        let mut ht = Vec::with_capacity(pick.len() * t * hsz);
3872        for &i in pick {
3873            let sl = &slots[i];
3874            ids.extend_from_slice(&s.ids[sl.off..sl.off + t]);
3875            tgt.extend_from_slice(&s.ids[sl.off + 1..sl.off + t + 1]);
3876            w.extend_from_slice(&sl.w);
3877            h0.extend_from_slice(&pre[i]);
3878            ht.extend_from_slice(&th[i]);
3879        }
3880        (ids, tgt, w, h0, ht)
3881    };
3882    let student_hidden = |ids: &[u32], h0: Vec<f32>, b: usize, ts: &TrainState, keep: Option<&mut Vec<Vec<f32>>>| {
3883        if from > 0 {
3884            fm.forward_span(SpanIn::Hidden(h0), from, fm.nl, b, t, Some(ts), true, keep)
3885        } else {
3886            fm.forward_span(SpanIn::Ids(ids), 0, fm.nl, b, t, Some(ts), true, keep)
3887        }
3888    };
3889    // weighted val ppl over every val window (teacher: cached hiddens)
3890    let val_ppl = |ts: Option<&TrainState>| -> f64 {
3891        let (mut nll, mut ws) = (0f64, 0f64);
3892        let idx: Vec<usize> = (0..va_slots.len()).collect();
3893        for chunk in idx.chunks(hp.bs.max(1)) {
3894            let (ids, tgt, w, h0, ht) = gather(&va, &va_slots, &va_pre, &va_th, chunk);
3895            let h = match ts {
3896                Some(ts) => student_hidden(&ids, h0, chunk.len(), ts, None),
3897                None => ht,
3898            };
3899            let (a, b) = fm.nll_on(&h, &tgt, &w);
3900            nll += a;
3901            ws += b;
3902        }
3903        if ws == 0.0 { f64::NAN } else { (nll / ws).exp() }
3904    };
3905    let teacher_ppl = val_ppl(None);
3906    let ppl_start = val_ppl(Some(&ts));
3907    tracing::info!("fcd: val ppl (scored tokens) teacher {teacher_ppl:.3} | student before training {ppl_start:.3}");
3908
3909    let mut gate_state: Option<(Pipeline, Vec<f64>)> = match gate {
3910        Some(g) if !g.prompts.is_empty() => {
3911            let greedy = SamplerConfig {
3912                temperature: 0.0,
3913                top_p: 1.0,
3914                presence_penalty: 0.0,
3915                top_k: 0,
3916                repetition_penalty: 1.0,
3917                min_p: 0.0,
3918                seed: Some(0),
3919                suppress_tokens: Vec::new(),
3920                penalty_window: 0,
3921                loop_stop: false,
3922            };
3923            let mut pipe = Pipeline::from_model(model, greedy).map_err(|e| format!("gen-gate pipeline: {e}"))?;
3924            if !hp.polish_only {
3925                pipe.set_o1(Some(o1.clone()));
3926            }
3927            apply_trainables(&mut pipe, &fm, &ts);
3928            let base = gate_gen_scores(&mut pipe, g)?;
3929            tracing::info!("fcd gen-gate baseline loop-scores: {base:?}");
3930            Some((pipe, base))
3931        }
3932        _ => None,
3933    };
3934    let init_snapshot: Vec<Vec<f32>> = ts.data.clone();
3935    let mut gate_evals: Vec<(usize, f64, Vec<f64>, bool)> = Vec::new();
3936    // the zero-shot state is a candidate: training never makes val worse
3937    let mut best: (f64, Option<Vec<Vec<f32>>>, usize) = (ppl_start, None, 0);
3938    let cum: Vec<f64> = tr_slots
3939        .iter()
3940        .scan(0f64, |a, s| {
3941            *a += s.wsum;
3942            Some(*a)
3943        })
3944        .collect();
3945    let total = *cum.last().unwrap();
3946    let mut rng = SplitMix64::new(hp.seed);
3947    let mut losses: Vec<(f64, f64)> = Vec::with_capacity(hp.steps);
3948    let t0 = std::time::Instant::now();
3949    for st in 1..=hp.steps {
3950        let pick: Vec<usize> = (0..hp.bs)
3951            .map(|_| {
3952                let u = (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64 * total;
3953                cum.partition_point(|&c| c <= u).min(tr_slots.len() - 1)
3954            })
3955            .collect();
3956        for &i in &pick {
3957            if tr_th[i].is_none() {
3958                let (mut p, mut h) = fill(&tr, &tr_slots[i..i + 1], "train", &mut t_rt, &mut s_rt)?;
3959                tr_pre[i] = p.pop();
3960                tr_th[i] = h.pop();
3961            }
3962        }
3963        let pre_v: Vec<Vec<f32>> = pick.iter().map(|&i| tr_pre[i].clone().unwrap_or_default()).collect();
3964        let th_v: Vec<Vec<f32>> = pick.iter().map(|&i| tr_th[i].clone().unwrap_or_default()).collect();
3965        let local: Vec<usize> = (0..pick.len()).collect();
3966        let picked: Vec<Slot> = pick.iter().map(|&i| Slot { off: tr_slots[i].off, w: tr_slots[i].w.clone(), wsum: tr_slots[i].wsum }).collect();
3967        let (ids, tgt, w, h0, ht) = gather(&tr, &picked, &pre_v, &th_v, &local);
3968        let mut keep: Vec<Vec<f32>> = Vec::with_capacity(fm.nl - from);
3969        let t_step = std::time::Instant::now();
3970        let hs = student_hidden(&ids, h0, hp.bs, &ts, Some(&mut keep));
3971        let t_fwd = t_step.elapsed().as_secs_f64();
3972        let (ce, kl, dhs) = fm.loss_and_dhidden(&hs, &ht, &tgt, hp.kl_w, Some(&w));
3973        let t_loss = t_step.elapsed().as_secs_f64() - t_fwd;
3974        ts.zero_grad();
3975        fm.backward_from(from, hp.bs, t, &keep, dhs, &mut ts);
3976        let t_bwd = t_step.elapsed().as_secs_f64() - t_fwd - t_loss;
3977        let gn = ts.clip_and_step(hp.lr);
3978        if std::env::var("CMF_BAKE_PROF").is_ok() && st % 10 == 0 {
3979            tracing::info!(
3980                "fcd prof step {st}: forward {t_fwd:.2}s (attn {:.2} ffn {:.2}) · loss head {t_loss:.2}s · backward {t_bwd:.2}s · adam {:.2}s",
3981                prof::take(&prof::ATTN_FWD),
3982                prof::take(&prof::FFN_FWD),
3983                t_step.elapsed().as_secs_f64() - t_fwd - t_loss - t_bwd
3984            );
3985            let _ = prof::take(&prof::BWD);
3986        }
3987        losses.push((ce, kl));
3988        tracing::info!(
3989            "fcd step {st}/{}: ce {ce:.3} kl {kl:.3} |g| {gn:.3} ({:.1}s/step)",
3990            hp.steps,
3991            t0.elapsed().as_secs_f64() / st as f64
3992        );
3993        if hp.eval_every > 0 && (st % hp.eval_every == 0 || st == hp.steps) {
3994            let p = val_ppl(Some(&ts));
3995            let pass = match (&mut gate_state, gate) {
3996                (Some((pipe, base)), Some(g)) => {
3997                    apply_trainables(pipe, &fm, &ts);
3998                    let scores = gate_gen_scores(pipe, g)?;
3999                    let pass = gate_pass(&scores, base, g.threshold, g.baseline_slack);
4000                    gate_evals.push((st, p, scores, pass));
4001                    pass
4002                }
4003                _ => true,
4004            };
4005            let tag = if pass && p < best.0 {
4006                best = (p, Some(ts.data.clone()), st);
4007                " *best*"
4008            } else {
4009                ""
4010            };
4011            tracing::info!("fcd eval step {st}: val ppl {p:.3}{}{tag}", if pass { "" } else { " (gen-gate FAIL)" });
4012        }
4013    }
4014    drop((t_rt, s_rt));
4015    tracing::info!(
4016        "fcd: {} of {} train windows were drawn and cached",
4017        tr_th.iter().filter(|x| x.is_some()).count(),
4018        tr_slots.len()
4019    );
4020    let chosen = match best.1.take() {
4021        Some(snap) => {
4022            ts.data = snap;
4023            tracing::info!("fcd: restored best checkpoint from step {} (val ppl {:.3})", best.2, best.0);
4024            Some(best.2)
4025        }
4026        None => {
4027            ts.data = init_snapshot;
4028            tracing::info!("fcd: no checkpoint beat the untrained state on val — identity written");
4029            None
4030        }
4031    };
4032    let ppl_final = val_ppl(Some(&ts));
4033    let report = FcdReport {
4034        converted: converted.clone(),
4035        teacher_ppl,
4036        ppl_start,
4037        ppl_best: best.0.min(ppl_final),
4038        best_step: best.2,
4039        ppl_final,
4040        steps_run: hp.steps,
4041        sec_per_step: t0.elapsed().as_secs_f64() / hp.steps.max(1) as f64,
4042        losses,
4043        gate: gate_state.map(|(_, base)| GateReport { baseline: base, evals: gate_evals, chosen }),
4044    };
4045    save_polished(model, out, &fm, &ts, o1, hp, &report)?;
4046    Ok(report)
4047}
4048
4049/// Hot-swap the trainable LN/FFN master copies into a runtime Pipeline
4050/// (frozen tensors stay mmap-backed — this reproduces the artifact the
4051/// polish would write, without writing it).
4052fn apply_trainables(pipe: &mut Pipeline, fm: &FcdModel, ts: &TrainState) {
4053    let hidden = fm.hidden;
4054    for (slot, &li) in ts.layers.iter().enumerate() {
4055        let b = slot * PARAMS_PER_LAYER;
4056        let inter = fm.layers[li].inter;
4057        let lw = &mut pipe.weights.layers[li];
4058        lw.input_norm = ts.data[b].clone();
4059        lw.post_norm = ts.data[b + 1].clone();
4060        lw.ffn = FfnKind::Dense(DenseFfn {
4061            gate_proj: QTensor::from_f32(ts.data[b + 2].clone(), inter, hidden),
4062            up_proj: QTensor::from_f32(ts.data[b + 3].clone(), inter, hidden),
4063            down_proj: QTensor::from_f32(ts.data[b + 4].clone(), hidden, inter),
4064            act: crate::pipeline::Act::Silu,
4065            down_t: None,
4066            segs: Vec::new(),
4067        });
4068    }
4069}
4070
4071/// Greedy loop-score probe through the streaming runtime.
4072fn gate_gen_scores(pipe: &mut Pipeline, g: &GenGateCfg) -> Result<Vec<f64>, String> {
4073    g.prompts
4074        .iter()
4075        .map(|p| {
4076            pipe.generate_from_ids(p, g.gen_tokens, None, None)
4077                .map(|r| loop_score(&r.token_ids))
4078        })
4079        .collect()
4080}
4081
4082/// Write the polished container: every source tensor byte-copied except
4083/// the converted layers' LN/FFN, which become f32 (per-tensor dtypes
4084/// are first-class in the directory — no requant noise on fresh
4085/// weights). Adds `provenance.o1_attn` + `provenance.fcd`.
4086fn save_polished(
4087    model: &CmfModel,
4088    out: &std::path::Path,
4089    fm: &FcdModel,
4090    ts: &TrainState,
4091    o1: &O1Cfg,
4092    hp: &FcdHyper,
4093    report: &FcdReport,
4094) -> Result<(), String> {
4095    use cortiq_core::format::TensorSpec;
4096    let mut replace: std::collections::HashMap<String, (usize, usize)> =
4097        std::collections::HashMap::new(); // name → (slot, param idx)
4098    for (s, &li) in ts.layers.iter().enumerate() {
4099        let p = format!("model.layers.{li}.");
4100        for (k, suffix) in [
4101            (0usize, "input_layernorm.weight"),
4102            (1, "post_attention_layernorm.weight"),
4103            (2, "mlp.gate_proj.weight"),
4104            (3, "mlp.up_proj.weight"),
4105            (4, "mlp.down_proj.weight"),
4106        ] {
4107            replace.insert(format!("{p}{suffix}"), (s, k));
4108        }
4109    }
4110    let mut specs = Vec::with_capacity(model.tensors.len());
4111    for t in &model.tensors {
4112        if let Some(&(s, k)) = replace.get(&t.name) {
4113            let data = &ts.data[s * PARAMS_PER_LAYER + k];
4114            let mut bytes = Vec::with_capacity(data.len() * 4);
4115            for v in data {
4116                bytes.extend_from_slice(&v.to_le_bytes());
4117            }
4118            specs.push(TensorSpec {
4119                name: t.name.clone(),
4120                dtype: TensorDtype::F32,
4121                shape: t.shape.clone(),
4122                data: bytes,
4123            });
4124        } else {
4125            specs.push(TensorSpec {
4126                name: t.name.clone(),
4127                dtype: t.dtype,
4128                shape: t.shape.clone(),
4129                data: model.entry_bytes(t).to_vec(),
4130            });
4131        }
4132    }
4133
4134    let mut header = model.header.clone();
4135    let mut prov = match header.provenance.take() {
4136        Some(serde_json::Value::Object(m)) => m,
4137        _ => serde_json::Map::new(),
4138    };
4139    let layers_json = match &o1.layers {
4140        O1Layers::All => serde_json::json!("all"),
4141        O1Layers::Deep(n) => serde_json::json!(format!("deep{n}")),
4142        O1Layers::List(v) => serde_json::json!(v),
4143    };
4144    // A polish-only run names TRAINABLE layers with the o1 spec; its
4145    // attention stayed exact. Writing that spec as the runtime's O(1) hint
4146    // would switch those layers to Nyström attention at every later load.
4147    if !hp.polish_only {
4148        prov.insert(
4149            "o1_attn".into(),
4150            serde_json::json!({
4151                "layers": layers_json, "m": o1.m, "w": o1.w, "sink": o1.sink
4152            }),
4153        );
4154    }
4155    prov.insert(
4156        "fcd".into(),
4157        serde_json::json!({
4158            "steps": hp.steps, "lr": hp.lr, "kl_w": hp.kl_w,
4159            "bs": hp.bs, "seq": hp.seq,
4160            "teacher_ppl": report.teacher_ppl,
4161            "ppl_start": report.ppl_start,
4162            "ppl_final": report.ppl_final,
4163            "best_step": report.best_step,
4164            "converted_layers": report.converted,
4165            "polish_only": hp.polish_only,
4166        }),
4167    );
4168    header.provenance = Some(serde_json::Value::Object(prov));
4169    let _ = fm; // geometry only used for validation today
4170
4171    let masks = if model.masks.masks.is_empty() {
4172        None
4173    } else {
4174        Some(&model.masks)
4175    };
4176    CmfModel::write(out, &header, &specs, masks, model.vocab.as_deref())
4177        .map_err(|e| format!("writing polished cmf: {e}"))
4178}
4179
4180#[cfg(test)]
4181mod tests {
4182    use super::*;
4183
4184    /// The bug this pins: on a hybrid, `--o1 deep8` under `--polish-only`
4185    /// used to select two layers instead of eight, because the eligibility
4186    /// filter for the O(1) CONVERSION also ran for a plain polish.
4187    #[test]
4188    fn polish_only_keeps_recurrent_layers_trainable() {
4189        // A Qwen3.5-shaped stretch: mostly GDN, a full-attention layer
4190        // every fourth. Ask for the deepest eight.
4191        let is_full: Vec<bool> = (0..8).map(|i| i % 4 == 3).collect();
4192
4193        let mut converting = vec![true; 8];
4194        apply_layer_eligibility(&mut converting, &is_full, false);
4195        assert_eq!(
4196            converting.iter().filter(|&&b| b).count(),
4197            2,
4198            "an O(1) conversion may only take the full-attention layers"
4199        );
4200
4201        let mut polishing = vec![true; 8];
4202        apply_layer_eligibility(&mut polishing, &is_full, true);
4203        assert_eq!(
4204            polishing.iter().filter(|&&b| b).count(),
4205            8,
4206            "a polish trains FFN and norms, which every layer has"
4207        );
4208
4209        // An unflagged layer is never raised by either path.
4210        let mut none = vec![false; 8];
4211        apply_layer_eligibility(&mut none, &is_full, true);
4212        assert!(none.iter().all(|&b| !b));
4213    }
4214
4215    /// `/proc/meminfo` reports the HOST inside a container. Believing it
4216    /// is what killed a 27B bake: 944 GB read, 117 GB actually available,
4217    /// the f32 replica declared to fit, SIGKILL a minute later.
4218    #[test]
4219    fn the_container_ceiling_wins_over_the_host_figure() {
4220        let host = 944 * 1_000_000_000u64;
4221        let cgroup = 117 * 1_000_000_000u64;
4222        assert_eq!(effective_total(host, Some(cgroup)), cgroup);
4223        // No cgroup (bare metal): the host figure is the truth.
4224        assert_eq!(effective_total(host, None), host);
4225        // A cgroup wider than the machine cannot conjure memory.
4226        assert_eq!(effective_total(host, Some(host * 2)), host);
4227    }
4228
4229    /// Headroom inside a cgroup is limit-minus-held, not host-free: the
4230    /// host can have hundreds of gigabytes free that this process will
4231    /// never be allowed to touch.
4232    #[test]
4233    fn container_headroom_is_the_limit_minus_what_it_holds() {
4234        let host_free = 800 * 1_000_000_000u64;
4235        let limit = 117 * 1_000_000_000u64;
4236        let used = 79 * 1_000_000_000u64;
4237        assert_eq!(
4238            effective_available(host_free, Some(limit), Some(used)),
4239            38 * 1_000_000_000u64
4240        );
4241        // Over the limit already — report nothing left, never underflow.
4242        assert_eq!(
4243            effective_available(host_free, Some(limit), Some(limit + 1)),
4244            0
4245        );
4246        // Limit known, usage not: fall back to the limit itself.
4247        assert_eq!(effective_available(host_free, Some(limit), None), limit);
4248        // Neither known: the host figure stands.
4249        assert_eq!(effective_available(host_free, None, None), host_free);
4250    }
4251
4252    /// Claim-13 selection: lowest ppl AMONG PASSING, not global lowest.
4253    #[test]
4254    fn gate_selects_lowest_ppl_among_passing() {
4255        let base = vec![0.10, 0.00, 0.20];
4256        let evals = vec![
4257            (25usize, 21.0, vec![0.10, 0.05, 0.20]), // pass
4258            (50, 18.0, vec![0.40, 0.00, 0.10]),      // fail: 0.40 > threshold
4259            (75, 19.0, vec![0.15, 0.05, 0.25]),      // pass — best passing
4260            (100, 18.5, vec![0.20, 0.30, 0.20]),     // fail: 0.30 > base+0.10
4261        ];
4262        let sel = select_checkpoint(&evals, &base, 0.35, 0.10);
4263        assert_eq!(sel, Some(2), "step 75 is the lowest-ppl PASSING checkpoint");
4264    }
4265
4266    /// All checkpoints fail → identity (None): the polish must never
4267    /// make generation worse than conversion alone.
4268    #[test]
4269    fn gate_all_fail_is_identity() {
4270        let base = vec![0.0, 0.0, 0.0];
4271        let evals = vec![
4272            (25usize, 15.0, vec![0.50, 0.0, 0.0]),
4273            (50, 14.0, vec![0.0, 0.36, 0.0]),
4274            (75, 13.0, vec![0.0, 0.0, 0.11]), // 0.11 > 0 + 0.10 slack
4275        ];
4276        assert_eq!(select_checkpoint(&evals, &base, 0.35, 0.10), None);
4277    }
4278
4279    /// Boundary discipline: scores AT the threshold / AT base+slack pass
4280    /// ("exceeds" is strict); ties in ppl resolve to the earliest step.
4281    #[test]
4282    fn gate_boundaries_and_tie_break() {
4283        let base = vec![0.25];
4284        assert!(gate_pass(&[0.35], &base, 0.35, 0.10), "== threshold passes");
4285        assert!(
4286            gate_pass(&[0.35], &[0.25], 0.35, 0.10),
4287            "== base+slack passes"
4288        );
4289        assert!(!gate_pass(&[0.351], &base, 0.35, 0.10));
4290        assert!(!gate_pass(&[0.30], &[0.10], 0.35, 0.10), "0.30 > 0.10+0.10");
4291        let evals = vec![(25usize, 20.0, vec![0.10]), (50, 20.0, vec![0.10])];
4292        assert_eq!(
4293            select_checkpoint(&evals, &base, 0.35, 0.10),
4294            Some(0),
4295            "equal ppl → earliest checkpoint"
4296        );
4297    }
4298}
4299
4300/// Backwards-compatible entry point: polish with the model as its own
4301/// KL anchor.
4302pub fn run_polish(
4303    model: &Arc<CmfModel>,
4304    o1: &O1Cfg,
4305    hp: &FcdHyper,
4306    tr: &[u32],
4307    va: &[u32],
4308    out: &std::path::Path,
4309    gate: Option<&GenGateCfg>,
4310) -> Result<FcdReport, String> {
4311    run_polish_distilled(model, None, o1, hp, tr, va, out, gate)
4312}