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