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.
82///
83/// In f32 and, where it matters, across the pool. A step puts half a billion
84/// values through this — 672 tokens × 16384 wide × 48 blocks — so computing
85/// it in f64 on one thread was worth several seconds of every step on its
86/// own. The f32 form agrees with the f64 one to ~1e-7 relative, which is far
87/// inside what the 4-bit weights around it carry.
88#[inline]
89pub(crate) fn gelu_tanh(v: f32) -> f32 {
90    const K: f32 = 0.797_884_56; // sqrt(2/pi)
91    0.5 * v * (1.0 + (K * (v + 0.044715 * v * v * v)).tanh())
92}
93
94/// The same activation over a whole buffer, split across the pool.
95pub(crate) fn gelu_tanh_rows(x: &mut [f32], pool: Option<&Pool>) {
96    let dst = Shared(x.as_mut_ptr());
97    let n = x.len();
98    let grain = 4096usize;
99    let chunks = n.div_ceil(grain);
100    rows(pool, chunks, &|s, e| {
101        let (lo, hi) = (s * grain, (e * grain).min(n));
102        let r = unsafe { dst.at(lo, hi - lo) };
103        for v in r.iter_mut() {
104            *v = gelu_tanh(*v);
105        }
106    });
107}
108
109/// One attention row, normalized. A step softmaxes on the order of a
110/// billion scores — forty-eight blocks × thirty-two heads × every query
111/// against every key — so the scalar `exp()` here was not a detail: it was
112/// the arithmetic. The NEON path evaluates four at a time.
113pub(crate) fn softmax(row: &mut [f32]) {
114    #[cfg(target_arch = "aarch64")]
115    {
116        crate::attention::softmax_row(row);
117    }
118    #[cfg(not(target_arch = "aarch64"))]
119    {
120        let mx = row.iter().cloned().fold(f32::MIN, f32::max);
121        let mut den = 0f32;
122        for r in row.iter_mut() {
123            *r = (*r - mx).exp();
124            den += *r;
125        }
126        if den > 0.0 {
127            let inv = 1.0 / den;
128            for r in row.iter_mut() {
129                *r *= inv;
130            }
131        }
132    }
133}
134
135/// LayerNorm with no affine — the output head's only normalization.
136fn layer_norm(x: &[f32], dst: &mut [f32]) {
137    let n = x.len() as f64;
138    let mean = x.iter().map(|&v| v as f64).sum::<f64>() / n;
139    let var = x.iter().map(|&v| (v as f64 - mean) * (v as f64 - mean)).sum::<f64>() / n;
140    let inv = 1.0 / (var + EPS).sqrt();
141    for (d, &v) in dst.iter_mut().zip(x) {
142        *d = ((v as f64 - mean) * inv) as f32;
143    }
144}
145
146// ---------------------------------------------------------------- linear
147
148/// `y = x·Wᵀ + b`, the weight read in place when the container quantized it.
149pub(crate) struct Lin {
150    w: Proj,
151    b: Option<Vec<f32>>,
152    /// A runtime low-rank branch, when an adapter is loaded. The container's
153    /// q4tp weights cannot absorb one, so it is evaluated beside them.
154    lora: Option<crate::ltxlora::LoraBranch>,
155}
156
157impl Lin {
158    pub(crate) fn load(model: &Arc<CmfModel>, name: &str, bias: bool) -> Result<Lin, String> {
159        Lin::load_lora(model, name, bias, None)
160    }
161
162    /// The same, consulting an adapter for a low-rank branch on this
163    /// projection. A bank that carries nothing for `name` leaves the
164    /// projection exactly as `load` would.
165    pub(crate) fn load_lora(
166        model: &Arc<CmfModel>,
167        name: &str,
168        bias: bool,
169        bank: Option<&crate::ltxlora::LoraBank>,
170    ) -> Result<Lin, String> {
171        let w = Proj::from_model(model, &format!("{name}.weight"))?;
172        let b = if bias {
173            Some(cmf_f32(model, &format!("{name}.bias"))?)
174        } else {
175            None
176        };
177        // Shape-checked: a branch that does not match this projection is an
178        // adapter for another model, and the branch writes through a raw
179        // pointer sized by ITS out dimension.
180        let lora = match bank {
181            Some(k) => k.branch_for(name, w.rows(), w.cols())?,
182            None => None,
183        };
184        Ok(Lin { w, b, lora })
185    }
186
187    /// The adapter half of `apply`, for the fused paths that got the base
188    /// product elsewhere. Runs before the bias, which is where the reference
189    /// implementations put it — the branch sees the same activations the
190    /// base projection did.
191    pub(crate) fn has_lora(&self) -> bool {
192        self.lora.as_ref().is_some_and(|l| l.live())
193    }
194
195    pub(crate) fn add_lora(&self, out: &mut [f32], x: &[f32], n: usize, pool: Option<&Pool>) {
196        if let Some(l) = &self.lora {
197            l.add(x, n, out, pool);
198        }
199    }
200
201    /// The container-mapped q4tp weight behind this projection, when there
202    /// is one: (model, tensor index, rows, cols).
203    #[cfg(target_os = "macos")]
204    fn mapped(&self) -> Option<(&Arc<CmfModel>, usize, usize, usize)> {
205        let (model, idx) = self.w.q4tp_mapped()?;
206        Some((model, idx, self.w.rows(), self.w.cols()))
207    }
208
209    /// The bias half of `apply`, for callers that got the product elsewhere.
210    pub(crate) fn add_bias(&self, out: &mut [f32], n: usize, pool: Option<&Pool>) {
211        let Some(b) = &self.b else { return };
212        let m = self.w.rows();
213        let dst = Shared(out.as_mut_ptr());
214        rows(pool, n, &|s, e| {
215            let r = unsafe { dst.at(s * m, (e - s) * m) };
216            for row in r.chunks_exact_mut(m) {
217                for (v, &bb) in row.iter_mut().zip(b) {
218                    *v += bb;
219                }
220            }
221        });
222    }
223
224    pub(crate) fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
225        let m = self.w.rows();
226        let cols = self.w.cols();
227        let t_alloc = std::time::Instant::now();
228        let mut out = vec![0f32; n * m];
229        attn_prof::ALLOC.fetch_add(
230            t_alloc.elapsed().as_micros() as u64,
231            std::sync::atomic::Ordering::Relaxed,
232        );
233        let t_mm = std::time::Instant::now();
234        // With an adapter on this projection, the base GEMM and the branch go
235        // to the device in ONE submission: the branch reads the activation the
236        // base GEMM already uploaded and accumulates into the output it just
237        // wrote, so the adapter costs no transfer. Falls through to the split
238        // path when the device declines the shape.
239        #[cfg(target_os = "macos")]
240        if let (Some(l), Some((model, idx, r, cl))) = (&self.lora, self.mapped()) {
241            // The router measures a branch by comparing it against the base
242            // panel, and this path never separates the two. With routing on,
243            // take the split path so the measurement can happen at all.
244            if l.live()
245                && crate::ltxlora::route_threshold().is_none()
246                && n >= 32
247                && n * r * cl >= 128_000_000
248                && cl % 32 == 0
249                && !crate::gpu::mm_killed()
250                && crate::gpu::enabled_here()
251                && crate::gpu_metal::q4tp_matmat_lora(
252                    model, idx, x, n, r, cl, &mut out, &l.side(),
253                )
254            {
255                attn_prof::MATMAT.fetch_add(
256                    t_mm.elapsed().as_micros() as u64,
257                    std::sync::atomic::Ordering::Relaxed,
258                );
259                self.add_bias(&mut out, n, pool);
260                return out;
261            }
262        }
263        // A GPU binding is capped near 2 GiB, and the prompt encoder's
264        // aggregate projection reads 188160 numbers per token — 1024 of them
265        // at once is past the cap. Chunk the batch so no single dispatch
266        // binds more than a quarter of a gigabyte of activations.
267        let per_row = cols * 4;
268        let chunk = (0x1000_0000usize / per_row.max(1)).max(1);
269        let mut done = 0usize;
270        while done < n {
271            let take = chunk.min(n - done);
272            self.w.matmat(
273                &x[done * cols..(done + take) * cols],
274                take,
275                &mut out[done * m..(done + take) * m],
276                pool,
277            );
278            done += take;
279        }
280        attn_prof::MATMAT.fetch_add(
281            t_mm.elapsed().as_micros() as u64,
282            std::sync::atomic::Ordering::Relaxed,
283        );
284        if let Some(l) = &self.lora {
285            l.add(x, n, &mut out, pool);
286        }
287        if let Some(b) = &self.b {
288            let dst = Shared(out.as_mut_ptr());
289            rows(pool, n, &|s, e| {
290                let r = unsafe { dst.at(s * m, (e - s) * m) };
291                for row in r.chunks_exact_mut(m) {
292                    for (v, &bb) in row.iter_mut().zip(b) {
293                        *v += bb;
294                    }
295                }
296            });
297        }
298        out
299    }
300}
301
302// ------------------------------------------------------------------ rope
303
304/// Split-RoPE tables: `cos`/`sin` laid out as `[tokens, heads·dh/2]`.
305pub struct Rope {
306    cos: Vec<f32>,
307    sin: Vec<f32>,
308    heads: usize,
309    half: usize,
310}
311
312impl Rope {
313    /// `positions[t][d]` are patch midpoints and `max_pos[d]` the axis
314    /// extent they are divided by. `dim` is the *inner* dimension
315    /// (heads·dh) the frequency ladder is sized from.
316    pub fn build(positions: &[Vec<f64>], max_pos: &[f64], dim: usize, heads: usize, theta: f64) -> Rope {
317        let ndim = max_pos.len();
318        let count = dim / (2 * ndim);
319        // indices = theta^linspace(0, 1, count) · π/2, in f64
320        let idx: Vec<f64> = (0..count)
321            .map(|j| {
322                let e = if count > 1 { j as f64 / (count - 1) as f64 } else { 0.0 };
323                theta.powf(e) * std::f64::consts::PI / 2.0
324            })
325            .collect();
326        let n = positions.len();
327        let half = dim / 2;
328        let pad = half - count * ndim;
329        let mut cos = vec![0f32; n * half];
330        let mut sin = vec![0f32; n * half];
331        for (t, p) in positions.iter().enumerate() {
332            let base = t * half;
333            for i in 0..pad {
334                cos[base + i] = 1.0;
335            }
336            for (j, &ind) in idx.iter().enumerate() {
337                for (d, &mp) in max_pos.iter().enumerate() {
338                    let f = ind * (p[d] / mp * 2.0 - 1.0);
339                    let o = base + pad + j * ndim + d;
340                    cos[o] = f.cos() as f32;
341                    sin[o] = f.sin() as f32;
342                }
343            }
344        }
345        Rope { cos, sin, heads, half: half / heads }
346    }
347
348    /// In-place split rotation of one token's `[heads·dh]` projection.
349    fn apply_row(&self, t: usize, row: &mut [f32]) {
350        let dh = self.half * 2;
351        let stride = self.heads * self.half;
352        for h in 0..self.heads {
353            let off = t * stride + h * self.half;
354            let (c, s) = (&self.cos[off..off + self.half], &self.sin[off..off + self.half]);
355            let v = &mut row[h * dh..(h + 1) * dh];
356            for i in 0..self.half {
357                let (a, b) = (v[i], v[i + self.half]);
358                v[i] = a * c[i] - b * s[i];
359                v[i + self.half] = b * c[i] + a * s[i];
360            }
361        }
362    }
363}
364
365
366/// Sub-phase microseconds inside attention, summed across every call in a
367/// step. `CMF_LTX_PROF=1` prints them: the phase timers above say *which*
368/// attention is slow, these say *what part of it* is.
369pub(crate) mod attn_prof {
370    use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
371    pub static PROJ: AtomicU64 = AtomicU64::new(0);
372    pub static NORM: AtomicU64 = AtomicU64::new(0);
373    pub static GATHER: AtomicU64 = AtomicU64::new(0);
374    pub static SCORE: AtomicU64 = AtomicU64::new(0);
375    pub static SOFT: AtomicU64 = AtomicU64::new(0);
376    pub static VALUE: AtomicU64 = AtomicU64::new(0);
377    pub static OUT: AtomicU64 = AtomicU64::new(0);
378    pub static ALLOC: AtomicU64 = AtomicU64::new(0);
379    pub static MATMAT: AtomicU64 = AtomicU64::new(0);
380
381    pub fn add(c: &AtomicU64, t: std::time::Instant) -> std::time::Instant {
382        c.fetch_add(t.elapsed().as_micros() as u64, Relaxed);
383        std::time::Instant::now()
384    }
385
386    pub fn report() -> String {
387        let s = |c: &AtomicU64| c.swap(0, Relaxed) as f64 / 1e6;
388        format!(
389            "proj {:.2}s  qk-norm+rope {:.2}s  gather {:.2}s  scores {:.2}s  softmax {:.2}s  values {:.2}s  out {:.2}s  [linear: alloc {:.2}s  matmat {:.2}s]",
390            s(&PROJ), s(&NORM), s(&GATHER), s(&SCORE), s(&SOFT), s(&VALUE), s(&OUT),
391            s(&ALLOC), s(&MATMAT)
392        )
393    }
394}
395
396// ------------------------------------------------------------- attention
397
398pub(crate) struct Attn {
399    q: Lin,
400    k: Lin,
401    v: Lin,
402    o: Lin,
403    q_norm: Vec<f32>,
404    k_norm: Vec<f32>,
405    gate: Option<Lin>,
406    heads: usize,
407    dh: usize,
408}
409
410impl Attn {
411    pub(crate) fn load(model: &Arc<CmfModel>, p: &str, heads: usize, dh: usize) -> Result<Attn, String> {
412        Attn::load_lora(model, p, heads, dh, None)
413    }
414
415    pub(crate) fn load_lora(
416        model: &Arc<CmfModel>,
417        p: &str,
418        heads: usize,
419        dh: usize,
420        bank: Option<&crate::ltxlora::LoraBank>,
421    ) -> Result<Attn, String> {
422        Ok(Attn {
423            q: Lin::load_lora(model, &format!("{p}.to_q"), true, bank)?,
424            k: Lin::load_lora(model, &format!("{p}.to_k"), true, bank)?,
425            v: Lin::load_lora(model, &format!("{p}.to_v"), true, bank)?,
426            o: Lin::load_lora(model, &format!("{p}.to_out.0"), true, bank)?,
427            q_norm: cmf_f32(model, &format!("{p}.q_norm.weight"))?,
428            k_norm: cmf_f32(model, &format!("{p}.k_norm.weight"))?,
429            gate: match model.tensor(&format!("{p}.to_gate_logits.weight")) {
430                Some(_) => Some(Lin::load(model, &format!("{p}.to_gate_logits"), true)?),
431                None => None,
432            },
433            heads,
434            dh,
435        })
436    }
437
438    /// The three projections in one submission, when the platform has a
439    /// batched entry and all three read the same activation. Returns `None`
440    /// when they do not — cross-attention's query comes from the tokens and
441    /// its keys from the prompt — and the caller falls back to three calls.
442    #[cfg(target_os = "macos")]
443    fn fused_qkv(
444        &self,
445        x: &[f32],
446        n: usize,
447        ctx: &[f32],
448        m: usize,
449        pool: Option<&Pool>,
450    ) -> Option<(Vec<f32>, Vec<f32>, Vec<f32>)> {
451        if !std::ptr::eq(x.as_ptr(), ctx.as_ptr()) || n != m {
452            return None;
453        }
454        if !crate::gpu::enabled_here() || crate::gpu::mm_killed() {
455            return None;
456        }
457        // The batched entry carries one weight per job and no branch. When an
458        // adapter is loaded, decline: `apply` then takes the per-projection
459        // path that fuses the base GEMM and the branch into one submission,
460        // which is the cheaper of the two.
461        if self.q.has_lora() || self.k.has_lora() || self.v.has_lora() {
462            return None;
463        }
464        let (qw, kw, vw) = (self.q.mapped()?, self.k.mapped()?, self.v.mapped()?);
465        if !Arc::ptr_eq(qw.0, kw.0) || !Arc::ptr_eq(qw.0, vw.0) {
466            return None;
467        }
468        let jobs = [
469            crate::gpu_metal::MmJob { idx: qw.1, rows: qw.2, cols: qw.3 },
470            crate::gpu_metal::MmJob { idx: kw.1, rows: kw.2, cols: kw.3 },
471            crate::gpu_metal::MmJob { idx: vw.1, rows: vw.2, cols: vw.3 },
472        ];
473        if n * jobs[0].rows * jobs[0].cols < 128_000_000 || n < 32 {
474            return None;
475        }
476        let mut oq = vec![0f32; n * jobs[0].rows];
477        let mut ok = vec![0f32; n * jobs[1].rows];
478        let mut ov = vec![0f32; n * jobs[2].rows];
479        let done = {
480            let mut outs: [&mut [f32]; 3] = [&mut oq, &mut ok, &mut ov];
481            crate::gpu_metal::q4tp_matmat_many(qw.0, &jobs, x, n, &mut outs)
482        };
483        if !done {
484            return None;
485        }
486        self.q.add_lora(&mut oq, x, n, pool);
487        self.k.add_lora(&mut ok, x, n, pool);
488        self.v.add_lora(&mut ov, x, n, pool);
489        self.q.add_bias(&mut oq, n, pool);
490        self.k.add_bias(&mut ok, n, pool);
491        self.v.add_bias(&mut ov, n, pool);
492        Some((oq, ok, ov))
493    }
494
495    /// The key and value projections in one submission — they always read
496    /// the same buffer, whatever the query does.
497    #[cfg(target_os = "macos")]
498    fn fused_kv(&self, ctx: &[f32], m: usize) -> Option<(Vec<f32>, Vec<f32>)> {
499        if !crate::gpu::enabled_here() || crate::gpu::mm_killed() {
500            return None;
501        }
502        if self.k.has_lora() || self.v.has_lora() {
503            return None;
504        }
505        let (kw, vw) = (self.k.mapped()?, self.v.mapped()?);
506        if !Arc::ptr_eq(kw.0, vw.0) {
507            return None;
508        }
509        let jobs = [
510            crate::gpu_metal::MmJob { idx: kw.1, rows: kw.2, cols: kw.3 },
511            crate::gpu_metal::MmJob { idx: vw.1, rows: vw.2, cols: vw.3 },
512        ];
513        if m < 32 || m * jobs[0].rows * jobs[0].cols < 128_000_000 {
514            return None;
515        }
516        let mut ok = vec![0f32; m * jobs[0].rows];
517        let mut ov = vec![0f32; m * jobs[1].rows];
518        let done = {
519            let mut outs: [&mut [f32]; 2] = [&mut ok, &mut ov];
520            crate::gpu_metal::q4tp_matmat_many(kw.0, &jobs, ctx, m, &mut outs)
521        };
522        if !done {
523            return None;
524        }
525        self.k.add_lora(&mut ok, ctx, m, None);
526        self.v.add_lora(&mut ov, ctx, m, None);
527        self.k.add_bias(&mut ok, m, None);
528        self.v.add_bias(&mut ov, m, None);
529        Some((ok, ov))
530    }
531
532    #[cfg(not(target_os = "macos"))]
533    fn fused_kv(&self, _ctx: &[f32], _m: usize) -> Option<(Vec<f32>, Vec<f32>)> {
534        None
535    }
536
537    #[cfg(not(target_os = "macos"))]
538    fn fused_qkv(
539        &self,
540        _x: &[f32],
541        _n: usize,
542        _ctx: &[f32],
543        _m: usize,
544        _pool: Option<&Pool>,
545    ) -> Option<(Vec<f32>, Vec<f32>, Vec<f32>)> {
546        None
547    }
548
549    /// `x` is `[n, query_dim]`, `ctx` is `[m, context_dim]` (self-attention
550    /// passes the same buffer twice). `mask` is an additive per-key bias.
551    #[allow(clippy::too_many_arguments)]
552    pub(crate) fn forward(
553        &self,
554        x: &[f32],
555        n: usize,
556        ctx: &[f32],
557        m: usize,
558        pe_q: Option<&Rope>,
559        pe_k: Option<&Rope>,
560        mask: Option<&[f32]>,
561        pool: Option<&Pool>,
562    ) -> Vec<f32> {
563        let inner = self.heads * self.dh;
564        let prof = std::env::var("CMF_LTX_PROF").is_ok();
565        let mut t = std::time::Instant::now();
566        // q, k and v do not depend on each other. When they also read the
567        // same buffer — self-attention, and the A↔V pair on the context
568        // side — they go to the device as one command buffer instead of
569        // three, which is three times less of the ~1.3 ms a completion
570        // costs whatever it contains.
571        let (mut q, mut k, v) = match self.fused_qkv(x, n, ctx, m, pool) {
572            Some(t) => t,
573            // Cross-attention's query reads the tokens and its keys read the
574            // prompt, so those two cannot share a submission — but the keys
575            // and the values still can.
576            None => match self.fused_kv(ctx, m) {
577                Some((k, v)) => (self.q.apply(x, n, pool), k, v),
578                None => (
579                    self.q.apply(x, n, pool),
580                    self.k.apply(ctx, m, pool),
581                    self.v.apply(ctx, m, pool),
582                ),
583            },
584        };
585        if prof {
586            t = attn_prof::add(&attn_prof::PROJ, t);
587        }
588
589        let qn = Shared(q.as_mut_ptr());
590        rows(pool, n, &|s, e| {
591            let r = unsafe { qn.at(s * inner, (e - s) * inner) };
592            for (i, row) in r.chunks_exact_mut(inner).enumerate() {
593                rms_w(row, &self.q_norm);
594                if let Some(pe) = pe_q {
595                    pe.apply_row(s + i, row);
596                }
597            }
598        });
599        let kn = Shared(k.as_mut_ptr());
600        rows(pool, m, &|s, e| {
601            let r = unsafe { kn.at(s * inner, (e - s) * inner) };
602            for (i, row) in r.chunks_exact_mut(inner).enumerate() {
603                rms_w(row, &self.k_norm);
604                if let Some(pe) = pe_k {
605                    pe.apply_row(s + i, row);
606                }
607            }
608        });
609
610        // Per head, both halves of attention are GEMMs: scores are
611        // q·kᵀ and the value product is p·v. Gathering each head into a
612        // contiguous `[tokens, dh]` block costs one copy and buys the
613        // engine's blocked/BLAS/GPU kernels instead of a scalar loop —
614        // this is most of a step's arithmetic.
615        if prof {
616            t = attn_prof::add(&attn_prof::NORM, t);
617        }
618        let mut out = vec![0f32; n * inner];
619        let scale = 1.0 / (self.dh as f32).sqrt();
620        let dh = self.dh;
621        let mut qh = vec![0f32; n * dh];
622        let mut kh = vec![0f32; m * dh];
623        let mut vh = vec![0f32; m * dh];
624        let mut sc = vec![0f32; n * m];
625        let mut oh = vec![0f32; n * dh];
626        for h in 0..self.heads {
627            for i in 0..n {
628                qh[i * dh..(i + 1) * dh].copy_from_slice(&q[i * inner + h * dh..][..dh]);
629            }
630            for j in 0..m {
631                kh[j * dh..(j + 1) * dh].copy_from_slice(&k[j * inner + h * dh..][..dh]);
632                vh[j * dh..(j + 1) * dh].copy_from_slice(&v[j * inner + h * dh..][..dh]);
633            }
634            if prof {
635                t = attn_prof::add(&attn_prof::GATHER, t);
636            }
637            crate::fcd_ops::gemm_nt(&qh, &kh, &mut sc, n, dh, m, pool);
638            if prof {
639                t = attn_prof::add(&attn_prof::SCORE, t);
640            }
641            let sp = Shared(sc.as_mut_ptr());
642            rows(pool, n, &|s, e| {
643                let r = unsafe { sp.at(s * m, (e - s) * m) };
644                for row in r.chunks_exact_mut(m) {
645                    for (x, j) in row.iter_mut().zip(0..m) {
646                        *x = *x * scale + mask.map_or(0.0, |mk| mk[j]);
647                    }
648                    softmax(row);
649                }
650            });
651            if prof {
652                t = attn_prof::add(&attn_prof::SOFT, t);
653            }
654            oh.iter_mut().for_each(|x| *x = 0.0);
655            crate::fcd_ops::gemm_dx(&sc, &vh, &mut oh, n, dh, m, pool);
656            if prof {
657                t = attn_prof::add(&attn_prof::VALUE, t);
658            }
659            for i in 0..n {
660                out[i * inner + h * dh..i * inner + (h + 1) * dh]
661                    .copy_from_slice(&oh[i * dh..(i + 1) * dh]);
662            }
663            if prof {
664                t = attn_prof::add(&attn_prof::GATHER, t);
665            }
666        }
667
668        if let Some(g) = &self.gate {
669            let logits = g.apply(x, n, pool);
670            let h = self.heads;
671            let dst = Shared(out.as_mut_ptr());
672            rows(pool, n, &|s, e| {
673                let r = unsafe { dst.at(s * inner, (e - s) * inner) };
674                for (i, row) in r.chunks_exact_mut(inner).enumerate() {
675                    for hh in 0..h {
676                        let gate = 2.0 / (1.0 + (-logits[(s + i) * h + hh]).exp());
677                        for d in row[hh * self.dh..(hh + 1) * self.dh].iter_mut() {
678                            *d *= gate;
679                        }
680                    }
681                }
682            });
683        }
684        let r = self.o.apply(&out, n, pool);
685        if prof {
686            attn_prof::add(&attn_prof::OUT, t);
687        }
688        r
689    }
690}
691
692// ---------------------------------------------------------- adaLN single
693
694/// `AdaLayerNormSingle`: sinusoidal timestep → SiLU MLP → `coeff·dim`
695/// modulation values, plus the embedding the output head reuses.
696struct AdaLn {
697    l1: Lin,
698    l2: Lin,
699    lin: Lin,
700    dim: usize,
701}
702
703impl AdaLn {
704    fn load(model: &Arc<CmfModel>, p: &str, dim: usize) -> Result<AdaLn, String> {
705        Ok(AdaLn {
706            l1: Lin::load(model, &format!("{p}.emb.timestep_embedder.linear_1"), true)?,
707            l2: Lin::load(model, &format!("{p}.emb.timestep_embedder.linear_2"), true)?,
708            lin: Lin::load(model, &format!("{p}.linear"), true)?,
709            dim,
710        })
711    }
712
713    /// `(values [n, coeff·dim], embedded [n, dim])` for `n` timesteps.
714    fn forward(&self, t: &[f32], pool: Option<&Pool>) -> (Vec<f32>, Vec<f32>) {
715        let n = t.len();
716        // get_timestep_embedding(256, flip_sin_to_cos=True, shift=0): the
717        // flip puts cosine first, so the halves are [cos, sin].
718        let half = 128usize;
719        let mut proj = vec![0f32; n * 256];
720        let ws: Vec<f64> = (0..half)
721            .map(|j| (-(10000f64).ln() * j as f64 / half as f64).exp())
722            .collect();
723        for (i, &tv) in t.iter().enumerate() {
724            for (j, &w) in ws.iter().enumerate() {
725                let a = tv as f64 * w;
726                proj[i * 256 + j] = a.cos() as f32;
727                proj[i * 256 + half + j] = a.sin() as f32;
728            }
729        }
730        let mut h = self.l1.apply(&proj, n, pool);
731        for v in h.iter_mut() {
732            *v = silu(*v);
733        }
734        let embedded = self.l2.apply(&h, n, pool);
735        let mut act = embedded.clone();
736        for v in act.iter_mut() {
737            *v = silu(*v);
738        }
739        (self.lin.apply(&act, n, pool), embedded)
740    }
741}
742
743/// adaLN values for the *distinct* timesteps of a stream, plus each token's
744/// index into them. Per-token timesteps take only a handful of values here
745/// (a conditioning token sits at 0 while the rest sit at the current
746/// sigma), so the `[36864, 4096]` projection runs a few times, not `T`.
747struct TsTable {
748    vals: Vec<f32>,
749    emb: Vec<f32>,
750    idx: Vec<usize>,
751    width: usize,
752    edim: usize,
753}
754
755impl TsTable {
756    fn build(a: &AdaLn, ts: &[f32], scale: f64, pool: Option<&Pool>) -> TsTable {
757        let mut vals: Vec<f32> = Vec::new();
758        let mut idx = Vec::with_capacity(ts.len());
759        for &t in ts {
760            match vals.iter().position(|&v| v.to_bits() == t.to_bits()) {
761                Some(i) => idx.push(i),
762                None => {
763                    vals.push(t);
764                    idx.push(vals.len() - 1);
765                }
766            }
767        }
768        let scaled: Vec<f32> = vals.iter().map(|&v| (v as f64 * scale) as f32).collect();
769        let (v, e) = a.forward(&scaled, pool);
770        let width = v.len() / scaled.len().max(1);
771        TsTable { vals: v, emb: e, idx, width, edim: a.dim }
772    }
773
774    fn distinct(&self) -> usize {
775        self.vals.len() / self.width.max(1)
776    }
777
778    fn row(&self, r: usize) -> &[f32] {
779        &self.vals[r * self.width..(r + 1) * self.width]
780    }
781
782    fn emb_row(&self, r: usize) -> &[f32] {
783        &self.emb[r * self.edim..(r + 1) * self.edim]
784    }
785
786    /// `(shift, scale, gate)` per distinct timestep for the adaLN triple at
787    /// table row `off`: the block's static table plus the timestep's own
788    /// contribution, summed once instead of once per token.
789    fn triples(&self, table: &[f32], dim: usize, off: usize) -> Vec<[Vec<f32>; 3]> {
790        (0..self.distinct())
791            .map(|r| {
792                let v = self.row(r);
793                std::array::from_fn(|j| {
794                    let o = (off + j) * dim;
795                    (0..dim).map(|d| table[o + d] + v[o + d]).collect()
796                })
797            })
798            .collect()
799    }
800
801    /// `(scale, shift)` per distinct timestep for an A↔V table, which — unlike
802    /// the self-attention rows — comes out scale-first.
803    fn pairs(&self, table: &[f32], dim: usize, off: usize) -> Vec<[Vec<f32>; 2]> {
804        (0..self.distinct())
805            .map(|r| {
806                let v = self.row(r);
807                std::array::from_fn(|j| {
808                    let o = (off + j) * dim;
809                    (0..dim).map(|d| table[o + d] + v[o + d]).collect()
810                })
811            })
812            .collect()
813    }
814}
815
816
817/// `rms_norm(x) · (1 + scale) + shift` over every token, in parallel.
818/// `mods[r]` is the `(shift, scale, gate)` triple of the r-th distinct
819/// timestep and `idx[t]` says which one token `t` uses.
820fn ada_zero_rows(
821    x: &[f32],
822    out: &mut [f32],
823    n: usize,
824    dim: usize,
825    mods: &[[Vec<f32>; 3]],
826    idx: &[usize],
827    pool: Option<&Pool>,
828) {
829    let dst = Shared(out.as_mut_ptr());
830    rows(pool, n, &|s, e| {
831        let r = unsafe { dst.at(s * dim, (e - s) * dim) };
832        for (row, i) in r.chunks_exact_mut(dim).zip(s..e) {
833            let md = &mods[idx[i]];
834            rms_plain(&x[i * dim..(i + 1) * dim], row);
835            for d in 0..dim {
836                row[d] = row[d] * (1.0 + md[1][d]) + md[0][d];
837            }
838        }
839    });
840}
841
842/// `x += y · gate`, the residual every sub-layer writes back through.
843fn add_gated(
844    x: &mut [f32],
845    y: &[f32],
846    n: usize,
847    dim: usize,
848    mods: &[[Vec<f32>; 3]],
849    idx: &[usize],
850    pool: Option<&Pool>,
851) {
852    let dst = Shared(x.as_mut_ptr());
853    rows(pool, n, &|s, e| {
854        let r = unsafe { dst.at(s * dim, (e - s) * dim) };
855        for (row, i) in r.chunks_exact_mut(dim).zip(s..e) {
856            let g = &mods[idx[i]][2];
857            for d in 0..dim {
858                row[d] += y[i * dim + d] * g[d];
859            }
860        }
861    });
862}
863
864/// The post-SA pair: fold the gated update into the residual and hand the
865/// re-normalized result to cross-attention, in one pass over the tokens.
866fn post_sa_rows(
867    x: &mut [f32],
868    y: &[f32],
869    normed: &mut [f32],
870    n: usize,
871    dim: usize,
872    mods: &[[Vec<f32>; 3]],
873    idx: &[usize],
874    pool: Option<&Pool>,
875) {
876    let a = Shared(x.as_mut_ptr());
877    let b = Shared(normed.as_mut_ptr());
878    rows(pool, n, &|s, e| {
879        let xr = unsafe { a.at(s * dim, (e - s) * dim) };
880        let nr = unsafe { b.at(s * dim, (e - s) * dim) };
881        for ((row, nrow), i) in xr.chunks_exact_mut(dim).zip(nr.chunks_exact_mut(dim)).zip(s..e) {
882            let g = &mods[idx[i]][2];
883            for d in 0..dim {
884                row[d] += y[i * dim + d] * g[d];
885            }
886            rms_plain(row, nrow);
887        }
888    });
889}
890
891/// `x += y · g` with one shared per-channel gate (the A↔V fusion).
892fn add_scaled(x: &mut [f32], y: &[f32], n: usize, dim: usize, g: &[f32], pool: Option<&Pool>) {
893    let dst = Shared(x.as_mut_ptr());
894    rows(pool, n, &|s, e| {
895        let r = unsafe { dst.at(s * dim, (e - s) * dim) };
896        for (row, i) in r.chunks_exact_mut(dim).zip(s..e) {
897            for d in 0..dim {
898                row[d] += y[i * dim + d] * g[d];
899            }
900        }
901    });
902}
903
904/// The cross-attention query: an affine on an already-normalized row.
905fn affine_rows(
906    x: &[f32],
907    out: &mut [f32],
908    n: usize,
909    dim: usize,
910    mods: &[[Vec<f32>; 3]],
911    idx: &[usize],
912    pool: Option<&Pool>,
913) {
914    let dst = Shared(out.as_mut_ptr());
915    rows(pool, n, &|s, e| {
916        let r = unsafe { dst.at(s * dim, (e - s) * dim) };
917        for (row, i) in r.chunks_exact_mut(dim).zip(s..e) {
918            let md = &mods[idx[i]];
919            for d in 0..dim {
920                row[d] = x[i * dim + d] * (1.0 + md[1][d]) + md[0][d];
921            }
922        }
923    });
924}
925
926
927/// Where a denoising step actually goes. `CMF_LTX_PROF=1` prints the split
928/// once per forward: guessing at this is how ports stay slow.
929#[derive(Default)]
930struct Prof {
931    on: bool,
932    t: [f64; 6],
933}
934
935const P_ADALN: usize = 0;
936const P_SELF: usize = 1;
937const P_CROSS: usize = 2;
938const P_FUSE: usize = 3;
939const P_FF: usize = 4;
940const P_MOD: usize = 5;
941
942impl Prof {
943    fn new() -> Prof {
944        Prof { on: std::env::var("CMF_LTX_PROF").is_ok(), t: [0.0; 6] }
945    }
946    #[inline]
947    fn tick(&mut self, slot: usize, at: std::time::Instant) -> std::time::Instant {
948        if self.on {
949            self.t[slot] += at.elapsed().as_secs_f64();
950            return std::time::Instant::now();
951        }
952        at
953    }
954    fn report(&self) {
955        if !self.on {
956            return;
957        }
958        // The q4tp GEMM's own split, when Metal is keeping it: a copy-bound
959        // step wants fused blocks, a kernel-bound one wants a better kernel.
960        #[cfg(target_os = "macos")]
961        {
962            use std::sync::atomic::Ordering::Relaxed;
963            let n = crate::gpu_metal::MM_N.swap(0, Relaxed);
964            if n > 0 {
965                let us = |a: &std::sync::atomic::AtomicU64| a.swap(0, Relaxed) as f64 / 1e6;
966                println!(
967                    "  q4tp on device: {n} calls, upload {:.2}s  kernel {:.2}s  download {:.2}s",
968                    us(&crate::gpu_metal::MM_UP),
969                    us(&crate::gpu_metal::MM_GPU),
970                    us(&crate::gpu_metal::MM_DN),
971                );
972            }
973        }
974        println!("  attention: {}", attn_prof::report());
975        let names = ["adaln", "self-attn", "cross-attn", "a<->v", "ffn", "modulate"];
976        let total: f64 = self.t.iter().sum();
977        let parts: Vec<String> = names
978            .iter()
979            .zip(&self.t)
980            .map(|(n, v)| format!("{n} {v:.1}s ({:.0}%)", 100.0 * v / total.max(1e-9)))
981            .collect();
982        println!("  profile: {}", parts.join("  "));
983    }
984}
985
986// ----------------------------------------------------------------- block
987
988struct Stream {
989    attn1: Attn,
990    attn2: Attn,
991    ff_in: Lin,
992    ff_out: Lin,
993    sst: Vec<f32>,        // [9, dim]
994    prompt_sst: Vec<f32>, // [2, dim]
995}
996
997impl Stream {
998    fn load(
999        model: &Arc<CmfModel>,
1000        p: &str,
1001        prefix: &str,
1002        heads: usize,
1003        dh: usize,
1004        ff_bias: bool,
1005        bank: Option<&crate::ltxlora::LoraBank>,
1006    ) -> Result<Stream, String> {
1007        let a = |n: &str| format!("{p}.{prefix}{n}");
1008        Ok(Stream {
1009            attn1: Attn::load_lora(model, &a("attn1"), heads, dh, bank)?,
1010            attn2: Attn::load_lora(model, &a("attn2"), heads, dh, bank)?,
1011            ff_in: Lin::load_lora(model, &a("ff.net.0.proj"), ff_bias, bank)?,
1012            ff_out: Lin::load_lora(model, &a("ff.net.2"), ff_bias, bank)?,
1013            sst: cmf_f32(model, &a("scale_shift_table"))?,
1014            prompt_sst: cmf_f32(model, &a("prompt_scale_shift_table"))?,
1015        })
1016    }
1017
1018    fn ff(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
1019        let mut h = self.ff_in.apply(x, n, pool);
1020        gelu_tanh_rows(&mut h, pool);
1021        self.ff_out.apply(&h, n, pool)
1022    }
1023}
1024
1025struct Block {
1026    video: Stream,
1027    audio: Stream,
1028    a2v: Attn,
1029    v2a: Attn,
1030    sst_a2v_video: Vec<f32>, // [5, 4096]
1031    sst_a2v_audio: Vec<f32>, // [5, 2048]
1032}
1033
1034// ----------------------------------------------------------------- model
1035
1036/// One modality's per-step conditioning: everything the blocks read that is
1037/// not a weight.
1038pub struct StreamInput {
1039    /// Patchified latent, `[tokens, in_channels]`.
1040    pub latent: Vec<f32>,
1041    pub tokens: usize,
1042    /// Per-token timestep (the sigma·denoising-mask product).
1043    pub timesteps: Vec<f32>,
1044    /// Per-token patch midpoints, one entry per RoPE axis.
1045    pub positions: Vec<Vec<f64>>,
1046    /// Prompt embeddings out of the connector, `[ctx_len, cross_dim]`.
1047    pub context: Vec<f32>,
1048    pub ctx_len: usize,
1049    /// Additive per-key prompt mask, or empty for "attend to all".
1050    pub context_mask: Vec<f32>,
1051    /// Non-zero for tokens holding a standalone pixel frame (video only).
1052    pub keyframes: Vec<f32>,
1053    /// This stream's sigma — the *other* stream's fusion gate reads it.
1054    pub sigma: f32,
1055}
1056
1057pub struct LtxDit {
1058    model: Arc<CmfModel>,
1059    blocks: Vec<Block>,
1060    patchify: Lin,
1061    a_patchify: Lin,
1062    keyframes_emb: Option<Vec<f32>>,
1063    adaln: AdaLn,
1064    a_adaln: AdaLn,
1065    prompt_adaln: AdaLn,
1066    a_prompt_adaln: AdaLn,
1067    av_v_ss: AdaLn,
1068    av_a_ss: AdaLn,
1069    av_a2v_gate: AdaLn,
1070    av_v2a_gate: AdaLn,
1071    proj_out: Lin,
1072    a_proj_out: Lin,
1073    sst_out: Vec<f32>,
1074    a_sst_out: Vec<f32>,
1075    pub heads: usize,
1076    pub dh: usize,
1077    pub a_heads: usize,
1078    pub a_dh: usize,
1079    pub max_pos: Vec<f64>,
1080    pub a_max_pos: Vec<f64>,
1081    pub cross_max_pos: f64,
1082    pub theta: f64,
1083    pub t_scale: f64,
1084    pub av_t_scale: f64,
1085    pub audio_cross_dim: usize,
1086}
1087
1088impl LtxDit {
1089    pub fn from_cmf(model: &Arc<CmfModel>) -> Result<LtxDit, String> {
1090        LtxDit::from_cmf_lora(model, None)
1091    }
1092
1093    /// The same, with a runtime adapter bound to whichever projections it
1094    /// names. Reported once at load so a file that matched nothing says so
1095    /// instead of rendering as if it had.
1096    pub fn from_cmf_lora(
1097        model: &Arc<CmfModel>,
1098        bank: Option<&crate::ltxlora::LoraBank>,
1099    ) -> Result<LtxDit, String> {
1100        let cfg_bytes = ["ltx.config_json", "dit.config_json"]
1101            .iter()
1102            .find_map(|n| model.tensor(n).map(|e| model.entry_bytes(e)))
1103            .ok_or("container carries no ltx.config_json")?;
1104        let cfg: serde_json::Value =
1105            serde_json::from_slice(cfg_bytes).map_err(|e| format!("ltx.config_json: {e}"))?;
1106        let t = cfg.get("transformer").unwrap_or(&cfg).clone();
1107        let g = |k: &str, d: f64| t.get(k).and_then(|v| v.as_f64()).unwrap_or(d);
1108        let heads = g("num_attention_heads", 32.0) as usize;
1109        let dh = g("attention_head_dim", 128.0) as usize;
1110        let a_heads = g("audio_num_attention_heads", 32.0) as usize;
1111        let a_dh = g("audio_attention_head_dim", 64.0) as usize;
1112        let n_layers = g("num_layers", 48.0) as usize;
1113        let ff_bias = t.get("ff_bias").and_then(|v| v.as_bool()).unwrap_or(true);
1114        let a_ff_bias = t.get("audio_ff_bias").and_then(|v| v.as_bool()).unwrap_or(true);
1115        let arr = |k: &str, d: Vec<f64>| -> Vec<f64> {
1116            t.get(k)
1117                .and_then(|v| v.as_array())
1118                .map(|a| a.iter().filter_map(|x| x.as_f64()).collect())
1119                .unwrap_or(d)
1120        };
1121        let max_pos = arr("positional_embedding_max_pos", vec![20.0, 2048.0, 2048.0]);
1122        let a_max_pos = arr("audio_positional_embedding_max_pos", vec![20.0]);
1123        let cross_max_pos = max_pos[0].max(a_max_pos[0]);
1124        let dim = heads * dh;
1125        let a_dim = a_heads * a_dh;
1126
1127        let mut blocks = Vec::with_capacity(n_layers);
1128        for i in 0..n_layers {
1129            let p = format!("dit.transformer_blocks.{i}");
1130            blocks.push(Block {
1131                video: Stream::load(model, &p, "", heads, dh, ff_bias, bank)?,
1132                audio: Stream::load(model, &p, "audio_", a_heads, a_dh, a_ff_bias, bank)?,
1133                a2v: Attn::load(model, &format!("{p}.audio_to_video_attn"), a_heads, a_dh)?,
1134                v2a: Attn::load(model, &format!("{p}.video_to_audio_attn"), a_heads, a_dh)?,
1135                sst_a2v_video: cmf_f32(model, &format!("{p}.scale_shift_table_a2v_ca_video"))?,
1136                sst_a2v_audio: cmf_f32(model, &format!("{p}.scale_shift_table_a2v_ca_audio"))?,
1137            });
1138        }
1139        let _ = (dim, a_dim);
1140        Ok(LtxDit {
1141            blocks,
1142            patchify: Lin::load(model, "dit.patchify_proj", true)?,
1143            a_patchify: Lin::load(model, "dit.audio_patchify_proj", true)?,
1144            keyframes_emb: match model.tensor("dit.keyframes_abs_pos_embedding") {
1145                Some(_) => Some(cmf_f32(model, "dit.keyframes_abs_pos_embedding")?),
1146                None => None,
1147            },
1148            adaln: AdaLn::load(model, "dit.adaln_single", dim)?,
1149            a_adaln: AdaLn::load(model, "dit.audio_adaln_single", a_dim)?,
1150            prompt_adaln: AdaLn::load(model, "dit.prompt_adaln_single", dim)?,
1151            a_prompt_adaln: AdaLn::load(model, "dit.audio_prompt_adaln_single", a_dim)?,
1152            av_v_ss: AdaLn::load(model, "dit.av_ca_video_scale_shift_adaln_single", dim)?,
1153            av_a_ss: AdaLn::load(model, "dit.av_ca_audio_scale_shift_adaln_single", a_dim)?,
1154            av_a2v_gate: AdaLn::load(model, "dit.av_ca_a2v_gate_adaln_single", dim)?,
1155            av_v2a_gate: AdaLn::load(model, "dit.av_ca_v2a_gate_adaln_single", a_dim)?,
1156            proj_out: Lin::load(model, "dit.proj_out", true)?,
1157            a_proj_out: Lin::load(model, "dit.audio_proj_out", true)?,
1158            sst_out: cmf_f32(model, "dit.scale_shift_table")?,
1159            a_sst_out: cmf_f32(model, "dit.audio_scale_shift_table")?,
1160            heads,
1161            dh,
1162            a_heads,
1163            a_dh,
1164            max_pos,
1165            a_max_pos,
1166            cross_max_pos,
1167            theta: g("positional_embedding_theta", 10000.0),
1168            t_scale: g("timestep_scale_multiplier", 1000.0),
1169            av_t_scale: g("av_ca_timestep_scale_multiplier", 1.0),
1170            audio_cross_dim: g("audio_cross_attention_dim", 2048.0) as usize,
1171            model: model.clone(),
1172        })
1173    }
1174
1175    pub fn blocks(&self) -> usize {
1176        self.blocks.len()
1177    }
1178
1179    pub fn container(&self) -> &Arc<CmfModel> {
1180        &self.model
1181    }
1182
1183    /// One denoising step: `(video velocity [T, C], audio velocity [T, C])`.
1184    pub fn forward(
1185        &self,
1186        video: &StreamInput,
1187        audio: &StreamInput,
1188        pool: Option<&Pool>,
1189    ) -> (Vec<f32>, Vec<f32>) {
1190        self.forward_traced(video, audio, pool, &mut |_, _| {})
1191    }
1192
1193    pub fn forward_traced(
1194        &self,
1195        video: &StreamInput,
1196        audio: &StreamInput,
1197        pool: Option<&Pool>,
1198        trace: &mut dyn FnMut(&str, &[f32]),
1199    ) -> (Vec<f32>, Vec<f32>) {
1200        // A denoising step is the opposite of what the per-op probe is built
1201        // for: forty-eight identical blocks, the same shapes every time, the
1202        // device warm throughout. Take the probe out of it.
1203        let _trust = crate::gpu::trust_gpu();
1204        let dim = self.heads * self.dh;
1205        let a_dim = self.a_heads * self.a_dh;
1206        let (n, m) = (video.tokens, audio.tokens);
1207
1208        // --- patchify -----------------------------------------------------
1209        let mut vx = self.patchify.apply(&video.latent, n, pool);
1210        if let Some(emb) = &self.keyframes_emb {
1211            for i in 0..n {
1212                if video.keyframes.get(i).copied().unwrap_or(0.0) > 0.0 {
1213                    for (d, &e) in vx[i * dim..(i + 1) * dim].iter_mut().zip(emb) {
1214                        *d += e;
1215                    }
1216                }
1217            }
1218        }
1219        let mut ax = self.a_patchify.apply(&audio.latent, m, pool);
1220        trace("v.args.x", &vx);
1221        trace("a.args.x", &ax);
1222
1223        // --- adaLN tables, one row per distinct timestep -------------------
1224        let vt = TsTable::build(&self.adaln, &video.timesteps, self.t_scale, pool);
1225        let at = TsTable::build(&self.a_adaln, &audio.timesteps, self.t_scale, pool);
1226        let vpt = TsTable::build(&self.prompt_adaln, &[video.sigma], self.t_scale, pool);
1227        let apt = TsTable::build(&self.a_prompt_adaln, &[audio.sigma], self.t_scale, pool);
1228        if std::env::var("CMF_LTX_PROMPTADALN").is_ok() {
1229            let r = vpt.row(0);
1230            let mx = r.iter().fold(0f32, |m, &v| m.max(v.abs()));
1231            let sum: f32 = r.iter().sum();
1232            eprintln!("prompt-adaln sigma={:.6} max|row|={mx:.6e} sum={sum:.6e}", video.sigma);
1233        }
1234        let vxs = TsTable::build(&self.av_v_ss, &video.timesteps, self.t_scale, pool);
1235        let axs = TsTable::build(&self.av_a_ss, &audio.timesteps, self.t_scale, pool);
1236        // The fusion gate reads the *other* stream's sigma — the noise level
1237        // it is being asked to trust — at the A-V multiplier.
1238        let vgt = TsTable::build(&self.av_a2v_gate, &[audio.sigma], self.av_t_scale, pool);
1239        let agt = TsTable::build(&self.av_v2a_gate, &[video.sigma], self.av_t_scale, pool);
1240
1241        // --- RoPE ---------------------------------------------------------
1242        let v_pe = Rope::build(&video.positions, &self.max_pos, dim, self.heads, self.theta);
1243        let a_pe = Rope::build(&audio.positions, &self.a_max_pos, a_dim, self.a_heads, self.theta);
1244        let time_only = |p: &[Vec<f64>]| p.iter().map(|r| vec![r[0]]).collect::<Vec<_>>();
1245        let v_xpe = Rope::build(
1246            &time_only(&video.positions),
1247            &[self.cross_max_pos],
1248            self.audio_cross_dim,
1249            self.heads,
1250            self.theta,
1251        );
1252        let a_xpe = Rope::build(
1253            &time_only(&audio.positions),
1254            &[self.cross_max_pos],
1255            self.audio_cross_dim,
1256            self.a_heads,
1257            self.theta,
1258        );
1259
1260        let vmask = (!video.context_mask.is_empty()).then_some(&video.context_mask[..]);
1261        let amask = (!audio.context_mask.is_empty()).then_some(&audio.context_mask[..]);
1262
1263        let mut prof = Prof::new();
1264        for (bi, blk) in self.blocks.iter().enumerate() {
1265            let mut pt = std::time::Instant::now();
1266            let v_msa = vt.triples(&blk.video.sst, dim, 0);
1267            let v_ca = vt.triples(&blk.video.sst, dim, 6);
1268            let v_mlp = vt.triples(&blk.video.sst, dim, 3);
1269            let a_msa = at.triples(&blk.audio.sst, a_dim, 0);
1270            let a_ca = at.triples(&blk.audio.sst, a_dim, 6);
1271            let a_mlp = at.triples(&blk.audio.sst, a_dim, 3);
1272
1273            // ---- video: self-attention, then prompt cross-attention ----
1274            pt = prof.tick(P_ADALN, pt);
1275            let mut vnorm = vec![0f32; n * dim];
1276            ada_zero_rows(&vx, &mut vnorm, n, dim, &v_msa, &vt.idx, pool);
1277            pt = prof.tick(P_MOD, pt);
1278            if bi == 0 {
1279                trace("v.b0.sa.in", &vnorm);
1280            }
1281            let vsa = blk
1282                .video
1283                .attn1
1284                .forward(&vnorm, n, &vnorm, n, Some(&v_pe), Some(&v_pe), None, pool);
1285            if bi == 0 {
1286                trace("v.b0.sa.out", &vsa);
1287            }
1288            pt = prof.tick(P_SELF, pt);
1289            let mut vnormed = vec![0f32; n * dim];
1290            post_sa_rows(&mut vx, &vsa, &mut vnormed, n, dim, &v_msa, &vt.idx, pool);
1291            let mut vq = vec![0f32; n * dim];
1292            affine_rows(&vnormed, &mut vq, n, dim, &v_ca, &vt.idx, pool);
1293            let vctx = modulate_kv(&video.context, video.ctx_len, dim, &blk.video.prompt_sst, vpt.row(0), pool);
1294            let vca = blk.video.attn2.forward(&vq, n, &vctx, video.ctx_len, None, None, vmask, pool);
1295            if bi == 0 {
1296                trace("v.b0.ca.in", &vq);
1297                trace("v.b0.ca.ctx", &vctx);
1298                trace("v.b0.ca.out", &vca);
1299            }
1300            add_gated(&mut vx, &vca, n, dim, &v_ca, &vt.idx, pool);
1301            pt = prof.tick(P_CROSS, pt);
1302
1303            // ---- audio: the same two steps ----
1304            let mut anorm = vec![0f32; m * a_dim];
1305            ada_zero_rows(&ax, &mut anorm, m, a_dim, &a_msa, &at.idx, pool);
1306            if bi == 0 {
1307                trace("a.b0.sa.in", &anorm);
1308            }
1309            let asa = blk
1310                .audio
1311                .attn1
1312                .forward(&anorm, m, &anorm, m, Some(&a_pe), Some(&a_pe), None, pool);
1313            if bi == 0 {
1314                trace("a.b0.sa.out", &asa);
1315            }
1316            let mut anormed = vec![0f32; m * a_dim];
1317            post_sa_rows(&mut ax, &asa, &mut anormed, m, a_dim, &a_msa, &at.idx, pool);
1318            let mut aq = vec![0f32; m * a_dim];
1319            affine_rows(&anormed, &mut aq, m, a_dim, &a_ca, &at.idx, pool);
1320            let actx = modulate_kv(&audio.context, audio.ctx_len, a_dim, &blk.audio.prompt_sst, apt.row(0), pool);
1321            let aca = blk.audio.attn2.forward(&aq, m, &actx, audio.ctx_len, None, None, amask, pool);
1322            if bi == 0 {
1323                trace("a.b0.ca.in", &aq);
1324                trace("a.b0.ca.ctx", &actx);
1325                trace("a.b0.ca.out", &aca);
1326            }
1327            add_gated(&mut ax, &aca, m, a_dim, &a_ca, &at.idx, pool);
1328            pt = prof.tick(P_CROSS, pt);
1329
1330            // ---- audio ↔ video, both directions off the pre-fusion state ----
1331            let vx_pre = vx.clone();
1332            let ax_pre = ax.clone();
1333            let a2v_vp = vxs.pairs(&blk.sst_a2v_video, dim, 0);
1334            let a2v_ap = axs.pairs(&blk.sst_a2v_audio, a_dim, 0);
1335            let a2v_v = ada_pair(&vx_pre, n, dim, &a2v_vp, &vxs.idx, pool);
1336            let a2v_a = ada_pair(&ax_pre, m, a_dim, &a2v_ap, &axs.idx, pool);
1337            let a2v = blk
1338                .a2v
1339                .forward(&a2v_v, n, &a2v_a, m, Some(&v_xpe), Some(&a_xpe), None, pool);
1340            if bi == 0 {
1341                trace("v.b0.a2v.in", &a2v_v);
1342                trace("v.b0.a2v.ctx", &a2v_a);
1343                trace("v.b0.a2v.out", &a2v);
1344            }
1345            let gate_a2v = gate_row(&blk.sst_a2v_video, dim, vgt.row(0));
1346            add_scaled(&mut vx, &a2v, n, dim, &gate_a2v, pool);
1347            let v2a_ap = axs.pairs(&blk.sst_a2v_audio, a_dim, 2);
1348            let v2a_vp = vxs.pairs(&blk.sst_a2v_video, dim, 2);
1349            let v2a_a = ada_pair(&ax_pre, m, a_dim, &v2a_ap, &axs.idx, pool);
1350            let v2a_v = ada_pair(&vx_pre, n, dim, &v2a_vp, &vxs.idx, pool);
1351            let v2a = blk
1352                .v2a
1353                .forward(&v2a_a, m, &v2a_v, n, Some(&a_xpe), Some(&v_xpe), None, pool);
1354            if bi == 0 {
1355                trace("a.b0.v2a.in", &v2a_a);
1356                trace("a.b0.v2a.ctx", &v2a_v);
1357                trace("a.b0.v2a.out", &v2a);
1358            }
1359            let gate_v2a = gate_row(&blk.sst_a2v_audio, a_dim, agt.row(0));
1360            add_scaled(&mut ax, &v2a, m, a_dim, &gate_v2a, pool);
1361            pt = prof.tick(P_FUSE, pt);
1362
1363            // ---- feed-forward ----
1364            let mut vsc = vec![0f32; n * dim];
1365            ada_zero_rows(&vx, &mut vsc, n, dim, &v_mlp, &vt.idx, pool);
1366            let vff = blk.video.ff(&vsc, n, pool);
1367            if bi == 0 {
1368                trace("v.b0.ff.in", &vsc);
1369                trace("v.b0.ff.out", &vff);
1370            }
1371            add_gated(&mut vx, &vff, n, dim, &v_mlp, &vt.idx, pool);
1372            let mut asc = vec![0f32; m * a_dim];
1373            ada_zero_rows(&ax, &mut asc, m, a_dim, &a_mlp, &at.idx, pool);
1374            let aff = blk.audio.ff(&asc, m, pool);
1375            if bi == 0 {
1376                trace("a.b0.ff.in", &asc);
1377                trace("a.b0.ff.out", &aff);
1378            }
1379            add_gated(&mut ax, &aff, m, a_dim, &a_mlp, &at.idx, pool);
1380            pt = prof.tick(P_FF, pt);
1381            trace(&format!("v.block{bi}"), &vx);
1382            trace(&format!("a.block{bi}"), &ax);
1383        }
1384
1385        prof.report();
1386
1387        // --- output head: LayerNorm (no affine), adaLN, projection --------
1388        let vout = head(&vx, n, dim, &self.sst_out, &vt, &self.proj_out, pool);
1389        let aout = head(&ax, m, a_dim, &self.a_sst_out, &at, &self.a_proj_out, pool);
1390        trace("v.out", &vout);
1391        trace("a.out", &aout);
1392        (vout, aout)
1393    }
1394}
1395
1396/// `prompt_scale_shift_table` plus the prompt adaLN row, modulating the
1397/// cross-attention K/V — the same modulation for every context token.
1398fn modulate_kv(
1399    ctx: &[f32],
1400    len: usize,
1401    dim: usize,
1402    table: &[f32],
1403    extra: &[f32],
1404    pool: Option<&Pool>,
1405) -> Vec<f32> {
1406    let mut out = vec![0f32; len * dim];
1407    let shift: Vec<f32> = (0..dim).map(|d| table[d] + extra[d]).collect();
1408    let scale: Vec<f32> = (0..dim).map(|d| table[dim + d] + extra[dim + d]).collect();
1409    // A thousand prompt tokens by four thousand channels, rebuilt in every
1410    // one of forty-eight blocks: three hundred million writes a step, which
1411    // is not something to do on one thread.
1412    let dst = Shared(out.as_mut_ptr());
1413    rows(pool, len, &|s, e| {
1414        let r = unsafe { dst.at(s * dim, (e - s) * dim) };
1415        for (row, i) in r.chunks_exact_mut(dim).zip(s..e) {
1416            for d in 0..dim {
1417                row[d] = ctx[i * dim + d] * (1.0 + scale[d]) + shift[d];
1418            }
1419        }
1420    });
1421    out
1422}
1423
1424
1425/// `ada_zero` with an A↔V `(scale, shift)` pair per distinct timestep.
1426fn ada_pair(
1427    x: &[f32],
1428    n: usize,
1429    dim: usize,
1430    pairs: &[[Vec<f32>; 2]],
1431    idx: &[usize],
1432    pool: Option<&Pool>,
1433) -> Vec<f32> {
1434    let mut out = vec![0f32; n * dim];
1435    let dst = Shared(out.as_mut_ptr());
1436    rows(pool, n, &|s, e| {
1437        let r = unsafe { dst.at(s * dim, (e - s) * dim) };
1438        for (row, i) in r.chunks_exact_mut(dim).zip(s..e) {
1439            let p = &pairs[idx[i]];
1440            rms_plain(&x[i * dim..(i + 1) * dim], row);
1441            for d in 0..dim {
1442                row[d] = row[d] * (1.0 + p[0][d]) + p[1][d];
1443            }
1444        }
1445    });
1446    out
1447}
1448
1449/// The single gate row of an A↔V table — row 4 of `[5, dim]`, plus the
1450/// gate adaLN's own output.
1451fn gate_row(table: &[f32], dim: usize, extra: &[f32]) -> Vec<f32> {
1452    (0..dim).map(|d| table[4 * dim + d] + extra[d]).collect()
1453}
1454
1455/// The output head: LayerNorm without affine, the final scale/shift pair
1456/// (both offset by the same embedded timestep), then the projection.
1457fn head(
1458    x: &[f32],
1459    n: usize,
1460    dim: usize,
1461    sst: &[f32],
1462    ts: &TsTable,
1463    proj: &Lin,
1464    pool: Option<&Pool>,
1465) -> Vec<f32> {
1466    let mut y = vec![0f32; n * dim];
1467    let dst = Shared(y.as_mut_ptr());
1468    rows(pool, n, &|s, e| {
1469        let r = unsafe { dst.at(s * dim, (e - s) * dim) };
1470        let mut ln = vec![0f32; dim];
1471        for (row, i) in r.chunks_exact_mut(dim).zip(s..e) {
1472            let emb = ts.emb_row(ts.idx[i.min(ts.idx.len() - 1)]);
1473            layer_norm(&x[i * dim..(i + 1) * dim], &mut ln);
1474            for d in 0..dim {
1475                row[d] = ln[d] * (1.0 + sst[dim + d] + emb[d]) + sst[d] + emb[d];
1476            }
1477        }
1478    });
1479    proj.apply(&y, n, pool)
1480}