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 refs: Vec<(Vec<f32>, usize, usize)>,
57 pub lora: Option<String>,
59 pub lora_strength: f32,
60 pub upscale: Option<String>,
65 pub upscale_by: f32,
66 pub stream_chunk: usize,
73 pub stream_sink: usize,
74 pub stream_window: usize,
75}
76
77const VISION_START: u32 = 151_652;
79const VISION_END: u32 = 151_653;
80
81pub 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 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
158pub 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
170pub 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
188pub 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
195pub 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
210pub 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
231pub 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 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
260pub(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 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 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 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 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 keyframes.sort_by_key(|(_, i)| *i);
401 keyframes.dedup_by_key(|(_, i)| *i);
402 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 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 let mut ref_sizes: Vec<(usize, usize)> = Vec::new();
417
418 if !pictures.is_empty() {
419 let tower = VisionTower::from_cmf(&model)?;
420 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 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 ids.push(VISION_START);
462 tags.push(0);
463 let start = ids.len();
464 for _ in 0..n_img {
465 ids.push(VISION_START); 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 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); tags.push(1);
497 }
498 ids.truncate(picture_rows + p.max_tokens);
499 tags.truncate(ids.len());
500 lap(&mut marks, "prepare");
501 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 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 if std::env::var("CMF_TE_ONLY").as_deref() == Ok("1") {
533 return Err("CMF_TE_ONLY: encode dumped, render skipped".into());
534 }
535 {
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 crate::gpu::stage_done(&model);
553
554 let (mut video, audio) = {
556 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 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 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 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 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 if p.stream_chunk > 0 && cond.is_empty() {
662 let hw = lat_h * lat_w / 4 * 4; let _ = hw;
664 let vc = dit.latents_dim;
665 let ac = dit.audio_dim;
666 let vframe = lat_h * lat_w; 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 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 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 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; 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 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 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 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 crate::gpu::stage_done(&model);
881
882 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 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 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 #[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 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 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 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 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 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 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 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}