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::vae3d::VideoVaeEncoder;
24use crate::sampler::SplitMix64;
25use crate::tokenizer::Tokenizer;
26use crate::vae3d::VideoVae;
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}
49
50/// The vision-block token ids the H3 presentation flanks a picture with.
51const VISION_START: u32 = 151_652;
52const VISION_END: u32 = 151_653;
53
54/// Resize `[3, h, w]` RGB to the canvas. The first frame is a geometry
55/// anchor and is stretched; the last one follows and is cover-cropped,
56/// which is what the reference node does with each.
57pub fn fit_to_canvas(
58    rgb: &[f32],
59    h: usize,
60    w: usize,
61    out_h: usize,
62    out_w: usize,
63    crop: bool,
64) -> Vec<f32> {
65    // Cover-crop picks the largest centred rectangle of the source with
66    // the target's aspect; a stretch takes the whole thing.
67    let (sx0, sy0, sw, sh) = if crop {
68        let (tw, th) = (out_w as f64, out_h as f64);
69        let scale = (w as f64 / tw).min(h as f64 / th);
70        let (cw, ch) = ((tw * scale).round() as usize, (th * scale).round() as usize);
71        ((w - cw) / 2, (h - ch) / 2, cw.max(1), ch.max(1))
72    } else {
73        (0, 0, w, h)
74    };
75    let mut out = vec![0f32; 3 * out_h * out_w];
76    for c in 0..3 {
77        for y in 0..out_h {
78            let sy = ((y as f64 + 0.5) * sh as f64 / out_h as f64 - 0.5).max(0.0);
79            let y0 = sy.floor() as usize;
80            let y1 = (y0 + 1).min(sh - 1);
81            let fy = (sy - y0 as f64) as f32;
82            for x in 0..out_w {
83                let sx = ((x as f64 + 0.5) * sw as f64 / out_w as f64 - 0.5).max(0.0);
84                let x0 = sx.floor() as usize;
85                let x1 = (x0 + 1).min(sw - 1);
86                let fx = (sx - x0 as f64) as f32;
87                let p = |yy: usize, xx: usize| rgb[(c * h + sy0 + yy) * w + sx0 + xx];
88                let top = p(y0, x0) * (1.0 - fx) + p(y0, x1) * fx;
89                let bot = p(y1, x0) * (1.0 - fx) + p(y1, x1) * fx;
90                out[(c * out_h + y) * out_w + x] = top * (1.0 - fy) + bot * fy;
91            }
92        }
93    }
94    out
95}
96
97impl Default for AnimParams {
98    fn default() -> Self {
99        Self {
100            width: 512,
101            height: 288,
102            frames: 39,
103            steps: 4,
104            seed: 42,
105            stock_sampler: false,
106            max_tokens: 512,
107            first_frame: None,
108            last_frame: None,
109        }
110    }
111}
112
113/// The rendered result: RGB in [0, 1] as `[3, frames, h, w]`, and
114/// stereo f32 in [-1, 1] as `[2, samples]`.
115pub struct Anim {
116    pub rgb: Vec<f32>,
117    pub frames: usize,
118    pub height: usize,
119    pub width: usize,
120    pub audio: Vec<f32>,
121    pub samples: usize,
122    pub sample_rate: usize,
123}
124
125/// Frame counts snap UP to 17k+5 — the grid the temporal VAE and the
126/// DiT's frame-span pattern agree on.
127pub fn align_frames(n: usize) -> usize {
128    let mut n = n.max(5);
129    while n % 17 != 5 {
130        n += 1;
131    }
132    n
133}
134
135pub fn video_latent_t(frames: usize) -> usize {
136    if frames <= 5 {
137        2
138    } else {
139        (frames - 5) / 17 * 5 + 2
140    }
141}
142
143/// `(frames, latent_t, audio_t)` for a requested length.
144pub fn temporal_shape(len: usize) -> (usize, usize, usize) {
145    let frames = align_frames(len);
146    let audio_t =
147        ((frames as f64 / FPS as f64) * AUDIO_LATENT_FPS as f64).round() as usize;
148    (frames, video_latent_t(frames), audio_t)
149}
150
151/// The `simple` scheduler over `ModelSamplingDiscreteFlow(shift)`: the
152/// 1000-entry sigma table sampled at even strides, terminal 0 appended.
153pub fn sigmas(steps: usize, shift: f64) -> Vec<f64> {
154    let table = 1000usize;
155    let mut out: Vec<f64> = (0..steps)
156        .map(|x| {
157            let idx = table - 1 - x * table / steps;
158            let t = (idx + 1) as f64 / table as f64;
159            shift * t / (1.0 + (shift - 1.0) * t)
160        })
161        .collect();
162    out.push(0.0);
163    out
164}
165
166/// Shared with the DiT's condition-row noise blend.
167pub fn gauss_pub(n: usize, seed: u64) -> Vec<f32> {
168    gauss(n, seed)
169}
170
171fn gauss(n: usize, seed: u64) -> Vec<f32> {
172    let mut rng = SplitMix64::new(seed);
173    let mut u = || (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64;
174    let mut out = Vec::with_capacity(n);
175    while out.len() < n {
176        let (a, b) = (u().max(1e-300), u());
177        let r = (-2.0 * a.ln()).sqrt();
178        let ang = 2.0 * std::f64::consts::PI * b;
179        out.push((r * ang.cos()) as f32);
180        if out.len() < n {
181            out.push((r * ang.sin()) as f32);
182        }
183    }
184    out
185}
186
187/// Text→(video, audio) from a packaged `.cmf`.
188pub fn generate(
189    path: &Path,
190    prompt: &str,
191    p: &AnimParams,
192    mut progress: impl FnMut(&str, usize, usize),
193) -> Result<Anim, String> {
194    if p.width % 32 != 0 || p.height % 32 != 0 {
195        return Err("width/height must be multiples of 32".into());
196    }
197    // The wgpu wide-GEMM arm was measured WRONG on one driver stack
198    // (RTX PRO 6000: step-1 velocity rms off, step-2 NaN) and byte-
199    // healthy on another (2×RTX 5090, coop and plain arms within 0.5%
200    // of each other and 3.5% of the host render). Trust is therefore
201    // PER-STACK, decided by a parity probe on this file's own first
202    // qkv weight at DiT-scale activations — not by a hardcoded verdict
203    // either way. CMF_MMH3_GPU=1/0 still forces.
204    let use_gpu = match std::env::var("CMF_MMH3_GPU").ok().as_deref() {
205        Some("1") => true,
206        Some("0") => false,
207        _ => mmh3_gpu_parity_probe(path).unwrap_or(false),
208    };
209    if use_gpu {
210        generate_inner(path, prompt, p, &mut progress)
211    } else {
212        crate::gpu::cpu_scope(|| generate_inner(path, prompt, p, &mut progress))
213    }
214}
215
216/// GPU-vs-host parity on the packed DiT's first attention projection:
217/// the real q4tp bytes, activations spanning the modulation range
218/// (±2000 mixed with ±2), rms gate at 1e-2 — the measured failure was
219/// ~24%, honest drift is ~1e-5, so the gate has a decade of margin on
220/// each side. Any refusal (no adapter, dtype outside the kernel) is a
221/// clean "no": the host path is never wrong, only slower.
222fn mmh3_gpu_parity_probe(path: &Path) -> Result<bool, String> {
223    let model = Arc::new(
224        cortiq_core::CmfModel::open(path).map_err(|e| format!("{}: {e}", path.display()))?,
225    );
226    let Some(idx) = model.tensors.iter().position(|t| {
227        t.name.starts_with("dit.")
228            && t.name.ends_with("attn.qkv_proj.weight")
229            && t.dtype == cortiq_core::TensorDtype::Q4TiledP
230    }) else {
231        tracing::info!("mmh3 GPU parity probe: no q4tp qkv tensor — host path");
232        return Ok(false);
233    };
234    let entry = &model.tensors[idx];
235    let (rows, cols) = (entry.shape[0], entry.shape[1]);
236    let b = 64usize;
237    let mut xs = vec![0f32; b * cols];
238    for (i, v) in xs.iter_mut().enumerate() {
239        let base = ((i * 37 + 11) % 1009) as f32 / 1009.0 - 0.5;
240        *v = base * if i % 7 == 0 { 2000.0 } else { 2.0 };
241    }
242    let mut gpu = vec![0f32; b * rows];
243    if std::env::var("CMF_GPU_DEBUG").is_ok() {
244        eprintln!(
245            "mmh3 probe env: CMF_GPU={:?} enabled={} avail={}",
246            std::env::var("CMF_GPU").ok(),
247            crate::gpu::enabled(),
248            crate::gpu::backend_available(),
249        );
250    }
251    if !crate::gpu::q4tp_matmat(&model, idx, &xs, b, rows, cols, &mut gpu) {
252        tracing::info!(
253            "mmh3 GPU parity probe: q4tp_matmat refused ({rows}x{cols}) — host path"
254        );
255        if std::env::var("CMF_GPU_DEBUG").is_ok() {
256            eprintln!("mmh3 probe: q4tp_matmat refused {rows}x{cols}");
257        }
258        return Ok(false);
259    }
260    let host = {
261        let name = entry.name.clone();
262        let proj = crate::dit::Proj::from_model(&model, &name)?;
263        let mut out = vec![0f32; b * rows];
264        crate::gpu::cpu_scope(|| proj.matmat(&xs, b, &mut out, None));
265        out
266    };
267    let mut num = 0f64;
268    let mut den = 0f64;
269    for (g, h) in gpu.iter().zip(&host) {
270        num += ((g - h) as f64).powi(2);
271        den += (*h as f64).powi(2);
272    }
273    let rel = (num / den.max(1e-30)).sqrt();
274    let ok = rel < 1e-2;
275    tracing::info!(
276        "mmh3 GPU parity probe: rel rms {rel:.2e} → {}",
277        if ok { "device" } else { "host" }
278    );
279    if std::env::var("CMF_GPU_DEBUG").is_ok() {
280        eprintln!("mmh3 GPU parity probe: rel rms {rel:.2e}");
281    }
282    Ok(ok)
283}
284
285fn generate_inner(
286    path: &Path,
287    prompt: &str,
288    p: &AnimParams,
289    progress: &mut dyn FnMut(&str, usize, usize),
290) -> Result<Anim, String> {
291    let model = Arc::new(
292        cortiq_core::CmfModel::open(path).map_err(|e| format!("{}: {e}", path.display()))?,
293    );
294    let (frames_total, latent_t, audio_t) = temporal_shape(p.frames);
295    let (lat_h, lat_w) = (p.height / 16, p.width / 16);
296
297    // ── prompt ──
298    // The H3 presentation is raw text: no chat template, no BOS, no
299    // special tokens at all.
300    // Stage clock. Half of a render is not the DiT — at 8 steps the
301    // denoiser is 63 s of 116 — and until this line existed there was
302    // no way to see which half anything went to.
303    let t_stage = std::time::Instant::now();
304    let mut marks: Vec<(&str, f32)> = Vec::new();
305    let mut lap = |marks: &mut Vec<(&'static str, f32)>, name: &'static str| {
306        let prev: f32 = marks.iter().map(|(_, v)| v).sum();
307        marks.push((name, t_stage.elapsed().as_secs_f32() - prev));
308    };
309    let vocab = model
310        .vocab
311        .as_deref()
312        .ok_or("packaged .cmf has no embedded tokenizer")?;
313    let tok = Tokenizer::from_bytes(vocab).map_err(|e| format!("tokenizer: {e}"))?;
314    // fl2va: every keyframe is presented as "<Picture i>: " and a
315    // vision block BEFORE the prompt, and separately conditions the DiT
316    // as a latent. Both halves come from the same picture.
317    let keyframes: Vec<(&(Vec<f32>, usize, usize), usize)> = p
318        .first_frame
319        .iter()
320        .map(|f| (f, 0usize))
321        .chain(p.last_frame.iter().map(|f| (f, frames_total - 1)))
322        .collect();
323    let mut ids: Vec<u32> = Vec::new();
324    let mut spans: Vec<ImageSpan> = Vec::new();
325    let mut embeds: Vec<Vec<f32>> = Vec::new();
326    let mut deepstack: Vec<Vec<f32>> = Vec::new();
327    let mut cond: Vec<Vec<f32>> = Vec::new();
328    let mut tags: Vec<u8> = Vec::new();
329
330    if !keyframes.is_empty() {
331        let tower = VisionTower::from_cmf(&model)?;
332        let venc = VideoVaeEncoder::from_cmf(&model)?;
333        for (i, (frame, _)) in keyframes.iter().enumerate() {
334            let (src, sh, sw) = *frame;
335            // The picture the DiT sees is on the generation canvas; the
336            // one Qwen sees keeps its own resolution policy.
337            let fitted = fit_to_canvas(src, *sh, *sw, p.height, p.width, i > 0);
338            let (z, _, _) = venc.encode_frame(
339                &fitted.iter().map(|&v| v * 2.0 - 1.0).collect::<Vec<_>>(),
340                p.height,
341                p.width,
342            );
343            cond.push(z);
344
345            for t in tok.encode(&format!("<Picture {}>: ", i + 1)) {
346                ids.push(t);
347                tags.push(1);
348            }
349            let (patches, gh, gw) = qwen3vis::preprocess(
350                &fitted, p.height, p.width,
351                tower.patch_size, tower.temporal_patch, tower.merge,
352            );
353            let (merged, deep) = tower.forward(&patches, gh, gw);
354            let n_img = merged.len() / tower.out_hidden;
355            // The whole block carries the VIDEO tag, the flanking
356            // markers included.
357            ids.push(VISION_START);
358            tags.push(0);
359            let start = ids.len();
360            for _ in 0..n_img {
361                ids.push(VISION_START); // a placeholder the embed replaces
362                tags.push(0);
363            }
364            ids.push(VISION_END);
365            tags.push(0);
366            spans.push(ImageSpan { start, len: n_img, merged_h: gh / tower.merge, merged_w: gw / tower.merge });
367            embeds.push(merged);
368            if deepstack.is_empty() {
369                deepstack = deep;
370            } else {
371                for (a, b) in deepstack.iter_mut().zip(deep) {
372                    a.extend_from_slice(&b);
373                }
374            }
375        }
376    }
377    for t in tok.encode(prompt) {
378        ids.push(t);
379        tags.push(1);
380    }
381    if ids.is_empty() {
382        ids.push(151643); // the pad id, as the reference does for ""
383        tags.push(1);
384    }
385    ids.truncate(p.max_tokens);
386    tags.truncate(ids.len());
387    lap(&mut marks, "prepare");
388    progress("encode", 0, 1);
389    let states = {
390        let enc = Qwen3Encoder::from_cmf(&model)?;
391        enc.encode_with_images(&ids, &spans, &embeds, &deepstack)
392    };
393    // `CMF_TE_DUMP=<path>`: the conditioning as `[u64 n][u64 width]`
394    // then f32 rows. A stand-in encoder is only as good as the stream
395    // it hands the DiT, and that is measurable against the teacher's
396    // dump on the same prompt WITHOUT rendering a frame.
397    if let Ok(p) = std::env::var("CMF_TE_DUMP") {
398        let w = states.len() / ids.len().max(1);
399        let mut b = Vec::with_capacity(16 + states.len() * 4);
400        b.extend_from_slice(&(ids.len() as u64).to_le_bytes());
401        b.extend_from_slice(&(w as u64).to_le_bytes());
402        for v in &states {
403            b.extend_from_slice(&v.to_le_bytes());
404        }
405        std::fs::write(&p, &b).map_err(|e| format!("CMF_TE_DUMP {p}: {e}"))?;
406        eprintln!("te dump: {} tokens x {w} -> {p}", ids.len());
407    }
408    progress("encode", 1, 1);
409    lap(&mut marks, "text encode");
410
411    // ── denoise ──
412    let (video, audio) = {
413        let dit = MiniMaxH3::from_cmf(&model)?;
414        let kf: Vec<(usize, usize)> = keyframes.iter().map(|&(_, idx)| (idx, frames_total)).collect();
415        let layout = if kf.is_empty() {
416            Layout::t2va(ids.len(), latent_t, lat_h, lat_w, audio_t)
417        } else {
418            Layout::fl2va(ids.len(), latent_t, lat_h, lat_w, audio_t, &kf, &tags)
419        };
420        let text = dit.refine_text(&states, ids.len());
421        let mut v = gauss(dit.latents_dim * latent_t * lat_h * lat_w, p.seed);
422        let mut a = gauss(dit.audio_dim * 2 * audio_t, p.seed ^ 0x9E37_79B9_7F4A_7C15);
423        let sg = sigmas(p.steps, dit.shift_video);
424        // `CMF_ANIM_PROF=1`: the per-step rms of both streams and of
425        // their velocities. A run that is not denoising shows it here
426        // long before anything is written out.
427        let prof = std::env::var_os("CMF_ANIM_PROF").is_some();
428        let rms = |x: &[f32]| {
429            (x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64).sqrt()
430        };
431        if prof {
432            eprintln!(
433                "  text {} tok, refined rms {:.4}, sigmas {:?}",
434                ids.len(),
435                rms(&text),
436                sg.iter().map(|v| (v * 1e4).round() / 1e4).collect::<Vec<_>>()
437            );
438        }
439        for i in 0..p.steps {
440            let (sv, sv_n) = (sg[i], sg[i + 1]);
441            let (dv, da) = dit.forward(&layout, &text, &v, &a, sv, &cond);
442            let step_v = (sv_n - sv) as f32;
443            for (x, &d) in v.iter_mut().zip(&dv) {
444                *x += step_v * d;
445            }
446            let step_a = if p.stock_sampler {
447                step_v
448            } else {
449                (time_shift_sigma(sv_n, dit.shift_video, dit.shift_audio)
450                    - time_shift_sigma(sv.max(1e-6), dit.shift_video, dit.shift_audio))
451                    as f32
452            };
453            for (x, &d) in a.iter_mut().zip(&da) {
454                *x += step_a * d;
455            }
456            if prof {
457                eprintln!(
458                    "  step {i}: sv {sv:.4}->{sv_n:.4} v_vel {:.4} a_vel {:.4} | video {:.4} audio {:.4}",
459                    rms(&dv), rms(&da), rms(&v), rms(&a)
460                );
461            }
462            progress("denoise", i + 1, p.steps);
463        }
464        (v, a)
465    };
466
467    lap(&mut marks, "denoise");
468    // ── decode ──
469    progress("video vae", 0, 1);
470    let (rgb, out_frames) = {
471        let vae = VideoVae::from_cmf(&model)?;
472        vae.decode(&video, latent_t, lat_h, lat_w)
473    };
474    progress("video vae", 1, 1);
475    lap(&mut marks, "video vae");
476    progress("audio vae", 0, 1);
477    let (wave, samples, sr) = {
478        let vae = AudioVae::from_cmf(&model)?;
479        let c = audio.len() / (2 * audio_t);
480        let (w, n) = vae.decode(&audio, c, audio_t);
481        (w, n, vae.sample_rate)
482    };
483    progress("audio vae", 1, 1);
484    lap(&mut marks, "audio vae");
485    tracing::info!(
486        "stages: {}",
487        marks
488            .iter()
489            .map(|(n, v)| format!("{n} {v:.1}s"))
490            .collect::<Vec<_>>()
491            .join(" · ")
492    );
493    // Where a GEMM's wall time goes on unified memory: copies or kernel.
494    // The answer decides whether fusing blocks or tuning the kernel is
495    // the optimization worth doing.
496    #[cfg(target_os = "macos")]
497    if std::env::var("CMF_METAL_MMPROF").is_ok() {
498        use std::sync::atomic::Ordering::Relaxed;
499        let n = crate::gpu_metal::MM_N.load(Relaxed);
500        eprintln!(
501            "  q4tp mm x{n}: upload {:.1}s · submit+wait {:.1}s · readback {:.1}s",
502            crate::gpu_metal::MM_UP.load(Relaxed) as f64 / 1e6,
503            crate::gpu_metal::MM_GPU.load(Relaxed) as f64 / 1e6,
504            crate::gpu_metal::MM_DN.load(Relaxed) as f64 / 1e6,
505        );
506    }
507
508    // The VAE emits latent_t·4 frames; the request snapped to 17k+5,
509    // which is one fewer than a multiple of four plus the leading key
510    // frame, so trim rather than pad.
511    let keep = out_frames.min(frames_total);
512    Ok(Anim {
513        rgb: trim_frames(&rgb, out_frames, keep, p.height, p.width),
514        frames: keep,
515        height: p.height,
516        width: p.width,
517        audio: wave,
518        samples,
519        sample_rate: sr,
520    })
521}
522
523fn trim_frames(rgb: &[f32], have: usize, keep: usize, h: usize, w: usize) -> Vec<f32> {
524    if keep == have {
525        return rgb.to_vec();
526    }
527    let mut out = vec![0f32; 3 * keep * h * w];
528    for c in 0..3 {
529        let s = c * have * h * w;
530        let d = c * keep * h * w;
531        out[d..d + keep * h * w].copy_from_slice(&rgb[s..s + keep * h * w]);
532    }
533    out
534}
535
536#[cfg(test)]
537mod tests {
538    use super::*;
539
540    #[test]
541    fn the_four_step_schedule_is_the_references() {
542        let s = sigmas(4, 12.0);
543        let want = [1.0, 0.972_973, 0.923_077, 0.8, 0.0];
544        assert_eq!(s.len(), want.len());
545        for (g, w) in s.iter().zip(&want) {
546            assert!((g - w).abs() < 1e-6, "{s:?}");
547        }
548    }
549
550    #[test]
551    fn a_stretch_keeps_the_corners_and_a_crop_takes_the_middle() {
552        // A 4x2 ramp: value rises left to right, so the corners name
553        // themselves.
554        let (h, w) = (2usize, 4usize);
555        let mut rgb = vec![0f32; 3 * h * w];
556        for c in 0..3 {
557            for y in 0..h {
558                for x in 0..w {
559                    rgb[(c * h + y) * w + x] = x as f32 / (w - 1) as f32;
560                }
561            }
562        }
563        // Stretch to a square: the far edges survive.
564        let s = fit_to_canvas(&rgb, h, w, 4, 4, false);
565        assert!((s[0] - 0.0).abs() < 1e-6, "left edge");
566        assert!((s[3] - 1.0).abs() < 1e-6, "right edge");
567        // Cover-crop to a square takes the centre 2x2, so the extremes
568        // are gone and the span is narrower.
569        let c = fit_to_canvas(&rgb, h, w, 4, 4, true);
570        let (lo, hi) = c[..16]
571            .iter()
572            .fold((f32::MAX, f32::MIN), |(a, b), &v| (a.min(v), b.max(v)));
573        assert!(lo > 0.05, "crop kept the left edge: {lo}");
574        assert!(hi < 0.95, "crop kept the right edge: {hi}");
575    }
576
577    #[test]
578    fn frame_counts_snap_to_the_models_grid() {
579        // The grid is 5 + 17k: 5, 22, 39, 56, … 124.
580        assert_eq!(align_frames(1), 5);
581        assert_eq!(align_frames(39), 39);
582        assert_eq!(align_frames(41), 56);
583        assert_eq!(align_frames(124), 124);
584        assert_eq!(video_latent_t(124), 37);
585        assert_eq!(video_latent_t(39), 12);
586        let (f, lt, at) = temporal_shape(124);
587        assert_eq!((f, lt, at), (124, 37, 207));
588    }
589}