Skip to main content

cortiq_engine/
skillbake.rs

1//! Native DTG-MA skill bake (Patent 2) — no Python, no torch.
2//!
3//! The certified recipe of `converter/make_skill_l1fcd.py`, in Rust on
4//! the `FcdModel` f32 replica:
5//!
6//! - **Phase A** — a trainable L1 mask over FFN neurons (one logit per
7//!   neuron, applied to the input of down_proj as σ(m)): pure LM loss
8//!   on the task corpus + a progressive L1 penalty. Every 30 steps the
9//!   binarized mask (σ>τ) is scored on held-out chunks; the best
10//!   checkpoint — the *denoising bottom* — is restored at the end.
11//!   Pruning noise neurons IMPROVES the model before it starts to hurt.
12//! - **Phase B** — FCD: the FFN of the last N layers trains against the
13//!   same LM loss with the hard mask active (cosine LR), held-out
14//!   gated, best checkpoint restored.
15//!
16//! Attention (softmax and GDN alike) is FROZEN and carries no gradient
17//! — exactly like the reference recipe (`torch.no_grad()` around the
18//! attention branch): the backward walks the residual stream through
19//! the FFN chain only, which is what makes a pure-Rust backward small.
20
21use crate::fcd::{AttnW, FcdModel, LnFfn, act_bwd_rows, add_into_pooled, pooled_rows, rmsnorm_bwd_pooled, rmsnorm_fwd_pooled};
22use crate::fcd_ops as ops;
23use crate::sampler::SplitMix64;
24use cortiq_core::CmfModel;
25use std::sync::Arc;
26
27/// Supervised chat records scored on the assistant's answer only: every
28/// target from the first token after `start` (the rendered generation
29/// prompt, e.g. `<|Bot|></think>`) through the first `end` token (the
30/// turn terminator) carries the LM loss; the prompt is context. This is
31/// the multi-token sibling of `focus_tokens` — a JSON verdict, a number,
32/// a sentence — where a one-token label does not fit.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct AnswerSpan {
35    /// Token ids of the generation prompt; the answer starts right after
36    /// its LAST occurrence in the record.
37    pub start: Vec<u32>,
38    /// The turn terminator (one token); the last scored target.
39    pub end: u32,
40    /// Decoded text of every vocabulary id. When present, the answer's
41    /// top-level JSON values are located in it and the held score grades
42    /// whole verdicts (`answer_values`): a question counts as correct only
43    /// when every token of its value is the argmax. Token accuracy over
44    /// the span alone is dominated by the braces, quotes and question ids
45    /// the model copies from the prompt.
46    pub values: Option<TokenText>,
47}
48
49/// Decoded text per token id (see `AnswerSpan::values`).
50#[derive(Clone, PartialEq, Eq)]
51pub struct TokenText(pub Arc<Vec<String>>);
52
53impl std::fmt::Debug for TokenText {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        write!(f, "TokenText({} ids)", self.0.len())
56    }
57}
58
59/// The target positions of each top-level value of the JSON object an
60/// answer span holds (`{"q1": "option_24", "q2": 3}` → two groups), in
61/// order. A token overlapping a value's characters belongs to it, so a
62/// token that merges a quote with the label's first letters is graded with
63/// the label. Positions are indices into `ids`, within `first..=last`.
64pub fn answer_values(ids: &[u32], first: usize, last: usize, text: &TokenText) -> Vec<Vec<usize>> {
65    let mut groups = Vec::new();
66    let mut cur: Option<Vec<usize>> = None;
67    let (mut depth, mut in_str, mut esc, mut expect_value) = (0i32, false, false, false);
68    let mark = |cur: &mut Option<Vec<usize>>, p: usize| {
69        if let Some(g) = cur.as_mut() {
70            if g.last() != Some(&p) {
71                g.push(p);
72            }
73        }
74    };
75    for p in first..=last.min(ids.len().saturating_sub(1)) {
76        let piece = text.0.get(ids[p] as usize).map(String::as_str).unwrap_or("");
77        for ch in piece.chars() {
78            if in_str {
79                if esc {
80                    esc = false;
81                } else if ch == '\\' {
82                    esc = true;
83                } else if ch == '"' {
84                    in_str = false;
85                }
86                mark(&mut cur, p);
87                continue;
88            }
89            if expect_value && !ch.is_whitespace() {
90                expect_value = false;
91                cur = Some(Vec::new());
92            }
93            match ch {
94                '"' => {
95                    in_str = true;
96                    mark(&mut cur, p);
97                }
98                '{' | '[' => {
99                    depth += 1;
100                    mark(&mut cur, p);
101                }
102                '}' | ']' => {
103                    if depth == 1 {
104                        if let Some(g) = cur.take() {
105                            if !g.is_empty() {
106                                groups.push(g);
107                            }
108                        }
109                    } else {
110                        mark(&mut cur, p);
111                    }
112                    depth -= 1;
113                }
114                ',' if depth == 1 => {
115                    if let Some(g) = cur.take() {
116                        if !g.is_empty() {
117                            groups.push(g);
118                        }
119                    }
120                }
121                ':' if depth == 1 && cur.is_none() => expect_value = true,
122                c if c.is_whitespace() && depth == 1 => {}
123                _ => mark(&mut cur, p),
124            }
125        }
126    }
127    if let Some(g) = cur {
128        if !g.is_empty() {
129            groups.push(g);
130        }
131    }
132    groups
133}
134
135/// The scored target range `(first, last)` (inclusive, indices into
136/// `ids`) of one record, or `None` when the record carries no answer.
137pub fn answer_targets(ids: &[u32], span: &AnswerSpan) -> Option<(usize, usize)> {
138    let m = span.start.len();
139    if m == 0 || ids.len() <= m {
140        return None;
141    }
142    let at = (0..=ids.len() - m).rev().find(|&i| ids[i..i + m] == span.start[..])?;
143    let first = at + m;
144    if first >= ids.len() {
145        return None;
146    }
147    let last = (first..ids.len())
148        .find(|&i| ids[i] == span.end)
149        .unwrap_or(ids.len() - 1);
150    Some((first, last))
151}
152
153/// Hyper-parameters — defaults are the certified recipe.
154#[derive(Clone, Debug)]
155pub struct BakeHyper {
156    pub steps_a: usize,
157    pub steps_b: usize,
158    pub l1_init: f64,
159    pub l1_step: f64,
160    pub eval_every: usize,
161    pub lr_a: f64,
162    pub lr_b: f64,
163    pub tau: f32,
164    pub fcd_layers: usize,
165    /// Independent fixed-length records per optimizer step.  The loss is
166    /// normalized over all focused targets in the batch.
167    pub batch: usize,
168    /// Focused records per cached final-FFN optimizer step.  This is separate
169    /// from `batch` because Phase A stores every layer's activations while a
170    /// one-layer FCD cache stores only two hidden vectors per record.
171    pub fcd_batch: usize,
172    pub seed: u64,
173    /// Target sparsity (0..1). When >0, the best checkpoint must have
174    /// at least this fraction of neurons pruned; if none qualifies the
175    /// highest-sparsity checkpoint is used.
176    pub target_sparsity: f64,
177    /// L1 aggression multiplier: scales both l1_init and l1_step.
178    /// >1.0 = harder pruning push, <1.0 = softer.
179    pub l1_mult: f64,
180    /// Effective unlooped mask logit at step zero. The per-visit value is
181    /// solved so that the product over loop visits equals sigmoid(init).
182    /// 2.0 preserves the native recipe; 4.0 reproduces the older DTG-MA
183    /// trading notebooks' near-identity start.
184    pub mask_init: f32,
185    /// Penalize softplus(logit), whose derivative is sigmoid(logit), instead
186    /// of penalizing sigmoid(logit) itself. This reproduces the older DTG-MA
187    /// recipe and avoids an extra (1-sigmoid) attenuation near an open gate.
188    pub softplus_l1: bool,
189    /// Select Phase-A checkpoints by held-out hard balanced accuracy when
190    /// focused class tokens are configured. Otherwise held-out PPL remains
191    /// the checkpoint metric.
192    pub checkpoint_accuracy: bool,
193    /// Optional strict lower bound for a focused checkpoint's raw accuracy.
194    /// A checkpoint is eligible only when its measured accuracy is greater
195    /// than this value. This lets callers impose a natural-distribution
196    /// majority guard instead of selecting from a balanced holdout.
197    pub checkpoint_min_accuracy: Option<f64>,
198    /// Optional strict lower bound for focused balanced accuracy. Combined
199    /// with `checkpoint_min_accuracy`, this prevents a majority-only mask
200    /// from becoming the shipped specialist.
201    pub checkpoint_min_balanced_accuracy: Option<f64>,
202    /// When a joint accuracy guard is configured, rank eligible checkpoints
203    /// by raw accuracy first, then balanced accuracy and PPL. The historical
204    /// balanced-first selector remains the default for compatibility.
205    pub checkpoint_raw_priority: bool,
206    /// Round each layer's kept-neuron count UP to a multiple of this
207    /// (0/1 = off). 32 keeps the defragged FFN on grouped codecs
208    /// (in % 32 == 0) and SIMD kernels off their scalar tails.
209    pub align: usize,
210    /// Force one FFN width across all layers (the max aligned count) —
211    /// the whole-token GPU graphs require a uniform intermediate size.
212    pub uniform_inter: bool,
213    /// When non-empty, LM loss is accumulated only where the next token
214    /// is one of these ids. The whole chunk is still forwarded as context.
215    /// This is useful for supervised corpora with a long input and a
216    /// one-token answer, where ordinary all-token LM loss would drown the
217    /// task signal in prompt reconstruction.
218    pub focus_tokens: Vec<u32>,
219    /// Optional token(s) that must immediately follow a focused target.
220    /// Supervised ChatML uses the one-token label followed by `<|im_end|>`;
221    /// this prevents label names mentioned inside the user instruction from
222    /// being mistaken for answer positions.
223    pub focus_follow_tokens: Vec<u32>,
224    /// Score the assistant's answer span of each chat record instead of
225    /// every token (or one-token labels). Exclusive with `focus_tokens`.
226    pub answer_span: Option<AnswerSpan>,
227    /// Start Phase A from these mask logits (one row per virtual layer,
228    /// e.g. a previous run's archaeology `selected_logits`) instead of
229    /// the uniform init — so a mask trained once can be FCD-polished
230    /// again, or Phase A resumed, in a separate run (`--steps-a 0` keeps it).
231    pub mask_logits: Option<Vec<Vec<f32>>>,
232    /// Patent 2 Soft-Fold compilation: the neurons that survive τ keep
233    /// their LEARNED gain σ(m) (folded into down_proj by the writer) instead
234    /// of being snapped to 1. Evaluation and Phase B then run that exact
235    /// function (σ(m) above τ, 0 below), so what is scored is what ships.
236    pub soft_fold: bool,
237    /// Full-layer FCD: Phase B also trains the attention projections
238    /// (q/k/v/o, the projected head gate) and both norm gains of the FCD
239    /// layers — the notebook's "unfreeze the last N layers entirely".
240    pub fcd_attn: bool,
241    /// Write every Phase-A evaluation's mask logits to
242    /// `<dir>/phase-a-step-<n>.json` as it happens (a `--mask-from` input),
243    /// so a long run survives being stopped.
244    pub checkpoint_dir: Option<String>,
245    /// Tags of the held records (in held order before the length sort):
246    /// held scores then report per-tag verdict accuracy and gate on its
247    /// macro average.
248    pub held_tags: Option<HeldTags>,
249}
250
251impl Default for BakeHyper {
252    fn default() -> Self {
253        Self {
254            steps_a: 240,
255            steps_b: 120,
256            l1_init: 0.01,
257            l1_step: 0.005,
258            eval_every: 30,
259            lr_a: 0.1,
260            lr_b: 1e-5,
261            tau: 0.5,
262            fcd_layers: 4,
263            batch: 1,
264            fcd_batch: 128,
265            seed: 0,
266            target_sparsity: 0.0,
267            l1_mult: 1.0,
268            mask_init: 2.0,
269            softplus_l1: false,
270            checkpoint_accuracy: false,
271            checkpoint_min_accuracy: None,
272            checkpoint_min_balanced_accuracy: None,
273            checkpoint_raw_priority: false,
274            align: 32,
275            uniform_inter: false,
276            focus_tokens: Vec::new(),
277            focus_follow_tokens: Vec::new(),
278            answer_span: None,
279            mask_logits: None,
280            soft_fold: false,
281            fcd_attn: false,
282            checkpoint_dir: None,
283            held_tags: None,
284        }
285    }
286}
287
288/// What the bake measured and produced.
289pub struct BakeReport {
290    /// Held-out PPL of the untouched backbone.
291    pub backbone: f64,
292    /// Held-out PPL with the best hard mask (the denoising bottom).
293    pub masked: f64,
294    /// Held-out PPL after FCD (the final specialist).
295    pub overlaid: f64,
296    pub pruned_ratio: f64,
297    pub kept_per_layer: Vec<usize>,
298    /// Hard focused-label accuracy, present when focus tokens were supplied.
299    pub backbone_accuracy: Option<f64>,
300    pub masked_accuracy: Option<f64>,
301    pub overlaid_accuracy: Option<f64>,
302    /// Macro recall over focused labels. Unlike raw accuracy this cannot be
303    /// improved by collapsing to the majority UP/DOWN class.
304    pub backbone_balanced_accuracy: Option<f64>,
305    pub masked_balanced_accuracy: Option<f64>,
306    pub overlaid_balanced_accuracy: Option<f64>,
307    pub selected_step: usize,
308    pub sec: f64,
309}
310
311pub struct BakeCheckpoint {
312    pub step: usize,
313    pub l1: f64,
314    pub ppl: f64,
315    pub sparsity: f64,
316    pub accuracy: Option<f64>,
317    pub balanced_accuracy: Option<f64>,
318    /// The mask logits at this evaluation — so any iteration's mask can
319    /// be picked after the run (`--mask-from` with a chosen checkpoint).
320    pub logits: Vec<Vec<f32>>,
321}
322
323/// Trained attention + norm masters of a full-layer FCD layer (f32).
324#[derive(Clone)]
325pub struct AttnMasters {
326    /// Fused `[qrows + 2·kvdim, hidden]` (q rows first, then k, then v).
327    pub wqkv: Vec<f32>,
328    /// `[hidden, nh·hd]`.
329    pub wo: Vec<f32>,
330    /// Per-head gate projection `[nh, hidden]` (Spark-X2.5), if the layer has one.
331    pub gproj: Option<Vec<f32>>,
332    pub iln: Vec<f32>,
333    pub pln: Vec<f32>,
334}
335
336/// Their gradients (f64 accumulators), same shapes.
337pub struct AttnGrads {
338    pub wqkv: Vec<f64>,
339    pub wo: Vec<f64>,
340    pub gproj: Option<Vec<f64>>,
341    pub iln: Vec<f64>,
342    pub pln: Vec<f64>,
343}
344
345impl AttnGrads {
346    fn zeros_like(m: &AttnMasters) -> Self {
347        Self {
348            wqkv: vec![0.0; m.wqkv.len()],
349            wo: vec![0.0; m.wo.len()],
350            gproj: m.gproj.as_ref().map(|g| vec![0.0; g.len()]),
351            iln: vec![0.0; m.iln.len()],
352            pln: vec![0.0; m.pln.len()],
353        }
354    }
355}
356
357/// The trained artifacts: everything the defrag writer needs, f32.
358pub struct BakeArtifacts {
359    /// Per-PHYSICAL-layer live flags: the union over visits — a weight
360    /// row is removable from disk only when no visit keeps it.
361    pub keep: Vec<Vec<bool>>,
362    /// Per-VIRTUAL-layer live flags (physical × loops, pass-major): the
363    /// mask the file ships and the runtime applies per visit.
364    pub keep_visits: Vec<Vec<bool>>,
365    /// Per-layer down_proj `[hidden, inter]` with dead columns zeroed
366    /// (FCD layers: the trained weights; others: the backbone's).
367    pub down: Vec<Vec<f32>>,
368    /// Trained gate/up for the FCD layers (`None` elsewhere).
369    pub gate_up: Vec<Option<(Vec<f32>, Vec<f32>)>>,
370    /// Which layers went through Phase B.
371    pub fcd_layers: Vec<usize>,
372    /// Trained attention/norm masters (full-layer FCD), per layer.
373    pub attn: Vec<Option<AttnMasters>>,
374    /// The trained mask logits, per virtual layer — a CONTINUOUS
375    /// per-neuron importance the hard keep flags throw away. The tube
376    /// planner ranks and orders neurons by these, not by raw
377    /// activation mass.
378    pub logits: Vec<Vec<f32>>,
379    /// Phase-A logits after the last requested optimization step, before
380    /// restoring the selected hard-validation checkpoint.
381    pub final_logits: Vec<Vec<f32>>,
382    pub checkpoints: Vec<BakeCheckpoint>,
383}
384
385const CLIP: f64 = 1.0;
386const B1: f64 = 0.9;
387const B2: f64 = 0.999;
388const EPS: f64 = 1e-8;
389
390/// Plain Adam over a set of f32 tensors (masks are tiny, FFN mid-size).
391struct Adam {
392    m: Vec<Vec<f64>>,
393    v: Vec<Vec<f64>>,
394    t: i32,
395    lr: f64,
396}
397
398impl Adam {
399    fn new(sizes: &[usize], lr: f64) -> Self {
400        Self {
401            m: sizes.iter().map(|&n| vec![0.0; n]).collect(),
402            v: sizes.iter().map(|&n| vec![0.0; n]).collect(),
403            t: 0,
404            lr,
405        }
406    }
407
408    /// Global-norm clip + Adam step. `params[i].len() == grads[i].len()`.
409    fn step(&mut self, params: &mut [&mut [f32]], grads: &[Vec<f64>], lr_scale: f64) {
410        let gn: f64 = grads
411            .iter()
412            .flat_map(|g| g.iter().map(|x| x * x))
413            .sum::<f64>()
414            .sqrt();
415        let clip = if gn > CLIP { CLIP / gn } else { 1.0 };
416        self.t += 1;
417        let (bc1, bc2) = (1.0 - B1.powi(self.t), 1.0 - B2.powi(self.t));
418        for (pi, p) in params.iter_mut().enumerate() {
419            for j in 0..p.len() {
420                let g = grads[pi][j] * clip;
421                let m = &mut self.m[pi][j];
422                let v = &mut self.v[pi][j];
423                *m = B1 * *m + (1.0 - B1) * g;
424                *v = B2 * *v + (1.0 - B2) * g * g;
425                let upd = (*m / bc1) / ((*v / bc2).sqrt() + EPS);
426                p[j] -= (self.lr * lr_scale * upd) as f32;
427            }
428        }
429    }
430}
431
432/// Mask logit at step zero, solved for the loop depth.
433///
434/// The gate multiplies the FFN once per VISIT, so a Looped Transformer
435/// applies it `loops` times per token and the factor compounds. What
436/// must be held constant across depths is the EFFECTIVE start — the
437/// product the stack actually sees — at the value the recipe was
438/// validated with on ordinary models, σ(2.0) = 0.881:
439///
440/// ```text
441/// σ(m0)^loops = σ(2.0)   →   m0 = logit( σ(2.0)^(1/loops) )
442/// ```
443///
444/// `loops = 1` returns 2.0 exactly, so nothing regresses. Two known
445/// wrong answers this replaces: the old hardcoded 2.0, which at two
446/// visits compounds to 0.776 and took Nanbeige 4.2 from a baseline of
447/// 4.187 to 278.4 at step 30; and a start pushed to identity, which
448/// cannot learn because the update carries σ'(m) = σ(1−σ), worth 5e-4
449/// at σ = 0.9995 against 0.105 at 2.0.
450pub fn mask_init_logit_for(loops: usize, effective_logit: f32) -> f32 {
451    let base = 1.0f32 / (1.0 + (-effective_logit).exp());
452    let per_visit = base.powf(1.0 / loops.max(1) as f32);
453    (per_visit / (1.0 - per_visit)).ln()
454}
455
456pub fn mask_init_logit(loops: usize) -> f32 {
457    mask_init_logit_for(loops, 2.0)
458}
459
460/// Learning-rate scale for the mask step, given the loop depth.
461///
462/// The backward accumulates every visit of a physical layer into the
463/// same mask gradient, so an unscaled step is `loops` times the tuned
464/// one. One step should mean one token's worth of movement at any depth.
465pub fn mask_step_scale(loops: usize) -> f64 {
466    1.0 / loops.max(1) as f64
467}
468
469fn sigmoid(x: f32) -> f32 {
470    1.0 / (1.0 + (-x).exp())
471}
472
473fn sparsity_grad(logit: f32, softplus_l1: bool) -> f64 {
474    let s = sigmoid(logit) as f64;
475    if softplus_l1 { s } else { s * (1.0 - s) }
476}
477
478fn is_scored_target(
479    ids: &[u32],
480    target_index: usize,
481    sequence_end: usize,
482    focus: &[u32],
483    follow: &[u32],
484) -> bool {
485    if focus.is_empty() {
486        return true;
487    }
488    focus.contains(&ids[target_index])
489        && (follow.is_empty()
490            || (target_index + 1 < sequence_end && follow.contains(&ids[target_index + 1])))
491}
492
493/// The scored target indices (into the flat batch) of the sequence at
494/// `base..base + t`: its answer span, its focused labels, or every
495/// position.
496fn scored_targets(
497    ids: &[u32],
498    base: usize,
499    t: usize,
500    focus: &[u32],
501    follow: &[u32],
502    span: Option<&AnswerSpan>,
503) -> Vec<usize> {
504    match span {
505        Some(sp) => match answer_targets(&ids[base..base + t], sp) {
506            Some((first, last)) => (base + first.max(1)..=base + last).collect(),
507            None => Vec::new(),
508        },
509        None => (base + 1..base + t)
510            .filter(|&target_index| is_scored_target(ids, target_index, base + t, focus, follow))
511            .collect(),
512    }
513}
514
515/// One forward + CE(+optionally backward through the FFN chain).
516/// Returns (nll_sum, tokens). `dmask`/`dffn` accumulate when given.
517struct Pass<'a> {
518    fm: &'a FcdModel,
519    tau: f32,
520    /// σ(m) per layer when soft; binarized when `hard`.
521    logits: &'a [Vec<f32>],
522    hard: bool,
523    /// Phase-B replacement FFN weights per layer (trained copies).
524    ffn: &'a [Option<(Vec<f32>, Vec<f32>, Vec<f32>)>],
525    /// Empty means ordinary all-token LM loss.
526    focus_tokens: &'a [u32],
527    /// Empty means no right-context constraint on focused targets.
528    focus_follow_tokens: &'a [u32],
529    /// Answer-span scoring (see `AnswerSpan`); None = focus/all-token.
530    span: Option<&'a AnswerSpan>,
531    /// `hard` gates keep σ(m) above τ instead of snapping to 1 (Soft-Fold).
532    soft_fold: bool,
533    /// Full-layer FCD masters per layer (attention + norms); None = frozen.
534    attn_tr: &'a [Option<AttnMasters>],
535}
536
537/// Raw-pointer carriers for pooled row writes (disjoint ranges per worker).
538struct SendMutF(*mut f32);
539unsafe impl Send for SendMutF {}
540unsafe impl Sync for SendMutF {}
541impl SendMutF {
542    #[inline]
543    unsafe fn at(&self, i: usize) -> *mut f32 {
544        unsafe { self.0.add(i) }
545    }
546}
547struct SendMutF64(*mut f64);
548unsafe impl Send for SendMutF64 {}
549unsafe impl Sync for SendMutF64 {}
550impl SendMutF64 {
551    #[inline]
552    unsafe fn at(&self, i: usize) -> *mut f64 {
553        unsafe { self.0.add(i) }
554    }
555}
556
557#[derive(Clone, Debug, Default)]
558struct FocusStats {
559    total: usize,
560    correct: usize,
561    class_total: Vec<usize>,
562    class_correct: Vec<usize>,
563    /// Answer-span verdicts (`answer_values`) and those predicted whole.
564    questions: usize,
565    questions_correct: usize,
566    /// (verdicts, right) per sequence of the LAST scored call — the held
567    /// scorer attributes them to the records' tags; never merged.
568    seq: Vec<(usize, usize)>,
569}
570
571impl FocusStats {
572    fn new(classes: usize) -> Self {
573        Self {
574            class_total: vec![0; classes],
575            class_correct: vec![0; classes],
576            ..Self::default()
577        }
578    }
579
580    fn accuracy(&self) -> Option<f64> {
581        (self.total > 0).then(|| self.correct as f64 / self.total as f64)
582    }
583
584    fn question_accuracy(&self) -> Option<f64> {
585        (self.questions > 0).then(|| self.questions_correct as f64 / self.questions as f64)
586    }
587
588    /// The held score's accuracy pair: whole-verdict accuracy when the span
589    /// located values (then the token accuracy rides along for the log),
590    /// otherwise the token/class accuracy alone.
591    fn accuracies(&self) -> (Option<f64>, Option<f64>) {
592        match self.question_accuracy() {
593            Some(q) => (Some(q), self.accuracy()),
594            None => (self.accuracy(), None),
595        }
596    }
597
598    fn balanced_accuracy(&self) -> Option<f64> {
599        let recalls: Vec<f64> = self
600            .class_total
601            .iter()
602            .zip(&self.class_correct)
603            .filter_map(|(&n, &ok)| (n > 0).then(|| ok as f64 / n as f64))
604            .collect();
605        (!recalls.is_empty()).then(|| recalls.iter().sum::<f64>() / recalls.len() as f64)
606    }
607
608    fn merge(&mut self, other: &Self) {
609        self.total += other.total;
610        self.correct += other.correct;
611        self.questions += other.questions;
612        self.questions_correct += other.questions_correct;
613        if self.class_total.len() < other.class_total.len() {
614            self.class_total.resize(other.class_total.len(), 0);
615            self.class_correct.resize(other.class_correct.len(), 0);
616        }
617        for (dst, src) in self.class_total.iter_mut().zip(&other.class_total) {
618            *dst += src;
619        }
620        for (dst, src) in self.class_correct.iter_mut().zip(&other.class_correct) {
621            *dst += src;
622        }
623    }
624}
625
626#[derive(Clone, Debug)]
627struct HeldScore {
628    ppl: f64,
629    /// Whole-verdict accuracy in answer-span mode with located values,
630    /// else token (span) or class (focus) accuracy.
631    accuracy: Option<f64>,
632    balanced_accuracy: Option<f64>,
633    /// The span's token accuracy when `accuracy` is the verdict accuracy.
634    token_accuracy: Option<f64>,
635    /// Verdict accuracy over all questions when `accuracy` is the macro
636    /// over held tags (families); None otherwise.
637    micro_accuracy: Option<f64>,
638    /// (tag, verdicts, right) per held tag, in tag order.
639    per_tag: Vec<(String, usize, usize)>,
640}
641
642/// Held records' tags (e.g. the benchmark family of each validation
643/// record): the names, and one name index per held record.
644#[derive(Clone, Debug, Default)]
645pub struct HeldTags {
646    pub names: Vec<String>,
647    pub of: Vec<usize>,
648}
649
650/// " | <tag> 61.0 (41)" per tag — the macro gate's ingredients.
651fn tag_line(score: &HeldScore) -> Option<String> {
652    (!score.per_tag.is_empty()).then(|| {
653        score
654            .per_tag
655            .iter()
656            .map(|(name, n, ok)| {
657                format!(
658                    "{name} {:.1} ({n})",
659                    if *n > 0 { *ok as f64 * 100.0 / *n as f64 } else { f64::NAN }
660                )
661            })
662            .collect::<Vec<_>>()
663            .join(" | ")
664    })
665}
666
667/// Frozen boundary immediately before one trainable final FFN.  This is not
668/// an adapter or a donor checkpoint: both vectors are extracted directly from
669/// the opened CMF, kept in RAM, and discarded when the native bake ends.
670#[derive(Default)]
671struct FocusedFcdCache {
672    h1: Vec<f32>,
673    n2: Vec<f32>,
674    targets: Vec<usize>,
675}
676
677impl FocusedFcdCache {
678    fn len(&self) -> usize {
679        self.targets.len()
680    }
681
682    fn append(&mut self, mut other: Self) {
683        self.h1.append(&mut other.h1);
684        self.n2.append(&mut other.n2);
685        self.targets.append(&mut other.targets);
686    }
687}
688
689fn gather_rows(values: &[f32], rows: &[usize], width: usize) -> Vec<f32> {
690    let mut out = Vec::with_capacity(rows.len() * width);
691    for &row in rows {
692        out.extend_from_slice(&values[row * width..(row + 1) * width]);
693    }
694    out
695}
696
697impl Pass<'_> {
698    /// Whole verdicts of an answer-span pass: a question is right when every
699    /// token of its value is the argmax (what greedy decoding emits after the
700    /// same prefix). `hits` / `preds` run along `targets`.
701    #[allow(clippy::too_many_arguments)]
702    fn whole_verdicts(&self, ids: &[u32], b: usize, t: usize, targets: &[usize], h: &[bool], preds: &[u32], stats: &mut FocusStats, qdebug: usize) {
703        let Some(sp) = self.span else { return };
704        let Some(text) = &sp.values else { return };
705        let at: std::collections::HashMap<usize, bool> = targets.iter().copied().zip(h.iter().copied()).collect();
706        let pred_at: std::collections::HashMap<usize, u32> = targets.iter().copied().zip(preds.iter().copied()).collect();
707        let mut shown = 0usize;
708        stats.seq = vec![(0, 0); b];
709        for bi in 0..b {
710            let seq = &ids[bi * t..(bi + 1) * t];
711            let Some((first, last)) = answer_targets(seq, sp) else {
712                continue;
713            };
714            if shown < qdebug {
715                let gold: Vec<String> = (first.max(1)..=last).map(|q| format!("{:?}", text.0.get(seq[q] as usize).map(String::as_str).unwrap_or("?"))).collect();
716                let got: Vec<String> = (first.max(1)..=last).map(|q| format!("{:?}", pred_at.get(&(bi * t + q)).and_then(|&id| text.0.get(id as usize)).map(String::as_str).unwrap_or("?"))).collect();
717                let groups = answer_values(seq, first.max(1), last, text);
718                eprintln!("[qdebug] gold {} | argmax {} | value groups {:?} (span starts at {})", gold.join(" "), got.join(" "), groups, first.max(1));
719                shown += 1;
720            }
721            for group in answer_values(seq, first.max(1), last, text) {
722                stats.questions += 1;
723                stats.seq[bi].0 += 1;
724                if group.iter().all(|&q| at.get(&(bi * t + q)).copied().unwrap_or(false)) {
725                    stats.questions_correct += 1;
726                    stats.seq[bi].1 += 1;
727                }
728            }
729        }
730    }
731
732    /// The whole pass (forward, loss, Phase-A backward) as one resident step
733    /// on CUDA (`FcdModel::resident_step`): language-model or answer-span
734    /// loss, frozen attention, no trained copies, a single loop. None: the
735    /// layer-by-layer path below runs.
736    #[cfg(feature = "cuda")]
737    #[allow(clippy::type_complexity)]
738    fn resident(
739        &self,
740        ids: &[u32],
741        b: usize,
742        grad: &mut Option<(
743            &mut [Vec<f64>],
744            &mut [Option<(Vec<f64>, Vec<f64>, Vec<f64>)>],
745            &mut [Option<AttnGrads>],
746        )>,
747        focus_stats: &mut Option<&mut FocusStats>,
748    ) -> Option<(f64, usize)> {
749        let fm = self.fm;
750        if !crate::gpu::cuda_active() || !self.focus_tokens.is_empty() || fm.loops > 1 || b == 0 || ids.len() % b != 0 {
751            return None;
752        }
753        if self.attn_tr.iter().any(|a| a.is_some()) || self.ffn.iter().any(|f| f.is_some()) {
754            return None;
755        }
756        let t = ids.len() / b;
757        let nl = fm.layers.len();
758        let targets: Vec<usize> = (0..b)
759            .flat_map(|bi| scored_targets(ids, bi * t, t, self.focus_tokens, self.focus_follow_tokens, self.span))
760            .collect();
761        if targets.is_empty() {
762            return None;
763        }
764        let mats: Vec<std::sync::Arc<crate::fcd::LayerMats>> = (0..nl).map(|li| fm.mats(li).ok()).collect::<Option<_>>()?;
765        let ffn: Vec<(LnFfn, Vec<f32>)> = (0..nl).map(|li| (self.wts(li, &mats[li]), self.gates(li))).collect();
766        let scored = targets.len();
767        let inv_n = 1.0 / scored as f64;
768        let out = fm.resident_step(ids, b, &ffn, &mats, &targets, inv_n as f32, grad.is_some())?;
769        let mut nll = 0f64;
770        let span_stats = self.span.is_some();
771        let want_hits = focus_stats.is_some() && self.span.is_some_and(|sp| sp.values.is_some());
772        let mut hits = Vec::with_capacity(if want_hits { scored } else { 0 });
773        for (r, &ti) in targets.iter().enumerate() {
774            nll += out.nll[r] as f64;
775            let ok = out.argmax[r] == ids[ti];
776            if span_stats {
777                if let Some(stats) = focus_stats.as_deref_mut() {
778                    stats.total += 1;
779                    if ok {
780                        stats.correct += 1;
781                    }
782                }
783            }
784            if want_hits {
785                hits.push(ok);
786            }
787        }
788        if want_hits {
789            let qdebug: usize = std::env::var("CMF_BAKE_QDEBUG").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
790            if let Some(stats) = focus_stats.as_deref_mut() {
791                self.whole_verdicts(ids, b, t, &targets, &hits, &out.argmax, stats, qdebug);
792            }
793        }
794        if let Some((dmask, _, _)) = grad.as_mut() {
795            for (li, dm) in out.dmask.iter().enumerate() {
796                for (d, &x) in dmask[li].iter_mut().zip(dm) {
797                    *d += x as f64;
798                }
799            }
800        }
801        Some((nll, scored))
802    }
803
804    fn gates(&self, li: usize) -> Vec<f32> {
805        self.logits[li]
806            .iter()
807            .map(|&l| {
808                let s = sigmoid(l);
809                if self.hard {
810                    if s > self.tau {
811                        if self.soft_fold { s } else { 1.0 }
812                    } else {
813                        0.0
814                    }
815                } else {
816                    s
817                }
818            })
819            .collect()
820    }
821
822    fn wts<'b>(&'b self, li: usize, mats: &'b crate::fcd::LayerMats) -> LnFfn<'b> {
823        let l = &self.fm.layers[li];
824        let (iln, pln): (&[f32], &[f32]) = match &self.attn_tr[li] {
825            Some(m) => (&m.iln, &m.pln),
826            None => (&l.iln, &l.pln),
827        };
828        match &self.ffn[li] {
829            Some((g, u, d)) => LnFfn {
830                iln,
831                pln,
832                gate: g,
833                up: u,
834                down: d,
835                // Trained copies move every Adam step — no prebuilt concat.
836                gu: None,
837            },
838            None => LnFfn {
839                iln,
840                pln,
841                gate: &[],
842                up: &[],
843                down: &mats.down,
844                gu: Some(&mats.gu),
845            },
846        }
847    }
848
849    /// Extract the exact frozen boundary of the final FFN for focused answer
850    /// positions.  Only the ordinary one-pass/final-layer case is cacheable:
851    /// looped stacks revisit the same FFN after its own changed output and
852    /// correctly fall back to the full Phase-B path.
853    fn cache_final_ffn_batch(&self, ids: &[u32], batch: usize) -> Result<FocusedFcdCache, String> {
854        let fm = self.fm;
855        if fm.loops.max(1) != 1 || fm.layers.is_empty() || self.focus_tokens.is_empty() {
856            return Err("focused final-FFN cache needs a one-pass stack and focus tokens".into());
857        }
858        if ids.len() % batch.max(1) != 0 {
859            return Err("focused final-FFN cache received a ragged batch".into());
860        }
861        let t = ids.len() / batch.max(1);
862        let hsz = fm.hidden;
863        let last = fm.layers.len() - 1;
864        let mut sources = Vec::new();
865        let mut targets = Vec::new();
866        for bi in 0..batch {
867            let base = bi * t;
868            for target_index in base + 1..base + t {
869                if !is_scored_target(
870                    ids,
871                    target_index,
872                    base + t,
873                    self.focus_tokens,
874                    self.focus_follow_tokens,
875                ) {
876                    continue;
877                }
878                sources.push(target_index - 1);
879                targets.push(
880                    self.focus_tokens
881                        .iter()
882                        .position(|&id| id == ids[target_index])
883                        .expect("focused target belongs to focus_tokens"),
884                );
885            }
886        }
887        if sources.is_empty() {
888            return Ok(FocusedFcdCache::default());
889        }
890
891        let mut hidden = vec![0f32; ids.len() * hsz];
892        for (row, &id) in ids.iter().enumerate() {
893            hidden[row * hsz..(row + 1) * hsz]
894                .copy_from_slice(&fm.embed[id as usize * hsz..(id as usize + 1) * hsz]);
895        }
896        for layer in 0..=last {
897            let gate = self.gates(layer);
898            let mats = fm.mats(layer)?;
899            let weights = self.wts(layer, &mats);
900            let (next, acts) = fm.layer_forward_scaled(
901                layer,
902                &hidden,
903                batch,
904                t,
905                &weights,
906                false,
907                layer == last,
908                Some(&gate),
909                true,
910                None,
911                false,
912            );
913            if layer == last {
914                let acts = acts.expect("last FFN boundary requested");
915                return Ok(FocusedFcdCache {
916                    h1: gather_rows(&acts.h1, &sources, hsz),
917                    n2: gather_rows(&acts.n2, &sources, hsz),
918                    targets,
919                });
920            }
921            hidden = next;
922        }
923        unreachable!("non-empty stack has a final layer")
924    }
925
926    /// Teacher-forced NLL over one chunk; when `grad` is set, backprop
927    /// through the FFN chain into the mask grads (and FFN grads for
928    /// Phase-B layers).
929    #[allow(clippy::too_many_arguments)]
930    fn chunk(
931        &self,
932        ids: &[u32],
933        grad: Option<(
934            &mut [Vec<f64>],
935            &mut [Option<(Vec<f64>, Vec<f64>, Vec<f64>)>],
936            &mut [Option<AttnGrads>],
937        )>,
938    ) -> (f64, usize) {
939        self.chunk_batch(ids, 1, grad)
940    }
941
942    /// `chunk` over `b` equal-length sequences flattened into `ids`.
943    ///
944    /// Everything under this level was batch-aware all along
945    /// (`layer_forward_scaled` and every attention fwd/bwd take `b`);
946    /// only this wrapper hardcoded 1. Evaluation is where it pays: the
947    /// held set is 12 chunks scored one at a time, which on a 4 B model
948    /// meant 12× the GEMM submits for the same arithmetic.
949    fn chunk_batch(
950        &self,
951        ids: &[u32],
952        b: usize,
953        grad: Option<(
954            &mut [Vec<f64>],
955            &mut [Option<(Vec<f64>, Vec<f64>, Vec<f64>)>],
956            &mut [Option<AttnGrads>],
957        )>,
958    ) -> (f64, usize) {
959        self.chunk_batch_scored(ids, b, grad, None)
960    }
961
962    fn chunk_batch_scored(
963        &self,
964        ids: &[u32],
965        b: usize,
966        grad: Option<(
967            &mut [Vec<f64>],
968            &mut [Option<(Vec<f64>, Vec<f64>, Vec<f64>)>],
969            &mut [Option<AttnGrads>],
970        )>,
971        mut focus_stats: Option<&mut FocusStats>,
972    ) -> (f64, usize) {
973        #[cfg(feature = "cuda")]
974        let mut grad = grad;
975        #[cfg(feature = "cuda")]
976        let mut focus_stats = focus_stats;
977        #[cfg(feature = "cuda")]
978        if let Some(r) = self.resident(ids, b, &mut grad, &mut focus_stats) {
979            return r;
980        }
981        let fm = self.fm;
982        let hsz = fm.hidden;
983        let pool = fm.pool.as_deref();
984        debug_assert!(ids.len() % b.max(1) == 0, "ragged batch");
985        let t = ids.len() / b.max(1);
986        let n = b * t;
987        let nl = fm.layers.len();
988        // Embed.
989        let mut h = vec![0f32; n * hsz];
990        for (r, &id) in ids.iter().enumerate() {
991            h[r * hsz..(r + 1) * hsz]
992                .copy_from_slice(&fm.embed[id as usize * hsz..(id as usize + 1) * hsz]);
993        }
994        // Forward over VIRTUAL layers: a Looped Transformer runs the
995        // stack `fm.loops` times, with a final_norm at each loop
996        // boundary when the file says so. Everything below indexes
997        // activations by the virtual step and weights/grads by the
998        // physical layer `vl % nl` — so a physical layer visited twice
999        // accumulates both visits' gradients, which is what the loop
1000        // means mathematically.
1001        let loops = fm.loops.max(1);
1002        let vn = nl * loops;
1003        let mut h_ins = Vec::with_capacity(vn);
1004        let mut acts = Vec::with_capacity(vn);
1005        let mut masks = Vec::with_capacity(vn);
1006        // Loop-boundary norms, saved for the backward: (input, inv).
1007        let mut lnorms: Vec<Option<(Vec<f32>, Vec<f32>)>> = vec![None; vn];
1008        for vl in 0..vn {
1009            let li = vl % nl;
1010            // The gate is PER VISIT: the two passes of a loop are
1011            // different computations sharing one set of weights, so the
1012            // mask must be allowed to differ between them. Weights stay
1013            // indexed by the physical layer.
1014            let g = self.gates(vl);
1015            let mats_hold = fm.mats(li).expect("layer mats");
1016            let wts = self.wts(li, &mats_hold);
1017            let want = grad.is_some();
1018            // A frozen layer's backward runs on the card from the plane the
1019            // forward parks there; only a trained (Phase-B) layer needs its
1020            // gate/up/act planes on the host.
1021            let planes_host = !(want && self.ffn[li].is_none());
1022            let attn_w = self.attn_tr[li].as_ref().map(|m| AttnW {
1023                wqkv: &m.wqkv,
1024                wo: &m.wo,
1025                head_gate: m.gproj.as_deref(),
1026            });
1027            let (h2, a) = fm.layer_forward_scaled(
1028                li,
1029                &h,
1030                b,
1031                t,
1032                &wts,
1033                false,
1034                want,
1035                Some(&g),
1036                planes_host,
1037                attn_w,
1038                want && attn_w.is_some(),
1039            );
1040            h_ins.push(if want { h } else { Vec::new() });
1041            acts.push(a);
1042            masks.push(g);
1043            h = h2;
1044            // Mid-stack norm at every loop boundary except the last —
1045            // the final one folds into the head below.
1046            if fm.loop_norm && li + 1 == nl && vl + 1 < vn {
1047                let mut hn = vec![0f32; n * hsz];
1048                let mut inv = vec![0f32; n];
1049                rmsnorm_fwd_pooled(&h, &fm.final_norm, fm.eps, fm.gemma, &mut hn, &mut inv, pool);
1050                if want {
1051                    lnorms[vl] = Some((h, inv));
1052                }
1053                h = hn;
1054            }
1055        }
1056        // Final norm + tied LM head, CE summed over positions 1..t.
1057        let mut hn = vec![0f32; n * hsz];
1058        let mut inv = vec![0f32; n];
1059        rmsnorm_fwd_pooled(&h, &fm.final_norm, fm.eps, fm.gemma, &mut hn, &mut inv, pool);
1060        let lm: &[f32] = fm.lm_head.as_deref().unwrap_or(&fm.embed);
1061        let vocab = lm.len() / hsz;
1062        let mut nll = 0f64;
1063        let mut dh_n = vec![0f32; n * hsz]; // dL/d hn
1064        // Chunk the vocab matmul over positions to bound the logits buf.
1065        // Positions are walked PER SEQUENCE: the last position of chunk
1066        // i must not be scored against the first token of chunk i+1.
1067        const POS_CHUNK: usize = 64;
1068        let targets: Vec<usize> = (0..b)
1069            .flat_map(|bi| {
1070                scored_targets(
1071                    ids,
1072                    bi * t,
1073                    t,
1074                    self.focus_tokens,
1075                    self.focus_follow_tokens,
1076                    self.span,
1077                )
1078            })
1079            .collect();
1080        let scored = targets.len();
1081        if scored == 0 {
1082            return (0.0, 0);
1083        }
1084        if self.focus_tokens.is_empty() {
1085            // Ordinary language-model mode: the complete vocabulary
1086            // distribution at every scored target — every position, or
1087            // the answer span of each record. The scored rows are gathered
1088            // so a span pays for its own positions only, not the prompt's.
1089            let inv_n = 1.0 / scored as f64;
1090            // Argmax hit per scored target, for the whole-verdict count.
1091            let mut hits: Option<Vec<bool>> = (focus_stats.is_some()
1092                && self.span.is_some_and(|sp| sp.values.is_some()))
1093            .then(|| vec![false; scored]);
1094            // CMF_BAKE_QDEBUG=N prints gold vs argmax of the first N verdicts
1095            // of every held call (diagnosing the verdict locator).
1096            let qdebug: usize = std::env::var("CMF_BAKE_QDEBUG").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
1097            let mut preds: Vec<u32> = if qdebug > 0 && hits.is_some() { vec![0; scored] } else { Vec::new() };
1098            let mut p0 = 0usize;
1099            // On CUDA the whole head runs on the card (`gpu_cuda::bake_lm_loss`):
1100            // the full-vocabulary rows never reach the host.
1101            #[cfg(feature = "cuda")]
1102            if crate::gpu::cuda_active() {
1103                let src: Vec<usize> = targets.iter().map(|&ti| ti - 1).collect();
1104                let hsrc = gather_rows(&hn, &src, hsz);
1105                let tg: Vec<u32> = targets.iter().map(|&ti| ids[ti]).collect();
1106                if let Some((nl, am, dsrc)) = crate::gpu_cuda::bake_lm_loss(&hsrc, lm, &tg, hsz, inv_n as f32, grad.is_some()) {
1107                    for (r, &target_index) in targets.iter().enumerate() {
1108                        let target = ids[target_index];
1109                        nll += nl[r] as f64;
1110                        if let (Some(stats), Some(_)) = (focus_stats.as_deref_mut(), self.span) {
1111                            stats.total += 1;
1112                            if am[r] == target {
1113                                stats.correct += 1;
1114                            }
1115                        }
1116                        if let Some(h) = hits.as_mut() {
1117                            h[r] = am[r] == target;
1118                        }
1119                        if !preds.is_empty() {
1120                            preds[r] = am[r];
1121                        }
1122                        if grad.is_some() {
1123                            let s = src[r];
1124                            for (d, &x) in dh_n[s * hsz..(s + 1) * hsz].iter_mut().zip(&dsrc[r * hsz..(r + 1) * hsz]) {
1125                                *d += x;
1126                            }
1127                        }
1128                    }
1129                    p0 = scored;
1130                }
1131            }
1132            while p0 < scored {
1133                let pc = POS_CHUNK.min(scored - p0);
1134                let rows = &targets[p0..p0 + pc];
1135                let src: Vec<usize> = rows.iter().map(|&target_index| target_index - 1).collect();
1136                let hsrc = gather_rows(&hn, &src, hsz);
1137                let mut logits = vec![0f32; pc * vocab];
1138                ops::gemm_nt(&hsrc, lm, &mut logits, pc, hsz, vocab, pool);
1139                for (r, &target_index) in rows.iter().enumerate() {
1140                    let target = ids[target_index] as usize;
1141                    let row = &mut logits[r * vocab..(r + 1) * vocab];
1142                    let (mut mx, mut arg) = (f32::NEG_INFINITY, 0usize);
1143                    for (j, &v) in row.iter().enumerate() {
1144                        if v > mx {
1145                            mx = v;
1146                            arg = j;
1147                        }
1148                    }
1149                    let mx = mx as f64;
1150                    let mut sum = 0f64;
1151                    for v in row.iter() {
1152                        sum += ((*v as f64) - mx).exp();
1153                    }
1154                    nll += mx + sum.ln() - row[target] as f64;
1155                    // Teacher-forced token accuracy of the answer span — the
1156                    // one number a verdict corpus is really graded on.
1157                    if let (Some(stats), Some(_)) = (focus_stats.as_deref_mut(), self.span) {
1158                        stats.total += 1;
1159                        if arg == target {
1160                            stats.correct += 1;
1161                        }
1162                    }
1163                    if let Some(h) = hits.as_mut() {
1164                        h[p0 + r] = arg == target;
1165                    }
1166                    if !preds.is_empty() {
1167                        preds[p0 + r] = arg as u32;
1168                    }
1169                    if grad.is_some() {
1170                        // dCE/dlogit = softmax − onehot, scaled by 1/scored.
1171                        for v in row.iter_mut() {
1172                            *v = ((((*v as f64) - mx).exp() / sum) * inv_n) as f32;
1173                        }
1174                        row[target] -= inv_n as f32;
1175                    }
1176                }
1177                if grad.is_some() {
1178                    let mut dsrc = vec![0f32; pc * hsz];
1179                    ops::gemm_dx(&logits, lm, &mut dsrc, pc, hsz, vocab, pool);
1180                    for (r, &s) in src.iter().enumerate() {
1181                        for (d, &x) in dh_n[s * hsz..(s + 1) * hsz]
1182                            .iter_mut()
1183                            .zip(&dsrc[r * hsz..(r + 1) * hsz])
1184                        {
1185                            *d += x;
1186                        }
1187                    }
1188                }
1189                p0 += pc;
1190            }
1191            // Whole verdicts: a question is right when every token of its
1192            // value is the argmax (what greedy decoding emits after the
1193            // same prefix).
1194            if let (Some(h), Some(stats)) = (&hits, focus_stats.as_deref_mut()) {
1195                self.whole_verdicts(ids, b, t, &targets, h, &preds, stats, qdebug);
1196            }
1197        } else {
1198            // Exact classifier mode. Only the declared label rows can enter
1199            // either the normalizer or its gradient, so multiplying every
1200            // hidden by the full ~250k-row LM head is pure wasted work. It
1201            // made a two-label archaeology run spend more time in the head
1202            // than in mask Adam and limited experiments to a tiny fraction
1203            // of the updates used by the original notebooks.
1204            let inv_n = 1.0 / scored as f64;
1205            for bi in 0..b {
1206                let base = bi * t;
1207                for target_index in base + 1..base + t {
1208                    if !is_scored_target(
1209                        ids,
1210                        target_index,
1211                        base + t,
1212                        self.focus_tokens,
1213                        self.focus_follow_tokens,
1214                    ) {
1215                        continue;
1216                    }
1217                    let target_class = self
1218                        .focus_tokens
1219                        .iter()
1220                        .position(|&id| id == ids[target_index])
1221                        .expect("focused target belongs to focus_tokens");
1222                    let source = target_index - 1;
1223                    let hidden = &hn[source * hsz..(source + 1) * hsz];
1224                    let class_logits: Vec<f32> = self
1225                        .focus_tokens
1226                        .iter()
1227                        .map(|&id| {
1228                            let row = &lm[id as usize * hsz..(id as usize + 1) * hsz];
1229                            hidden.iter().zip(row).map(|(&x, &w)| x * w).sum()
1230                        })
1231                        .collect();
1232                    let mx = class_logits
1233                        .iter()
1234                        .copied()
1235                        .fold(f32::NEG_INFINITY, f32::max) as f64;
1236                    let probs: Vec<f64> = class_logits
1237                        .iter()
1238                        .map(|&value| ((value as f64) - mx).exp())
1239                        .collect();
1240                    let sum: f64 = probs.iter().sum();
1241                    nll += mx + sum.ln() - class_logits[target_class] as f64;
1242                    if let Some(stats) = focus_stats.as_deref_mut() {
1243                        let predicted_class = class_logits
1244                            .iter()
1245                            .enumerate()
1246                            .max_by(|(_, left), (_, right)| left.total_cmp(right))
1247                            .map(|(index, _)| index)
1248                            .expect("focus_tokens is non-empty");
1249                        stats.total += 1;
1250                        stats.class_total[target_class] += 1;
1251                        if predicted_class == target_class {
1252                            stats.correct += 1;
1253                            stats.class_correct[target_class] += 1;
1254                        }
1255                    }
1256                    if grad.is_some() {
1257                        let dh = &mut dh_n[source * hsz..(source + 1) * hsz];
1258                        for (class, (&id, probability)) in
1259                            self.focus_tokens.iter().zip(probs).enumerate()
1260                        {
1261                            let coefficient = (probability / sum
1262                                - usize::from(class == target_class) as f64)
1263                                * inv_n;
1264                            let row = &lm[id as usize * hsz..(id as usize + 1) * hsz];
1265                            for (value, &weight) in dh.iter_mut().zip(row) {
1266                                *value += (coefficient * weight as f64) as f32;
1267                            }
1268                        }
1269                    }
1270                }
1271            }
1272        }
1273        let Some((dmask, dffn, dattn)) = grad else {
1274            return (nll, scored);
1275        };
1276        // Backward: final norm, then the FFN chain layer by layer.
1277        let t_bwd = std::time::Instant::now();
1278        let mut dh = vec![0f32; n * hsz];
1279        rmsnorm_bwd_pooled(&h, &fm.final_norm, &inv, &dh_n, fm.gemma, &mut dh, pool);
1280        for vl in (0..vn).rev() {
1281            let li = vl % nl;
1282            // Undo the loop-boundary norm this step fed into.
1283            if let Some((hb, inv)) = lnorms[vl].as_ref() {
1284                let mut dprev = vec![0f32; n * hsz];
1285                rmsnorm_bwd_pooled(hb, &fm.final_norm, inv, &dh, fm.gemma, &mut dprev, pool);
1286                dh = dprev;
1287            }
1288            let a = acts[vl].as_ref().expect("acts saved in grad mode");
1289            let g = &masks[vl];
1290            let inter = fm.layers[li].inter;
1291            let mats_hold = fm.mats(li).expect("layer mats");
1292            let wts = self.wts(li, &mats_hold);
1293            let mut dn2 = vec![0f32; n * hsz];
1294            let mut device_done = false;
1295            #[cfg(feature = "gpu")]
1296            if a.act.is_empty() && dffn[li].is_none() {
1297                if let Some(gu) = wts.gu {
1298                    // Phase A on the card: dact = dh·down, the mask gradient
1299                    // from the resident plane, dgu through the act link
1300                    // with the gate folded in, dn2 = dgu·gu. Only dn2 and
1301                    // dm[inter] come back.
1302                    let mut dm_dev = vec![0f32; inter];
1303                    if crate::fcd::bake_ffn_bwd_chain(
1304                        &dh, wts.down, gu, li, &mut dn2, n, hsz, inter, fm.act, Some(g), Some(&mut dm_dev),
1305                    ) {
1306                        for (d, &x) in dmask[vl].iter_mut().zip(&dm_dev) {
1307                            *d += x as f64;
1308                        }
1309                        device_done = true;
1310                    }
1311                }
1312            }
1313            if !device_done {
1314                assert!(
1315                    !a.act.is_empty(),
1316                    "layer {li}: the forward left its FFN plane on the device but the device backward declined"
1317                );
1318                // h2 = h1 + act2 @ downᵀ  →  dact2 = dh @ down.
1319                let mut dact2 = vec![0f32; n * inter];
1320                ops::gemm_dx(&dh, wts.down, &mut dact2, n, inter, hsz, fm.pool.as_deref());
1321                if let Some((_, _, dd)) = dffn[li].as_mut() {
1322                    // dW_down += dhᵀ · act2 (act2 = act·g).
1323                    let mut act2 = a.act.clone();
1324                    {
1325                        let ap = SendMutF(act2.as_mut_ptr());
1326                        pooled_rows(n, pool, &|lo, hi| {
1327                            // SAFETY: disjoint row ranges per worker.
1328                            let rows = unsafe { std::slice::from_raw_parts_mut(ap.at(lo * inter), (hi - lo) * inter) };
1329                            for row in rows.chunks_exact_mut(inter) {
1330                                for (x, &gv) in row.iter_mut().zip(g) {
1331                                    *x *= gv;
1332                                }
1333                            }
1334                        });
1335                    }
1336                    let mut dw = vec![0f32; hsz * inter];
1337                    ops::gemm_dw(&dh, &act2, &mut dw, n, inter, hsz, fm.pool.as_deref());
1338                    for (o, &x) in dd.iter_mut().zip(&dw) {
1339                        *o += x as f64;
1340                    }
1341                }
1342                // Mask grad: dm = Σ_t dact2·act · σ'(m)  (soft; STE-equal).
1343                // Indexed by the VIRTUAL layer: each visit's mask row gets
1344                // exactly its own visit's gradient, no cross-visit sum.
1345                {
1346                    let dm = &mut dmask[vl];
1347                    // Parallel over neuron ranges: each worker owns a column
1348                    // span of dm and walks every row for it.
1349                    let dmp = SendMutF64(dm.as_mut_ptr());
1350                    let (dact2_r, act_r) = (&dact2, &a.act);
1351                    pooled_rows(inter.div_ceil(256), pool, &|lo, hi| {
1352                        let (js, je) = (lo * 256, (hi * 256).min(inter));
1353                        // SAFETY: disjoint column ranges per worker.
1354                        let dmj = unsafe { std::slice::from_raw_parts_mut(dmp.at(js), je - js) };
1355                        for r in 0..n {
1356                            let da = &dact2_r[r * inter + js..r * inter + je];
1357                            let aa = &act_r[r * inter + js..r * inter + je];
1358                            for ((d, &x), &y) in dmj.iter_mut().zip(da).zip(aa) {
1359                                *d += x as f64 * y as f64;
1360                            }
1361                        }
1362                    });
1363                    // σ'(m) folded in once per chunk (constant per neuron).
1364                    for (j, d) in dm.iter_mut().enumerate() {
1365                        let _ = j;
1366                        let _ = d;
1367                    }
1368                }
1369                // dact = dact2 · g;  act·mul backward (pooled).
1370                let mut dg_pre = vec![0f32; n * inter];
1371                let mut du_pre = vec![0f32; n * inter];
1372                act_bwd_rows(
1373                    fm.act,
1374                    &a.gpre,
1375                    &a.upre,
1376                    &dact2,
1377                    Some(g),
1378                    &mut dg_pre,
1379                    &mut du_pre,
1380                    n,
1381                    inter,
1382                    fm.pool.as_deref(),
1383                );
1384                // dn2 = dg_pre @ gate + du_pre @ up — one fused submit when
1385                // the frozen concat exists; the trained-copy path keeps two.
1386                if let Some(gu) = wts.gu {
1387                    let mut dgu = vec![0f32; n * 2 * inter];
1388                    {
1389                        let gp = SendMutF(dgu.as_mut_ptr());
1390                        let (dgr, dur) = (&dg_pre, &du_pre);
1391                        pooled_rows(n, pool, &|lo, hi| {
1392                            for r in lo..hi {
1393                                // SAFETY: disjoint rows per worker.
1394                                let row = unsafe { std::slice::from_raw_parts_mut(gp.at(r * 2 * inter), 2 * inter) };
1395                                row[..inter].copy_from_slice(&dgr[r * inter..(r + 1) * inter]);
1396                                row[inter..].copy_from_slice(&dur[r * inter..(r + 1) * inter]);
1397                            }
1398                        });
1399                    }
1400                    ops::gemm_dx(&dgu, gu, &mut dn2, n, hsz, 2 * inter, fm.pool.as_deref());
1401                } else {
1402                    ops::gemm_dx(
1403                        &dg_pre,
1404                        wts.gate,
1405                        &mut dn2,
1406                        n,
1407                        hsz,
1408                        inter,
1409                        fm.pool.as_deref(),
1410                    );
1411                    let mut dn2b = vec![0f32; n * hsz];
1412                    ops::gemm_dx(
1413                        &du_pre,
1414                        wts.up,
1415                        &mut dn2b,
1416                        n,
1417                        hsz,
1418                        inter,
1419                        fm.pool.as_deref(),
1420                    );
1421                    for (x, &y) in dn2.iter_mut().zip(&dn2b) {
1422                        *x += y;
1423                    }
1424                }
1425                if let Some((dgw, duw, _)) = dffn[li].as_mut() {
1426                    let mut dw = vec![0f32; inter * hsz];
1427                    ops::gemm_dw(&dg_pre, &a.n2, &mut dw, n, hsz, inter, fm.pool.as_deref());
1428                    for (o, &x) in dgw.iter_mut().zip(&dw) {
1429                        *o += x as f64;
1430                    }
1431                    dw.fill(0.0);
1432                    ops::gemm_dw(&du_pre, &a.n2, &mut dw, n, hsz, inter, fm.pool.as_deref());
1433                    for (o, &x) in duw.iter_mut().zip(&dw) {
1434                        *o += x as f64;
1435                    }
1436                }
1437            }
1438            // Post-norm backward into h1; a frozen attention branch carries
1439            // no gradient, so dh1 flows straight to dh_in.
1440            let mut dh1 = dh.clone(); // residual h2 = h1 + ffn
1441            rmsnorm_bwd_pooled(&a.h1, wts.pln, &a.inv2, &dn2, fm.gemma, &mut dh1, pool);
1442            if let (Some(m), Some(dg)) = (&self.attn_tr[li], dattn[li].as_mut()) {
1443                // Full-layer FCD: through the trained attention — post-norm
1444                // gain, o_proj, the head gate, the attention core (device),
1445                // RoPE, q/k/v projections, the input norm — into dh_in.
1446                norm_gain_grad(&a.h1, &a.inv2, &dn2, &mut dg.pln, pool);
1447                let dh_attn = self.attn_backward(li, vl, &h_ins[vl], a, &dh1, m, dg, b, t);
1448                add_into_pooled(&mut dh1, &dh_attn, pool);
1449            }
1450            dh = dh1;
1451        }
1452        crate::fcd::prof::add(&crate::fcd::prof::BWD, t_bwd);
1453        (nll, scored)
1454    }
1455}
1456
1457
1458/// dw[j] = Σ_r dy[r,j]·x[r,j]·inv[r] — the RMSNorm gain gradient (Qwen
1459/// style), pooled over column spans.
1460fn norm_gain_grad(x: &[f32], inv: &[f32], dy: &[f32], dw: &mut [f64], pool: Option<&crate::pool::Pool>) {
1461    let d = dw.len();
1462    let n = x.len() / d;
1463    let dp = SendMutF64(dw.as_mut_ptr());
1464    pooled_rows(d.div_ceil(64), pool, &|lo, hi| {
1465        let (js, je) = (lo * 64, (hi * 64).min(d));
1466        // SAFETY: disjoint column spans per worker.
1467        let out = unsafe { std::slice::from_raw_parts_mut(dp.at(js), je - js) };
1468        for r in 0..n {
1469            let inv_r = inv[r] as f64;
1470            for (o, j) in out.iter_mut().zip(js..je) {
1471                *o += dy[r * d + j] as f64 * x[r * d + j] as f64 * inv_r;
1472            }
1473        }
1474    });
1475}
1476
1477impl Pass<'_> {
1478    /// The attention branch's backward for a full-layer FCD layer: from
1479    /// `dattn` (the gradient at attn_out) to the gradient at h_in through
1480    /// the attention path, accumulating the trained weights' gradients.
1481    #[allow(clippy::too_many_arguments)]
1482    fn attn_backward(
1483        &self,
1484        li: usize,
1485        _vl: usize,
1486        h_in: &[f32],
1487        a: &crate::fcd::LayerActs,
1488        dattn: &[f32],
1489        m: &AttnMasters,
1490        dg: &mut AttnGrads,
1491        b: usize,
1492        t: usize,
1493    ) -> Vec<f32> {
1494        let fm = self.fm;
1495        let pool = fm.pool.as_deref();
1496        let (hsz, nh, nkv, hd) = (fm.hidden, fm.nh, fm.nkv, fm.hd);
1497        let n = b * t;
1498        let (qdim, kvdim) = (nh * hd, nkv * hd);
1499        let (window, local) = fm.attn_geometry(li).expect("full-layer FCD on a non-attention layer");
1500        let (qrot, krot, vproj, ao, head_gain) = a
1501            .attn_full()
1502            .expect("full-layer FCD needs the attention activations");
1503        // n1: the normed input the projections read (recomputed from h_in).
1504        let mut n1 = vec![0f32; n * hsz];
1505        let mut inv1 = vec![0f32; n];
1506        rmsnorm_fwd_pooled(h_in, &m.iln, fm.eps, fm.gemma, &mut n1, &mut inv1, pool);
1507        // ao_eff = ao ⊙ gain; dWo += dattnᵀ·ao_eff; dao_eff = dattn·Wo.
1508        let mut ao_eff = ao.to_vec();
1509        if !head_gain.is_empty() {
1510            for r in 0..n {
1511                for h in 0..nh {
1512                    let gain = head_gain[r * nh + h];
1513                    for x in &mut ao_eff[r * qdim + h * hd..r * qdim + (h + 1) * hd] {
1514                        *x *= gain;
1515                    }
1516                }
1517            }
1518        }
1519        {
1520            let mut dw = vec![0f32; hsz * qdim];
1521            ops::gemm_dw(dattn, &ao_eff, &mut dw, n, qdim, hsz, pool);
1522            for (o, &x) in dg.wo.iter_mut().zip(&dw) {
1523                *o += x as f64;
1524            }
1525        }
1526        let mut dao_eff = vec![0f32; n * qdim];
1527        ops::gemm_dx(dattn, &m.wo, &mut dao_eff, n, qdim, hsz, pool);
1528        // Head gate: dao = dao_eff·gain; dgain = Σ_c dao_eff·ao; dgraw = dgain·σ′.
1529        let mut dn1 = vec![0f32; n * hsz];
1530        let mut dao = dao_eff;
1531        if let (Some(gw), Some(dgw)) = (&m.gproj, dg.gproj.as_mut()) {
1532            let mut dgraw = vec![0f32; n * nh];
1533            for r in 0..n {
1534                for h in 0..nh {
1535                    let gain = head_gain[r * nh + h];
1536                    let s = r * qdim + h * hd;
1537                    let mut dgain = 0f32;
1538                    for c in 0..hd {
1539                        dgain += dao[s + c] * ao[s + c];
1540                        dao[s + c] *= gain;
1541                    }
1542                    dgraw[r * nh + h] = dgain * gain * (1.0 - gain);
1543                }
1544            }
1545            let mut dw = vec![0f32; nh * hsz];
1546            ops::gemm_dw(&dgraw, &n1, &mut dw, n, hsz, nh, pool);
1547            for (o, &x) in dgw.iter_mut().zip(&dw) {
1548                *o += x as f64;
1549            }
1550            ops::gemm_dx(&dgraw, gw, &mut dn1, n, hsz, nh, pool);
1551        }
1552        // Attention core: dq/dk (rotated space), dv — device chain, host fallback.
1553        let mut dqrot = vec![0f32; n * qdim];
1554        let mut dkrot = vec![0f32; n * kvdim];
1555        let mut dvproj = vec![0f32; n * kvdim];
1556        let mut done = false;
1557        #[cfg(feature = "gpu")]
1558        {
1559            #[cfg(feature = "cuda")]
1560            if crate::gpu::cuda_active() {
1561                done = crate::gpu_cuda::bake_attn_bwd(
1562                    qrot, krot, vproj, &dao, b, t, nh, nkv, hd, window, &mut dqrot, &mut dkrot, &mut dvproj,
1563                );
1564            }
1565            if !done {
1566                done = crate::gpu_wgpu::attn_bwd_chain_f32(
1567                    qrot, krot, vproj, &dao, b, t, nh, nkv, hd, window, &mut dqrot, &mut dkrot, &mut dvproj,
1568                );
1569            }
1570        }
1571        if !done {
1572            let rep = nh / nkv;
1573            for bi in 0..b {
1574                for h in 0..nh {
1575                    let g = h / rep;
1576                    let mut q64 = vec![0f64; t * hd];
1577                    let mut k64 = vec![0f64; t * hd];
1578                    let mut v64 = vec![0f64; t * hd];
1579                    let mut do64 = vec![0f64; t * hd];
1580                    for p in 0..t {
1581                        let r = bi * t + p;
1582                        for c in 0..hd {
1583                            q64[p * hd + c] = qrot[r * qdim + h * hd + c] as f64;
1584                            k64[p * hd + c] = krot[r * kvdim + g * hd + c] as f64;
1585                            v64[p * hd + c] = vproj[r * kvdim + g * hd + c] as f64;
1586                            do64[p * hd + c] = dao[r * qdim + h * hd + c] as f64;
1587                        }
1588                    }
1589                    let mut dq = vec![0f64; t * hd];
1590                    let mut dk = vec![0f64; t * hd];
1591                    let mut dv = vec![0f64; t * hd];
1592                    ops::attn_head_bwd_window(&q64, &k64, &v64, &do64, t, hd, hd, window, &mut dq, &mut dk, &mut dv);
1593                    for p in 0..t {
1594                        let r = bi * t + p;
1595                        for c in 0..hd {
1596                            dqrot[r * qdim + h * hd + c] += dq[p * hd + c] as f32;
1597                            dkrot[r * kvdim + g * hd + c] += dk[p * hd + c] as f32;
1598                            dvproj[r * kvdim + g * hd + c] += dv[p * hd + c] as f32;
1599                        }
1600                    }
1601                }
1602            }
1603        }
1604        // RoPE backward (no qk-norm on these layers), per head.
1605        let (rotary_dim, inv_freq) = fm.layer_rope(local);
1606        for r in 0..n {
1607            let pos = r % t;
1608            for h in 0..nh {
1609                let s = r * qdim + h * hd;
1610                ops::rope_bwd(&mut dqrot[s..s + rotary_dim], pos, inv_freq);
1611            }
1612            for g in 0..nkv {
1613                let s = r * kvdim + g * hd;
1614                ops::rope_bwd(&mut dkrot[s..s + rotary_dim], pos, inv_freq);
1615            }
1616        }
1617        // dqkv = [dq | dk | dv]; dWqkv += dqkvᵀ·n1; dn1 += dqkv·Wqkv.
1618        let fused = qdim + 2 * kvdim;
1619        let mut dqkv = vec![0f32; n * fused];
1620        for r in 0..n {
1621            let row = &mut dqkv[r * fused..(r + 1) * fused];
1622            row[..qdim].copy_from_slice(&dqrot[r * qdim..(r + 1) * qdim]);
1623            row[qdim..qdim + kvdim].copy_from_slice(&dkrot[r * kvdim..(r + 1) * kvdim]);
1624            row[qdim + kvdim..].copy_from_slice(&dvproj[r * kvdim..(r + 1) * kvdim]);
1625        }
1626        {
1627            let mut dw = vec![0f32; fused * hsz];
1628            ops::gemm_dw(&dqkv, &n1, &mut dw, n, hsz, fused, pool);
1629            for (o, &x) in dg.wqkv.iter_mut().zip(&dw) {
1630                *o += x as f64;
1631            }
1632        }
1633        {
1634            let mut dx = vec![0f32; n * hsz];
1635            ops::gemm_dx(&dqkv, &m.wqkv, &mut dx, n, hsz, fused, pool);
1636            add_into_pooled(&mut dn1, &dx, pool);
1637        }
1638        // Input norm: gain gradient + through-grad into h_in.
1639        norm_gain_grad(h_in, &inv1, &dn1, &mut dg.iln, pool);
1640        let mut dh_in = vec![0f32; n * hsz];
1641        rmsnorm_bwd_pooled(h_in, &m.iln, &inv1, &dn1, fm.gemma, &mut dh_in, pool);
1642        dh_in
1643    }
1644}
1645
1646/// Held-out PPL with the hard mask (and Phase-B weights when present).
1647/// The device chains' phase timers (0 weights, 1 submit→poll, 2 copies);
1648/// zero without the gpu feature.
1649fn chain_prof(i: usize) -> f64 {
1650    #[cfg(feature = "gpu")]
1651    {
1652        crate::gpu_wgpu::chain_prof_take(i)
1653    }
1654    #[cfg(not(feature = "gpu"))]
1655    {
1656        let _ = i;
1657        0.0
1658    }
1659}
1660
1661/// " | acc X% bal Y%" (focused classes), " | tok-acc X%" (answer span),
1662/// or nothing (all-token LM).
1663fn score_suffix(score: &HeldScore) -> String {
1664    match (score.accuracy, score.balanced_accuracy) {
1665        (Some(a), Some(b)) => format!(" | acc {:.2}% bal {:.2}%", a * 100.0, b * 100.0),
1666        (Some(a), None) => match (score.micro_accuracy, score.token_accuracy) {
1667            (Some(m), Some(t)) => format!(
1668                " | q-acc macro {:.2}% micro {:.2}% tok {:.2}%",
1669                a * 100.0,
1670                m * 100.0,
1671                t * 100.0
1672            ),
1673            (None, Some(t)) => format!(" | q-acc {:.2}% tok-acc {:.2}%", a * 100.0, t * 100.0),
1674            _ => format!(" | tok-acc {:.2}%", a * 100.0),
1675        },
1676        _ => String::new(),
1677    }
1678}
1679
1680fn held_ppl(pass: &Pass, held: &[Vec<u32>]) -> f64 {
1681    held_score(pass, held).ppl
1682}
1683
1684fn held_score(pass: &Pass, held: &[Vec<u32>]) -> HeldScore {
1685    held_score_tagged(pass, held, None)
1686}
1687
1688/// `held_score` with per-tag verdict counts: when the records carry tags
1689/// and the span locates values, the score's accuracy is the MACRO verdict
1690/// accuracy over tags (each family weighs the same, as in a benchmark
1691/// index), the micro one rides along.
1692fn held_score_tagged(pass: &Pass, held: &[Vec<u32>], tags: Option<&HeldTags>) -> HeldScore {
1693    // Bounded batched passes over the held set: equal-length records share
1694    // one GEMM per weight, while the cap keeps activation/GPU scratch memory
1695    // predictable for a full validation sweep. Aggregation is exact because
1696    // NLL and focused-class counts are additive across groups.
1697    if held.is_empty() {
1698        return HeldScore {
1699            ppl: f64::NAN,
1700            accuracy: None,
1701            balanced_accuracy: None,
1702            token_accuracy: None,
1703            micro_accuracy: None,
1704            per_tag: Vec::new(),
1705        };
1706    }
1707    let mut nll = 0f64;
1708    let mut n = 0usize;
1709    let mut stats = FocusStats::new(pass.focus_tokens.len());
1710    // Up to 32 records per pass, bounded by tokens: 32 x 3072-token chat
1711    // records made a 98k-row pass whose gate+up plane (n x 2*inter f32)
1712    // crossed the 2 GiB device binding limit and panicked wgpu.
1713    // 8k tokens keeps a 4 B model's gate+up plane (n × 20480 f32) under
1714    // the 2 GiB binding ceiling once the scratch rounds up; CMF_BAKE_EVAL_TOKENS
1715    // overrides.
1716    const GROUP_MAX: usize = 32;
1717    let group_tokens: usize = std::env::var("CMF_BAKE_EVAL_TOKENS")
1718        .ok()
1719        .and_then(|v| v.parse().ok())
1720        .unwrap_or(8_192);
1721    let groups: Vec<&[Vec<u32>]> = {
1722        let mut v = Vec::new();
1723        let mut i = 0;
1724        while i < held.len() {
1725            let len = held[i].len();
1726            let cap = (group_tokens / len.max(1)).clamp(1, GROUP_MAX);
1727            let mut j = i;
1728            while j < held.len() && held[j].len() == len && j - i < cap {
1729                j += 1;
1730            }
1731            v.push(&held[i..j]);
1732            i = j;
1733        }
1734        v
1735    };
1736    let mut per_tag: Vec<(usize, usize)> = vec![(0, 0); tags.map_or(0, |t| t.names.len())];
1737    let mut credit = |at: usize, part: &FocusStats| {
1738        if let Some(tg) = tags {
1739            for (j, &(q, ok)) in part.seq.iter().enumerate() {
1740                if let Some(&ti) = tg.of.get(at + j) {
1741                    per_tag[ti].0 += q;
1742                    per_tag[ti].1 += ok;
1743                }
1744            }
1745        }
1746    };
1747    let mut at = 0usize;
1748    for group in groups {
1749        let t = group[0].len();
1750        if group.iter().all(|c| c.len() == t) {
1751            let flat: Vec<u32> = group.iter().flatten().copied().collect();
1752            let mut part = FocusStats::new(pass.focus_tokens.len());
1753            let (l, k) = pass.chunk_batch_scored(&flat, group.len(), None, Some(&mut part));
1754            nll += l;
1755            n += k;
1756            credit(at, &part);
1757            stats.merge(&part);
1758        } else {
1759            for (j, c) in group.iter().enumerate() {
1760                let mut part = FocusStats::new(pass.focus_tokens.len());
1761                let (l, k) = pass.chunk_batch_scored(c, 1, None, Some(&mut part));
1762                nll += l;
1763                n += k;
1764                credit(at + j, &part);
1765                stats.merge(&part);
1766            }
1767        }
1768        at += group.len();
1769    }
1770    let (mut accuracy, token_accuracy) = stats.accuracies();
1771    let mut micro_accuracy = None;
1772    let mut tagged = Vec::new();
1773    if let Some(tg) = tags
1774        && token_accuracy.is_some()
1775    {
1776        let rates: Vec<f64> =
1777            per_tag.iter().filter(|(q, _)| *q > 0).map(|&(q, ok)| ok as f64 / q as f64).collect();
1778        if !rates.is_empty() {
1779            micro_accuracy = accuracy;
1780            accuracy = Some(rates.iter().sum::<f64>() / rates.len() as f64);
1781            tagged = tg.names.iter().cloned().zip(per_tag).map(|(name, (q, ok))| (name, q, ok)).collect();
1782        }
1783    }
1784    HeldScore {
1785        ppl: (nll / n.max(1) as f64).exp(),
1786        accuracy,
1787        balanced_accuracy: stats.balanced_accuracy(),
1788        token_accuracy,
1789        micro_accuracy,
1790        per_tag: tagged,
1791    }
1792}
1793
1794/// The calibration records as runs of equal length, each cut into blocks
1795/// of at most `batch` records: `(start, count)`. Records are expected
1796/// sorted by length (stable, so the shuffle within a length survives);
1797/// the batch at `step` is `blocks[step % blocks.len()]`.
1798fn length_blocks(calib: &[Vec<u32>], batch: usize) -> Vec<(usize, usize)> {
1799    let batch = batch.max(1);
1800    let mut blocks = Vec::new();
1801    let mut i = 0;
1802    while i < calib.len() {
1803        let len = calib[i].len();
1804        let mut j = i;
1805        while j < calib.len() && calib[j].len() == len && j - i < batch {
1806            j += 1;
1807        }
1808        blocks.push((i, j - i));
1809        i = j;
1810    }
1811    blocks
1812}
1813
1814fn calibration_batch(
1815    calib: &[Vec<u32>],
1816    step: usize,
1817    requested: usize,
1818) -> Result<(Vec<u32>, usize), String> {
1819    let batch = requested.max(1).min(calib.len());
1820    // Equal-length records only: with length buckets the records are
1821    // sorted by length and the blocks never mix widths.
1822    let blocks = length_blocks(calib, batch);
1823    let (start, count) = blocks[step % blocks.len()];
1824    let width = calib[start].len();
1825    let mut flat = Vec::with_capacity(count * width);
1826    for record in &calib[start..start + count] {
1827        if record.len() != width {
1828            return Err(format!(
1829                "skill bake: --batch needs equal-length records ({} != {width})",
1830                record.len()
1831            ));
1832        }
1833        flat.extend_from_slice(record);
1834    }
1835    Ok((flat, count))
1836}
1837
1838fn build_focused_fcd_cache(
1839    pass: &Pass<'_>,
1840    records: &[Vec<u32>],
1841    extraction_batch: usize,
1842) -> Result<FocusedFcdCache, String> {
1843    let mut cache = FocusedFcdCache::default();
1844    for group in records.chunks(extraction_batch.max(1)) {
1845        let width = group[0].len();
1846        if group.iter().any(|record| record.len() != width) {
1847            return Err("focused final-FFN cache needs equal-length records".into());
1848        }
1849        let flat: Vec<u32> = group.iter().flatten().copied().collect();
1850        cache.append(pass.cache_final_ffn_batch(&flat, group.len())?);
1851    }
1852    Ok(cache)
1853}
1854
1855/// Exact final-FFN focused loss, optionally with gradients for the three full
1856/// FCD projections.  The upstream representation came from the same CMF and
1857/// mask in `build_focused_fcd_cache`; no external checkpoint format is used.
1858fn cached_fcd_run(
1859    fm: &FcdModel,
1860    cache: &FocusedFcdCache,
1861    indices: &[usize],
1862    weights: (&[f32], &[f32], &[f32]),
1863    gate: &[f32],
1864    focus_tokens: &[u32],
1865    want_grad: bool,
1866) -> (HeldScore, Option<(Vec<f64>, Vec<f64>, Vec<f64>)>) {
1867    let (gate_w, up_w, down_w) = weights;
1868    let rows = indices.len();
1869    let hidden = fm.hidden;
1870    let inter = gate.len();
1871    if rows == 0 {
1872        return (
1873            HeldScore {
1874                ppl: f64::NAN,
1875                accuracy: None,
1876                balanced_accuracy: None,
1877                token_accuracy: None,
1878                micro_accuracy: None,
1879                per_tag: Vec::new(),
1880            },
1881            None,
1882        );
1883    }
1884    let h1 = gather_rows(&cache.h1, indices, hidden);
1885    let n2 = gather_rows(&cache.n2, indices, hidden);
1886    let mut gate_pre = vec![0f32; rows * inter];
1887    let mut up_pre = vec![0f32; rows * inter];
1888    ops::gemm_nt(
1889        &n2,
1890        gate_w,
1891        &mut gate_pre,
1892        rows,
1893        hidden,
1894        inter,
1895        fm.pool.as_deref(),
1896    );
1897    ops::gemm_nt(
1898        &n2,
1899        up_w,
1900        &mut up_pre,
1901        rows,
1902        hidden,
1903        inter,
1904        fm.pool.as_deref(),
1905    );
1906    let mut act = vec![0f32; rows * inter];
1907    for row in 0..rows {
1908        for column in 0..inter {
1909            let at = row * inter + column;
1910            act[at] = fm.act.fwd(gate_pre[at]) * up_pre[at] * gate[column];
1911        }
1912    }
1913    let mut ffn = vec![0f32; rows * hidden];
1914    ops::gemm_nt(
1915        &act,
1916        down_w,
1917        &mut ffn,
1918        rows,
1919        inter,
1920        hidden,
1921        fm.pool.as_deref(),
1922    );
1923    let mut h2 = h1;
1924    for (value, &delta) in h2.iter_mut().zip(&ffn) {
1925        *value += delta;
1926    }
1927    let mut normed = vec![0f32; rows * hidden];
1928    let mut inv = vec![0f32; rows];
1929    ops::rmsnorm_fwd(&h2, &fm.final_norm, fm.eps, fm.gemma, &mut normed, &mut inv);
1930
1931    let lm: &[f32] = fm.lm_head.as_deref().unwrap_or(&fm.embed);
1932    let mut stats = FocusStats::new(focus_tokens.len());
1933    let mut nll = 0f64;
1934    let mut dh_normed = want_grad.then(|| vec![0f32; rows * hidden]);
1935    for (local_row, &cache_row) in indices.iter().enumerate() {
1936        let target = cache.targets[cache_row];
1937        let state = &normed[local_row * hidden..(local_row + 1) * hidden];
1938        let logits: Vec<f32> = focus_tokens
1939            .iter()
1940            .map(|&id| {
1941                state
1942                    .iter()
1943                    .zip(&lm[id as usize * hidden..(id as usize + 1) * hidden])
1944                    .map(|(&left, &right)| left * right)
1945                    .sum()
1946            })
1947            .collect();
1948        let mx = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max) as f64;
1949        let exps: Vec<f64> = logits
1950            .iter()
1951            .map(|&value| ((value as f64) - mx).exp())
1952            .collect();
1953        let sum: f64 = exps.iter().sum();
1954        nll += mx + sum.ln() - logits[target] as f64;
1955        let predicted = logits
1956            .iter()
1957            .enumerate()
1958            .max_by(|(_, left), (_, right)| left.total_cmp(right))
1959            .map(|(class, _)| class)
1960            .expect("focused classes are non-empty");
1961        stats.total += 1;
1962        stats.class_total[target] += 1;
1963        if predicted == target {
1964            stats.correct += 1;
1965            stats.class_correct[target] += 1;
1966        }
1967        if let Some(gradient) = dh_normed.as_mut() {
1968            let row = &mut gradient[local_row * hidden..(local_row + 1) * hidden];
1969            for (class, (&id, probability)) in focus_tokens.iter().zip(exps).enumerate() {
1970                let coefficient =
1971                    (probability / sum - usize::from(class == target) as f64) / rows as f64;
1972                let head = &lm[id as usize * hidden..(id as usize + 1) * hidden];
1973                for (value, &weight) in row.iter_mut().zip(head) {
1974                    *value += (coefficient * weight as f64) as f32;
1975                }
1976            }
1977        }
1978    }
1979    let score = HeldScore {
1980        ppl: (nll / rows as f64).exp(),
1981        accuracy: stats.accuracy(),
1982        balanced_accuracy: stats.balanced_accuracy(),
1983        token_accuracy: None,
1984        micro_accuracy: None,
1985        per_tag: Vec::new(),
1986    };
1987    let Some(dh_normed) = dh_normed else {
1988        return (score, None);
1989    };
1990
1991    let mut dh = vec![0f32; rows * hidden];
1992    ops::rmsnorm_bwd(
1993        &h2,
1994        &fm.final_norm,
1995        &inv,
1996        &dh_normed,
1997        fm.gemma,
1998        &mut dh,
1999        None,
2000    );
2001    let mut dact = vec![0f32; rows * inter];
2002    ops::gemm_dx(
2003        &dh,
2004        down_w,
2005        &mut dact,
2006        rows,
2007        inter,
2008        hidden,
2009        fm.pool.as_deref(),
2010    );
2011    let mut dg_pre = vec![0f32; rows * inter];
2012    let mut du_pre = vec![0f32; rows * inter];
2013    for row in 0..rows {
2014        for column in 0..inter {
2015            let at = row * inter + column;
2016            let da = dact[at] * gate[column];
2017            dg_pre[at] = da * up_pre[at] * fm.act.bwd(gate_pre[at]);
2018            du_pre[at] = da * fm.act.fwd(gate_pre[at]);
2019        }
2020    }
2021    let mut dg = vec![0f32; inter * hidden];
2022    let mut du = vec![0f32; inter * hidden];
2023    let mut dd = vec![0f32; hidden * inter];
2024    ops::gemm_dw(
2025        &dg_pre,
2026        &n2,
2027        &mut dg,
2028        rows,
2029        hidden,
2030        inter,
2031        fm.pool.as_deref(),
2032    );
2033    ops::gemm_dw(
2034        &du_pre,
2035        &n2,
2036        &mut du,
2037        rows,
2038        hidden,
2039        inter,
2040        fm.pool.as_deref(),
2041    );
2042    ops::gemm_dw(&dh, &act, &mut dd, rows, inter, hidden, fm.pool.as_deref());
2043    (
2044        score,
2045        Some((
2046            dg.into_iter().map(f64::from).collect(),
2047            du.into_iter().map(f64::from).collect(),
2048            dd.into_iter().map(f64::from).collect(),
2049        )),
2050    )
2051}
2052
2053/// Score a WRITTEN specialist through the replica's own math (f32
2054/// dequant of whatever the file carries) with the file's binary mask
2055/// held hard — the decomposition probe that tells "the requant at write
2056/// cost the quality" from "the runtime applies the mask differently".
2057/// Returns (bare, masked) held-PPL over the chunks.
2058pub fn replica_score_file_mask(
2059    model: &Arc<CmfModel>,
2060    chunks: &[Vec<u32>],
2061) -> Result<(f64, f64), String> {
2062    let o1_off = crate::nystrom::O1Cfg {
2063        layers: crate::nystrom::O1Layers::List(Vec::new()),
2064        m: 4,
2065        w: 8,
2066        sink: 1,
2067        rect: crate::nystrom::O1_DEFAULT_RECT,
2068    };
2069    let fm = FcdModel::from_cmf(model, &o1_off, false)?;
2070    let nl = fm.layers.len();
2071    let loops = fm.loops.max(1);
2072    let vn = nl * loops;
2073    let inter = fm.layers[0].inter;
2074    let ffn: Vec<Option<(Vec<f32>, Vec<f32>, Vec<f32>)>> = vec![None; nl];
2075    let no_attn: Vec<Option<AttnMasters>> = vec![None; ffn.len()];
2076    // Binary mask → logits at ±50: σ crosses any τ exactly as the bit says.
2077    let task = &model.masks.default_task;
2078    let mask = model
2079        .masks
2080        .masks
2081        .iter()
2082        .find(|m| &m.name == task)
2083        .or_else(|| model.masks.masks.first());
2084    let open: Vec<Vec<f32>> = vec![vec![50.0; inter]; vn];
2085    let masked_logits: Vec<Vec<f32>> = match mask {
2086        Some(m) => (0..vn)
2087            .map(|vl| {
2088                let row = m.ffn_masks.get(vl).map(|v| v.as_slice()).unwrap_or(&[]);
2089                (0..inter)
2090                    .map(|j| {
2091                        if (row.get(j >> 3).copied().unwrap_or(0) >> (j & 7)) & 1 != 0 {
2092                            50.0
2093                        } else {
2094                            -50.0
2095                        }
2096                    })
2097                    .collect()
2098            })
2099            .collect(),
2100        None => open.clone(),
2101    };
2102    let score = |logits: &[Vec<f32>]| -> f64 {
2103        let pass = Pass {
2104            fm: &fm,
2105            tau: 0.5,
2106            logits,
2107            hard: true,
2108            ffn: &ffn,
2109            focus_tokens: &[],
2110            focus_follow_tokens: &[],
2111            span: None,
2112            soft_fold: false,
2113            attn_tr: &no_attn,
2114        };
2115        held_ppl(&pass, chunks)
2116    };
2117    Ok((score(&open), score(&masked_logits)))
2118}
2119
2120/// The whole recipe. `log` receives progress lines.
2121pub fn skill_bake(
2122    model: &Arc<CmfModel>,
2123    chunks: &[Vec<u32>],
2124    held_n: usize,
2125    hy: &BakeHyper,
2126    mut log: impl FnMut(&str),
2127) -> Result<(BakeReport, BakeArtifacts), String> {
2128    let t0 = std::time::Instant::now();
2129    let o1_off = crate::nystrom::O1Cfg {
2130        layers: crate::nystrom::O1Layers::List(Vec::new()),
2131        m: 4,
2132        w: 8,
2133        sink: 1,
2134        rect: crate::nystrom::O1_DEFAULT_RECT,
2135    };
2136    let mut fm = FcdModel::from_cmf(model, &o1_off, false)?;
2137    // The bake's backward never enters attention (frozen, residual
2138    // through-path only), so the attention activations are dead weight:
2139    // on the device chain they were ~700 MB of PCIe readback per layer.
2140    fm.attn_acts = false;
2141    let nl = fm.layers.len();
2142    // Full-layer FCD masters (attention + norms), filled before Phase B;
2143    // every Pass carries the slice so a trained layer's forward reads them.
2144    let mut attn_tr: Vec<Option<AttnMasters>> = vec![None; nl];
2145    let inter = fm.layers.iter().map(|l| l.inter).max().unwrap_or(0);
2146    // Stable sorts by length: with --length-buckets the batches and the
2147    // held-out groups stay homogeneous while the shuffle within a length
2148    // survives; without buckets every record has the chunk width and
2149    // nothing moves.
2150    let mut held: Vec<Vec<u32>> = chunks[..held_n.min(chunks.len())].to_vec();
2151    // The tags follow their records through the stable length sort.
2152    let mut order: Vec<usize> = (0..held.len()).collect();
2153    order.sort_by_key(|&i| held[i].len());
2154    let held_tags: Option<HeldTags> = hy.held_tags.as_ref().map(|t| HeldTags {
2155        names: t.names.clone(),
2156        of: order.iter().map(|&i| t.of.get(i).copied().unwrap_or(0)).collect(),
2157    });
2158    held = order.iter().map(|&i| std::mem::take(&mut held[i])).collect();
2159    let mut calib: Vec<Vec<u32>> = chunks[held_n.min(chunks.len())..].to_vec();
2160    calib.sort_by_key(Vec::len);
2161    if calib.len() < 12 {
2162        return Err(format!(
2163            "skill bake: corpus too small ({} calib chunks)",
2164            calib.len()
2165        ));
2166    }
2167    // Analysis-only callers can request a native, batched focused score over
2168    // a validation corpus without training or writing a specialist.  The
2169    // scoring path already handles per-layer FFN widths; the optimizer and
2170    // defragment writer below still require one common width, so return the
2171    // identity checkpoint before that training-only constraint is applied.
2172    // (A supplied mask is not an identity run: it goes through the scored
2173    // path below so the mask is evaluated and written.)
2174    if hy.steps_a == 0 && hy.steps_b == 0 && hy.fcd_layers == 0 && hy.mask_logits.is_none() {
2175        let logits: Vec<Vec<f32>> = fm
2176            .layers
2177            .iter()
2178            .map(|layer| vec![100.0; layer.inter])
2179            .collect();
2180        let ffn = vec![None; nl];
2181        let pass = Pass {
2182            fm: &fm,
2183            tau: hy.tau,
2184            logits: &logits,
2185            hard: true,
2186            ffn: &ffn,
2187            focus_tokens: &hy.focus_tokens,
2188            focus_follow_tokens: &hy.focus_follow_tokens,
2189            span: hy.answer_span.as_ref(),
2190            soft_fold: hy.soft_fold,
2191            attn_tr: &attn_tr,
2192        };
2193        let score = held_score(&pass, &held);
2194        let keep: Vec<Vec<bool>> = fm
2195            .layers
2196            .iter()
2197            .map(|layer| vec![true; layer.inter])
2198            .collect();
2199        let loops = fm.loops.max(1);
2200        let keep_visits = (0..loops).flat_map(|_| keep.iter().cloned()).collect();
2201        let report = BakeReport {
2202            backbone: score.ppl,
2203            masked: score.ppl,
2204            overlaid: score.ppl,
2205            pruned_ratio: 0.0,
2206            kept_per_layer: keep.iter().map(Vec::len).collect(),
2207            backbone_accuracy: score.accuracy,
2208            masked_accuracy: score.accuracy,
2209            overlaid_accuracy: score.accuracy,
2210            backbone_balanced_accuracy: score.balanced_accuracy,
2211            masked_balanced_accuracy: score.balanced_accuracy,
2212            overlaid_balanced_accuracy: score.balanced_accuracy,
2213            selected_step: 0,
2214            sec: t0.elapsed().as_secs_f64(),
2215        };
2216        let arts = BakeArtifacts {
2217            keep,
2218            keep_visits,
2219            down: vec![Vec::new(); nl],
2220            gate_up: vec![None; nl],
2221            fcd_layers: Vec::new(),
2222            attn: (0..nl).map(|_| None).collect(),
2223            logits: logits.clone(),
2224            final_logits: logits,
2225            checkpoints: Vec::new(),
2226        };
2227        return Ok((report, arts));
2228    }
2229    if fm.layers.iter().any(|l| l.inter != inter) {
2230        return Err("skill bake: non-uniform FFN widths".into());
2231    }
2232    if hy.batch == 0 {
2233        return Err("skill bake: batch must be positive".into());
2234    }
2235    let fcd: Vec<usize> = (nl.saturating_sub(hy.fcd_layers)..nl).collect();
2236    let _rng = SplitMix64::new(hy.seed);
2237
2238    // Trainables. The gate starts as close to OPEN as the arithmetic
2239    // allows, because step zero must be the backbone and nothing else.
2240    //
2241    // It used to start at 2.0, and σ(2.0) = 0.881 — every FFN neuron
2242    // scaled to seven eighths before a single gradient. On an ordinary
2243    // stack that costs a few percent of perplexity and hides. On a
2244    // LOOPED Transformer it does not: Nanbeige 4.2 runs its 22 layers
2245    // twice, so each physical FFN is visited twice and the factor
2246    // compounds to 0.881² = 0.776 per layer over 44 visits. Measured:
2247    // baseline 4.187 → 278.4 at step 30 with 0% pruned. Nothing had been
2248    // pruned; the mask had simply turned the model down.
2249    //
2250    // So solve for the init instead of hardcoding it — but solve for the
2251    // right target. Pushing σ(m0)^loops to 0.999 starts at the backbone
2252    // and cannot move: the gradient carries σ'(m) = σ(1−σ), which at
2253    // σ = 0.9995 is 5e-4 against 0.105 at the old 2.0, and BOTH the data
2254    // term and the L1 term are scaled by it (see the update below). That
2255    // was tried: 60 steps, 0% pruned, hard-PPL equal to the baseline to
2256    // three digits. Identity that cannot learn is not an improvement.
2257    //
2258    // The quantity to preserve is the EFFECTIVE start — what the stack
2259    // actually multiplies by, once per visit compounded over the loop —
2260    // at the value the recipe was validated with on ordinary models:
2261    // σ(m0)^loops = σ(2.0) = 0.881. One loop reproduces the old constant
2262    // exactly, so nothing regresses; two loops open the per-visit gate to
2263    // 0.9385 so the compounded factor is again 0.881, with σ' = 0.058
2264    // rather than 0.0005.
2265    let loops = fm.loops.max(1);
2266    let m0 = mask_init_logit_for(loops, hy.mask_init);
2267    // One mask row per VIRTUAL layer: nl × loops. Unlooped: vn == nl.
2268    let vn = nl * loops;
2269    let mut logits: Vec<Vec<f32>> = match &hy.mask_logits {
2270        Some(m) => {
2271            if m.len() != vn || m.iter().any(|row| row.len() != inter) {
2272                return Err(format!(
2273                    "skill bake: --mask-from has {} rows of {} logits; this model needs {vn} × {inter}",
2274                    m.len(),
2275                    m.first().map(Vec::len).unwrap_or(0)
2276                ));
2277            }
2278            log(&format!("mask: resuming from {} supplied logit rows", m.len()));
2279            m.clone()
2280        }
2281        None => vec![vec![m0; inter]; vn],
2282    };
2283    let mut ffn: Vec<Option<(Vec<f32>, Vec<f32>, Vec<f32>)>> = vec![None; nl];
2284
2285    // Baseline (no mask): even σ(m0) is not exactly 1, so measure with
2286    // gates forced open via hard mask over +∞… simplest: logits +50.
2287    let open: Vec<Vec<f32>> = vec![vec![50.0; inter]; vn];
2288    let base_pass = Pass {
2289        fm: &fm,
2290        tau: hy.tau,
2291        logits: &open,
2292        hard: true,
2293        ffn: &ffn,
2294        focus_tokens: &hy.focus_tokens,
2295        focus_follow_tokens: &hy.focus_follow_tokens,
2296        span: hy.answer_span.as_ref(),
2297            soft_fold: hy.soft_fold,
2298            attn_tr: &attn_tr,
2299    };
2300    // CMF_BAKE_SKIP_BASELINE=1 with a supplied mask: a checkpoint
2301    // measurement that already knows the backbone's score skips its pass.
2302    let skip_baseline = hy.mask_logits.is_some()
2303        && std::env::var("CMF_BAKE_SKIP_BASELINE").is_ok_and(|v| v == "1");
2304    let backbone_score = if skip_baseline {
2305        HeldScore {
2306            ppl: f64::NAN,
2307            accuracy: None,
2308            balanced_accuracy: None,
2309            token_accuracy: None,
2310            micro_accuracy: None,
2311            per_tag: Vec::new(),
2312        }
2313    } else {
2314        held_score_tagged(&base_pass, &held, held_tags.as_ref())
2315    };
2316    let backbone = backbone_score.ppl;
2317    log(&format!(
2318        "baseline (full): {backbone:.3}{}",
2319        score_suffix(&backbone_score)
2320    ));
2321    if let Some(line) = tag_line(&backbone_score) {
2322        log(&format!("    per tag: {line}"));
2323    }
2324    // A resumed mask is scored before it trains on: the run's own start,
2325    // and with --steps-a 0 a held-out measurement of any checkpoint.
2326    if hy.mask_logits.is_some() {
2327        let start_pass = Pass {
2328            fm: &fm,
2329            tau: hy.tau,
2330            logits: &logits,
2331            hard: true,
2332            ffn: &ffn,
2333            focus_tokens: &hy.focus_tokens,
2334            focus_follow_tokens: &hy.focus_follow_tokens,
2335            span: hy.answer_span.as_ref(),
2336            soft_fold: hy.soft_fold,
2337            attn_tr: &attn_tr,
2338        };
2339        let s0 = held_score_tagged(&start_pass, &held, held_tags.as_ref());
2340        log(&format!("supplied mask: {:.3}{}", s0.ppl, score_suffix(&s0)));
2341        if let Some(line) = tag_line(&s0) {
2342            log(&format!("    per tag: {line}"));
2343        }
2344    }
2345
2346    // ── Phase A: mask training ──
2347    let mut adam_a = Adam::new(&vec![inter; vn], hy.lr_a);
2348    let mut l1 = hy.l1_init * hy.l1_mult;
2349    let l1_step_eff = hy.l1_step * hy.l1_mult;
2350    // best = (ppl, logits_snapshot, sparsity)
2351    let mut best: (f64, Option<Vec<Vec<f32>>>, f64) = (f64::MAX, None, 0.0);
2352    let mut best_accuracy = f64::NEG_INFINITY;
2353    let mut best_balanced = f64::NEG_INFINITY;
2354    let mut best_step = 0usize;
2355    let mut checkpoints = Vec::new();
2356    // Track the highest-sparsity checkpoint as fallback.
2357    let mut max_sp: (f64, Option<Vec<Vec<f32>>>, f64) = (f64::MAX, None, 0.0);
2358    let mut max_sp_step = 0usize;
2359    let mut prev_alive: Option<Vec<Vec<bool>>> = None;
2360    // In-process phase timers: this loop was estimated three different
2361    // ways and every estimate came out under a fifth of the measured
2362    // step time. Measure, then optimize the top line, not the guess.
2363    let mut acc_chunk = 0f64;
2364    let mut acc_adam = 0f64;
2365    // Phase A trains in strict f32: the mask SELECTS neurons by its
2366    // gradient, and f16 operand rounding on that signal — fine for every
2367    // forward and eval in this file — compounds over ~90 steps into
2368    // closing the wrong neurons (measured: hard-PPL 5.207 vs 4.293 at the
2369    // same 2.56% sparsity; the f32 run retraces the reference trajectory
2370    // to the third decimal). Evals inside the loop lift the restriction —
2371    // their tensor-core numbers match f32 at print precision.
2372    // CMF_BAKE_A_STRICT=0 lifts it: Phase A then rides the tensor-core
2373    // chains like Phase B (tf32-class operands) — the choice of a bake
2374    // that measures its mask on the held-out set anyway and cannot
2375    // afford a CPU-only phase on a 4 B model.
2376    let strict_a = std::env::var("CMF_BAKE_A_STRICT")
2377        .map(|v| v != "0")
2378        .unwrap_or(true);
2379    crate::gpu::bake_precision_strict(strict_a);
2380    for step in 0..hy.steps_a {
2381        let t_step = std::time::Instant::now();
2382        let (batch_ids, batch) = calibration_batch(&calib, step, hy.batch)?;
2383        let mut dmask: Vec<Vec<f64>> = vec![vec![0.0; inter]; vn];
2384        let mut dffn: Vec<Option<(Vec<f64>, Vec<f64>, Vec<f64>)>> = vec![None; nl];
2385        let mut dattn: Vec<Option<AttnGrads>> = (0..nl).map(|_| None).collect();
2386        let pass = Pass {
2387            fm: &fm,
2388            tau: hy.tau,
2389            logits: &logits,
2390            hard: false,
2391            ffn: &ffn,
2392            focus_tokens: &hy.focus_tokens,
2393            focus_follow_tokens: &hy.focus_follow_tokens,
2394            span: hy.answer_span.as_ref(),
2395            soft_fold: hy.soft_fold,
2396            attn_tr: &attn_tr,
2397        };
2398        let _ = pass.chunk_batch(&batch_ids, batch, Some((&mut dmask, &mut dffn, &mut dattn)));
2399        // Fold σ'(m) into the mask grads + add the L1 term.
2400        let l1_per = l1 / (inter as f64 * nl as f64);
2401        for li in 0..vn {
2402            for j in 0..inter {
2403                let s = sigmoid(logits[li][j]) as f64;
2404                let sparse_grad = sparsity_grad(logits[li][j], hy.softplus_l1);
2405                dmask[li][j] = dmask[li][j] * s * (1.0 - s) + l1_per * sparse_grad;
2406            }
2407        }
2408        // One gradient per VISIT, one step per token. A Looped
2409        // Transformer visits each physical layer `loops` times and the
2410        // backward accumulates every visit into the same mask, so an
2411        // unnormalised step is `loops` times the one the recipe was
2412        // tuned with — the mask overshoots, neurons cross tau within the
2413        // first evaluation window, and each of them is then missing from
2414        // both passes. Dividing by the visit count makes a step mean the
2415        // same thing at any loop depth.
2416        // Per-visit rows: each mask logit receives exactly one visit's
2417        // gradient, so the step needs no visit normalisation here — that
2418        // scale now belongs to Phase B alone, where the FFN weights ARE
2419        // shared across visits.
2420        let t_chunk = t_step.elapsed().as_secs_f64();
2421        let mut params: Vec<&mut [f32]> = logits.iter_mut().map(|v| v.as_mut_slice()).collect();
2422        adam_a.step(&mut params, &dmask, 1.0);
2423        acc_chunk += t_chunk;
2424        acc_adam += t_step.elapsed().as_secs_f64() - t_chunk;
2425        if (step + 1) % hy.eval_every == 0 {
2426            l1 += l1_step_eff;
2427            let pass = Pass {
2428                fm: &fm,
2429                tau: hy.tau,
2430                logits: &logits,
2431                hard: true,
2432                ffn: &ffn,
2433                focus_tokens: &hy.focus_tokens,
2434                focus_follow_tokens: &hy.focus_follow_tokens,
2435                span: hy.answer_span.as_ref(),
2436            soft_fold: hy.soft_fold,
2437            attn_tr: &attn_tr,
2438            };
2439            crate::gpu::bake_precision_strict(false);
2440            let hs = held_score_tagged(&pass, &held, held_tags.as_ref());
2441            let hp = hs.ppl;
2442            crate::gpu::bake_precision_strict(strict_a);
2443            // Name the neurons that crossed τ since the last eval. At
2444            // 0.01% pruned = ~24 neurons for a 135 held-PPL, WHICH 24 is
2445            // the whole diagnosis: it decides between "this model has no
2446            // noise neurons" and "a shared mask cannot spare a neuron
2447            // that only one visit of the loop needs".
2448            let cur: Vec<Vec<bool>> = logits
2449                .iter()
2450                .map(|l| l.iter().map(|&x| sigmoid(x) > hy.tau).collect())
2451                .collect();
2452            if let Some(prev) = &prev_alive {
2453                let died: Vec<String> = cur
2454                    .iter()
2455                    .zip(prev)
2456                    .enumerate()
2457                    .flat_map(|(li, (c, p))| {
2458                        c.iter()
2459                            .zip(p.iter())
2460                            .enumerate()
2461                            .filter(|&(_, (&cj, &pj))| pj && !cj)
2462                            .map(move |(j, _)| format!("L{li}:{j}"))
2463                    })
2464                    .collect();
2465                if !died.is_empty() {
2466                    log(&format!(
2467                        "    closed since last eval: {}: {}{}",
2468                        died.len(),
2469                        died.iter().take(32).cloned().collect::<Vec<_>>().join(" "),
2470                        if died.len() > 32 { " …" } else { "" }
2471                    ));
2472                }
2473            }
2474            let alive: usize = cur.iter().map(|l| l.iter().filter(|&&b| b).count()).sum();
2475            prev_alive = Some(cur);
2476            let sp = 1.0 - alive as f64 / (vn * inter) as f64;
2477            // Track highest-sparsity checkpoint.
2478            if sp > max_sp.2 {
2479                max_sp = (hp, Some(logits.clone()), sp);
2480                max_sp_step = step + 1;
2481            }
2482            checkpoints.push(BakeCheckpoint {
2483                step: step + 1,
2484                l1,
2485                ppl: hp,
2486                sparsity: sp,
2487                accuracy: hs.accuracy,
2488                balanced_accuracy: hs.balanced_accuracy,
2489                logits: logits.clone(),
2490            });
2491            if let Some(dir) = &hy.checkpoint_dir {
2492                let doc = serde_json::json!({
2493                    "schema": "cmf-bake-checkpoint-v1",
2494                    "step": step + 1,
2495                    "l1": l1,
2496                    "ppl": hp,
2497                    "sparsity": sp,
2498                    "accuracy": hs.accuracy,
2499                    "micro_accuracy": hs.micro_accuracy,
2500                    "token_accuracy": hs.token_accuracy,
2501                    "per_tag": hs.per_tag,
2502                    "selected_logits": &logits,
2503                });
2504                let path = format!("{dir}/phase-a-step-{}.json", step + 1);
2505                match serde_json::to_vec(&doc) {
2506                    Ok(bytes) => match std::fs::write(&path, bytes) {
2507                        Ok(()) => log(&format!("  [A] checkpoint written: {path}")),
2508                        Err(e) => log(&format!("  [A] checkpoint NOT written ({path}): {e}")),
2509                    },
2510                    Err(e) => log(&format!("  [A] checkpoint NOT serialised: {e}")),
2511                }
2512            }
2513            // Best checkpoint selection: respect target_sparsity and any
2514            // caller-declared natural-distribution quality guards. The
2515            // guards are strict (`>`, not `>=`) so a majority baseline cannot
2516            // sneak through on an exactly tied checkpoint.
2517            let eligible_sparsity = hy.target_sparsity <= 0.0 || sp >= hy.target_sparsity;
2518            let eligible_accuracy = hy
2519                .checkpoint_min_accuracy
2520                .map_or(true, |min| hs.accuracy.is_some_and(|value| value > min));
2521            let eligible_balanced = hy.checkpoint_min_balanced_accuracy.map_or(true, |min| {
2522                hs.balanced_accuracy.is_some_and(|value| value > min)
2523            });
2524            let eligible = eligible_sparsity && eligible_accuracy && eligible_balanced;
2525            if eligible && hy.checkpoint_raw_priority && !hy.focus_tokens.is_empty() {
2526                let acc = hs.accuracy.unwrap_or(f64::NEG_INFINITY);
2527                let bal = hs.balanced_accuracy.unwrap_or(f64::NEG_INFINITY);
2528                if acc > best_accuracy
2529                    || (acc == best_accuracy && bal > best_balanced)
2530                    || (acc == best_accuracy && bal == best_balanced && hp < best.0)
2531                {
2532                    best_balanced = bal;
2533                    best_accuracy = acc;
2534                    best = (hp, Some(logits.clone()), sp);
2535                    best_step = step + 1;
2536                }
2537            } else if eligible && hy.checkpoint_accuracy && !hy.focus_tokens.is_empty() {
2538                let acc = hs.accuracy.unwrap_or(f64::NEG_INFINITY);
2539                let bal = hs.balanced_accuracy.unwrap_or(f64::NEG_INFINITY);
2540                if bal > best_balanced
2541                    || (bal == best_balanced && acc > best_accuracy)
2542                    || (bal == best_balanced && acc == best_accuracy && hp < best.0)
2543                {
2544                    best_balanced = bal;
2545                    best_accuracy = acc;
2546                    best = (hp, Some(logits.clone()), sp);
2547                    best_step = step + 1;
2548                }
2549            } else if eligible && hy.checkpoint_accuracy && hy.answer_span.is_some() {
2550                // Answer-span mode: the held-out accuracy of the hard mask
2551                // decides — whole verdicts when the span locates values,
2552                // else span tokens (the experiments' accuracy gate); PPL
2553                // breaks ties.
2554                let acc = hs.accuracy.unwrap_or(f64::NEG_INFINITY);
2555                if acc > best_accuracy || (acc == best_accuracy && hp < best.0) {
2556                    best_accuracy = acc;
2557                    best = (hp, Some(logits.clone()), sp);
2558                    best_step = step + 1;
2559                }
2560            } else if eligible && hp < best.0 {
2561                best = (hp, Some(logits.clone()), sp);
2562                best_step = step + 1;
2563            }
2564            log(&format!(
2565                "  [A] step {}: L1={l1:.3} pruned={:.2}% hard-PPL={hp:.3}{} (bottom {}@{:.2}%) [fwd+bwd {:.1}s, adam {:.2}s per step]",
2566                step + 1,
2567                sp * 100.0,
2568                score_suffix(&hs),
2569                if best.0 == f64::MAX {
2570                    "—".to_string()
2571                } else {
2572                    format!("{:.3}", best.0)
2573                },
2574                best.2 * 100.0,
2575                acc_chunk / (step + 1) as f64,
2576                acc_adam / (step + 1) as f64
2577            ));
2578            if let Some(line) = tag_line(&hs) {
2579                log(&format!("    per tag: {line}"));
2580            }
2581        }
2582    }
2583    // If target_sparsity was set but no checkpoint qualified, fall back
2584    // to the highest-sparsity checkpoint.
2585    // Phase A is over — phase B and every eval after run on the fast arms.
2586    crate::gpu::bake_precision_strict(false);
2587    if (hy.checkpoint_min_accuracy.is_some() || hy.checkpoint_min_balanced_accuracy.is_some())
2588        && best.1.is_none()
2589    {
2590        return Err(
2591            "skill bake: no Phase-A checkpoint met the configured focused accuracy guards".into(),
2592        );
2593    }
2594    if hy.target_sparsity > 0.0 && best.1.is_none() {
2595        log(&format!(
2596            "[A] target sparsity {:.0}% not reached; using max-sparsity checkpoint ({:.0}%)",
2597            hy.target_sparsity * 100.0,
2598            max_sp.2 * 100.0
2599        ));
2600        best = max_sp;
2601        best_step = max_sp_step;
2602    }
2603    // Phase totals, printed unconditionally — a 5-step measurement run
2604    // must report even though no eval fired.
2605    {
2606        use crate::fcd::prof;
2607        let (a, f, bw, g, gc) = (
2608            prof::take(&prof::ATTN_FWD),
2609            prof::take(&prof::FFN_FWD),
2610            prof::take(&prof::BWD),
2611            prof::take(&prof::GEMM),
2612            prof::GEMM_CALLS.swap(0, std::sync::atomic::Ordering::Relaxed),
2613        );
2614        log(&format!(
2615            "[prof] phase A over {} step(s): attn-fwd {a:.1}s | ffn-fwd {f:.1}s | bwd {bw:.1}s |              gemm total {g:.1}s in {gc} calls ({:.1} ms/call)",
2616            hy.steps_a,
2617            if gc > 0 { g * 1000.0 / gc as f64 } else { 0.0 }
2618        ));
2619        log(&format!(
2620            "[prof] inside: attn-chain {:.1}s | gdn {:.1}s | ffn-pre {:.1}s | ffn-chain {:.1}s | ffn-act(split+act) {:.1}s | ffn-host {:.1}s | ffn-post {:.1}s | chain-w {:.1}s gpu {:.1}s copy {:.1}s",
2621            prof::take(&prof::ATTN_CHAIN),
2622            prof::take(&prof::GDN),
2623            prof::take(&prof::FFN_PRE),
2624            prof::take(&prof::FFN_CHAIN),
2625            prof::take(&prof::FFN_ACT),
2626            prof::take(&prof::FFN_HOST),
2627            prof::take(&prof::FFN_POST),
2628            chain_prof(0),
2629            chain_prof(1),
2630            chain_prof(2),
2631        ));
2632        log(&format!("[prof] sections: {}", prof::named_report()));
2633        log(&format!("[prof] gemm shapes:\n{}", prof::shape_report(6)));
2634    }
2635    let final_logits = logits.clone();
2636    if let Some(b) = best.1.take() {
2637        logits = b;
2638    }
2639    let pass = Pass {
2640        fm: &fm,
2641        tau: hy.tau,
2642        logits: &logits,
2643        hard: true,
2644        ffn: &ffn,
2645        focus_tokens: &hy.focus_tokens,
2646        focus_follow_tokens: &hy.focus_follow_tokens,
2647        span: hy.answer_span.as_ref(),
2648            soft_fold: hy.soft_fold,
2649            attn_tr: &attn_tr,
2650    };
2651    // With no mask-training steps the hard mask is still exactly all-open,
2652    // so rescoring the same validation batch is pure duplicate work.  This
2653    // matters for focused 512-token records where one gate can take minutes
2654    // on a laptop, and keeps short FCD sweeps practical without changing a
2655    // single number.
2656    let masked_score = if hy.steps_a == 0 && hy.mask_logits.is_none() {
2657        backbone_score.clone()
2658    } else {
2659        held_score_tagged(&pass, &held, held_tags.as_ref())
2660    };
2661    let masked = masked_score.ppl;
2662    log(&format!(
2663        "[A] {:.0}s: masked-PPL {masked:.3}{}",
2664        t0.elapsed().as_secs_f64(),
2665        score_suffix(&masked_score)
2666    ));
2667
2668    // ── Phase B: FCD of the last N layers' FFN (hard mask active) ──
2669    for &li in &fcd {
2670        let p = format!("model.layers.{li}.");
2671        ffn[li] = Some((
2672            crate::fcd::deq_pub(&fm.src, &format!("{p}mlp.gate_proj.weight"))
2673                .map_err(|e| format!("phase-B gate: {e}"))?,
2674            crate::fcd::deq_pub(&fm.src, &format!("{p}mlp.up_proj.weight"))
2675                .map_err(|e| format!("phase-B up: {e}"))?,
2676            crate::fcd::deq_pub(&fm.src, &format!("{p}mlp.down_proj.weight"))
2677                .map_err(|e| format!("phase-B down: {e}"))?,
2678        ));
2679    }
2680    if hy.fcd_attn {
2681        for &li in &fcd {
2682            if fm.attn_geometry(li).is_none() {
2683                return Err(format!("--fcd-attn: layer {li} is not a softmax-attention layer"));
2684            }
2685            let mats = fm.mats(li)?;
2686            attn_tr[li] = Some(AttnMasters {
2687                wqkv: mats.wqkv.clone(),
2688                wo: mats.wo.clone(),
2689                gproj: fm.head_gate_weights(li).map(<[f32]>::to_vec),
2690                iln: fm.layers[li].iln.clone(),
2691                pln: fm.layers[li].pln.clone(),
2692            });
2693        }
2694        log(&format!("[B] full-layer FCD: attention + norms of {} layer(s) train too", fcd.len()));
2695    }
2696    let sizes: Vec<usize> = fcd
2697        .iter()
2698        .flat_map(|&li| {
2699            let (g, u, d) = ffn[li].as_ref().expect("phase-B masters");
2700            let mut v = vec![g.len(), u.len(), d.len()];
2701            if let Some(m) = &attn_tr[li] {
2702                v.extend([m.wqkv.len(), m.wo.len(), m.gproj.as_ref().map_or(0, Vec::len), m.iln.len(), m.pln.len()]);
2703            }
2704            v
2705        })
2706        .filter(|&n| n > 0)
2707        .collect();
2708    let mut adam_b = Adam::new(&sizes, hy.lr_b);
2709    // The mask-only model is a real checkpoint too. If every FCD eval is
2710    // worse, restore `None` overlays rather than accidentally writing the
2711    // final (rejected) training step while reporting the mask-only PPL.
2712    let mut best_b: (
2713        HeldScore,
2714        Option<Vec<Option<(Vec<f32>, Vec<f32>, Vec<f32>)>>>,
2715    ) = (masked_score.clone(), Some(vec![None; nl]));
2716    let mut best_attn: Vec<Option<AttnMasters>> = attn_tr.clone();
2717    let cached_phase_b =
2718        hy.steps_b > 0 && fcd.len() == 1 && loops == 1 && !hy.focus_tokens.is_empty();
2719    if cached_phase_b {
2720        let last = fcd[0];
2721        let pass = Pass {
2722            fm: &fm,
2723            tau: hy.tau,
2724            logits: &logits,
2725            hard: true,
2726            ffn: &ffn,
2727            focus_tokens: &hy.focus_tokens,
2728            focus_follow_tokens: &hy.focus_follow_tokens,
2729            span: hy.answer_span.as_ref(),
2730            soft_fold: hy.soft_fold,
2731            attn_tr: &attn_tr,
2732        };
2733        log(&format!(
2734            "[B-cache] extracting native CMF boundaries: {} train + {} held records",
2735            calib.len(),
2736            held.len()
2737        ));
2738        let train_cache = build_focused_fcd_cache(&pass, &calib, 32)?;
2739        let held_cache = build_focused_fcd_cache(&pass, &held, 32)?;
2740        if train_cache.len() < 12 || held_cache.len() == 0 {
2741            return Err(format!(
2742                "focused final-FFN cache is too small: {} train, {} held answers",
2743                train_cache.len(),
2744                held_cache.len()
2745            ));
2746        }
2747        let gate = pass.gates(last);
2748        let held_indices: Vec<usize> = (0..held_cache.len()).collect();
2749        let (initial_cached, _) = {
2750            let (g, u, d) = ffn[last].as_ref().expect("cached FCD master");
2751            cached_fcd_run(
2752                &fm,
2753                &held_cache,
2754                &held_indices,
2755                (g, u, d),
2756                &gate,
2757                &hy.focus_tokens,
2758                false,
2759            )
2760        };
2761        log(&format!(
2762            "[B-cache] ready: {} train / {} held | parity PPL {:.3} vs full {:.3}{}",
2763            train_cache.len(),
2764            held_cache.len(),
2765            initial_cached.ppl,
2766            masked_score.ppl,
2767            initial_cached
2768                .accuracy
2769                .map(|value| format!(" | acc {:.2}%", value * 100.0))
2770                .unwrap_or_default()
2771        ));
2772        if (initial_cached.ppl - masked_score.ppl).abs() > 5e-3
2773            || initial_cached.accuracy != masked_score.accuracy
2774        {
2775            return Err(format!(
2776                "focused final-FFN cache parity failed: PPL {:.6} vs {:.6}, accuracy {:?} vs {:?}",
2777                initial_cached.ppl,
2778                masked_score.ppl,
2779                initial_cached.accuracy,
2780                masked_score.accuracy
2781            ));
2782        }
2783        for step in 0..hy.steps_b {
2784            let count = hy.fcd_batch.min(train_cache.len());
2785            let indices: Vec<usize> = (0..count)
2786                .map(|offset| (step * count + offset) % train_cache.len())
2787                .collect();
2788            let (_, gradients) = {
2789                let (g, u, d) = ffn[last].as_ref().expect("cached FCD master");
2790                cached_fcd_run(
2791                    &fm,
2792                    &train_cache,
2793                    &indices,
2794                    (g, u, d),
2795                    &gate,
2796                    &hy.focus_tokens,
2797                    true,
2798                )
2799            };
2800            let (dg, du, dd) = gradients.expect("cached FCD requested gradients");
2801            let lr_scale =
2802                0.5 * (1.0 + (std::f64::consts::PI * step as f64 / hy.steps_b as f64).cos());
2803            let (g, u, d) = ffn[last].as_mut().expect("cached FCD master");
2804            let mut params = vec![g.as_mut_slice(), u.as_mut_slice(), d.as_mut_slice()];
2805            let grads = vec![dg, du, dd];
2806            adam_b.step(&mut params, &grads, lr_scale);
2807            if (step + 1) % hy.eval_every == 0 {
2808                let cur = {
2809                    let (g, u, d) = ffn[last].as_ref().expect("cached FCD master");
2810                    cached_fcd_run(
2811                        &fm,
2812                        &held_cache,
2813                        &held_indices,
2814                        (g, u, d),
2815                        &gate,
2816                        &hy.focus_tokens,
2817                        false,
2818                    )
2819                    .0
2820                };
2821                let cur_bal = cur.balanced_accuracy.unwrap_or(f64::NEG_INFINITY);
2822                let best_bal = best_b.0.balanced_accuracy.unwrap_or(f64::NEG_INFINITY);
2823                let cur_acc = cur.accuracy.unwrap_or(f64::NEG_INFINITY);
2824                let best_acc = best_b.0.accuracy.unwrap_or(f64::NEG_INFINITY);
2825                let better = if hy.checkpoint_accuracy {
2826                    cur_bal > best_bal
2827                        || (cur_bal == best_bal && cur_acc > best_acc)
2828                        || (cur_bal == best_bal && cur_acc == best_acc && cur.ppl < best_b.0.ppl)
2829                } else {
2830                    cur.ppl < best_b.0.ppl
2831                };
2832                if better {
2833                    best_b = (cur.clone(), Some(ffn.clone()));
2834                    best_attn = attn_tr.clone();
2835                }
2836                log(&format!(
2837                    "  [B-cache] step {}: held-PPL {:.3} acc={:.2}% bal={:.2}% (best {:.3})",
2838                    step + 1,
2839                    cur.ppl,
2840                    cur_acc * 100.0,
2841                    cur_bal * 100.0,
2842                    best_b.0.ppl
2843                ));
2844            }
2845        }
2846    } else {
2847        for step in 0..hy.steps_b {
2848            let (batch_ids, batch) = calibration_batch(&calib, step, hy.batch)?;
2849            let mut dmask: Vec<Vec<f64>> = vec![vec![0.0; inter]; vn];
2850            let mut dffn: Vec<Option<(Vec<f64>, Vec<f64>, Vec<f64>)>> = (0..nl)
2851                .map(|li| {
2852                    ffn[li].as_ref().map(|(g, u, d)| {
2853                        (vec![0.0; g.len()], vec![0.0; u.len()], vec![0.0; d.len()])
2854                    })
2855                })
2856                .collect();
2857            let mut dattn: Vec<Option<AttnGrads>> =
2858                attn_tr.iter().map(|m| m.as_ref().map(AttnGrads::zeros_like)).collect();
2859            let pass = Pass {
2860                fm: &fm,
2861                tau: hy.tau,
2862                logits: &logits,
2863                hard: true,
2864                ffn: &ffn,
2865                focus_tokens: &hy.focus_tokens,
2866                focus_follow_tokens: &hy.focus_follow_tokens,
2867                span: hy.answer_span.as_ref(),
2868            soft_fold: hy.soft_fold,
2869            attn_tr: &attn_tr,
2870            };
2871            let _ = pass.chunk_batch(&batch_ids, batch, Some((&mut dmask, &mut dffn, &mut dattn)));
2872            // Cosine LR.
2873            let lr_scale =
2874                0.5 * (1.0 + (std::f64::consts::PI * step as f64 / hy.steps_b as f64).cos());
2875            let first_fcd = fcd[0];
2876            let mut params: Vec<&mut [f32]> = Vec::new();
2877            let mut grads: Vec<Vec<f64>> = Vec::new();
2878            let attn_tr_slots = &mut attn_tr[first_fcd..];
2879            for (off, (slot, aslot)) in ffn[first_fcd..]
2880                .iter_mut()
2881                .zip(attn_tr_slots.iter_mut())
2882                .enumerate()
2883            {
2884                let li = first_fcd + off;
2885                let Some((g, u, d)) = slot.as_mut() else {
2886                    continue;
2887                };
2888                let (dg, du, dd) = dffn[li].take().unwrap();
2889                params.push(g.as_mut_slice());
2890                grads.push(dg);
2891                params.push(u.as_mut_slice());
2892                grads.push(du);
2893                params.push(d.as_mut_slice());
2894                grads.push(dd);
2895                if let (Some(m), Some(ag)) = (aslot.as_mut(), dattn[li].take()) {
2896                    params.push(m.wqkv.as_mut_slice());
2897                    grads.push(ag.wqkv);
2898                    params.push(m.wo.as_mut_slice());
2899                    grads.push(ag.wo);
2900                    if let (Some(gp), Some(dgp)) = (m.gproj.as_mut(), ag.gproj) {
2901                        params.push(gp.as_mut_slice());
2902                        grads.push(dgp);
2903                    }
2904                    params.push(m.iln.as_mut_slice());
2905                    grads.push(ag.iln);
2906                    params.push(m.pln.as_mut_slice());
2907                    grads.push(ag.pln);
2908                }
2909            }
2910            // Same visit normalisation as Phase A: dffn accumulates every
2911            // visit of a physical layer, and an FFN update perturbs BOTH
2912            // passes of the loop, so per-step damage is `loops` times what
2913            // lr_b was tuned for on ordinary stacks.
2914            adam_b.step(&mut params, &grads, lr_scale * mask_step_scale(loops));
2915            if (step + 1) % hy.eval_every == 0 {
2916                let pass = Pass {
2917                    fm: &fm,
2918                    tau: hy.tau,
2919                    logits: &logits,
2920                    hard: true,
2921                    ffn: &ffn,
2922                    focus_tokens: &hy.focus_tokens,
2923                    focus_follow_tokens: &hy.focus_follow_tokens,
2924                    span: hy.answer_span.as_ref(),
2925            soft_fold: hy.soft_fold,
2926            attn_tr: &attn_tr,
2927                };
2928                let cur = held_score_tagged(&pass, &held, held_tags.as_ref());
2929                let better = if hy.checkpoint_accuracy && hy.answer_span.is_some() {
2930                    let cur_acc = cur.accuracy.unwrap_or(f64::NEG_INFINITY);
2931                    let best_acc = best_b.0.accuracy.unwrap_or(f64::NEG_INFINITY);
2932                    cur_acc > best_acc || (cur_acc == best_acc && cur.ppl < best_b.0.ppl)
2933                } else if hy.checkpoint_accuracy && !hy.focus_tokens.is_empty() {
2934                    let cur_bal = cur.balanced_accuracy.unwrap_or(f64::NEG_INFINITY);
2935                    let best_bal = best_b.0.balanced_accuracy.unwrap_or(f64::NEG_INFINITY);
2936                    let cur_acc = cur.accuracy.unwrap_or(f64::NEG_INFINITY);
2937                    let best_acc = best_b.0.accuracy.unwrap_or(f64::NEG_INFINITY);
2938                    cur_bal > best_bal
2939                        || (cur_bal == best_bal && cur_acc > best_acc)
2940                        || (cur_bal == best_bal && cur_acc == best_acc && cur.ppl < best_b.0.ppl)
2941                } else {
2942                    cur.ppl < best_b.0.ppl
2943                };
2944                // CMF_BAKE_B_TAKE_LAST=1: the correction the recipe prescribes
2945                // (Patent 2 §4.5: one light FCD step) ships as trained — a
2946                // held set of a few verdicts per family cannot veto it on noise;
2947                // its score is still logged.
2948                let take_last = std::env::var("CMF_BAKE_B_TAKE_LAST").is_ok_and(|v| v == "1");
2949                if better || (take_last && step + 1 == hy.steps_b) {
2950                    best_b = (cur.clone(), Some(ffn.clone()));
2951                    best_attn = attn_tr.clone();
2952                }
2953                log(&format!(
2954                    "  [B] step {}: held-PPL {:.3}{} (best {:.3})",
2955                    step + 1,
2956                    cur.ppl,
2957                    score_suffix(&cur),
2958                    best_b.0.ppl
2959                ));
2960                if let Some(line) = tag_line(&cur) {
2961                    log(&format!("    per tag: {line}"));
2962                }
2963            }
2964        }
2965    }
2966    ffn = best_b.1.take().expect("phase-B always has a checkpoint");
2967    attn_tr = best_attn;
2968    let overlaid_score = best_b.0;
2969    let overlaid = overlaid_score.ppl;
2970
2971    // ── Export artifacts ──
2972    // Per-visit keep flags are the mask that ships; the PHYSICAL keep is
2973    // their union, because a weight row can only be removed from disk if
2974    // no visit needs it.
2975    let keep_visits = keep_masks(&logits, hy.tau, hy.align, hy.uniform_inter);
2976    let keep: Vec<Vec<bool>> = (0..nl)
2977        .map(|li| {
2978            (0..inter)
2979                .map(|j| (0..loops).any(|v| keep_visits[v * nl + li][j]))
2980                .collect()
2981        })
2982        .collect();
2983    if hy.align > 1 || hy.uniform_inter {
2984        let raw: usize = logits
2985            .iter()
2986            .map(|l| l.iter().filter(|&&x| sigmoid(x) > hy.tau).count())
2987            .sum();
2988        // Compare like with like: raw σ-counts are over the VIRTUAL
2989        // rows, so the padded count must be too — the union rows are
2990        // fewer and the subtraction would underflow.
2991        let padded: usize = keep_visits
2992            .iter()
2993            .map(|a| a.iter().filter(|&&x| x).count())
2994            .sum::<usize>()
2995            .saturating_sub(raw);
2996        log(&format!(
2997            "align: +{padded} neurons resurrected (align {}, uniform {})",
2998            hy.align, hy.uniform_inter
2999        ));
3000    }
3001    let mut down_out = Vec::with_capacity(nl);
3002    let mut gate_up = Vec::with_capacity(nl);
3003    let mut kept_per_layer = Vec::with_capacity(nl);
3004    for li in 0..nl {
3005        let alive = &keep[li];
3006        kept_per_layer.push(alive.iter().filter(|&&a| a).count());
3007        let mut down = match &ffn[li] {
3008            Some((_, _, d)) => d.clone(),
3009            None => fm.mats(li).expect("layer mats").down.clone(),
3010        };
3011        let hsz = fm.hidden;
3012        for r in 0..hsz {
3013            for (c, &a) in alive.iter().enumerate() {
3014                if !a {
3015                    down[r * inter + c] = 0.0;
3016                }
3017            }
3018        }
3019        gate_up.push(ffn[li].as_ref().map(|(g, u, _)| (g.clone(), u.clone())));
3020        down_out.push(down);
3021    }
3022    let total: usize = keep_visits
3023        .iter()
3024        .map(|a| a.iter().filter(|&&x| x).count())
3025        .sum();
3026    let report = BakeReport {
3027        backbone,
3028        masked,
3029        overlaid,
3030        pruned_ratio: 1.0 - total as f64 / (vn * inter) as f64,
3031        kept_per_layer,
3032        backbone_accuracy: backbone_score.accuracy,
3033        masked_accuracy: masked_score.accuracy,
3034        overlaid_accuracy: overlaid_score.accuracy,
3035        backbone_balanced_accuracy: backbone_score.balanced_accuracy,
3036        masked_balanced_accuracy: masked_score.balanced_accuracy,
3037        overlaid_balanced_accuracy: overlaid_score.balanced_accuracy,
3038        selected_step: best_step,
3039        sec: t0.elapsed().as_secs_f64(),
3040    };
3041    let arts = BakeArtifacts {
3042        keep,
3043        keep_visits,
3044        down: down_out,
3045        gate_up,
3046        attn: attn_tr,
3047        fcd_layers: fcd,
3048        logits: logits.clone(),
3049        final_logits,
3050        checkpoints,
3051    };
3052    Ok((report, arts))
3053}
3054
3055/// Hard-threshold keep masks from the trained logits, then resurrect
3056/// the highest-logit pruned neurons until each layer's kept count is a
3057/// multiple of `align` (rounding UP — the resurrected neurons are the
3058/// ones the mask ranked closest to the threshold, so this only moves
3059/// toward the full backbone). `uniform` additionally raises every layer
3060/// to the max layer's aligned count. A layer with 0 live neurons gets
3061/// `align.max(1)` — the defrag writer rejects empty layers.
3062fn keep_masks(logits: &[Vec<f32>], tau: f32, align: usize, uniform: bool) -> Vec<Vec<bool>> {
3063    let inter = logits[0].len();
3064    let round = |n: usize| -> usize {
3065        let n = n.max(1);
3066        if align <= 1 {
3067            n.min(inter)
3068        } else {
3069            (n.div_ceil(align) * align).min(inter)
3070        }
3071    };
3072    let mut want: Vec<usize> = logits
3073        .iter()
3074        .map(|l| round(l.iter().filter(|&&x| sigmoid(x) > tau).count()))
3075        .collect();
3076    if uniform {
3077        let k = want.iter().copied().max().unwrap_or(inter);
3078        want = vec![k; logits.len()];
3079    }
3080    logits
3081        .iter()
3082        .zip(&want)
3083        .map(|(l, &k)| {
3084            let mut idx: Vec<usize> = (0..inter).collect();
3085            idx.sort_unstable_by(|&a, &b| l[b].total_cmp(&l[a]));
3086            let mut alive = vec![false; inter];
3087            for &i in idx.iter().take(k) {
3088                alive[i] = true;
3089            }
3090            alive
3091        })
3092        .collect()
3093}
3094
3095#[cfg(test)]
3096mod tests {
3097    use super::*;
3098
3099    fn kept(masks: &[Vec<bool>]) -> Vec<usize> {
3100        masks
3101            .iter()
3102            .map(|m| m.iter().filter(|&&a| a).count())
3103            .collect()
3104    }
3105
3106    #[test]
3107    fn terminal_focus_ignores_label_names_inside_the_prompt() {
3108        // DOWN and UP occur in the instruction, but only the final UP is an
3109        // assistant answer because it is immediately followed by im_end.
3110        let down = 10;
3111        let up = 11;
3112        let im_end = 99;
3113        let ids = [1, down, 2, up, 3, up, im_end, 4];
3114        let focus = [down, up];
3115        let follow = [im_end];
3116        assert!(!is_scored_target(&ids, 1, ids.len(), &focus, &follow));
3117        assert!(!is_scored_target(&ids, 3, ids.len(), &focus, &follow));
3118        assert!(is_scored_target(&ids, 5, ids.len(), &focus, &follow));
3119    }
3120
3121    #[test]
3122    fn configurable_mask_init_preserves_effective_gate_across_loops() {
3123        for effective_logit in [2.0, 4.0] {
3124            let target = sigmoid(effective_logit);
3125            for loops in [1usize, 2, 4] {
3126                let per_visit = sigmoid(mask_init_logit_for(loops, effective_logit));
3127                assert!((per_visit.powi(loops as i32) - target).abs() < 2e-6);
3128            }
3129        }
3130    }
3131
3132    #[test]
3133    fn softplus_penalty_keeps_a_gradient_near_an_open_gate() {
3134        let gate_penalty = sparsity_grad(4.0, false);
3135        let softplus_penalty = sparsity_grad(4.0, true);
3136        assert!(softplus_penalty > gate_penalty * 50.0);
3137        assert!((softplus_penalty - sigmoid(4.0) as f64).abs() < 1e-7);
3138    }
3139
3140    #[test]
3141    fn answer_values_group_each_top_level_value() {
3142        // {"q1": "option_24", "q2": [ "a" ], "q3": 3}<end>, split the way a
3143        // byte-level BPE might: quotes merged with keys and labels.
3144        let pieces = [
3145            "{\"", "q1", "\":", " \"", "option", "_", "24", "\",", " \"q2", "\":", " [", " \"a\"", " ]", ",", " \"q3\":",
3146            " 3", "}", "<end>",
3147        ];
3148        let text = TokenText(Arc::new(pieces.iter().map(|p| p.to_string()).collect()));
3149        let ids: Vec<u32> = (0..pieces.len() as u32).collect();
3150        let groups = answer_values(&ids, 0, ids.len() - 1, &text);
3151        assert_eq!(groups, vec![vec![3, 4, 5, 6, 7], vec![10, 11, 12], vec![15]]);
3152    }
3153
3154    #[test]
3155    fn answer_values_keep_escaped_quotes_inside_the_value() {
3156        let pieces = ["{\"q\": \"a", "\\\"", "b\"}", "<end>"];
3157        let text = TokenText(Arc::new(pieces.iter().map(|p| p.to_string()).collect()));
3158        let ids: Vec<u32> = (0..pieces.len() as u32).collect();
3159        assert_eq!(answer_values(&ids, 0, 3, &text), vec![vec![0, 1, 2]]);
3160    }
3161
3162    #[test]
3163    fn balanced_accuracy_exposes_majority_class_collapse() {
3164        let stats = FocusStats {
3165            total: 100,
3166            correct: 90,
3167            class_total: vec![90, 10],
3168            class_correct: vec![90, 0],
3169            ..FocusStats::default()
3170        };
3171        assert_eq!(stats.accuracy(), Some(0.9));
3172        assert_eq!(stats.balanced_accuracy(), Some(0.5));
3173    }
3174
3175    #[test]
3176    fn grouped_focus_stats_merge_is_additive() {
3177        let mut all = FocusStats {
3178            total: 3,
3179            correct: 2,
3180            class_total: vec![2, 1],
3181            class_correct: vec![1, 1],
3182            questions: 2,
3183            questions_correct: 1,
3184            seq: Vec::new(),
3185        };
3186        let second = FocusStats {
3187            total: 4,
3188            correct: 3,
3189            class_total: vec![1, 3],
3190            class_correct: vec![1, 2],
3191            questions: 3,
3192            questions_correct: 3,
3193            seq: Vec::new(),
3194        };
3195        all.merge(&second);
3196        assert_eq!(all.question_accuracy(), Some(4.0 / 5.0));
3197        assert_eq!(all.accuracies(), (Some(4.0 / 5.0), Some(5.0 / 7.0)));
3198        assert_eq!(all.total, 7);
3199        assert_eq!(all.correct, 5);
3200        assert_eq!(all.class_total, vec![3, 4]);
3201        assert_eq!(all.class_correct, vec![2, 3]);
3202        assert_eq!(all.accuracy(), Some(5.0 / 7.0));
3203        assert_eq!(all.balanced_accuracy(), Some((2.0 / 3.0 + 3.0 / 4.0) / 2.0));
3204    }
3205
3206    #[test]
3207    fn calibration_batches_keep_records_independent_and_wrap_deterministically() {
3208        let records = vec![vec![1, 2], vec![3, 4], vec![5, 6]];
3209        assert_eq!(
3210            calibration_batch(&records, 0, 2).unwrap(),
3211            (vec![1, 2, 3, 4], 2)
3212        );
3213        // A run of equal lengths is cut into blocks of at most `batch`;
3214        // the tail block is smaller, and the schedule wraps.
3215        assert_eq!(calibration_batch(&records, 1, 2).unwrap(), (vec![5, 6], 1));
3216        assert_eq!(
3217            calibration_batch(&records, 2, 2).unwrap(),
3218            (vec![1, 2, 3, 4], 2)
3219        );
3220        // Mixed lengths never share a block (length buckets).
3221        assert_eq!(calibration_batch(&[vec![1, 2], vec![3]], 0, 2).unwrap(), (vec![1, 2], 1));
3222        assert_eq!(calibration_batch(&[vec![1, 2], vec![3]], 1, 2).unwrap(), (vec![3], 1));
3223    }
3224
3225    /// align=32 rounds each layer UP by resurrecting the largest
3226    /// pruned logits; the originally-alive set stays alive.
3227    #[test]
3228    fn keep_masks_aligns_up_and_preserves_alive() {
3229        let inter = 96;
3230        // Layer 0: 40 alive (logits > 0 → σ > 0.5), the rest ramp
3231        // below threshold so resurrection order is deterministic.
3232        let l0: Vec<f32> = (0..inter)
3233            .map(|i| if i < 40 { 1.0 } else { -1.0 - i as f32 * 0.01 })
3234            .collect();
3235        // Layer 1: 64 alive — already aligned, must stay exactly 64.
3236        let l1: Vec<f32> = (0..inter)
3237            .map(|i| if i < 64 { 2.0 } else { -3.0 })
3238            .collect();
3239        let masks = keep_masks(&[l0.clone(), l1], 0.5, 32, false);
3240        assert_eq!(kept(&masks), vec![64, 64]);
3241        // The 40 originally-alive stay; resurrected are the top pruned
3242        // logits (indices 40..64 — the least-negative of the ramp).
3243        for i in 0..64 {
3244            assert!(masks[0][i], "neuron {i} should be kept");
3245        }
3246        for i in 64..inter {
3247            assert!(!masks[0][i], "neuron {i} should stay pruned");
3248        }
3249    }
3250
3251    /// uniform=true raises every layer to the max aligned count.
3252    #[test]
3253    fn keep_masks_uniform_takes_max() {
3254        let inter = 96;
3255        let l0: Vec<f32> = (0..inter)
3256            .map(|i| if i < 10 { 1.0 } else { -2.0 })
3257            .collect();
3258        let l1: Vec<f32> = (0..inter)
3259            .map(|i| if i < 70 { 1.0 } else { -2.0 })
3260            .collect();
3261        let masks = keep_masks(&[l0, l1], 0.5, 32, true);
3262        assert_eq!(kept(&masks), vec![96, 96]);
3263    }
3264
3265    /// align capped at inter; align=1 (off) keeps the raw threshold
3266    /// count; an all-pruned layer still keeps at least one neuron.
3267    #[test]
3268    fn keep_masks_edges() {
3269        let inter = 48;
3270        let l: Vec<f32> = (0..inter)
3271            .map(|i| if i < 47 { 1.0 } else { -2.0 })
3272            .collect();
3273        let masks = keep_masks(&[l.clone()], 0.5, 32, false);
3274        assert_eq!(kept(&masks), vec![48]); // 47 → 64 capped to 48
3275        let masks = keep_masks(&[l], 0.5, 1, false);
3276        assert_eq!(kept(&masks), vec![47]);
3277        let dead: Vec<f32> = vec![-5.0; inter];
3278        let masks = keep_masks(&[dead], 0.5, 32, false);
3279        assert_eq!(kept(&masks), vec![32]); // max(1) → rounded to 32
3280    }
3281}
3282
3283#[cfg(test)]
3284mod answer_span_tests {
3285    use super::*;
3286
3287    #[test]
3288    fn answer_targets_follow_the_last_prompt_to_the_terminator() {
3289        let sp = AnswerSpan {
3290            start: vec![7, 8],
3291            end: 1,
3292            values: None,
3293        };
3294        // prompt … [7 8] answer 20 21 [1] pad 1 1
3295        let ids = [5, 7, 8, 9, 7, 8, 20, 21, 1, 1, 1];
3296        assert_eq!(answer_targets(&ids, &sp), Some((6, 8)));
3297        // No terminator: the span runs to the end of the record.
3298        let ids = [5, 7, 8, 20, 21];
3299        assert_eq!(answer_targets(&ids, &sp), Some((3, 4)));
3300        // No prompt, or a prompt with nothing after it: unscored.
3301        assert_eq!(answer_targets(&[5, 6, 1], &sp), None);
3302        assert_eq!(answer_targets(&[5, 7, 8], &sp), None);
3303    }
3304
3305    #[test]
3306    fn scored_targets_cover_every_position_without_focus_or_span() {
3307        let ids = [1u32, 2, 3, 4, 5, 6];
3308        assert_eq!(scored_targets(&ids, 0, 3, &[], &[], None), vec![1, 2]);
3309        assert_eq!(scored_targets(&ids, 3, 3, &[], &[], None), vec![4, 5]);
3310        let sp = AnswerSpan {
3311            start: vec![2],
3312            end: 6,
3313            values: None,
3314        };
3315        assert_eq!(scored_targets(&ids, 0, 6, &[], &[], Some(&sp)), vec![2, 3, 4, 5]);
3316    }
3317}