Skip to main content

cortiq_engine/
mmh3.rs

1//! MiniMax-H3: the packed-token audio-video DiT.
2//!
3//! One stream of tokens — `[text | audio | video]` — denoised by fifty
4//! blocks of full self-attention, 3-axis RoPE and adaLN modulation, with
5//! the video and audio latents riding different flow schedules and a
6//! separate output head each.
7//!
8//! Three things make it unlike the image DiT next door:
9//!
10//! * **The sequence is packed, not batched.** Text, audio rows and video
11//!   rows sit in one sequence and attend to each other; there is no
12//!   cross-attention. Modulation is what tells a token which modality it
13//!   is: every block emits six modulation vectors for each of three
14//!   modality tags at each of the (at most two, for t2va) distinct
15//!   timesteps, and a segment table says which row each token reads.
16//!
17//! * **adaLN arrives as a curve, not a matrix.** The released weight is
18//!   [96768, 2688] per block — 13 B parameters, 40% of the model — for a
19//!   map whose input is one number. `cortiq animate-pack` collapses it
20//!   onto a rank-24 basis of the timestep curve that already carries the
21//!   Turbo LoRA, so what lands here is [96768, 24] and a [1025, 24]
22//!   table to interpolate. Measured against the full matrix: rms 8.7e-5
23//!   on a signal of rms 0.46.
24//!
25//! * **Two clocks.** The sampler hands in the video sigma; the audio
26//!   stream's own sigma is a closed-form remap of it (shift 12 → 3), and
27//!   the two are integrated separately. `forward` returns both
28//!   velocities unscaled, each on its own schedule — the reference
29//!   returns the audio one pre-multiplied by d(σ_a)/d(σ_v) so that a
30//!   single-schedule sampler is approximately right, which at four steps
31//!   it is not.
32//!
33//! Parity: `tools/mk_mmh3_toy.py` builds a toy checkpoint carrying the
34//! release's real tensor names and a golden forward from ComfyUI's own
35//! module; `tools/mmh3_toy_gate.sh` diffs this port against it.
36
37use crate::dit::Proj;
38use crate::ltxlora::{LoraBank, LoraBranch};
39
40/// Per-phase microseconds of the DiT block, under `CMF_MMH3_PROF=1`:
41/// 0 norm+modulate · 1 qkv GEMM · 2 qk-norm+RoPE · 3 attention ·
42/// 4 out GEMM+residual · 5 fc1 GEMM · 6 SwiGLU · 7 fc2 GEMM.
43pub static MMH3_PROF: [std::sync::atomic::AtomicU64; 9] = [
44    std::sync::atomic::AtomicU64::new(0),
45    std::sync::atomic::AtomicU64::new(0),
46    std::sync::atomic::AtomicU64::new(0),
47    std::sync::atomic::AtomicU64::new(0),
48    std::sync::atomic::AtomicU64::new(0),
49    std::sync::atomic::AtomicU64::new(0),
50    std::sync::atomic::AtomicU64::new(0),
51    std::sync::atomic::AtomicU64::new(0),
52    std::sync::atomic::AtomicU64::new(0),
53];
54
55pub(crate) fn mmh3_prof_on() -> bool {
56    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
57    *ON.get_or_init(|| std::env::var("CMF_MMH3_PROF").is_ok())
58}
59
60/// One line per phase, sorted by cost — the map that says which kernel
61/// to write next.
62pub fn mmh3_prof_report() -> Option<String> {
63    if !mmh3_prof_on() {
64        return None;
65    }
66    const NAMES: [&str; 9] = [
67        "norm+mod",
68        "qkv gemm",
69        "qknorm+rope",
70        "attention",
71        "out gemm",
72        "fc1 gemm",
73        "swiglu",
74        "fc2 gemm",
75        "residual",
76    ];
77    let mut v: Vec<(u64, &str)> = MMH3_PROF
78        .iter()
79        .map(|a| a.load(std::sync::atomic::Ordering::Relaxed))
80        .zip(NAMES)
81        .collect();
82    let total: u64 = v.iter().map(|(us, _)| *us).sum();
83    v.sort_by(|a, b| b.0.cmp(&a.0));
84    let mut out = format!("mmh3 phases (total {:.1} s):", total as f64 / 1e6);
85    for (us, name) in v {
86        out.push_str(&format!(
87            "\n  {name:<14} {:>7.1} s  {:>5.1}%",
88            us as f64 / 1e6,
89            100.0 * us as f64 / total.max(1) as f64
90        ));
91    }
92    Some(out)
93}
94
95use crate::pool::Pool;
96use cortiq_core::CmfModel;
97use std::sync::Arc;
98
99/// Frames a video latent token spans, cycling with period 5 — the
100/// checkpoint's temporal grid, which is NOT uniform.
101const FRAME_PER_TOKEN: [f64; 5] = [1.0, 4.0, 4.0, 4.0, 4.0];
102const FRAME_RESCALE: f64 = 5.0 / 3.0;
103
104/// Modality tags, as the adaLN row layout orders them.
105const TAG_VIDEO: usize = 0;
106const TAG_TEXT: usize = 1;
107const TAG_AUDIO: usize = 2;
108const MODALITIES: usize = 3;
109/// shift/scale/gate for attention, then the same three for the MLP.
110const EXPAND: usize = 6;
111/// Where a visual condition row sits on the schedule: all but arrived.
112const VISUAL_COND_TIMESTEP: f64 = 0.999;
113/// An audio condition is not noised at all.
114const AUDIO_COND_TIMESTEP: f64 = 1.0;
115
116// ── the flow-schedule remap ─────────────────────────────────────────
117
118/// σ on `to`'s schedule at the same point of the shared base grid.
119pub fn time_shift_sigma(sigma: f64, from_shift: f64, to_shift: f64) -> f64 {
120    let base = sigma / (from_shift + sigma * (1.0 - from_shift));
121    to_shift * base / (1.0 + (to_shift - 1.0) * base)
122}
123
124/// d(σ_to)/d(σ_from) at the same base-grid point.
125pub fn time_shift_slope(sigma: f64, from_shift: f64, to_shift: f64) -> f64 {
126    let base = sigma / (from_shift + sigma * (1.0 - from_shift));
127    (to_shift * (1.0 + (from_shift - 1.0) * base).powi(2))
128        / (from_shift * (1.0 + (to_shift - 1.0) * base).powi(2))
129}
130
131// ── the packed layout ───────────────────────────────────────────────
132
133#[derive(Clone, Copy, PartialEq, Debug)]
134pub enum Kind {
135    Text,
136    /// A keyframe's latent, re-injected every step and never denoised.
137    Cond,
138    /// A reference block's video rows — an image, or a clip's frames.
139    RefImg,
140    /// A reference block's audio rows.
141    RefAudio,
142    Audio,
143    Video,
144    /// Streaming context: video rows of an already-generated chunk, fed
145    /// back as the student's own x0 at timestep 0. Not denoised, not
146    /// decoded — they exist so the current chunk can attend to them.
147    CtxVideo,
148    /// The same for audio.
149    CtxAudio,
150}
151
152/// One contiguous run of rows sharing a modality tag and a timestep.
153#[derive(Clone, Copy, Debug)]
154pub struct Segment {
155    pub start: usize,
156    pub stop: usize,
157    pub kind: Kind,
158}
159
160/// The static structure of one shape signature: where each stream sits
161/// in the sequence and what 3-D position every row carries.
162pub struct Layout {
163    pub seq_len: usize,
164    pub segments: Vec<Segment>,
165    /// [seq_len, 3] — (t, h, w), f64 because the axes are fractional.
166    pub pos: Vec<[f64; 3]>,
167    pub text_len: usize,
168    pub audio_t: usize,
169    pub latent_t: usize,
170    pub lat_h: usize,
171    pub lat_w: usize,
172    /// Rows per latent frame after the 2×2 patch.
173    pub frame_rows: usize,
174    /// Per-token modality tag for the text span. A vision block inside
175    /// the prompt carries the VIDEO tag, not the text one.
176    pub text_tags: Vec<u8>,
177}
178
179/// One reference block, in the order it was given.
180#[derive(Clone, Debug)]
181pub enum Ref {
182    /// A still, at its own latent size.
183    Image { lat_h: usize, lat_w: usize },
184    /// Standalone audio, `t` latent frames of it.
185    Audio { t: usize },
186    /// Frames, with an optional soundtrack that packs immediately
187    /// before them and shares their origin.
188    Video {
189        latent_t: usize,
190        lat_h: usize,
191        lat_w: usize,
192        audio_t: usize,
193    },
194}
195
196/// Channel-major stereo rows: `t` frames per channel, the two channels
197/// pinned to the grid's extreme w coordinates so RoPE can tell them
198/// apart, h flat at zero.
199fn push_audio_grid(pos: &mut Vec<[f64; 3]>, cursor: f64, t: usize, w_low: f64, w_high: f64) {
200    for ch in 0..2 {
201        let w = if ch == 0 { w_low } else { w_high };
202        for i in 0..t {
203            pos.push([cursor + i as f64, 0.0, w]);
204        }
205    }
206}
207
208/// `linspace((1 − ratio)/2, (1 + ratio)/2, dim/patch, endpoint=False) · 32`
209fn axis_from_sqrt_area(dim: usize, patch: usize, sqrt_area: f64) -> Vec<f64> {
210    let ratio = dim as f64 / sqrt_area;
211    let n = dim / patch;
212    (0..n)
213        .map(|i| (i as f64 * (ratio / n as f64) + (1.0 - ratio) / 2.0) * 32.0)
214        .collect()
215}
216
217impl Layout {
218    /// t2va: `[text | audio | video]`, the target streams last and in
219    /// that order. Keyframe and reference blocks would slot between the
220    /// text and the audio; this port does text-to-video only.
221    pub fn t2va(
222        text_len: usize,
223        latent_t: usize,
224        lat_h: usize,
225        lat_w: usize,
226        audio_t: usize,
227    ) -> Self {
228        Self::build(text_len, latent_t, lat_h, lat_w, audio_t, &[], &[])
229    }
230
231    /// `fl2va`: keyframe condition rows sit between the text and the
232    /// audio, sharing the TARGET spatial grid, each pinned to the time
233    /// coordinate of the frame it stands for — the first frame at the
234    /// text's end, the last one a whole clip further on, minus one
235    /// span. They never advance the cursor, so audio and video still
236    /// start where they would have.
237    ///
238    /// `frames` gives each keyframe's pixel index and the clip's total,
239    /// and `text_tags` the per-token modality of the prompt span.
240    pub fn fl2va(
241        text_len: usize,
242        latent_t: usize,
243        lat_h: usize,
244        lat_w: usize,
245        audio_t: usize,
246        frames: &[(usize, usize)],
247        text_tags: &[u8],
248    ) -> Self {
249        Self::build(text_len, latent_t, lat_h, lat_w, audio_t, frames, text_tags)
250    }
251
252    /// `ref2va`: reference images, audio and clips ahead of the target
253    /// streams. Unlike a keyframe, a reference ADVANCES the cursor —
254    /// each block occupies its own stretch of the time axis, and the
255    /// target audio and video begin after the last of them.
256    pub fn ref2va(
257        text_len: usize,
258        latent_t: usize,
259        lat_h: usize,
260        lat_w: usize,
261        audio_t: usize,
262        refs: &[Ref],
263        text_tags: &[u8],
264    ) -> Self {
265        Self::build_full(
266            text_len,
267            latent_t,
268            lat_h,
269            lat_w,
270            audio_t,
271            &[],
272            refs,
273            text_tags,
274        )
275    }
276
277    fn build(
278        text_len: usize,
279        latent_t: usize,
280        lat_h: usize,
281        lat_w: usize,
282        audio_t: usize,
283        frames: &[(usize, usize)],
284        text_tags: &[u8],
285    ) -> Self {
286        Self::build_full(
287            text_len,
288            latent_t,
289            lat_h,
290            lat_w,
291            audio_t,
292            frames,
293            &[],
294            text_tags,
295        )
296    }
297
298    #[allow(clippy::too_many_arguments)]
299    fn build_full(
300        text_len: usize,
301        latent_t: usize,
302        lat_h: usize,
303        lat_w: usize,
304        audio_t: usize,
305        frames: &[(usize, usize)],
306        refs: &[Ref],
307        text_tags: &[u8],
308    ) -> Self {
309        let area = ((lat_h * lat_w) as f64).sqrt();
310        let h_axis = axis_from_sqrt_area(lat_h, 2, area);
311        let w_axis = axis_from_sqrt_area(lat_w, 2, area);
312        let frame_rows = h_axis.len() * w_axis.len();
313
314        let mut pos: Vec<[f64; 3]> = Vec::new();
315        let mut segments = Vec::new();
316
317        segments.push(Segment {
318            start: 0,
319            stop: text_len,
320            kind: Kind::Text,
321        });
322        for i in 0..text_len {
323            pos.push([i as f64, 0.0, 0.0]);
324        }
325
326        // Both target streams share this origin: the text runs out at
327        // `text_len` and audio and video start together from there —
328        // unless references push it along.
329        let mut cursor = text_len as f64;
330        let (w_low_t, w_high_t) = (w_axis[0], w_axis[w_axis.len() - 1]);
331
332        for r in refs {
333            match r {
334                Ref::Image { lat_h, lat_w } => {
335                    let (rh, rw) = (
336                        axis_from_sqrt_area(*lat_h, 2, ((lat_h * lat_w) as f64).sqrt()),
337                        axis_from_sqrt_area(*lat_w, 2, ((lat_h * lat_w) as f64).sqrt()),
338                    );
339                    let start = pos.len();
340                    for &h in &rh {
341                        for &w in &rw {
342                            pos.push([cursor, h, w]);
343                        }
344                    }
345                    segments.push(Segment {
346                        start,
347                        stop: pos.len(),
348                        kind: Kind::RefImg,
349                    });
350                    cursor += 1.0;
351                }
352                Ref::Audio { t } => {
353                    if *t > 0 {
354                        let start = pos.len();
355                        push_audio_grid(&mut pos, cursor, *t, w_low_t, w_high_t);
356                        segments.push(Segment {
357                            start,
358                            stop: pos.len(),
359                            kind: Kind::RefAudio,
360                        });
361                    }
362                    cursor += *t as f64;
363                }
364                Ref::Video {
365                    latent_t: vt,
366                    lat_h: rh_,
367                    lat_w: rw_,
368                    audio_t: rt,
369                } => {
370                    let area = ((rh_ * rw_) as f64).sqrt();
371                    let rh = axis_from_sqrt_area(*rh_, 2, area);
372                    let rw = axis_from_sqrt_area(*rw_, 2, area);
373                    // The block's audio packs immediately BEFORE its
374                    // frames, both from the same origin, and takes its
375                    // w extremes from the block's own grid.
376                    if *rt > 0 {
377                        let start = pos.len();
378                        push_audio_grid(&mut pos, cursor, *rt, rw[0], rw[rw.len() - 1]);
379                        segments.push(Segment {
380                            start,
381                            stop: pos.len(),
382                            kind: Kind::RefAudio,
383                        });
384                    }
385                    let start = pos.len();
386                    let mut t_coord = cursor;
387                    for k in 0..*vt {
388                        for &h in &rh {
389                            for &w in &rw {
390                                pos.push([t_coord, h, w]);
391                            }
392                        }
393                        t_coord += FRAME_RESCALE * FRAME_PER_TOKEN[k % 5];
394                    }
395                    segments.push(Segment {
396                        start,
397                        stop: pos.len(),
398                        kind: Kind::RefImg,
399                    });
400                    let spans: f64 = (0..*vt)
401                        .map(|k| FRAME_RESCALE * FRAME_PER_TOKEN[k % 5])
402                        .sum();
403                    cursor += (*rt as f64).max(spans);
404                }
405            }
406        }
407        let cursor = cursor;
408
409        // Keyframes, in the order given.
410        let spans: f64 = (0..latent_t)
411            .map(|k| FRAME_RESCALE * FRAME_PER_TOKEN[k % 5])
412            .sum();
413        for &(pixel_index, frame_count) in frames {
414            let cond_t = if pixel_index == 0 {
415                cursor
416            } else if frame_count > 0 && pixel_index == frame_count - 1 {
417                cursor + spans - FRAME_RESCALE
418            } else {
419                panic!("only the first and last frame can anchor a keyframe");
420            };
421            let start = pos.len();
422            for &h in &h_axis {
423                for &w in &w_axis {
424                    pos.push([cond_t, h, w]);
425                }
426            }
427            segments.push(Segment {
428                start,
429                stop: pos.len(),
430                kind: Kind::Cond,
431            });
432        }
433
434        // Audio is channel-major stereo: every latent frame once per
435        // channel, the two channels pinned to the frame grid's extreme
436        // w coordinates so they are distinguishable under RoPE.
437        let a_start = pos.len();
438        push_audio_grid(&mut pos, cursor, audio_t, w_low_t, w_high_t);
439        segments.push(Segment {
440            start: a_start,
441            stop: pos.len(),
442            kind: Kind::Audio,
443        });
444
445        // Video: the t axis advances by the per-token frame spans, not
446        // by one; h/w come from the shared frame grid.
447        let v_start = pos.len();
448        let mut t_coord = cursor;
449        for k in 0..latent_t {
450            for &h in &h_axis {
451                for &w in &w_axis {
452                    pos.push([t_coord, h, w]);
453                }
454            }
455            t_coord += FRAME_RESCALE * FRAME_PER_TOKEN[k % 5];
456        }
457        segments.push(Segment {
458            start: v_start,
459            stop: pos.len(),
460            kind: Kind::Video,
461        });
462
463        Self {
464            seq_len: pos.len(),
465            segments,
466            pos,
467            text_len,
468            audio_t,
469            latent_t,
470            lat_h,
471            lat_w,
472            frame_rows,
473            text_tags: if text_tags.is_empty() {
474                vec![TAG_TEXT as u8; text_len]
475            } else {
476                text_tags.to_vec()
477            },
478        }
479    }
480
481    /// The chunk-causal layout: one chunk being denoised, and the chunks
482    /// it is allowed to see.
483    ///
484    /// RAVEN generates a clip chunk by chunk, each one extrapolated from
485    /// what came before instead of denoised as one bidirectional clip.
486    /// Its attention pattern is `sink` chunks from the start plus a
487    /// sliding `window` of recent ones — the reference implements that
488    /// with a KV cache; the same *pattern* falls out of simply not
489    /// packing the rows a chunk may not see, which is what this builds.
490    /// The cache is then an optimization of this, not a prerequisite.
491    ///
492    /// Positions stay ABSOLUTE. A chunk five steps in must carry the RoPE
493    /// coordinates it would have had in the whole clip, or the model is
494    /// told it is generating the opening again.
495    ///
496    /// Rows come out as `[text | audio: ctx then current | video: ctx then
497    /// current]`: the audio and video blocks stay contiguous because the
498    /// patchifier hands them over that way, and audio is channel-major, so
499    /// its context is two runs — one per channel.
500    #[allow(clippy::too_many_arguments)]
501    pub fn streaming(
502        text_len: usize,
503        text_tags: &[u8],
504        lat_h: usize,
505        lat_w: usize,
506        ctx_video: &[usize],
507        cur_video: &[usize],
508        ctx_audio: &[usize],
509        cur_audio: &[usize],
510    ) -> Self {
511        let area = ((lat_h * lat_w) as f64).sqrt();
512        let h_axis = axis_from_sqrt_area(lat_h, 2, area);
513        let w_axis = axis_from_sqrt_area(lat_w, 2, area);
514        let frame_rows = h_axis.len() * w_axis.len();
515        let (w_low, w_high) = (w_axis[0], w_axis[w_axis.len() - 1]);
516
517        let mut pos: Vec<[f64; 3]> = Vec::new();
518        let mut segments = Vec::new();
519        segments.push(Segment {
520            start: 0,
521            stop: text_len,
522            kind: Kind::Text,
523        });
524        for i in 0..text_len {
525            pos.push([i as f64, 0.0, 0.0]);
526        }
527        let cursor = text_len as f64;
528
529        // The absolute t coordinate of latent frame k: the same running
530        // sum the bidirectional layout walks, evaluated at k.
531        let t_at = |k: usize| -> f64 {
532            cursor
533                + (0..k)
534                    .map(|j| FRAME_RESCALE * FRAME_PER_TOKEN[j % 5])
535                    .sum::<f64>()
536        };
537
538        // Audio, channel-major: for each channel, the context frames then
539        // the current ones, so each channel's half is [ctx | cur].
540        // Channel-major INSIDE each role, not across them: the packer
541        // hands over [ch0 | ch1] for a set of frames, so context and
542        // current each have to be one run of rows — the output side
543        // looks the current one up by kind and slices it whole.
544        for (idxs, kind) in [(ctx_audio, Kind::CtxAudio), (cur_audio, Kind::Audio)] {
545            if idxs.is_empty() {
546                continue;
547            }
548            let start = pos.len();
549            for ch in 0..2 {
550                let w = if ch == 0 { w_low } else { w_high };
551                for &i in idxs {
552                    pos.push([cursor + i as f64, 0.0, w]);
553                }
554            }
555            segments.push(Segment {
556                start,
557                stop: pos.len(),
558                kind,
559            });
560        }
561
562        for (idxs, kind) in [(ctx_video, Kind::CtxVideo), (cur_video, Kind::Video)] {
563            if idxs.is_empty() {
564                continue;
565            }
566            let start = pos.len();
567            for &k in idxs {
568                let t = t_at(k);
569                for &h in &h_axis {
570                    for &w in &w_axis {
571                        pos.push([t, h, w]);
572                    }
573                }
574            }
575            segments.push(Segment {
576                start,
577                stop: pos.len(),
578                kind,
579            });
580        }
581
582        Self {
583            seq_len: pos.len(),
584            segments,
585            pos,
586            text_len,
587            audio_t: ctx_audio.len() + cur_audio.len(),
588            latent_t: ctx_video.len() + cur_video.len(),
589            lat_h,
590            lat_w,
591            frame_rows,
592            text_tags: if text_tags.is_empty() {
593                vec![TAG_TEXT as u8; text_len]
594            } else {
595                text_tags.to_vec()
596            },
597        }
598    }
599
600    /// The contiguous span the video rows occupy — context and current
601    /// together, because the patchifier produces them as one block.
602    pub fn video_block(&self) -> (usize, usize) {
603        self.span(&[Kind::CtxVideo, Kind::Video])
604    }
605
606    /// The same for audio.
607    pub fn audio_block(&self) -> (usize, usize) {
608        self.span(&[Kind::CtxAudio, Kind::Audio])
609    }
610
611    fn span(&self, kinds: &[Kind]) -> (usize, usize) {
612        let mut lo = usize::MAX;
613        let mut hi = 0usize;
614        for s in self.segments.iter().filter(|s| kinds.contains(&s.kind)) {
615            lo = lo.min(s.start);
616            hi = hi.max(s.stop);
617        }
618        if lo == usize::MAX { (0, 0) } else { (lo, hi) }
619    }
620
621    /// How many keyframe condition rows the layout carries.
622    pub fn cond_rows(&self) -> usize {
623        self.segments
624            .iter()
625            .filter(|s| s.kind == Kind::Cond)
626            .map(|s| s.stop - s.start)
627            .sum()
628    }
629
630    fn segment(&self, kind: Kind) -> Segment {
631        *self
632            .segments
633            .iter()
634            .find(|s| s.kind == kind)
635            .expect("every layout carries all three streams")
636    }
637
638    /// MiniMax-H3-Image: `[text | reference images | target image]`, one
639    /// latent frame and no audio. Each reference is `(lat_h, lat_w)` of
640    /// its own latent; it sits at its own step of the time axis on its
641    /// own area-normalized grid, and the target follows the last of them.
642    pub fn image(
643        text_len: usize,
644        lat_h: usize,
645        lat_w: usize,
646        refs: &[(usize, usize)],
647        text_tags: &[u8],
648    ) -> Self {
649        let mut pos: Vec<[f64; 3]> = Vec::new();
650        let mut segments = vec![Segment {
651            start: 0,
652            stop: text_len,
653            kind: Kind::Text,
654        }];
655        for i in 0..text_len {
656            pos.push([i as f64, 0.0, 0.0]);
657        }
658        let mut cursor = text_len as f64;
659        let frame = |pos: &mut Vec<[f64; 3]>, h: usize, w: usize, t: f64| -> usize {
660            let area = ((h * w) as f64).sqrt();
661            let (ha, wa) = (
662                axis_from_sqrt_area(h, 2, area),
663                axis_from_sqrt_area(w, 2, area),
664            );
665            for &y in &ha {
666                for &x in &wa {
667                    pos.push([t, y, x]);
668                }
669            }
670            ha.len() * wa.len()
671        };
672        for &(rh, rw) in refs {
673            let start = pos.len();
674            let n = frame(&mut pos, rh, rw, cursor);
675            segments.push(Segment {
676                start,
677                stop: start + n,
678                kind: Kind::RefImg,
679            });
680            cursor += 1.0;
681        }
682        let start = pos.len();
683        let frame_rows = frame(&mut pos, lat_h, lat_w, cursor);
684        segments.push(Segment {
685            start,
686            stop: start + frame_rows,
687            kind: Kind::Video,
688        });
689        Self {
690            seq_len: pos.len(),
691            segments,
692            pos,
693            text_len,
694            audio_t: 0,
695            latent_t: 1,
696            lat_h,
697            lat_w,
698            frame_rows,
699            text_tags: if text_tags.is_empty() {
700                vec![TAG_TEXT as u8; text_len]
701            } else {
702                text_tags.to_vec()
703            },
704        }
705    }
706}
707
708// ── video sparse attention ──────────────────────────────────────────
709
710/// Rows of a VSA tile, padded or not: the kernels' native granularity.
711pub const VSA_TILE: usize = 64;
712
713/// Video sparse attention (VSA) as FastVideo's VSA-H3 backend runs it for a
714/// student trained with it (FastH3). The packed sequence is cut into tiles:
715/// each non-video stream (text, keyframes, audio) into chunks of 64 rows in
716/// its own order, the video into `4×4×4` blocks of `(t, h, w)` tokens
717/// (smaller at the edges). Per head, every tile is scored against every tile
718/// by the means of its queries and keys; a video query tile attends the
719/// rows of its top-k video key tiles and of every non-video tile, and a
720/// non-video query attends everything. With a trained gate, each row also
721/// adds `gate · (softmax(tile scores) · tile means of v)` of its tile — the
722/// compression branch.
723///
724/// Rows are addressed through `slot`: tile `i` owns slots `64 i .. 64 i +
725/// size[i]`, which is the order the device kernels keep q, k and v in.
726pub struct VsaPlan {
727    pub n: usize,
728    pub tiles: usize,
729    /// Tiles of the non-video streams, first in the tile order.
730    pub prefix_tiles: usize,
731    /// Video key tiles a video query tile keeps.
732    pub topk: usize,
733    /// `[n]` each row's slot.
734    pub slot: Vec<u32>,
735    /// `[tiles]` valid rows of each tile.
736    pub size: Vec<u32>,
737}
738
739impl VsaPlan {
740    /// The plan of a `[text | keyframes | audio | video]` layout, or `None`
741    /// for one VSA was not trained on (references, streaming chunks) or a
742    /// tile shape the kernels do not take.
743    pub fn build(layout: &Layout, tile: [usize; 3], sparsity: f64) -> Option<Self> {
744        if tile.iter().product::<usize>() != VSA_TILE || !(0.0..1.0).contains(&sparsity) {
745            return None;
746        }
747        let video = layout.segments.last().filter(|s| s.kind == Kind::Video && s.stop == layout.seq_len)?;
748        let (vt, vh, vw) = (layout.latent_t, layout.lat_h / 2, layout.lat_w / 2);
749        if vt * vh * vw != video.stop - video.start || vt * vh * vw == 0 {
750            return None;
751        }
752        // the non-video streams, consecutive keyframe blocks as one
753        let mut groups: Vec<(usize, usize, Kind)> = Vec::new();
754        for s in &layout.segments[..layout.segments.len() - 1] {
755            match s.kind {
756                Kind::Text | Kind::Cond | Kind::Audio => {}
757                _ => return None,
758            }
759            if s.stop == s.start {
760                continue;
761            }
762            let joins = matches!(groups.last(), Some(g) if g.2 == s.kind && g.1 == s.start);
763            if joins {
764                groups.last_mut().expect("joins a group").1 = s.stop;
765            } else {
766                groups.push((s.start, s.stop, s.kind));
767            }
768        }
769        let n = layout.seq_len;
770        let mut slot = vec![0u32; n];
771        let mut size: Vec<u32> = Vec::new();
772        for &(a, b, _) in &groups {
773            for (k, r) in (a..b).enumerate() {
774                if k % VSA_TILE == 0 {
775                    size.push(0);
776                }
777                let t = size.len() - 1;
778                slot[r] = (t * VSA_TILE + size[t] as usize) as u32;
779                size[t] += 1;
780            }
781        }
782        let prefix_tiles = size.len();
783        let [ta, ha, wa] = tile;
784        let (nt, nh, nw) = (vt.div_ceil(ta), vh.div_ceil(ha), vw.div_ceil(wa));
785        for it in 0..nt {
786            for ih in 0..nh {
787                for iw in 0..nw {
788                    let (et, eh, ew) = (ta.min(vt - it * ta), ha.min(vh - ih * ha), wa.min(vw - iw * wa));
789                    size.push((et * eh * ew) as u32);
790                }
791            }
792        }
793        for t in 0..vt {
794            for h in 0..vh {
795                for w in 0..vw {
796                    let (it, ih, iw) = (t / ta, h / ha, w / wa);
797                    let (eh, ew) = (ha.min(vh - ih * ha), wa.min(vw - iw * wa));
798                    let off = ((t - it * ta) * eh + (h - ih * ha)) * ew + (w - iw * wa);
799                    let tix = prefix_tiles + (it * nh + ih) * nw + iw;
800                    slot[video.start + (t * vh + h) * vw + w] = (tix * VSA_TILE + off) as u32;
801                }
802            }
803        }
804        let tiles = size.len();
805        let video_tiles = tiles - prefix_tiles;
806        let topk = (((1.0 - sparsity) * video_tiles as f64).ceil() as usize).clamp(1, video_tiles);
807        Some(Self {
808            n,
809            tiles,
810            prefix_tiles,
811            topk,
812            slot,
813            size,
814        })
815    }
816
817    /// The key tiles query tile `i` attends: every non-video tile, then its
818    /// `topk` best-scoring video tiles (`scores` its row of tile scores);
819    /// every tile for a non-video query.
820    pub fn select(&self, i: usize, scores: &[f32]) -> Vec<u32> {
821        if i < self.prefix_tiles || self.topk == self.tiles - self.prefix_tiles {
822            return (0..self.tiles as u32).collect();
823        }
824        let mut vid: Vec<u32> = (self.prefix_tiles as u32..self.tiles as u32).collect();
825        vid.sort_by(|&a, &b| scores[b as usize].total_cmp(&scores[a as usize]).then(a.cmp(&b)));
826        let mut out: Vec<u32> = (0..self.prefix_tiles as u32).collect();
827        out.extend_from_slice(&vid[..self.topk]);
828        out
829    }
830}
831
832/// Softmax of `x` in place, f64 sums.
833fn softmax_f64(x: &mut [f32]) {
834    let m = x.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v));
835    let mut s = 0f64;
836    for v in x.iter_mut() {
837        *v = (*v - m).exp();
838        s += *v as f64;
839    }
840    let inv = (1.0 / s) as f32;
841    for v in x.iter_mut() {
842        *v *= inv;
843    }
844}
845
846/// VSA over a qkv panel `[n][q | k | v]` whose q and k are normed and
847/// rotated, into `attn` `[n][heads · hd]`; `gate` `[n][heads · hd]` is the
848/// compression branch's gate (none: the branch is off). The host reference
849/// of the device kernels, row for row.
850#[allow(clippy::too_many_arguments)]
851pub fn vsa_attention_host(
852    plan: &VsaPlan,
853    qkv: &[f32],
854    gate: Option<&[f32]>,
855    heads: usize,
856    hd: usize,
857    attn: &mut [f32],
858    pool: Option<&Pool>,
859) {
860    let (n, t) = (plan.n, plan.tiles);
861    let inner = heads * hd;
862    let scale = 1.0 / (hd as f32).sqrt();
863    // rows of each tile, in slot order
864    let mut rows_of: Vec<Vec<u32>> = vec![Vec::new(); t];
865    let mut by_slot: Vec<(u32, u32)> = plan.slot.iter().enumerate().map(|(r, &s)| (s, r as u32)).collect();
866    by_slot.sort_unstable();
867    for (s, r) in by_slot {
868        rows_of[s as usize / VSA_TILE].push(r);
869    }
870    let at = |r: usize, plane: usize, h: usize| &qkv[r * 3 * inner + plane * inner + h * hd..][..hd];
871    for h in 0..heads {
872        // tile means of q, k and v, f64 sums
873        let mut means = vec![vec![0f32; t * hd]; 3];
874        for (i, rows) in rows_of.iter().enumerate() {
875            for (plane, m) in means.iter_mut().enumerate() {
876                let mut acc = vec![0f64; hd];
877                for &r in rows {
878                    for (a, &v) in acc.iter_mut().zip(at(r as usize, plane, h)) {
879                        *a += v as f64;
880                    }
881                }
882                for (d, a) in m[i * hd..(i + 1) * hd].iter_mut().zip(acc) {
883                    *d = (a / rows.len() as f64) as f32;
884                }
885            }
886        }
887        let mut scores = vec![0f32; t * t];
888        for i in 0..t {
889            for j in 0..t {
890                let (q, k) = (&means[0][i * hd..(i + 1) * hd], &means[1][j * hd..(j + 1) * hd]);
891                scores[i * t + j] = q.iter().zip(k).map(|(&a, &b)| a * b).sum::<f32>() * scale;
892            }
893        }
894        // the compression branch's output of every tile
895        let comp: Vec<f32> = if gate.is_some() {
896            let mut c = vec![0f32; t * hd];
897            for i in 0..t {
898                let mut p = scores[i * t..(i + 1) * t].to_vec();
899                softmax_f64(&mut p);
900                for (j, &w) in p.iter().enumerate() {
901                    for (d, &v) in c[i * hd..(i + 1) * hd].iter_mut().zip(&means[2][j * hd..(j + 1) * hd]) {
902                        *d += w * v;
903                    }
904                }
905            }
906            c
907        } else {
908            Vec::new()
909        };
910        let lists: Vec<Vec<u32>> = (0..t).map(|i| plan.select(i, &scores[i * t..(i + 1) * t])).collect();
911        let ptr = SendPtr(attn.as_mut_ptr());
912        let work = |lo: usize, hi: usize| {
913            let mut s: Vec<f32> = Vec::new();
914            let mut keys: Vec<u32> = Vec::new();
915            for r in lo..hi {
916                let i = plan.slot[r] as usize / VSA_TILE;
917                keys.clear();
918                for &kt in &lists[i] {
919                    keys.extend_from_slice(&rows_of[kt as usize]);
920                }
921                let q = at(r, 0, h);
922                s.clear();
923                s.extend(keys.iter().map(|&k| {
924                    q.iter().zip(at(k as usize, 1, h)).map(|(&a, &b)| a * b).sum::<f32>() * scale
925                }));
926                softmax_f64(&mut s);
927                // SAFETY: workers own disjoint rows; a row's head slots are its own.
928                let out = unsafe { ptr.row(r * inner + h * hd, hd) };
929                out.fill(0.0);
930                for (&w, &k) in s.iter().zip(&keys) {
931                    for (o, &v) in out.iter_mut().zip(at(k as usize, 2, h)) {
932                        *o += w * v;
933                    }
934                }
935                if let Some(g) = gate {
936                    let gr = &g[r * inner + h * hd..][..hd];
937                    for ((o, &gv), &c) in out.iter_mut().zip(gr).zip(&comp[i * hd..(i + 1) * hd]) {
938                        *o += gv * c;
939                    }
940                }
941            }
942        };
943        match pool {
944            Some(p) => p.run_rows(n, &work),
945            None => work(0, n),
946        }
947    }
948}
949
950// ── weights ─────────────────────────────────────────────────────────
951
952struct Adaln {
953    /// [out, rank] — the curve basis, already carrying the LoRA.
954    w: Proj,
955    b: Vec<f32>,
956    /// [grid, rank]
957    table: Vec<f32>,
958    rank: usize,
959    out: usize,
960}
961
962impl Adaln {
963    fn load(model: &Arc<CmfModel>, prefix: &str) -> Result<Self, String> {
964        let w = Proj::from_model(model, &format!("{prefix}.weight"))?;
965        let table = crate::dit::cmf_f32(model, &format!("{prefix}.table"))?;
966        let b = crate::dit::cmf_f32(model, &format!("{prefix}.bias"))?;
967        let out = w.rows();
968        let rank = table.len() / CURVE_GRID;
969        Ok(Self {
970            w,
971            b,
972            table,
973            rank,
974            out,
975        })
976    }
977
978    /// The modulation vectors at `ts`: `[ts.len() · MODALITIES, expand ·
979    /// hidden]` laid out so row `t·MODALITIES + tag`, chunk `e`, starts
980    /// at `(t·MODALITIES + tag)·expand·hidden + e·hidden`.
981    fn eval(&self, ts: &[f64], pool: Option<&Pool>) -> Vec<f32> {
982        let g = CURVE_GRID;
983        let mut coords = vec![0f32; ts.len() * self.rank];
984        for (i, &t) in ts.iter().enumerate() {
985            // t → fractional grid index; out-of-range clamps to the ends,
986            // and the last interval is kept whole so t = 1 does not read
987            // past the table.
988            let p = (t.clamp(0.0, 1.0) * (g - 1) as f64) as f32;
989            let i0 = (p.floor() as usize).min(g - 2);
990            let f = p - i0 as f32;
991            for k in 0..self.rank {
992                let (a, b) = (
993                    self.table[i0 * self.rank + k],
994                    self.table[(i0 + 1) * self.rank + k],
995                );
996                coords[i * self.rank + k] = a + (b - a) * f;
997            }
998        }
999        let mut out = vec![0f32; ts.len() * self.out];
1000        self.w.matmat(&coords, ts.len(), &mut out, pool);
1001        for row in out.chunks_exact_mut(self.out) {
1002            for (v, &bv) in row.iter_mut().zip(&self.b) {
1003                *v += bv;
1004            }
1005        }
1006        out
1007    }
1008}
1009
1010struct Block {
1011    norm1: Vec<f32>,
1012    norm2: Vec<f32>,
1013    qkv: Proj, // [3·heads·hd, hidden]
1014    out: Proj, // [hidden, heads·hd]
1015    q_norm: Vec<f32>,
1016    k_norm: Vec<f32>,
1017    fc1: Proj, // [2·ffn, hidden]
1018    fc2: Proj, // [hidden, ffn]
1019    adaln: Option<Adaln>,
1020    /// VSA's compression-branch gate `[heads·hd, hidden]` (FastH3).
1021    gate: Option<Proj>,
1022    /// Runtime low-rank branches, one per projection an adapter names.
1023    /// A branch is why the fused device paths below stand down: they
1024    /// keep qkv, the attention output and the FFN's middle on the card,
1025    /// and the branch has to read exactly those.
1026    lora: BlockLora,
1027}
1028
1029/// The four projections an adapter can reach in a packed block. `adaln`
1030/// is deliberately absent: this container carries the modulation as a
1031/// rank-24 curve, and folding an adaLN update into it needs the time
1032/// embedding the packer had (`animate-pack --lora --time-embedder`).
1033#[derive(Default)]
1034struct BlockLora {
1035    qkv: Option<LoraBranch>,
1036    out: Option<LoraBranch>,
1037    fc1: Option<LoraBranch>,
1038    fc2: Option<LoraBranch>,
1039}
1040
1041/// A projection and its branch, in one device submission where the platform
1042/// has that kernel and the shapes fit — the branch reads the activation the
1043/// base GEMM already uploaded and accumulates into the output it just wrote,
1044/// so it costs no transfer of its own. Falls back to `matmat` + `add`, which
1045/// is correct everywhere and pays a round trip for the branch.
1046///
1047/// The router and the probe both need the branch and the base separated to
1048/// measure one against the other, which the fused kernel does not do — so
1049/// when either is asked for, a branch takes the split path until it HAS been
1050/// measured, and the fused one from the next step onward. Without that the
1051/// probe reports 0.0000 for every branch and reads as "this adapter does
1052/// nothing", which is what it did in the first run of it.
1053fn proj_with_lora(
1054    p: &Proj,
1055    br: &Option<LoraBranch>,
1056    x: &[f32],
1057    n: usize,
1058    out: &mut [f32],
1059    pool: Option<&Pool>,
1060) {
1061    #[cfg(target_os = "macos")]
1062    if let Some(l) = br.as_ref().filter(|l| l.live()) {
1063        if let Some((model, idx)) = p.q4tp_mapped() {
1064            let (rows, cols) = (p.rows(), p.cols());
1065            if n >= 32
1066                && cols % 32 == 0
1067                && crate::gpu::enabled_here()
1068                && !crate::gpu::mm_killed()
1069                && (!crate::ltxlora::wants_measurement() || l.resonance() != 0.0)
1070                && crate::gpu_metal::q4tp_matmat_lora(model, idx, x, n, rows, cols, out, &l.side())
1071            {
1072                return;
1073            }
1074        }
1075    }
1076    p.matmat(x, n, out, pool);
1077    if let Some(l) = br {
1078        l.add(x, n, out, pool);
1079    }
1080}
1081
1082impl BlockLora {
1083    /// Live, not merely present: a branch the router has switched off
1084    /// gives the fused device path back for the rest of the render.
1085    fn live(br: &Option<LoraBranch>) -> bool {
1086        br.as_ref().is_some_and(|l| l.live())
1087    }
1088    fn ffn_any(&self) -> bool {
1089        Self::live(&self.fc1) || Self::live(&self.fc2)
1090    }
1091}
1092
1093pub(crate) const CURVE_GRID: usize = 1025;
1094
1095pub struct MiniMaxH3 {
1096    video_patch: Proj,
1097    video_patch_b: Vec<f32>,
1098    /// `None` on MiniMax-H3-Image, which has no audio stream.
1099    audio_patch: Option<Proj>,
1100    audio_patch_b: Vec<f32>,
1101    condition: Proj,
1102    condition_b: Vec<f32>,
1103    refiner: Vec<Block>,
1104    refiner_norm: Vec<f32>,
1105    blocks: Vec<Block>,
1106    final_norm: Vec<f32>,
1107    final_adaln: Adaln,
1108    video_out: Proj,
1109    video_out_b: Vec<f32>,
1110    audio_out: Option<Proj>,
1111    audio_out_b: Vec<f32>,
1112    /// MiniMax-H3-Image's output layer as plain f32 `[pdd_steps · out, hidden]`:
1113    /// a bank of per-step heads, block 0 a full head and the rest offsets
1114    /// from it. Empty on the video model.
1115    pdd_w: Vec<f32>,
1116    /// How many heads the bank stacks (1: a plain output layer) and the
1117    /// sigma grid they were distilled on.
1118    pub pdd_steps: usize,
1119    pub pdd_sigmas: Vec<f64>,
1120    /// MiniMax-H3-Image: `[text | reference images | target image]`.
1121    pub image: bool,
1122    /// The container, for the device chain's weight lookups.
1123    model: Arc<CmfModel>,
1124    inv_freq: Vec<f32>,
1125    pool: Option<Arc<Pool>>,
1126    pub hidden: usize,
1127    pub heads: usize,
1128    pub head_dim: usize,
1129    pub ffn: usize,
1130    pub latents_dim: usize,
1131    pub audio_dim: usize,
1132    pub text_dim: usize,
1133    pub shift_video: f64,
1134    pub shift_audio: f64,
1135    eps: f64,
1136    qk_eps: f64,
1137    final_eps: f64,
1138    /// How much of a keyframe latent survives the noise blend, and
1139    /// therefore where its rows sit on the schedule. `VISUAL_COND_
1140    /// TIMESTEP` is the reference's default; 1.0 turns the blend off.
1141    pub cond_aug: f64,
1142    /// The same, for a reference soundtrack. The reference's default is
1143    /// 1.0 — an audio condition is not noised at all.
1144    pub cond_aug_audio: f64,
1145    /// Adapter keys that found a projection, for the caller's report.
1146    lora_bound: std::collections::BTreeSet<String>,
1147    /// The trained video sparse attention: (sparsity, tile shape). `None`
1148    /// for a dense model; `CMF_VSA=0` forces dense attention on a sparse
1149    /// one (an A/B, not what the student was trained for).
1150    pub vsa: Option<(f64, [usize; 3])>,
1151    /// A few-step student's own schedule, unshifted (`[0.999, 0.749, 0.5,
1152    /// 0.25, 0]` for FastH3); empty: the `simple` grid.
1153    pub sampler_base_sigmas: Vec<f64>,
1154}
1155
1156fn rms_norm_into(x: &[f32], w: &[f32], eps: f64, dst: &mut [f32]) {
1157    let ss = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
1158    let inv = 1.0 / (ss + eps).sqrt();
1159    for ((d, &v), &g) in dst.iter_mut().zip(x).zip(w) {
1160        *d = (v as f64 * inv) as f32 * g;
1161    }
1162}
1163
1164fn silu(v: f32) -> f32 {
1165    v / (1.0 + (-v).exp())
1166}
1167
1168impl MiniMaxH3 {
1169    pub fn from_cmf(model: &Arc<CmfModel>) -> Result<Self, String> {
1170        Self::from_cmf_lora(model, None)
1171    }
1172
1173    /// The same, with an adapter consulted for every projection.
1174    ///
1175    /// The base weights are q4tp and stay untouched: a rank-32 update
1176    /// cannot be folded into a four-bit ladder without dequantizing the
1177    /// whole DiT, so the branch rides beside the base GEMM the way
1178    /// [`crate::ltxlora`] does it for LTX.
1179    pub fn from_cmf_lora(model: &Arc<CmfModel>, bank: Option<&LoraBank>) -> Result<Self, String> {
1180        let cfg: serde_json::Value = serde_json::from_slice(
1181            model
1182                .tensor_bytes("dit.config_json")
1183                .map_err(|e| e.to_string())?,
1184        )
1185        .map_err(|e| format!("dit.config_json: {e}"))?;
1186        let u = |k: &str| cfg[k].as_u64().unwrap_or(0) as usize;
1187        let f = |k: &str, d: f64| cfg[k].as_f64().unwrap_or(d);
1188        let n_blocks = u("num_layers");
1189        let n_refiner = u("token_refiner_num_layers");
1190        let f32v = |n: &str| crate::dit::cmf_f32(model, n);
1191        let image = cfg["image"].as_bool() == Some(true);
1192        let pdd_steps = u("pdd_steps").max(1);
1193        let pdd_sigmas: Vec<f64> = cfg["pdd_sigmas"]
1194            .as_array()
1195            .map(|a| a.iter().filter_map(|v| v.as_f64()).collect())
1196            .unwrap_or_default();
1197        if pdd_steps > 1 && pdd_sigmas.len() != pdd_steps + 1 {
1198            return Err(format!(
1199                "dit.config_json: {pdd_steps} PDD heads need {} sigmas, got {}",
1200                pdd_steps + 1,
1201                pdd_sigmas.len()
1202            ));
1203        }
1204
1205        // Which of the adapter's names actually found a projection here.
1206        let bound: std::cell::RefCell<std::collections::BTreeSet<String>> = Default::default();
1207        let load_block = |prefix: &str, with_adaln: bool| -> Result<Block, String> {
1208            let qkv = Proj::from_model(model, &format!("dit.{prefix}.attn.qkv_proj.weight"))?;
1209            let out = Proj::from_model(model, &format!("dit.{prefix}.attn.out_proj.weight"))?;
1210            let fc1 = Proj::from_model(model, &format!("dit.{prefix}.mlp.fc1.weight"))?;
1211            let fc2 = Proj::from_model(model, &format!("dit.{prefix}.mlp.fc2.weight"))?;
1212            // A branch is bound against the SHAPE of the projection it will
1213            // ride: `add` writes n·out floats through a raw pointer, so an
1214            // adapter for another model has to be refused by name, not
1215            // discovered as a corrupted panel.
1216            let lora = match bank {
1217                None => BlockLora::default(),
1218                Some(k) => {
1219                    let mut take = |suffix: &str, p: &Proj| -> Result<Option<LoraBranch>, String> {
1220                        let key = format!("{prefix}.{suffix}");
1221                        let br = k.branch_for(&format!("dit.{key}"), p.rows(), p.cols())?;
1222                        if br.is_some() {
1223                            bound.borrow_mut().insert(key);
1224                        }
1225                        Ok(br)
1226                    };
1227                    BlockLora {
1228                        qkv: take("attn.qkv_proj", &qkv)?,
1229                        out: take("attn.out_proj", &out)?,
1230                        fc1: take("mlp.fc1", &fc1)?,
1231                        fc2: take("mlp.fc2", &fc2)?,
1232                    }
1233                }
1234            };
1235            Ok(Block {
1236                norm1: f32v(&format!("dit.{prefix}.norm1.weight"))?,
1237                norm2: f32v(&format!("dit.{prefix}.norm2.weight"))?,
1238                qkv,
1239                out,
1240                q_norm: f32v(&format!("dit.{prefix}.attn.q_norm.weight"))?,
1241                k_norm: f32v(&format!("dit.{prefix}.attn.k_norm.weight"))?,
1242                fc1,
1243                fc2,
1244                adaln: if with_adaln {
1245                    Some(Adaln::load(model, &format!("dit.{prefix}.adaln"))?)
1246                } else {
1247                    None
1248                },
1249                gate: {
1250                    let name = format!("dit.{prefix}.attn.gate_compress.weight");
1251                    // `CMF_VSA_GATE=0`: the sparse attention without its
1252                    // compression branch (a diagnostic, every backend alike)
1253                    if model.tensor_index(&name).is_some() && std::env::var("CMF_VSA_GATE").as_deref() != Ok("0") {
1254                        Some(Proj::from_model(model, &name)?)
1255                    } else {
1256                        None
1257                    }
1258                },
1259                lora,
1260            })
1261        };
1262        let blocks = (0..n_blocks)
1263            .map(|i| load_block(&format!("blocks.{i}"), true))
1264            .collect::<Result<Vec<_>, _>>()?;
1265        let refiner = (0..n_refiner)
1266            .map(|i| load_block(&format!("token_refiner.blocks.{i}"), false))
1267            .collect::<Result<Vec<_>, _>>()?;
1268
1269        Ok(Self {
1270            video_patch: Proj::from_model(model, "dit.video_patch_proj.weight")?,
1271            video_patch_b: f32v("dit.video_patch_proj.bias")?,
1272            audio_patch: if image {
1273                None
1274            } else {
1275                Some(Proj::from_model(model, "dit.audio_patch_proj.weight")?)
1276            },
1277            audio_patch_b: if image {
1278                Vec::new()
1279            } else {
1280                f32v("dit.audio_patch_proj.bias")?
1281            },
1282            condition: Proj::from_model(model, "dit.condition_proj.weight")?,
1283            condition_b: f32v("dit.condition_proj.bias")?,
1284            refiner,
1285            refiner_norm: f32v("dit.token_refiner.final_norm.weight")?,
1286            blocks,
1287            final_norm: f32v("dit.final_layer.norm.weight")?,
1288            final_adaln: Adaln::load(model, "dit.final_layer.adaln")?,
1289            video_out: Proj::from_model(model, "dit.final_layer.video_out.weight")?,
1290            video_out_b: f32v("dit.final_layer.video_out.bias")?,
1291            audio_out: if image {
1292                None
1293            } else {
1294                Some(Proj::from_model(model, "dit.final_layer.audio_out.weight")?)
1295            },
1296            audio_out_b: if image {
1297                Vec::new()
1298            } else {
1299                f32v("dit.final_layer.audio_out.bias")?
1300            },
1301            pdd_w: if pdd_steps > 1 {
1302                f32v("dit.final_layer.video_out.weight")?
1303            } else {
1304                Vec::new()
1305            },
1306            pdd_steps,
1307            pdd_sigmas,
1308            image,
1309            model: model.clone(),
1310            inv_freq: f32v("dit.rope_inv_freq")?,
1311            pool: Pool::from_env(),
1312            hidden: u("hidden_size"),
1313            heads: u("num_attention_heads"),
1314            head_dim: u("attention_head_dim"),
1315            ffn: u("ffn_hidden_size"),
1316            latents_dim: u("latents_dim"),
1317            audio_dim: u("audio_latents_dim"),
1318            text_dim: u("text_dim"),
1319            shift_video: f("sigma_shift_video", 12.0),
1320            shift_audio: f("sigma_shift_audio", 3.0),
1321            eps: f("norm_eps", 1e-5),
1322            qk_eps: f("qk_norm_eps", 1e-5),
1323            final_eps: f("final_norm_eps", 1e-5),
1324            cond_aug: VISUAL_COND_TIMESTEP,
1325            cond_aug_audio: AUDIO_COND_TIMESTEP,
1326            lora_bound: bound.into_inner(),
1327            vsa: match (cfg["vsa_sparsity"].as_f64(), cfg["vsa_tile"].as_array()) {
1328                (Some(s), Some(t)) if t.len() == 3 && std::env::var("CMF_VSA").as_deref() != Ok("0") => {
1329                    let d = |i: usize| t[i].as_u64().unwrap_or(0) as usize;
1330                    // `CMF_VSA_SPARSITY`: another share of video tiles dropped
1331                    // (0 keeps them all: the full attention plus the gated
1332                    // compression branch — the kernels' parity check)
1333                    let s = std::env::var("CMF_VSA_SPARSITY")
1334                        .ok()
1335                        .and_then(|v| v.parse::<f64>().ok())
1336                        .filter(|v| (0.0..1.0).contains(v))
1337                        .unwrap_or(s);
1338                    Some((s, [d(0), d(1), d(2)]))
1339                }
1340                _ => None,
1341            },
1342            sampler_base_sigmas: cfg["sampler_base_sigmas"]
1343                .as_array()
1344                .map(|a| a.iter().filter_map(|v| v.as_f64()).collect())
1345                .unwrap_or_default(),
1346        })
1347    }
1348
1349    /// The video sigma grid of a `steps`-step render: the student's own
1350    /// schedule shifted onto the video clock when it carries one and
1351    /// `steps` matches it, else `None` (the caller's `simple` grid).
1352    pub fn student_sigmas(&self, steps: usize) -> Option<Vec<f64>> {
1353        let b = &self.sampler_base_sigmas;
1354        if b.len() < 2 || b.len() - 1 != steps {
1355            return None;
1356        }
1357        let s = self.shift_video;
1358        Some(b.iter().map(|&x| s * x / (1.0 + (s - 1.0) * x)).collect())
1359    }
1360
1361    /// The VSA plan of `layout` (`None`: a dense model, or a layout the
1362    /// sparse attention was not trained on — which then runs dense).
1363    pub fn vsa_plan(&self, layout: &Layout) -> Option<VsaPlan> {
1364        let (s, tile) = self.vsa?;
1365        let plan = VsaPlan::build(layout, tile, s);
1366        if plan.is_none() {
1367            static SAID: std::sync::Once = std::sync::Once::new();
1368            SAID.call_once(|| eprintln!("vsa: this layout is not [text | keyframes | audio | video] — dense attention"));
1369        }
1370        plan
1371    }
1372
1373    /// How many of the adapter's branches found a projection.
1374    pub fn lora_bound(&self) -> usize {
1375        self.lora_bound.len()
1376    }
1377
1378    /// Whether this adapter key landed on a projection of ours.
1379    pub fn lora_binds(&self, key: &str) -> bool {
1380        self.lora_bound.contains(key)
1381    }
1382
1383    /// Under `CMF_LORA_PROBE=1`: every branch by measured contribution,
1384    /// loudest first, and which ones the router switched off. This is the
1385    /// map that says where an adapter actually lives — for the Realism
1386    /// adapter it is not uniform across the fifty blocks.
1387    pub fn lora_report(&self) -> Option<String> {
1388        if !crate::ltxlora::probe_report_on() {
1389            return None;
1390        }
1391        let mut rows: Vec<(f32, bool, String)> = Vec::new();
1392        let mut walk = |blocks: &[Block], pre: &str| {
1393            for (i, b) in blocks.iter().enumerate() {
1394                for (name, br) in [
1395                    ("attn.qkv_proj", &b.lora.qkv),
1396                    ("attn.out_proj", &b.lora.out),
1397                    ("mlp.fc1", &b.lora.fc1),
1398                    ("mlp.fc2", &b.lora.fc2),
1399                ] {
1400                    if let Some(l) = br {
1401                        rows.push((l.resonance(), l.live(), format!("{pre}{i}.{name}")));
1402                    }
1403                }
1404            }
1405        };
1406        walk(&self.blocks, "blocks.");
1407        walk(&self.refiner, "token_refiner.blocks.");
1408        if rows.is_empty() {
1409            return None;
1410        }
1411        rows.sort_by(|a, b| b.0.total_cmp(&a.0));
1412        let live = rows.iter().filter(|r| r.1).count();
1413        let mut s = format!(
1414            "lora branches by contribution ‖sΔY‖/‖Y‖ ({} of {} live):\n",
1415            live,
1416            rows.len()
1417        );
1418        for (r, on, name) in &rows {
1419            s.push_str(&format!(
1420                "  {:>8.4}  {}  {name}\n",
1421                r,
1422                if *on { "on " } else { "off" }
1423            ));
1424        }
1425        Some(s)
1426    }
1427
1428    /// Qwen3-VL states `[n, text_dim]` → refined text embeds
1429    /// `[n, hidden]`. Prompt-only, so the caller does this once per
1430    /// generation rather than once per step.
1431    pub fn refine_text(&self, states: &[f32], n: usize) -> Vec<f32> {
1432        let pool = self.pool.as_deref();
1433        let mut h = vec![0f32; n * self.hidden];
1434        self.condition.matmat(states, n, &mut h, pool);
1435        for row in h.chunks_exact_mut(self.hidden) {
1436            for (v, &b) in row.iter_mut().zip(&self.condition_b) {
1437                *v += b;
1438            }
1439        }
1440        self.run_blocks(&self.refiner, &mut h, n, &[], &[], &[], None);
1441        let mut out = vec![0f32; n * self.hidden];
1442        for (o, x) in out
1443            .chunks_exact_mut(self.hidden)
1444            .zip(h.chunks_exact(self.hidden))
1445        {
1446            rms_norm_into(x, &self.refiner_norm, self.final_eps, o);
1447        }
1448        out
1449    }
1450
1451    /// The rotation angles of every row: `[n, 48]`. Each of the three
1452    /// position axes contributes `inv_freq.len()` angles, and the pair
1453    /// (j, j+48) of the first 96 head dims rotates by angle j.
1454    fn rope_angles(&self, pos: &[[f64; 3]]) -> Vec<f32> {
1455        let k = self.inv_freq.len();
1456        let mut out = Vec::with_capacity(pos.len() * 3 * k);
1457        for p in pos {
1458            for axis in 0..3 {
1459                for j in 0..k {
1460                    out.push((p[axis] * self.inv_freq[j] as f64) as f32);
1461                }
1462            }
1463        }
1464        out
1465    }
1466
1467    /// Per-head RMSNorm then the partial split-half rotation, in place.
1468    /// `angles` carries 48 angles a row — three axes × 16 frequencies —
1469    /// and pair (j, j+48) of the head's first 96 dims turns by angle j.
1470    /// Dims 96..128 are not rotated at all, which is the checkpoint's
1471    /// own `rope_inv_freq_len` arithmetic and not a truncation.
1472    /// In place on a STRIDED view of the fused qkv buffer: `stride` is
1473    /// the row pitch and `off` the plane's start. Normalizing q and k
1474    /// through a scratch copy cost four full passes over `n·heads·hd`
1475    /// per block — 10 G element copies over a render — for arithmetic
1476    /// that touches each element once.
1477    #[allow(clippy::too_many_arguments)]
1478    fn norm_rope_w(
1479        &self,
1480        v: &mut [f32],
1481        n: usize,
1482        heads: usize,
1483        w: &[f32],
1484        angles: &[f32],
1485        stride: usize,
1486        off: usize,
1487    ) {
1488        let hd = self.head_dim;
1489        let pairs = if angles.is_empty() {
1490            0
1491        } else {
1492            angles.len() / n
1493        };
1494        let pool = self.pool.as_deref();
1495        let ptr = SendPtr(v.as_mut_ptr());
1496        let work = |lo: usize, hi: usize| {
1497            for p in lo..hi {
1498                for h in 0..heads {
1499                    // SAFETY: workers own disjoint token ranges, and the
1500                    // heads of one token are disjoint within it.
1501                    let x = unsafe { ptr.row(p * stride + off + h * hd, hd) };
1502                    let ss = x.iter().map(|&a| (a as f64) * (a as f64)).sum::<f64>() / hd as f64;
1503                    let inv = 1.0 / (ss + self.qk_eps).sqrt();
1504                    for (d, &g) in x.iter_mut().zip(w) {
1505                        *d = (*d as f64 * inv) as f32 * g;
1506                    }
1507                    for j in 0..pairs {
1508                        let a = angles[p * pairs + j];
1509                        let (s, c) = a.sin_cos();
1510                        let (lo_v, hi_v) = (x[j], x[j + pairs]);
1511                        x[j] = lo_v * c - hi_v * s;
1512                        x[j + pairs] = lo_v * s + hi_v * c;
1513                    }
1514                }
1515            }
1516        };
1517        match pool {
1518            Some(pl) => pl.run_rows(n, &work),
1519            None => work(0, n),
1520        }
1521    }
1522
1523    /// Full bidirectional attention over the packed sequence.
1524    /// `nr` = (rope angles, q norm weights, k norm weights, eps) when the
1525    /// DEVICE should apply qk-norm and RoPE. Passing it means the caller
1526    /// skipped `norm_rope_w`, which is the only reason the qkv panel had
1527    /// to come back to the host at all.
1528    fn attention(
1529        &self,
1530        qkv: &[f32],
1531        n: usize,
1532        attn: &mut [f32],
1533        nr: Option<(&[f32], &[f32], &[f32], f32)>,
1534    ) {
1535        let t_repack = std::time::Instant::now();
1536        let (nh, hd) = (self.heads, self.head_dim);
1537        let inner = nh * hd;
1538        let scale = 1.0 / (hd as f32).sqrt();
1539        let pool = self.pool.as_deref();
1540        // Device path: scores, softmax and the PV product all stay in
1541        // device buffers (`dit_qk` → `dit_softmax` → `dit_pv`), so the
1542        // n×n score plane — 144 MB at render size — never crosses the
1543        // bus. Measured share of a denoise step before this: 41.5%.
1544        // The kernels exist and Lumina's DiT already rides them; this
1545        // block is what puts MiniMax on the same road. CMF_MMH3_ATTN=cpu
1546        // forces the host loop (the A/B that proved the parity).
1547        if std::env::var("CMF_MMH3_ATTN").as_deref() != Ok("cpu")
1548            && crate::gpu::enabled_here()
1549            && n >= 256
1550        {
1551            // The qkv panel goes up in one piece and is split into
1552            // head-major planes ON the card. The host repack below cost
1553            // 4.4 s of a 7.3 s attention phase — more than the device
1554            // work it fed. Measured at render size: repack 4.4 → 1.5 s,
1555            // render 130.0 → 111.8 s, frames bit-identical.
1556            // `CMF_MMH3_ATTN=repack` forces the host form.
1557            // The device can do qk-norm and RoPE itself (kernel and
1558            // plumbing are in; pass Some((angles, q_norm, k_norm, eps))).
1559            // `attention` cannot reach them: they live in the caller,
1560            // and handing them over means changing this signature — the
1561            // last step of task #33, and the point where the panel stops
1562            // coming home at all.
1563            if std::env::var("CMF_MMH3_ATTN").as_deref() != Ok("repack")
1564                && crate::gpu::dit_attention_packed(qkv, nh, n, hd, scale, nr, attn)
1565            {
1566                // No stamp: the caller's slot-3 stopwatch already spans
1567                // this whole call, and CMF_DIT_ATTN_PROF breaks the
1568                // device half into its three walls. Two overlapping
1569                // stopwatches on the same work is how a 19.2 s step
1570                // came to read as 26.1.
1571                return;
1572            }
1573            assert!(
1574                nr.is_none(),
1575                "device qk-norm was requested but the device path refused; \
1576                 the host loops below expect q/k already normalized"
1577            );
1578            let mut qh = vec![0f32; nh * n * hd];
1579            let mut kh = vec![0f32; nh * n * hd];
1580            let mut vh = vec![0f32; nh * n * hd];
1581            {
1582                let (pq, pk, pv) = (
1583                    SendPtr(qh.as_mut_ptr()),
1584                    SendPtr(kh.as_mut_ptr()),
1585                    SendPtr(vh.as_mut_ptr()),
1586                );
1587                pool_rows(pool, n, &|lo, hi| {
1588                    for p in lo..hi {
1589                        let base = p * 3 * inner;
1590                        for h in 0..nh {
1591                            let dst = (h * n + p) * hd;
1592                            // SAFETY: workers own disjoint token ranges,
1593                            // and each token writes its own head slots.
1594                            unsafe {
1595                                pq.row(dst, hd)
1596                                    .copy_from_slice(&qkv[base + h * hd..base + (h + 1) * hd]);
1597                                pk.row(dst, hd).copy_from_slice(
1598                                    &qkv[base + inner + h * hd..base + inner + (h + 1) * hd],
1599                                );
1600                                pv.row(dst, hd).copy_from_slice(
1601                                    &qkv[base + 2 * inner + h * hd
1602                                        ..base + 2 * inner + (h + 1) * hd],
1603                                );
1604                            }
1605                        }
1606                    }
1607                });
1608            }
1609            // Split the phase: the repack above is host work, this call
1610            // is device work. The last round wrote a tensor-core QK on
1611            // the assumption that the GEMMs dominate and the step did
1612            // not move — so measure the halves before writing anything
1613            // else. Slot 2 (qknorm+rope, unused on this path) takes the
1614            // repack; slot 3 keeps the device call.
1615            Self::prof(2, t_repack);
1616            // No stamp on the device call: the caller's slot-3 stopwatch
1617            // already spans it, and stamping both double-counts.
1618            if crate::gpu::dit_attention(&qh, &kh, &vh, nh, nh, n, hd, scale, attn) {
1619                return;
1620            }
1621        }
1622        let mut qh = vec![0f32; n * hd];
1623        let mut kh = vec![0f32; n * hd];
1624        let mut vt = vec![0f32; hd * n];
1625        let mut scores = vec![0f32; n * n];
1626        let mut oh = vec![0f32; n * hd];
1627        for h in 0..nh {
1628            for p in 0..n {
1629                let base = p * 3 * inner;
1630                let qs = &qkv[base + h * hd..base + (h + 1) * hd];
1631                for (d, &val) in qs.iter().enumerate() {
1632                    qh[p * hd + d] = val * scale;
1633                }
1634                kh[p * hd..(p + 1) * hd]
1635                    .copy_from_slice(&qkv[base + inner + h * hd..base + inner + (h + 1) * hd]);
1636                let vs = &qkv[base + 2 * inner + h * hd..base + 2 * inner + (h + 1) * hd];
1637                for (d, &val) in vs.iter().enumerate() {
1638                    vt[d * n + p] = val;
1639                }
1640            }
1641            crate::fcd_ops::gemm_nt(&qh, &kh, &mut scores, n, hd, n, pool);
1642            let sp = SendPtr(scores.as_mut_ptr());
1643            let soft = |lo: usize, hi: usize| {
1644                for r in lo..hi {
1645                    // SAFETY: workers own disjoint score rows.
1646                    softmax_inplace(unsafe { sp.row(r * n, n) });
1647                }
1648            };
1649            match pool {
1650                Some(pl) => pl.run_rows(n, &soft),
1651                None => soft(0, n),
1652            }
1653            crate::fcd_ops::gemm_nt(&scores, &vt, &mut oh, n, n, hd, pool);
1654            for p in 0..n {
1655                attn[p * inner + h * hd..p * inner + (h + 1) * hd]
1656                    .copy_from_slice(&oh[p * hd..(p + 1) * hd]);
1657            }
1658        }
1659    }
1660
1661    /// Where a denoise step's wall actually goes, in microseconds, under
1662    /// `CMF_MMH3_PROF=1`. Optimizing a 60-second step without this is
1663    /// guesswork, and guesswork on a rented card is expensive.
1664    fn prof(slot: usize, t: std::time::Instant) {
1665        if !mmh3_prof_on() {
1666            return;
1667        }
1668        MMH3_PROF[slot].fetch_add(
1669            t.elapsed().as_micros() as u64,
1670            std::sync::atomic::Ordering::Relaxed,
1671        );
1672    }
1673
1674    /// One block. `mods` is the block's modulation buffer and `rows` the
1675    /// per-token row index into it; both empty for the refiner, which is
1676    /// unmodulated and unrotated.
1677    fn block_forward(
1678        &self,
1679        blk: &Block,
1680        x: &mut [f32],
1681        n: usize,
1682        mods: Option<&[f32]>,
1683        pos: &[[f64; 3]],
1684        rows: &[u32],
1685        vsa: Option<&VsaPlan>,
1686    ) {
1687        let hs = self.hidden;
1688        let pool = self.pool.as_deref();
1689        let inner = self.heads * self.head_dim;
1690        let angles = if pos.is_empty() {
1691            Vec::new()
1692        } else {
1693            self.rope_angles(pos)
1694        };
1695
1696        let t = std::time::Instant::now();
1697        let mut xn = vec![0f32; n * hs];
1698        self.norm_rows(&mut xn, x, n, hs, &blk.norm1, self.eps);
1699        if let (Some(m), false) = (mods, rows.is_empty()) {
1700            self.modulate(&mut xn, hs, m, rows, 0, 1);
1701        }
1702        Self::prof(0, t);
1703        let t = std::time::Instant::now();
1704        // The projection writes its panel into a device buffer and the
1705        // split reads it THERE — with qk-norm on the device too, nothing
1706        // touches that panel on the host, so 160 MB down and the same
1707        // back up per block simply stop happening. Measured at render
1708        // size: 104.9 → 98.1 s, frames bit-identical.
1709        // `CMF_MMH3_FUSEQKV=0` sends the panel home again.
1710        let t_qkv = std::time::Instant::now();
1711        // Ask whether the device can TAKE the norm, not merely whether a
1712        // device exists. Skipping the host loop for a backend with no
1713        // packed kernel hands the attention unnormalized q/k and there is
1714        // no way back from there — which is why the refusal below used to
1715        // be an assert.
1716        let qk_gpu = vsa.is_none()
1717            && std::env::var("CMF_MMH3_QKNORM").as_deref() != Ok("cpu")
1718            && crate::gpu::enabled_here()
1719            && crate::gpu::dit_attention_packed_available()
1720            && n >= 256;
1721        // An adapter on qkv needs the panel the fused paths never let
1722        // out of the card; one on `out` needs the attention output. Each
1723        // stands down only for the projection it owns — a qkv-only
1724        // adapter still gets device attention through the chain below.
1725        if qk_gpu
1726            && !BlockLora::live(&blk.lora.qkv)
1727            && std::env::var("CMF_MMH3_FUSEQKV").as_deref() != Ok("0")
1728        {
1729            // Best case first: qkv, attention and the output projection
1730            // with nothing crossing the bus between them. It refuses at
1731            // the door when anything is missing, so falling through to
1732            // the chain below never repeats work.
1733            let fuse_out = !BlockLora::live(&blk.lora.out)
1734                && std::env::var("CMF_MMH3_FUSEOUT").as_deref() != Ok("0");
1735            if std::env::var("CMF_GPU_DEBUG").is_ok() {
1736                static ONCE: std::sync::Once = std::sync::Once::new();
1737                ONCE.call_once(|| {
1738                    eprintln!(
1739                        "mmh3 fuse-out gate: qkv_q={} out_q={} qkv_map={} out_map={}",
1740                        matches!(&blk.qkv, Proj::Q(_)),
1741                        matches!(&blk.out, Proj::Q(_)),
1742                        matches!(&blk.qkv, Proj::Q(q) if q.mapped_device_gemm().is_some()),
1743                        matches!(&blk.out, Proj::Q(o) if o.mapped_device_gemm().is_some()),
1744                    )
1745                });
1746            }
1747            if let (true, Proj::Q(q), Proj::Q(o)) = (fuse_out, &blk.qkv, &blk.out) {
1748                if let (Some((m, i)), Some((_, oi))) =
1749                    (q.mapped_device_gemm(), o.mapped_device_gemm())
1750                {
1751                    let mut proj = vec![0f32; n * hs];
1752                    if crate::gpu::dit_qkv_attn_out(
1753                        m,
1754                        i,
1755                        oi,
1756                        &xn,
1757                        n,
1758                        hs,
1759                        self.heads,
1760                        self.head_dim,
1761                        1.0 / (self.head_dim as f32).sqrt(),
1762                        (
1763                            &angles[..],
1764                            &blk.q_norm[..],
1765                            &blk.k_norm[..],
1766                            self.qk_eps as f32,
1767                        ),
1768                        &mut proj,
1769                    ) {
1770                        Self::prof(1, t_qkv);
1771                        let t_res = std::time::Instant::now();
1772                        self.residual(x, hs, &proj, mods, rows, 2);
1773                        Self::prof(8, t_res);
1774                        self.ffn_tail(blk, x, n, mods, rows);
1775                        return;
1776                    }
1777                }
1778            }
1779            if let Proj::Q(q) = &blk.qkv {
1780                if let Some((m, i)) = q.mapped_device_gemm() {
1781                    let mut attn = vec![0f32; n * inner];
1782                    if crate::gpu::dit_qkv_attention(
1783                        m,
1784                        i,
1785                        &xn,
1786                        n,
1787                        hs,
1788                        self.heads,
1789                        self.head_dim,
1790                        1.0 / (self.head_dim as f32).sqrt(),
1791                        (
1792                            &angles[..],
1793                            &blk.q_norm[..],
1794                            &blk.k_norm[..],
1795                            self.qk_eps as f32,
1796                        ),
1797                        &mut attn,
1798                    ) {
1799                        // Stamp the same slots the unfused path does, or
1800                        // the profile reads 5.5 s for a step the device
1801                        // spends 6+ in: an instrument with a blind spot
1802                        // is worse than none, and this one has cost two
1803                        // wrong conclusions already.
1804                        Self::prof(1, t_qkv);
1805                        let t_out = std::time::Instant::now();
1806                        let mut proj = vec![0f32; n * hs];
1807                        proj_with_lora(&blk.out, &blk.lora.out, &attn, n, &mut proj, pool);
1808                        Self::prof(4, t_out);
1809                        let t_res = std::time::Instant::now();
1810                        self.residual(x, hs, &proj, mods, rows, 2);
1811                        Self::prof(8, t_res);
1812                        self.ffn_tail(blk, x, n, mods, rows);
1813                        return;
1814                    }
1815                }
1816            }
1817        }
1818        let mut qkv = vec![0f32; n * 3 * inner];
1819        proj_with_lora(&blk.qkv, &blk.lora.qkv, &xn, n, &mut qkv, pool);
1820        Self::prof(1, t);
1821        // q and k are the first two thirds of every row; normalize and
1822        // rotate them where they lie, leaving v alone.
1823        // qk-norm and RoPE ride the same device pass that scatters the
1824        // panel head-major, so the host neither walks the panel nor
1825        // needs it back. Parity holds over a whole render: 1, 2 and 4
1826        // steps all match this loop's output exactly (delta 0.000).
1827        //
1828        // A 7.7% "drift" was measured first and was an artefact — the
1829        // reference had been rendered by an EARLIER binary, so the
1830        // comparison carried every change since, not this one. Same
1831        // binary, both arms, or the number means nothing.
1832        // `CMF_MMH3_QKNORM=cpu` restores the host loop.
1833        let qk_on_gpu = qk_gpu;
1834        let t = std::time::Instant::now();
1835        if !qk_on_gpu {
1836            for (which, w) in [(0usize, &blk.q_norm), (1usize, &blk.k_norm)] {
1837                self.norm_rope_w(
1838                    &mut qkv,
1839                    n,
1840                    self.heads,
1841                    w,
1842                    &angles,
1843                    3 * inner,
1844                    which * inner,
1845                );
1846            }
1847        }
1848        Self::prof(2, t);
1849        let t = std::time::Instant::now();
1850        let mut attn = vec![0f32; n * inner];
1851        if let Some(plan) = vsa {
1852            // the sparse student: the host reference (the device runs it in
1853            // the chain); the gate reads the same modulated input as qkv
1854            let gate = blk.gate.as_ref().map(|g| {
1855                let mut v = vec![0f32; n * inner];
1856                g.matmat(&xn, n, &mut v, pool);
1857                v
1858            });
1859            vsa_attention_host(plan, &qkv, gate.as_deref(), self.heads, self.head_dim, &mut attn, pool);
1860        } else {
1861        self.attention(
1862            &qkv,
1863            n,
1864            &mut attn,
1865            qk_on_gpu.then_some((
1866                &angles[..],
1867                &blk.q_norm[..],
1868                &blk.k_norm[..],
1869                self.qk_eps as f32,
1870            )),
1871        );
1872        }
1873        Self::prof(3, t);
1874        let t = std::time::Instant::now();
1875        let mut proj = vec![0f32; n * hs];
1876        proj_with_lora(&blk.out, &blk.lora.out, &attn, n, &mut proj, pool);
1877        Self::prof(4, t);
1878        // Own slot: the residual is host-side elementwise work with
1879        // modulation, and billing it to the projection hid which of the
1880        // two actually costs (they were 9.8 s together at 512×288).
1881        let t = std::time::Instant::now();
1882        self.residual(x, hs, &proj, mods, rows, 2);
1883        Self::prof(8, t);
1884
1885        self.ffn_tail(blk, x, n, mods, rows);
1886    }
1887
1888    /// The FFN half of a block: norm, modulate, SwiGLU, residual. Its
1889    /// own function so the attention half can return early — the fused
1890    /// path (`dit_qkv_attention`) finishes attention on the device and
1891    /// has nowhere to jump to otherwise.
1892    fn ffn_tail(&self, blk: &Block, x: &mut [f32], n: usize, mods: Option<&[f32]>, rows: &[u32]) {
1893        let hs = self.hidden;
1894        let pool = self.pool.as_deref();
1895        let mut xn = vec![0f32; n * hs];
1896        let mut proj = vec![0f32; n * hs];
1897        let t = std::time::Instant::now();
1898        self.norm_rows(&mut xn, x, n, hs, &blk.norm2, self.eps);
1899        if let (Some(m), false) = (mods, rows.is_empty()) {
1900            self.modulate(&mut xn, hs, m, rows, 3, 4);
1901        }
1902        Self::prof(0, t);
1903        let t = std::time::Instant::now();
1904        // Device-resident FFN: fc1 → SwiGLU → fc2 without the
1905        // intermediate crossing the bus. At render size that panel is
1906        // hundreds of megabytes each way, per block, per step.
1907        // CMF_MMH3_FFN=cpu forces the host chain below.
1908        if std::env::var("CMF_MMH3_FFN").as_deref() != Ok("cpu")
1909            && !blk.lora.ffn_any()
1910            && crate::gpu::enabled_here()
1911            && n >= 64
1912        {
1913            if let (Proj::Q(q1), Proj::Q(q2)) = (&blk.fc1, &blk.fc2) {
1914                if let (Some((m, i1)), Some((_, i2))) =
1915                    (q1.mapped_device_gemm(), q2.mapped_device_gemm())
1916                {
1917                    let mut fout = vec![0f32; n * hs];
1918                    if crate::gpu::q4tp_ffn_packed(m, i1, i2, &xn, n, hs, self.ffn, None, &mut fout)
1919                    {
1920                        Self::prof(5, t);
1921                        self.residual(x, hs, &fout, mods, rows, 5);
1922                        return;
1923                    }
1924                }
1925            }
1926        }
1927        let mut gu = vec![0f32; n * 2 * self.ffn];
1928        proj_with_lora(&blk.fc1, &blk.lora.fc1, &xn, n, &mut gu, pool);
1929        Self::prof(5, t);
1930        let t = std::time::Instant::now();
1931        // SwiGLU: fc1's output is [gate | up] per row.
1932        let ffn = self.ffn;
1933        let mut act = vec![0f32; n * ffn];
1934        let ap = SendPtr(act.as_mut_ptr());
1935        pool_rows(pool, n, &|lo, hi| {
1936            for p in lo..hi {
1937                let row = &gu[p * 2 * ffn..(p + 1) * 2 * ffn];
1938                let (g, up) = row.split_at(ffn);
1939                // SAFETY: workers own disjoint token ranges.
1940                for (o, (&a, &b)) in unsafe { ap.row(p * ffn, ffn) }
1941                    .iter_mut()
1942                    .zip(g.iter().zip(up))
1943                {
1944                    *o = silu(a) * b;
1945                }
1946            }
1947        });
1948        Self::prof(6, t);
1949        let t = std::time::Instant::now();
1950        proj_with_lora(&blk.fc2, &blk.lora.fc2, &act, n, &mut proj, pool);
1951        Self::prof(7, t);
1952        self.residual(x, hs, &proj, mods, rows, 5);
1953    }
1954
1955    /// RMSNorm every row of `src` into `dst`, across the pool. One
1956    /// block does this four times over `n·hidden`; on a 1 879-token
1957    /// pack that is 40 M elements a block, and it was running on one
1958    /// thread while forty-seven sat idle.
1959    fn norm_rows(&self, dst: &mut [f32], src: &[f32], n: usize, hs: usize, w: &[f32], eps: f64) {
1960        let ptr = SendPtr(dst.as_mut_ptr());
1961        pool_rows(self.pool.as_deref(), n, &|lo, hi| {
1962            for p in lo..hi {
1963                // SAFETY: workers own disjoint token ranges.
1964                rms_norm_into(&src[p * hs..(p + 1) * hs], w, eps, unsafe {
1965                    ptr.row(p * hs, hs)
1966                });
1967            }
1968        });
1969    }
1970
1971    /// `x = x·(1 + scale[row]) + shift[row]`, per token, across the pool.
1972    fn modulate(
1973        &self,
1974        x: &mut [f32],
1975        hs: usize,
1976        mods: &[f32],
1977        rows: &[u32],
1978        shift_e: usize,
1979        scale_e: usize,
1980    ) {
1981        let stride = EXPAND * hs;
1982        let ptr = SendPtr(x.as_mut_ptr());
1983        pool_rows(self.pool.as_deref(), rows.len(), &|lo, hi| {
1984            for p in lo..hi {
1985                let base = rows[p] as usize * stride;
1986                let shift = &mods[base + shift_e * hs..base + (shift_e + 1) * hs];
1987                let scale = &mods[base + scale_e * hs..base + (scale_e + 1) * hs];
1988                // SAFETY: workers own disjoint token ranges.
1989                for ((v, &sc), &sh) in unsafe { ptr.row(p * hs, hs) }
1990                    .iter_mut()
1991                    .zip(scale)
1992                    .zip(shift)
1993                {
1994                    *v = *v * (1.0 + sc) + sh;
1995                }
1996            }
1997        });
1998    }
1999
2000    /// The gated residual — or a plain one where there is no modulation
2001    /// (the token refiner).
2002    fn residual(
2003        &self,
2004        x: &mut [f32],
2005        hs: usize,
2006        other: &[f32],
2007        mods: Option<&[f32]>,
2008        rows: &[u32],
2009        gate_e: usize,
2010    ) {
2011        let n = x.len() / hs;
2012        let stride = EXPAND * hs;
2013        let ptr = SendPtr(x.as_mut_ptr());
2014        let gated = mods.filter(|_| !rows.is_empty());
2015        pool_rows(self.pool.as_deref(), n, &|lo, hi| {
2016            for p in lo..hi {
2017                // SAFETY: workers own disjoint token ranges.
2018                let row = unsafe { ptr.row(p * hs, hs) };
2019                let src = &other[p * hs..(p + 1) * hs];
2020                match gated {
2021                    Some(m) => {
2022                        let base = rows[p] as usize * stride;
2023                        let gate = &m[base + gate_e * hs..base + (gate_e + 1) * hs];
2024                        for ((v, &g), &o) in row.iter_mut().zip(gate).zip(src) {
2025                            *v += g * o;
2026                        }
2027                    }
2028                    None => {
2029                        for (v, &o) in row.iter_mut().zip(src) {
2030                            *v += o;
2031                        }
2032                    }
2033                }
2034            }
2035        });
2036    }
2037
2038    /// One denoise evaluation.
2039    ///
2040    /// `video` is `[latents_dim, latent_t, lat_h, lat_w]` and `audio` is
2041    /// `[audio_dim, 2, audio_t]`, both in the reference's channel-major
2042    /// order. `text` is the refined `[n, hidden]` stream. Returns the
2043    /// two velocities, EACH ON ITS OWN SCHEDULE and unscaled.
2044    pub fn forward(
2045        &self,
2046        layout: &Layout,
2047        text: &[f32],
2048        video: &[f32],
2049        audio: &[f32],
2050        sigma_v: f64,
2051        cond: &[Vec<f32>],
2052    ) -> (Vec<f32>, Vec<f32>) {
2053        let hs = self.hidden;
2054        let pool = self.pool.as_deref();
2055        let sigma_v = sigma_v.max(1e-6);
2056        let t_v = 1.0 - sigma_v;
2057        let t_a = 1.0 - time_shift_sigma(sigma_v, self.shift_video, self.shift_audio);
2058
2059        // Distinct timesteps, sorted — the adaLN row index is a position
2060        // in this list, so the order is part of the contract. A keyframe
2061        // pins its rows near 1: they are conditions, not noise being
2062        // removed.
2063        let has_cond = layout
2064            .segments
2065            .iter()
2066            .any(|s| matches!(s.kind, Kind::Cond | Kind::RefImg));
2067        let has_ref_audio = layout.segments.iter().any(|s| s.kind == Kind::RefAudio);
2068        // A reference soundtrack pins to the AUDIO clock's condition
2069        // timestep, which is its own number.
2070        let t_cond_a = t_a.max(self.cond_aug_audio);
2071        // The condition rows' timestep IS the noise-augmentation figure:
2072        // the reference blends `aug` of the latent with `1 − aug` of
2073        // noise and then tells the block the row sits at `aug`. Turning
2074        // the blend off means aug = 1, and the timestep moves with it.
2075        let t_cond = t_v.max(self.cond_aug);
2076        // Streaming context is the student's OWN x0, handed back at
2077        // timestep 0 — the reference passes literal zeros for the clean
2078        // role, and a chunk conditioned on anything else is conditioned
2079        // on a frame the previous chunk never produced.
2080        let has_ctx = layout
2081            .segments
2082            .iter()
2083            .any(|s| matches!(s.kind, Kind::CtxVideo | Kind::CtxAudio));
2084        let mut ts = vec![t_v, t_a];
2085        if has_ctx {
2086            ts.push(0.0);
2087        }
2088        if has_cond {
2089            ts.push(t_cond);
2090        }
2091        if has_ref_audio {
2092            ts.push(t_cond_a);
2093        }
2094        ts.sort_by(|a, b| a.partial_cmp(b).unwrap());
2095        ts.dedup();
2096        let row_of = |t: f64| ts.iter().position(|&x| x == t).unwrap();
2097        let (row_v, row_a) = (row_of(t_v), row_of(t_a));
2098        let row_c = if has_cond { row_of(t_cond) } else { 0 };
2099        let row_ctx = if has_ctx { row_of(0.0) } else { 0 };
2100        let row_ca = if has_ref_audio { row_of(t_cond_a) } else { 0 };
2101
2102        // Per-token modulation row: t_row · MODALITIES + tag. The text
2103        // span is not uniform once a vision block is in it — those
2104        // positions carry the VIDEO tag.
2105        let mut rows = vec![0u32; layout.seq_len];
2106        for s in &layout.segments {
2107            match s.kind {
2108                Kind::Text => {
2109                    for (i, v) in rows[s.start..s.stop].iter_mut().enumerate() {
2110                        let tag = *layout.text_tags.get(i).unwrap_or(&(TAG_TEXT as u8));
2111                        *v = (row_v * MODALITIES + tag as usize) as u32;
2112                    }
2113                }
2114                // A reference's rows are conditions too: same timestep
2115                // near 1, and the modality of whichever stream they
2116                // belong to.
2117                Kind::Cond | Kind::RefImg => {
2118                    for v in rows[s.start..s.stop].iter_mut() {
2119                        *v = (row_c * MODALITIES + TAG_VIDEO) as u32;
2120                    }
2121                }
2122                Kind::RefAudio => {
2123                    for v in rows[s.start..s.stop].iter_mut() {
2124                        *v = (row_ca * MODALITIES + TAG_AUDIO) as u32;
2125                    }
2126                }
2127                Kind::Video => {
2128                    for v in rows[s.start..s.stop].iter_mut() {
2129                        *v = (row_v * MODALITIES + TAG_VIDEO) as u32;
2130                    }
2131                }
2132                Kind::Audio => {
2133                    for v in rows[s.start..s.stop].iter_mut() {
2134                        *v = (row_a * MODALITIES + TAG_AUDIO) as u32;
2135                    }
2136                }
2137                Kind::CtxVideo => {
2138                    for v in rows[s.start..s.stop].iter_mut() {
2139                        *v = (row_ctx * MODALITIES + TAG_VIDEO) as u32;
2140                    }
2141                }
2142                Kind::CtxAudio => {
2143                    for v in rows[s.start..s.stop].iter_mut() {
2144                        *v = (row_ctx * MODALITIES + TAG_AUDIO) as u32;
2145                    }
2146                }
2147            }
2148        }
2149
2150        // ── embed ──
2151        let v_rows = patchify_video(
2152            video,
2153            self.latents_dim,
2154            layout.latent_t,
2155            layout.lat_h,
2156            layout.lat_w,
2157        );
2158        let v_n = v_rows.len() / (self.latents_dim * 4);
2159        let a_rows = pack_audio(audio, self.audio_dim, layout.audio_t);
2160        // Condition rows go through the SAME patch projection as the
2161        // target, so they are patchified the same way — one frame each.
2162        let vd = self.latents_dim * 4;
2163        let cond_rows: Vec<Vec<f32>> = cond
2164            .iter()
2165            .enumerate()
2166            .map(|(i, z)| {
2167                let mut r = patchify_video(z, self.latents_dim, 1, layout.lat_h, layout.lat_w);
2168                if self.cond_aug < 1.0 {
2169                    // The reference draws this from a torch generator
2170                    // reseeded per condition; ours is its own stream, so
2171                    // the 0.1% it contributes differs — deliberately, and
2172                    // it is 0.1% of a unit normal.
2173                    let noise = crate::videogen::gauss_pub(r.len(), 0x5EED ^ i as u64);
2174                    let a = self.cond_aug as f32;
2175                    for (v, n) in r.iter_mut().zip(&noise) {
2176                        *v = a * *v + (1.0 - a) * n;
2177                    }
2178                }
2179                r
2180            })
2181            .collect();
2182
2183        let mut h = vec![0f32; layout.seq_len * hs];
2184        let mut ci = 0usize;
2185        for s in layout.segments.iter().filter(|s| s.kind == Kind::Cond) {
2186            let n = s.stop - s.start;
2187            let r = cond_rows.get(ci).unwrap_or_else(|| {
2188                panic!(
2189                    "layout has {} cond segments, {} latents given",
2190                    ci + 1,
2191                    cond_rows.len()
2192                )
2193            });
2194            self.video_patch
2195                .matmat(r, n, &mut h[s.start * hs..s.stop * hs], pool);
2196            for row in h[s.start * hs..s.stop * hs].chunks_exact_mut(hs) {
2197                for (v, &b) in row.iter_mut().zip(&self.video_patch_b) {
2198                    *v += b;
2199                }
2200            }
2201            ci += 1;
2202        }
2203        // The embed writes the whole block — context and current — while
2204        // the OUTPUT is only the current chunk's rows, which is why these
2205        // are two different spans in streaming and the same one otherwise.
2206        let (vblk_start, vblk_stop) = layout.video_block();
2207        let (ablk_start, ablk_stop) = layout.audio_block();
2208        let vseg = layout.segment(Kind::Video);
2209        let aseg = layout.segment(Kind::Audio);
2210        let tseg = layout.segment(Kind::Text);
2211        h[tseg.start * hs..tseg.stop * hs].copy_from_slice(&text[..(tseg.stop - tseg.start) * hs]);
2212        self.video_patch
2213            .matmat(&v_rows, v_n, &mut h[vblk_start * hs..vblk_stop * hs], pool);
2214        let audio_patch = self
2215            .audio_patch
2216            .as_ref()
2217            .expect("the audio-video forward on a model without an audio stream");
2218        audio_patch.matmat(
2219            &a_rows,
2220            ablk_stop - ablk_start,
2221            &mut h[ablk_start * hs..ablk_stop * hs],
2222            pool,
2223        );
2224        for row in h[vblk_start * hs..vblk_stop * hs].chunks_exact_mut(hs) {
2225            for (v, &b) in row.iter_mut().zip(&self.video_patch_b) {
2226                *v += b;
2227            }
2228        }
2229        for row in h[ablk_start * hs..ablk_stop * hs].chunks_exact_mut(hs) {
2230            for (v, &b) in row.iter_mut().zip(&self.audio_patch_b) {
2231                *v += b;
2232            }
2233        }
2234
2235        // ── blocks ──
2236        // One resident chain where the backend has one (`run_blocks`). The
2237        // per-block watch reads the stream on the host between blocks, so
2238        // it keeps the per-op loop.
2239        let vsa = self.vsa_plan(layout);
2240        let watch = std::env::var("CMF_MMH3_WATCHROW")
2241            .ok()
2242            .and_then(|w| w.parse::<usize>().ok());
2243        if let Some(r) = watch {
2244            for (i, blk) in self.blocks.iter().enumerate() {
2245                let mods = blk.adaln.as_ref().unwrap().eval(&ts, pool);
2246                self.block_forward(blk, &mut h, layout.seq_len, Some(&mods), &layout.pos, &rows, vsa.as_ref());
2247                // Growing magnitude is an overflow, a sudden jump from
2248                // finite to NaN is a kernel.
2249                let row = &h[r * hs..(r + 1) * hs];
2250                let amax = row
2251                    .iter()
2252                    .filter(|v| v.is_finite())
2253                    .fold(0f32, |a, v| a.max(v.abs()));
2254                let bad = row.iter().filter(|v| !v.is_finite()).count();
2255                if bad > 0 || i == 0 || amax > 1e3 {
2256                    eprintln!("  watch blk {i}: row {r} absmax {amax:.3e} nonfinite {bad}");
2257                }
2258                if std::env::var_os("CMF_DIT_PROGRESS").is_some() {
2259                    eprint!("\r  block {}/{}", i + 1, self.blocks.len());
2260                }
2261            }
2262        } else {
2263            self.run_blocks(&self.blocks, &mut h, layout.seq_len, &ts, &layout.pos, &rows, vsa.as_ref());
2264        }
2265
2266        // ── heads ──
2267        if std::env::var("CMF_MMH3_NANPROBE").is_ok() {
2268            let bad: Vec<usize> = (0..h.len() / hs)
2269                .filter(|r| h[r * hs..(r + 1) * hs].iter().any(|v| !v.is_finite()))
2270                .collect();
2271            if !bad.is_empty() {
2272                eprintln!(
2273                    "  nanprobe rows: {} of {} bad, first 8 {:?}, video seg {}..{}, audio seg {}..{}",
2274                    bad.len(),
2275                    h.len() / hs,
2276                    &bad[..bad.len().min(8)],
2277                    vseg.start,
2278                    vseg.stop,
2279                    aseg.start,
2280                    aseg.stop
2281                );
2282            }
2283        }
2284        let fm = self.final_adaln.eval(&ts, pool);
2285        let mut video_out = vec![0f32; (vseg.stop - vseg.start) * vd];
2286        let mut audio_out = vec![0f32; (aseg.stop - aseg.start) * self.audio_dim];
2287        for (seg, row, w, b, dst, dim) in [
2288            (
2289                vseg,
2290                row_v,
2291                &self.video_out,
2292                &self.video_out_b,
2293                &mut video_out,
2294                vd,
2295            ),
2296            (
2297                aseg,
2298                row_a,
2299                self.audio_out
2300                    .as_ref()
2301                    .expect("the audio-video forward on a model without an audio stream"),
2302                &self.audio_out_b,
2303                &mut audio_out,
2304                self.audio_dim,
2305            ),
2306        ] {
2307            let n = seg.stop - seg.start;
2308            let mut hn = vec![0f32; n * hs];
2309            for (o, src) in hn
2310                .chunks_exact_mut(hs)
2311                .zip(h[seg.start * hs..seg.stop * hs].chunks_exact(hs))
2312            {
2313                rms_norm_into(src, &self.final_norm, self.final_eps, o);
2314            }
2315            // The final layer's adaLN has one modality, so the row IS
2316            // the timestep index.
2317            let shift = &fm[row * 2 * hs..row * 2 * hs + hs];
2318            let scale = &fm[row * 2 * hs + hs..(row + 1) * 2 * hs];
2319            for r in hn.chunks_exact_mut(hs) {
2320                for ((v, &sc), &sh) in r.iter_mut().zip(scale).zip(shift) {
2321                    *v = *v * (1.0 + sc) + sh;
2322                }
2323            }
2324            // `CMF_MMH3_NANPROBE=1`: which side of the head's GEMM a NaN
2325            // is on. The stream that dies is the one to instrument, and
2326            // "the input was already bad" and "this GEMM made it bad" are
2327            // different bugs in different files.
2328            let probe = std::env::var("CMF_MMH3_NANPROBE").is_ok();
2329            if probe {
2330                let bad_in = hn.iter().filter(|v| !v.is_finite()).count();
2331                eprintln!(
2332                    "  nanprobe dim={dim} n={n} in_bad={bad_in} in_absmax={:.4}",
2333                    hn.iter()
2334                        .filter(|v| v.is_finite())
2335                        .fold(0f32, |a, v| a.max(v.abs()))
2336                );
2337            }
2338            w.matmat(&hn, n, dst, pool);
2339            if probe {
2340                let bad_out = dst.iter().filter(|v| !v.is_finite()).count();
2341                eprintln!(
2342                    "  nanprobe dim={dim} out_bad={bad_out}/{} out_absmax={:.4}",
2343                    dst.len(),
2344                    dst.iter()
2345                        .filter(|v| v.is_finite())
2346                        .fold(0f32, |a, v| a.max(v.abs()))
2347                );
2348            }
2349            for r in dst.chunks_exact_mut(dim) {
2350                for (v, &bv) in r.iter_mut().zip(b.iter()) {
2351                    *v += bv;
2352                }
2353            }
2354        }
2355
2356        // The reference predicts toward the data and the sampler steps
2357        // σ down, hence the sign; the audio velocity is returned on its
2358        // OWN clock rather than pre-scaled by d(σ_a)/d(σ_v).
2359        // The output covers the rows the sampler owns — which in the
2360        // chunk-causal layout is the CURRENT chunk, not every visible
2361        // frame. Sizing this by `layout.latent_t` (context included) fed
2362        // one chunk's rows into a buffer shaped for five and walked off
2363        // the end on the first chunk that had any context.
2364        let out_t = (vseg.stop - vseg.start) / layout.frame_rows;
2365        let out_at = (aseg.stop - aseg.start) / 2;
2366        let video = unpatchify_video(
2367            &video_out,
2368            self.latents_dim,
2369            out_t,
2370            layout.lat_h,
2371            layout.lat_w,
2372        );
2373        let audio = unpack_audio(&audio_out, self.audio_dim, out_at);
2374        (
2375            video.iter().map(|&v| -v).collect(),
2376            audio.iter().map(|&v| -v).collect(),
2377        )
2378    }
2379}
2380
2381// ── MiniMax-H3-Image ────────────────────────────────────────────────
2382
2383impl MiniMaxH3 {
2384    /// `blocks` over `h` `[n, hidden]`, in place. On a backend with a
2385    /// resident chain the whole stack runs on the card — the stream goes
2386    /// up once and comes back once; otherwise block by block through the
2387    /// per-op paths. `ts` are the distinct timesteps (empty for the
2388    /// unmodulated token refiner), `pos` the rows' positions (empty: no
2389    /// rotation), `rows` each row's modulation row.
2390    /// `CMF_MMH3_CHAIN=0` keeps the per-op path.
2391    fn run_blocks(
2392        &self,
2393        blocks: &[Block],
2394        h: &mut [f32],
2395        n: usize,
2396        ts: &[f64],
2397        pos: &[[f64; 3]],
2398        rows: &[u32],
2399        vsa: Option<&VsaPlan>,
2400    ) {
2401        let pool = self.pool.as_deref();
2402        if std::env::var("CMF_MMH3_CHAIN").as_deref() != Ok("0")
2403            && crate::gpu::enabled_here()
2404            && crate::gpu::h3_chain_available()
2405        {
2406            let mods: Vec<Vec<f32>> = blocks
2407                .iter()
2408                .map(|b| b.adaln.as_ref().map(|a| a.eval(ts, pool)).unwrap_or_default())
2409                .collect();
2410            let angles = if pos.is_empty() {
2411                Vec::new()
2412            } else {
2413                self.rope_angles(pos)
2414            };
2415            let idx = |p: &Proj| match p {
2416                Proj::Q(q) => q.mapped_device_gemm().map(|(_, i)| i),
2417                Proj::F32 { .. } => None,
2418            };
2419            let chain: Option<Vec<crate::gpu::H3ChainBlock>> = blocks
2420                .iter()
2421                .zip(&mods)
2422                .map(|(b, m)| {
2423                    if BlockLora::live(&b.lora.qkv)
2424                        || BlockLora::live(&b.lora.out)
2425                        || b.lora.ffn_any()
2426                    {
2427                        return None;
2428                    }
2429                    Some(crate::gpu::H3ChainBlock {
2430                        qkv: idx(&b.qkv)?,
2431                        out: idx(&b.out)?,
2432                        fc1: idx(&b.fc1)?,
2433                        fc2: idx(&b.fc2)?,
2434                        norm1: &b.norm1,
2435                        norm2: &b.norm2,
2436                        q_norm: &b.q_norm,
2437                        k_norm: &b.k_norm,
2438                        mods: m,
2439                        qkv_bias: &[],
2440                        out_bias: &[],
2441                        fc1_bias: &[],
2442                        fc2_bias: &[],
2443                        scale1: &[],
2444                        scale2: &[],
2445                        gate: match (&b.gate, vsa) {
2446                            (Some(g), Some(_)) => idx(g)?,
2447                            _ => usize::MAX,
2448                        },
2449                    })
2450                })
2451                .collect();
2452            if let Some(chain) = chain {
2453                let job = crate::gpu::H3Chain {
2454                    model: &self.model,
2455                    blocks: &chain,
2456                    n,
2457                    hidden: self.hidden,
2458                    heads: self.heads,
2459                    head_dim: self.head_dim,
2460                    ffn: self.ffn,
2461                    eps: self.eps as f32,
2462                    qk_eps: self.qk_eps as f32,
2463                    angles: &angles,
2464                    rows,
2465                    groups: 1,
2466                    qkv_interleaved: false,
2467                    vsa,
2468                };
2469                if crate::gpu::h3_chain(&job, h) {
2470                    return;
2471                }
2472            }
2473        }
2474        for (i, blk) in blocks.iter().enumerate() {
2475            let mods = blk.adaln.as_ref().map(|a| a.eval(ts, pool));
2476            self.block_forward(blk, h, n, mods.as_deref(), pos, rows, vsa);
2477            if std::env::var_os("CMF_DIT_PROGRESS").is_some() {
2478                eprint!("\r  block {}/{}", i + 1, blocks.len());
2479            }
2480        }
2481    }
2482
2483    /// One denoise evaluation of MiniMax-H3-Image.
2484    ///
2485    /// `latent` is `[latents_dim, lat_h, lat_w]`, channel-major; `text`
2486    /// the refined `[n, hidden]` stream; `refs` each reference picture's
2487    /// latent with its `(lat_h, lat_w)`, in the layout's order. The step
2488    /// runs from `sigma` to `sigma_next` — the output layer is a bank of
2489    /// per-step heads, and the step takes the heads of the grid intervals
2490    /// it spans. Returns the velocity the sampler steps with
2491    /// (`x += (sigma_next − sigma) · v`).
2492    pub fn forward_image(
2493        &self,
2494        layout: &Layout,
2495        text: &[f32],
2496        latent: &[f32],
2497        refs: &[(&[f32], usize, usize)],
2498        sigma: f64,
2499        sigma_next: f64,
2500    ) -> Vec<f32> {
2501        let hs = self.hidden;
2502        let pool = self.pool.as_deref();
2503        let t = 1.0 - sigma;
2504        // Text follows the target; a reference's rows are conditions and
2505        // pin near 1.
2506        let has_ref = layout.segments.iter().any(|s| s.kind == Kind::RefImg);
2507        let t_ref = t.max(self.cond_aug);
2508        let mut ts = vec![t];
2509        if has_ref && t_ref != t {
2510            ts.push(t_ref);
2511        }
2512        ts.sort_by(|a, b| a.partial_cmp(b).unwrap());
2513        let row_of = |x: f64| ts.iter().position(|&v| v == x).unwrap();
2514        let (row_t, row_r) = (row_of(t), if has_ref { row_of(t_ref) } else { 0 });
2515
2516        let mut rows = vec![0u32; layout.seq_len];
2517        for s in &layout.segments {
2518            match s.kind {
2519                Kind::Text => {
2520                    for (i, v) in rows[s.start..s.stop].iter_mut().enumerate() {
2521                        let tag = *layout.text_tags.get(i).unwrap_or(&(TAG_TEXT as u8));
2522                        *v = (row_t * MODALITIES + tag as usize) as u32;
2523                    }
2524                }
2525                Kind::RefImg => {
2526                    for v in rows[s.start..s.stop].iter_mut() {
2527                        *v = (row_r * MODALITIES + TAG_VIDEO) as u32;
2528                    }
2529                }
2530                _ => {
2531                    for v in rows[s.start..s.stop].iter_mut() {
2532                        *v = (row_t * MODALITIES + TAG_VIDEO) as u32;
2533                    }
2534                }
2535            }
2536        }
2537
2538        // ── embed ──
2539        let vd = self.latents_dim * 4;
2540        let mut h = vec![0f32; layout.seq_len * hs];
2541        let tseg = layout.segment(Kind::Text);
2542        h[tseg.start * hs..tseg.stop * hs].copy_from_slice(&text[..(tseg.stop - tseg.start) * hs]);
2543        let embed = |r: &[f32], dst: &mut [f32]| {
2544            self.video_patch.matmat(r, r.len() / vd, dst, pool);
2545            for row in dst.chunks_exact_mut(hs) {
2546                for (v, &b) in row.iter_mut().zip(&self.video_patch_b) {
2547                    *v += b;
2548                }
2549            }
2550        };
2551        for (i, s) in layout
2552            .segments
2553            .iter()
2554            .filter(|s| s.kind == Kind::RefImg)
2555            .enumerate()
2556        {
2557            let (z, rh, rw) = refs[i];
2558            let mut r = patchify_video(z, self.latents_dim, 1, rh, rw);
2559            if self.cond_aug < 1.0 {
2560                // The reference blends 0.1% of seeded noise into a
2561                // condition row; ours is its own stream of the same law.
2562                let noise = crate::videogen::gauss_pub(r.len(), 0x5EED ^ i as u64);
2563                let a = self.cond_aug as f32;
2564                for (v, n) in r.iter_mut().zip(&noise) {
2565                    *v = a * *v + (1.0 - a) * n;
2566                }
2567            }
2568            embed(&r, &mut h[s.start * hs..s.stop * hs]);
2569        }
2570        let vseg = layout.segment(Kind::Video);
2571        let v_rows = patchify_video(latent, self.latents_dim, 1, layout.lat_h, layout.lat_w);
2572        embed(&v_rows, &mut h[vseg.start * hs..vseg.stop * hs]);
2573
2574        // ── blocks ──
2575        self.run_blocks(&self.blocks, &mut h, layout.seq_len, &ts, &layout.pos, &rows, None);
2576
2577        // ── the output layer ──
2578        let n = vseg.stop - vseg.start;
2579        let fm = self.final_adaln.eval(&ts, pool);
2580        let shift = &fm[row_t * 2 * hs..row_t * 2 * hs + hs];
2581        let scale = &fm[row_t * 2 * hs + hs..(row_t + 1) * 2 * hs];
2582        let mut hn = vec![0f32; n * hs];
2583        for (o, src) in hn
2584            .chunks_exact_mut(hs)
2585            .zip(h[vseg.start * hs..vseg.stop * hs].chunks_exact(hs))
2586        {
2587            rms_norm_into(src, &self.final_norm, self.final_eps, o);
2588            for ((v, &sc), &sh) in o.iter_mut().zip(scale).zip(shift) {
2589                *v = *v * (1.0 + sc) + sh;
2590            }
2591        }
2592        let mut out = vec![0f32; n * vd];
2593        if self.pdd_steps > 1 {
2594            let (w, b) = self.pdd_head(sigma, sigma_next);
2595            crate::fcd_ops::gemm_nt(&hn, &w, &mut out, n, hs, vd, pool);
2596            for r in out.chunks_exact_mut(vd) {
2597                for (v, &bv) in r.iter_mut().zip(&b) {
2598                    *v += bv;
2599                }
2600            }
2601        } else {
2602            self.video_out.matmat(&hn, n, &mut out, pool);
2603            for r in out.chunks_exact_mut(vd) {
2604                for (v, &bv) in r.iter_mut().zip(&self.video_out_b) {
2605                    *v += bv;
2606                }
2607            }
2608        }
2609        let img = unpatchify_video(&out, self.latents_dim, 1, layout.lat_h, layout.lat_w);
2610        img.iter().map(|&v| -v).collect()
2611    }
2612
2613    /// The output head of the step `sigma → sigma_next`: block 0 of the
2614    /// bank is a full head and the later blocks are offsets from it; a
2615    /// step takes the Δσ-weighted mean of the heads of the grid intervals
2616    /// it spans (one interval, on the grid the bank was distilled for).
2617    fn pdd_head(&self, sigma: f64, sigma_next: f64) -> (Vec<f32>, Vec<f32>) {
2618        let n = self.pdd_steps;
2619        let grid = &self.pdd_sigmas;
2620        let nearest = |s: f64| {
2621            (0..=n)
2622                .min_by(|&a, &b| {
2623                    (grid[a] - s)
2624                        .abs()
2625                        .partial_cmp(&(grid[b] - s).abs())
2626                        .unwrap()
2627                })
2628                .unwrap()
2629        };
2630        let start = nearest(sigma).min(n - 1);
2631        let stop = nearest(sigma_next).max(start + 1);
2632        let dt: Vec<f64> = (start..stop).map(|k| grid[k] - grid[k + 1]).collect();
2633        let total: f64 = dt.iter().sum();
2634        let (hs, vd) = (self.hidden, self.latents_dim * 4);
2635        let mut w = self.pdd_w[..vd * hs].to_vec();
2636        let mut b = self.video_out_b[..vd].to_vec();
2637        let first = start.max(1);
2638        for k in first..stop {
2639            let wk = (dt[k - start] / total) as f32;
2640            for (d, &s) in w.iter_mut().zip(&self.pdd_w[k * vd * hs..(k + 1) * vd * hs]) {
2641                *d += wk * s;
2642            }
2643            for (d, &s) in b.iter_mut().zip(&self.video_out_b[k * vd..(k + 1) * vd]) {
2644                *d += wk * s;
2645            }
2646        }
2647        (w, b)
2648    }
2649}
2650
2651// ── modulation helpers ──────────────────────────────────────────────
2652
2653/// Rows of `n` items split across pool workers (serial without a pool).
2654fn pool_rows(pool: Option<&Pool>, n: usize, f: &(dyn Fn(usize, usize) + Sync)) {
2655    match pool {
2656        Some(p) => p.run_rows(n, f),
2657        None => f(0, n),
2658    }
2659}
2660
2661// ── stream (un)packing ──────────────────────────────────────────────
2662
2663/// `[C, T, H, W]` → `[T·(H/2)·(W/2), C·4]`, the 2×2 spatial patch
2664/// flattened channel-major-outer as `einsum("nctrhpwq->nthwcrpq")`.
2665pub fn patchify_video(x: &[f32], c: usize, t: usize, h: usize, w: usize) -> Vec<f32> {
2666    let (ph, pw) = (h / 2, w / 2);
2667    let mut out = vec![0f32; t * ph * pw * c * 4];
2668    let mut i = 0;
2669    for ti in 0..t {
2670        for hi in 0..ph {
2671            for wi in 0..pw {
2672                for ci in 0..c {
2673                    for p in 0..2 {
2674                        for q in 0..2 {
2675                            out[i] = x[((ci * t + ti) * h + hi * 2 + p) * w + wi * 2 + q];
2676                            i += 1;
2677                        }
2678                    }
2679                }
2680            }
2681        }
2682    }
2683    out
2684}
2685
2686/// The inverse of `patchify_video`.
2687pub fn unpatchify_video(rows: &[f32], c: usize, t: usize, h: usize, w: usize) -> Vec<f32> {
2688    let (ph, pw) = (h / 2, w / 2);
2689    let mut out = vec![0f32; c * t * h * w];
2690    let mut i = 0;
2691    for ti in 0..t {
2692        for hi in 0..ph {
2693            for wi in 0..pw {
2694                for ci in 0..c {
2695                    for p in 0..2 {
2696                        for q in 0..2 {
2697                            out[((ci * t + ti) * h + hi * 2 + p) * w + wi * 2 + q] = rows[i];
2698                            i += 1;
2699                        }
2700                    }
2701                }
2702            }
2703        }
2704    }
2705    out
2706}
2707
2708/// `[C, 2, T]` → `[2·T, C]`, channel-major: channel 0's frames then
2709/// channel 1's.
2710pub fn pack_audio(x: &[f32], c: usize, t: usize) -> Vec<f32> {
2711    let mut out = vec![0f32; 2 * t * c];
2712    for ch in 0..2 {
2713        for ti in 0..t {
2714            for ci in 0..c {
2715                out[(ch * t + ti) * c + ci] = x[(ci * 2 + ch) * t + ti];
2716            }
2717        }
2718    }
2719    out
2720}
2721
2722/// The inverse of `pack_audio`.
2723pub fn unpack_audio(rows: &[f32], c: usize, t: usize) -> Vec<f32> {
2724    let mut out = vec![0f32; c * 2 * t];
2725    for ch in 0..2 {
2726        for ti in 0..t {
2727            for ci in 0..c {
2728                out[(ci * 2 + ch) * t + ti] = rows[(ch * t + ti) * c + ci];
2729            }
2730        }
2731    }
2732    out
2733}
2734
2735// ── small shared bits ───────────────────────────────────────────────
2736
2737struct SendPtr(*mut f32);
2738unsafe impl Send for SendPtr {}
2739unsafe impl Sync for SendPtr {}
2740impl SendPtr {
2741    /// SAFETY: caller guarantees disjoint `[off, off+len)` per worker.
2742    #[allow(clippy::mut_from_ref)]
2743    unsafe fn row(&self, off: usize, len: usize) -> &mut [f32] {
2744        unsafe { std::slice::from_raw_parts_mut(self.0.add(off), len) }
2745    }
2746}
2747
2748fn softmax_inplace(row: &mut [f32]) {
2749    let mx = row.iter().cloned().fold(f32::MIN, f32::max);
2750    let mut den = 0f32;
2751    for r in row.iter_mut() {
2752        *r = (*r - mx).exp();
2753        den += *r;
2754    }
2755    if den > 0.0 {
2756        let inv = 1.0 / den;
2757        for r in row.iter_mut() {
2758            *r *= inv;
2759        }
2760    }
2761}
2762
2763#[cfg(test)]
2764mod tests {
2765    /// A streaming layout whose "current chunk" is the whole clip and
2766    /// which sees no context must be the bidirectional layout, row for
2767    /// row. Absolute positions are the whole point of the chunked path:
2768    /// if this drifts, every chunk after the first is told it is
2769    /// generating the opening again.
2770    #[test]
2771    fn an_image_layout_puts_references_between_the_text_and_the_target() {
2772        // 5 text rows, one 4x8 reference latent (2x4 rows), an 8x8 target
2773        // latent (4x4 rows)
2774        let l = Layout::image(5, 8, 8, &[(4, 8)], &[]);
2775        assert_eq!(l.seq_len, 5 + 8 + 16);
2776        assert_eq!((l.latent_t, l.audio_t, l.frame_rows), (1, 0, 16));
2777        let kinds: Vec<Kind> = l.segments.iter().map(|s| s.kind).collect();
2778        assert_eq!(kinds, vec![Kind::Text, Kind::RefImg, Kind::Video]);
2779        // text rows count along the time axis only
2780        assert_eq!(l.pos[3], [3.0, 0.0, 0.0]);
2781        // the reference sits at the text's end, on its own area-normalized
2782        // grid: sqrt(4·8) = 5.657, so h spans 4/5.657 and w 8/5.657 of 32
2783        let r = l.pos[5];
2784        assert_eq!(r[0], 5.0);
2785        let (ratio_h, ratio_w) = (4.0 / 32f64.sqrt(), 8.0 / 32f64.sqrt());
2786        assert!((r[1] - (1.0 - ratio_h) / 2.0 * 32.0).abs() < 1e-9);
2787        assert!((r[2] - (1.0 - ratio_w) / 2.0 * 32.0).abs() < 1e-9);
2788        // the target follows the reference by one step, a square grid
2789        // from 0 in steps of 32 / 4
2790        assert_eq!(l.pos[13], [6.0, 0.0, 0.0]);
2791        assert_eq!(l.pos[14], [6.0, 0.0, 8.0]);
2792        assert_eq!(l.pos[13 + 4], [6.0, 8.0, 0.0]);
2793        // without references the target starts where the text ends
2794        let t = Layout::image(5, 8, 8, &[], &[]);
2795        assert_eq!(t.pos[5], [5.0, 0.0, 0.0]);
2796        assert_eq!(t.seq_len, 21);
2797    }
2798
2799    #[test]
2800    fn streaming_layout_degenerates_to_the_bidirectional_one() {
2801        let (lat_h, lat_w, latent_t, audio_t, text_len) = (16, 24, 7, 12, 5);
2802        let base = Layout::t2va(text_len, latent_t, lat_h, lat_w, audio_t);
2803        let cur_v: Vec<usize> = (0..latent_t).collect();
2804        let cur_a: Vec<usize> = (0..audio_t).collect();
2805        let stream = Layout::streaming(text_len, &[], lat_h, lat_w, &[], &cur_v, &[], &cur_a);
2806        assert_eq!(stream.seq_len, base.seq_len, "row count");
2807        assert_eq!(stream.latent_t, base.latent_t);
2808        assert_eq!(stream.audio_t, base.audio_t);
2809        for (i, (a, b)) in stream.pos.iter().zip(&base.pos).enumerate() {
2810            for axis in 0..3 {
2811                assert!(
2812                    (a[axis] - b[axis]).abs() < 1e-9,
2813                    "row {i} axis {axis}: {a:?} vs {b:?}"
2814                );
2815            }
2816        }
2817        let seg = |l: &Layout, k: Kind| {
2818            l.segments
2819                .iter()
2820                .find(|s| s.kind == k)
2821                .map(|s| (s.start, s.stop))
2822        };
2823        assert_eq!(seg(&stream, Kind::Video), seg(&base, Kind::Video));
2824        assert_eq!(seg(&stream, Kind::Audio), seg(&base, Kind::Audio));
2825    }
2826
2827    /// A later chunk keeps the coordinates it would have had in the whole
2828    /// clip — that is what makes the chunks line up into one video.
2829    #[test]
2830    fn streaming_positions_are_absolute() {
2831        let (lat_h, lat_w) = (16, 24);
2832        let whole = Layout::streaming(
2833            3,
2834            &[],
2835            lat_h,
2836            lat_w,
2837            &[],
2838            &(0..9).collect::<Vec<_>>(),
2839            &[],
2840            &[],
2841        );
2842        let tail = Layout::streaming(
2843            3,
2844            &[],
2845            lat_h,
2846            lat_w,
2847            &[],
2848            &(6..9).collect::<Vec<_>>(),
2849            &[],
2850            &[],
2851        );
2852        let rows = whole.frame_rows;
2853        let (ws, _) = whole.video_block();
2854        let (ts_, _) = tail.video_block();
2855        for k in 0..3 {
2856            let a = whole.pos[ws + (6 + k) * rows];
2857            let b = tail.pos[ts_ + k * rows];
2858            assert!((a[0] - b[0]).abs() < 1e-9, "frame {k}: {a:?} vs {b:?}");
2859        }
2860    }
2861
2862    use super::*;
2863
2864    #[test]
2865    fn schedule_remap_is_an_involution() {
2866        for &s in &[1e-3, 0.25, 0.5, 0.8, 0.972_973, 1.0] {
2867            let a = time_shift_sigma(s, 12.0, 3.0);
2868            let back = time_shift_sigma(a, 3.0, 12.0);
2869            assert!((back - s).abs() < 1e-9, "{s} -> {a} -> {back}");
2870        }
2871    }
2872
2873    #[test]
2874    fn slope_matches_a_finite_difference() {
2875        let h = 1e-6;
2876        for &s in &[0.2, 0.5, 0.9] {
2877            let num = (time_shift_sigma(s + h, 12.0, 3.0) - time_shift_sigma(s - h, 12.0, 3.0))
2878                / (2.0 * h);
2879            let got = time_shift_slope(s, 12.0, 3.0);
2880            assert!((num - got).abs() < 1e-5, "{s}: {num} vs {got}");
2881        }
2882    }
2883
2884    #[test]
2885    fn patchify_round_trips() {
2886        let (c, t, h, w) = (3usize, 2usize, 4usize, 6usize);
2887        let x: Vec<f32> = (0..c * t * h * w).map(|i| i as f32).collect();
2888        let rows = patchify_video(&x, c, t, h, w);
2889        assert_eq!(rows.len(), t * (h / 2) * (w / 2) * c * 4);
2890        assert_eq!(unpatchify_video(&rows, c, t, h, w), x);
2891    }
2892
2893    #[test]
2894    fn audio_pack_round_trips() {
2895        let (c, t) = (5usize, 7usize);
2896        let x: Vec<f32> = (0..c * 2 * t).map(|i| i as f32).collect();
2897        let rows = pack_audio(&x, c, t);
2898        assert_eq!(unpack_audio(&rows, c, t), x);
2899    }
2900
2901    #[test]
2902    fn keyframes_sit_between_the_text_and_the_audio() {
2903        let (tl, lt, lh, lw, at) = (8usize, 3usize, 8usize, 12usize, 5usize);
2904        let base = Layout::t2va(tl, lt, lh, lw, at);
2905        // First and last frame of a 39-frame clip.
2906        let l = Layout::fl2va(tl, lt, lh, lw, at, &[(0, 39), (38, 39)], &[]);
2907        assert_eq!(l.cond_rows(), 2 * l.frame_rows);
2908        assert_eq!(l.seq_len, base.seq_len + 2 * l.frame_rows);
2909        let kinds: Vec<_> = l.segments.iter().map(|s| s.kind).collect();
2910        assert_eq!(
2911            kinds,
2912            vec![Kind::Text, Kind::Cond, Kind::Cond, Kind::Audio, Kind::Video]
2913        );
2914        // A keyframe never advances the cursor: audio and video start
2915        // where they would have without it.
2916        let (a0, v0) = (l.segment(Kind::Audio), l.segment(Kind::Video));
2917        let (ba, bv) = (base.segment(Kind::Audio), base.segment(Kind::Video));
2918        assert_eq!(l.pos[a0.start][0], base.pos[ba.start][0]);
2919        assert_eq!(l.pos[v0.start][0], base.pos[bv.start][0]);
2920        // The first frame's rows sit at the text's end; the last one's a
2921        // whole clip further on, minus one span.
2922        let c: Vec<_> = l.segments.iter().filter(|s| s.kind == Kind::Cond).collect();
2923        assert_eq!(l.pos[c[0].start][0], tl as f64);
2924        let spans: f64 = (0..lt)
2925            .map(|k| FRAME_RESCALE * FRAME_PER_TOKEN[k % 5])
2926            .sum();
2927        assert!((l.pos[c[1].start][0] - (tl as f64 + spans - FRAME_RESCALE)).abs() < 1e-12);
2928        // Both share the TARGET spatial grid.
2929        assert_eq!(l.pos[c[0].start][1], l.pos[v0.start][1]);
2930        assert_eq!(l.pos[c[0].start][2], l.pos[v0.start][2]);
2931    }
2932
2933    #[test]
2934    fn layout_places_the_target_streams_last() {
2935        let l = Layout::t2va(8, 3, 8, 12, 5);
2936        assert_eq!(l.frame_rows, 4 * 6);
2937        assert_eq!(l.seq_len, 8 + 2 * 5 + 3 * 24);
2938        assert_eq!(l.segments[0].kind, Kind::Text);
2939        assert_eq!(l.segments[1].kind, Kind::Audio);
2940        assert_eq!(l.segments[2].kind, Kind::Video);
2941        // The video t axis advances by the 1,4,4,4,4 span pattern.
2942        let v = l.segment(Kind::Video);
2943        let t0 = l.pos[v.start][0];
2944        let t1 = l.pos[v.start + l.frame_rows][0];
2945        assert!((t1 - t0 - FRAME_RESCALE).abs() < 1e-12);
2946    }
2947
2948    /// VSA's tiles cover every row once: the non-video streams in 64-row
2949    /// chunks, the video in 4x4x4 blocks with smaller ones at the edges.
2950    #[test]
2951    fn vsa_tiles_cover_every_row_once() {
2952        // 70 text rows (two chunks), 2 x 40 audio rows (two chunks), video
2953        // 5 x 6 x 10 after the patch (tiles 2 x 2 x 3)
2954        let l = Layout::t2va(70, 5, 12, 20, 40);
2955        let p = VsaPlan::build(&l, [4, 4, 4], 0.9).unwrap();
2956        assert_eq!(p.prefix_tiles, 2 + 2);
2957        assert_eq!(p.tiles, 4 + 2 * 2 * 3);
2958        assert_eq!(p.size.iter().map(|&s| s as usize).sum::<usize>(), l.seq_len);
2959        assert_eq!((p.size[0], p.size[1], p.size[2], p.size[3]), (64, 6, 64, 16));
2960        // a corner tile: t 4..5, h 4..6, w 8..10
2961        assert_eq!(*p.size.last().unwrap(), 4); // 1 x 2 x 2
2962        let mut seen = std::collections::HashSet::new();
2963        for (r, &s) in p.slot.iter().enumerate() {
2964            let t = s as usize / VSA_TILE;
2965            assert!((s as usize % VSA_TILE) < p.size[t] as usize, "row {r} in a pad slot");
2966            assert!(seen.insert(s), "slot {s} twice");
2967        }
2968        assert_eq!(p.topk, (0.1f64 * 12.0).ceil() as usize);
2969    }
2970
2971    /// With every video tile kept and no gate, VSA is the full attention.
2972    #[test]
2973    fn vsa_without_sparsity_is_full_attention() {
2974        let l = Layout::t2va(9, 3, 8, 12, 5);
2975        let p = VsaPlan::build(&l, [4, 4, 4], 0.0).unwrap();
2976        assert_eq!(p.topk, p.tiles - p.prefix_tiles);
2977        let (heads, hd, n) = (2usize, 8usize, l.seq_len);
2978        let inner = heads * hd;
2979        let mut seed = 0x2545_F491u64;
2980        let qkv: Vec<f32> = (0..n * 3 * inner)
2981            .map(|_| {
2982                seed ^= seed << 13;
2983                seed ^= seed >> 7;
2984                seed ^= seed << 17;
2985                (seed % 2001) as f32 / 1000.0 - 1.0
2986            })
2987            .collect();
2988        let mut got = vec![0f32; n * inner];
2989        vsa_attention_host(&p, &qkv, None, heads, hd, &mut got, None);
2990        let scale = 1.0 / (hd as f32).sqrt();
2991        for h in 0..heads {
2992            for r in 0..n {
2993                let q = &qkv[r * 3 * inner + h * hd..][..hd];
2994                let mut s: Vec<f32> = (0..n)
2995                    .map(|k| q.iter().zip(&qkv[k * 3 * inner + inner + h * hd..][..hd]).map(|(a, b)| a * b).sum::<f32>() * scale)
2996                    .collect();
2997                softmax_f64(&mut s);
2998                for d in 0..hd {
2999                    let want: f32 = (0..n).map(|k| s[k] * qkv[k * 3 * inner + 2 * inner + h * hd + d]).sum();
3000                    let g = got[r * inner + h * hd + d];
3001                    assert!((g - want).abs() < 1e-5, "head {h} row {r} dim {d}: {g} vs {want}");
3002                }
3003            }
3004        }
3005    }
3006}