1use 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 pub frames: usize,
38 pub steps: usize,
39 pub seed: u64,
40 pub stock_sampler: bool,
43 pub max_tokens: usize,
44 pub first_frame: Option<(Vec<f32>, usize, usize)>,
47 pub last_frame: Option<(Vec<f32>, usize, usize)>,
48 pub mid_frames: Vec<((Vec<f32>, usize, usize), usize)>,
53 pub lora: Option<String>,
55 pub lora_strength: f32,
56 pub upscale: Option<String>,
61 pub upscale_by: f32,
62}
63
64const VISION_START: u32 = 151_652;
66const VISION_END: u32 = 151_653;
67
68pub fn fit_to_canvas(
72 rgb: &[f32],
73 h: usize,
74 w: usize,
75 out_h: usize,
76 out_w: usize,
77 crop: bool,
78) -> Vec<f32> {
79 let (sx0, sy0, sw, sh) = if crop {
82 let (tw, th) = (out_w as f64, out_h as f64);
83 let scale = (w as f64 / tw).min(h as f64 / th);
84 let (cw, ch) = ((tw * scale).round() as usize, (th * scale).round() as usize);
85 ((w - cw) / 2, (h - ch) / 2, cw.max(1), ch.max(1))
86 } else {
87 (0, 0, w, h)
88 };
89 let mut out = vec![0f32; 3 * out_h * out_w];
90 for c in 0..3 {
91 for y in 0..out_h {
92 let sy = ((y as f64 + 0.5) * sh as f64 / out_h as f64 - 0.5).max(0.0);
93 let y0 = sy.floor() as usize;
94 let y1 = (y0 + 1).min(sh - 1);
95 let fy = (sy - y0 as f64) as f32;
96 for x in 0..out_w {
97 let sx = ((x as f64 + 0.5) * sw as f64 / out_w as f64 - 0.5).max(0.0);
98 let x0 = sx.floor() as usize;
99 let x1 = (x0 + 1).min(sw - 1);
100 let fx = (sx - x0 as f64) as f32;
101 let p = |yy: usize, xx: usize| rgb[(c * h + sy0 + yy) * w + sx0 + xx];
102 let top = p(y0, x0) * (1.0 - fx) + p(y0, x1) * fx;
103 let bot = p(y1, x0) * (1.0 - fx) + p(y1, x1) * fx;
104 out[(c * out_h + y) * out_w + x] = top * (1.0 - fy) + bot * fy;
105 }
106 }
107 }
108 out
109}
110
111impl Default for AnimParams {
112 fn default() -> Self {
113 Self {
114 width: 512,
115 height: 288,
116 frames: 39,
117 steps: 4,
118 seed: 42,
119 stock_sampler: false,
120 max_tokens: 512,
121 first_frame: None,
122 last_frame: None,
123 mid_frames: Vec::new(),
124 lora: None,
125 lora_strength: 1.0,
126 upscale: None,
127 upscale_by: 2.0,
128 }
129 }
130}
131
132pub struct Anim {
135 pub rgb: Vec<f32>,
136 pub frames: usize,
137 pub height: usize,
138 pub width: usize,
139 pub audio: Vec<f32>,
140 pub samples: usize,
141 pub sample_rate: usize,
142}
143
144pub fn align_frames(n: usize) -> usize {
147 let mut n = n.max(5);
148 while n % 17 != 5 {
149 n += 1;
150 }
151 n
152}
153
154pub fn video_latent_t(frames: usize) -> usize {
155 if frames <= 5 {
156 2
157 } else {
158 (frames - 5) / 17 * 5 + 2
159 }
160}
161
162pub fn temporal_shape(len: usize) -> (usize, usize, usize) {
164 let frames = align_frames(len);
165 let audio_t = ((frames as f64 / FPS as f64) * AUDIO_LATENT_FPS as f64).round() as usize;
166 (frames, video_latent_t(frames), audio_t)
167}
168
169pub fn sigmas(steps: usize, shift: f64) -> Vec<f64> {
172 let table = 1000usize;
173 let mut out: Vec<f64> = (0..steps)
174 .map(|x| {
175 let idx = table - 1 - x * table / steps;
176 let t = (idx + 1) as f64 / table as f64;
177 shift * t / (1.0 + (shift - 1.0) * t)
178 })
179 .collect();
180 out.push(0.0);
181 out
182}
183
184pub fn gauss_pub(n: usize, seed: u64) -> Vec<f32> {
186 gauss(n, seed)
187}
188
189fn gauss(n: usize, seed: u64) -> Vec<f32> {
190 let mut rng = SplitMix64::new(seed);
191 let mut u = || (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64;
192 let mut out = Vec::with_capacity(n);
193 while out.len() < n {
194 let (a, b) = (u().max(1e-300), u());
195 let r = (-2.0 * a.ln()).sqrt();
196 let ang = 2.0 * std::f64::consts::PI * b;
197 out.push((r * ang.cos()) as f32);
198 if out.len() < n {
199 out.push((r * ang.sin()) as f32);
200 }
201 }
202 out
203}
204
205pub fn generate(
207 path: &Path,
208 prompt: &str,
209 p: &AnimParams,
210 mut progress: impl FnMut(&str, usize, usize),
211) -> Result<Anim, String> {
212 if p.width % 32 != 0 || p.height % 32 != 0 {
213 return Err("width/height must be multiples of 32".into());
214 }
215 let use_gpu = match std::env::var("CMF_MMH3_GPU").ok().as_deref() {
223 Some("1") => true,
224 Some("0") => false,
225 _ => mmh3_gpu_parity_probe(path).unwrap_or(false),
226 };
227 if use_gpu {
228 generate_inner(path, prompt, p, &mut progress)
229 } else {
230 crate::gpu::cpu_scope(|| generate_inner(path, prompt, p, &mut progress))
231 }
232}
233
234fn mmh3_gpu_parity_probe(path: &Path) -> Result<bool, String> {
241 let model = Arc::new(
242 cortiq_core::CmfModel::open(path).map_err(|e| format!("{}: {e}", path.display()))?,
243 );
244 let Some(idx) = model.tensors.iter().position(|t| {
245 t.name.starts_with("dit.")
246 && t.name.ends_with("attn.qkv_proj.weight")
247 && t.dtype == cortiq_core::TensorDtype::Q4TiledP
248 }) else {
249 tracing::info!("mmh3 GPU parity probe: no q4tp qkv tensor — host path");
250 return Ok(false);
251 };
252 let entry = &model.tensors[idx];
253 let (rows, cols) = (entry.shape[0], entry.shape[1]);
254 let b = 64usize;
255 let mut xs = vec![0f32; b * cols];
256 for (i, v) in xs.iter_mut().enumerate() {
257 let base = ((i * 37 + 11) % 1009) as f32 / 1009.0 - 0.5;
258 *v = base * if i % 7 == 0 { 2000.0 } else { 2.0 };
259 }
260 let mut gpu = vec![0f32; b * rows];
261 if std::env::var("CMF_GPU_DEBUG").is_ok() {
262 eprintln!(
263 "mmh3 probe env: CMF_GPU={:?} enabled={} avail={}",
264 std::env::var("CMF_GPU").ok(),
265 crate::gpu::enabled(),
266 crate::gpu::backend_available(),
267 );
268 }
269 if !crate::gpu::q4tp_matmat(&model, idx, &xs, b, rows, cols, &mut gpu) {
270 tracing::info!("mmh3 GPU parity probe: q4tp_matmat refused ({rows}x{cols}) — host path");
271 if std::env::var("CMF_GPU_DEBUG").is_ok() {
272 eprintln!("mmh3 probe: q4tp_matmat refused {rows}x{cols}");
273 }
274 return Ok(false);
275 }
276 let host = {
277 let name = entry.name.clone();
278 let proj = crate::dit::Proj::from_model(&model, &name)?;
279 let mut out = vec![0f32; b * rows];
280 crate::gpu::cpu_scope(|| proj.matmat(&xs, b, &mut out, None));
281 out
282 };
283 let mut num = 0f64;
284 let mut den = 0f64;
285 for (g, h) in gpu.iter().zip(&host) {
286 num += ((g - h) as f64).powi(2);
287 den += (*h as f64).powi(2);
288 }
289 let rel = (num / den.max(1e-30)).sqrt();
290 let ok = rel < 1e-2;
291 tracing::info!(
292 "mmh3 GPU parity probe: rel rms {rel:.2e} → {}",
293 if ok { "device" } else { "host" }
294 );
295 if std::env::var("CMF_GPU_DEBUG").is_ok() {
296 eprintln!("mmh3 GPU parity probe: rel rms {rel:.2e}");
297 }
298 Ok(ok)
299}
300
301fn generate_inner(
302 path: &Path,
303 prompt: &str,
304 p: &AnimParams,
305 progress: &mut dyn FnMut(&str, usize, usize),
306) -> Result<Anim, String> {
307 let model = Arc::new(
308 cortiq_core::CmfModel::open(path).map_err(|e| format!("{}: {e}", path.display()))?,
309 );
310 let (frames_total, latent_t, audio_t) = temporal_shape(p.frames);
311 let (lat_h, lat_w) = (p.height / 16, p.width / 16);
312
313 let t_stage = std::time::Instant::now();
320 let mut marks: Vec<(&str, f32)> = Vec::new();
321 let lap = |marks: &mut Vec<(&'static str, f32)>, name: &'static str| {
322 let prev: f32 = marks.iter().map(|(_, v)| v).sum();
323 marks.push((name, t_stage.elapsed().as_secs_f32() - prev));
324 };
325 let vocab = model
326 .vocab
327 .as_deref()
328 .ok_or("packaged .cmf has no embedded tokenizer")?;
329 let tok = Tokenizer::from_bytes(vocab).map_err(|e| format!("tokenizer: {e}"))?;
330 let mut keyframes: Vec<(&(Vec<f32>, usize, usize), usize)> = p
334 .first_frame
335 .iter()
336 .map(|f| (f, 0usize))
337 .chain(p.mid_frames.iter().map(|(f, i)| (f, (*i).min(frames_total - 1))))
338 .chain(p.last_frame.iter().map(|f| (f, frames_total - 1)))
339 .collect();
340 keyframes.sort_by_key(|(_, i)| *i);
344 keyframes.dedup_by_key(|(_, i)| *i);
345 let mut ids: Vec<u32> = Vec::new();
346 let mut spans: Vec<ImageSpan> = Vec::new();
347 let mut embeds: Vec<Vec<f32>> = Vec::new();
348 let mut deepstack: Vec<Vec<f32>> = Vec::new();
349 let mut cond: Vec<Vec<f32>> = Vec::new();
350 let mut tags: Vec<u8> = Vec::new();
351
352 if !keyframes.is_empty() {
353 let tower = VisionTower::from_cmf(&model)?;
354 let te_only = std::env::var("CMF_TE_ONLY").as_deref() == Ok("1");
358 let venc = if te_only {
359 None
360 } else {
361 Some(VideoVaeEncoder::from_cmf(&model)?)
362 };
363 for (i, (frame, _)) in keyframes.iter().enumerate() {
364 let (src, sh, sw) = *frame;
365 let fitted = fit_to_canvas(src, *sh, *sw, p.height, p.width, i > 0);
368 if let Some(venc) = &venc {
369 let (z, _, _) = venc.encode_frame(
370 &fitted.iter().map(|&v| v * 2.0 - 1.0).collect::<Vec<_>>(),
371 p.height,
372 p.width,
373 );
374 cond.push(z);
375 }
376
377 for t in tok.encode(&format!("<Picture {}>: ", i + 1)) {
378 ids.push(t);
379 tags.push(1);
380 }
381 let (patches, gh, gw) = qwen3vis::preprocess(
382 &fitted,
383 p.height,
384 p.width,
385 tower.patch_size,
386 tower.temporal_patch,
387 tower.merge,
388 );
389 let (merged, deep) = tower.forward(&patches, gh, gw);
390 let n_img = merged.len() / tower.out_hidden;
391 ids.push(VISION_START);
394 tags.push(0);
395 let start = ids.len();
396 for _ in 0..n_img {
397 ids.push(VISION_START); tags.push(0);
399 }
400 ids.push(VISION_END);
401 tags.push(0);
402 spans.push(ImageSpan {
403 start,
404 len: n_img,
405 merged_h: gh / tower.merge,
406 merged_w: gw / tower.merge,
407 });
408 embeds.push(merged);
409 if deepstack.is_empty() {
410 deepstack = deep;
411 } else {
412 for (a, b) in deepstack.iter_mut().zip(deep) {
413 a.extend_from_slice(&b);
414 }
415 }
416 }
417 }
418 for t in tok.encode(prompt) {
419 ids.push(t);
420 tags.push(1);
421 }
422 if ids.is_empty() {
423 ids.push(151643); tags.push(1);
425 }
426 ids.truncate(p.max_tokens);
427 tags.truncate(ids.len());
428 lap(&mut marks, "prepare");
429 crate::gpu::mm_kill_arm(false);
435 progress("encode", 0, 1);
436 let states = {
437 let enc = Qwen3Encoder::from_cmf(&model)?;
438 enc.encode_with_images(&ids, &spans, &embeds, &deepstack)
439 };
440 if let Ok(p) = std::env::var("CMF_TE_DUMP") {
445 let w = states.len() / ids.len().max(1);
446 let mut b = Vec::with_capacity(16 + states.len() * 4);
447 b.extend_from_slice(&(ids.len() as u64).to_le_bytes());
448 b.extend_from_slice(&(w as u64).to_le_bytes());
449 for v in &states {
450 b.extend_from_slice(&v.to_le_bytes());
451 }
452 std::fs::write(&p, &b).map_err(|e| format!("CMF_TE_DUMP {p}: {e}"))?;
453 eprintln!("te dump: {} tokens x {w} -> {p}", ids.len());
454 }
455 progress("encode", 1, 1);
456 lap(&mut marks, "text encode");
457 crate::gpu::mm_kill_arm(true);
458 if std::env::var("CMF_TE_ONLY").as_deref() == Ok("1") {
461 return Err("CMF_TE_ONLY: encode dumped, render skipped".into());
462 }
463 {
469 let dropped = model.advise_done(|n| n.starts_with("model.") || n.starts_with("vis."));
470 if dropped > 0 {
471 tracing::info!(
472 "encoder pages released after prompt encode: {} MB",
473 dropped / (1024 * 1024)
474 );
475 }
476 }
477
478 let (mut video, audio) = {
480 let bank = match p.lora.as_deref() {
485 None => None,
486 Some(path) => {
487 let k = crate::ltxlora::LoraBank::load(std::path::Path::new(path), p.lora_strength)?;
488 Some(k)
489 }
490 };
491 let dit = MiniMaxH3::from_cmf_lora(&model, bank.as_ref())?;
492 if let Some(k) = &bank {
493 let bound = dit.lora_bound();
494 let mut skipped: std::collections::BTreeMap<String, usize> = Default::default();
498 for name in k.keys() {
499 if !dit.lora_binds(name) {
500 let fam = name
501 .rsplit_once('.')
502 .map(|(_, t)| {
503 let head = name.split('.').next().unwrap_or("");
504 format!("{head}…{t}")
505 })
506 .unwrap_or_else(|| name.to_string());
507 *skipped.entry(fam).or_default() += 1;
508 }
509 }
510 let tail = if skipped.is_empty() {
511 String::new()
512 } else {
513 let parts: Vec<String> =
514 skipped.iter().map(|(k, v)| format!("{k} ×{v}")).collect();
515 format!("; not applied: {}", parts.join(", "))
516 };
517 tracing::info!(
518 "lora: rank {}, {} branches, {} bound at strength {}{}",
519 k.rank(),
520 k.len(),
521 bound,
522 p.lora_strength,
523 tail
524 );
525 println!(
526 "lora: rank {}, {}/{} branches bound{}",
527 k.rank(),
528 bound,
529 k.len(),
530 tail
531 );
532 }
533 let kf: Vec<(usize, usize)> = keyframes
534 .iter()
535 .map(|&(_, idx)| (idx, frames_total))
536 .collect();
537 let layout = if kf.is_empty() {
538 Layout::t2va(ids.len(), latent_t, lat_h, lat_w, audio_t)
539 } else {
540 Layout::fl2va(ids.len(), latent_t, lat_h, lat_w, audio_t, &kf, &tags)
541 };
542 let text = dit.refine_text(&states, ids.len());
543 let mut v = gauss(dit.latents_dim * latent_t * lat_h * lat_w, p.seed);
544 let mut a = gauss(dit.audio_dim * 2 * audio_t, p.seed ^ 0x9E37_79B9_7F4A_7C15);
545 let sg = sigmas(p.steps, dit.shift_video);
546 let prof = std::env::var_os("CMF_ANIM_PROF").is_some();
550 let rms = |x: &[f32]| {
551 (x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64).sqrt()
552 };
553 if prof {
554 eprintln!(
555 " text {} tok, refined rms {:.4}, sigmas {:?}",
556 ids.len(),
557 rms(&text),
558 sg.iter()
559 .map(|v| (v * 1e4).round() / 1e4)
560 .collect::<Vec<_>>()
561 );
562 }
563 for i in 0..p.steps {
564 let (sv, sv_n) = (sg[i], sg[i + 1]);
565 let (dv, da) = dit.forward(&layout, &text, &v, &a, sv, &cond);
566 let step_v = (sv_n - sv) as f32;
567 for (x, &d) in v.iter_mut().zip(&dv) {
568 *x += step_v * d;
569 }
570 let step_a = if p.stock_sampler {
571 step_v
572 } else {
573 (time_shift_sigma(sv_n, dit.shift_video, dit.shift_audio)
574 - time_shift_sigma(sv.max(1e-6), dit.shift_video, dit.shift_audio))
575 as f32
576 };
577 for (x, &d) in a.iter_mut().zip(&da) {
578 *x += step_a * d;
579 }
580 if prof {
581 eprintln!(
582 " step {i}: sv {sv:.4}->{sv_n:.4} v_vel {:.4} a_vel {:.4} | video {:.4} audio {:.4}",
583 rms(&dv),
584 rms(&da),
585 rms(&v),
586 rms(&a)
587 );
588 }
589 progress("denoise", i + 1, p.steps);
590 }
591 if let Some(rep) = dit.lora_report() {
592 eprint!("{rep}");
593 }
594 (v, a)
595 };
596
597 lap(&mut marks, "denoise");
598
599 let (mut out_h, mut out_w) = (p.height, p.width);
601 let (mut lat_h, mut lat_w) = (lat_h, lat_w);
602 if let Some(path) = p.upscale.as_deref() {
603 progress("upscale", 0, 1);
604 let t = std::time::Instant::now();
605 let ups = crate::mmh3ups::LatentUpscaler::load(std::path::Path::new(path))?;
606 let z = crate::mmh3ups::Vol {
607 c: video.len() / (latent_t * lat_h * lat_w),
608 t: latent_t,
609 h: lat_h,
610 w: lat_w,
611 data: video,
612 };
613 let f = p.upscale_by.max(1.0);
616 let nh = ((lat_h as f32 * f).round() as usize).max(lat_h);
617 let nw = ((lat_w as f32 * f).round() as usize).max(lat_w);
618 let big = ups.upscale(&z, nh, nw, None);
619 tracing::info!(
620 "latent upscale {}x{} -> {}x{} in {:.1}s",
621 lat_h,
622 lat_w,
623 nh,
624 nw,
625 t.elapsed().as_secs_f64()
626 );
627 out_h = out_h * nh / lat_h;
628 out_w = out_w * nw / lat_w;
629 lat_h = nh;
630 lat_w = nw;
631 video = big.data;
632 progress("upscale", 1, 1);
633 lap(&mut marks, "upscale");
634 }
635
636 progress("video vae", 0, 1);
638 let (rgb, out_frames) = {
639 let vae = VideoVae::from_cmf(&model)?;
640 vae.decode(&video, latent_t, lat_h, lat_w)
641 };
642 progress("video vae", 1, 1);
643 lap(&mut marks, "video vae");
644 progress("audio vae", 0, 1);
645 let (wave, samples, sr) = {
646 let vae = AudioVae::from_cmf(&model)?;
647 let c = audio.len() / (2 * audio_t);
648 let (w, n) = vae.decode(&audio, c, audio_t);
649 (w, n, vae.sample_rate)
650 };
651 progress("audio vae", 1, 1);
652 lap(&mut marks, "audio vae");
653 tracing::info!(
654 "stages: {}",
655 marks
656 .iter()
657 .map(|(n, v)| format!("{n} {v:.1}s"))
658 .collect::<Vec<_>>()
659 .join(" · ")
660 );
661 #[cfg(target_os = "macos")]
665 if std::env::var("CMF_METAL_MMPROF").is_ok() {
666 use std::sync::atomic::Ordering::Relaxed;
667 let n = crate::gpu_metal::MM_N.load(Relaxed);
668 eprintln!(
669 " q4tp mm x{n}: upload {:.1}s · submit+wait {:.1}s · readback {:.1}s",
670 crate::gpu_metal::MM_UP.load(Relaxed) as f64 / 1e6,
671 crate::gpu_metal::MM_GPU.load(Relaxed) as f64 / 1e6,
672 crate::gpu_metal::MM_DN.load(Relaxed) as f64 / 1e6,
673 );
674 }
675
676 let keep = out_frames.min(frames_total);
680 Ok(Anim {
681 rgb: trim_frames(&rgb, out_frames, keep, out_h, out_w),
682 frames: keep,
683 height: out_h,
684 width: out_w,
685 audio: wave,
686 samples,
687 sample_rate: sr,
688 })
689}
690
691fn trim_frames(rgb: &[f32], have: usize, keep: usize, h: usize, w: usize) -> Vec<f32> {
692 if keep == have {
693 return rgb.to_vec();
694 }
695 let mut out = vec![0f32; 3 * keep * h * w];
696 for c in 0..3 {
697 let s = c * have * h * w;
698 let d = c * keep * h * w;
699 out[d..d + keep * h * w].copy_from_slice(&rgb[s..s + keep * h * w]);
700 }
701 out
702}
703
704#[cfg(test)]
705mod tests {
706 use super::*;
707
708 #[test]
709 fn the_four_step_schedule_is_the_references() {
710 let s = sigmas(4, 12.0);
711 let want = [1.0, 0.972_973, 0.923_077, 0.8, 0.0];
712 assert_eq!(s.len(), want.len());
713 for (g, w) in s.iter().zip(&want) {
714 assert!((g - w).abs() < 1e-6, "{s:?}");
715 }
716 }
717
718 #[test]
719 fn a_stretch_keeps_the_corners_and_a_crop_takes_the_middle() {
720 let (h, w) = (2usize, 4usize);
723 let mut rgb = vec![0f32; 3 * h * w];
724 for c in 0..3 {
725 for y in 0..h {
726 for x in 0..w {
727 rgb[(c * h + y) * w + x] = x as f32 / (w - 1) as f32;
728 }
729 }
730 }
731 let s = fit_to_canvas(&rgb, h, w, 4, 4, false);
733 assert!((s[0] - 0.0).abs() < 1e-6, "left edge");
734 assert!((s[3] - 1.0).abs() < 1e-6, "right edge");
735 let c = fit_to_canvas(&rgb, h, w, 4, 4, true);
738 let (lo, hi) = c[..16]
739 .iter()
740 .fold((f32::MAX, f32::MIN), |(a, b), &v| (a.min(v), b.max(v)));
741 assert!(lo > 0.05, "crop kept the left edge: {lo}");
742 assert!(hi < 0.95, "crop kept the right edge: {hi}");
743 }
744
745 #[test]
746 fn frame_counts_snap_to_the_models_grid() {
747 assert_eq!(align_frames(1), 5);
749 assert_eq!(align_frames(39), 39);
750 assert_eq!(align_frames(41), 56);
751 assert_eq!(align_frames(124), 124);
752 assert_eq!(video_latent_t(124), 37);
753 assert_eq!(video_latent_t(39), 12);
754 let (f, lt, at) = temporal_shape(124);
755 assert_eq!((f, lt, at), (124, 37, 207));
756 }
757}