Skip to main content

cortiq_engine/
s2vgen.rs

1//! Kandinsky S2V: reference frame + speech track → avatar video.
2//!
3//! The pipeline of `KandinskyS2VDistilledAutoBlocks`: Thinker text and audio
4//! features plus CLIP's pooled embedding → the reference frame through the VAE
5//! encoder → per chunk, fresh noise, 16 pi-Flow segments over the DiT, the
6//! chunk's tail rolled into FramePack memory → the temporally tiled VAE
7//! decoder, the chunks joined and cut to the length of the track.
8//!
9//! pi-Flow (the distilled head): one forward predicts `n_grid` x0 values across
10//! a segment of raw time and the ODE is integrated across that segment with no
11//! further network evaluations, so one segment costs one forward.
12
13use crate::ltxvae::Vol;
14use crate::s2v::{S2vConfig, S2vDit, S2vGeom, S2vInput};
15use crate::s2v_enc::{ClipText, OmniAudio, OmniText, omni_mel};
16use crate::s2v_vae::{S2vVae, S2vVaeEncoder, SCALING_FACTOR, TEMPORAL};
17use crate::tokenizer::Tokenizer;
18use cortiq_core::CmfModel;
19use std::path::Path;
20use std::sync::Arc;
21use std::time::Instant;
22
23pub use crate::s2v::ARCH_NAME;
24
25pub const SAMPLE_RATE: usize = 16000;
26pub const AUDIO_TOKENS_PER_SECOND: usize = 25;
27
28/// The recipe stored in the container (`s2v.config_json`).
29#[derive(Clone, Debug)]
30pub struct S2vDefaults {
31    pub steps: usize,
32    pub fps: usize,
33    pub latent_frames: usize,
34    pub seed: u64,
35    pub buckets: Vec<(usize, usize)>,
36    pub scale_factor: [f32; 3],
37    pub prompt: String,
38    pub system_prompt: String,
39    pub shift: f32,
40    pub n_grid: usize,
41    pub eps: f32,
42    pub final_scale: f32,
43    pub substeps: usize,
44}
45
46impl S2vDefaults {
47    pub fn of(model: &CmfModel) -> Result<Self, String> {
48        let v: serde_json::Value = serde_json::from_slice(model.tensor_bytes("s2v.config_json").map_err(|e| e.to_string())?)
49            .map_err(|e| format!("s2v.config_json: {e}"))?;
50        let u = |k: &str, d: u64| v[k].as_u64().unwrap_or(d) as usize;
51        let f = |k: &str, d: f64| v[k].as_f64().unwrap_or(d) as f32;
52        let sf = v["scale_factor"].as_array().ok_or("s2v.config_json: no scale_factor")?;
53        Ok(Self {
54            steps: u("steps", 16),
55            fps: u("fps", 25),
56            latent_frames: u("latent_frames", 32),
57            seed: v["seed"].as_u64().unwrap_or(5),
58            buckets: v["buckets"]
59                .as_array()
60                .ok_or("s2v.config_json: no buckets")?
61                .iter()
62                .filter_map(|b| Some((b[0].as_u64()? as usize, b[1].as_u64()? as usize)))
63                .collect(),
64            scale_factor: [
65                sf[0].as_f64().unwrap_or(1.0) as f32,
66                sf[1].as_f64().unwrap_or(2.0) as f32,
67                sf[2].as_f64().unwrap_or(2.0) as f32,
68            ],
69            prompt: v["prompt"].as_str().unwrap_or("").to_string(),
70            system_prompt: v["system_prompt"].as_str().unwrap_or("").to_string(),
71            shift: f("shift", 10.0),
72            n_grid: u("n_grid", 5),
73            eps: f("eps", 1e-6),
74            final_scale: f("final_step_size_scale", 0.5),
75            substeps: u("num_policy_substeps", 128),
76        })
77    }
78}
79
80/// `(height, width)` of the bucket closest in aspect ratio to the image.
81pub fn select_bucket(buckets: &[(usize, usize)], w: usize, h: usize) -> (usize, usize) {
82    let aspect = w as f64 / h as f64;
83    let mut best = buckets[0];
84    let mut d = f64::MAX;
85    for &b in buckets {
86        let e = (aspect - b.1 as f64 / b.0 as f64).abs();
87        if e < d {
88            d = e;
89            best = b;
90        }
91    }
92    best
93}
94
95fn shift_t(t: f32, shift: f32) -> f32 {
96    shift * t / (1.0 + (shift - 1.0) * t)
97}
98
99/// The segment schedule of `PiflowScheduler.set_timesteps`, walked one segment
100/// at a time in f32, as the sampler the students were trained against does.
101pub struct Piflow {
102    pub shift: f32,
103    pub eps: f32,
104    pub n_grid: usize,
105    pub substeps: usize,
106    pub raw: Vec<f32>,
107    pub segments: Vec<f32>,
108    pub sigmas: Vec<f32>,
109}
110
111impl Piflow {
112    pub fn new(d: &S2vDefaults, steps: usize) -> Self {
113        let base = 1.0f64 / (steps as f64 - (1.0 - d.final_scale as f64));
114        let mut raw = Vec::with_capacity(steps);
115        let mut segments = Vec::with_capacity(steps);
116        let mut r = 1.0f32;
117        for s in 0..steps {
118            let seg = base * if s == steps - 1 { d.final_scale as f64 } else { 1.0 };
119            raw.push(r);
120            segments.push(seg as f32);
121            r = (r - seg as f32).max(d.eps);
122        }
123        let sigmas = raw.iter().map(|&t| shift_t(t, d.shift)).collect();
124        Self { shift: d.shift, eps: d.eps, n_grid: d.n_grid, substeps: d.substeps, raw, segments, sigmas }
125    }
126
127    pub fn timesteps(&self) -> Vec<f32> {
128        self.sigmas.iter().map(|&s| s * 1000.0).collect()
129    }
130
131    /// One segment: `pred` is `[T, H, W, n_grid·C]` grid-major, `x` `[T, H, W, C]`.
132    pub fn step(&self, i: usize, pred: &[f32], x: &mut [f32], c: usize, pool: Option<&crate::pool::Pool>) {
133        let g = self.n_grid;
134        let sigma_src = self.sigmas[i];
135        let unwarp = |s: f32| s / (self.shift + (1.0 - self.shift) * s);
136        let raw_src_p = unwarp(sigma_src);
137        let raw_dst_p = (raw_src_p - self.segments[i]).max(0.0);
138        let seg_p = (raw_src_p - raw_dst_p).max(self.eps);
139        let raw_end = (self.raw[i] - self.segments[i]).max(self.eps);
140        let delta = self.raw[i] - raw_end;
141        let n = ((delta * self.substeps as f32).round() as i64).max(1) as usize;
142        let sub = delta / n as f32;
143        // Every voxel shares the schedule, so each substep is two scalars and
144        // one pair of grid rows: x += (x - x0)·dσ/σ.
145        let mut plan = Vec::with_capacity(n);
146        let (mut raw, mut sigma) = (self.raw[i], sigma_src);
147        for _ in 0..n {
148            let r = unwarp(sigma);
149            let t = ((r - raw_dst_p) / seg_p).clamp(0.0, 1.0) * (g - 1) as f32;
150            let t0 = (t.floor() as i64).clamp(0, g as i64 - 2) as usize;
151            let t1 = t0 + 1;
152            let raw_m = (raw - sub).max(0.0);
153            let sigma_m = shift_t(raw_m, self.shift);
154            plan.push((t0, t1 as f32 - t, t - t0 as f32, sigma.max(self.eps), sigma_m - sigma));
155            raw = raw_m;
156            sigma = sigma_m;
157        }
158        let rows = x.len() / c;
159        let xp = crate::s2v::Rows(x.as_mut_ptr());
160        crate::s2v::pool_rows(pool, rows, &|lo, hi| {
161            let mut x0 = vec![0f32; g];
162            for r in lo..hi {
163                // SAFETY: disjoint rows.
164                let xr = unsafe { xp.at(r * c, c) };
165                let pr = &pred[r * g * c..(r + 1) * g * c];
166                for ch in 0..c {
167                    let x_src = xr[ch];
168                    for (gi, v) in x0.iter_mut().enumerate() {
169                        *v = x_src - sigma_src * pr[gi * c + ch];
170                    }
171                    let mut v = x_src;
172                    for &(t0, a, b, sig, ds) in &plan {
173                        let target = a * x0[t0] + b * x0[t0 + 1];
174                        v += (v - target) / sig * ds;
175                    }
176                    xr[ch] = v;
177                }
178            }
179        });
180    }
181}
182
183/// PIL's BILINEAR `resize` (antialiased triangle filter, 8-bit fixed point),
184/// which `torchvision.transforms.functional.resize` calls on a PIL image.
185pub fn pil_bilinear(src: &[u8], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<u8> {
186    const PREC: i64 = 22;
187    let coeffs = |ins: usize, outs: usize| -> (Vec<(usize, usize)>, Vec<Vec<i64>>) {
188        let scale = ins as f64 / outs as f64;
189        let filterscale = scale.max(1.0);
190        let support = filterscale;
191        let mut bounds = Vec::with_capacity(outs);
192        let mut kk = Vec::with_capacity(outs);
193        for xx in 0..outs {
194            let center = (xx as f64 + 0.5) * scale;
195            let xmin = ((center - support + 0.5).floor() as i64).max(0) as usize;
196            let xmax = ((center + support + 0.5).floor() as i64).min(ins as i64) as usize;
197            let mut w = Vec::with_capacity(xmax - xmin);
198            let mut sum = 0.0;
199            for x in xmin..xmax {
200                let d = (x as f64 - center + 0.5) / filterscale;
201                let v = if d.abs() < 1.0 { 1.0 - d.abs() } else { 0.0 };
202                w.push(v);
203                sum += v;
204            }
205            let fixed: Vec<i64> = w
206                .iter()
207                .map(|v| {
208                    let n = v / sum * (1i64 << PREC) as f64;
209                    (if n < 0.0 { n - 0.5 } else { n + 0.5 }) as i64
210                })
211                .collect();
212            bounds.push((xmin, xmax - xmin));
213            kk.push(fixed);
214        }
215        (bounds, kk)
216    };
217    let clip = |v: i64| ((v >> PREC).clamp(0, 255)) as u8;
218    let round = 1i64 << (PREC - 1);
219    let (bx, kx) = coeffs(sw, dw);
220    let mut mid = vec![0u8; dw * sh * 3];
221    for y in 0..sh {
222        for x in 0..dw {
223            let (x0, n) = bx[x];
224            for c in 0..3 {
225                let mut ss = round;
226                for j in 0..n {
227                    ss += src[(y * sw + x0 + j) * 3 + c] as i64 * kx[x][j];
228                }
229                mid[(y * dw + x) * 3 + c] = clip(ss);
230            }
231        }
232    }
233    let (by, ky) = coeffs(sh, dh);
234    let mut out = vec![0u8; dw * dh * 3];
235    for y in 0..dh {
236        let (y0, n) = by[y];
237        for x in 0..dw * 3 {
238            let mut ss = round;
239            for j in 0..n {
240                ss += mid[(y0 + j) * dw * 3 + x] as i64 * ky[y][j];
241            }
242            out[y * dw * 3 + x] = clip(ss);
243        }
244    }
245    out
246}
247
248/// The reference frame as `[3, 1, H, W]` in [-1, 1]: bilinear to cover the
249/// bucket, then a centered crop.
250pub fn prepare_image(rgb: &[u8], w: usize, h: usize, height: usize, width: usize) -> Vol {
251    let scale = (width as f64 / w as f64).max(height as f64 / h as f64);
252    let (rw, rh) = (
253        ((w as f64 * scale).round_ties_even() as usize),
254        ((h as f64 * scale).round_ties_even() as usize),
255    );
256    let resized = pil_bilinear(rgb, w, h, rw, rh);
257    let top = ((rh - height) as f64 / 2.0).round_ties_even() as usize;
258    let left = ((rw - width) as f64 / 2.0).round_ties_even() as usize;
259    let mut v = Vol::zeros(3, 1, height, width);
260    for c in 0..3 {
261        for r in 0..height {
262            for col in 0..width {
263                let s = resized[((r + top) * rw + col + left) * 3 + c] as f32 / 255.0;
264                v.data[c * height * width + r * width + col] = s * 2.0 - 1.0;
265            }
266        }
267    }
268    v
269}
270
271/// Everything that conditions the DiT, whichever path computes the latents.
272pub struct S2vCond {
273    pub text: Vec<f32>,
274    pub pooled: Vec<f32>,
275    pub audio: Vec<Vec<f32>>,
276    pub reference: Vec<f32>,
277    pub height: usize,
278    pub width: usize,
279}
280
281/// The chat string of `encode_qwen_omni`, cut before the audio.
282pub fn prompt_ids(tok: &Tokenizer, system: &str, prompt: &str) -> (Vec<u32>, usize) {
283    let head = format!("<|im_start|>system\n{system}<|im_end|>\n<|im_start|>user\n");
284    let head_ids = tok.encode(&head);
285    let body = tok.encode(prompt);
286    let start = head_ids.len();
287    let mut ids = head_ids;
288    ids.extend(body);
289    (ids, start)
290}
291
292/// `FramePack` memory: zero for the first chunk, `[1×, 2×, 4×]` order.
293pub fn init_memory(cfg: &S2vConfig, lh: usize, lw: usize) -> [Vec<f32>; 3] {
294    let c = cfg.in_visual;
295    let dim = |m: usize| (lh - lh % m, lw - lw % m);
296    let b = cfg.frame_buckets;
297    let (h1, w1) = dim(2);
298    let (h2, w2) = dim(4);
299    let (h4, w4) = dim(8);
300    [
301        vec![0f32; b[0] * h1 * w1 * c],
302        vec![0f32; b[1] * h2 * w2 * c],
303        vec![0f32; b[2] * h4 * w4 * c],
304    ]
305}
306
307/// The tail of a chunk becomes the next chunk's memory: newest two frames at
308/// 1×, the four before them at 2×, the 24 before those at 4×.
309pub fn roll_memory(cfg: &S2vConfig, g: &S2vGeom, x: &[f32]) -> [Vec<f32>; 3] {
310    let c = cfg.in_visual;
311    let b = cfg.frame_buckets;
312    let t = g.lt;
313    let mut off = 0usize;
314    let mut out: [Vec<f32>; 3] = Default::default();
315    for (i, slot) in out.iter_mut().enumerate() {
316        let m = 2usize << i;
317        let (hh, ww) = (g.lh - g.lh % m, g.lw - g.lw % m);
318        let (a, e) = (t - off - b[i], t - off);
319        let mut v = Vec::with_capacity((e - a) * hh * ww * c);
320        for f in a..e {
321            for r in 0..hh {
322                let s = ((f * g.lh + r) * g.lw) * c;
323                v.extend_from_slice(&x[s..s + ww * c]);
324            }
325        }
326        *slot = v;
327        off += b[i];
328    }
329    out
330}
331
332/// A progress line, stage + counters.
333pub type Progress<'a> = &'a mut dyn FnMut(&str, usize, usize);
334
335pub struct S2vParams {
336    pub height: Option<usize>,
337    pub width: Option<usize>,
338    pub steps: Option<usize>,
339    pub chunks: Option<usize>,
340    pub seed: u64,
341    pub prompt: Option<String>,
342    /// Raw f32 reference posterior noise and per-chunk noise, parity work only.
343    pub oracle_noise: Option<(Vec<f32>, Vec<Vec<f32>>)>,
344    /// Fix the conditioning to oracle tensors (text, audio, pooled), parity only.
345    pub oracle_cond: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,
346    pub max_steps: Option<usize>,
347}
348
349pub struct S2vOutput {
350    /// `[3, F, H, W]` in [-1, 1], trimmed to the track.
351    pub frames: Vol,
352    pub fps: usize,
353    pub latents: Vec<Vec<f32>>,
354    pub lt: usize,
355    pub lh: usize,
356    pub lw: usize,
357}
358
359struct SplitMix(crate::ltxpipe::Rng);
360impl SplitMix {
361    fn normal_vec(&mut self, n: usize) -> Vec<f32> {
362        let mut v = vec![0f32; n];
363        self.0.fill_normal(&mut v);
364        v
365    }
366}
367
368/// Read a speech track as mono 16 kHz: WAV here, anything else through ffmpeg.
369pub fn load_speech(path: &Path) -> Result<Vec<f32>, String> {
370    crate::egemma2_audio::read_audio(path)
371}
372
373/// `reference` latent `[H, W, C]` from the posterior: mean + std·ε, scaled.
374pub fn reference_latent(mean: &Vol, logvar: &Vol, eps: &[f32]) -> Vec<f32> {
375    let (h, w, c) = (mean.h, mean.w, mean.c);
376    let mut out = vec![0f32; h * w * c];
377    for ch in 0..c {
378        for p in 0..h * w {
379            let m = mean.data[ch * h * w + p];
380            let s = (0.5 * logvar.data[ch * h * w + p]).exp();
381            out[p * c + ch] = (m + s * eps[ch * h * w + p]) * SCALING_FACTOR;
382        }
383    }
384    out
385}
386
387/// `[T, H, W, C]` latents → `[C, T, H, W]`, unscaled, for the decoder.
388pub fn to_vol(x: &[f32], t: usize, h: usize, w: usize, c: usize) -> Vol {
389    let mut v = Vol::zeros(c, t, h, w);
390    let n = t * h * w;
391    for p in 0..n {
392        for ch in 0..c {
393            v.data[ch * n + p] = x[p * c + ch] / SCALING_FACTOR;
394        }
395    }
396    v
397}
398
399/// Thinker hidden states of the user's text and CLIP's pooled embedding.
400pub fn encode_prompt(model: &Arc<CmfModel>, d: &S2vDefaults, prompt: &str) -> Result<(Vec<f32>, Vec<f32>), String> {
401    let vocab = model.vocab.as_deref().ok_or("S2V .cmf has no embedded tokenizer")?;
402    let tok = Tokenizer::from_bytes(vocab).map_err(|e| format!("tokenizer: {e}"))?;
403    let (ids, start) = prompt_ids(&tok, &d.system_prompt, prompt);
404    let text = {
405        let te = OmniText::from_cmf(model)?;
406        let h = te.encode(&ids);
407        h[start * te.hidden..].to_vec()
408    };
409    let clip_vocab = model.tensor_bytes("clip.tokenizer_json").map_err(|e| e.to_string())?;
410    let clip_tok = Tokenizer::from_bytes(clip_vocab).map_err(|e| format!("clip tokenizer: {e}"))?;
411    let ct = ClipText::from_cmf(model)?;
412    let mut cids = clip_tok.encode(prompt);
413    const BOS: u32 = 49406;
414    const EOS: u32 = 49407;
415    if cids.first() != Some(&BOS) {
416        cids.insert(0, BOS);
417    }
418    cids.truncate(76);
419    cids.push(EOS);
420    cids.resize(77, EOS);
421    Ok((text, ct.pooled(&cids, EOS)))
422}
423
424/// Text, speech and reference latent. Each model loads and is dropped.
425pub fn encode_conditions(
426    model: &Arc<CmfModel>,
427    d: &S2vDefaults,
428    image: &crate::media::RgbFrame,
429    wav: &[f32],
430    chunks: usize,
431    p: &S2vParams,
432    rng_eps: &mut dyn FnMut(usize) -> Vec<f32>,
433    progress: Progress<'_>,
434) -> Result<S2vCond, String> {
435    let chunk_seconds = ((d.latent_frames - 1) * TEMPORAL + 1) as f64 / d.fps as f64;
436    let target = chunks as f64 * chunk_seconds;
437    let samples = (target * SAMPLE_RATE as f64).round() as usize;
438    let mut speech = wav.to_vec();
439    speech.resize(samples, 0.0);
440
441    let (text, audio, pooled) = if let Some((t, a, po)) = &p.oracle_cond {
442        (t.clone(), a.clone(), po.clone())
443    } else {
444        let t0 = Instant::now();
445        progress("audio tower", 0, 1);
446        let (mel, frames) = omni_mel(&speech);
447        let audio = {
448            let at = OmniAudio::from_cmf(model)?;
449            at.features(&mel, frames)
450        };
451        prof("audio", t0);
452        let t0 = Instant::now();
453        // The canned prompt's conditions are in the file; the 7B Thinker is only
454        // opened for another prompt.
455        let canned = model.tensor("s2v.default_text").is_some() && p.prompt.as_ref().is_none_or(|q| *q == d.prompt);
456        let (text, pooled) = if canned {
457            (crate::dit::cmf_f32(model, "s2v.default_text")?, crate::dit::cmf_f32(model, "s2v.default_pooled")?)
458        } else {
459            progress("text encoder", 0, 1);
460            encode_prompt(model, d, p.prompt.as_deref().unwrap_or(&d.prompt))?
461        };
462        prof("prompt", t0);
463        (text, audio, pooled)
464    };
465    let tokens = audio.len() / 3584;
466    if tokens < (target * AUDIO_TOKENS_PER_SECOND as f64 * 0.95) as usize {
467        return Err(format!("the speech encoder returned {tokens} tokens for {target:.1} s"));
468    }
469    let per = tokens / chunks;
470    let audio_chunks: Vec<Vec<f32>> = (0..chunks).map(|k| audio[k * per * 3584..(k + 1) * per * 3584].to_vec()).collect();
471
472    let (height, width) = match (p.height, p.width) {
473        (Some(h), Some(w)) => (h, w),
474        _ => select_bucket(&d.buckets, image.width, image.height),
475    };
476    let t0 = Instant::now();
477    progress("reference frame", 0, 1);
478    let img = prepare_image(&image.data, image.width, image.height, height, width);
479    let (mean, logvar) = {
480        let enc = S2vVaeEncoder::from_cmf(model)?;
481        crate::gpu::s2v_vae_encode(&enc, &img).unwrap_or_else(|| enc.encode(&img))
482    };
483    prof("vae encode", t0);
484    let eps = rng_eps(mean.data.len());
485    Ok(S2vCond {
486        text,
487        pooled,
488        audio: audio_chunks,
489        reference: reference_latent(&mean, &logvar, &eps),
490        height,
491        width,
492    })
493}
494
495pub(crate) fn prof(what: &str, t0: Instant) {
496    if std::env::var("CMF_S2V_PROF").is_ok() {
497        eprintln!("s2v {what}: {:.2} s", t0.elapsed().as_secs_f64());
498    }
499}
500
501/// One whole render.
502pub fn generate(
503    model_path: &Path,
504    image: &crate::media::RgbFrame,
505    wav: &[f32],
506    p: &S2vParams,
507    mut progress: Progress<'_>,
508) -> Result<S2vOutput, String> {
509    let model = Arc::new(CmfModel::open_sharded(model_path).map_err(|e| e.to_string())?);
510    if model.header.arch.arch_name != ARCH_NAME {
511        return Err(format!(
512            "{}: architecture '{}' is not {ARCH_NAME}",
513            model_path.display(),
514            model.header.arch.arch_name
515        ));
516    }
517    let d = S2vDefaults::of(&model)?;
518    let chunk_seconds = ((d.latent_frames - 1) * TEMPORAL + 1) as f64 / d.fps as f64;
519    let track = wav.len() as f64 / SAMPLE_RATE as f64;
520    let chunks = p.chunks.unwrap_or_else(|| (track / chunk_seconds).ceil().max(1.0) as usize);
521    let target = chunks as f64 * chunk_seconds;
522    if target > 300.0 + 0.01 {
523        return Err(format!("{chunks} chunks need {target} s of speech, the encoder truncates at 300 s"));
524    }
525    let mut rng = SplitMix(crate::ltxpipe::Rng::new(p.seed));
526    let oracle = p.oracle_noise.as_ref();
527    let cond = {
528        let mut eps = |n: usize| -> Vec<f32> {
529            match oracle {
530                Some((e, _)) => e.clone(),
531                None => rng.normal_vec(n),
532            }
533        };
534        encode_conditions(&model, &d, image, wav, chunks, p, &mut eps, &mut progress)?
535    };
536    let (lh, lw) = (cond.height / 8, cond.width / 8);
537    let lt = d.latent_frames;
538    let steps = p.steps.unwrap_or(d.steps);
539    let flow = Piflow::new(&d, steps);
540    let ts = flow.timesteps();
541    let t_load = Instant::now();
542    let dit = S2vDit::from_cmf(&model)?;
543    prof("dit load", t_load);
544    let cfg = dit.cfg.clone();
545    let g = S2vGeom::new(&cfg, lt, lh, lw);
546    let c = cfg.in_visual;
547    let mut memory = init_memory(&cfg, lh, lw);
548    let mut latents = Vec::with_capacity(chunks);
549    let reference = cond.reference.clone();
550    let mut dev = crate::gpu::s2v_prepare(&dit, &g, &cond, &ts, d.scale_factor);
551    for k in 0..chunks {
552        let mut x = match oracle {
553            Some((_, n)) => n[k].clone(),
554            None => rng.normal_vec(lt * lh * lw * c),
555        };
556        for (i, &t) in ts.iter().enumerate() {
557            if p.max_steps.is_some_and(|m| i >= m) {
558                break;
559            }
560            let t0 = Instant::now();
561            let pred = match dev.as_mut() {
562                Some(dv) => dv.step(i, k, &x, &memory)?,
563                None => dit.forward(
564                    &S2vInput {
565                        x: &x,
566                        reference: &reference,
567                        mem1: &memory[0],
568                        mem2: &memory[1],
569                        mem4: &memory[2],
570                        t,
571                        text_feats: &cond.text,
572                        audio_feats: &cond.audio[k],
573                        pooled: &cond.pooled,
574                        geom: g,
575                        scale_factor: d.scale_factor,
576                    },
577                    None,
578                )?,
579            };
580            flow.step(i, &pred, &mut x, c, dit.pool());
581            progress("step", i + 1, steps);
582            prof(&format!("chunk {k} step {i}"), t0);
583        }
584        if k + 1 < chunks {
585            memory = roll_memory(&cfg, &g, &x);
586        }
587        latents.push(x);
588    }
589    drop(dev);
590    drop(dit);
591    crate::gpu::s2v_release();
592
593    let t0 = Instant::now();
594    progress("vae decode", 0, chunks);
595    let vae = S2vVae::from_cmf(&model)?;
596    let frames_per = (lt - 1) * TEMPORAL + 1;
597    let keep = ((track * d.fps as f64) as usize).min(chunks * frames_per);
598    let px = (cond.height, cond.width);
599    let mut out = Vol::zeros(3, keep, px.0, px.1);
600    let per = px.0 * px.1;
601    let mut done = 0usize;
602    for (k, lat) in latents.iter().enumerate() {
603        let z = to_vol(lat, lt, lh, lw, c);
604        let dec = crate::gpu::s2v_vae_decode(&vae, &z).unwrap_or_else(|| vae.decode(&z));
605        let take = dec.f.min(keep - done);
606        for ch in 0..3 {
607            let src = &dec.data[ch * dec.f * per..ch * dec.f * per + take * per];
608            out.data[ch * keep * per + done * per..ch * keep * per + (done + take) * per].copy_from_slice(src);
609        }
610        done += take;
611        progress("vae decode", k + 1, chunks);
612    }
613    prof("vae decode", t0);
614    Ok(S2vOutput { frames: out, fps: d.fps, latents, lt, lh, lw })
615}
616
617#[cfg(test)]
618mod tests {
619    use super::*;
620
621    fn defaults() -> S2vDefaults {
622        S2vDefaults {
623            steps: 16,
624            fps: 25,
625            latent_frames: 32,
626            seed: 5,
627            buckets: vec![(512, 512), (768, 512), (512, 768)],
628            scale_factor: [1.0, 2.0, 2.0],
629            prompt: String::new(),
630            system_prompt: String::new(),
631            shift: 10.0,
632            n_grid: 5,
633            eps: 1e-6,
634            final_scale: 0.5,
635            substeps: 128,
636        }
637    }
638
639    #[test]
640    fn piflow_schedule_matches_the_reference() {
641        let f = Piflow::new(&defaults(), 16);
642        let t = f.timesteps();
643        assert_eq!(t.len(), 16);
644        // `PiflowScheduler.set_timesteps(16)` of diffusers.
645        assert!((t[0] - 1000.0).abs() < 1e-3);
646        assert!((t[1] - 993.1507).abs() < 1e-2);
647        assert!((t[2] - 985.4014).abs() < 1e-2);
648        assert!((t[15] - 250.0).abs() < 2e-1);
649    }
650
651    #[test]
652    fn piflow_step_on_a_constant_grid_lands_on_the_constant() {
653        // Every grid point predicts x0 = 0, so u = x/σ and the rollout scales x by σ_dst/σ_src.
654        let d = defaults();
655        let f = Piflow::new(&d, 16);
656        let sigma = f.sigmas[0];
657        let mut x = vec![2.0f32; 16];
658        let pred = vec![2.0 / sigma; 16 * 5];
659        f.step(0, &pred, &mut x, 16, None);
660        let want = 2.0 * f.sigmas[1] / sigma;
661        assert!(x.iter().all(|v| (v - want).abs() < 1e-3), "{} vs {want}", x[0]);
662    }
663
664    #[test]
665    fn bucket_follows_the_aspect_ratio() {
666        let b = defaults().buckets;
667        assert_eq!(select_bucket(&b, 960, 960), (512, 512));
668        assert_eq!(select_bucket(&b, 960, 1431), (768, 512));
669        assert_eq!(select_bucket(&b, 1431, 960), (512, 768));
670    }
671
672    #[test]
673    fn pil_bilinear_keeps_a_flat_image() {
674        let src = vec![90u8; 8 * 6 * 3];
675        let out = pil_bilinear(&src, 8, 6, 4, 3);
676        assert_eq!(out.len(), 4 * 3 * 3);
677        assert!(out.iter().all(|&v| v == 90));
678    }
679
680    #[test]
681    fn memory_rolls_the_newest_frames_to_the_finest_scale() {
682        let v: serde_json::Value = serde_json::json!({
683            "in_visual_dim": 1, "out_visual_dim": 5, "in_text_dim": 8, "in_text_dim2": 8, "in_audio_dim": 8,
684            "time_dim": 8, "patch_size": [1, 2, 2], "frame_buckets": [2, 4, 24], "index_rope_ref_image": 40,
685            "model_dim": 128, "ff_dim": 256, "num_text_blocks": 1, "num_audio_blocks": 1, "num_visual_blocks": 1,
686            "axes_dims": [32, 48, 48], "audio_inject_layers": []
687        });
688        let cfg = S2vConfig::from_json(&v).unwrap();
689        let g = S2vGeom::new(&cfg, 32, 8, 8);
690        // One value per frame.
691        let mut x = vec![0f32; 32 * 8 * 8];
692        for f in 0..32 {
693            x[f * 64..(f + 1) * 64].fill(f as f32);
694        }
695        let m = roll_memory(&cfg, &g, &x);
696        assert_eq!(m[0].len(), 2 * 64);
697        assert_eq!(m[0][0], 30.0);
698        assert_eq!(m[1][0], 26.0);
699        assert_eq!(m[2][0], 2.0);
700        assert_eq!(g.total(), g.n4 + g.n2 + g.n1 + g.nref + g.nvis);
701        let (c, _) = crate::s2v::rope_visual(&cfg, &g, [1.0, 2.0, 2.0]);
702        assert_eq!(c.len(), g.total() * crate::s2v::ROPE_PAIRS);
703    }
704
705    #[test]
706    fn speech_groups_cover_the_tokens_once() {
707        let g = crate::s2v::audio_groups(125, 32);
708        assert_eq!(g.len(), 32);
709        assert_eq!(g[0], (0, 1));
710        assert_eq!(g.iter().map(|x| x.1).sum::<usize>(), 125);
711        assert_eq!(g[31].0 + g[31].1, 125);
712    }
713}