Skip to main content

cortiq_engine/
ltxdit.rs

1//! LTX-2.5 `AVTransformer3DModel` — the audio-video diffusion transformer,
2//! read straight from an `ltx-2.5-av` CMF container.
3//!
4//! One forward is one denoising step for both streams at once: 48 blocks
5//! that each run video self-attention, video↔prompt cross-attention,
6//! audio self-attention, audio↔prompt cross-attention and the two
7//! directions of audio↔video cross-attention, every one of them modulated
8//! by adaLN values that come from the timestep — per token, not per sample.
9//!
10//! What the reference does and this reproduces:
11//!
12//! * **adaLN-single**: a sinusoidal timestep embedding (256) → SiLU MLP →
13//!   one `[9·dim]` vector per distinct timestep, added to the block's own
14//!   `scale_shift_table`. Rows 0..3 modulate self-attention, 3..6 the
15//!   feed-forward, 6..9 the prompt cross-attention.
16//! * **ada-zero**: `rms_norm(x) · (1 + scale) + shift`, no learned weight.
17//! * **post-SA**: `x + y·gate`, then a second `rms_norm` whose output is
18//!   what cross-attention reads — the block never normalizes twice.
19//! * **Split RoPE** over three video axes (frame, row, column) and one
20//!   audio axis, evaluated at the *middle* of each patch's `[start, end)`
21//!   bounds, with the frequency ladder built in f64 (the checkpoint's
22//!   `frequencies_precision: float64`).
23//! * **Gated attention**: `2·sigmoid(to_gate_logits(x))`, per head.
24//! * **q/k RMS-norm across the whole inner dimension**, not per head.
25//! * The A↔V pair reads the *pre-fusion* state of both streams, so the
26//!   order the two directions run in cannot bias the result.
27//!
28//! Gated against reference forward-hook dumps by `cortiq ltx-dit`.
29
30use crate::dit::{Proj, cmf_f32};
31use crate::pool::Pool;
32use cortiq_core::CmfModel;
33use std::sync::Arc;
34
35const EPS: f64 = 1e-6;
36
37// ---------------------------------------------------------------- helpers
38
39/// Rows of `n` items split across pool workers (serial without a pool).
40pub(crate) fn rows(pool: Option<&Pool>, n: usize, f: &(dyn Fn(usize, usize) + Sync)) {
41    match pool {
42        Some(p) => p.run_rows(n, f),
43        None => f(0, n),
44    }
45}
46
47/// Row handout for pool workers over one flat buffer.
48pub(crate) struct Shared(pub(crate) *mut f32);
49unsafe impl Send for Shared {}
50unsafe impl Sync for Shared {}
51impl Shared {
52    /// SAFETY: callers take disjoint `[off, off+len)` ranges.
53    #[allow(clippy::mut_from_ref)]
54    pub(crate) unsafe fn at(&self, off: usize, len: usize) -> &mut [f32] {
55        unsafe { std::slice::from_raw_parts_mut(self.0.add(off), len) }
56    }
57}
58
59/// RMS normalization with no learned weight (`ada_zero`, `post_sa`).
60pub(crate) fn rms_plain(x: &[f32], dst: &mut [f32]) {
61    let ss = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
62    let inv = 1.0 / (ss + EPS).sqrt();
63    for (d, &v) in dst.iter_mut().zip(x) {
64        *d = (v as f64 * inv) as f32;
65    }
66}
67
68/// RMS normalization with a learned weight (q/k-norm).
69fn rms_w(x: &mut [f32], w: &[f32]) {
70    let ss = x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64;
71    let inv = 1.0 / (ss + EPS).sqrt();
72    for (v, &g) in x.iter_mut().zip(w) {
73        *v = (*v as f64 * inv) as f32 * g;
74    }
75}
76
77fn silu(v: f32) -> f32 {
78    v / (1.0 + (-v).exp())
79}
80
81/// `gelu(x, approximate="tanh")`, the feed-forward's projection activation.
82pub(crate) fn gelu_tanh(v: f32) -> f32 {
83    let x = v as f64;
84    let inner = (2.0f64 / std::f64::consts::PI).sqrt() * (x + 0.044715 * x * x * x);
85    (0.5 * x * (1.0 + inner.tanh())) as f32
86}
87
88pub(crate) fn softmax(row: &mut [f32]) {
89    let mx = row.iter().cloned().fold(f32::MIN, f32::max);
90    let mut den = 0f32;
91    for r in row.iter_mut() {
92        *r = (*r - mx).exp();
93        den += *r;
94    }
95    if den > 0.0 {
96        let inv = 1.0 / den;
97        for r in row.iter_mut() {
98            *r *= inv;
99        }
100    }
101}
102
103/// LayerNorm with no affine — the output head's only normalization.
104fn layer_norm(x: &[f32], dst: &mut [f32]) {
105    let n = x.len() as f64;
106    let mean = x.iter().map(|&v| v as f64).sum::<f64>() / n;
107    let var = x.iter().map(|&v| (v as f64 - mean) * (v as f64 - mean)).sum::<f64>() / n;
108    let inv = 1.0 / (var + EPS).sqrt();
109    for (d, &v) in dst.iter_mut().zip(x) {
110        *d = ((v as f64 - mean) * inv) as f32;
111    }
112}
113
114// ---------------------------------------------------------------- linear
115
116/// `y = x·Wᵀ + b`, the weight read in place when the container quantized it.
117pub(crate) struct Lin {
118    w: Proj,
119    b: Option<Vec<f32>>,
120}
121
122impl Lin {
123    pub(crate) fn load(model: &Arc<CmfModel>, name: &str, bias: bool) -> Result<Lin, String> {
124        let w = Proj::from_model(model, &format!("{name}.weight"))?;
125        let b = if bias {
126            Some(cmf_f32(model, &format!("{name}.bias"))?)
127        } else {
128            None
129        };
130        Ok(Lin { w, b })
131    }
132
133    pub(crate) fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
134        let m = self.w.rows();
135        let cols = self.w.cols();
136        let mut out = vec![0f32; n * m];
137        // A GPU binding is capped near 2 GiB, and the prompt encoder's
138        // aggregate projection reads 188160 numbers per token — 1024 of them
139        // at once is past the cap. Chunk the batch so no single dispatch
140        // binds more than a quarter of a gigabyte of activations.
141        let per_row = cols * 4;
142        let chunk = (0x1000_0000usize / per_row.max(1)).max(1);
143        let mut done = 0usize;
144        while done < n {
145            let take = chunk.min(n - done);
146            self.w.matmat(
147                &x[done * cols..(done + take) * cols],
148                take,
149                &mut out[done * m..(done + take) * m],
150                pool,
151            );
152            done += take;
153        }
154        if let Some(b) = &self.b {
155            let dst = Shared(out.as_mut_ptr());
156            rows(pool, n, &|s, e| {
157                let r = unsafe { dst.at(s * m, (e - s) * m) };
158                for row in r.chunks_exact_mut(m) {
159                    for (v, &bb) in row.iter_mut().zip(b) {
160                        *v += bb;
161                    }
162                }
163            });
164        }
165        out
166    }
167}
168
169// ------------------------------------------------------------------ rope
170
171/// Split-RoPE tables: `cos`/`sin` laid out as `[tokens, heads·dh/2]`.
172pub struct Rope {
173    cos: Vec<f32>,
174    sin: Vec<f32>,
175    heads: usize,
176    half: usize,
177}
178
179impl Rope {
180    /// `positions[t][d]` are patch midpoints and `max_pos[d]` the axis
181    /// extent they are divided by. `dim` is the *inner* dimension
182    /// (heads·dh) the frequency ladder is sized from.
183    pub fn build(positions: &[Vec<f64>], max_pos: &[f64], dim: usize, heads: usize, theta: f64) -> Rope {
184        let ndim = max_pos.len();
185        let count = dim / (2 * ndim);
186        // indices = theta^linspace(0, 1, count) · π/2, in f64
187        let idx: Vec<f64> = (0..count)
188            .map(|j| {
189                let e = if count > 1 { j as f64 / (count - 1) as f64 } else { 0.0 };
190                theta.powf(e) * std::f64::consts::PI / 2.0
191            })
192            .collect();
193        let n = positions.len();
194        let half = dim / 2;
195        let pad = half - count * ndim;
196        let mut cos = vec![0f32; n * half];
197        let mut sin = vec![0f32; n * half];
198        for (t, p) in positions.iter().enumerate() {
199            let base = t * half;
200            for i in 0..pad {
201                cos[base + i] = 1.0;
202            }
203            for (j, &ind) in idx.iter().enumerate() {
204                for (d, &mp) in max_pos.iter().enumerate() {
205                    let f = ind * (p[d] / mp * 2.0 - 1.0);
206                    let o = base + pad + j * ndim + d;
207                    cos[o] = f.cos() as f32;
208                    sin[o] = f.sin() as f32;
209                }
210            }
211        }
212        Rope { cos, sin, heads, half: half / heads }
213    }
214
215    /// In-place split rotation of one token's `[heads·dh]` projection.
216    fn apply_row(&self, t: usize, row: &mut [f32]) {
217        let dh = self.half * 2;
218        let stride = self.heads * self.half;
219        for h in 0..self.heads {
220            let off = t * stride + h * self.half;
221            let (c, s) = (&self.cos[off..off + self.half], &self.sin[off..off + self.half]);
222            let v = &mut row[h * dh..(h + 1) * dh];
223            for i in 0..self.half {
224                let (a, b) = (v[i], v[i + self.half]);
225                v[i] = a * c[i] - b * s[i];
226                v[i + self.half] = b * c[i] + a * s[i];
227            }
228        }
229    }
230}
231
232// ------------------------------------------------------------- attention
233
234pub(crate) struct Attn {
235    q: Lin,
236    k: Lin,
237    v: Lin,
238    o: Lin,
239    q_norm: Vec<f32>,
240    k_norm: Vec<f32>,
241    gate: Option<Lin>,
242    heads: usize,
243    dh: usize,
244}
245
246impl Attn {
247    pub(crate) fn load(model: &Arc<CmfModel>, p: &str, heads: usize, dh: usize) -> Result<Attn, String> {
248        Ok(Attn {
249            q: Lin::load(model, &format!("{p}.to_q"), true)?,
250            k: Lin::load(model, &format!("{p}.to_k"), true)?,
251            v: Lin::load(model, &format!("{p}.to_v"), true)?,
252            o: Lin::load(model, &format!("{p}.to_out.0"), true)?,
253            q_norm: cmf_f32(model, &format!("{p}.q_norm.weight"))?,
254            k_norm: cmf_f32(model, &format!("{p}.k_norm.weight"))?,
255            gate: match model.tensor(&format!("{p}.to_gate_logits.weight")) {
256                Some(_) => Some(Lin::load(model, &format!("{p}.to_gate_logits"), true)?),
257                None => None,
258            },
259            heads,
260            dh,
261        })
262    }
263
264    /// `x` is `[n, query_dim]`, `ctx` is `[m, context_dim]` (self-attention
265    /// passes the same buffer twice). `mask` is an additive per-key bias.
266    #[allow(clippy::too_many_arguments)]
267    pub(crate) fn forward(
268        &self,
269        x: &[f32],
270        n: usize,
271        ctx: &[f32],
272        m: usize,
273        pe_q: Option<&Rope>,
274        pe_k: Option<&Rope>,
275        mask: Option<&[f32]>,
276        pool: Option<&Pool>,
277    ) -> Vec<f32> {
278        let inner = self.heads * self.dh;
279        let mut q = self.q.apply(x, n, pool);
280        let mut k = self.k.apply(ctx, m, pool);
281        let v = self.v.apply(ctx, m, pool);
282
283        let qn = Shared(q.as_mut_ptr());
284        rows(pool, n, &|s, e| {
285            let r = unsafe { qn.at(s * inner, (e - s) * inner) };
286            for (i, row) in r.chunks_exact_mut(inner).enumerate() {
287                rms_w(row, &self.q_norm);
288                if let Some(pe) = pe_q {
289                    pe.apply_row(s + i, row);
290                }
291            }
292        });
293        let kn = Shared(k.as_mut_ptr());
294        rows(pool, m, &|s, e| {
295            let r = unsafe { kn.at(s * inner, (e - s) * inner) };
296            for (i, row) in r.chunks_exact_mut(inner).enumerate() {
297                rms_w(row, &self.k_norm);
298                if let Some(pe) = pe_k {
299                    pe.apply_row(s + i, row);
300                }
301            }
302        });
303
304        // Per head, both halves of attention are GEMMs: scores are
305        // q·kᵀ and the value product is p·v. Gathering each head into a
306        // contiguous `[tokens, dh]` block costs one copy and buys the
307        // engine's blocked/BLAS/GPU kernels instead of a scalar loop —
308        // this is most of a step's arithmetic.
309        let mut out = vec![0f32; n * inner];
310        let scale = 1.0 / (self.dh as f32).sqrt();
311        let dh = self.dh;
312        let mut qh = vec![0f32; n * dh];
313        let mut kh = vec![0f32; m * dh];
314        let mut vh = vec![0f32; m * dh];
315        let mut sc = vec![0f32; n * m];
316        let mut oh = vec![0f32; n * dh];
317        for h in 0..self.heads {
318            for i in 0..n {
319                qh[i * dh..(i + 1) * dh].copy_from_slice(&q[i * inner + h * dh..][..dh]);
320            }
321            for j in 0..m {
322                kh[j * dh..(j + 1) * dh].copy_from_slice(&k[j * inner + h * dh..][..dh]);
323                vh[j * dh..(j + 1) * dh].copy_from_slice(&v[j * inner + h * dh..][..dh]);
324            }
325            crate::fcd_ops::gemm_nt(&qh, &kh, &mut sc, n, dh, m, pool);
326            let sp = Shared(sc.as_mut_ptr());
327            rows(pool, n, &|s, e| {
328                let r = unsafe { sp.at(s * m, (e - s) * m) };
329                for row in r.chunks_exact_mut(m) {
330                    for (x, j) in row.iter_mut().zip(0..m) {
331                        *x = *x * scale + mask.map_or(0.0, |mk| mk[j]);
332                    }
333                    softmax(row);
334                }
335            });
336            oh.iter_mut().for_each(|x| *x = 0.0);
337            crate::fcd_ops::gemm_dx(&sc, &vh, &mut oh, n, dh, m, pool);
338            for i in 0..n {
339                out[i * inner + h * dh..i * inner + (h + 1) * dh]
340                    .copy_from_slice(&oh[i * dh..(i + 1) * dh]);
341            }
342        }
343
344        if let Some(g) = &self.gate {
345            let logits = g.apply(x, n, pool);
346            let h = self.heads;
347            let dst = Shared(out.as_mut_ptr());
348            rows(pool, n, &|s, e| {
349                let r = unsafe { dst.at(s * inner, (e - s) * inner) };
350                for (i, row) in r.chunks_exact_mut(inner).enumerate() {
351                    for hh in 0..h {
352                        let gate = 2.0 / (1.0 + (-logits[(s + i) * h + hh]).exp());
353                        for d in row[hh * self.dh..(hh + 1) * self.dh].iter_mut() {
354                            *d *= gate;
355                        }
356                    }
357                }
358            });
359        }
360        self.o.apply(&out, n, pool)
361    }
362}
363
364// ---------------------------------------------------------- adaLN single
365
366/// `AdaLayerNormSingle`: sinusoidal timestep → SiLU MLP → `coeff·dim`
367/// modulation values, plus the embedding the output head reuses.
368struct AdaLn {
369    l1: Lin,
370    l2: Lin,
371    lin: Lin,
372    dim: usize,
373}
374
375impl AdaLn {
376    fn load(model: &Arc<CmfModel>, p: &str, dim: usize) -> Result<AdaLn, String> {
377        Ok(AdaLn {
378            l1: Lin::load(model, &format!("{p}.emb.timestep_embedder.linear_1"), true)?,
379            l2: Lin::load(model, &format!("{p}.emb.timestep_embedder.linear_2"), true)?,
380            lin: Lin::load(model, &format!("{p}.linear"), true)?,
381            dim,
382        })
383    }
384
385    /// `(values [n, coeff·dim], embedded [n, dim])` for `n` timesteps.
386    fn forward(&self, t: &[f32], pool: Option<&Pool>) -> (Vec<f32>, Vec<f32>) {
387        let n = t.len();
388        // get_timestep_embedding(256, flip_sin_to_cos=True, shift=0): the
389        // flip puts cosine first, so the halves are [cos, sin].
390        let half = 128usize;
391        let mut proj = vec![0f32; n * 256];
392        let ws: Vec<f64> = (0..half)
393            .map(|j| (-(10000f64).ln() * j as f64 / half as f64).exp())
394            .collect();
395        for (i, &tv) in t.iter().enumerate() {
396            for (j, &w) in ws.iter().enumerate() {
397                let a = tv as f64 * w;
398                proj[i * 256 + j] = a.cos() as f32;
399                proj[i * 256 + half + j] = a.sin() as f32;
400            }
401        }
402        let mut h = self.l1.apply(&proj, n, pool);
403        for v in h.iter_mut() {
404            *v = silu(*v);
405        }
406        let embedded = self.l2.apply(&h, n, pool);
407        let mut act = embedded.clone();
408        for v in act.iter_mut() {
409            *v = silu(*v);
410        }
411        (self.lin.apply(&act, n, pool), embedded)
412    }
413}
414
415/// adaLN values for the *distinct* timesteps of a stream, plus each token's
416/// index into them. Per-token timesteps take only a handful of values here
417/// (a conditioning token sits at 0 while the rest sit at the current
418/// sigma), so the `[36864, 4096]` projection runs a few times, not `T`.
419struct TsTable {
420    vals: Vec<f32>,
421    emb: Vec<f32>,
422    idx: Vec<usize>,
423    width: usize,
424    edim: usize,
425}
426
427impl TsTable {
428    fn build(a: &AdaLn, ts: &[f32], scale: f64, pool: Option<&Pool>) -> TsTable {
429        let mut vals: Vec<f32> = Vec::new();
430        let mut idx = Vec::with_capacity(ts.len());
431        for &t in ts {
432            match vals.iter().position(|&v| v.to_bits() == t.to_bits()) {
433                Some(i) => idx.push(i),
434                None => {
435                    vals.push(t);
436                    idx.push(vals.len() - 1);
437                }
438            }
439        }
440        let scaled: Vec<f32> = vals.iter().map(|&v| (v as f64 * scale) as f32).collect();
441        let (v, e) = a.forward(&scaled, pool);
442        let width = v.len() / scaled.len().max(1);
443        TsTable { vals: v, emb: e, idx, width, edim: a.dim }
444    }
445
446    fn distinct(&self) -> usize {
447        self.vals.len() / self.width.max(1)
448    }
449
450    fn row(&self, r: usize) -> &[f32] {
451        &self.vals[r * self.width..(r + 1) * self.width]
452    }
453
454    fn emb_row(&self, r: usize) -> &[f32] {
455        &self.emb[r * self.edim..(r + 1) * self.edim]
456    }
457
458    /// `(shift, scale, gate)` per distinct timestep for the adaLN triple at
459    /// table row `off`: the block's static table plus the timestep's own
460    /// contribution, summed once instead of once per token.
461    fn triples(&self, table: &[f32], dim: usize, off: usize) -> Vec<[Vec<f32>; 3]> {
462        (0..self.distinct())
463            .map(|r| {
464                let v = self.row(r);
465                std::array::from_fn(|j| {
466                    let o = (off + j) * dim;
467                    (0..dim).map(|d| table[o + d] + v[o + d]).collect()
468                })
469            })
470            .collect()
471    }
472
473    /// `(scale, shift)` per distinct timestep for an A↔V table, which — unlike
474    /// the self-attention rows — comes out scale-first.
475    fn pairs(&self, table: &[f32], dim: usize, off: usize) -> Vec<[Vec<f32>; 2]> {
476        (0..self.distinct())
477            .map(|r| {
478                let v = self.row(r);
479                std::array::from_fn(|j| {
480                    let o = (off + j) * dim;
481                    (0..dim).map(|d| table[o + d] + v[o + d]).collect()
482                })
483            })
484            .collect()
485    }
486}
487
488// ----------------------------------------------------------------- block
489
490struct Stream {
491    attn1: Attn,
492    attn2: Attn,
493    ff_in: Lin,
494    ff_out: Lin,
495    sst: Vec<f32>,        // [9, dim]
496    prompt_sst: Vec<f32>, // [2, dim]
497}
498
499impl Stream {
500    fn load(
501        model: &Arc<CmfModel>,
502        p: &str,
503        prefix: &str,
504        heads: usize,
505        dh: usize,
506        ff_bias: bool,
507    ) -> Result<Stream, String> {
508        let a = |n: &str| format!("{p}.{prefix}{n}");
509        Ok(Stream {
510            attn1: Attn::load(model, &a("attn1"), heads, dh)?,
511            attn2: Attn::load(model, &a("attn2"), heads, dh)?,
512            ff_in: Lin::load(model, &a("ff.net.0.proj"), ff_bias)?,
513            ff_out: Lin::load(model, &a("ff.net.2"), ff_bias)?,
514            sst: cmf_f32(model, &a("scale_shift_table"))?,
515            prompt_sst: cmf_f32(model, &a("prompt_scale_shift_table"))?,
516        })
517    }
518
519    fn ff(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
520        let mut h = self.ff_in.apply(x, n, pool);
521        for v in h.iter_mut() {
522            *v = gelu_tanh(*v);
523        }
524        self.ff_out.apply(&h, n, pool)
525    }
526}
527
528struct Block {
529    video: Stream,
530    audio: Stream,
531    a2v: Attn,
532    v2a: Attn,
533    sst_a2v_video: Vec<f32>, // [5, 4096]
534    sst_a2v_audio: Vec<f32>, // [5, 2048]
535}
536
537// ----------------------------------------------------------------- model
538
539/// One modality's per-step conditioning: everything the blocks read that is
540/// not a weight.
541pub struct StreamInput {
542    /// Patchified latent, `[tokens, in_channels]`.
543    pub latent: Vec<f32>,
544    pub tokens: usize,
545    /// Per-token timestep (the sigma·denoising-mask product).
546    pub timesteps: Vec<f32>,
547    /// Per-token patch midpoints, one entry per RoPE axis.
548    pub positions: Vec<Vec<f64>>,
549    /// Prompt embeddings out of the connector, `[ctx_len, cross_dim]`.
550    pub context: Vec<f32>,
551    pub ctx_len: usize,
552    /// Additive per-key prompt mask, or empty for "attend to all".
553    pub context_mask: Vec<f32>,
554    /// Non-zero for tokens holding a standalone pixel frame (video only).
555    pub keyframes: Vec<f32>,
556    /// This stream's sigma — the *other* stream's fusion gate reads it.
557    pub sigma: f32,
558}
559
560pub struct LtxDit {
561    model: Arc<CmfModel>,
562    blocks: Vec<Block>,
563    patchify: Lin,
564    a_patchify: Lin,
565    keyframes_emb: Option<Vec<f32>>,
566    adaln: AdaLn,
567    a_adaln: AdaLn,
568    prompt_adaln: AdaLn,
569    a_prompt_adaln: AdaLn,
570    av_v_ss: AdaLn,
571    av_a_ss: AdaLn,
572    av_a2v_gate: AdaLn,
573    av_v2a_gate: AdaLn,
574    proj_out: Lin,
575    a_proj_out: Lin,
576    sst_out: Vec<f32>,
577    a_sst_out: Vec<f32>,
578    pub heads: usize,
579    pub dh: usize,
580    pub a_heads: usize,
581    pub a_dh: usize,
582    pub max_pos: Vec<f64>,
583    pub a_max_pos: Vec<f64>,
584    pub cross_max_pos: f64,
585    pub theta: f64,
586    pub t_scale: f64,
587    pub av_t_scale: f64,
588    pub audio_cross_dim: usize,
589}
590
591impl LtxDit {
592    pub fn from_cmf(model: &Arc<CmfModel>) -> Result<LtxDit, String> {
593        let cfg_bytes = ["ltx.config_json", "dit.config_json"]
594            .iter()
595            .find_map(|n| model.tensor(n).map(|e| model.entry_bytes(e)))
596            .ok_or("container carries no ltx.config_json")?;
597        let cfg: serde_json::Value =
598            serde_json::from_slice(cfg_bytes).map_err(|e| format!("ltx.config_json: {e}"))?;
599        let t = cfg.get("transformer").unwrap_or(&cfg).clone();
600        let g = |k: &str, d: f64| t.get(k).and_then(|v| v.as_f64()).unwrap_or(d);
601        let heads = g("num_attention_heads", 32.0) as usize;
602        let dh = g("attention_head_dim", 128.0) as usize;
603        let a_heads = g("audio_num_attention_heads", 32.0) as usize;
604        let a_dh = g("audio_attention_head_dim", 64.0) as usize;
605        let n_layers = g("num_layers", 48.0) as usize;
606        let ff_bias = t.get("ff_bias").and_then(|v| v.as_bool()).unwrap_or(true);
607        let a_ff_bias = t.get("audio_ff_bias").and_then(|v| v.as_bool()).unwrap_or(true);
608        let arr = |k: &str, d: Vec<f64>| -> Vec<f64> {
609            t.get(k)
610                .and_then(|v| v.as_array())
611                .map(|a| a.iter().filter_map(|x| x.as_f64()).collect())
612                .unwrap_or(d)
613        };
614        let max_pos = arr("positional_embedding_max_pos", vec![20.0, 2048.0, 2048.0]);
615        let a_max_pos = arr("audio_positional_embedding_max_pos", vec![20.0]);
616        let cross_max_pos = max_pos[0].max(a_max_pos[0]);
617        let dim = heads * dh;
618        let a_dim = a_heads * a_dh;
619
620        let mut blocks = Vec::with_capacity(n_layers);
621        for i in 0..n_layers {
622            let p = format!("dit.transformer_blocks.{i}");
623            blocks.push(Block {
624                video: Stream::load(model, &p, "", heads, dh, ff_bias)?,
625                audio: Stream::load(model, &p, "audio_", a_heads, a_dh, a_ff_bias)?,
626                a2v: Attn::load(model, &format!("{p}.audio_to_video_attn"), a_heads, a_dh)?,
627                v2a: Attn::load(model, &format!("{p}.video_to_audio_attn"), a_heads, a_dh)?,
628                sst_a2v_video: cmf_f32(model, &format!("{p}.scale_shift_table_a2v_ca_video"))?,
629                sst_a2v_audio: cmf_f32(model, &format!("{p}.scale_shift_table_a2v_ca_audio"))?,
630            });
631        }
632        let _ = (dim, a_dim);
633        Ok(LtxDit {
634            blocks,
635            patchify: Lin::load(model, "dit.patchify_proj", true)?,
636            a_patchify: Lin::load(model, "dit.audio_patchify_proj", true)?,
637            keyframes_emb: match model.tensor("dit.keyframes_abs_pos_embedding") {
638                Some(_) => Some(cmf_f32(model, "dit.keyframes_abs_pos_embedding")?),
639                None => None,
640            },
641            adaln: AdaLn::load(model, "dit.adaln_single", dim)?,
642            a_adaln: AdaLn::load(model, "dit.audio_adaln_single", a_dim)?,
643            prompt_adaln: AdaLn::load(model, "dit.prompt_adaln_single", dim)?,
644            a_prompt_adaln: AdaLn::load(model, "dit.audio_prompt_adaln_single", a_dim)?,
645            av_v_ss: AdaLn::load(model, "dit.av_ca_video_scale_shift_adaln_single", dim)?,
646            av_a_ss: AdaLn::load(model, "dit.av_ca_audio_scale_shift_adaln_single", a_dim)?,
647            av_a2v_gate: AdaLn::load(model, "dit.av_ca_a2v_gate_adaln_single", dim)?,
648            av_v2a_gate: AdaLn::load(model, "dit.av_ca_v2a_gate_adaln_single", a_dim)?,
649            proj_out: Lin::load(model, "dit.proj_out", true)?,
650            a_proj_out: Lin::load(model, "dit.audio_proj_out", true)?,
651            sst_out: cmf_f32(model, "dit.scale_shift_table")?,
652            a_sst_out: cmf_f32(model, "dit.audio_scale_shift_table")?,
653            heads,
654            dh,
655            a_heads,
656            a_dh,
657            max_pos,
658            a_max_pos,
659            cross_max_pos,
660            theta: g("positional_embedding_theta", 10000.0),
661            t_scale: g("timestep_scale_multiplier", 1000.0),
662            av_t_scale: g("av_ca_timestep_scale_multiplier", 1.0),
663            audio_cross_dim: g("audio_cross_attention_dim", 2048.0) as usize,
664            model: model.clone(),
665        })
666    }
667
668    pub fn blocks(&self) -> usize {
669        self.blocks.len()
670    }
671
672    pub fn container(&self) -> &Arc<CmfModel> {
673        &self.model
674    }
675
676    /// One denoising step: `(video velocity [T, C], audio velocity [T, C])`.
677    pub fn forward(
678        &self,
679        video: &StreamInput,
680        audio: &StreamInput,
681        pool: Option<&Pool>,
682    ) -> (Vec<f32>, Vec<f32>) {
683        self.forward_traced(video, audio, pool, &mut |_, _| {})
684    }
685
686    pub fn forward_traced(
687        &self,
688        video: &StreamInput,
689        audio: &StreamInput,
690        pool: Option<&Pool>,
691        trace: &mut dyn FnMut(&str, &[f32]),
692    ) -> (Vec<f32>, Vec<f32>) {
693        let dim = self.heads * self.dh;
694        let a_dim = self.a_heads * self.a_dh;
695        let (n, m) = (video.tokens, audio.tokens);
696
697        // --- patchify -----------------------------------------------------
698        let mut vx = self.patchify.apply(&video.latent, n, pool);
699        if let Some(emb) = &self.keyframes_emb {
700            for i in 0..n {
701                if video.keyframes.get(i).copied().unwrap_or(0.0) > 0.0 {
702                    for (d, &e) in vx[i * dim..(i + 1) * dim].iter_mut().zip(emb) {
703                        *d += e;
704                    }
705                }
706            }
707        }
708        let mut ax = self.a_patchify.apply(&audio.latent, m, pool);
709        trace("v.args.x", &vx);
710        trace("a.args.x", &ax);
711
712        // --- adaLN tables, one row per distinct timestep -------------------
713        let vt = TsTable::build(&self.adaln, &video.timesteps, self.t_scale, pool);
714        let at = TsTable::build(&self.a_adaln, &audio.timesteps, self.t_scale, pool);
715        let vpt = TsTable::build(&self.prompt_adaln, &[video.sigma], self.t_scale, pool);
716        let apt = TsTable::build(&self.a_prompt_adaln, &[audio.sigma], self.t_scale, pool);
717        let vxs = TsTable::build(&self.av_v_ss, &video.timesteps, self.t_scale, pool);
718        let axs = TsTable::build(&self.av_a_ss, &audio.timesteps, self.t_scale, pool);
719        // The fusion gate reads the *other* stream's sigma — the noise level
720        // it is being asked to trust — at the A-V multiplier.
721        let vgt = TsTable::build(&self.av_a2v_gate, &[audio.sigma], self.av_t_scale, pool);
722        let agt = TsTable::build(&self.av_v2a_gate, &[video.sigma], self.av_t_scale, pool);
723
724        // --- RoPE ---------------------------------------------------------
725        let v_pe = Rope::build(&video.positions, &self.max_pos, dim, self.heads, self.theta);
726        let a_pe = Rope::build(&audio.positions, &self.a_max_pos, a_dim, self.a_heads, self.theta);
727        let time_only = |p: &[Vec<f64>]| p.iter().map(|r| vec![r[0]]).collect::<Vec<_>>();
728        let v_xpe = Rope::build(
729            &time_only(&video.positions),
730            &[self.cross_max_pos],
731            self.audio_cross_dim,
732            self.heads,
733            self.theta,
734        );
735        let a_xpe = Rope::build(
736            &time_only(&audio.positions),
737            &[self.cross_max_pos],
738            self.audio_cross_dim,
739            self.a_heads,
740            self.theta,
741        );
742
743        let vmask = (!video.context_mask.is_empty()).then_some(&video.context_mask[..]);
744        let amask = (!audio.context_mask.is_empty()).then_some(&audio.context_mask[..]);
745
746        for (bi, blk) in self.blocks.iter().enumerate() {
747            let v_msa = vt.triples(&blk.video.sst, dim, 0);
748            let v_ca = vt.triples(&blk.video.sst, dim, 6);
749            let v_mlp = vt.triples(&blk.video.sst, dim, 3);
750            let a_msa = at.triples(&blk.audio.sst, a_dim, 0);
751            let a_ca = at.triples(&blk.audio.sst, a_dim, 6);
752            let a_mlp = at.triples(&blk.audio.sst, a_dim, 3);
753
754            // ---- video: self-attention, then prompt cross-attention ----
755            let mut vnorm = vec![0f32; n * dim];
756            for i in 0..n {
757                let md = &v_msa[vt.idx[i]];
758                let dst = &mut vnorm[i * dim..(i + 1) * dim];
759                rms_plain(&vx[i * dim..(i + 1) * dim], dst);
760                for d in 0..dim {
761                    dst[d] = dst[d] * (1.0 + md[1][d]) + md[0][d];
762                }
763            }
764            if bi == 0 {
765                trace("v.b0.sa.in", &vnorm);
766            }
767            let vsa = blk
768                .video
769                .attn1
770                .forward(&vnorm, n, &vnorm, n, Some(&v_pe), Some(&v_pe), None, pool);
771            if bi == 0 {
772                trace("v.b0.sa.out", &vsa);
773            }
774            let mut vnormed = vec![0f32; n * dim];
775            for i in 0..n {
776                let md = &v_msa[vt.idx[i]];
777                for d in 0..dim {
778                    vx[i * dim + d] += vsa[i * dim + d] * md[2][d];
779                }
780                rms_plain(&vx[i * dim..(i + 1) * dim], &mut vnormed[i * dim..(i + 1) * dim]);
781            }
782            let mut vq = vec![0f32; n * dim];
783            for i in 0..n {
784                let md = &v_ca[vt.idx[i]];
785                for d in 0..dim {
786                    vq[i * dim + d] = vnormed[i * dim + d] * (1.0 + md[1][d]) + md[0][d];
787                }
788            }
789            let vctx = modulate_kv(&video.context, video.ctx_len, dim, &blk.video.prompt_sst, vpt.row(0));
790            let vca = blk.video.attn2.forward(&vq, n, &vctx, video.ctx_len, None, None, vmask, pool);
791            if bi == 0 {
792                trace("v.b0.ca.in", &vq);
793                trace("v.b0.ca.ctx", &vctx);
794                trace("v.b0.ca.out", &vca);
795            }
796            for i in 0..n {
797                let md = &v_ca[vt.idx[i]];
798                for d in 0..dim {
799                    vx[i * dim + d] += vca[i * dim + d] * md[2][d];
800                }
801            }
802
803            // ---- audio: the same two steps ----
804            let mut anorm = vec![0f32; m * a_dim];
805            for i in 0..m {
806                let md = &a_msa[at.idx[i]];
807                let dst = &mut anorm[i * a_dim..(i + 1) * a_dim];
808                rms_plain(&ax[i * a_dim..(i + 1) * a_dim], dst);
809                for d in 0..a_dim {
810                    dst[d] = dst[d] * (1.0 + md[1][d]) + md[0][d];
811                }
812            }
813            if bi == 0 {
814                trace("a.b0.sa.in", &anorm);
815            }
816            let asa = blk
817                .audio
818                .attn1
819                .forward(&anorm, m, &anorm, m, Some(&a_pe), Some(&a_pe), None, pool);
820            if bi == 0 {
821                trace("a.b0.sa.out", &asa);
822            }
823            let mut anormed = vec![0f32; m * a_dim];
824            for i in 0..m {
825                let md = &a_msa[at.idx[i]];
826                for d in 0..a_dim {
827                    ax[i * a_dim + d] += asa[i * a_dim + d] * md[2][d];
828                }
829                rms_plain(
830                    &ax[i * a_dim..(i + 1) * a_dim],
831                    &mut anormed[i * a_dim..(i + 1) * a_dim],
832                );
833            }
834            let mut aq = vec![0f32; m * a_dim];
835            for i in 0..m {
836                let md = &a_ca[at.idx[i]];
837                for d in 0..a_dim {
838                    aq[i * a_dim + d] = anormed[i * a_dim + d] * (1.0 + md[1][d]) + md[0][d];
839                }
840            }
841            let actx = modulate_kv(&audio.context, audio.ctx_len, a_dim, &blk.audio.prompt_sst, apt.row(0));
842            let aca = blk.audio.attn2.forward(&aq, m, &actx, audio.ctx_len, None, None, amask, pool);
843            if bi == 0 {
844                trace("a.b0.ca.in", &aq);
845                trace("a.b0.ca.ctx", &actx);
846                trace("a.b0.ca.out", &aca);
847            }
848            for i in 0..m {
849                let md = &a_ca[at.idx[i]];
850                for d in 0..a_dim {
851                    ax[i * a_dim + d] += aca[i * a_dim + d] * md[2][d];
852                }
853            }
854
855            // ---- audio ↔ video, both directions off the pre-fusion state ----
856            let vx_pre = vx.clone();
857            let ax_pre = ax.clone();
858            let a2v_vp = vxs.pairs(&blk.sst_a2v_video, dim, 0);
859            let a2v_ap = axs.pairs(&blk.sst_a2v_audio, a_dim, 0);
860            let a2v_v = ada_pair(&vx_pre, n, dim, &a2v_vp, &vxs.idx);
861            let a2v_a = ada_pair(&ax_pre, m, a_dim, &a2v_ap, &axs.idx);
862            let a2v = blk
863                .a2v
864                .forward(&a2v_v, n, &a2v_a, m, Some(&v_xpe), Some(&a_xpe), None, pool);
865            if bi == 0 {
866                trace("v.b0.a2v.in", &a2v_v);
867                trace("v.b0.a2v.ctx", &a2v_a);
868                trace("v.b0.a2v.out", &a2v);
869            }
870            let gate_a2v = gate_row(&blk.sst_a2v_video, dim, vgt.row(0));
871            for i in 0..n {
872                for d in 0..dim {
873                    vx[i * dim + d] += a2v[i * dim + d] * gate_a2v[d];
874                }
875            }
876            let v2a_ap = axs.pairs(&blk.sst_a2v_audio, a_dim, 2);
877            let v2a_vp = vxs.pairs(&blk.sst_a2v_video, dim, 2);
878            let v2a_a = ada_pair(&ax_pre, m, a_dim, &v2a_ap, &axs.idx);
879            let v2a_v = ada_pair(&vx_pre, n, dim, &v2a_vp, &vxs.idx);
880            let v2a = blk
881                .v2a
882                .forward(&v2a_a, m, &v2a_v, n, Some(&a_xpe), Some(&v_xpe), None, pool);
883            if bi == 0 {
884                trace("a.b0.v2a.in", &v2a_a);
885                trace("a.b0.v2a.ctx", &v2a_v);
886                trace("a.b0.v2a.out", &v2a);
887            }
888            let gate_v2a = gate_row(&blk.sst_a2v_audio, a_dim, agt.row(0));
889            for i in 0..m {
890                for d in 0..a_dim {
891                    ax[i * a_dim + d] += v2a[i * a_dim + d] * gate_v2a[d];
892                }
893            }
894
895            // ---- feed-forward ----
896            let mut vsc = vec![0f32; n * dim];
897            for i in 0..n {
898                let md = &v_mlp[vt.idx[i]];
899                let dst = &mut vsc[i * dim..(i + 1) * dim];
900                rms_plain(&vx[i * dim..(i + 1) * dim], dst);
901                for d in 0..dim {
902                    dst[d] = dst[d] * (1.0 + md[1][d]) + md[0][d];
903                }
904            }
905            let vff = blk.video.ff(&vsc, n, pool);
906            if bi == 0 {
907                trace("v.b0.ff.in", &vsc);
908                trace("v.b0.ff.out", &vff);
909            }
910            for i in 0..n {
911                let md = &v_mlp[vt.idx[i]];
912                for d in 0..dim {
913                    vx[i * dim + d] += vff[i * dim + d] * md[2][d];
914                }
915            }
916            let mut asc = vec![0f32; m * a_dim];
917            for i in 0..m {
918                let md = &a_mlp[at.idx[i]];
919                let dst = &mut asc[i * a_dim..(i + 1) * a_dim];
920                rms_plain(&ax[i * a_dim..(i + 1) * a_dim], dst);
921                for d in 0..a_dim {
922                    dst[d] = dst[d] * (1.0 + md[1][d]) + md[0][d];
923                }
924            }
925            let aff = blk.audio.ff(&asc, m, pool);
926            if bi == 0 {
927                trace("a.b0.ff.in", &asc);
928                trace("a.b0.ff.out", &aff);
929            }
930            for i in 0..m {
931                let md = &a_mlp[at.idx[i]];
932                for d in 0..a_dim {
933                    ax[i * a_dim + d] += aff[i * a_dim + d] * md[2][d];
934                }
935            }
936            trace(&format!("v.block{bi}"), &vx);
937            trace(&format!("a.block{bi}"), &ax);
938        }
939
940        // --- output head: LayerNorm (no affine), adaLN, projection --------
941        let vout = head(&vx, n, dim, &self.sst_out, &vt, &self.proj_out, pool);
942        let aout = head(&ax, m, a_dim, &self.a_sst_out, &at, &self.a_proj_out, pool);
943        trace("v.out", &vout);
944        trace("a.out", &aout);
945        (vout, aout)
946    }
947}
948
949/// `prompt_scale_shift_table` plus the prompt adaLN row, modulating the
950/// cross-attention K/V — the same modulation for every context token.
951fn modulate_kv(ctx: &[f32], len: usize, dim: usize, table: &[f32], extra: &[f32]) -> Vec<f32> {
952    let mut out = vec![0f32; len * dim];
953    let shift: Vec<f32> = (0..dim).map(|d| table[d] + extra[d]).collect();
954    let scale: Vec<f32> = (0..dim).map(|d| table[dim + d] + extra[dim + d]).collect();
955    for i in 0..len {
956        for d in 0..dim {
957            out[i * dim + d] = ctx[i * dim + d] * (1.0 + scale[d]) + shift[d];
958        }
959    }
960    out
961}
962
963/// `ada_zero` with an A↔V `(scale, shift)` pair per distinct timestep.
964fn ada_pair(x: &[f32], n: usize, dim: usize, pairs: &[[Vec<f32>; 2]], idx: &[usize]) -> Vec<f32> {
965    let mut out = vec![0f32; n * dim];
966    for i in 0..n {
967        let p = &pairs[idx[i]];
968        let dst = &mut out[i * dim..(i + 1) * dim];
969        rms_plain(&x[i * dim..(i + 1) * dim], dst);
970        for d in 0..dim {
971            dst[d] = dst[d] * (1.0 + p[0][d]) + p[1][d];
972        }
973    }
974    out
975}
976
977/// The single gate row of an A↔V table — row 4 of `[5, dim]`, plus the
978/// gate adaLN's own output.
979fn gate_row(table: &[f32], dim: usize, extra: &[f32]) -> Vec<f32> {
980    (0..dim).map(|d| table[4 * dim + d] + extra[d]).collect()
981}
982
983/// The output head: LayerNorm without affine, the final scale/shift pair
984/// (both offset by the same embedded timestep), then the projection.
985fn head(
986    x: &[f32],
987    n: usize,
988    dim: usize,
989    sst: &[f32],
990    ts: &TsTable,
991    proj: &Lin,
992    pool: Option<&Pool>,
993) -> Vec<f32> {
994    let mut y = vec![0f32; n * dim];
995    let mut ln = vec![0f32; dim];
996    for i in 0..n {
997        let e = ts.emb_row(ts.idx[i.min(ts.idx.len() - 1)]);
998        layer_norm(&x[i * dim..(i + 1) * dim], &mut ln);
999        for d in 0..dim {
1000            y[i * dim + d] = ln[d] * (1.0 + sst[dim + d] + e[d]) + sst[d] + e[d];
1001        }
1002    }
1003    proj.apply(&y, n, pool)
1004}