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