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