Skip to main content

cortiq_engine/
sam3.rs

1//! SAM3 image inference on CPU (f32) over the sections written by
2//! `cortiq-cli sam3-pack` (`trunk.*`, `fpn.*`, `text.*`, `det.*`).
3//!
4//! Semantics follow transformers 5.20.2 `Sam3Model` (fixtures: run
5//! `tools/sam3_ref.py` on the pod): CLIP-L text tower + resizer, ViT trunk
6//! with windowed axial RoPE (per-layer baked freqs_cis), SAM2-style FPN
7//! neck, DETR encoder/decoder (presence token + 200 queries + log
8//! box-RPB, POST-norm decoder layers) and the mask decoder. Geometry
9//! prompts are not part of the image path. Batch size 1; `pixels` is a
10//! preprocessed [3,1008,1008] tensor.
11
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::Arc;
14
15use anyhow::{anyhow, Context, Result};
16use cortiq_core::quant::dequant_tensor;
17use cortiq_core::{CmfModel, TensorDtype};
18
19use crate::inference::gelu_erf;
20use crate::pool::Pool;
21use crate::qtensor::QTensor;
22
23/// Additive mask for "key is padded": saturates softmax to 0.
24const NEG: f32 = -1e30;
25
26/// The vendor image preprocess, exactly as `cfg.processor` spells it:
27/// resize to 1008×1008 with `resample: 2` (bilinear), rescale 1/255,
28/// normalize with mean/std 0.5 per channel, emit CHW f32. This produces
29/// the parity fixtures' `pixels.f32` from the source image.
30pub fn preprocess(frame: &crate::media::RgbFrame) -> Vec<f32> {
31    use image::imageops::{self, FilterType};
32    let img = image::RgbImage::from_raw(
33        frame.width as u32,
34        frame.height as u32,
35        frame.data.clone(),
36    )
37    .expect("RgbFrame buffer matches its own dimensions");
38    let rs = imageops::resize(&img, PIX as u32, PIX as u32, FilterType::Triangle);
39    let raw = rs.into_raw();
40    let mut out = vec![0f32; 3 * PIX * PIX];
41    for i in 0..PIX * PIX {
42        for c in 0..3 {
43            out[c * PIX * PIX + i] = (raw[i * 3 + c] as f32 / 255.0 - 0.5) / 0.5;
44        }
45    }
46    out
47}
48
49const PIX: usize = 1008;
50pub(crate) const PATCH: usize = 14;
51pub(crate) const GRID: usize = PIX / PATCH; // 72
52pub(crate) const WIN: usize = 24;
53pub(crate) const TD: usize = 1024;
54pub(crate) const TH: usize = 16;
55pub(crate) const TL: usize = 32;
56pub(crate) const TI: usize = 4736;
57pub(crate) const T_EPS: f32 = 1e-6;
58pub(crate) const GLOBAL: [usize; 4] = [7, 15, 23, 31];
59
60pub(crate) const SS: usize = 32;
61pub(crate) const SD: usize = 1024;
62pub(crate) const SL: usize = 24;
63pub(crate) const SI: usize = 4096;
64pub(crate) const S_EPS: f32 = 1e-5;
65const PROJ: usize = 512;
66
67const FD: usize = 256;
68const FI: usize = 2048;
69const FH: usize = 8;
70const D_EPS: f32 = 1e-6;
71const NL: usize = 6;
72const NQ: usize = 200;
73const MH: usize = 288;
74
75/// One forward's outputs (batch 1), flat row-major f32.
76pub struct Sam3Out {
77    /// CLIP text projection of the pooled token, [512].
78    pub text_embeds: Vec<f32>,
79    /// Resizer output fed to the DETR stack, [32 * 256].
80    pub text_feats: Vec<f32>,
81    /// Trunk features, [5184 * 1024].
82    pub trunk_feats: Vec<f32>,
83    /// FPN levels 288/144/72/36, each [256 * H * W].
84    pub fpn: Vec<Vec<f32>>,
85    /// DETR encoder output, [5184 * 256].
86    pub enc_hidden: Vec<f32>,
87    /// Stacked decoder layer outputs, [6 * 200 * 256].
88    pub dec_hidden: Vec<f32>,
89    /// Final boxes (xyxy), [200 * 4].
90    pub pred_boxes: Vec<f32>,
91    /// Instance masks, [200 * 288 * 288].
92    pub pred_masks: Vec<f32>,
93    /// Per-query classification logits from the dot-product scorer
94    /// (`det.scoring.*`), [200] — the final score of a query is
95    /// `sigmoid(pred_logits) * sigmoid(presence_logit)` (HF's
96    /// `post_process_object_detection`). Empty when `SAM3_ONLY`
97    /// skips the decoder.
98    pub pred_logits: Vec<f32>,
99    /// Presence-token logit of the final decoder layer (clamped ±10).
100    /// 0.0 when the decoder did not run.
101    pub presence_logit: f32,
102}
103
104/// Additive attention masks (added to scores before softmax).
105#[derive(Clone, Copy)]
106pub(crate) enum Mask<'a> {
107    None,
108    /// One value per key, shared by all queries/heads (padding).
109    Key(&'a [f32]),
110    /// [n_q, n_k] matrix, shared across heads (CLIP causal).
111    Add(&'a [f32]),
112    /// [heads, n_q, n_k] per-head bias (box RPB).
113    Head(&'a [f32]),
114}
115
116/// Attention sub-timers (ns), accumulated inside `run_attn` (qkv/proj
117/// GEMMs vs the softmax core) and printed by the session timer's Drop.
118static ATT_PROJ_NS: AtomicU64 = AtomicU64::new(0);
119static ATT_CORE_NS: AtomicU64 = AtomicU64::new(0);
120
121/// `SAM3_STAGES=1` — in-code wall-clock counters: `lap(name)` closes the
122/// current segment under `name` (laps with the same name merge), `add`
123/// accumulates inside loops. On drop the merged totals print as one
124/// `[sam3-prof]` block on stderr. Off by default (one env read per run).
125struct StageTimer {
126    on: bool,
127    main: bool,
128    t0: std::time::Instant,
129    acc: Vec<(&'static str, f64)>,
130}
131
132impl StageTimer {
133    fn new() -> Self {
134        Self {
135            on: std::env::var("SAM3_STAGES").is_ok_and(|v| v != "0"),
136            main: false,
137            t0: std::time::Instant::now(),
138            acc: Vec::new(),
139        }
140    }
141
142    /// The forward-level timer: resets the per-run attention statics so
143    /// multi-frame (video) runs report per-frame numbers.
144    fn new_session() -> Self {
145        ATT_PROJ_NS.store(0, Ordering::Relaxed);
146        ATT_CORE_NS.store(0, Ordering::Relaxed);
147        Self {
148            on: std::env::var("SAM3_STAGES").is_ok_and(|v| v != "0"),
149            main: true,
150            t0: std::time::Instant::now(),
151            acc: Vec::new(),
152        }
153    }
154
155    fn lap(&mut self, name: &'static str) {
156        if self.on {
157            self.acc.push((name, self.t0.elapsed().as_secs_f64() * 1e3));
158        }
159        self.t0 = std::time::Instant::now();
160    }
161}
162
163impl Drop for StageTimer {
164    fn drop(&mut self) {
165        if !self.on || self.acc.is_empty() {
166            return;
167        }
168        let mut merged: Vec<(&'static str, f64)> = Vec::new();
169        for (n, ms) in &self.acc {
170            match merged.iter_mut().find(|(m, _)| m == n) {
171                Some((_, t)) => *t += *ms,
172                None => merged.push((*n, *ms)),
173            }
174        }
175        let total: f64 = merged.iter().map(|(_, t)| t).sum();
176        for (n, ms) in &merged {
177            eprintln!("[sam3-prof] {n:>14} {ms:>10.1} ms  ({:.1}%)", ms / total * 100.0);
178        }
179        eprintln!("[sam3-prof] {:>14} {total:>10.1} ms", "TOTAL");
180        if self.main {
181            eprintln!(
182                "[sam3-prof] {:>14} {:>10.1} ms",
183                "attn_proj",
184                ATT_PROJ_NS.load(Ordering::Relaxed) as f64 / 1e6
185            );
186            eprintln!(
187                "[sam3-prof] {:>14} {:>10.1} ms",
188                "attn_core",
189                ATT_CORE_NS.load(Ordering::Relaxed) as f64 / 1e6
190            );
191            eprintln!(
192                "[sam3-prof] {:>14} hit/gate={}/{}",
193                "matmat_gpu",
194                crate::qtensor::MATMAT_GPU_HIT.load(Ordering::Relaxed),
195                crate::qtensor::MATMAT_GATE.load(Ordering::Relaxed)
196            );
197            #[cfg(feature = "gpu")]
198            eprintln!(
199                "[sam3-prof] {:>14} noctx/shape/entry/bounds/disp={}/{}/{}/{}/{}",
200                "m2f_refuse",
201                crate::gpu_wgpu::M2F_NO_CTX.load(Ordering::Relaxed),
202                crate::gpu_wgpu::M2F_SHAPE.load(Ordering::Relaxed),
203                crate::gpu_wgpu::M2F_ENTRY.load(Ordering::Relaxed),
204                crate::gpu_wgpu::M2F_BOUNDS.load(Ordering::Relaxed),
205                crate::gpu_wgpu::M2F_DISPATCH.load(Ordering::Relaxed),
206            );
207        }
208    }
209}
210
211pub struct Sam3 {
212    model: Arc<CmfModel>,
213    pool: Option<Arc<Pool>>,
214    /// `fpn.convs` (image detector neck) or `fpn.sam2_convs` (SAM3_FPN).
215    fpn_prefix: &'static str,
216    /// `trunk.pos_embed` is [1,577,1024]: Meta's leading cls row is
217    /// dropped by the HF conversion (SAM3_POS=first keeps rows 0..576).
218    pos_skip_cls: bool,
219    /// The text tower's result for the last prompt (a video's frames share it).
220    text_cache: Option<(Vec<u32>, Vec<u8>, Vec<f32>, Vec<f32>)>,
221}
222
223impl Sam3 {
224    pub fn open(path: &str) -> Result<Self> {
225        let model = CmfModel::open(path)
226            .with_context(|| format!("open {path}"))?
227            .into();
228        let fpn_prefix = match std::env::var("SAM3_FPN").as_deref() {
229            Ok("sam2_convs") => "fpn.sam2_convs",
230            _ => "fpn.convs",
231        };
232        let pos_skip_cls = std::env::var("SAM3_POS").as_deref() != Ok("first");
233        Ok(Self { model, pool: Pool::from_env(), fpn_prefix, pos_skip_cls, text_cache: None })
234    }
235
236    /// The shared CMF handle (the video tracker reads its `trk.*` section
237    /// through it).
238    pub(crate) fn cmf(&self) -> &Arc<CmfModel> { &self.model }
239
240    /// The GEMM thread pool the detector was opened with.
241    pub(crate) fn pool_handle(&self) -> Option<&Arc<Pool>> { self.pool.as_ref() }
242
243    /// Debug: `"name dtype shape"` lines for every tensor in the CMF
244    /// directory (the parity tests filter them by section).
245    pub fn directory(&self) -> Vec<String> {
246        self.model
247            .tensors
248            .iter()
249            .map(|t| format!("{} {:?} {:?}", t.name, t.dtype, t.shape))
250            .collect()
251    }
252
253    /// Debug: raw payload bytes of one directory tensor.
254    pub fn raw_tensor(&self, name: &str) -> Option<Vec<u8>> {
255        let e = self.model.tensor(name)?;
256        Some(self.model.entry_bytes(e).to_vec())
257    }
258
259    /// Debug: every `q8_row` row scale and every `f16` payload element
260    /// whose bit pattern is non-finite, as `"name@idx bad=0x…"` lines.
261    pub fn bad_scales(&self) -> Vec<String> {
262        let f16_bad = |h: u16| h & 0x7C00 == 0x7C00;
263        let mut out = Vec::new();
264        for t in self.model.tensors.iter() {
265            let bytes = self.model.entry_bytes(t);
266            match t.dtype {
267                TensorDtype::Q8Row if t.shape.len() == 2 => {
268                    let (rows, cols) = (t.shape[0], t.shape[1]);
269                    let off = rows * cols;
270                    if bytes.len() < off + rows * 2 {
271                        out.push(format!("{}@payload short", t.name));
272                        continue;
273                    }
274                    for r in 0..rows {
275                        let h = u16::from_le_bytes([bytes[off + r * 2], bytes[off + r * 2 + 1]]);
276                        if f16_bad(h) {
277                            out.push(format!("{}@row{r} scale_f16=0x{h:04x}", t.name));
278                        }
279                    }
280                }
281                TensorDtype::F16 => {
282                    for (i, c) in bytes.chunks_exact(2).enumerate() {
283                        let h = u16::from_le_bytes([c[0], c[1]]);
284                        if f16_bad(h) {
285                            out.push(format!("{}@{i} val_f16=0x{h:04x}", t.name));
286                            if out.len() > 200 { return out; }
287                        }
288                    }
289                }
290                _ => {}
291            }
292        }
293        out
294    }
295
296    /// `pixels` [3,1008,1008] preprocessed; `ids`/`attn` length 32
297    /// (Sam3Processor, padding to max_length=32).
298    ///
299    /// Debug knobs (unset in normal runs): `SAM3_ONLY=trunk,...` runs only
300    /// the listed stages and returns empty tensors for the rest (the
301    /// parity test skips while it is set); `SAM3_DUMP_DIR` makes `trunk`
302    /// write its stage outputs (`trunk_patch.f32`, `trunk_pre.f32`,
303    /// `trunk_b{l}.f32`) for reference bisection; `SAM3_TEXT_DEBUG=1`
304    /// prints per-stage finiteness stats of the text tower.
305    pub fn forward(&mut self, pixels: &[f32], ids: &[u32], attn: &[u8]) -> Result<Sam3Out> {
306        let _prof = crate::cpuprof::spans::dump_on_drop("image forward");
307        if pixels.len() != 3 * PIX * PIX {
308            return Err(anyhow!("pixels {} != 3*{}*{}", pixels.len(), PIX, PIX));
309        }
310        if ids.len() != SS || attn.len() != SS {
311            return Err(anyhow!("ids/attn must be {SS} long"));
312        }
313        let only = std::env::var("SAM3_ONLY").ok();
314        let want = |k: &str| {
315            only
316                .as_deref()
317                .map_or(true, |o| o.split(',').any(|s| s.trim() == k))
318        };
319        let pool = self.pool.as_deref();
320        let mut stg = StageTimer::new_session();
321        let _p = crate::cpuprof::spans::span("text");
322        let (text_embeds, text_feats) = match &self.text_cache {
323            Some((i, a, e, f)) if i == ids && a == attn => (e.clone(), f.clone()),
324            _ => {
325                let (e, f) = self.text(ids, attn, pool)?;
326                self.text_cache = Some((ids.to_vec(), attn.to_vec(), e.clone(), f.clone()));
327                (e, f)
328            }
329        };
330        drop(_p);
331        stg.lap("text");
332        let blank = |te: Vec<f32>, tf: Vec<f32>| Sam3Out {
333            text_embeds: te,
334            text_feats: tf,
335            trunk_feats: Vec::new(),
336            fpn: Vec::new(),
337            enc_hidden: Vec::new(),
338            dec_hidden: Vec::new(),
339            pred_boxes: Vec::new(),
340            pred_masks: Vec::new(),
341            pred_logits: Vec::new(),
342            presence_logit: 0.0,
343        };
344        if !want("trunk") {
345            return Ok(blank(text_embeds, text_feats));
346        }
347        let trunk_feats = {
348            let _p = crate::cpuprof::spans::span("trunk");
349            self.trunk(pixels, pool)?
350        };
351        stg.lap("trunk");
352        if !want("fpn") {
353            let mut o = blank(text_embeds, text_feats);
354            o.trunk_feats = trunk_feats;
355            return Ok(o);
356        }
357        let fpn = self.fpn(&trunk_feats, pool)?;
358        stg.lap("fpn");
359        let pos = sine_pos(GRID, GRID, FD / 2); // level-2 (72) encoding, rows
360        let vision = chw_to_rows(&fpn[2], GRID, GRID);
361        let enc_hidden = {
362            let _p = crate::cpuprof::spans::span("detr_enc");
363            self.detr_encoder(&vision, &pos, &text_feats, attn, pool)?
364        };
365        stg.lap("enc");
366        if !want("dec") {
367            let mut o = blank(text_embeds, text_feats);
368            o.trunk_feats = trunk_feats;
369            o.fpn = fpn;
370            o.enc_hidden = enc_hidden;
371            return Ok(o);
372        }
373        let (dec_hidden, final_refs, presence_logit) = {
374            let _p = crate::cpuprof::spans::span("detr_dec");
375            self.detr_decoder(&enc_hidden, &pos, &text_feats, attn, pool)?
376        };
377        stg.lap("dec");
378        // Dot-product scoring (det.scoring.*): the FINAL layer's DETR
379        // queries against the mean-pooled prompt features. Logits, not
380        // probabilities — the caller multiplies both sigmoids, as HF's
381        // post-processor does (`all_pred_logits[-1]`).
382        let pred_logits = {
383            let _p = crate::cpuprof::spans::span("score");
384            self.score(
385                &text_feats,
386                attn,
387                &dec_hidden[(NL - 1) * NQ * FD..],
388                pool,
389            )?
390        };
391        stg.lap("score");
392        if !want("masks") {
393            let mut o = blank(text_embeds, text_feats);
394            o.trunk_feats = trunk_feats;
395            o.fpn = fpn;
396            o.enc_hidden = enc_hidden;
397            o.dec_hidden = dec_hidden.clone();
398            o.pred_boxes = xyxy(&final_refs);
399            o.pred_logits = pred_logits;
400            o.presence_logit = presence_logit;
401            return Ok(o);
402        }
403        let pred_boxes = xyxy(&final_refs);
404        let pred_masks = {
405            let _p = crate::cpuprof::spans::span("mask_dec");
406            self.mask_decoder(
407                &dec_hidden[(NL - 1) * NQ * FD..],
408                &enc_hidden,
409                &fpn,
410                &text_feats,
411                attn,
412                pool,
413            )?
414        };
415        stg.lap("masks");
416        Ok(Sam3Out {
417            text_embeds,
418            text_feats,
419            trunk_feats,
420            fpn,
421            enc_hidden,
422            dec_hidden,
423            pred_boxes,
424            pred_masks,
425            pred_logits,
426            presence_logit,
427        })
428    }
429
430    // ── text tower (CLIP-L, pre-norm transformer) ───────────────────
431
432    fn text(&self, ids: &[u32], attn: &[u8], pool: Option<&Pool>) -> Result<(Vec<f32>, Vec<f32>)> {
433        let m = &self.model;
434        let mut tst = StageTimer::new();
435        let tok = lin(m, "text.encoder.token_embedding.weight")?;
436        let pos = load_vec(m, "text.encoder.positional_embedding")?;
437        let mut x = vec![0f32; SS * SD];
438        let mut row = vec![0f32; SD];
439        for (i, &id) in ids.iter().enumerate() {
440            tok.row_f32(id as usize, &mut row);
441            let r = &mut x[i * SD..(i + 1) * SD];
442            r.copy_from_slice(&row);
443            for (v, p) in r.iter_mut().zip(&pos[i * SD..(i + 1) * SD]) {
444                *v += *p;
445            }
446        }
447        dbg_stats("text.emb", &x);
448        // causal + padding additive mask [SS, SS]
449        let mut cm = vec![0f32; SS * SS];
450        for q in 0..SS {
451            for k in 0..=q {
452                if attn[k] == 0 {
453                    cm[q * SS + k] = NEG;
454                }
455            }
456            for k in (q + 1)..SS {
457                cm[q * SS + k] = NEG;
458            }
459        }
460        tst.lap("txt_embed");
461        let on_device = std::env::var("SAM3_DUMP_DIR").is_err() && crate::gpu::sam3_text(m, &mut x, &cm);
462        tst.lap("txt_tower");
463        for l in 0..if on_device { 0 } else { SL } {
464            let b = format!("text.encoder.transformer.resblocks.{l}.");
465            let (lw, lb) = (load_vec(m, &format!("{b}ln_1.weight"))?, load_vec(m, &format!("{b}ln_1.bias"))?);
466            // Pre-norm: branch reads a normalized CLONE, x keeps the residual.
467            let mut h = x.clone();
468            layer_norm_rows(&mut h, &lw, &lb, S_EPS);
469            let qkv = lin(m, &format!("{b}attn.in_proj_weight"))?;
470            let ib = load_vec(m, &format!("{b}attn.in_proj_bias"))?;
471            let op = lin(m, &format!("{b}attn.out_proj.weight"))?;
472            let ob = load_vec(m, &format!("{b}attn.out_proj.bias"))?;
473            let mut ao = vec![0f32; SS * SD];
474            run_attn(
475                &qkv, &ib, &op, &ob,
476                &h, &h, &h, SS, SS, SD, 16, None, Mask::Add(&cm), pool, &mut ao,
477            );
478            for (a, c) in x.iter_mut().zip(&ao) { *a += *c; }
479            let (lw, lb) = (load_vec(m, &format!("{b}ln_2.weight"))?, load_vec(m, &format!("{b}ln_2.bias"))?);
480            let mut h = x.clone();
481            layer_norm_rows(&mut h, &lw, &lb, S_EPS);
482            let f1 = lin(m, &format!("{b}mlp.c_fc.weight"))?;
483            let f1b = load_vec(m, &format!("{b}mlp.c_fc.bias"))?;
484            let f2 = lin(m, &format!("{b}mlp.c_proj.weight"))?;
485            let f2b = load_vec(m, &format!("{b}mlp.c_proj.bias"))?;
486            let mut ff = vec![0f32; SS * SI];
487            f1.matmat_dev(&h, SS, &mut ff, pool);
488            add_bias(&mut ff, SI, &f1b);
489            ff.iter_mut().for_each(|v| *v = gelu_erf(*v));
490            let mut fo = vec![0f32; SS * SD];
491            f2.matmat_dev(&ff, SS, &mut fo, pool);
492            add_bias(&mut fo, SD, &f2b);
493            for (a, c) in x.iter_mut().zip(&fo) { *a += *c; }
494            dbg_stats(&format!("text.l{l}"), &x);
495        }
496        if !on_device {
497            let (lw, lb) = (load_vec(m, "text.encoder.ln_final.weight")?, load_vec(m, "text.encoder.ln_final.bias")?);
498            layer_norm_rows(&mut x, &lw, &lb, S_EPS);
499        }
500        dbg_stats("text.ln_final", &x);
501        if let Some(d) = std::env::var("SAM3_DUMP_DIR").ok() {
502            dump_f32(&d, "text_lh", &x);
503        }
504        tst.lap("txt_tower");
505        // CLIP pools at the first eos token: (ids == eos).argmax()
506        let p = ids.iter().position(|&v| v == 49407).ok_or_else(|| anyhow!("no eos token"))?;
507        let pooled = &x[p * SD..(p + 1) * SD];
508        // text_embeds = pooled @ projection; projection is stored [1024, 512]
509        let proj = load_vec(m, "text.encoder.text_projection")?;
510        dbg_stats("text.proj", &proj);
511        let mut embeds = vec![0f32; PROJ];
512        for j in 0..PROJ {
513            let mut acc = 0f32;
514            for i in 0..SD { acc += pooled[i] * proj[i * PROJ + j]; }
515            embeds[j] = acc;
516        }
517        dbg_stats("text.pooled", pooled);
518        dbg_stats("text.embeds", &embeds);
519        // DETR text features: Linear(1024 -> 256) over the full sequence
520        let rz = lin(m, "text.resizer.weight")?;
521        let rb = load_vec(m, "text.resizer.bias")?;
522        let mut feats = vec![0f32; SS * FD];
523        rz.matmat_dev(&x, SS, &mut feats, pool);
524        add_bias(&mut feats, FD, &rb);
525        dbg_stats("text.feats", &feats);
526        tst.lap("txt_proj");
527        Ok((embeds, feats))
528    }
529
530    // ── trunk (ViT, pre-norm layers, windowed/global axial RoPE) ────
531
532    fn trunk(&self, pixels: &[f32], pool: Option<&Pool>) -> Result<Vec<f32>> {
533        let _patch = crate::cpuprof::spans::span("trunk.patch");
534        let m = &self.model;
535        let np = GRID * GRID;
536        let kc = 3 * PATCH * PATCH;
537        let dump = std::env::var("SAM3_DUMP_DIR").ok();
538        let dlayers: Option<Vec<usize>> = std::env::var("SAM3_DUMP_LAYERS")
539            .ok()
540            .map(|s| s.split(',').filter_map(|t| t.trim().parse().ok()).collect());
541        let w = load_vec(m, "trunk.patch_embed.proj.weight")?; // [1024,3,14,14]
542        let mut pv = vec![0f32; np * kc];
543        let pvb = pv.as_mut_ptr() as usize;
544        let fill = |s: usize, e: usize| {
545            let pv = unsafe { std::slice::from_raw_parts_mut(pvb as *mut f32, np * kc) };
546            for pt in s..e {
547                let (py, px) = (pt / GRID, pt % GRID);
548                let d = &mut pv[pt * kc..(pt + 1) * kc];
549                let mut o = 0;
550                for c in 0..3 {
551                    for ky in 0..PATCH {
552                        let y = py * PATCH + ky;
553                        for kx in 0..PATCH {
554                            d[o] = pixels[c * PIX * PIX + y * PIX + px * PATCH + kx];
555                            o += 1;
556                        }
557                    }
558                }
559            }
560        };
561        match pool { Some(p) => p.run_rows(np, &fill), None => fill(0, np) };
562        // the whole trunk on the device when it takes it (not under the dumps)
563        if dump.is_none()
564            && let Some(x) = crate::gpu::sam3_trunk(m, &pv, self.pos_skip_cls)
565        {
566            return Ok(x);
567        }
568        let mut x = vec![0f32; np * TD];
569        let xb = x.as_mut_ptr() as usize;
570        let gemm = |s: usize, e: usize| {
571            let x = unsafe { std::slice::from_raw_parts_mut(xb as *mut f32, np * TD) };
572            for ch in s..e {
573                let wr = &w[ch * kc..(ch + 1) * kc];
574                for pt in 0..np {
575                    let xv = &pv[pt * kc..(pt + 1) * kc];
576                    let mut acc = 0f32;
577                    for k in 0..kc { acc += wr[k] * xv[k]; }
578                    x[pt * TD + ch] = acc;
579                }
580            }
581        };
582        match pool { Some(p) => p.run_rows(TD, &gemm), None => gemm(0, TD) };
583        drop(_patch);
584        if let Some(d) = &dump { dump_f32(d, "trunk_patch", &x); }
585        // position embeddings [1,577,1024]: drop Meta's cls row, tile 24x24 -> 72x72
586        let pos = load_vec(m, "trunk.pos_embed")?;
587        let base = if self.pos_skip_cls { 1 } else { 0 };
588        if pos.len() < (base + 576) * TD { return Err(anyhow!("pos_embed too small")); }
589        for pt in 0..np {
590            let (py, px) = (pt / GRID, pt % GRID);
591            let src = (base + (py % 24) * 24 + px % 24) * TD;
592            for d in 0..TD { x[pt * TD + d] += pos[src + d]; }
593        }
594        let (lw, lb) = (load_vec(m, "trunk.ln_pre.weight")?, load_vec(m, "trunk.ln_pre.bias")?);
595        layer_norm_rows(&mut x, &lw, &lb, T_EPS);
596        if let Some(d) = &dump { dump_f32(d, "trunk_pre", &x); }
597
598        let mut tst = StageTimer::new();
599        for l in 0..TL {
600            let b = format!("trunk.blocks.{l}.");
601            let _attn = crate::cpuprof::spans::span("trunk.attn");
602            let (nw, nb) = (load_vec(m, &format!("{b}norm1.weight"))?, load_vec(m, &format!("{b}norm1.bias"))?);
603            let mut h = x.clone();
604            layer_norm_rows(&mut h, &nw, &nb, T_EPS);
605            let dbg0 = dump.is_some() && l == 0;
606            if let (Some(d), true) = (&dump, dbg0) { dump_f32(d, "b0_ln1", &h); }
607            drop(_attn);
608            let qkv = lin(m, &format!("{b}attn.qkv.weight"))?;
609            let qb = load_vec(m, &format!("{b}attn.qkv.bias"))?;
610            let proj = lin(m, &format!("{b}attn.proj.weight"))?;
611            let pb = load_vec(m, &format!("{b}attn.proj.bias"))?;
612            let fc = load_vec(m, &format!("{b}attn.freqs_cis"))?;
613            tst.lap("trk_attn_ln");
614            let attn_out = if GLOBAL.contains(&l) {
615                let mut o = vec![0f32; np * TD];
616                let _pa = crate::cpuprof::spans::span("trunk.attn.run");
617                run_attn(&qkv, &qb, &proj, &pb, &h, &h, &h, np, np, TD, TH, Some(&fc), Mask::None, pool, &mut o);
618                drop(_pa);
619                o
620            } else {
621                let _pa = crate::cpuprof::spans::span("trunk.attn.run");
622                let o = self.vit_windows(&h, &qkv, &qb, &proj, &pb, &fc, pool)?;
623                drop(_pa);
624                o
625            };
626            if let (Some(d), true) = (&dump, dbg0) { dump_f32(d, "b0_attn", &attn_out); }
627            for (a, c) in x.iter_mut().zip(&attn_out) { *a += *c; }
628            tst.lap("trk_attn_run");
629            if let (Some(d), true) = (&dump, dbg0) { dump_f32(d, "b0_x2", &x); }
630            // pre-norm MLP branch: norm a CLONE — x keeps the residual
631            // (norming x in place made the block add mlp(ln2(x)) instead
632            // of x + mlp(ln2(x))).
633            let (nw, nb) = (load_vec(m, &format!("{b}norm2.weight"))?, load_vec(m, &format!("{b}norm2.bias"))?);
634            let mut h = x.clone();
635            layer_norm_rows(&mut h, &nw, &nb, T_EPS);
636            if let (Some(d), true) = (&dump, dbg0) { dump_f32(d, "b0_ln2", &h); }
637            let f1 = lin(m, &format!("{b}mlp.fc1.weight"))?;
638            let f1b = load_vec(m, &format!("{b}mlp.fc1.bias"))?;
639            let f2 = lin(m, &format!("{b}mlp.fc2.weight"))?;
640            let f2b = load_vec(m, &format!("{b}mlp.fc2.bias"))?;
641            let mut ff = vec![0f32; np * TI];
642            f1.matmat_dev(&h, np, &mut ff, pool);
643            add_bias(&mut ff, TI, &f1b);
644            gelu_slice(&mut ff);
645            let mut fo = vec![0f32; np * TD];
646            f2.matmat_dev(&ff, np, &mut fo, pool);
647            add_bias(&mut fo, TD, &f2b);
648            if let (Some(d), true) = (&dump, dbg0) { dump_f32(d, "b0_mlp", &fo); }
649            for (a, c) in x.iter_mut().zip(&fo) { *a += *c; }
650            tst.lap("trk_mlp");
651            if let (Some(d), true) = (&dump, dlayers.as_ref().map_or(true, |ls| ls.contains(&l))) {
652                dump_f32(d, &format!("trunk_b{l}"), &x);
653            }
654        }
655        Ok(x)
656    }
657
658    /// Windowed trunk attention: 3x3 windows of 24x24 tokens (freqs [576]).
659    fn vit_windows(
660        &self,
661        h: &[f32],
662        qkv: &QTensor,
663        qb: &[f32],
664        proj: &QTensor,
665        pb: &[f32],
666        fc: &[f32],
667        pool: Option<&Pool>,
668    ) -> Result<Vec<f32>> {
669        let np = GRID * GRID;
670        let nw = GRID / WIN;
671        let wl = WIN * WIN;
672        let mut wh = vec![0f32; wl * TD];
673        let mut ao = vec![0f32; wl * TD];
674        let mut out = vec![0f32; np * TD];
675        for wy in 0..nw {
676            for wx in 0..nw {
677                for y in 0..WIN {
678                    for x2 in 0..WIN {
679                        let s = ((wy * WIN + y) * GRID + wx * WIN + x2) * TD;
680                        let d = (y * WIN + x2) * TD;
681                        wh[d..d + TD].copy_from_slice(&h[s..s + TD]);
682                    }
683                }
684                run_attn(qkv, qb, proj, pb, &wh, &wh, &wh, wl, wl, TD, TH, Some(fc), Mask::None, pool, &mut ao);
685                for y in 0..WIN {
686                    for x2 in 0..WIN {
687                        let d = ((wy * WIN + y) * GRID + wx * WIN + x2) * TD;
688                        let s = (y * WIN + x2) * TD;
689                        out[d..d + TD].copy_from_slice(&ao[s..s + TD]);
690                    }
691                }
692            }
693        }
694        Ok(out)
695    }
696
697    // ── FPN neck ────────────────────────────────────────────────────
698
699    /// Four pyramid levels from the trunk map: 288/144/72/36, each
700    /// [256, H, W] channels-first.
701    fn fpn(&self, trunk: &[f32], pool: Option<&Pool>) -> Result<Vec<Vec<f32>>> {
702        fpn_levels(&self.model, self.fpn_prefix, trunk, pool, 4)
703    }
704
705    // ── DETR encoder (pre-norm layers) ──────────────────────────────
706
707    #[allow(clippy::too_many_arguments)]
708    fn detr_encoder(
709        &self,
710        vision: &[f32],
711        pos: &[f32],
712        text: &[f32],
713        am: &[u8],
714        pool: Option<&Pool>,
715    ) -> Result<Vec<f32>> {
716        let m = &self.model;
717        let n = vision.len() / FD;
718        let mut xs = vision.to_vec();
719        let mut km = vec![0f32; SS];
720        for (k, &v) in am.iter().enumerate() { km[k] = if v == 0 { NEG } else { 0.0 }; }
721        let mut tse = StageTimer::new();
722        for l in 0..NL {
723            let b = format!("det.transformer.encoder.layers.{l}.");
724            // pre-norm self attention: q=k=normed+pos, v=normed
725            let (nw, nb) = (load_vec(m, &format!("{b}norm1.weight"))?, load_vec(m, &format!("{b}norm1.bias"))?);
726            let mut h = xs.clone();
727            layer_norm_rows(&mut h, &nw, &nb, D_EPS);
728            let hp: Vec<f32> = h
729                .chunks_exact(FD)
730                .zip(pos.chunks_exact(FD))
731                .flat_map(|(a, c)| a.iter().zip(c).map(|(x, y)| x + y))
732                .collect();
733            let qkv = lin(m, &format!("{b}self_attn.in_proj_weight"))?;
734            let ib = load_vec(m, &format!("{b}self_attn.in_proj_bias"))?;
735            let op = lin(m, &format!("{b}self_attn.out_proj.weight"))?;
736            let ob = load_vec(m, &format!("{b}self_attn.out_proj.bias"))?;
737            let mut ao = vec![0f32; n * FD];
738            run_attn(&qkv, &ib, &op, &ob, &hp, &hp, &h, n, n, FD, FH, None, Mask::None, pool, &mut ao);
739            for (a, c) in xs.iter_mut().zip(&ao) { *a += *c; }
740            tse.lap("enc_self_attn");
741            // cross attention to the text features (query has no pos add)
742            let (nw, nb) = (load_vec(m, &format!("{b}norm2.weight"))?, load_vec(m, &format!("{b}norm2.bias"))?);
743            let mut h = xs.clone();
744            layer_norm_rows(&mut h, &nw, &nb, D_EPS);
745            let qkv = lin(m, &format!("{b}cross_attn_image.in_proj_weight"))?;
746            let ib = load_vec(m, &format!("{b}cross_attn_image.in_proj_bias"))?;
747            let op = lin(m, &format!("{b}cross_attn_image.out_proj.weight"))?;
748            let ob = load_vec(m, &format!("{b}cross_attn_image.out_proj.bias"))?;
749            let mut ao = vec![0f32; n * FD];
750            run_attn(&qkv, &ib, &op, &ob, &h, text, text, n, SS, FD, FH, None, Mask::Key(&km), pool, &mut ao);
751            for (a, c) in xs.iter_mut().zip(&ao) { *a += *c; }
752            tse.lap("enc_cross_text");
753            // relu MLP
754            let (nw, nb) = (load_vec(m, &format!("{b}norm3.weight"))?, load_vec(m, &format!("{b}norm3.bias"))?);
755            let mut h = xs.clone();
756            layer_norm_rows(&mut h, &nw, &nb, D_EPS);
757            let l1 = lin(m, &format!("{b}linear1.weight"))?;
758            let l1b = load_vec(m, &format!("{b}linear1.bias"))?;
759            let l2 = lin(m, &format!("{b}linear2.weight"))?;
760            let l2b = load_vec(m, &format!("{b}linear2.bias"))?;
761            let mut mid = vec![0f32; n * FI];
762            l1.matmat_dev(&h, n, &mut mid, pool);
763            add_bias(&mut mid, FI, &l1b);
764            mid.iter_mut().for_each(|v| *v = v.max(0.0));
765            let mut fo = vec![0f32; n * FD];
766            l2.matmat_dev(&mid, n, &mut fo, pool);
767            add_bias(&mut fo, FD, &l2b);
768            for (a, c) in xs.iter_mut().zip(&fo) { *a += *c; }
769            tse.lap("enc_ffn");
770        }
771        Ok(xs)
772    }
773
774    // ── DETR decoder (POST-norm layers) ─────────────────────────────
775
776    /// Returns (stacked layer outputs [6*200*256], final reference boxes
777    /// in cxcywh — the box_head refinement of the last layer, which
778    /// equals Sam3Model's `all_pred_boxes[-1]` pre-xyxy conversion — and
779    /// the FINAL layer's presence logit: the presence row through
780    /// `presence_token_out_norm` + the 3-layer presence head, clamped
781    /// ±10 as HF clamps it).
782    fn detr_decoder(
783        &self,
784        enc: &[f32],
785        pos: &[f32],
786        text: &[f32],
787        am: &[u8],
788        pool: Option<&Pool>,
789    ) -> Result<(Vec<f32>, Vec<[f32; 4]>, f32)> {
790        let m = &self.model;
791        let n = enc.len() / FD;
792        let db = "det.transformer.decoder.";
793        let query = load_vec(m, &format!("{db}query_embed.weight"))?;
794        let presence = load_vec(m, &format!("{db}presence_token.weight"))?;
795        let ref0 = load_vec(m, &format!("{db}reference_points.weight"))?;
796        let mut hidden = vec![0f32; (NQ + 1) * FD];
797        hidden[..FD].copy_from_slice(&presence);
798        hidden[FD..].copy_from_slice(&query);
799        let mut refs: Vec<[f32; 4]> = ref0
800            .chunks_exact(4)
801            .map(|c| [sigm(c[0]), sigm(c[1]), sigm(c[2]), sigm(c[3])])
802            .collect();
803        let mut km = vec![0f32; SS];
804        for (k, &v) in am.iter().enumerate() { km[k] = if v == 0 { NEG } else { 0.0 }; }
805        let mut tsd = StageTimer::new();
806        // heads (all loaded once, biases included)
807        let rh0 = lin(m, &format!("{db}ref_point_head.layers.0.weight"))?;
808        let rh0b = load_vec(m, &format!("{db}ref_point_head.layers.0.bias"))?;
809        let rh1 = lin(m, &format!("{db}ref_point_head.layers.1.weight"))?;
810        let rh1b = load_vec(m, &format!("{db}ref_point_head.layers.1.bias"))?;
811        let rx = DecoderMlp::load(m, &format!("{db}boxRPB_embed_x."))?;
812        let ry = DecoderMlp::load(m, &format!("{db}boxRPB_embed_y."))?;
813        let bbox = DecoderMlp3::load3(m, &format!("{db}bbox_embed."))?;
814        let olnw = load_vec(m, &format!("{db}norm.weight"))?;
815        let olnb = load_vec(m, &format!("{db}norm.bias"))?;
816        let pres_w = load_vec(m, &format!("{db}presence_token_out_norm.weight"))?;
817        let pres_b = load_vec(m, &format!("{db}presence_token_out_norm.bias"))?;
818        let pres_head = DecoderMlp3::load3(m, &format!("{db}presence_token_head."))?;
819        let key = add_rows(enc, pos); // enc + pos, [n, FD]
820        let mut inter: Vec<Vec<f32>> = Vec::with_capacity(NL);
821        for l in 0..NL {
822            let b = format!("{db}layers.{l}.");
823            // query position from the sine encoding of the reference boxes
824            let sine = sine_boxes(&refs);
825            let mut qp = vec![0f32; NQ * FD];
826            rh0.matmat_dev(&sine, NQ, &mut qp, pool);
827            add_bias(&mut qp, FD, &rh0b);
828            qp.iter_mut().for_each(|v| *v = v.max(0.0)); // DecoderMLP: relu between
829            let mut qp2 = vec![0f32; NQ * FD];
830            rh1.matmat_dev(&qp, NQ, &mut qp2, pool);
831            add_bias(&mut qp2, FD, &rh1b);
832            let qp = qp2;
833            let mut qp_full = vec![0f32; (NQ + 1) * FD];
834            qp_full[FD..].copy_from_slice(&qp);
835            tsd.lap("dec_qpos");
836            let rpb = rpb_bias(&refs, &rx, &ry, n, pool)?;
837            tsd.lap("dec_rpb");
838            // self attention: q=k=h+qp (pad row stays qp=0), v=h ; POST-norm
839            let hqp = add_rows(&hidden, &qp_full);
840            let qkv = lin(m, &format!("{b}self_attn.in_proj_weight"))?;
841            let ib = load_vec(m, &format!("{b}self_attn.in_proj_bias"))?;
842            let op = lin(m, &format!("{b}self_attn.out_proj.weight"))?;
843            let ob = load_vec(m, &format!("{b}self_attn.out_proj.bias"))?;
844            let mut ao = vec![0f32; (NQ + 1) * FD];
845            run_attn(&qkv, &ib, &op, &ob, &hqp, &hqp, &hidden, NQ + 1, NQ + 1, FD, FH, None, Mask::None, pool, &mut ao);
846            for (a, c) in hidden.iter_mut().zip(&ao) { *a += *c; }
847            tsd.lap("dec_self_attn");
848            let (nw, nb) = (load_vec(m, &format!("{b}norm1.weight"))?, load_vec(m, &format!("{b}norm1.bias"))?);
849            layer_norm_rows(&mut hidden, &nw, &nb, D_EPS);
850            // text cross attention
851            let hqp = add_rows(&hidden, &qp_full);
852            let qkv = lin(m, &format!("{b}ca_text.in_proj_weight"))?;
853            let ib = load_vec(m, &format!("{b}ca_text.in_proj_bias"))?;
854            let op = lin(m, &format!("{b}ca_text.out_proj.weight"))?;
855            let ob = load_vec(m, &format!("{b}ca_text.out_proj.bias"))?;
856            let mut ao = vec![0f32; (NQ + 1) * FD];
857            run_attn(&qkv, &ib, &op, &ob, &hqp, text, text, NQ + 1, SS, FD, FH, None, Mask::Key(&km), pool, &mut ao);
858            for (a, c) in hidden.iter_mut().zip(&ao) { *a += *c; }
859            tsd.lap("dec_cross_text");
860            let (nw, nb) = (load_vec(m, &format!("{b}catext_norm.weight"))?, load_vec(m, &format!("{b}catext_norm.bias"))?);
861            layer_norm_rows(&mut hidden, &nw, &nb, D_EPS);
862            // vision cross attention (keys = enc + pos, values = enc, RPB bias)
863            let hqp = add_rows(&hidden, &qp_full);
864            let qkv = lin(m, &format!("{b}cross_attn.in_proj_weight"))?;
865            let ib = load_vec(m, &format!("{b}cross_attn.in_proj_bias"))?;
866            let op = lin(m, &format!("{b}cross_attn.out_proj.weight"))?;
867            let ob = load_vec(m, &format!("{b}cross_attn.out_proj.bias"))?;
868            let mut ao = vec![0f32; (NQ + 1) * FD];
869            run_attn(&qkv, &ib, &op, &ob, &hqp, &key, enc, NQ + 1, n, FD, FH, None, Mask::Head(&rpb), pool, &mut ao);
870            for (a, c) in hidden.iter_mut().zip(&ao) { *a += *c; }
871            tsd.lap("dec_cross_enc");
872            let (nw, nb) = (load_vec(m, &format!("{b}norm2.weight"))?, load_vec(m, &format!("{b}norm2.bias"))?);
873            layer_norm_rows(&mut hidden, &nw, &nb, D_EPS);
874            // relu MLP (Sam3MLP)
875            let l1 = lin(m, &format!("{b}linear1.weight"))?;
876            let l1b = load_vec(m, &format!("{b}linear1.bias"))?;
877            let l2 = lin(m, &format!("{b}linear2.weight"))?;
878            let l2b = load_vec(m, &format!("{b}linear2.bias"))?;
879            let mut mid = vec![0f32; (NQ + 1) * FI];
880            l1.matmat_dev(&hidden, NQ + 1, &mut mid, pool);
881            add_bias(&mut mid, FI, &l1b);
882            mid.iter_mut().for_each(|v| *v = v.max(0.0));
883            let mut fo = vec![0f32; (NQ + 1) * FD];
884            l2.matmat_dev(&mid, NQ + 1, &mut fo, pool);
885            add_bias(&mut fo, FD, &l2b);
886            for (a, c) in hidden.iter_mut().zip(&fo) { *a += *c; }
887            tsd.lap("dec_ffn");
888            let (nw, nb) = (load_vec(m, &format!("{b}norm3.weight"))?, load_vec(m, &format!("{b}norm3.bias"))?);
889            layer_norm_rows(&mut hidden, &nw, &nb, D_EPS);
890            // box refine + intermediate (query rows only, output_layer_norm)
891            let mut qh = hidden[FD..].to_vec();
892            layer_norm_rows(&mut qh, &olnw, &olnb, D_EPS);
893            inter.push(qh.clone());
894            let d = bbox.forward(&qh, NQ, pool);
895            for (r, dd) in refs.iter_mut().zip(d.chunks_exact(4)) {
896                for k in 0..4 { r[k] = sigm(inv_sigmoid(r[k]) + dd[k]); }
897            }
898            tsd.lap("dec_box_ref");
899        }
900        let dec = inter.iter().flat_map(|v| v.iter().copied()).collect();
901        // Presence logit of the FINAL layer: row 0 (the presence token)
902        // is post-normed by the layer stack like every other row — feed
903        // it through presence_layer_norm + presence_head (relu, relu,
904        // linear — 3 layers), clamp ±10 (HF `clamp_presence_logit_max_val`).
905        let mut ph = hidden[0..FD].to_vec();
906        layer_norm_rows(&mut ph, &pres_w, &pres_b, D_EPS);
907        let pl = pres_head.forward(&ph, 1, pool);
908        let presence_logit = pl[0].clamp(-10.0, 10.0);
909        Ok((dec, refs, presence_logit))
910    }
911
912    /// Dot-product concept scoring — HF `Sam3DotProductScoring` over
913    /// the `det.scoring.*` section: the prompt MLP (2 layers, relu
914    /// between) + residual + out-norm on the resizer features,
915    /// mean-pooled over the unpadded positions, projected by
916    /// `prompt_proj`; the output-normed queries of the FINAL decoder
917    /// layer projected by `hs_proj`; the dot product scaled by
918    /// 1/sqrt(256) and clamped to ±12 (HF `clamp_max_val`). `dec` is
919    /// one layer's `[nq * FD]` queries; returns `nq` logits.
920    fn score(
921        &self,
922        text: &[f32],
923        am: &[u8],
924        dec: &[f32],
925        pool: Option<&Pool>,
926    ) -> Result<Vec<f32>> {
927        let m = &self.model;
928        let mlp = DecoderMlp::load(m, "det.scoring.prompt_mlp.")?;
929        let mut h = mlp.forward(text, SS, pool, FD);
930        for (a, b) in h.iter_mut().zip(text) {
931            *a += *b;
932        }
933        let (ow, ob) = (
934            load_vec(m, "det.scoring.prompt_mlp.out_norm.weight")?,
935            load_vec(m, "det.scoring.prompt_mlp.out_norm.bias")?,
936        );
937        layer_norm_rows(&mut h, &ow, &ob, D_EPS);
938        // Mean pool over attention_mask == 1 (HF `_pool_text_features`).
939        let n_valid = am.iter().filter(|&&v| v == 1).count().max(1) as f32;
940        let mut pooled = vec![0f32; FD];
941        for (i, &v) in am.iter().enumerate().take(SS) {
942            if v == 1 {
943                for d in 0..FD {
944                    pooled[d] += h[i * FD + d];
945                }
946            }
947        }
948        for v in pooled.iter_mut() {
949            *v /= n_valid;
950        }
951        let pt = lin(m, "det.scoring.prompt_proj.weight")?;
952        let pb = load_vec(m, "det.scoring.prompt_proj.bias")?;
953        let mut tp = vec![0f32; FD];
954        pt.matmat_dev(&pooled, 1, &mut tp, pool);
955        add_bias(&mut tp, FD, &pb);
956        let nq = dec.len() / FD;
957        let hs = lin(m, "det.scoring.hs_proj.weight")?;
958        let hb = load_vec(m, "det.scoring.hs_proj.bias")?;
959        let mut q = vec![0f32; nq * FD];
960        hs.matmat_dev(dec, nq, &mut q, pool);
961        add_bias(&mut q, FD, &hb);
962        let scale = 1.0 / (FD as f32).sqrt();
963        Ok(q
964            .chunks(FD)
965            .map(|r| {
966                let mut acc = 0f32;
967                for d in 0..FD {
968                    acc += r[d] * tp[d];
969                }
970                (acc * scale).clamp(-12.0, 12.0)
971            })
972            .collect())
973    }
974
975    // ── mask decoder ────────────────────────────────────────────────
976
977    /// Prompt cross-attention over the encoder states, pixel decoder
978    /// (nearest upsample + sum + conv3x3 + GroupNorm + ReLU), then
979    /// pred_masks[q] = einsum(mask_embed[q], instance_embed).
980    #[allow(clippy::too_many_arguments)]
981    fn mask_decoder(
982        &self,
983        queries: &[f32],
984        enc: &[f32],
985        fpn: &[Vec<f32>],
986        text: &[f32],
987        am: &[u8],
988        pool: Option<&Pool>,
989    ) -> Result<Vec<f32>> {
990        let m = &self.model;
991        let db = "det.seghead.";
992        let n = enc.len() / FD;
993        let mut km = vec![0f32; SS];
994        for (k, &v) in am.iter().enumerate() { km[k] = if v == 0 { NEG } else { 0.0 }; }
995        let nw = load_vec(m, &format!("{db}cross_attn_norm.weight"))?;
996        let nb = load_vec(m, &format!("{db}cross_attn_norm.bias"))?;
997        let mut h = enc.to_vec();
998        layer_norm_rows(&mut h, &nw, &nb, D_EPS);
999        let qkv = lin(m, &format!("{db}cross_attend_prompt.in_proj_weight"))?;
1000        let ib = load_vec(m, &format!("{db}cross_attend_prompt.in_proj_bias"))?;
1001        let op = lin(m, &format!("{db}cross_attend_prompt.out_proj.weight"))?;
1002        let ob = load_vec(m, &format!("{db}cross_attend_prompt.out_proj.bias"))?;
1003        let mut tsm = StageTimer::new();
1004        let mut e = enc.to_vec();
1005        let mut ao = vec![0f32; n * FD];
1006        run_attn(&qkv, &ib, &op, &ob, &h, text, text, n, SS, FD, FH, None, Mask::Key(&km), pool, &mut ao);
1007        for (a, c) in e.iter_mut().zip(&ao) { *a += *c; }
1008        tsm.lap("msk_cross_attn");
1009        // pixel decoder: encoder states replace level 2 (72), then upsample
1010        let l72 = rows_to_chw(&e, GRID, GRID);
1011        let sizes = [(144usize, 144usize), (288, 288)];
1012        let mut prev = l72;
1013        for (li, &(sh, sw)) in sizes.iter().enumerate() {
1014            let _pp = crate::cpuprof::spans::span("mask.pixdec");
1015            prev = upsample_nearest(&prev, FD, sh / 2, sh / 2, sh, sw);
1016            let fw = &fpn[1 - li]; // reversed(fpn[:-1]): 144 then 288
1017            for (a, b) in prev.iter_mut().zip(fw.iter()) { *a += *b; }
1018            let cw = load_vec(m, &format!("{db}pixel_decoder.conv_layers.{li}.weight"))?;
1019            let cb = load_vec(m, &format!("{db}pixel_decoder.conv_layers.{li}.bias"))?;
1020            prev = conv2d(&cw, &cb, &prev, FD, sh, sw, 3, 3, 1, 1, pool);
1021            let gw = load_vec(m, &format!("{db}pixel_decoder.norms.{li}.weight"))?;
1022            let gb = load_vec(m, &format!("{db}pixel_decoder.norms.{li}.bias"))?;
1023            group_norm(&mut prev, 8, &gw, &gb, 1e-5);
1024            prev.iter_mut().for_each(|v| *v = v.max(0.0));
1025            drop(_pp);
1026        }
1027        tsm.lap("msk_pixel_dec");
1028        let iw = load_vec(m, &format!("{db}instance_seg_head.weight"))?;
1029        let ib2 = load_vec(m, &format!("{db}instance_seg_head.bias"))?;
1030        let inst = conv2d(&iw, &ib2, &prev, FD, MH, MH, 1, 1, 1, 0, pool);
1031        // mask embeddings from the (already output-normed) queries
1032        let mut q = queries.to_vec();
1033        for i in 0..3 {
1034            let w = lin(m, &format!("{db}mask_predictor.mask_embed.layers.{i}.weight"))?;
1035            let b = load_vec(m, &format!("{db}mask_predictor.mask_embed.layers.{i}.bias"))?;
1036            let mut o = vec![0f32; NQ * FD];
1037            w.matmat_dev(&q, NQ, &mut o, pool);
1038            add_bias(&mut o, FD, &b);
1039            if i < 2 { o.iter_mut().for_each(|v| *v = v.max(0.0)); }
1040            q = o;
1041        }
1042        tsm.lap("msk_inst_head");
1043        let hw = MH * MH;
1044        let _pe = crate::cpuprof::spans::span("mask.einsum");
1045        if let Some(out) = crate::gpu::sam3_mm(&q, &inst, NQ, FD, hw) {
1046            drop(_pe);
1047            tsm.lap("msk_einsum");
1048            return Ok(out);
1049        }
1050        let mut out = vec![0f32; NQ * hw];
1051        let ob2 = out.as_mut_ptr() as usize;
1052        let run = |s: usize, e: usize| {
1053            let o = unsafe { std::slice::from_raw_parts_mut(ob2 as *mut f32, NQ * hw) };
1054            for qi in s..e {
1055                let qq = &q[qi * FD..(qi + 1) * FD];
1056                let dst = &mut o[qi * hw..(qi + 1) * hw];
1057                for c in 0..FD {
1058                    let wgt = qq[c];
1059                    if wgt == 0.0 { continue; }
1060                    let ic = &inst[c * hw..(c + 1) * hw];
1061                    for p in 0..hw { dst[p] += wgt * ic[p]; }
1062                }
1063            }
1064        };
1065        match pool { Some(p) => p.run_rows(NQ, &run), None => run(0, NQ) }
1066        drop(_pe);
1067        tsm.lap("msk_einsum");
1068        Ok(out)
1069    }
1070}
1071
1072/// `Sam3VisionNeck` (`Sam3FPNLayer` stack) over the trunk map: the first
1073/// `n_levels` pyramid levels at 288/144/72/36, each [256, H, W]
1074/// channels-first. The DETR path uses all four; the video tracker's neck
1075/// (`fpn.sam2_convs`) only consumes the first three.
1076pub(crate) fn fpn_levels(
1077    m: &Arc<CmfModel>,
1078    p: &str,
1079    trunk: &[f32],
1080    pool: Option<&Pool>,
1081    n_levels: usize,
1082) -> Result<Vec<Vec<f32>>> {
1083    let hidden = rows_to_chw(trunk, GRID, GRID); // [1024,72,72]
1084    let scales = [4.0f32, 2.0, 1.0, 0.5];
1085    let mut levels = Vec::with_capacity(n_levels);
1086    let _p = crate::cpuprof::spans::span("fpn.levels");
1087    for (i, &s) in scales.iter().enumerate().take(n_levels) {
1088        let (mut ci, mut ch, mut cw) = (TD, GRID, GRID);
1089        let mut cur = hidden.clone();
1090        match s {
1091            4.0 => {
1092                let w0 = load_vec(m, &format!("{p}.{i}.dconv_2x2_0.weight"))?;
1093                let b0 = load_vec(m, &format!("{p}.{i}.dconv_2x2_0.bias"))?;
1094                cur = convt2x2(&w0, &b0, &cur, ci, ch, cw, pool);
1095                (ch, cw, ci) = (ch * 2, cw * 2, b0.len());
1096                gelu_slice(&mut cur);
1097                let w1 = load_vec(m, &format!("{p}.{i}.dconv_2x2_1.weight"))?;
1098                let b1 = load_vec(m, &format!("{p}.{i}.dconv_2x2_1.bias"))?;
1099                cur = convt2x2(&w1, &b1, &cur, ci, ch, cw, pool);
1100                (ch, cw, ci) = (ch * 2, cw * 2, b1.len());
1101            }
1102            2.0 => {
1103                let w0 = load_vec(m, &format!("{p}.{i}.dconv_2x2.weight"))?;
1104                let b0 = load_vec(m, &format!("{p}.{i}.dconv_2x2.bias"))?;
1105                cur = convt2x2(&w0, &b0, &cur, ci, ch, cw, pool);
1106                (ch, cw, ci) = (ch * 2, cw * 2, b0.len());
1107            }
1108            1.0 => {}
1109            _ => {
1110                cur = maxpool2(&cur, ci, ch, cw);
1111                (ch, cw) = (ch / 2, cw / 2);
1112            }
1113        }
1114        let w1 = load_vec(m, &format!("{p}.{i}.conv_1x1.weight"))?;
1115        let b1 = load_vec(m, &format!("{p}.{i}.conv_1x1.bias"))?;
1116        cur = conv2d(&w1, &b1, &cur, ci, ch, cw, 1, 1, 1, 0, pool);
1117        ci = b1.len();
1118        let w3 = load_vec(m, &format!("{p}.{i}.conv_3x3.weight"))?;
1119        let b3 = load_vec(m, &format!("{p}.{i}.conv_3x3.bias"))?;
1120        cur = conv2d(&w3, &b3, &cur, ci, ch, cw, 3, 3, 1, 1, pool);
1121        levels.push(cur);
1122    }
1123    Ok(levels)
1124}
1125
1126// ───────────────────── model pieces ─────────────────────
1127
1128/// Sam3DecoderMLP, 2 layers: relu(l1), l2 (with biases).
1129struct DecoderMlp {
1130    w0: QTensor,
1131    b0: Vec<f32>,
1132    w1: QTensor,
1133    b1: Vec<f32>,
1134}
1135
1136impl DecoderMlp {
1137    fn load(m: &Arc<CmfModel>, prefix: &str) -> Result<Self> {
1138        Ok(Self {
1139            w0: lin(m, &format!("{prefix}layers.0.weight"))?,
1140            b0: load_vec(m, &format!("{prefix}layers.0.bias"))?,
1141            w1: lin(m, &format!("{prefix}layers.1.weight"))?,
1142            b1: load_vec(m, &format!("{prefix}layers.1.bias"))?,
1143        })
1144    }
1145    fn forward(&self, x: &[f32], rows: usize, pool: Option<&Pool>, out_w: usize) -> Vec<f32> {
1146        let mut h = vec![0f32; rows * self.b0.len()];
1147        self.w0.matmat_dev(x, rows, &mut h, pool);
1148        add_bias(&mut h, self.b0.len(), &self.b0);
1149        h.iter_mut().for_each(|v| *v = v.max(0.0));
1150        let mut o = vec![0f32; rows * out_w];
1151        self.w1.matmat_dev(&h, rows, &mut o, pool);
1152        add_bias(&mut o, out_w, &self.b1);
1153        o
1154    }
1155}
1156
1157/// Sam3DecoderMLP, 3 layers: relu(l1), relu(l2), l3 (box head).
1158struct DecoderMlp3 {
1159    w0: QTensor,
1160    b0: Vec<f32>,
1161    w1: QTensor,
1162    b1: Vec<f32>,
1163    w2: QTensor,
1164    b2: Vec<f32>,
1165}
1166
1167impl DecoderMlp3 {
1168    fn load3(m: &Arc<CmfModel>, prefix: &str) -> Result<Self> {
1169        Ok(Self {
1170            w0: lin(m, &format!("{prefix}layers.0.weight"))?,
1171            b0: load_vec(m, &format!("{prefix}layers.0.bias"))?,
1172            w1: lin(m, &format!("{prefix}layers.1.weight"))?,
1173            b1: load_vec(m, &format!("{prefix}layers.1.bias"))?,
1174            w2: lin(m, &format!("{prefix}layers.2.weight"))?,
1175            b2: load_vec(m, &format!("{prefix}layers.2.bias"))?,
1176        })
1177    }
1178    fn forward(&self, x: &[f32], rows: usize, pool: Option<&Pool>) -> Vec<f32> {
1179        let mut d = vec![0f32; rows * self.b0.len()];
1180        self.w0.matmat_dev(x, rows, &mut d, pool);
1181        add_bias(&mut d, self.b0.len(), &self.b0);
1182        d.iter_mut().for_each(|v| *v = v.max(0.0));
1183        let mut d2 = vec![0f32; rows * self.b1.len()];
1184        self.w1.matmat_dev(&d, rows, &mut d2, pool);
1185        add_bias(&mut d2, self.b1.len(), &self.b1);
1186        d2.iter_mut().for_each(|v| *v = v.max(0.0));
1187        let mut o = vec![0f32; rows * self.b2.len()];
1188        self.w2.matmat_dev(&d2, rows, &mut o, pool);
1189        add_bias(&mut o, self.b2.len(), &self.b2);
1190        o
1191    }
1192}
1193
1194pub(crate) fn sigm(x: f32) -> f32 {
1195    1.0 / (1.0 + (-x).exp())
1196}
1197
1198fn inv_sigmoid(x: f32) -> f32 {
1199    let x = x.clamp(0.0, 1.0);
1200    ((x.max(1e-3)) / ((1.0 - x).max(1e-3))).ln()
1201}
1202
1203fn xyxy(boxes: &[[f32; 4]]) -> Vec<f32> {
1204    let mut out = vec![0f32; boxes.len() * 4];
1205    for (i, b) in boxes.iter().enumerate() {
1206        out[i * 4] = b[0] - 0.5 * b[2];
1207        out[i * 4 + 1] = b[1] - 0.5 * b[3];
1208        out[i * 4 + 2] = b[0] + 0.5 * b[2];
1209        out[i * 4 + 3] = b[1] + 0.5 * b[3];
1210    }
1211    out
1212}
1213
1214pub(crate) fn lin(m: &Arc<CmfModel>, name: &str) -> Result<QTensor> {
1215    let _p = crate::cpuprof::spans::span("qtensor.wrap");
1216    QTensor::from_model(m, name).map_err(|e| anyhow!(e))
1217}
1218
1219/// Dequantize a tensor to flat f32 (norms, biases, tables, convs).
1220pub(crate) fn load_vec(m: &Arc<CmfModel>, name: &str) -> Result<Vec<f32>> {
1221    let _p = crate::cpuprof::spans::span("load.decode");
1222    let e = m.tensor(name).ok_or_else(|| anyhow!("tensor '{name}' not found"))?;
1223    if matches!(e.dtype, TensorDtype::U8) { return Err(anyhow!("'{name}' is u8")); }
1224    let bytes = m.entry_bytes(e);
1225    let mut dst = vec![0f32; e.n_elems()];
1226    dequant_tensor(e, bytes, &mut dst).map_err(|er| anyhow!("{name}: {er}"))?;
1227    Ok(dst)
1228}
1229
1230/// `gelu_erf` over a whole buffer, one `SAM3_PROF` span for the loop.
1231pub(crate) fn gelu_slice(v: &mut [f32]) {
1232    let _p = crate::cpuprof::spans::span("op.gelu");
1233    v.iter_mut().for_each(|x| *x = gelu_erf(*x));
1234}
1235
1236/// Row-major [rows, cols] += bias (broadcast over rows).
1237pub(crate) fn add_bias(out: &mut [f32], cols: usize, bias: &[f32]) {
1238    debug_assert_eq!(bias.len(), cols);
1239    for r in out.chunks_exact_mut(cols) {
1240        for (v, b) in r.iter_mut().zip(bias) { *v += *b; }
1241    }
1242}
1243
1244/// LayerNorm over rows of `x` (row length = w.len()).
1245pub(crate) fn layer_norm_rows(x: &mut [f32], w: &[f32], b: &[f32], eps: f32) {
1246    let _p = crate::cpuprof::spans::span("op.layernorm");
1247    let d = w.len();
1248    for r in x.chunks_exact_mut(d) {
1249        let mean = r.iter().sum::<f32>() / d as f32;
1250        let var = r.iter().map(|v| (v - mean) * (v - mean)).sum::<f32>() / d as f32;
1251        let inv = 1.0 / (var + eps).sqrt();
1252        for (v, (&ww, &bb)) in r.iter_mut().zip(w.iter().zip(b.iter())) {
1253            *v = (*v - mean) * inv * ww + bb;
1254        }
1255    }
1256}
1257
1258/// Axial 2D RoPE in place on a fused QKV block: rotates the q part
1259/// (dims [0, dim)) and the k part ([dim, 2*dim)); v untouched. freqs_cis
1260/// = [n, 32, 2] = (cos, sin) per pair; pairs 0..15 from w-position,
1261/// 16..31 from h-position; per head block of 64 dims (16 heads share the
1262/// same position-dependent table).
1263fn apply_rope(buf: &mut [f32], n: usize, stride: usize, width: usize, fc: &[f32]) {
1264    let npairs = 32;
1265    debug_assert_eq!(fc.len(), n * npairs * 2);
1266    let blocks = width / 64;
1267    for i in 0..n {
1268        let f = &fc[i * npairs * 2..(i + 1) * npairs * 2];
1269        let row = &mut buf[i * stride..i * stride + width];
1270        for b in 0..blocks {
1271            let base = b * 64;
1272            for j in 0..npairs {
1273                let (c, s) = (f[j * 2], f[j * 2 + 1]);
1274                let (a, d) = (row[base + j * 2], row[base + j * 2 + 1]);
1275                row[base + j * 2] = a * c - d * s;
1276                row[base + j * 2 + 1] = d * c + a * s;
1277            }
1278        }
1279    }
1280}
1281
1282/// RAII bypass of the f16-staged coop kernel for the calling thread —
1283/// the attention arm needs the pure-f32 scalar GEMM to stay inside the
1284/// parity gate (the coop kernel rounds operands to f16: measured ~1e-3
1285/// per-op, which compounds through a 32-layer trunk to rel 0.36).
1286struct CoopBypass;
1287
1288impl CoopBypass {
1289    fn new() -> Self {
1290        #[cfg(feature = "gpu")]
1291        crate::gpu_wgpu::COOP_BYPASS.with(|b| b.set(true));
1292        Self
1293    }
1294}
1295
1296impl Drop for CoopBypass {
1297    fn drop(&mut self) {
1298        #[cfg(feature = "gpu")]
1299        crate::gpu_wgpu::COOP_BYPASS.with(|b| b.set(false));
1300    }
1301}
1302
1303/// GPU arm for `run_attn`'s core (QKᵀ softmax A·V), owner GPU port.
1304///
1305/// Per head: Q/K/V rows are packed contiguous, QKᵀ and A·V run as f32
1306/// `gemm_nt_f32` GEMMs (transient both operands are activations), the
1307/// scale/mask/softmax step stays on the CPU in exactly the scalar arm's
1308/// order — only the f32 dot-product summation order differs (allowed:
1309/// cos >= 0.999 vs the CPU arm). Returns false on ANY refusal — backend
1310/// down, `CMF_GPU=0`, inside `cpu_scope`, job under the GEMM floor, a
1311/// device decline mid-loop — and leaves `out` untouched, so the caller
1312/// falls back to the scalar arm. `CMF_SAM3_GPU=0` disables the arm.
1313#[allow(clippy::too_many_arguments)]
1314fn attn_core_gpu(
1315    qkv_q: &[f32],
1316    k: &[f32],
1317    v: &[f32],
1318    n_q: usize,
1319    n_k: usize,
1320    dim: usize,
1321    heads: usize,
1322    mask: Mask<'_>,
1323    scale: f32,
1324    out: &mut [f32],
1325) -> bool {
1326    if std::env::var("CMF_SAM3_GPU").as_deref() == Ok("0") {
1327        return false;
1328    }
1329    {
1330        let (mode, mt): (i32, &[f32]) = match mask {
1331            Mask::None => (0, &[]),
1332            Mask::Key(km) => (1, km),
1333            Mask::Add(am) => (2, am),
1334            Mask::Head(hm) => (3, hm),
1335        };
1336        if n_q * n_k * (dim / heads.max(1)) >= 1 << 20
1337            && crate::gpu::sam3_attn_core(qkv_q, k, v, n_q, n_k, dim, heads, mode, mt, scale, out)
1338        {
1339            return true;
1340        }
1341        // an unmasked self-attention (the DETR encoder's) on the device's
1342        // flash path over head-major planes: Vulkan and Metal
1343        let hd = dim / heads.max(1);
1344        if mode == 0 && n_q == n_k && hd * heads == dim && n_q * n_k * hd >= 1 << 24 && crate::gpu::enabled_here() {
1345            let h3 = dim * 3;
1346            let plane = |src: &[f32], off: usize| -> Vec<f32> {
1347                let mut p = vec![0f32; heads * n_q * hd];
1348                for t in 0..heads {
1349                    for i in 0..n_q {
1350                        p[(t * n_q + i) * hd..(t * n_q + i + 1) * hd].copy_from_slice(&src[i * h3 + off + t * hd..i * h3 + off + (t + 1) * hd]);
1351                    }
1352                }
1353                p
1354            };
1355            let (qh, kh, vh) = (plane(qkv_q, 0), plane(k, dim), plane(v, 2 * dim));
1356            if crate::gpu::dit_attention(&qh, &kh, &vh, heads, heads, n_q, hd, scale, out) {
1357                return true;
1358            }
1359        }
1360    }
1361    #[cfg(feature = "gpu")]
1362    {
1363        if !crate::gpu::enabled_here() {
1364            return false;
1365        }
1366        let hd = dim / heads;
1367        if hd == 0 || out.len() < n_q * dim {
1368            return false;
1369        }
1370        // Same floor gemm_nt enforces, checked before any packing: both
1371        // GEMMs carry the identical n_q * n_k * hd MAC product.
1372        if n_q.saturating_mul(n_k).saturating_mul(hd) < (1 << 22) {
1373            return false;
1374        }
1375        let h3 = dim * 3;
1376        // Q/K packed [.., hd] rows; V packed transposed (rows = hd) so
1377        // A·V is the same NT GEMM: out[n_q, hd] = A[n_q, n_k]·Vᵀ[hd, n_k].
1378        let _byp = CoopBypass::new();
1379        let mut qpk = vec![0f32; n_q * hd];
1380        let mut kpk = vec![0f32; n_k * hd];
1381        let mut vtp = vec![0f32; hd * n_k];
1382        let mut raw = vec![0f32; n_q * n_k];
1383        let mut outt = vec![0f32; n_q * hd];
1384        let mut acc = vec![0f32; n_q * dim];
1385        // The pure-f32 scalar arm refuses grids over 2^22 workgroups (a
1386        // hang guard) — QKᵀ over a big square (n_q * n_k) is chunked
1387        // along query rows; output rows are independent, so chunking
1388        // changes nothing but the dispatch.
1389        let qk_chunk = ((1usize << 22) / n_k.max(1)).max(1);
1390        for t in 0..heads {
1391            let off = t * hd;
1392            for i in 0..n_q {
1393                qpk[i * hd..(i + 1) * hd]
1394                    .copy_from_slice(&qkv_q[i * h3 + off..i * h3 + off + hd]);
1395            }
1396            for j in 0..n_k {
1397                kpk[j * hd..(j + 1) * hd]
1398                    .copy_from_slice(&k[j * h3 + dim + off..j * h3 + dim + off + hd]);
1399            }
1400            for d in 0..hd {
1401                let rowd = &mut vtp[d * n_k..(d + 1) * n_k];
1402                for (j, rv) in rowd.iter_mut().enumerate() {
1403                    *rv = v[j * h3 + 2 * dim + off + d];
1404                }
1405            }
1406            // QKᵀ: raw[i, j] = qpk[i]·kpk[j]  (chunked over query rows)
1407            let mut i0 = 0usize;
1408            while i0 < n_q {
1409                let i1 = (i0 + qk_chunk).min(n_q);
1410                if !crate::gpu_wgpu::gemm_nt_f32_transient(
1411                    &qpk[i0 * hd..i1 * hd],
1412                    &kpk,
1413                    &mut raw[i0 * n_k..i1 * n_k],
1414                    i1 - i0,
1415                    hd,
1416                    n_k,
1417                ) {
1418                    return false;
1419                }
1420                i0 = i1;
1421            }
1422            // scale + mask + stable softmax — the scalar arm's order.
1423            let mut rowmax = vec![0f32; n_q];
1424            for i in 0..n_q {
1425                let base = i * n_k;
1426                let mut mx = f32::NEG_INFINITY;
1427                for j in 0..n_k {
1428                    let mut val = raw[base + j] * scale;
1429                    val += match mask {
1430                        Mask::None => 0.0,
1431                        Mask::Key(km) => km[j],
1432                        Mask::Add(am) => am[i * n_k + j],
1433                        Mask::Head(hm) => hm[(t * n_q + i) * n_k + j],
1434                    };
1435                    raw[base + j] = val;
1436                    if val > mx {
1437                        mx = val;
1438                    }
1439                }
1440                rowmax[i] = mx;
1441                let mut sum = 0.0f32;
1442                for j in 0..n_k {
1443                    let e = (raw[base + j] - mx).exp();
1444                    raw[base + j] = e;
1445                    sum += e;
1446                }
1447                let inv = 1.0 / sum;
1448                for j in 0..n_k {
1449                    raw[base + j] *= inv;
1450                }
1451            }
1452            // A·V: outt[i, d] = raw[i]·vtp[d]
1453            if !crate::gpu_wgpu::gemm_nt_f32_transient(&raw, &vtp, &mut outt, n_q, n_k, hd) {
1454                return false;
1455            }
1456            for i in 0..n_q {
1457                acc[i * dim + off..i * dim + off + hd]
1458                    .copy_from_slice(&outt[i * hd..(i + 1) * hd]);
1459            }
1460        }
1461        out.copy_from_slice(&acc);
1462        true
1463    }
1464    #[cfg(not(feature = "gpu"))]
1465    {
1466        let _ = (qkv_q, k, v, n_q, n_k, dim, heads, mask, scale, out);
1467        false
1468    }
1469}
1470
1471/// Multi-head attention for one sequence: fused QKV projection
1472/// (`w_qkv` rows = 3*dim laid out [q | k | v] per row, `qb` its bias),
1473/// optional axial RoPE on q/k, additive mask, softmax, output projection
1474/// (`w_o` + `ob`). `out` is [n_q, dim]; scale = head_dim^-0.5.
1475#[allow(clippy::too_many_arguments)]
1476pub(crate) fn run_attn(
1477    w_qkv: &QTensor,
1478    qb: &[f32],
1479    w_o: &QTensor,
1480    ob: &[f32],
1481    xs_q: &[f32],
1482    xs_k: &[f32],
1483    xs_v: &[f32],
1484    n_q: usize,
1485    n_k: usize,
1486    dim: usize,
1487    heads: usize,
1488    rope: Option<&[f32]>,
1489    mask: Mask,
1490    pool: Option<&Pool>,
1491    out: &mut [f32],
1492) {
1493    let h3 = dim * 3;
1494    let hd = dim / heads;
1495    let scale = 1.0 / (hd as f32).sqrt();
1496    let _tp = std::time::Instant::now();
1497    let mut qkv_q = vec![0f32; n_q * h3];
1498    let _pg = crate::cpuprof::spans::span("attn.gemm");
1499    w_qkv.matmat_dev(xs_q, n_q, &mut qkv_q, pool);
1500    add_bias(&mut qkv_q, h3, qb);
1501    let same_k = xs_k.as_ptr() == xs_q.as_ptr();
1502    let mut kbuf = Vec::new();
1503    if !same_k {
1504        kbuf = vec![0f32; n_k * h3];
1505        w_qkv.matmat_dev(xs_k, n_k, &mut kbuf, pool);
1506        add_bias(&mut kbuf, h3, qb);
1507    }
1508    let same_v = xs_v.as_ptr() == xs_q.as_ptr();
1509    let mut vbuf = Vec::new();
1510    if !same_v {
1511        vbuf = vec![0f32; n_k * h3];
1512        w_qkv.matmat_dev(xs_v, n_k, &mut vbuf, pool);
1513        add_bias(&mut vbuf, h3, qb);
1514    }
1515    drop(_pg);
1516    if let Some(fc) = rope {
1517        // rotate q (and k when they share the buffer) over the first 2*dim dims
1518        apply_rope(&mut qkv_q, n_q, h3, dim * 2, fc);
1519        if !same_k {
1520            apply_rope(&mut kbuf, n_k, h3, dim * 2, fc);
1521        }
1522    }
1523    ATT_PROJ_NS.fetch_add(_tp.elapsed().as_nanos() as u64, Ordering::Relaxed);
1524    let _tc = std::time::Instant::now();
1525    let qkv_k: &[f32] = if same_k { &qkv_q } else { &kbuf };
1526    let qkv_v: &[f32] = if same_v { &qkv_q } else { &vbuf };
1527    let mut attn = vec![0f32; n_q * dim];
1528    if attn_core_gpu(&qkv_q, qkv_k, qkv_v, n_q, n_k, dim, heads, mask, scale, &mut attn) {
1529        ATT_CORE_NS.fetch_add(_tc.elapsed().as_nanos() as u64, Ordering::Relaxed);
1530        let _tw = std::time::Instant::now();
1531        w_o.matmat_dev(&attn, n_q, out, pool);
1532        add_bias(out, dim, ob);
1533        ATT_PROJ_NS.fetch_add(_tw.elapsed().as_nanos() as u64, Ordering::Relaxed);
1534        return;
1535    }
1536    let ab = attn.as_mut_ptr() as usize;
1537    let _pc = crate::cpuprof::spans::span("attn.core");
1538    // Attention core as two packed GEMMs per head over each row chunk —
1539    // QKᵀ then softmax then AV — instead of the per-(row, head) scalar
1540    // loops with a dot()/axpy() call per key. matrixmultiply packs K/V
1541    // once per call (the old code rebuilt a hd-wide dot and re-sliced a
1542    // strided V row n_q×heads×n_k times: 1.0G+ tiny calls/frame at
1543    // ~115 µs per (row, head) group). Per-element mask/softmax values are
1544    // unchanged; only the reduction ORDER differs (gates are numeric).
1545    let run = |s: usize, e: usize| {
1546        if s >= e {
1547            return;
1548        }
1549        let a = unsafe { std::slice::from_raw_parts_mut(ab as *mut f32, n_q * dim) };
1550        let rows = e - s;
1551        let mut scores = vec![0f32; rows * n_k];
1552        let prof = crate::cpuprof::spans::on();
1553        for t in 0..heads {
1554            let tq = prof.then(std::time::Instant::now);
1555            // C[rows, n_k] = scale · Q[rows, hd] × Kᵀ (K head rows, stride h3)
1556            crate::qtensor::sgemm_public(
1557                rows,
1558                n_k,
1559                hd,
1560                scale,
1561                &qkv_q[s * h3 + t * hd..],
1562                h3,
1563                &qkv_k[dim + t * hd..],
1564                h3,
1565                true,
1566                &mut scores,
1567                n_k,
1568            );
1569            match mask {
1570                Mask::None => {}
1571                Mask::Key(km) => {
1572                    for r in 0..rows {
1573                        let sr = &mut scores[r * n_k..(r + 1) * n_k];
1574                        for (v, &m) in sr.iter_mut().zip(km) {
1575                            *v += m;
1576                        }
1577                    }
1578                }
1579                Mask::Add(am) => {
1580                    for (r, i) in (s..e).enumerate() {
1581                        let sr = &mut scores[r * n_k..(r + 1) * n_k];
1582                        for (v, &m) in sr.iter_mut().zip(&am[i * n_k..(i + 1) * n_k]) {
1583                            *v += m;
1584                        }
1585                    }
1586                }
1587                Mask::Head(hm) => {
1588                    for (r, i) in (s..e).enumerate() {
1589                        let base = (t * n_q + i) * n_k;
1590                        let sr = &mut scores[r * n_k..(r + 1) * n_k];
1591                        for (v, &m) in sr.iter_mut().zip(&hm[base..base + n_k]) {
1592                            *v += m;
1593                        }
1594                    }
1595                }
1596            }
1597            let tm = prof.then(std::time::Instant::now);
1598            // Stable softmax: the trunk's ViT scores reach ~155, so a
1599            // raw exp() overflows to inf for the row-max and the sum
1600            // turns inf → inv = 0 → the whole attention row silently
1601            // collapses to zeros. Subtract the row max (`mx`).
1602            for r in 0..rows {
1603                let sr = &mut scores[r * n_k..(r + 1) * n_k];
1604                let mut mx = f32::NEG_INFINITY;
1605                for &v in sr.iter() {
1606                    if v > mx {
1607                        mx = v;
1608                    }
1609                }
1610                let mut sum = 0.0f32;
1611                for v in sr.iter_mut() {
1612                    *v = (*v - mx).exp();
1613                    sum += *v;
1614                }
1615                let inv = 1.0 / sum;
1616                for v in sr.iter_mut() {
1617                    *v *= inv;
1618                }
1619            }
1620            let ta = prof.then(std::time::Instant::now);
1621            // C[rows, hd] = S[rows, n_k] × V_head (rows stride h3) → out
1622            crate::qtensor::sgemm_public(
1623                rows,
1624                hd,
1625                n_k,
1626                1.0,
1627                &scores,
1628                n_k,
1629                &qkv_v[2 * dim + t * hd..],
1630                h3,
1631                false,
1632                &mut a[s * dim + t * hd..],
1633                dim,
1634            );
1635            if let (Some(t0), Some(t1), Some(t2)) = (tq, tm, ta) {
1636                let t3 = std::time::Instant::now();
1637                crate::cpuprof::spans::add("attn.qk", t1 - t0);
1638                crate::cpuprof::spans::add("attn.sm", t2 - t1);
1639                crate::cpuprof::spans::add("attn.av", t3 - t2);
1640            }
1641        }
1642    };
1643    match pool { Some(p) => p.run_rows(n_q, &run), None => run(0, n_q) }
1644    drop(_pc);
1645    let _pg = crate::cpuprof::spans::span("attn.gemm");
1646    ATT_CORE_NS.fetch_add(_tc.elapsed().as_nanos() as u64, Ordering::Relaxed);
1647    let _tw = std::time::Instant::now();
1648    w_o.matmat_dev(&attn, n_q, out, pool);
1649    add_bias(out, dim, ob);
1650    ATT_PROJ_NS.fetch_add(_tw.elapsed().as_nanos() as u64, Ordering::Relaxed);
1651}
1652
1653// ─────────── convolutions (NCHW f32, explicit shapes) ───────────
1654
1655pub(crate) fn conv2d(
1656    w: &[f32],
1657    b: &[f32],
1658    x: &[f32],
1659    ci: usize,
1660    h: usize,
1661    wid: usize,
1662    kh: usize,
1663    kw: usize,
1664    stride: usize,
1665    pad: usize,
1666    pool: Option<&Pool>,
1667) -> Vec<f32> {
1668    let co = b.len();
1669    debug_assert_eq!(w.len(), co * ci * kh * kw);
1670    debug_assert_eq!(x.len(), ci * h * wid);
1671    let oh = (h + 2 * pad - kh) / stride + 1;
1672    let ow = (wid + 2 * pad - kw) / stride + 1;
1673    let _p = crate::cpuprof::spans::span("op.conv2d");
1674    // the device takes the large ones (the transfer outweighs a small one)
1675    if co * oh * ow * ci * kh * kw >= 1 << 25
1676        && let Some(o) = crate::gpu::sam3_conv2d(w, b, x, ci, h, wid, kh, kw, stride, pad)
1677    {
1678        return o;
1679    }
1680    let mut out = vec![0f32; co * oh * ow];
1681    let ob = out.as_mut_ptr() as usize;
1682    // One output ROW per unit instead of one pixel: the (c, dy, dx)
1683    // accumulation order per element is unchanged (results stay bit-exact),
1684    // but the innermost loop becomes a contiguous `orow[lo..hi] += w *
1685    // xrow[..]` slice that auto-vectorizes — the pixel loop fed LLVM a
1686    // strided load, a div/mod for (oy, ox) and two bounds checks per tap,
1687    // and ran ~50% of the SAM3 image forward scalar.
1688    let run = |s: usize, e: usize| {
1689        let o = unsafe { std::slice::from_raw_parts_mut(ob as *mut f32, co * oh * ow) };
1690        for r in s..e {
1691            let c_o = r / oh;
1692            let oy = r % oh;
1693            let obase = c_o * oh * ow + oy * ow;
1694            let orow = &mut o[obase..obase + ow];
1695            orow.fill(b[c_o]);
1696            for c in 0..ci {
1697                for dy in 0..kh {
1698                    let iy = oy * stride + dy;
1699                    if iy < pad || iy - pad >= h { continue; }
1700                    let xrow = &x[(c * h + iy - pad) * wid..][..wid];
1701                    for dx in 0..kw {
1702                        let wv = w[((c_o * ci + c) * kh + dy) * kw + dx];
1703                        // ox with 0 <= ox*stride + dx - pad < wid, 0 <= ox < ow
1704                        let lo = if pad > dx {
1705                            (pad - dx).div_ceil(stride)
1706                        } else {
1707                            0
1708                        };
1709                        if lo >= ow { continue; }
1710                        let hi_excl = (pad + wid - dx).div_ceil(stride).min(ow);
1711                        if lo >= hi_excl { continue; }
1712                        if stride == 1 {
1713                            // vectorizable: both slices are contiguous
1714                            let xo = lo + dx - pad;
1715                            let hi = hi_excl;
1716                            for (a, b) in orow[lo..hi].iter_mut().zip(&xrow[xo..xo + (hi - lo)]) {
1717                                *a += wv * *b;
1718                            }
1719                        } else {
1720                            for ox in lo..hi_excl {
1721                                orow[ox] += wv * xrow[ox * stride + dx - pad];
1722                            }
1723                        }
1724                    }
1725                }
1726            }
1727        }
1728    };
1729    match pool { Some(p) => p.run_rows(co * oh, &run), None => run(0, co * oh) }
1730    out
1731}
1732
1733/// ConvTranspose2d(k=2, s=2): w is [ci, co, 2, 2]; x is [ci, h, wid].
1734pub(crate) fn convt2x2(w: &[f32], b: &[f32], x: &[f32], ci: usize, h: usize, wid: usize, pool: Option<&Pool>) -> Vec<f32> {
1735    let co = b.len();
1736    debug_assert_eq!(w.len(), ci * co * 4);
1737    let (oh, ow) = (h * 2, wid * 2);
1738    let _p = crate::cpuprof::spans::span("op.convt");
1739    if co * oh * ow * ci >= 1 << 25
1740        && let Some(o) = crate::gpu::sam3_convt2x2(w, b, x, ci, h, wid)
1741    {
1742        return o;
1743    }
1744    let mut out = vec![0f32; co * oh * ow];
1745    let ob = out.as_mut_ptr() as usize;
1746    // Per output row: (kh, kx) = (oy & 1, ox & 1), so even columns take
1747    // w[.., 0] and odd columns w[.., 1] — accumulate into two contiguous
1748    // scratch rows (vectorizable axpy over x, per-channel order kept →
1749    // bit-exact) and interleave once at the end.
1750    let run = |s: usize, e: usize| {
1751        let o = unsafe { std::slice::from_raw_parts_mut(ob as *mut f32, co * oh * ow) };
1752        let mut t0 = vec![0f32; wid];
1753        let mut t1 = vec![0f32; wid];
1754        for r in s..e {
1755            let c_o = r / oh;
1756            let oy = r % oh;
1757            let (slot, iy) = (oy & 1, oy >> 1);
1758            t0.fill(b[c_o]);
1759            t1.fill(b[c_o]);
1760            for c in 0..ci {
1761                let xrow = &x[(c * h + iy) * wid..][..wid];
1762                let wb = &w[(c * co + c_o) * 4 + slot * 2..][..2];
1763                let (w0, w1) = (wb[0], wb[1]);
1764                for (t, &xv) in t0.iter_mut().zip(xrow) {
1765                    *t += w0 * xv;
1766                }
1767                for (t, &xv) in t1.iter_mut().zip(xrow) {
1768                    *t += w1 * xv;
1769                }
1770            }
1771            let obase = c_o * oh * ow + oy * ow;
1772            for j in 0..wid {
1773                o[obase + 2 * j] = t0[j];
1774                o[obase + 2 * j + 1] = t1[j];
1775            }
1776        }
1777    };
1778    match pool { Some(p) => p.run_rows(co * oh, &run), None => run(0, co * oh) }
1779    out
1780}
1781
1782pub(crate) fn maxpool2(x: &[f32], ci: usize, h: usize, wid: usize) -> Vec<f32> {
1783    let (oh, ow) = (h / 2, wid / 2);
1784    let mut out = vec![0f32; ci * oh * ow];
1785    for c in 0..ci {
1786        for oy in 0..oh {
1787            for ox in 0..ow {
1788                let mut mx = f32::NEG_INFINITY;
1789                for dy in 0..2 {
1790                    for dx in 0..2 {
1791                        let v = x[(c * h + oy * 2 + dy) * wid + ox * 2 + dx];
1792                        if v > mx { mx = v; }
1793                    }
1794                }
1795                out[(c * oh + oy) * ow + ox] = mx;
1796            }
1797        }
1798    }
1799    out
1800}
1801
1802/// Nearest-neighbour upsample of [ci, h, wid] to [ci, sh, sw].
1803pub(crate) fn upsample_nearest(x: &[f32], ci: usize, h: usize, wid: usize, sh: usize, sw: usize) -> Vec<f32> {
1804    let mut out = vec![0f32; ci * sh * sw];
1805    for c in 0..ci {
1806        for oy in 0..sh {
1807            let iy = oy * h / sh;
1808            for ox in 0..sw {
1809                let ix = ox * wid / sw;
1810                out[(c * sh + oy) * sw + ox] = x[(c * h + iy) * wid + ix];
1811            }
1812        }
1813    }
1814    out
1815}
1816
1817/// GroupNorm(eps=1e-5) over channels of [c, h, w].
1818pub(crate) fn group_norm(x: &mut [f32], groups: usize, w: &[f32], b: &[f32], eps: f32) {
1819    let co = w.len();
1820    let gsz = co / groups;
1821    let rest = x.len() / co;
1822    for g in 0..groups {
1823        let s = g * gsz * rest;
1824        let e = s + gsz * rest;
1825        let mean = x[s..e].iter().sum::<f32>() / (e - s) as f32;
1826        let var = x[s..e].iter().map(|v| (v - mean) * (v - mean)).sum::<f32>() / (e - s) as f32;
1827        let inv = 1.0 / (var + eps).sqrt();
1828        for (i, v) in x[s..e].iter_mut().enumerate() {
1829            let ch = g * gsz + (i / rest);
1830            *v = (*v - mean) * inv * w[ch] + b[ch];
1831        }
1832    }
1833}
1834
1835// ─────────── layout helpers ───────────
1836
1837pub(crate) fn rows_to_chw(rows: &[f32], h: usize, w: usize) -> Vec<f32> {
1838    let _p = crate::cpuprof::spans::span("op.layout");
1839    let n = h * w;
1840    let c = rows.len() / n;
1841    let mut out = vec![0f32; c * h * w];
1842    for ch in 0..c {
1843        for y in 0..h {
1844            for x in 0..w { out[(ch * h + y) * w + x] = rows[(y * w + x) * c + ch]; }
1845        }
1846    }
1847    out
1848}
1849
1850pub(crate) fn chw_to_rows(chw: &[f32], h: usize, w: usize) -> Vec<f32> {
1851    let _p = crate::cpuprof::spans::span("op.layout");
1852    let c = chw.len() / (h * w);
1853    let mut out = vec![0f32; h * w * c];
1854    for ch in 0..c {
1855        for y in 0..h {
1856            for x in 0..w { out[(y * w + x) * c + ch] = chw[(ch * h + y) * w + x]; }
1857        }
1858    }
1859    out
1860}
1861
1862/// Normalized sine position encoding for an FPN level: rows [h*w, 2n]
1863/// (pos_y then pos_x), scale 2π, temperature 10000.
1864pub(crate) fn sine_pos(h: usize, w: usize, n: usize) -> Vec<f32> {
1865    let _p = crate::cpuprof::spans::span("op.sine_pos");
1866    let scale = std::f32::consts::TAU;
1867    let mut dim_t = vec![0f32; n];
1868    for i in 0..n { dim_t[i] = 10000f32.powf((2 * (i / 2)) as f32 / n as f32); }
1869    let mut out = vec![0f32; h * w * n * 2];
1870    let (hn, wn) = (h as f32, w as f32);
1871    for y in 0..h {
1872        let yy = (y + 1) as f32 / (hn + 1e-6) * scale;
1873        for x in 0..w {
1874            let xx = (x + 1) as f32 / (wn + 1e-6) * scale;
1875            let row = (y * w + x) * n * 2;
1876            for i in 0..n {
1877                let (py, px) = (yy / dim_t[i], xx / dim_t[i]);
1878                if i % 2 == 0 {
1879                    out[row + i] = py.sin();
1880                    out[row + n + i] = px.sin();
1881                } else {
1882                    out[row + i] = py.cos();
1883                    out[row + n + i] = px.cos();
1884                }
1885            }
1886        }
1887    }
1888    out
1889}
1890
1891/// Sine box embedding (decoder query_pos input): [N, 4*128] =
1892/// cat(pos_y, pos_x, pos_w, pos_h) for boxes in (cx, cy, w, h),
1893/// scale 2π (Sam3SinePositionEmbedding.encode_boxes).
1894fn sine_boxes(boxes: &[[f32; 4]]) -> Vec<f32> {
1895    let nf = 128;
1896    let scale = std::f32::consts::TAU;
1897    let mut dim_t = vec![0f32; nf];
1898    for i in 0..nf { dim_t[i] = 10000f32.powf((2 * (i / 2)) as f32 / nf as f32); }
1899    let mut out = vec![0f32; boxes.len() * 4 * nf];
1900    for (q, b) in boxes.iter().enumerate() {
1901        let base = q * 4 * nf;
1902        for (ci, v) in [b[1], b[0], b[2], b[3]].iter().enumerate() {
1903            for i in 0..nf {
1904                let val = v * scale / dim_t[i];
1905                out[base + ci * nf + i] = if i % 2 == 0 { val.sin() } else { val.cos() };
1906            }
1907        }
1908    }
1909    out
1910}
1911
1912/// Per-head log box-RPB additive bias: [heads, NQ+1, n]. Row 0 (the
1913/// presence token) is zero — HF pads the query dim from NQ to NQ+1.
1914fn rpb_bias(refs: &[[f32; 4]], rx: &DecoderMlp, ry: &DecoderMlp, n: usize, pool: Option<&Pool>) -> Result<Vec<f32>> {
1915    let gh = GRID;
1916    debug_assert_eq!(n, gh * gh);
1917    let l2_8 = 8.0f32.ln();
1918    let mut dy = vec![0f32; refs.len() * gh * 2];
1919    let mut dx = vec![0f32; refs.len() * gh * 2];
1920    for (q, r) in refs.iter().enumerate() {
1921        let x1 = r[0] - 0.5 * r[2];
1922        let y1 = r[1] - 0.5 * r[3];
1923        let x2 = r[0] + 0.5 * r[2];
1924        let y2 = r[1] + 0.5 * r[3];
1925        for hi in 0..gh {
1926            let c = hi as f32 / gh as f32;
1927            dy[(q * gh + hi) * 2] = log_compress(c - y1, l2_8);
1928            dy[(q * gh + hi) * 2 + 1] = log_compress(c - y2, l2_8);
1929        }
1930        for wi in 0..gh {
1931            let c = wi as f32 / gh as f32;
1932            dx[(q * gh + wi) * 2] = log_compress(c - x1, l2_8);
1933            dx[(q * gh + wi) * 2 + 1] = log_compress(c - x2, l2_8);
1934        }
1935    }
1936    let py = ry.forward(&dy, refs.len() * gh, pool, FH);
1937    let px = rx.forward(&dx, refs.len() * gh, pool, FH);
1938    let mut out = vec![0f32; FH * (NQ + 1) * n];
1939    let nq = refs.len();
1940    let ob = out.as_mut_ptr() as usize;
1941    // one (head, query) row of keys a unit, across the pool
1942    let fill = |s: usize, e: usize| {
1943        let o = unsafe { std::slice::from_raw_parts_mut(ob as *mut f32, FH * (NQ + 1) * n) };
1944        for u in s..e {
1945            let (t, q) = (u / nq, u % nq);
1946            let row = &mut o[(t * (NQ + 1) + (q + 1)) * n..][..n];
1947            for hi in 0..gh {
1948                let y = py[(q * gh + hi) * FH + t];
1949                for wi in 0..gh {
1950                    row[hi * gh + wi] = y + px[(q * gh + wi) * FH + t];
1951                }
1952            }
1953        }
1954    };
1955    match pool { Some(p) => p.run_rows(FH * nq, &fill), None => fill(0, FH * nq) }
1956    Ok(out)
1957}
1958
1959/// sign(d) * log2(|8d| + 1) / log2(8)  (box_rpb_mode = "log").
1960fn log_compress(d: f32, l2_8: f32) -> f32 {
1961    d.signum() * ((8.0 * d).abs() + 1.0).log2() / l2_8
1962}
1963
1964/// elementwise a+b over equal-length buffers
1965fn add_rows(a: &[f32], b: &[f32]) -> Vec<f32> {
1966    a.iter().zip(b).map(|(x, y)| x + y).collect()
1967}
1968
1969/// Finiteness/range stats for one debug stage (env `SAM3_TEXT_DEBUG`).
1970#[allow(dead_code)]
1971fn dbg_stats(tag: &str, v: &[f32]) {
1972    if std::env::var("SAM3_TEXT_DEBUG").is_err() {
1973        return;
1974    }
1975    let (mut bad, mut mn, mut mx) = (0usize, f32::INFINITY, f32::NEG_INFINITY);
1976    for &x in v {
1977        if !x.is_finite() {
1978            bad += 1;
1979            continue;
1980        }
1981        if x < mn { mn = x; }
1982        if x > mx { mx = x; }
1983    }
1984    eprintln!(
1985        "[sam3] {tag} n={} nonfinite={} min={:.4e} max={:.4e}",
1986        v.len(), bad, mn, mx
1987    );
1988}
1989
1990/// Raw f32 dump for reference bisection (env `SAM3_DUMP_DIR`).
1991#[allow(dead_code)]
1992fn dump_f32(dir: &str, name: &str, v: &[f32]) {
1993    use std::io::Write;
1994    let p = std::path::Path::new(dir).join(format!("{name}.f32"));
1995    let mut b = Vec::with_capacity(v.len() * 4);
1996    for x in v {
1997        b.extend_from_slice(&x.to_le_bytes());
1998    }
1999    match std::fs::File::create(&p).and_then(|mut f| f.write_all(&b)) {
2000        Ok(()) => eprintln!("[sam3] dumped {} ({} elems)", p.display(), v.len()),
2001        Err(e) => eprintln!("[sam3] dump {} failed: {e}", p.display()),
2002    }
2003}
2004
2005// ───────────────────────── tests (gpu feature) ─────────────────────
2006
2007/// Isolated GPU-vs-CPU check of `run_attn` itself on deterministic
2008/// pseudo-random inputs — no model, no fixtures: if the owner gate
2009/// (rel/cos) fails at the Sam3Out level, this says whether the
2010/// attention GPU arm or another block is the diverger.
2011#[cfg(all(test, feature = "gpu"))]
2012mod attn_gpu_tests {
2013    use super::*;
2014
2015    fn lcg(state: &mut u64) -> f32 {
2016        *state = state
2017            .wrapping_mul(6364136223846793005)
2018            .wrapping_add(1442695040888963407);
2019        ((*state >> 40) as f32 / (1u64 << 24) as f32) - 0.5
2020    }
2021
2022    fn rel_cos(g: &[f32], w: &[f32]) -> (f32, f32) {
2023        let mut md = 0f32;
2024        let mut mx = 0f32;
2025        let (mut dot, mut ng, mut nw) = (0f64, 0f64, 0f64);
2026        for (&g, &w) in g.iter().zip(w) {
2027            let d = (g - w).abs();
2028            if d > md { md = d; }
2029            if g.abs() > mx { mx = g.abs(); }
2030            dot += g as f64 * w as f64;
2031            ng += g as f64 * g as f64;
2032            nw += w as f64 * w as f64;
2033        }
2034        let rel = if mx > 0.0 { md / mx } else { md };
2035        let cos = if ng > 0.0 && nw > 0.0 {
2036            (dot / (ng.sqrt() * nw.sqrt())) as f32
2037        } else {
2038            1.0
2039        };
2040        (rel, cos)
2041    }
2042
2043    #[test]
2044    fn attn_gpu_matches_cpu() {
2045        if std::env::var("CMF_GPU").as_deref() != Ok("1") {
2046            eprintln!("skip attn_gpu_matches_cpu: CMF_GPU != 1");
2047            return;
2048        }
2049        if !crate::gpu::backend_available() {
2050            eprintln!("skip attn_gpu_matches_cpu: no wgpu backend");
2051            return;
2052        }
2053        // Shapes that mirror the real trunk: 1024x1024 (small square),
2054        // 576x576x1024/16 (windowed layer) and 5184x5184x1024/16 (global
2055        // layer — the only shape that exercises QK query-chunking).
2056        let cases: [(usize, usize, usize, usize, bool); 3] = [
2057            (1024, 1024, 256, 4, true),
2058            (576, 576, 1024, 16, false),
2059            (5184, 5184, 1024, 16, false),
2060        ];
2061        for &(n_q, n_k, dim, heads, with_head) in &cases {
2062            let h3 = dim * 3;
2063            let mut st = 0x9e37_79b9_7f4a_7c15u64;
2064            let xs: Vec<f32> = (0..n_k * h3).map(|_| lcg(&mut st) * 2.0).collect();
2065            let mut st2 = 0xdead_beefu64.wrapping_mul(0x5bd1_e995);
2066            let w_qkv = QTensor::F32 {
2067                data: (0..h3 * dim).map(|_| lcg(&mut st2)).collect(),
2068                rows: h3,
2069                cols: dim,
2070            };
2071            let w_o = QTensor::F32 {
2072                data: (0..dim * dim).map(|_| lcg(&mut st2)).collect(),
2073                rows: dim,
2074                cols: dim,
2075            };
2076            let qb = vec![0.01f32; h3];
2077            let ob = vec![0.02f32; dim];
2078            let head_mask: Vec<f32>;
2079            let mut head_owned: Vec<f32> = Vec::new();
2080            if with_head {
2081                head_owned = vec![0f32; heads * n_q * n_k];
2082                for (i, v) in head_owned.iter_mut().enumerate() {
2083                    *v = (i % 97) as f32 * 0.001 - 0.048;
2084            }
2085            }
2086            head_mask = head_owned;
2087            let mask_kinds: [(Option<usize>, &str); 2] =
2088                [(None, "none"), (with_head.then_some(0usize), "head")];
2089            for (kind, label) in mask_kinds {
2090                if kind.is_none() && !matches!(label, "none") {
2091                    continue;
2092                }
2093                let mask = match kind {
2094                    Some(_) if with_head => Mask::Head(&head_mask),
2095                    Some(_) => continue,
2096                    None => Mask::None,
2097                };
2098                if label == "head" && !with_head {
2099                    continue;
2100                }
2101                let mut out_cpu = vec![0f32; n_q * dim];
2102                let mut out_gpu = vec![0f32; n_q * dim];
2103                crate::gpu::cpu_scope(|| {
2104                    run_attn(
2105                        &w_qkv, &qb, &w_o, &ob, &xs, &xs, &xs,
2106                        n_q, n_k, dim, heads, None, mask, None, &mut out_cpu,
2107                    )
2108                });
2109                run_attn(
2110                    &w_qkv, &qb, &w_o, &ob, &xs, &xs, &xs,
2111                    n_q, n_k, dim, heads, None, mask, None, &mut out_gpu,
2112                );
2113                let (rel, cos) = rel_cos(&out_gpu, &out_cpu);
2114                eprintln!(
2115                    "attn_gpu_vs_cpu[{n_q}x{n_k}x{dim}/{heads} {label}] rel={rel:.3e} cos={cos:.6}"
2116                );
2117                assert!(
2118                    rel <= 1e-2 && cos >= 0.999,
2119                    "attn {n_q}x{n_k} mask={label}: rel={rel:.3e} cos={cos:.6} outside gate"
2120                );
2121            }
2122        }
2123    }
2124}