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