Skip to main content

cortiq_engine/
dit.rs

1//! Lumina2 Next-DiT forward (the Lumina-Image 2.0 denoiser):
2//! noisy latent + caption features + timestep → velocity prediction.
3//!
4//! Third increment of the image-generation runtime
5//! (docs/GENERATIVE.ru.md). Standalone f32 forward loaded from a
6//! diffusers `transformer/` directory, mirroring
7//! Lumina2Transformer2DModel exactly: plain-w RMSNorm (not Gemma's
8//! 1+w), per-head qk-norm, 3-axis complex-interleaved RoPE θ=10000
9//! (caption tokens advance axis 0, image tokens sit at axis0=cap_len
10//! with row/col on axes 1/2), AdaLN modulation with tanh gates from
11//! the 1024-d timestep embedding, sandwich RMSNorms, SwiGLU FFN, and
12//! a final LayerNorm(eps 1e-6, no affine) scaled by (1+scale) before
13//! the patch projection. Attention is full/bidirectional.
14//!
15//! Parity: `python/nextdit_ref.py` + `tests/dit_parity.rs` on the
16//! real Lumina transformer weights.
17
18use crate::pool::Pool;
19use crate::qtensor::QTensor;
20use crate::vae::{StTensor, read_safetensors};
21use cortiq_core::CmfModel;
22use std::collections::HashMap;
23use std::path::Path;
24use std::sync::Arc;
25
26/// A projection weight: exact f32 (diffusers load — Accelerate GEMM)
27/// or a CMF-quantized tensor on the engine's batched dot kernels.
28pub(crate) enum Proj {
29    F32 {
30        w: Vec<f32>,
31        rows: usize,
32        cols: usize,
33    },
34    Q(QTensor),
35}
36
37impl Proj {
38    /// f32 weight `[?, cols]`; rows derived from the data length.
39    pub(crate) fn f32(w: Vec<f32>, cols: usize) -> Self {
40        let rows = w.len() / cols;
41        debug_assert_eq!(w.len(), rows * cols);
42        Proj::F32 { w, rows, cols }
43    }
44
45    /// Load from a CMF directory entry (mmap-resident when quantized;
46    /// an F32 entry dequantizes into the exact-GEMM arm).
47    pub(crate) fn from_model(model: &Arc<CmfModel>, name: &str) -> Result<Self, String> {
48        Ok(match QTensor::from_model(model, name)? {
49            QTensor::F32 { data, rows, cols } => Proj::F32 {
50                w: data,
51                rows,
52                cols,
53            },
54            q => Proj::Q(q),
55        })
56    }
57
58    /// The container-mapped q4tp weight behind this projection, when the
59    /// codec put one there — a batched device path needs the tensor index,
60    /// not the bytes.
61    pub(crate) fn q4tp_mapped(&self) -> Option<(&Arc<CmfModel>, usize)> {
62        match self {
63            Proj::Q(q) => q.q4tp_mapped(),
64            Proj::F32 { .. } => None,
65        }
66    }
67
68    pub(crate) fn rows(&self) -> usize {
69        match self {
70            Proj::F32 { rows, .. } => *rows,
71            Proj::Q(q) => q.rows(),
72        }
73    }
74
75    /// The token-graph descriptor for this weight, when it is a
76    /// quantized mapped tensor the graph can read in place.
77    pub(crate) fn graph_w(&self) -> Option<(&Arc<CmfModel>, crate::gpu::GraphW<'_>)> {
78        match self {
79            Proj::Q(q) => q.graph_weight().map(|(m, idx, kind, rs)| {
80                (
81                    m,
82                    crate::gpu::GraphW {
83                        idx,
84                        kind,
85                        row_scale: rs,
86                        data: &[],
87                    },
88                )
89            }),
90            Proj::F32 { .. } => None,
91        }
92    }
93
94    pub(crate) fn cols(&self) -> usize {
95        match self {
96            Proj::F32 { cols, .. } => *cols,
97            Proj::Q(q) => q.cols(),
98        }
99    }
100
101    /// The same product as `matmat`, but as `b` separate matvecs.
102    ///
103    /// For a NARROW batch that is not a pessimisation, it is the point:
104    /// the batched device kernel tiles for 32 columns and at b=2 — an
105    /// autoregressive decode with its classifier-free pair — throws away
106    /// fifteen sixteenths of every tile, which is why simply lowering the
107    /// batch floor measured SLOWER than the host. The matvec kernel is
108    /// written for this shape and carries its own probe and threshold.
109    pub(crate) fn matvec_rows(&self, xs: &[f32], b: usize, out: &mut [f32], pool: Option<&Pool>) {
110        let (rows, cols) = (self.rows(), self.cols());
111        match self {
112            Proj::F32 { w, .. } => crate::fcd_ops::gemm_nt(xs, w, out, b, cols, rows, pool),
113            Proj::Q(q) => {
114                for i in 0..b {
115                    q.matvec(
116                        &xs[i * cols..(i + 1) * cols],
117                        &mut out[i * rows..(i + 1) * rows],
118                        pool,
119                    );
120                }
121            }
122        }
123    }
124
125    /// y[b, rows] = x[b, cols] · Wᵀ.
126    pub(crate) fn matmat(&self, xs: &[f32], b: usize, out: &mut [f32], pool: Option<&Pool>) {
127        match self {
128            Proj::F32 { w, rows, cols } => {
129                crate::fcd_ops::gemm_nt(xs, w, out, b, *cols, *rows, pool)
130            }
131            Proj::Q(q) => q.matmat(xs, b, out, pool),
132        }
133    }
134}
135
136struct Block {
137    /// AdaLN: (linear [4·hidden, 1024], bias [4·hidden]); None = plain norm1.
138    modulation: Option<(Proj, Vec<f32>)>,
139    norm1: Vec<f32>,
140    q: Proj, // [nh·hd, hidden]
141    k: Proj, // [nkv·hd, hidden]
142    v: Proj,
143    o: Proj,          // [hidden, nh·hd]
144    norm_q: Vec<f32>, // [hd]
145    norm_k: Vec<f32>,
146    norm2: Vec<f32>,
147    ffn_norm1: Vec<f32>,
148    w1: Proj, // gate [inter, hidden]
149    w3: Proj, // up
150    w2: Proj, // down [hidden, inter]
151    ffn_norm2: Vec<f32>,
152}
153
154/// Next-DiT: exact f32 from a diffusers directory, or CMF-quantized
155/// (mmap-resident) from a packaged file.
156pub struct NextDit {
157    x_emb: Proj, // [hidden, p·p·c]
158    x_emb_b: Vec<f32>,
159    t_lin1_w: Vec<f32>, // [temb, 256]
160    t_lin1_b: Vec<f32>,
161    t_lin2_w: Vec<f32>, // [temb, temb]
162    t_lin2_b: Vec<f32>,
163    cap_norm: Vec<f32>, // [cap_feat]
164    cap_w: Proj,        // [hidden, cap_feat]
165    cap_b: Vec<f32>,
166    context_refiner: Vec<Block>,
167    noise_refiner: Vec<Block>,
168    layers: Vec<Block>,
169    out_lin1_w: Vec<f32>, // [hidden, temb]
170    out_lin1_b: Vec<f32>,
171    out_lin2: Proj, // [p·p·c, hidden]
172    out_lin2_b: Vec<f32>,
173    pool: Option<Arc<Pool>>,
174    pub hidden: usize,
175    pub in_channels: usize,
176    pub patch: usize,
177    nh: usize,
178    nkv: usize,
179    hd: usize,
180    axes_dim: Vec<usize>,
181    eps: f64,
182}
183
184/// `CMF_DIT_PROF=1`: wall-time totals per forward stage, accumulated
185/// across every block of every step and dumped when the model drops.
186/// Same spirit as `CMF_VAE_PROF` — the knife for "where do the
187/// seconds go" before touching any kernel.
188mod prof {
189    use std::sync::OnceLock;
190    use std::sync::atomic::{AtomicU64, Ordering};
191
192    pub const MODNORM: usize = 0;
193    pub const QKV: usize = 1;
194    pub const ROPE: usize = 2;
195    pub const APACK: usize = 3;
196    pub const AQK: usize = 4;
197    pub const SOFTMAX: usize = 5;
198    pub const APV: usize = 6;
199    pub const OPROJ: usize = 7;
200    pub const FFN: usize = 8;
201    pub const FFNEL: usize = 9;
202    pub const HEADTAIL: usize = 10;
203    pub const GPUBLK: usize = 11;
204    const NAMES: [&str; 12] = [
205        "mod+norms",
206        "qkv-proj",
207        "qknorm+rope",
208        "attn-pack",
209        "attn-qk",
210        "softmax",
211        "attn-pv",
212        "o-proj",
213        "ffn-mm",
214        "ffn-silu",
215        "head+tail",
216        "gpu-block",
217    ];
218    static NS: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12];
219
220    pub fn on() -> bool {
221        static ON: OnceLock<bool> = OnceLock::new();
222        *ON.get_or_init(|| std::env::var("CMF_DIT_PROF").is_ok_and(|v| v != "0"))
223    }
224
225    /// RAII span: charges its category on drop. Free when prof is off.
226    pub struct Span(Option<(std::time::Instant, usize)>);
227    pub fn span(cat: usize) -> Span {
228        Span(on().then(|| (std::time::Instant::now(), cat)))
229    }
230    impl Drop for Span {
231        fn drop(&mut self) {
232            if let Some((t0, c)) = self.0 {
233                NS[c].fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
234            }
235        }
236    }
237
238    pub fn dump() {
239        if !on() {
240            return;
241        }
242        let total: u64 = NS.iter().map(|a| a.load(Ordering::Relaxed)).sum();
243        if total == 0 {
244            return;
245        }
246        eprintln!("dit prof ({:.1} s total in blocks):", total as f64 / 1e9);
247        for (name, a) in NAMES.iter().zip(&NS) {
248            let ns = a.load(Ordering::Relaxed);
249            eprintln!(
250                "  {name:<12} {:>7.2} s  {:>4.1}%",
251                ns as f64 / 1e9,
252                ns as f64 * 100.0 / total as f64
253            );
254        }
255    }
256}
257
258/// diffusers RMSNorm: x·rsqrt(mean x²+eps) · w (plain w).
259fn rms_norm(x: &[f32], w: &[f32], eps: f64) -> Vec<f32> {
260    let ss = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
261    let inv = 1.0 / (ss + eps).sqrt();
262    x.iter()
263        .zip(w)
264        .map(|(&v, &g)| (v as f64 * inv) as f32 * g)
265        .collect()
266}
267
268/// `rms_norm` into a caller buffer — same math, no per-row alloc.
269fn rms_norm_into(x: &[f32], w: &[f32], eps: f64, dst: &mut [f32]) {
270    let ss = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
271    let inv = 1.0 / (ss + eps).sqrt();
272    for ((d, &v), &g) in dst.iter_mut().zip(x).zip(w) {
273        *d = (v as f64 * inv) as f32 * g;
274    }
275}
276
277/// `rms_norm` in place — same math, no per-row alloc.
278fn rms_norm_inplace(v: &mut [f32], w: &[f32], eps: f64) {
279    let ss = v.iter().map(|&x| (x as f64) * (x as f64)).sum::<f64>() / v.len() as f64;
280    let inv = 1.0 / (ss + eps).sqrt();
281    for (x, &g) in v.iter_mut().zip(w) {
282        *x = (*x as f64 * inv) as f32 * g;
283    }
284}
285
286/// Rows of `n` items split across pool workers (serial without a pool).
287fn pool_rows(pool: Option<&Pool>, n: usize, f: &(dyn Fn(usize, usize) + Sync)) {
288    match pool {
289        Some(p) => p.run_rows(n, f),
290        None => f(0, n),
291    }
292}
293
294fn silu(v: f32) -> f32 {
295    v / (1.0 + (-v).exp())
296}
297
298/// y = x·Wᵀ + b for a single row.
299fn linear(x: &[f32], w: &[f32], b: &[f32]) -> Vec<f32> {
300    let k = x.len();
301    b.iter()
302        .enumerate()
303        .map(|(o, &bias)| {
304            let row = &w[o * k..(o + 1) * k];
305            bias + row.iter().zip(x).map(|(&a, &c)| a * c).sum::<f32>()
306        })
307        .collect()
308}
309
310/// Row handout for pool workers over one flat buffer (Rust-2021
311/// closures capture the raw pointer field, not the wrapper — hence
312/// the accessor method).
313struct SendRows(*mut f32);
314unsafe impl Send for SendRows {}
315unsafe impl Sync for SendRows {}
316impl SendRows {
317    /// SAFETY: caller guarantees disjoint `[off, off+len)` per worker.
318    #[allow(clippy::mut_from_ref)] // the disjoint-rows contract IS the point
319    unsafe fn row(&self, off: usize, len: usize) -> &mut [f32] {
320        unsafe { std::slice::from_raw_parts_mut(self.0.add(off), len) }
321    }
322
323    /// Single scattered element (transposed stores). SAFETY: as `row`.
324    unsafe fn set(&self, off: usize, v: f32) {
325        unsafe { *self.0.add(off) = v }
326    }
327}
328
329/// Numerically stable in-place softmax of one full row (NEON exp on
330/// aarch64, scalar elsewhere).
331fn softmax_inplace(row: &mut [f32]) {
332    #[cfg(target_arch = "aarch64")]
333    {
334        crate::attention::softmax_row(row);
335    }
336    #[cfg(not(target_arch = "aarch64"))]
337    {
338        let mx = row.iter().cloned().fold(f32::MIN, f32::max);
339        let mut den = 0f32;
340        for r in row.iter_mut() {
341            *r = (*r - mx).exp();
342            den += *r;
343        }
344        if den > 0.0 {
345            let inv = 1.0 / den;
346            for r in row.iter_mut() {
347                *r *= inv;
348            }
349        }
350    }
351}
352
353/// Any CMF directory entry → f32 (norms, biases, f16 conv kernels).
354pub(crate) fn cmf_f32(model: &CmfModel, name: &str) -> Result<Vec<f32>, String> {
355    let entry = model
356        .tensor(name)
357        .ok_or_else(|| format!("missing tensor {name}"))?;
358    let bytes = model.entry_bytes(entry);
359    let mut out = vec![0f32; entry.shape.iter().product()];
360    cortiq_core::quant::dequant_tensor(entry, bytes, &mut out)?;
361    Ok(out)
362}
363
364/// Per-token RoPE table: interleaved-pair rotation angles, f64.
365/// `ids` is [n, 3]; each axis contributes dim/2 frequencies.
366fn rope_table(ids: &[[u32; 3]], axes_dim: &[usize]) -> (Vec<f64>, Vec<f64>) {
367    let pairs: usize = axes_dim.iter().sum::<usize>() / 2;
368    let mut cos = Vec::with_capacity(ids.len() * pairs);
369    let mut sin = Vec::with_capacity(ids.len() * pairs);
370    for id in ids {
371        for (a, &d) in axes_dim.iter().enumerate() {
372            for j in 0..d / 2 {
373                let freq = 1.0 / 10000f64.powf(2.0 * j as f64 / d as f64);
374                let ang = id[a] as f64 * freq;
375                cos.push(ang.cos());
376                sin.push(ang.sin());
377            }
378        }
379    }
380    (cos, sin)
381}
382
383impl Drop for NextDit {
384    fn drop(&mut self) {
385        prof::dump();
386    }
387}
388
389impl NextDit {
390    pub fn load_dir(dir: &Path) -> Result<Self, String> {
391        let cfg: serde_json::Value = serde_json::from_slice(
392            &std::fs::read(dir.join("config.json")).map_err(|e| format!("config.json: {e}"))?,
393        )
394        .map_err(|e| format!("config.json: {e}"))?;
395        let idx: serde_json::Value = serde_json::from_slice(
396            &std::fs::read(dir.join("diffusion_pytorch_model.safetensors.index.json"))
397                .map_err(|e| format!("index: {e}"))?,
398        )
399        .map_err(|e| format!("index: {e}"))?;
400        let mut shards: Vec<String> = idx["weight_map"]
401            .as_object()
402            .ok_or("weight_map")?
403            .values()
404            .filter_map(|v| v.as_str().map(String::from))
405            .collect();
406        shards.sort();
407        shards.dedup();
408        let mut t: HashMap<String, StTensor> = HashMap::new();
409        for sh in &shards {
410            t.extend(read_safetensors(&dir.join(sh))?);
411        }
412        let mut take = |n: String| -> Result<Vec<f32>, String> {
413            t.remove(&n)
414                .map(|v| v.data)
415                .ok_or_else(|| format!("missing tensor {n}"))
416        };
417        let hidden = cfg["hidden_size"].as_u64().ok_or("hidden")? as usize;
418        let mut blocks = |pfx: &str, count: usize, modulated: bool| -> Result<Vec<Block>, String> {
419            (0..count)
420                .map(|l| {
421                    let p = format!("{pfx}.{l}");
422                    let w1 = take(format!("{p}.feed_forward.linear_1.weight"))?;
423                    let inter = w1.len() / hidden;
424                    Ok(Block {
425                        modulation: if modulated {
426                            let mw = take(format!("{p}.norm1.linear.weight"))?;
427                            let cols = mw.len() / (4 * hidden);
428                            Some((Proj::f32(mw, cols), take(format!("{p}.norm1.linear.bias"))?))
429                        } else {
430                            None
431                        },
432                        norm1: if modulated {
433                            take(format!("{p}.norm1.norm.weight"))?
434                        } else {
435                            take(format!("{p}.norm1.weight"))?
436                        },
437                        q: Proj::f32(take(format!("{p}.attn.to_q.weight"))?, hidden),
438                        k: Proj::f32(take(format!("{p}.attn.to_k.weight"))?, hidden),
439                        v: Proj::f32(take(format!("{p}.attn.to_v.weight"))?, hidden),
440                        o: {
441                            let o = take(format!("{p}.attn.to_out.0.weight"))?;
442                            let cols = o.len() / hidden;
443                            Proj::f32(o, cols)
444                        },
445                        norm_q: take(format!("{p}.attn.norm_q.weight"))?,
446                        norm_k: take(format!("{p}.attn.norm_k.weight"))?,
447                        norm2: take(format!("{p}.norm2.weight"))?,
448                        ffn_norm1: take(format!("{p}.ffn_norm1.weight"))?,
449                        w1: Proj::f32(w1, hidden),
450                        w3: Proj::f32(take(format!("{p}.feed_forward.linear_3.weight"))?, hidden),
451                        w2: Proj::f32(take(format!("{p}.feed_forward.linear_2.weight"))?, inter),
452                        ffn_norm2: take(format!("{p}.ffn_norm2.weight"))?,
453                    })
454                })
455                .collect()
456        };
457        let nl = cfg["num_layers"].as_u64().ok_or("num_layers")? as usize;
458        let nr = cfg["num_refiner_layers"].as_u64().unwrap_or(2) as usize;
459        let context_refiner = blocks("context_refiner", nr, false)?;
460        let noise_refiner = blocks("noise_refiner", nr, true)?;
461        let layers = blocks("layers", nl, true)?;
462        let nh = cfg["num_attention_heads"].as_u64().ok_or("nh")? as usize;
463        let in_channels = cfg["in_channels"].as_u64().ok_or("in_channels")? as usize;
464        let patch = cfg["patch_size"].as_u64().unwrap_or(2) as usize;
465        let axes_dim: Vec<usize> = cfg["axes_dim_rope"]
466            .as_array()
467            .ok_or("axes_dim_rope")?
468            .iter()
469            .map(|v| v.as_u64().unwrap_or(0) as usize)
470            .collect();
471        let cap_norm = take("time_caption_embed.caption_embedder.0.weight".into())?;
472        let cap_feat = cap_norm.len();
473        Ok(Self {
474            x_emb: Proj::f32(
475                take("x_embedder.weight".into())?,
476                patch * patch * in_channels,
477            ),
478            x_emb_b: take("x_embedder.bias".into())?,
479            t_lin1_w: take("time_caption_embed.timestep_embedder.linear_1.weight".into())?,
480            t_lin1_b: take("time_caption_embed.timestep_embedder.linear_1.bias".into())?,
481            t_lin2_w: take("time_caption_embed.timestep_embedder.linear_2.weight".into())?,
482            t_lin2_b: take("time_caption_embed.timestep_embedder.linear_2.bias".into())?,
483            cap_norm,
484            cap_w: Proj::f32(
485                take("time_caption_embed.caption_embedder.1.weight".into())?,
486                cap_feat,
487            ),
488            cap_b: take("time_caption_embed.caption_embedder.1.bias".into())?,
489            context_refiner,
490            noise_refiner,
491            layers,
492            out_lin1_w: take("norm_out.linear_1.weight".into())?,
493            out_lin1_b: take("norm_out.linear_1.bias".into())?,
494            out_lin2: Proj::f32(take("norm_out.linear_2.weight".into())?, hidden),
495            out_lin2_b: take("norm_out.linear_2.bias".into())?,
496            pool: Pool::from_env(),
497            hidden,
498            in_channels,
499            patch,
500            nh,
501            nkv: cfg["num_kv_heads"].as_u64().unwrap_or(nh as u64) as usize,
502            hd: hidden / nh,
503            axes_dim,
504            eps: cfg["norm_eps"].as_f64().unwrap_or(1e-5),
505        })
506    }
507
508    /// Load from a packaged imagegen .cmf (`dit.*` tensors +
509    /// `dit.config_json`). Quantized projections stay mmap-resident.
510    pub fn from_cmf(model: &Arc<CmfModel>) -> Result<Self, String> {
511        let cfg: serde_json::Value = serde_json::from_slice(
512            model
513                .tensor_bytes("dit.config_json")
514                .map_err(|e| e.to_string())?,
515        )
516        .map_err(|e| format!("dit.config_json: {e}"))?;
517        let f32v = |n: &str| -> Result<Vec<f32>, String> { cmf_f32(model, n) };
518        let hidden = cfg["hidden_size"].as_u64().ok_or("hidden")? as usize;
519        let blocks = |pfx: &str, count: usize, modulated: bool| -> Result<Vec<Block>, String> {
520            (0..count)
521                .map(|l| {
522                    let p = format!("dit.{pfx}.{l}");
523                    Ok(Block {
524                        modulation: if modulated {
525                            Some((
526                                Proj::from_model(model, &format!("{p}.norm1.linear.weight"))?,
527                                f32v(&format!("{p}.norm1.linear.bias"))?,
528                            ))
529                        } else {
530                            None
531                        },
532                        norm1: if modulated {
533                            f32v(&format!("{p}.norm1.norm.weight"))?
534                        } else {
535                            f32v(&format!("{p}.norm1.weight"))?
536                        },
537                        q: Proj::from_model(model, &format!("{p}.attn.to_q.weight"))?,
538                        k: Proj::from_model(model, &format!("{p}.attn.to_k.weight"))?,
539                        v: Proj::from_model(model, &format!("{p}.attn.to_v.weight"))?,
540                        o: Proj::from_model(model, &format!("{p}.attn.to_out.0.weight"))?,
541                        norm_q: f32v(&format!("{p}.attn.norm_q.weight"))?,
542                        norm_k: f32v(&format!("{p}.attn.norm_k.weight"))?,
543                        norm2: f32v(&format!("{p}.norm2.weight"))?,
544                        ffn_norm1: f32v(&format!("{p}.ffn_norm1.weight"))?,
545                        w1: Proj::from_model(model, &format!("{p}.feed_forward.linear_1.weight"))?,
546                        w3: Proj::from_model(model, &format!("{p}.feed_forward.linear_3.weight"))?,
547                        w2: Proj::from_model(model, &format!("{p}.feed_forward.linear_2.weight"))?,
548                        ffn_norm2: f32v(&format!("{p}.ffn_norm2.weight"))?,
549                    })
550                })
551                .collect()
552        };
553        let nl = cfg["num_layers"].as_u64().ok_or("num_layers")? as usize;
554        let nr = cfg["num_refiner_layers"].as_u64().unwrap_or(2) as usize;
555        let nh = cfg["num_attention_heads"].as_u64().ok_or("nh")? as usize;
556        let axes_dim: Vec<usize> = cfg["axes_dim_rope"]
557            .as_array()
558            .ok_or("axes_dim_rope")?
559            .iter()
560            .map(|v| v.as_u64().unwrap_or(0) as usize)
561            .collect();
562        Ok(Self {
563            x_emb: Proj::from_model(model, "dit.x_embedder.weight")?,
564            x_emb_b: f32v("dit.x_embedder.bias")?,
565            t_lin1_w: f32v("dit.time_caption_embed.timestep_embedder.linear_1.weight")?,
566            t_lin1_b: f32v("dit.time_caption_embed.timestep_embedder.linear_1.bias")?,
567            t_lin2_w: f32v("dit.time_caption_embed.timestep_embedder.linear_2.weight")?,
568            t_lin2_b: f32v("dit.time_caption_embed.timestep_embedder.linear_2.bias")?,
569            cap_norm: f32v("dit.time_caption_embed.caption_embedder.0.weight")?,
570            cap_w: Proj::from_model(model, "dit.time_caption_embed.caption_embedder.1.weight")?,
571            cap_b: f32v("dit.time_caption_embed.caption_embedder.1.bias")?,
572            context_refiner: blocks("context_refiner", nr, false)?,
573            noise_refiner: blocks("noise_refiner", nr, true)?,
574            layers: blocks("layers", nl, true)?,
575            out_lin1_w: f32v("dit.norm_out.linear_1.weight")?,
576            out_lin1_b: f32v("dit.norm_out.linear_1.bias")?,
577            out_lin2: Proj::from_model(model, "dit.norm_out.linear_2.weight")?,
578            out_lin2_b: f32v("dit.norm_out.linear_2.bias")?,
579            pool: Pool::from_env(),
580            hidden,
581            in_channels: cfg["in_channels"].as_u64().ok_or("in_channels")? as usize,
582            patch: cfg["patch_size"].as_u64().unwrap_or(2) as usize,
583            nh,
584            nkv: cfg["num_kv_heads"].as_u64().unwrap_or(nh as u64) as usize,
585            hd: hidden / nh,
586            axes_dim,
587            eps: cfg["norm_eps"].as_f64().unwrap_or(1e-5),
588        })
589    }
590
591    /// Sinusoidal(256, cos-first) → 2-layer MLP → temb [1024].
592    fn time_embed(&self, t: f32) -> Vec<f32> {
593        const HALF: usize = 128;
594        let mut freq = [0f32; 2 * HALF];
595        for i in 0..HALF {
596            let ang = t as f64 * (-(10000f64.ln()) * i as f64 / HALF as f64).exp();
597            freq[i] = ang.cos() as f32;
598            freq[HALF + i] = ang.sin() as f32;
599        }
600        let mut h = linear(&freq, &self.t_lin1_w, &self.t_lin1_b);
601        for v in h.iter_mut() {
602            *v = silu(*v);
603        }
604        linear(&h, &self.t_lin2_w, &self.t_lin2_b)
605    }
606
607    /// Fused on-device SwiGLU FFN (Metal). Taken only once the wide
608    /// GEMM probe has settled on the GPU arm: during probing the
609    /// per-op path feeds the samples, after a CPU verdict (or a
610    /// contention kill) the CPU path is the right one anyway. Carries
611    /// the same work-proportional contention tripwire as the per-op
612    /// route (cold ops exempt).
613    fn gpu_ffn(&self, blk: &Block, xn: &[f32], n: usize, out: &mut [f32]) -> bool {
614        use crate::gpu;
615        if n < 128 || !gpu::enabled_here() || gpu::mm_killed() {
616            return false;
617        }
618        // A fused block is not a wide matmat: see `fused_block_trusted`.
619        if !gpu::fused_block_trusted()
620            && (gpu::probe_deciding(gpu::OpClass::MatmatWide)
621                || !matches!(gpu::probe_arm(gpu::OpClass::MatmatWide), gpu::ProbeArm::Gpu))
622        {
623            return false;
624        }
625        let (Proj::Q(q1), Proj::Q(q3), Proj::Q(q2)) = (&blk.w1, &blk.w3, &blk.w2) else {
626            return false;
627        };
628        // q4t or q4tp — the fused chain exists for both, and picking by dtype
629        // here is what keeps a q4tp image model off the unfused path (which
630        // ships the [b, inter] intermediates across the CPU boundary twice per
631        // layer: 28 s against 14 s on Lumina at 256px).
632        let tp = q1.mapped_q4tp().is_some();
633        let (Some((m, i1)), Some((_, i3)), Some((_, i2))) = (if tp {
634            (q1.mapped_q4tp(), q3.mapped_q4tp(), q2.mapped_q4tp())
635        } else {
636            (q1.mapped_q4t(), q3.mapped_q4t(), q2.mapped_q4t())
637        }) else {
638            return false;
639        };
640        let inter = q1.rows();
641        let t0 = std::time::Instant::now();
642        let ok = if tp {
643            gpu::q4tp_ffn(m, i1, i3, i2, xn, n, self.hidden, inter, out)
644        } else {
645            gpu::q4t_ffn(m, i1, i3, i2, xn, n, self.hidden, inter, out)
646        };
647        if !ok {
648            return false;
649        }
650        let flops = 6.0 * n as f64 * self.hidden as f64 * inter as f64;
651        let budget = std::time::Duration::from_secs_f64(flops / 1.5e12 * 8.0 + 0.020);
652        let el = t0.elapsed();
653        gpu::mm_budget_check("ffn", el, budget, gpu::probe_was_cold());
654        true
655    }
656
657    /// All-heads attention on the device (same probe/kill gating as
658    /// the fused FFN). Packs q/k/v head-major (pool-parallel), runs
659    /// scores→softmax→P·V→unstack in one command buffer, and writes
660    /// straight into the [n][nh·hd] attn layout the O-projection
661    /// consumes. Returns false → caller runs the CPU per-head loop.
662    fn gpu_attention(
663        &self,
664        q_all: &[f32],
665        k_all: &[f32],
666        v_all: &[f32],
667        n: usize,
668        scale: f32,
669        attn: &mut [f32],
670    ) -> bool {
671        use crate::gpu;
672        let (nh, nkv, hd) = (self.nh, self.nkv, self.hd);
673        if n < 128 || !gpu::enabled_here() || gpu::mm_killed() {
674            return false;
675        }
676        // A fused block is not a wide matmat: see `fused_block_trusted`.
677        if !gpu::fused_block_trusted()
678            && (gpu::probe_deciding(gpu::OpClass::MatmatWide)
679                || !matches!(gpu::probe_arm(gpu::OpClass::MatmatWide), gpu::ProbeArm::Gpu))
680        {
681            return false;
682        }
683        let pool = self.pool.as_deref();
684        let mut qh = vec![0f32; nh * n * hd];
685        let mut kh = vec![0f32; nkv * n * hd];
686        let mut vh = vec![0f32; nkv * n * hd];
687        {
688            let _s = prof::span(prof::APACK);
689            let (sq, sk, sv) = (
690                SendRows(qh.as_mut_ptr()),
691                SendRows(kh.as_mut_ptr()),
692                SendRows(vh.as_mut_ptr()),
693            );
694            pool_rows(pool, n, &|start, end| {
695                for p in start..end {
696                    for h in 0..nh {
697                        // SAFETY: workers cover disjoint token ranges.
698                        unsafe { sq.row((h * n + p) * hd, hd) }
699                            .copy_from_slice(&q_all[(p * nh + h) * hd..(p * nh + h + 1) * hd]);
700                    }
701                    for h in 0..nkv {
702                        unsafe { sk.row((h * n + p) * hd, hd) }
703                            .copy_from_slice(&k_all[(p * nkv + h) * hd..(p * nkv + h + 1) * hd]);
704                        unsafe { sv.row((h * n + p) * hd, hd) }
705                            .copy_from_slice(&v_all[(p * nkv + h) * hd..(p * nkv + h + 1) * hd]);
706                    }
707                }
708            });
709        }
710        let _s = prof::span(prof::AQK);
711        let t0 = std::time::Instant::now();
712        if !gpu::dit_attention(&qh, &kh, &vh, nh, nkv, n, hd, scale, attn) {
713            return false;
714        }
715        let flops = 4.0 * nh as f64 * (n as f64) * (n as f64) * hd as f64;
716        let budget = std::time::Duration::from_secs_f64(flops / 1.5e12 * 8.0 + 0.020);
717        let el = t0.elapsed();
718        gpu::mm_budget_check("attention", el, budget, gpu::probe_was_cold());
719        true
720    }
721
722    /// One whole block on the device (norms → qkv → RoPE → attention
723    /// → O → residual → FFN → residual, single command buffer). Same
724    /// gating and contention tripwire as the per-stage GPU arms.
725    fn gpu_block(
726        &self,
727        blk: &Block,
728        x: &mut [f32],
729        n: usize,
730        rope32: &(Vec<f32>, Vec<f32>),
731        m: &[f32],
732    ) -> bool {
733        self.gpu_block_seg(blk, x, n, rope32, m, &[n], (false, false))
734    }
735
736    #[allow(clippy::too_many_arguments)]
737    fn gpu_block_seg(
738        &self,
739        blk: &Block,
740        x: &mut [f32],
741        n: usize,
742        rope32: &(Vec<f32>, Vec<f32>),
743        m: &[f32],
744        segs: &[usize],
745        resident: (bool, bool),
746    ) -> bool {
747        use crate::gpu;
748        let (hs, nh, nkv, hd) = (self.hidden, self.nh, self.nkv, self.hd);
749        if n < 128 || !gpu::enabled_here() || gpu::mm_killed() {
750            return false;
751        }
752        // A fused block is not a wide matmat: see `fused_block_trusted`.
753        if !gpu::fused_block_trusted()
754            && (gpu::probe_deciding(gpu::OpClass::MatmatWide)
755                || !matches!(gpu::probe_arm(gpu::OpClass::MatmatWide), gpu::ProbeArm::Gpu))
756        {
757            return false;
758        }
759        // The pack kernel assumes the rope table covers the full head
760        // dim (axes_dim sums to hd — true for Lumina; bail otherwise).
761        if rope32.0.len() != n * hd / 2 {
762            return false;
763        }
764        // Either 4-bit tiled layout: the ladder (q4tp) is what the
765        // published file uses, and taking only the older one is how the
766        // fused path came to be dead for it on every backend.
767        fn q(p: &Proj) -> Option<(&Arc<CmfModel>, usize)> {
768            match p {
769                Proj::Q(q) => q.mapped_q4t().or_else(|| q.mapped_q4tp()),
770                Proj::F32 { .. } => None,
771            }
772        }
773        let is_q4tp = matches!(&blk.q, Proj::Q(q) if q.mapped_q4tp().is_some());
774        let (
775            Some((model, wq)),
776            Some((_, wk)),
777            Some((_, wv)),
778            Some((_, wo)),
779            Some((_, w1)),
780            Some((_, w3)),
781            Some((_, w2)),
782        ) = (
783            q(&blk.q),
784            q(&blk.k),
785            q(&blk.v),
786            q(&blk.o),
787            q(&blk.w1),
788            q(&blk.w3),
789            q(&blk.w2),
790        )
791        else {
792            return false;
793        };
794        let inter = blk.w1.rows();
795        let gate_msa: Vec<f32> = m[hs..2 * hs].iter().map(|&v| v.tanh()).collect();
796        let gate_mlp: Vec<f32> = m[3 * hs..].iter().map(|&v| v.tanh()).collect();
797        let args = gpu::DitBlockArgs {
798            q4tp: is_q4tp,
799            resident_in: resident.0,
800            resident_out: resident.1,
801            n,
802            hidden: hs,
803            inter,
804            nh,
805            nkv,
806            hd,
807            eps: self.eps as f32,
808            rope_cos: &rope32.0,
809            rope_sin: &rope32.1,
810            norm1: &blk.norm1,
811            norm2: &blk.norm2,
812            ffn_norm1: &blk.ffn_norm1,
813            ffn_norm2: &blk.ffn_norm2,
814            norm_q: &blk.norm_q,
815            norm_k: &blk.norm_k,
816            s_msa: &m[..hs],
817            gate_msa: &gate_msa,
818            s_mlp: &m[2 * hs..3 * hs],
819            gate_mlp: &gate_mlp,
820            wq,
821            wk,
822            wv,
823            wo,
824            w1,
825            w3,
826            w2,
827        };
828        let t0 = std::time::Instant::now();
829        if !gpu::dit_block_seg(model, &args, segs, x) {
830            return false;
831        }
832        let flops = 2.0 * n as f64 * hs as f64 * ((nh + 2 * nkv) * hd) as f64
833            + 4.0 * nh as f64 * (n as f64) * (n as f64) * hd as f64
834            + 2.0 * n as f64 * hs as f64 * (nh * hd) as f64
835            + 6.0 * n as f64 * hs as f64 * inter as f64;
836        let budget = std::time::Duration::from_secs_f64(flops / 1.5e12 * 8.0 + 0.030);
837        let el = t0.elapsed();
838        gpu::mm_budget_check("dit block", el, budget, gpu::probe_was_cold());
839        true
840    }
841
842    /// Full bidirectional attention over ONE sequence: per head, pack
843    /// q/k/v, scores as a GEMM, row softmax, P·V, scatter back. Lifted
844    /// out of the block so a batched call can run it per segment
845    /// without the segments ever meeting in a score matrix.
846    fn attention_seq(
847        &self,
848        q_all: &[f32],
849        k_all: &[f32],
850        v_all: &[f32],
851        n: usize,
852        scale: f32,
853        attn: &mut [f32],
854    ) {
855        let (nh, nkv, hd) = (self.nh, self.nkv, self.hd);
856        let hpk = nh / nkv;
857        let pool = self.pool.as_deref();
858        let mut qh = vec![0f32; n * hd];
859        let mut kh = vec![0f32; n * hd];
860        let mut vt = vec![0f32; hd * n]; // V transposed: gemm_nt's W layout
861        let mut scores = vec![0f32; n * n];
862        let mut oh = vec![0f32; n * hd];
863        for hh in 0..nh {
864            let kv = hh / hpk;
865            {
866                let _s = prof::span(prof::APACK);
867                let (sq, sk, sv) = (
868                    SendRows(qh.as_mut_ptr()),
869                    SendRows(kh.as_mut_ptr()),
870                    SendRows(vt.as_mut_ptr()),
871                );
872                pool_rows(pool, n, &|start, end| {
873                    for p in start..end {
874                        let qsrc = &q_all[(p * nh + hh) * hd..(p * nh + hh + 1) * hd];
875                        // SAFETY: workers cover disjoint token ranges
876                        // (`vt` columns are indexed by token too).
877                        let qd = unsafe { sq.row(p * hd, hd) };
878                        for (d, &v) in qsrc.iter().enumerate() {
879                            qd[d] = v * scale;
880                        }
881                        unsafe { sk.row(p * hd, hd) }
882                            .copy_from_slice(&k_all[(p * nkv + kv) * hd..(p * nkv + kv + 1) * hd]);
883                        let vv = &v_all[(p * nkv + kv) * hd..(p * nkv + kv + 1) * hd];
884                        for (d, &val) in vv.iter().enumerate() {
885                            unsafe { sv.set(d * n + p, val) };
886                        }
887                    }
888                });
889            }
890            {
891                let _s = prof::span(prof::AQK);
892                crate::fcd_ops::gemm_nt(&qh, &kh, &mut scores, n, hd, n, pool);
893            }
894            {
895                let _s = prof::span(prof::SOFTMAX);
896                let sp = SendRows(scores.as_mut_ptr());
897                let soft = |start: usize, end: usize| {
898                    for r in start..end {
899                        // SAFETY: workers cover disjoint row ranges.
900                        softmax_inplace(unsafe { sp.row(r * n, n) });
901                    }
902                };
903                match pool {
904                    Some(p) => p.run_rows(n, &soft),
905                    None => soft(0, n),
906                }
907            }
908            {
909                let _s = prof::span(prof::APV);
910                crate::fcd_ops::gemm_nt(&scores, &vt, &mut oh, n, n, hd, pool);
911            }
912            let _s = prof::span(prof::APACK);
913            let sa = SendRows(attn.as_mut_ptr());
914            pool_rows(pool, n, &|start, end| {
915                for p in start..end {
916                    // SAFETY: workers cover disjoint token ranges.
917                    unsafe { sa.row((p * nh + hh) * hd, hd) }
918                        .copy_from_slice(&oh[p * hd..(p + 1) * hd]);
919                }
920            });
921        }
922    }
923
924    fn block_forward(
925        &self,
926        blk: &Block,
927        x: &mut [f32],
928        rope: &(Vec<f64>, Vec<f64>),
929        rope32: Option<&(Vec<f32>, Vec<f32>)>,
930        temb: Option<&[f32]>,
931    ) {
932        let n_all = x.len() / self.hidden;
933        let _ = self.block_forward_seg(blk, x, rope, rope32, temb, &[n_all], (false, false));
934    }
935
936    /// `block_forward` over a CONCATENATION of independent sequences.
937    /// Everything position-wise (norms, projections, FFN) sees one tall
938    /// batch — the weights are read once for all of them, which is the
939    /// whole point on a CPU or a phone — while attention runs per
940    /// segment, so no sample ever attends to another's tokens. `segs`
941    /// are the token counts in order; a single-element slice is the
942    /// plain path, bit for bit.
943    fn block_forward_seg(
944        &self,
945        blk: &Block,
946        x: &mut [f32],
947        rope: &(Vec<f64>, Vec<f64>),
948        rope32: Option<&(Vec<f32>, Vec<f32>)>,
949        temb: Option<&[f32]>,
950        segs: &[usize],
951        resident: (bool, bool),
952    ) -> bool {
953        let (hs, nh, nkv, hd) = (self.hidden, self.nh, self.nkv, self.hd);
954        let pool = self.pool.as_deref();
955        let n = x.len() / hs;
956        let modv = {
957            let _s = prof::span(prof::MODNORM);
958            blk.modulation.as_ref().zip(temb).map(|((w, b), t)| {
959                let s: Vec<f32> = t.iter().map(|&v| silu(v)).collect();
960                let mut m = vec![0f32; w.rows()];
961                w.matmat(&s, 1, &mut m, pool);
962                for (v, &bias) in m.iter_mut().zip(b) {
963                    *v += bias;
964                }
965                m
966            })
967        };
968        if let (Some(m), Some(r32)) = (&modv, rope32) {
969            let _s = prof::span(prof::GPUBLK);
970            if self.gpu_block_seg(blk, x, n, r32, m, segs, resident) {
971                return true;
972            }
973        }
974        // Falling back to the host after a chained block: the device holds
975        // the state and `x` is stale. Recover it before reading `x`.
976        if resident.0 {
977            crate::gpu::dit_state_fetch(&mut x[..n * hs]);
978        }
979        let modnorm = prof::span(prof::MODNORM);
980        let (s_msa, g_msa, s_mlp, g_mlp) = match &modv {
981            Some(m) => (
982                Some(&m[..hs]),
983                Some(&m[hs..2 * hs]),
984                Some(&m[2 * hs..3 * hs]),
985                Some(&m[3 * hs..]),
986            ),
987            None => (None, None, None, None),
988        };
989        // Gates: tanh once per block — every row shares the same gate
990        // vector, and the naive per-element tanh in the residual loop
991        // was billions of repeated evaluations per render.
992        let gate_msa: Option<Vec<f32>> = g_msa.map(|g| g.iter().map(|&v| v.tanh()).collect());
993        let gate_mlp: Option<Vec<f32>> = g_mlp.map(|g| g.iter().map(|&v| v.tanh()).collect());
994        // Pool-parallel row helpers: dst = rms(src)·w · (1+s)  and
995        // x += gate ⊙ rms(src)·w. Same math and per-row summation
996        // order as the serial loops — rows are independent, so the
997        // parallel split is bit-exact.
998        let norm_scaled = |src: &[f32], w: &[f32], s: Option<&[f32]>, dst: &mut [f32]| {
999            let sr = SendRows(dst.as_mut_ptr());
1000            pool_rows(pool, n, &|start, end| {
1001                for p in start..end {
1002                    // SAFETY: workers cover disjoint row ranges.
1003                    let row = unsafe { sr.row(p * hs, hs) };
1004                    rms_norm_into(&src[p * hs..(p + 1) * hs], w, self.eps, row);
1005                    if let Some(s) = s {
1006                        for (r, &sc) in row.iter_mut().zip(s) {
1007                            *r *= 1.0 + sc;
1008                        }
1009                    }
1010                }
1011            });
1012        };
1013        let residual = |src: &[f32], w: &[f32], gate: Option<&[f32]>, x: &mut [f32]| {
1014            let sr = SendRows(x.as_mut_ptr());
1015            pool_rows(pool, n, &|start, end| {
1016                let mut tmp = vec![0f32; hs];
1017                for p in start..end {
1018                    rms_norm_into(&src[p * hs..(p + 1) * hs], w, self.eps, &mut tmp);
1019                    // SAFETY: workers cover disjoint row ranges.
1020                    let dst = unsafe { sr.row(p * hs, hs) };
1021                    match gate {
1022                        Some(g) => {
1023                            for ((d, &v), &gt) in dst.iter_mut().zip(&tmp).zip(g) {
1024                                *d += gt * v;
1025                            }
1026                        }
1027                        None => {
1028                            for (d, &v) in dst.iter_mut().zip(&tmp) {
1029                                *d += v;
1030                            }
1031                        }
1032                    }
1033                }
1034            });
1035        };
1036        // ── attention ──
1037        let mut xn = vec![0f32; n * hs];
1038        norm_scaled(x, &blk.norm1, s_msa, &mut xn);
1039        drop(modnorm);
1040        let mut q_all = vec![0f32; n * nh * hd];
1041        let mut k_all = vec![0f32; n * nkv * hd];
1042        let mut v_all = vec![0f32; n * nkv * hd];
1043        {
1044            let _s = prof::span(prof::QKV);
1045            // One submission for the three projections when the device
1046            // offers it: they share `xn`, so three uploads and three
1047            // waits a block were ceremony.
1048            let fused = match (&blk.q, &blk.k, &blk.v) {
1049                (Proj::Q(q), Proj::Q(k), Proj::Q(v))
1050                    if n >= 128 && crate::gpu::enabled_here() && !crate::gpu::mm_killed() =>
1051                {
1052                    match (q.model_arc(), q.model_idx(), k.model_idx(), v.model_idx()) {
1053                        (Some(m), Some(iq), Some(ik), Some(iv)) => crate::gpu::dit_qkv(
1054                            &m,
1055                            iq,
1056                            ik,
1057                            iv,
1058                            &xn,
1059                            n,
1060                            hs,
1061                            nh * hd,
1062                            nkv * hd,
1063                            &mut q_all,
1064                            &mut k_all,
1065                            &mut v_all,
1066                        ),
1067                        _ => false,
1068                    }
1069                }
1070                _ => false,
1071            };
1072            if !fused {
1073                blk.q.matmat(&xn, n, &mut q_all, pool);
1074                blk.k.matmat(&xn, n, &mut k_all, pool);
1075                blk.v.matmat(&xn, n, &mut v_all, pool);
1076            }
1077        }
1078        let rope_span = prof::span(prof::ROPE);
1079        // per-head qk-norm, then interleaved-pair RoPE
1080        let (cos, sin) = rope;
1081        let pairs = hd / 2;
1082        for (all, heads, w) in [
1083            (&mut q_all, nh, &blk.norm_q),
1084            (&mut k_all, nkv, &blk.norm_k),
1085        ] {
1086            let sr = SendRows(all.as_mut_ptr());
1087            pool_rows(pool, n, &|start, end| {
1088                for p in start..end {
1089                    for hh in 0..heads {
1090                        // SAFETY: workers cover disjoint token ranges.
1091                        let v = unsafe { sr.row((p * heads + hh) * hd, hd) };
1092                        rms_norm_inplace(v, w, 1e-5);
1093                        for j in 0..pairs {
1094                            let (c, s) = (cos[p * pairs + j], sin[p * pairs + j]);
1095                            let (a, b) = (v[2 * j] as f64, v[2 * j + 1] as f64);
1096                            v[2 * j] = (a * c - b * s) as f32;
1097                            v[2 * j + 1] = (a * s + b * c) as f32;
1098                        }
1099                    }
1100                }
1101            });
1102        }
1103        drop(rope_span);
1104        // full (bidirectional) softmax attention, GQA — per head:
1105        // scores = (Q·s)·Kᵀ and P·V as GEMMs (Accelerate/blocked),
1106        // pool-parallel row softmax between them. The naive
1107        // per-position loop was the depth wall: at 512px (1064
1108        // tokens) attention alone cost hundreds of serial GFLOP.
1109        let scale = 1.0 / (hd as f32).sqrt();
1110        let _hpk = nh / nkv;
1111        let mut attn = vec![0f32; n * nh * hd];
1112        if segs.len() > 1 {
1113            // Each sequence attends within itself. The slices are row
1114            // ranges of the same buffers, so the per-head math below is
1115            // the one the single-sequence path runs.
1116            let mut off = 0usize;
1117            for &ns in segs {
1118                let (qs, ks, vs) = (
1119                    &q_all[off * nh * hd..(off + ns) * nh * hd],
1120                    &k_all[off * nkv * hd..(off + ns) * nkv * hd],
1121                    &v_all[off * nkv * hd..(off + ns) * nkv * hd],
1122                );
1123                let dst = &mut attn[off * nh * hd..(off + ns) * nh * hd];
1124                if !self.gpu_attention(qs, ks, vs, ns, scale, dst) {
1125                    self.attention_seq(qs, ks, vs, ns, scale, dst);
1126                }
1127                off += ns;
1128            }
1129        } else if !self.gpu_attention(&q_all, &k_all, &v_all, n, scale, &mut attn) {
1130            self.attention_seq(&q_all, &k_all, &v_all, n, scale, &mut attn);
1131        }
1132        let mut proj = vec![0f32; n * hs];
1133        {
1134            let _s = prof::span(prof::OPROJ);
1135            blk.o.matmat(&attn, n, &mut proj, pool);
1136        }
1137        let modnorm = prof::span(prof::MODNORM);
1138        residual(&proj, &blk.norm2, gate_msa.as_deref(), x);
1139        // ── SwiGLU FFN ──
1140        norm_scaled(x, &blk.ffn_norm1, s_mlp, &mut xn);
1141        drop(modnorm);
1142        let mut d_all = vec![0f32; n * hs];
1143        let fused = {
1144            let _s = prof::span(prof::FFN);
1145            self.gpu_ffn(blk, &xn, n, &mut d_all)
1146        };
1147        if !fused {
1148            let inter = blk.w1.rows();
1149            let mut g_all = vec![0f32; n * inter];
1150            let mut u_all = vec![0f32; n * inter];
1151            {
1152                let _s = prof::span(prof::FFN);
1153                blk.w1.matmat(&xn, n, &mut g_all, pool);
1154                blk.w3.matmat(&xn, n, &mut u_all, pool);
1155            }
1156            {
1157                let _s = prof::span(prof::FFNEL);
1158                let sg = SendRows(g_all.as_mut_ptr());
1159                pool_rows(pool, n, &|start, end| {
1160                    for p in start..end {
1161                        // SAFETY: workers cover disjoint token ranges.
1162                        let g = unsafe { sg.row(p * inter, inter) };
1163                        for (gv, &uv) in g.iter_mut().zip(&u_all[p * inter..(p + 1) * inter]) {
1164                            *gv = silu(*gv) * uv;
1165                        }
1166                    }
1167                });
1168            }
1169            {
1170                let _s = prof::span(prof::FFN);
1171                blk.w2.matmat(&g_all, n, &mut d_all, pool);
1172            }
1173        }
1174        let _modnorm = prof::span(prof::MODNORM);
1175        residual(&d_all, &blk.ffn_norm2, gate_mlp.as_deref(), x);
1176        false
1177    }
1178
1179    /// One denoising forward: latent `[c, h, w]` (NCHW), caption
1180    /// features `[cap_n, cap_feat]`, timestep `t` ∈ [0,1] (the
1181    /// pipeline's `1 − σ`). Returns the velocity prediction `[c, h, w]`.
1182    pub fn forward(
1183        &self,
1184        latent: &[f32],
1185        h: usize,
1186        w: usize,
1187        cap: &[f32],
1188        cap_n: usize,
1189        t: f32,
1190    ) -> Vec<f32> {
1191        self.forward_with_cap(latent, h, w, &self.refine_caption(cap, cap_n), cap_n, t)
1192    }
1193
1194    /// Caption features → hidden, through the context refiner. Depends on
1195    /// NOTHING that moves during denoising — not the timestep, not the
1196    /// latents — so the whole thing is a constant of the prompt. The
1197    /// denoise loop hoists it out and hands the result to
1198    /// `forward_with_cap`; it used to be recomputed on every model call,
1199    /// which for 30 steps under CFG meant 60 evaluations of a value with
1200    /// two distinct instances.
1201    pub fn refine_caption(&self, cap: &[f32], cap_n: usize) -> Vec<f32> {
1202        let hs = self.hidden;
1203        let cap_feat = self.cap_norm.len();
1204        let mut cap_n_all = vec![0f32; cap_n * cap_feat];
1205        for i in 0..cap_n {
1206            cap_n_all[i * cap_feat..(i + 1) * cap_feat].copy_from_slice(&rms_norm(
1207                &cap[i * cap_feat..(i + 1) * cap_feat],
1208                &self.cap_norm,
1209                self.eps,
1210            ));
1211        }
1212        let mut cap_e = vec![0f32; cap_n * hs];
1213        self.cap_w
1214            .matmat(&cap_n_all, cap_n, &mut cap_e, self.pool.as_deref());
1215        for i in 0..cap_n {
1216            for (v, &b) in cap_e[i * hs..(i + 1) * hs].iter_mut().zip(&self.cap_b) {
1217                *v += b;
1218            }
1219        }
1220        let cap_ids: Vec<[u32; 3]> = (0..cap_n).map(|i| [i as u32, 0, 0]).collect();
1221        let cap_rope = rope_table(&cap_ids, &self.axes_dim);
1222        for blk in &self.context_refiner {
1223            self.block_forward(blk, &mut cap_e, &cap_rope, None, None);
1224        }
1225        cap_e
1226    }
1227
1228    /// The rest of the forward, from an already-refined caption.
1229    /// Classifier-free guidance in ONE pass: the conditional and the
1230    /// unconditional sequence go through the joint stack as a single
1231    /// batch. Every weight is read once for both — which is the whole
1232    /// cost on a CPU or a phone — and the image branch (patchify,
1233    /// x_embedder, the noise refiners) is computed once instead of
1234    /// twice, because it does not depend on the caption at all.
1235    /// Attention stays per sequence, so the two never mix and each
1236    /// prediction equals what the single-sequence path returns.
1237    #[allow(clippy::too_many_arguments)]
1238    pub fn forward_cfg_pair(
1239        &self,
1240        latent: &[f32],
1241        h: usize,
1242        w: usize,
1243        cap_c: &[f32],
1244        cap_c_n: usize,
1245        cap_u: &[f32],
1246        cap_u_n: usize,
1247        t: f32,
1248    ) -> (Vec<f32>, Vec<f32>) {
1249        let (c, p, hs) = (self.in_channels, self.patch, self.hidden);
1250        let (hp, wp) = (h / p, w / p);
1251        let n_img = hp * wp;
1252        let head = prof::span(prof::HEADTAIL);
1253        let temb = self.time_embed(t);
1254        let pv = p * p * c;
1255        let mut tok = vec![0f32; n_img * pv];
1256        for ph in 0..hp {
1257            for pw in 0..wp {
1258                let dst = &mut tok[(ph * wp + pw) * pv..(ph * wp + pw + 1) * pv];
1259                for dy in 0..p {
1260                    for dx in 0..p {
1261                        for ch in 0..c {
1262                            dst[(dy * p + dx) * c + ch] =
1263                                latent[ch * h * w + (ph * p + dy) * w + pw * p + dx];
1264                        }
1265                    }
1266                }
1267            }
1268        }
1269        let mut img = vec![0f32; n_img * hs];
1270        self.x_emb
1271            .matmat(&tok, n_img, &mut img, self.pool.as_deref());
1272        for i in 0..n_img {
1273            for (v, &b) in img[i * hs..(i + 1) * hs].iter_mut().zip(&self.x_emb_b) {
1274                *v += b;
1275            }
1276        }
1277        let img_ids: Vec<[u32; 3]> = (0..n_img)
1278            .map(|i| [0, (i / wp) as u32, (i % wp) as u32])
1279            .collect();
1280        let to32 = |r: &(Vec<f64>, Vec<f64>)| {
1281            (
1282                r.0.iter().map(|&v| v as f32).collect::<Vec<f32>>(),
1283                r.1.iter().map(|&v| v as f32).collect::<Vec<f32>>(),
1284            )
1285        };
1286        // The refiners see the image alone — same for both branches.
1287        let img_rope_r = rope_table(
1288            &(0..n_img)
1289                .map(|i| [0u32, (i / wp) as u32, (i % wp) as u32])
1290                .collect::<Vec<_>>(),
1291            &self.axes_dim,
1292        );
1293        let img_rope32_r = to32(&img_rope_r);
1294        drop(head);
1295        for blk in &self.noise_refiner {
1296            self.block_forward(blk, &mut img, &img_rope_r, Some(&img_rope32_r), Some(&temb));
1297        }
1298        let _ = img_ids;
1299        // Joint sequences, concatenated: [cap_c | img] then [cap_u | img].
1300        let n_c = cap_c_n + n_img;
1301        let n_u = cap_u_n + n_img;
1302        let mut x = Vec::with_capacity((n_c + n_u) * hs);
1303        x.extend_from_slice(&cap_c[..cap_c_n * hs]);
1304        x.extend_from_slice(&img);
1305        x.extend_from_slice(&cap_u[..cap_u_n * hs]);
1306        x.extend_from_slice(&img);
1307        let rope_for = |cap_n: usize| -> (Vec<f64>, Vec<f64>) {
1308            let cap_ids: Vec<[u32; 3]> = (0..cap_n).map(|i| [i as u32, 0, 0]).collect();
1309            let im_ids: Vec<[u32; 3]> = (0..n_img)
1310                .map(|i| [cap_n as u32, (i / wp) as u32, (i % wp) as u32])
1311                .collect();
1312            let a = rope_table(&cap_ids, &self.axes_dim);
1313            let b = rope_table(&im_ids, &self.axes_dim);
1314            ([a.0, b.0].concat(), [a.1, b.1].concat())
1315        };
1316        let (rc, ru) = (rope_for(cap_c_n), rope_for(cap_u_n));
1317        let joint_rope = ([rc.0, ru.0].concat(), [rc.1, ru.1].concat());
1318        let joint_rope32 = to32(&joint_rope);
1319        let segs = [n_c, n_u];
1320        // The state stays on the device for the whole stack: nothing here
1321        // reads `x` between blocks, so uploading and reading back 19 MB
1322        // around each of 28 blocks was pure round trip. Only the first
1323        // block uploads and only the last reads back.
1324        let chain = crate::gpu::dit_chain_supported();
1325        let last = self.layers.len().saturating_sub(1);
1326        let mut resident = false;
1327        for (i, blk) in self.layers.iter().enumerate() {
1328            let want = if chain {
1329                (resident, i != last)
1330            } else {
1331                (false, false)
1332            };
1333            // A block the device declines runs on the host and leaves the
1334            // state there, so the next one must upload again.
1335            let on_gpu = self.block_forward_seg(
1336                blk,
1337                &mut x,
1338                &joint_rope,
1339                Some(&joint_rope32),
1340                Some(&temb),
1341                &segs,
1342                want,
1343            );
1344            resident = on_gpu && want.1;
1345        }
1346        let _tail = prof::span(prof::HEADTAIL);
1347        let n = n_c + n_u;
1348        let silu_t: Vec<f32> = temb.iter().map(|&v| silu(v)).collect();
1349        let scale = linear(&silu_t, &self.out_lin1_w, &self.out_lin1_b);
1350        for row in x.chunks_exact_mut(hs) {
1351            let mean = row.iter().map(|&v| v as f64).sum::<f64>() / hs as f64;
1352            let var = row
1353                .iter()
1354                .map(|&v| (v as f64 - mean) * (v as f64 - mean))
1355                .sum::<f64>()
1356                / hs as f64;
1357            let inv = 1.0 / (var + 1e-6).sqrt();
1358            for (v, &s) in row.iter_mut().zip(&scale) {
1359                *v = ((*v as f64 - mean) * inv) as f32 * (1.0 + s);
1360            }
1361        }
1362        let mut out = vec![0f32; n * pv];
1363        self.out_lin2.matmat(&x, n, &mut out, self.pool.as_deref());
1364        for i in 0..n {
1365            for (v, &b) in out[i * pv..(i + 1) * pv].iter_mut().zip(&self.out_lin2_b) {
1366                *v += b;
1367            }
1368        }
1369        let unpatch = |base: usize| -> Vec<f32> {
1370            let mut pred = vec![0f32; c * h * w];
1371            for ph in 0..hp {
1372                for pw in 0..wp {
1373                    let src = &out[(base + ph * wp + pw) * pv..(base + ph * wp + pw + 1) * pv];
1374                    for dy in 0..p {
1375                        for dx in 0..p {
1376                            for ch in 0..c {
1377                                pred[ch * h * w + (ph * p + dy) * w + pw * p + dx] =
1378                                    src[(dy * p + dx) * c + ch];
1379                            }
1380                        }
1381                    }
1382                }
1383            }
1384            pred
1385        };
1386        (unpatch(cap_c_n), unpatch(n_c + cap_u_n))
1387    }
1388
1389    pub fn forward_with_cap(
1390        &self,
1391        latent: &[f32],
1392        h: usize,
1393        w: usize,
1394        cap_e_in: &[f32],
1395        cap_n: usize,
1396        t: f32,
1397    ) -> Vec<f32> {
1398        let (c, p, hs) = (self.in_channels, self.patch, self.hidden);
1399        assert_eq!(latent.len(), c * h * w);
1400        let (hp, wp) = (h / p, w / p);
1401        let n_img = hp * wp;
1402        let head = prof::span(prof::HEADTAIL);
1403        let temb = self.time_embed(t);
1404        let cap_e = cap_e_in.to_vec();
1405
1406        // patchify (dy, dx, ch inner order) + x_embedder
1407        let pv = p * p * c;
1408        let mut tok = vec![0f32; n_img * pv];
1409        for ph in 0..hp {
1410            for pw in 0..wp {
1411                let dst = &mut tok[(ph * wp + pw) * pv..(ph * wp + pw + 1) * pv];
1412                for dy in 0..p {
1413                    for dx in 0..p {
1414                        for ch in 0..c {
1415                            dst[(dy * p + dx) * c + ch] =
1416                                latent[ch * h * w + (ph * p + dy) * w + pw * p + dx];
1417                        }
1418                    }
1419                }
1420            }
1421        }
1422        let mut img = vec![0f32; n_img * hs];
1423        self.x_emb
1424            .matmat(&tok, n_img, &mut img, self.pool.as_deref());
1425        for i in 0..n_img {
1426            for (v, &b) in img[i * hs..(i + 1) * hs].iter_mut().zip(&self.x_emb_b) {
1427                *v += b;
1428            }
1429        }
1430
1431        // 3-axis position ids: caption (i,0,0), image (cap_n, row, col)
1432        let cap_ids: Vec<[u32; 3]> = (0..cap_n).map(|i| [i as u32, 0, 0]).collect();
1433        let img_ids: Vec<[u32; 3]> = (0..n_img)
1434            .map(|i| [cap_n as u32, (i / wp) as u32, (i % wp) as u32])
1435            .collect();
1436        let cap_rope = rope_table(&cap_ids, &self.axes_dim);
1437        let img_rope = rope_table(&img_ids, &self.axes_dim);
1438        // f32 twins for the on-device block (values stay f64-derived).
1439        let to32 = |r: &(Vec<f64>, Vec<f64>)| {
1440            (
1441                r.0.iter().map(|&v| v as f32).collect::<Vec<f32>>(),
1442                r.1.iter().map(|&v| v as f32).collect::<Vec<f32>>(),
1443            )
1444        };
1445        let img_rope32 = to32(&img_rope);
1446        drop(head);
1447
1448        // The context refiner already ran in `refine_caption` — it is a
1449        // constant of the prompt, not of this call.
1450        for blk in &self.noise_refiner {
1451            self.block_forward(blk, &mut img, &img_rope, Some(&img_rope32), Some(&temb));
1452        }
1453
1454        // joint sequence: caption first
1455        let n = cap_n + n_img;
1456        let mut x = cap_e;
1457        x.extend_from_slice(&img);
1458        let joint_rope = (
1459            [cap_rope.0, img_rope.0].concat(),
1460            [cap_rope.1, img_rope.1].concat(),
1461        );
1462        let joint_rope32 = to32(&joint_rope);
1463        for blk in &self.layers {
1464            self.block_forward(blk, &mut x, &joint_rope, Some(&joint_rope32), Some(&temb));
1465        }
1466
1467        // norm_out: LayerNorm(eps 1e-6, no affine) · (1+scale), project
1468        let _tail = prof::span(prof::HEADTAIL);
1469        let silu_t: Vec<f32> = temb.iter().map(|&v| silu(v)).collect();
1470        let scale = linear(&silu_t, &self.out_lin1_w, &self.out_lin1_b);
1471        for row in x.chunks_exact_mut(hs) {
1472            let mean = row.iter().map(|&v| v as f64).sum::<f64>() / hs as f64;
1473            let var = row
1474                .iter()
1475                .map(|&v| (v as f64 - mean) * (v as f64 - mean))
1476                .sum::<f64>()
1477                / hs as f64;
1478            let inv = 1.0 / (var + 1e-6).sqrt();
1479            for (v, &s) in row.iter_mut().zip(&scale) {
1480                *v = ((*v as f64 - mean) * inv) as f32 * (1.0 + s);
1481            }
1482        }
1483        let mut out = vec![0f32; n * pv];
1484        self.out_lin2.matmat(&x, n, &mut out, self.pool.as_deref());
1485        for i in 0..n {
1486            for (v, &b) in out[i * pv..(i + 1) * pv].iter_mut().zip(&self.out_lin2_b) {
1487                *v += b;
1488            }
1489        }
1490
1491        // unpatchify image tokens → [c, h, w]
1492        let mut pred = vec![0f32; c * h * w];
1493        for ph in 0..hp {
1494            for pw in 0..wp {
1495                let src = &out[(cap_n + ph * wp + pw) * pv..(cap_n + ph * wp + pw + 1) * pv];
1496                for dy in 0..p {
1497                    for dx in 0..p {
1498                        for ch in 0..c {
1499                            pred[ch * h * w + (ph * p + dy) * w + pw * p + dx] =
1500                                src[(dy * p + dx) * c + ch];
1501                        }
1502                    }
1503                }
1504            }
1505        }
1506        pred
1507    }
1508}