Skip to main content

cortiq_engine/
videogen.rs

1//! End-to-end MiniMax-H3 text→(video + synchronized stereo audio):
2//! Qwen3-VL prompt encode → 4-step dual-schedule flow sampling over the
3//! packed DiT → ViT3D video decode and BigVGAN audio decode.
4//!
5//! Stages load and drop one at a time, as the image pipeline next door
6//! does: peak resident is one component, not their sum.
7//!
8//! ## Two clocks, four steps
9//!
10//! The sampler walks the VIDEO sigma grid — `simple` at shift 12, which
11//! at four steps is 1, 0.973, 0.923, 0.8, 0 — and the audio stream is
12//! integrated on its own remap of that grid (shift 3). Stepping both on
13//! the video grid is what a stock sampler does, and it is fine at
14//! twenty steps and audibly wrong at four: `Δσ_a` and `Δσ_v` differ by
15//! a factor of three over the last interval, and no per-step slope
16//! correction fixes a step that large. Hence `--stock-sampler`, which
17//! reproduces the broken behaviour on purpose, for comparison.
18
19use crate::audiovae::AudioVae;
20use crate::mmh3::{Layout, MiniMaxH3, time_shift_sigma};
21use crate::qwen3te::{ImageSpan, Qwen3Encoder};
22use crate::qwen3vis::{self, VisionTower};
23use crate::sampler::SplitMix64;
24use crate::tokenizer::Tokenizer;
25use crate::vae3d::VideoVae;
26use crate::vae3d::VideoVaeEncoder;
27use std::path::Path;
28use std::sync::Arc;
29
30pub const FPS: usize = 24;
31pub const AUDIO_LATENT_FPS: usize = 40;
32
33pub struct AnimParams {
34    pub width: usize,
35    pub height: usize,
36    /// Frames at 24 fps; snapped up to the model's 17k+5 grid.
37    pub frames: usize,
38    pub steps: usize,
39    pub seed: u64,
40    /// Integrate the audio on the video's grid, as a stock sampler
41    /// would. Wrong at four steps; kept for A/B.
42    pub stock_sampler: bool,
43    pub max_tokens: usize,
44    /// RGB in [0, 1] as `[3, h, w]` with its size — the clip's first
45    /// frame, and/or its last.
46    pub first_frame: Option<(Vec<f32>, usize, usize)>,
47    pub last_frame: Option<(Vec<f32>, usize, usize)>,
48    /// Extra reference frames with the pixel index each one stands for:
49    /// video-to-video as this architecture actually takes it — every
50    /// frame is a condition row pinned to its own time coordinate, the
51    /// same machinery `--first-frame`/`--last-frame` use for two.
52    pub mid_frames: Vec<((Vec<f32>, usize, usize), usize)>,
53    /// Reference pictures (ref2va), RGB in [0, 1] as `[3, h, w]` with their
54    /// size: presented in the prompt as `<Picture i>: ` and a vision block,
55    /// and laid ahead of the clip as reference latents on the canvas.
56    pub refs: Vec<(Vec<f32>, usize, usize)>,
57    /// A LoRA adapter (.safetensors) applied at runtime, and how hard.
58    pub lora: Option<String>,
59    pub lora_strength: f32,
60    /// The published latent upscaler (.safetensors) and the factor to
61    /// apply: the denoised latent is resized by the learned net and the
62    /// VAE decodes at the larger size, so the 5 B-parameter decode →
63    /// pixel resize → encode round trip never happens.
64    pub upscale: Option<String>,
65    pub upscale_by: f32,
66    /// Chunk-causal (streaming) generation: latent frames per chunk, and
67    /// how many chunks a chunk may see — `sink` from the start of the
68    /// clip and a sliding `window` of recent ones. 0 chunks = the
69    /// bidirectional path. This is what a streaming adapter is trained
70    /// for, and it is what stops the activation cache growing with the
71    /// clip's length.
72    pub stream_chunk: usize,
73    pub stream_sink: usize,
74    pub stream_window: usize,
75}
76
77/// The vision-block token ids the H3 presentation flanks a picture with.
78const VISION_START: u32 = 151_652;
79const VISION_END: u32 = 151_653;
80
81/// Resize `[3, h, w]` RGB to the canvas. The first frame is a geometry
82/// anchor and is stretched; the last one follows and is cover-cropped,
83/// which is what the reference node does with each.
84/// A reference picture's canvas: its own aspect at `area` pixels, each
85/// side on the 32-pixel grid (at least 32) — a portrait reference beside a
86/// landscape clip is neither stretched nor cropped.
87pub fn ref_canvas(h: usize, w: usize, area: usize) -> (usize, usize) {
88    let scale = (area as f64 / (h.max(1) * w.max(1)) as f64).sqrt();
89    let snap = |x: usize| (((x as f64 * scale) / 32.0).round() as usize).max(1) * 32;
90    (snap(h), snap(w))
91}
92
93pub fn fit_to_canvas(
94    rgb: &[f32],
95    h: usize,
96    w: usize,
97    out_h: usize,
98    out_w: usize,
99    crop: bool,
100) -> Vec<f32> {
101    // Cover-crop picks the largest centred rectangle of the source with
102    // the target's aspect; a stretch takes the whole thing.
103    let (sx0, sy0, sw, sh) = if crop {
104        let (tw, th) = (out_w as f64, out_h as f64);
105        let scale = (w as f64 / tw).min(h as f64 / th);
106        let (cw, ch) = ((tw * scale).round() as usize, (th * scale).round() as usize);
107        ((w - cw) / 2, (h - ch) / 2, cw.max(1), ch.max(1))
108    } else {
109        (0, 0, w, h)
110    };
111    let mut out = vec![0f32; 3 * out_h * out_w];
112    for c in 0..3 {
113        for y in 0..out_h {
114            let sy = ((y as f64 + 0.5) * sh as f64 / out_h as f64 - 0.5).max(0.0);
115            let y0 = sy.floor() as usize;
116            let y1 = (y0 + 1).min(sh - 1);
117            let fy = (sy - y0 as f64) as f32;
118            for x in 0..out_w {
119                let sx = ((x as f64 + 0.5) * sw as f64 / out_w as f64 - 0.5).max(0.0);
120                let x0 = sx.floor() as usize;
121                let x1 = (x0 + 1).min(sw - 1);
122                let fx = (sx - x0 as f64) as f32;
123                let p = |yy: usize, xx: usize| rgb[(c * h + sy0 + yy) * w + sx0 + xx];
124                let top = p(y0, x0) * (1.0 - fx) + p(y0, x1) * fx;
125                let bot = p(y1, x0) * (1.0 - fx) + p(y1, x1) * fx;
126                out[(c * out_h + y) * out_w + x] = top * (1.0 - fy) + bot * fy;
127            }
128        }
129    }
130    out
131}
132
133impl Default for AnimParams {
134    fn default() -> Self {
135        Self {
136            width: 512,
137            height: 288,
138            frames: 39,
139            steps: 4,
140            seed: 42,
141            stock_sampler: false,
142            max_tokens: 512,
143            first_frame: None,
144            last_frame: None,
145            mid_frames: Vec::new(),
146            refs: Vec::new(),
147            lora: None,
148            lora_strength: 1.0,
149            upscale: None,
150            upscale_by: 2.0,
151            stream_chunk: 0,
152            stream_sink: 2,
153            stream_window: 2,
154        }
155    }
156}
157
158/// The rendered result: RGB in [0, 1] as `[3, frames, h, w]`, and
159/// stereo f32 in [-1, 1] as `[2, samples]`.
160pub struct Anim {
161    pub rgb: Vec<f32>,
162    pub frames: usize,
163    pub height: usize,
164    pub width: usize,
165    pub audio: Vec<f32>,
166    pub samples: usize,
167    pub sample_rate: usize,
168}
169
170/// Frame counts snap UP to 17k+5 — the grid the temporal VAE and the
171/// DiT's frame-span pattern agree on.
172pub fn align_frames(n: usize) -> usize {
173    let mut n = n.max(5);
174    while n % 17 != 5 {
175        n += 1;
176    }
177    n
178}
179
180pub fn video_latent_t(frames: usize) -> usize {
181    if frames <= 5 {
182        2
183    } else {
184        (frames - 5) / 17 * 5 + 2
185    }
186}
187
188/// `(frames, latent_t, audio_t)` for a requested length.
189pub fn temporal_shape(len: usize) -> (usize, usize, usize) {
190    let frames = align_frames(len);
191    let audio_t = ((frames as f64 / FPS as f64) * AUDIO_LATENT_FPS as f64).round() as usize;
192    (frames, video_latent_t(frames), audio_t)
193}
194
195/// The `simple` scheduler over `ModelSamplingDiscreteFlow(shift)`: the
196/// 1000-entry sigma table sampled at even strides, terminal 0 appended.
197pub fn sigmas(steps: usize, shift: f64) -> Vec<f64> {
198    let table = 1000usize;
199    let mut out: Vec<f64> = (0..steps)
200        .map(|x| {
201            let idx = table - 1 - x * table / steps;
202            let t = (idx + 1) as f64 / table as f64;
203            shift * t / (1.0 + (shift - 1.0) * t)
204        })
205        .collect();
206    out.push(0.0);
207    out
208}
209
210/// Shared with the DiT's condition-row noise blend.
211pub fn gauss_pub(n: usize, seed: u64) -> Vec<f32> {
212    gauss(n, seed)
213}
214
215fn gauss(n: usize, seed: u64) -> Vec<f32> {
216    let mut rng = SplitMix64::new(seed);
217    let mut u = || (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64;
218    let mut out = Vec::with_capacity(n);
219    while out.len() < n {
220        let (a, b) = (u().max(1e-300), u());
221        let r = (-2.0 * a.ln()).sqrt();
222        let ang = 2.0 * std::f64::consts::PI * b;
223        out.push((r * ang.cos()) as f32);
224        if out.len() < n {
225            out.push((r * ang.sin()) as f32);
226        }
227    }
228    out
229}
230
231/// Text→(video, audio) from a packaged `.cmf`.
232pub fn generate(
233    path: &Path,
234    prompt: &str,
235    p: &AnimParams,
236    mut progress: impl FnMut(&str, usize, usize),
237) -> Result<Anim, String> {
238    if p.width % 32 != 0 || p.height % 32 != 0 {
239        return Err("width/height must be multiples of 32".into());
240    }
241    // The wgpu wide-GEMM arm was measured WRONG on one driver stack
242    // (RTX PRO 6000: step-1 velocity rms off, step-2 NaN) and byte-
243    // healthy on another (2×RTX 5090, coop and plain arms within 0.5%
244    // of each other and 3.5% of the host render). Trust is therefore
245    // PER-STACK, decided by a parity probe on this file's own first
246    // qkv weight at DiT-scale activations — not by a hardcoded verdict
247    // either way. CMF_MMH3_GPU=1/0 still forces.
248    let use_gpu = match std::env::var("CMF_MMH3_GPU").ok().as_deref() {
249        Some("1") => true,
250        Some("0") => false,
251        _ => mmh3_gpu_parity_probe(path).unwrap_or(false),
252    };
253    if use_gpu {
254        generate_inner(path, prompt, p, &mut progress)
255    } else {
256        crate::gpu::cpu_scope(|| generate_inner(path, prompt, p, &mut progress))
257    }
258}
259
260/// GPU-vs-host parity on the packed DiT's first attention projection:
261/// the real q4tp bytes, activations spanning the modulation range
262/// (±2000 mixed with ±2), rms gate at 1e-2 — the measured failure was
263/// ~24%, honest drift is ~1e-5, so the gate has a decade of margin on
264/// each side. Any refusal (no adapter, dtype outside the kernel) is a
265/// clean "no": the host path is never wrong, only slower.
266pub(crate) fn mmh3_gpu_parity_probe(path: &Path) -> Result<bool, String> {
267    let model = Arc::new(
268        cortiq_core::CmfModel::open(path).map_err(|e| format!("{}: {e}", path.display()))?,
269    );
270    // Any codec, not just q4tp: the probe's job is to check THIS file's
271    // device arm against the host, and a container packed as q8_2f has one
272    // too. Matching on dtype sent every non-q4tp build to the CPU for the
273    // whole render — measured at 357 s against 60 on the same card.
274    // A container with the prompt encoder alone (`animate-pack --te` by
275    // itself) is probed on the encoder's first projection instead.
276    let Some(idx) = model
277        .tensors
278        .iter()
279        .position(|t| t.name.starts_with("dit.") && t.name.ends_with("attn.qkv_proj.weight"))
280        .or_else(|| {
281            model
282                .tensors
283                .iter()
284                .position(|t| t.name.starts_with("te.layers.") && t.name.ends_with("mlp.gate_proj.weight"))
285        })
286    else {
287        tracing::info!("mmh3 GPU parity probe: no qkv weight — host path");
288        return Ok(false);
289    };
290    let entry = &model.tensors[idx];
291    let (rows, cols) = (entry.shape[0], entry.shape[1]);
292    let b = 64usize;
293    let mut xs = vec![0f32; b * cols];
294    for (i, v) in xs.iter_mut().enumerate() {
295        let base = ((i * 37 + 11) % 1009) as f32 / 1009.0 - 0.5;
296        *v = base * if i % 7 == 0 { 2000.0 } else { 2.0 };
297    }
298    let mut gpu = vec![0f32; b * rows];
299    if std::env::var("CMF_GPU_DEBUG").is_ok() {
300        eprintln!(
301            "mmh3 probe env: CMF_GPU={:?} enabled={} avail={}",
302            std::env::var("CMF_GPU").ok(),
303            crate::gpu::enabled(),
304            crate::gpu::backend_available(),
305        );
306    }
307    let qt = crate::qtensor::QTensor::from_model(&model, &entry.name.clone())?;
308    // The native CUDA backend reads q4tp and q8_2f alike through one
309    // product (`gpu::q4tp_matmat`'s arm there); the per-codec device entry
310    // points of `device_matmat` are wgpu's and Metal's.
311    let took = if crate::gpu::cuda_active() {
312        crate::gpu::q4tp_matmat(&model, idx, &xs, b, rows, cols, &mut gpu)
313    } else {
314        qt.device_matmat(&xs, b, &mut gpu)
315    };
316    if !took {
317        tracing::info!(
318            "mmh3 GPU parity probe: {:?} device GEMM refused ({rows}x{cols}) — host path",
319            entry.dtype
320        );
321        if std::env::var("CMF_GPU_DEBUG").is_ok() {
322            eprintln!(
323                "mmh3 probe: device GEMM refused {rows}x{cols} for {:?}",
324                entry.dtype
325            );
326        }
327        return Ok(false);
328    }
329    let host = {
330        let name = entry.name.clone();
331        let proj = crate::dit::Proj::from_model(&model, &name)?;
332        let mut out = vec![0f32; b * rows];
333        crate::gpu::cpu_scope(|| proj.matmat(&xs, b, &mut out, None));
334        out
335    };
336    let mut num = 0f64;
337    let mut den = 0f64;
338    for (g, h) in gpu.iter().zip(&host) {
339        num += ((g - h) as f64).powi(2);
340        den += (*h as f64).powi(2);
341    }
342    let rel = (num / den.max(1e-30)).sqrt();
343    let ok = rel < 1e-2;
344    tracing::info!(
345        "mmh3 GPU parity probe: rel rms {rel:.2e} → {}",
346        if ok { "device" } else { "host" }
347    );
348    if std::env::var("CMF_GPU_DEBUG").is_ok() {
349        eprintln!("mmh3 GPU parity probe: rel rms {rel:.2e}");
350    }
351    Ok(ok)
352}
353
354fn generate_inner(
355    path: &Path,
356    prompt: &str,
357    p: &AnimParams,
358    progress: &mut dyn FnMut(&str, usize, usize),
359) -> Result<Anim, String> {
360    let model = Arc::new(
361        cortiq_core::CmfModel::open(path).map_err(|e| format!("{}: {e}", path.display()))?,
362    );
363    let (frames_total, latent_t, audio_t) = temporal_shape(p.frames);
364    let (lat_h, lat_w) = (p.height / 16, p.width / 16);
365
366    // ── prompt ──
367    // The H3 presentation is raw text: no chat template, no BOS, no
368    // special tokens at all.
369    // Stage clock. Half of a render is not the DiT — at 8 steps the
370    // denoiser is 63 s of 116 — and until this line existed there was
371    // no way to see which half anything went to.
372    let t_stage = std::time::Instant::now();
373    let mut marks: Vec<(&str, f32)> = Vec::new();
374    let lap = |marks: &mut Vec<(&'static str, f32)>, name: &'static str| {
375        let prev: f32 = marks.iter().map(|(_, v)| v).sum();
376        marks.push((name, t_stage.elapsed().as_secs_f32() - prev));
377    };
378    let vocab = model
379        .vocab
380        .as_deref()
381        .ok_or("packaged .cmf has no embedded tokenizer")?;
382    let tok = Tokenizer::from_bytes(vocab).map_err(|e| format!("tokenizer: {e}"))?;
383    // fl2va: every keyframe is presented as "<Picture i>: " and a
384    // vision block BEFORE the prompt, and separately conditions the DiT
385    // as a latent. Both halves come from the same picture.
386    let mut keyframes: Vec<(&(Vec<f32>, usize, usize), usize)> = p
387        .first_frame
388        .iter()
389        .map(|f| (f, 0usize))
390        .chain(
391            p.mid_frames
392                .iter()
393                .map(|(f, i)| (f, (*i).min(frames_total - 1))),
394        )
395        .chain(p.last_frame.iter().map(|f| (f, frames_total - 1)))
396        .collect();
397    // Condition rows are placed by time coordinate, so they have to arrive
398    // in time order and only once per frame — two references pinned to the
399    // same pixel index would be two rows claiming one moment.
400    keyframes.sort_by_key(|(_, i)| *i);
401    keyframes.dedup_by_key(|(_, i)| *i);
402    // ref2va's pictures and fl2va's keyframes are two layouts: one or the other.
403    if !p.refs.is_empty() && !keyframes.is_empty() {
404        return Err("--ref (ref2va) and --first-frame/--last-frame/--video (fl2va) are two layouts: pass one".into());
405    }
406    // Every picture the prompt presents, in order: the keyframes, or the
407    // references (each one fitted to the canvas like a first frame).
408    let pictures: Vec<&(Vec<f32>, usize, usize)> = keyframes.iter().map(|(f, _)| *f).chain(p.refs.iter()).collect();
409    let mut ids: Vec<u32> = Vec::new();
410    let mut spans: Vec<ImageSpan> = Vec::new();
411    let mut embeds: Vec<Vec<f32>> = Vec::new();
412    let mut deepstack: Vec<Vec<f32>> = Vec::new();
413    let mut cond: Vec<Vec<f32>> = Vec::new();
414    let mut tags: Vec<u8> = Vec::new();
415    // Each reference's latent size, in order (ref2va).
416    let mut ref_sizes: Vec<(usize, usize)> = Vec::new();
417
418    if !pictures.is_empty() {
419        let tower = VisionTower::from_cmf(&model)?;
420        // An activation harvest (CMF_TE_ONLY) never denoises, and the
421        // VAE latent is the DiT's food alone — the frame's 3-D conv
422        // encode is 99.5 s of a 102.5 s M4 run. Skip it.
423        let te_only = std::env::var("CMF_TE_ONLY").as_deref() == Ok("1");
424        let venc = if te_only {
425            None
426        } else {
427            Some(VideoVaeEncoder::from_cmf(&model)?)
428        };
429        for (i, frame) in pictures.iter().enumerate() {
430            let (src, sh, sw) = *frame;
431            // A keyframe is drawn on the generation canvas (a last frame
432            // cover-cropped where the first is stretched); a reference
433            // keeps its own aspect at the canvas's area (`ref_canvas`).
434            let is_ref = i >= keyframes.len();
435            let (ph, pw) = if is_ref { ref_canvas(*sh, *sw, p.height * p.width) } else { (p.height, p.width) };
436            let fitted = fit_to_canvas(src, *sh, *sw, ph, pw, i > 0 && !is_ref);
437            if is_ref {
438                ref_sizes.push((ph / 16, pw / 16));
439            }
440            if let Some(venc) = &venc {
441                let (z, _, _) = venc.encode_frame(&fitted.iter().map(|&v| v * 2.0 - 1.0).collect::<Vec<_>>(), ph, pw);
442                cond.push(z);
443            }
444
445            for t in tok.encode(&format!("<Picture {}>: ", i + 1)) {
446                ids.push(t);
447                tags.push(1);
448            }
449            let (patches, gh, gw) = qwen3vis::preprocess(
450                &fitted,
451                ph,
452                pw,
453                tower.patch_size,
454                tower.temporal_patch,
455                tower.merge,
456            );
457            let (merged, deep) = tower.forward(&patches, gh, gw);
458            let n_img = merged.len() / tower.out_hidden;
459            // The whole block carries the VIDEO tag, the flanking
460            // markers included.
461            ids.push(VISION_START);
462            tags.push(0);
463            let start = ids.len();
464            for _ in 0..n_img {
465                ids.push(VISION_START); // a placeholder the embed replaces
466                tags.push(0);
467            }
468            ids.push(VISION_END);
469            tags.push(0);
470            spans.push(ImageSpan {
471                start,
472                len: n_img,
473                merged_h: gh / tower.merge,
474                merged_w: gw / tower.merge,
475            });
476            embeds.push(merged);
477            if deepstack.is_empty() {
478                deepstack = deep;
479            } else {
480                for (a, b) in deepstack.iter_mut().zip(deep) {
481                    a.extend_from_slice(&b);
482                }
483            }
484        }
485    }
486    // The picture blocks come first and are never cut: `max_tokens` caps the
487    // prompt's text. Cutting into a block left its span past the sequence —
488    // two references on a 768×448 canvas are 672 vision rows before the text.
489    let picture_rows = ids.len();
490    for t in tok.encode(prompt) {
491        ids.push(t);
492        tags.push(1);
493    }
494    if ids.is_empty() {
495        ids.push(151643); // the pad id, as the reference does for ""
496        tags.push(1);
497    }
498    ids.truncate(picture_rows + p.max_tokens);
499    tags.truncate(ids.len());
500    lap(&mut marks, "prepare");
501    // The prompt encoder is a one-shot pass over 12 GB of weights; on a
502    // machine the file does not fit it streams from disk and its GEMMs
503    // run over any contention budget for reasons that are not contention.
504    // The kill stays disarmed until the encode is done (users on 24 GB
505    // Macs had to patch it out to keep the denoise loop on the GPU).
506    crate::gpu::mm_kill_arm(false);
507    progress("encode", 0, 1);
508    let states = {
509        let enc = Qwen3Encoder::from_cmf(&model)?;
510        enc.encode_with_images(&ids, &spans, &embeds, &deepstack)
511    };
512    // `CMF_TE_DUMP=<path>`: the conditioning as `[u64 n][u64 width]`
513    // then f32 rows. A stand-in encoder is only as good as the stream
514    // it hands the DiT, and that is measurable against the teacher's
515    // dump on the same prompt WITHOUT rendering a frame.
516    if let Ok(p) = std::env::var("CMF_TE_DUMP") {
517        let w = states.len() / ids.len().max(1);
518        let mut b = Vec::with_capacity(16 + states.len() * 4);
519        b.extend_from_slice(&(ids.len() as u64).to_le_bytes());
520        b.extend_from_slice(&(w as u64).to_le_bytes());
521        for v in &states {
522            b.extend_from_slice(&v.to_le_bytes());
523        }
524        std::fs::write(&p, &b).map_err(|e| format!("CMF_TE_DUMP {p}: {e}"))?;
525        eprintln!("te dump: {} tokens x {w} -> {p}", ids.len());
526    }
527    progress("encode", 1, 1);
528    lap(&mut marks, "text encode");
529    crate::gpu::mm_kill_arm(true);
530    // `CMF_TE_ONLY=1`: stop after the dump — an activation-harvest run
531    // (the ClipProj refit) wants hundreds of encodes and zero renders.
532    if std::env::var("CMF_TE_ONLY").as_deref() == Ok("1") {
533        return Err("CMF_TE_ONLY: encode dumped, render skipped".into());
534    }
535    // The prompt encoder and vision tower ran their once-per-generation
536    // pass; release their page cache so the denoise loop's DiT does not
537    // fight 12+ GB of dead weights for RAM. On a 24 GB Mac with the
538    // 25.7 GB full-encoder fl2va file this is the difference between
539    // denoise steps at DiT speed and 320 s/step of SSD thrash.
540    {
541        let dropped = model.advise_done(|n| n.starts_with("model.") || n.starts_with("vis."));
542        if dropped > 0 {
543            tracing::info!(
544                "encoder pages released after prompt encode: {} MB",
545                dropped / (1024 * 1024)
546            );
547        }
548    }
549    // The same on the card: a resident chain keeps the encoder's weights
550    // until its stage is declared done, and the DiT does not fit beside
551    // them on a 24 GB card.
552    crate::gpu::stage_done(&model);
553
554    // ── denoise ──
555    let (mut video, audio) = {
556        // The adapter is read here, after the encoder's pages are gone:
557        // a rank-32 file for this DiT is 130 MB of f32 once expanded and
558        // there is no reason for it to share a peak with 12 GB of text
559        // tower on a 24 GB machine.
560        let bank = match p.lora.as_deref() {
561            None => None,
562            Some(path) => {
563                let k =
564                    crate::ltxlora::LoraBank::load(std::path::Path::new(path), p.lora_strength)?;
565                Some(k)
566            }
567        };
568        let dit = MiniMaxH3::from_cmf_lora(&model, bank.as_ref())?;
569        if let Some(k) = &bank {
570            let bound = dit.lora_bound();
571            // Say what did NOT land. An adaLN branch on a curve-form
572            // pack is the one real gap, and a user who sees "applied"
573            // while half the adapter sat out has been lied to.
574            let mut skipped: std::collections::BTreeMap<String, usize> = Default::default();
575            for name in k.keys() {
576                if !dit.lora_binds(name) {
577                    let fam = name
578                        .rsplit_once('.')
579                        .map(|(_, t)| {
580                            let head = name.split('.').next().unwrap_or("");
581                            format!("{head}…{t}")
582                        })
583                        .unwrap_or_else(|| name.to_string());
584                    *skipped.entry(fam).or_default() += 1;
585                }
586            }
587            let tail = if skipped.is_empty() {
588                String::new()
589            } else {
590                let parts: Vec<String> = skipped.iter().map(|(k, v)| format!("{k} ×{v}")).collect();
591                format!("; not applied: {}", parts.join(", "))
592            };
593            tracing::info!(
594                "lora: rank {}, {} branches, {} bound at strength {}{}",
595                k.rank(),
596                k.len(),
597                bound,
598                p.lora_strength,
599                tail
600            );
601            println!(
602                "lora: rank {}, {}/{} branches bound{}",
603                k.rank(),
604                bound,
605                k.len(),
606                tail
607            );
608        }
609        let kf: Vec<(usize, usize)> = keyframes
610            .iter()
611            .map(|&(_, idx)| (idx, frames_total))
612            .collect();
613        let layout = if !p.refs.is_empty() {
614            // Each reference latent is one frame at its own size.
615            let refs: Vec<crate::mmh3::Ref> = ref_sizes.iter().map(|&(lat_h, lat_w)| crate::mmh3::Ref::Image { lat_h, lat_w }).collect();
616            Layout::ref2va(ids.len(), latent_t, lat_h, lat_w, audio_t, &refs, &tags)
617        } else if kf.is_empty() {
618            Layout::t2va(ids.len(), latent_t, lat_h, lat_w, audio_t)
619        } else {
620            Layout::fl2va(ids.len(), latent_t, lat_h, lat_w, audio_t, &kf, &tags)
621        };
622        let text = dit.refine_text(&states, ids.len());
623        let mut v = gauss(dit.latents_dim * latent_t * lat_h * lat_w, p.seed);
624        let mut a = gauss(dit.audio_dim * 2 * audio_t, p.seed ^ 0x9E37_79B9_7F4A_7C15);
625        // A few-step student carries the schedule it was distilled on
626        // (FastH3: 999, 749, 500, 250 on the 1000-step grid); a step count
627        // of its own keeps the `simple` grid.
628        // `steps = 0`: the file's own count (H3-Tiny FewStep: 6), else the
629        // Turbo LoRA's 4.
630        let steps = if p.steps == 0 { dit.default_steps.unwrap_or(4) } else { p.steps };
631        let sg = dit
632            .student_sigmas(steps)
633            .unwrap_or_else(|| sigmas(steps, dit.shift_video));
634        let mut return_streaming: Option<(Vec<f32>, Vec<f32>)> = None;
635        // `CMF_ANIM_PROF=1`: the per-step rms of both streams and of
636        // their velocities. A run that is not denoising shows it here
637        // long before anything is written out.
638        let prof = std::env::var_os("CMF_ANIM_PROF").is_some();
639        let rms = |x: &[f32]| {
640            (x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64).sqrt()
641        };
642        if prof {
643            eprintln!(
644                "  text {} tok, refined rms {:.4}, sigmas {:?}",
645                ids.len(),
646                rms(&text),
647                sg.iter()
648                    .map(|v| (v * 1e4).round() / 1e4)
649                    .collect::<Vec<_>>()
650            );
651        }
652        // ── chunk-causal rollout ──
653        //
654        // Each chunk is denoised while seeing only the text, `sink` chunks
655        // from the start and a sliding `window` of recent ones, and it is
656        // conditioned on their finished frames at timestep 0 — the
657        // protocol a streaming adapter is trained for. The reference keeps
658        // that context in a KV cache; not packing the rows a chunk may not
659        // see produces the same attention pattern, and the cache is then
660        // an optimization of this rather than a prerequisite.
661        if p.stream_chunk > 0 && cond.is_empty() {
662            let hw = lat_h * lat_w / 4 * 4; // frame element count is c·h·w below
663            let _ = hw;
664            let vc = dit.latents_dim;
665            let ac = dit.audio_dim;
666            let vframe = lat_h * lat_w; // per channel, per latent frame
667            let mut chunks: Vec<std::ops::Range<usize>> = (0..latent_t)
668                .step_by(p.stream_chunk)
669                .map(|s| s..(s + p.stream_chunk).min(latent_t))
670                .collect();
671            // A tail shorter than half a chunk joins the one before it. A
672            // two-frame chunk with four frames of context is the one shape
673            // that reliably wandered off — a different street in the last
674            // half second — and it is an artefact of the arithmetic, not
675            // something anyone asked for.
676            if chunks.len() > 1 {
677                let tail = chunks[chunks.len() - 1].clone();
678                if tail.len() < p.stream_chunk.div_ceil(2) {
679                    chunks.pop();
680                    let last = chunks.len() - 1;
681                    chunks[last].end = tail.end;
682                }
683            }
684            // The audio grid runs at its own rate; split it in the same
685            // proportion so a chunk's sound is the sound of its frames.
686            let a_bound = |k: usize| (k * audio_t).div_ceil(latent_t.max(1));
687            let mut v_out = vec![0f32; v.len()];
688            let mut a_out = vec![0f32; a.len()];
689            let gather_v = |src: &[f32], idx: &[usize]| -> Vec<f32> {
690                let mut out = vec![0f32; vc * idx.len() * vframe];
691                for ci in 0..vc {
692                    for (n, &k) in idx.iter().enumerate() {
693                        let s = (ci * latent_t + k) * vframe;
694                        let d = (ci * idx.len() + n) * vframe;
695                        out[d..d + vframe].copy_from_slice(&src[s..s + vframe]);
696                    }
697                }
698                out
699            };
700            let gather_a = |src: &[f32], idx: &[usize]| -> Vec<f32> {
701                let mut out = vec![0f32; ac * 2 * idx.len()];
702                for ci in 0..ac {
703                    for ch in 0..2 {
704                        for (n, &i) in idx.iter().enumerate() {
705                            out[(ci * 2 + ch) * idx.len() + n] = src[(ci * 2 + ch) * audio_t + i];
706                        }
707                    }
708                }
709                out
710            };
711            for (ci_, cur) in chunks.iter().enumerate() {
712                // The sink and the window are counted in LATENT FRAMES, the
713                // unit the reference's KV cache holds: two frames pinned at
714                // the start and two trailing the current chunk, not two whole
715                // chunks of each. Counting them in chunks made a chunk attend
716                // to four chunks' worth of rows — which is both slower than
717                // the bidirectional path it replaces and not the pattern the
718                // adapter trained. `CMF_STREAM_UNIT=chunks` keeps the old
719                // reading for comparison.
720                let by_chunk = std::env::var("CMF_STREAM_UNIT").as_deref() == Ok("chunks");
721                let ctx_v: Vec<usize> = if by_chunk {
722                    let mut vis: Vec<usize> = (0..p.stream_sink.min(ci_)).collect();
723                    for j in ci_.saturating_sub(p.stream_window)..ci_ {
724                        if !vis.contains(&j) {
725                            vis.push(j);
726                        }
727                    }
728                    vis.sort_unstable();
729                    vis.iter().flat_map(|&j| chunks[j].clone()).collect()
730                } else {
731                    let done = cur.start; // every frame finished so far
732                    let mut f: Vec<usize> = (0..p.stream_sink.min(done)).collect();
733                    for k in done.saturating_sub(p.stream_window)..done {
734                        if !f.contains(&k) {
735                            f.push(k);
736                        }
737                    }
738                    f.sort_unstable();
739                    f
740                };
741                let cur_v: Vec<usize> = cur.clone().collect();
742                // Audio rows follow the video frames they belong to.
743                let mut ctx_a: Vec<usize> = Vec::new();
744                for &k in &ctx_v {
745                    for i in a_bound(k)..a_bound(k + 1) {
746                        if !ctx_a.contains(&i) {
747                            ctx_a.push(i);
748                        }
749                    }
750                }
751                ctx_a.sort_unstable();
752                let cur_a: Vec<usize> = (a_bound(cur.start)..a_bound(cur.end)).collect();
753                let clay = Layout::streaming(
754                    ids.len(),
755                    &tags,
756                    lat_h,
757                    lat_w,
758                    &ctx_v,
759                    &cur_v,
760                    &ctx_a,
761                    &cur_a,
762                );
763                let ctx_vx = gather_v(&v_out, &ctx_v);
764                let ctx_ax = gather_a(&a_out, &ctx_a);
765                let mut xv = gather_v(&v, &cur_v);
766                let mut xa = gather_a(&a, &cur_a);
767                for i in 0..steps {
768                    let (sv, sv_n) = (sg[i], sg[i + 1]);
769                    // [context frames | current frames], the order the
770                    // layout lays its rows out in.
771                    let mut vin = vec![0f32; vc * (ctx_v.len() + cur_v.len()) * vframe];
772                    let mut ain = vec![0f32; ac * 2 * (ctx_a.len() + cur_a.len())];
773                    let (nc, nk) = (ctx_v.len(), cur_v.len());
774                    for c in 0..vc {
775                        let d = c * (nc + nk) * vframe;
776                        vin[d..d + nc * vframe]
777                            .copy_from_slice(&ctx_vx[c * nc * vframe..(c + 1) * nc * vframe]);
778                        vin[d + nc * vframe..d + (nc + nk) * vframe]
779                            .copy_from_slice(&xv[c * nk * vframe..(c + 1) * nk * vframe]);
780                    }
781                    let (mc, mk) = (ctx_a.len(), cur_a.len());
782                    for c in 0..ac {
783                        for ch in 0..2 {
784                            let d = (c * 2 + ch) * (mc + mk);
785                            ain[d..d + mc]
786                                .copy_from_slice(&ctx_ax[(c * 2 + ch) * mc..(c * 2 + ch + 1) * mc]);
787                            ain[d + mc..d + mc + mk]
788                                .copy_from_slice(&xa[(c * 2 + ch) * mk..(c * 2 + ch + 1) * mk]);
789                        }
790                    }
791                    let (dv, da) = dit.forward_to(&clay, &text, &vin, &ain, sv, Some(sv_n), &[]);
792                    let step_v = (sv_n - sv) as f32;
793                    for (x, &d) in xv.iter_mut().zip(&dv) {
794                        *x += step_v * d;
795                    }
796                    let step_a = if p.stock_sampler {
797                        step_v
798                    } else {
799                        (time_shift_sigma(sv_n, dit.shift_video, dit.shift_audio)
800                            - time_shift_sigma(sv.max(1e-6), dit.shift_video, dit.shift_audio))
801                            as f32
802                    };
803                    for (x, &d) in xa.iter_mut().zip(&da) {
804                        *x += step_a * d;
805                    }
806                }
807                for c in 0..vc {
808                    for (n, &k) in cur_v.iter().enumerate() {
809                        let d = (c * latent_t + k) * vframe;
810                        let s = (c * cur_v.len() + n) * vframe;
811                        v_out[d..d + vframe].copy_from_slice(&xv[s..s + vframe]);
812                    }
813                }
814                for c in 0..ac {
815                    for ch in 0..2 {
816                        for (n, &i) in cur_a.iter().enumerate() {
817                            a_out[(c * 2 + ch) * audio_t + i] = xa[(c * 2 + ch) * cur_a.len() + n];
818                        }
819                    }
820                }
821                progress("stream", ci_ + 1, chunks.len());
822            }
823            if let Some(rep) = dit.lora_report() {
824                eprint!("{rep}");
825            }
826            return_streaming = Some((v_out, a_out));
827        }
828
829        for i in 0..steps {
830            if return_streaming.is_some() {
831                break;
832            }
833            let (sv, sv_n) = (sg[i], sg[i + 1]);
834            let (dv, da) = dit.forward_to(&layout, &text, &v, &a, sv, Some(sv_n), &cond);
835            // `CMF_ANIM_DUMP=<prefix>`: this step's two velocities as raw
836            // f32 (`<prefix>.v<i>.f32`, `<prefix>.a<i>.f32`), so one forward
837            // can be compared between two paths before the sampler
838            // amplifies their difference.
839            if let Ok(pre) = std::env::var("CMF_ANIM_DUMP") {
840                let raw = |x: &[f32]| x.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>();
841                let _ = std::fs::write(format!("{pre}.v{i}.f32"), raw(&dv));
842                let _ = std::fs::write(format!("{pre}.a{i}.f32"), raw(&da));
843            }
844            let step_v = (sv_n - sv) as f32;
845            for (x, &d) in v.iter_mut().zip(&dv) {
846                *x += step_v * d;
847            }
848            let step_a = if p.stock_sampler {
849                step_v
850            } else {
851                (time_shift_sigma(sv_n, dit.shift_video, dit.shift_audio)
852                    - time_shift_sigma(sv.max(1e-6), dit.shift_video, dit.shift_audio))
853                    as f32
854            };
855            for (x, &d) in a.iter_mut().zip(&da) {
856                *x += step_a * d;
857            }
858            if prof {
859                eprintln!(
860                    "  step {i}: sv {sv:.4}->{sv_n:.4} v_vel {:.4} a_vel {:.4} | video {:.4} audio {:.4}",
861                    rms(&dv),
862                    rms(&da),
863                    rms(&v),
864                    rms(&a)
865                );
866            }
867            progress("denoise", i + 1, steps);
868        }
869        if let Some(rep) = dit.lora_report() {
870            eprint!("{rep}");
871        }
872        match return_streaming {
873            Some(pair) => pair,
874            None => (v, a),
875        }
876    };
877
878    lap(&mut marks, "denoise");
879    // The DiT is done: its weights leave the card before the decoders load.
880    crate::gpu::stage_done(&model);
881
882    // ── the learned latent resize, when one was handed in ──
883    let (mut out_h, mut out_w) = (p.height, p.width);
884    let (mut lat_h, mut lat_w) = (lat_h, lat_w);
885    if let Some(path) = p.upscale.as_deref() {
886        progress("upscale", 0, 1);
887        let t = std::time::Instant::now();
888        let ups = crate::mmh3ups::LatentUpscaler::load(std::path::Path::new(path))?;
889        let z = crate::mmh3ups::Vol {
890            c: video.len() / (latent_t * lat_h * lat_w),
891            t: latent_t,
892            h: lat_h,
893            w: lat_w,
894            data: video,
895        };
896        // Snap to the VAE's own 16-pixel grid: the net takes any target,
897        // the decoder does not.
898        let f = p.upscale_by.max(1.0);
899        let nh = ((lat_h as f32 * f).round() as usize).max(lat_h);
900        let nw = ((lat_w as f32 * f).round() as usize).max(lat_w);
901        let big = ups.upscale(&z, nh, nw, None);
902        tracing::info!(
903            "latent upscale {}x{} -> {}x{} in {:.1}s",
904            lat_h,
905            lat_w,
906            nh,
907            nw,
908            t.elapsed().as_secs_f64()
909        );
910        out_h = out_h * nh / lat_h;
911        out_w = out_w * nw / lat_w;
912        lat_h = nh;
913        lat_w = nw;
914        video = big.data;
915        progress("upscale", 1, 1);
916        lap(&mut marks, "upscale");
917    }
918
919    // ── decode ──
920    progress("video vae", 0, 1);
921    let (rgb, out_frames) = {
922        let vae = VideoVae::from_cmf(&model)?;
923        vae.decode(&video, latent_t, lat_h, lat_w)
924    };
925    progress("video vae", 1, 1);
926    lap(&mut marks, "video vae");
927    crate::gpu::stage_done(&model);
928    progress("audio vae", 0, 1);
929    let (wave, samples, sr) = {
930        let vae = AudioVae::from_cmf(&model)?;
931        let c = audio.len() / (2 * audio_t);
932        let (w, n) = vae.decode(&audio, c, audio_t);
933        (w, n, vae.sample_rate)
934    };
935    progress("audio vae", 1, 1);
936    lap(&mut marks, "audio vae");
937    tracing::info!(
938        "stages: {}",
939        marks
940            .iter()
941            .map(|(n, v)| format!("{n} {v:.1}s"))
942            .collect::<Vec<_>>()
943            .join(" · ")
944    );
945    // Where a GEMM's wall time goes on unified memory: copies or kernel.
946    // The answer decides whether fusing blocks or tuning the kernel is
947    // the optimization worth doing.
948    #[cfg(target_os = "macos")]
949    if std::env::var("CMF_METAL_MMPROF").is_ok() {
950        use std::sync::atomic::Ordering::Relaxed;
951        let n = crate::gpu_metal::MM_N.load(Relaxed);
952        eprintln!(
953            "  q4tp mm x{n}: upload {:.1}s · submit+wait {:.1}s · readback {:.1}s",
954            crate::gpu_metal::MM_UP.load(Relaxed) as f64 / 1e6,
955            crate::gpu_metal::MM_GPU.load(Relaxed) as f64 / 1e6,
956            crate::gpu_metal::MM_DN.load(Relaxed) as f64 / 1e6,
957        );
958    }
959
960    // The VAE emits latent_t·4 frames; the request snapped to 17k+5,
961    // which is one fewer than a multiple of four plus the leading key
962    // frame, so trim rather than pad.
963    let keep = out_frames.min(frames_total);
964    Ok(Anim {
965        rgb: trim_frames(&rgb, out_frames, keep, out_h, out_w),
966        frames: keep,
967        height: out_h,
968        width: out_w,
969        audio: wave,
970        samples,
971        sample_rate: sr,
972    })
973}
974
975fn trim_frames(rgb: &[f32], have: usize, keep: usize, h: usize, w: usize) -> Vec<f32> {
976    if keep == have {
977        return rgb.to_vec();
978    }
979    let mut out = vec![0f32; 3 * keep * h * w];
980    for c in 0..3 {
981        let s = c * have * h * w;
982        let d = c * keep * h * w;
983        out[d..d + keep * h * w].copy_from_slice(&rgb[s..s + keep * h * w]);
984    }
985    out
986}
987
988#[cfg(test)]
989mod tests {
990    use super::*;
991
992    #[test]
993    fn a_reference_keeps_its_aspect_at_the_canvas_area() {
994        // a portrait picture beside a 512 x 288 clip: about the clip's area,
995        // its own shape, both sides on the 32-pixel grid
996        let (h, w) = ref_canvas(640, 475, 288 * 512);
997        assert_eq!((h % 32, w % 32), (0, 0));
998        assert!(((h as f64 / w as f64) - 640.0 / 475.0).abs() < 0.12, "{h}x{w}");
999        assert!(((h * w) as f64 / (288.0 * 512.0) - 1.0).abs() < 0.15, "{h}x{w}");
1000        // a picture already the clip's shape keeps the clip's size
1001        assert_eq!(ref_canvas(360, 640, 288 * 512), (288, 512));
1002    }
1003
1004    #[test]
1005    fn the_four_step_schedule_is_the_references() {
1006        let s = sigmas(4, 12.0);
1007        let want = [1.0, 0.972_973, 0.923_077, 0.8, 0.0];
1008        assert_eq!(s.len(), want.len());
1009        for (g, w) in s.iter().zip(&want) {
1010            assert!((g - w).abs() < 1e-6, "{s:?}");
1011        }
1012    }
1013
1014    #[test]
1015    fn a_stretch_keeps_the_corners_and_a_crop_takes_the_middle() {
1016        // A 4x2 ramp: value rises left to right, so the corners name
1017        // themselves.
1018        let (h, w) = (2usize, 4usize);
1019        let mut rgb = vec![0f32; 3 * h * w];
1020        for c in 0..3 {
1021            for y in 0..h {
1022                for x in 0..w {
1023                    rgb[(c * h + y) * w + x] = x as f32 / (w - 1) as f32;
1024                }
1025            }
1026        }
1027        // Stretch to a square: the far edges survive.
1028        let s = fit_to_canvas(&rgb, h, w, 4, 4, false);
1029        assert!((s[0] - 0.0).abs() < 1e-6, "left edge");
1030        assert!((s[3] - 1.0).abs() < 1e-6, "right edge");
1031        // Cover-crop to a square takes the centre 2x2, so the extremes
1032        // are gone and the span is narrower.
1033        let c = fit_to_canvas(&rgb, h, w, 4, 4, true);
1034        let (lo, hi) = c[..16]
1035            .iter()
1036            .fold((f32::MAX, f32::MIN), |(a, b), &v| (a.min(v), b.max(v)));
1037        assert!(lo > 0.05, "crop kept the left edge: {lo}");
1038        assert!(hi < 0.95, "crop kept the right edge: {hi}");
1039    }
1040
1041    #[test]
1042    fn frame_counts_snap_to_the_models_grid() {
1043        // The grid is 5 + 17k: 5, 22, 39, 56, … 124.
1044        assert_eq!(align_frames(1), 5);
1045        assert_eq!(align_frames(39), 39);
1046        assert_eq!(align_frames(41), 56);
1047        assert_eq!(align_frames(124), 124);
1048        assert_eq!(video_latent_t(124), 37);
1049        assert_eq!(video_latent_t(39), 12);
1050        let (f, lt, at) = temporal_shape(124);
1051        assert_eq!((f, lt, at), (124, 37, 207));
1052    }
1053}