Skip to main content

cortiq_engine/
audiovae.rs

1//! MiniMax-H3's audio VAE decoder: BigVGAN at 32 kHz, stereo.
2//!
3//! 32 latent channels at 40 frames a second become a waveform at 800
4//! samples a frame, through seven transposed-convolution stages and
5//! their AMP residual blocks. The two stereo channels are two
6//! independent mono passes, which is how the reference batches them.
7//!
8//! The activations are the interesting part and the easy thing to get
9//! subtly wrong: every nonlinearity is wrapped in a 2× kaiser-sinc
10//! upsample, the pointwise SnakeBeta, and a 2× lowpass back down. The
11//! filter is designed here rather than shipped, from the same
12//! `kaiser_sinc_filter1d(cutoff, half_width, 12)` the reference calls,
13//! so it cannot drift out of step with a checkpoint that does not
14//! contain it.
15
16use crate::pool::Pool;
17
18/// Where an audio decode goes (`CMF_AVAE_TIME=1`). The video decoder
19/// went a whole session untuned because nothing measured it; this one
20/// already misled once, when the shape of the per-channel FIR promised
21/// more than the 9.2 s → 8.1 s it delivered.
22pub static AVAE_TIME: [std::sync::atomic::AtomicU64; 6] = [
23    std::sync::atomic::AtomicU64::new(0),
24    std::sync::atomic::AtomicU64::new(0),
25    std::sync::atomic::AtomicU64::new(0),
26    std::sync::atomic::AtomicU64::new(0),
27    std::sync::atomic::AtomicU64::new(0),
28    std::sync::atomic::AtomicU64::new(0),
29];
30
31fn atime_on() -> bool {
32    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
33    *ON.get_or_init(|| std::env::var("CMF_AVAE_TIME").is_ok())
34}
35
36fn atime(slot: usize, t: std::time::Instant) {
37    if atime_on() {
38        AVAE_TIME[slot].fetch_add(
39            t.elapsed().as_micros() as u64,
40            std::sync::atomic::Ordering::Relaxed,
41        );
42    }
43}
44
45/// One line per phase, sorted by cost.
46pub fn avae_time_report() -> Option<String> {
47    if !atime_on() {
48        return None;
49    }
50    const NAMES: [&str; 6] = [
51        "dec_in",
52        "conv_pre",
53        "upsamples",
54        "resblocks",
55        "act_post",
56        "conv_post",
57    ];
58    let mut v: Vec<(u64, &str)> = AVAE_TIME
59        .iter()
60        .map(|a| a.load(std::sync::atomic::Ordering::Relaxed))
61        .zip(NAMES)
62        .collect();
63    let total: u64 = v.iter().map(|(u, _)| u).sum();
64    if total == 0 {
65        return None;
66    }
67    v.sort_by(|a, b| b.0.cmp(&a.0));
68    let mut out = format!("audio vae phases (total {:.1} s):\n", total as f64 / 1e6);
69    for (us, name) in v {
70        out.push_str(&format!(
71            "  {name:<12} {:>6.1} s  {:>5.1}%\n",
72            us as f64 / 1e6,
73            100.0 * us as f64 / total as f64
74        ));
75    }
76    Some(out)
77}
78use cortiq_core::CmfModel;
79use std::sync::Arc;
80
81/// Both resampling filters in the alias-free activation are designed at
82/// this kernel length.
83const FILTER_LEN: usize = 12;
84
85pub(crate) struct Conv1d {
86    w: Vec<f32>, // [out, in, k]
87    b: Option<Vec<f32>>,
88    out_ch: usize,
89    in_ch: usize,
90    k: usize,
91    pad: usize,
92    dilation: usize,
93}
94
95impl Conv1d {
96    pub(crate) fn load(
97        model: &Arc<CmfModel>,
98        name: &str,
99        pad: usize,
100        dilation: usize,
101    ) -> Result<Self, String> {
102        let e = model
103            .tensor(&format!("{name}.weight"))
104            .ok_or_else(|| format!("missing {name}.weight"))?;
105        let w = crate::dit::cmf_f32(model, &format!("{name}.weight"))?;
106        let b = crate::dit::cmf_f32(model, &format!("{name}.bias")).ok();
107        Ok(Self {
108            out_ch: e.shape[0],
109            in_ch: e.shape[1],
110            k: e.shape[2],
111            w,
112            b,
113            pad,
114            dilation,
115        })
116    }
117
118    /// `x` is `[in_ch, n]`; the result is `[out_ch, n]` for the
119    /// paddings used here (all `same`).
120    pub(crate) fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
121        let out_n = (n + 2 * self.pad).saturating_sub(self.dilation * (self.k - 1));
122        let mut out = vec![0f32; self.out_ch * out_n];
123        let ptr = SendPtr(out.as_mut_ptr());
124        // Each (channel, time slice) pair is independent, so time is
125        // tiled until there are enough rows for any pool. Kept because
126        // it is free and bit-identical — but MEASURED SMALL: 8.6 s →
127        // 8.2 s on a stage that is 95.4% these convolutions. That is
128        // the finding. The resblocks are not starved of parallelism,
129        // they are arithmetic: ~8 s of dilated convolution on the CPU
130        // while the card is idle. The next move is the device, not a
131        // finer split — everything else in this render already went
132        // that way, and this is the last host-bound stage left.
133        //
134        // The shape it wants, so the next pass is implementation and not
135        // research: this convolution IS a GEMM under im2col. Build
136        // `[in_ch·k × out_n]` where row `(i, j)` holds
137        // `x[i, t + j·dilation - pad]` (zero outside), and the weights
138        // are ALREADY `[out_ch × in_ch·k]` in exactly that order —
139        // `w[(o·in_ch + i)·k + j]` — so nothing needs repacking. Then
140        // `out = W · col` with a bias per row. im2col is a gather, which
141        // the card does far better than it does the branch in this loop.
142        //
143        // The f32 device GEMM already exists and is public INSIDE the
144        // backend — `gpu_wgpu::gemm_nt_f32(x, w, y, n, k, m)`, tensor
145        // cores when the card has them. It is simply not re-exported
146        // through `gpu.rs`, which is where every other caller goes. Two
147        // conditions come with it and both suit this decoder: it refuses
148        // under `CMF_BAKE_GPU=0` or strict-f32, and it refuses jobs
149        // below n·k·m = 4M — these convolutions are far above that
150        // (out_ch × in_ch·k × out_n runs to hundreds of millions).
151        // So the work is: a facade re-export, an im2col buffer, and a
152        // parity check against this loop.
153        // im2col + the device GEMM: `out[out_ch × out_n] = W · col`,
154        // with W already `[out_ch × in_ch·k]` in the order this loop
155        // reads it. Opt-in (`CMF_AVAE_CONV_GPU=1`) until measured — the
156        // column buffer is in_ch·k × out_n floats, which is the price.
157        if std::env::var("CMF_AVAE_CONV_GPU").as_deref() != Ok("0") && crate::gpu::enabled_here() {
158            let kk = self.in_ch * self.k;
159            // First ask the device to expand the columns itself. That is
160            // strictly less work than the host arm below: `x` is k times
161            // smaller than the column buffer, the transposed copy is not
162            // built at all, and the tiling the 2 GiB binding limit forces
163            // happens without a host allocation per tile. The host arm
164            // stays for the backends and shapes the kernel refuses.
165            {
166                let mut yt = vec![0f32; out_n * self.out_ch];
167                if crate::gpu::conv1d_gemm(
168                    x,
169                    &self.w,
170                    self.in_ch,
171                    self.out_ch,
172                    n,
173                    self.k,
174                    self.pad,
175                    self.dilation,
176                    out_n,
177                    &mut yt,
178                ) {
179                    // [out_n × out_ch] back to channel-major with the bias,
180                    // the channels over the pool (a long render's last
181                    // stages are tens of millions of strided reads)
182                    let back = |lo: usize, hi: usize| {
183                        for o in lo..hi {
184                            let bias = self.b.as_ref().map_or(0.0, |b| b[o]);
185                            // SAFETY: workers own disjoint output channels.
186                            let dst = unsafe { ptr.row(o * out_n, out_n) };
187                            for (t, d) in dst.iter_mut().enumerate() {
188                                *d = yt[t * self.out_ch + o] + bias;
189                            }
190                        }
191                    };
192                    match pool {
193                        Some(p) => p.run_rows(self.out_ch, &back),
194                        None => back(0, self.out_ch),
195                    }
196                    return out;
197                }
198            }
199            // The column buffer is kk x out_n floats and out_n is the
200            // AUDIO length, so it grows with the song: 20 s through this
201            // decoder's last stage wants 2.37 GB and Vulkan refuses a
202            // binding over 2 GiB — `Buffer binding range 2147483648
203            // exceeds limit 2147483644`, which is what a 20-second render
204            // died on. Tile the time axis so one pass always fits, and
205            // keep the device arm instead of falling back to the host for
206            // exactly the lengths that need it most.
207            const MAX_COL_FLOATS: usize = 96 << 20; // 384 MB a tile
208            let span = (MAX_COL_FLOATS / kk.max(1)).max(1).min(out_n);
209            if span < out_n {
210                let mut done = 0usize;
211                while done < out_n {
212                    let w = span.min(out_n - done);
213                    // Build the window with its zeros already in it, so
214                    // the sub-convolution runs at pad = 0 and both edges
215                    // are right by construction: a tile that clamped its
216                    // input instead would lose the right-hand padding the
217                    // untiled path applies, and the tail would be short.
218                    let need = w + self.dilation * (self.k - 1);
219                    let mut sub = vec![0f32; self.in_ch * need];
220                    for i in 0..self.in_ch {
221                        let src = &x[i * n..(i + 1) * n];
222                        let dst = &mut sub[i * need..(i + 1) * need];
223                        for (u, d) in dst.iter_mut().enumerate() {
224                            let p = (done + u) as isize - self.pad as isize;
225                            if p >= 0 && (p as usize) < n {
226                                *d = src[p as usize];
227                            }
228                        }
229                    }
230                    let piece = Self {
231                        w: self.w.clone(),
232                        b: self.b.clone(),
233                        out_ch: self.out_ch,
234                        in_ch: self.in_ch,
235                        k: self.k,
236                        pad: 0,
237                        dilation: self.dilation,
238                    }
239                    .apply(&sub, need, pool);
240                    for o in 0..self.out_ch {
241                        // SAFETY: single-threaded here.
242                        let dst = unsafe { ptr.row(o * out_n + done, w) };
243                        dst.copy_from_slice(&piece[o * w..(o + 1) * w]);
244                    }
245                    done += w;
246                }
247                return out;
248            }
249            if let Some(col_len) = kk.checked_mul(out_n) {
250                let mut col = vec![0f32; col_len];
251                let pc = SendPtr(col.as_mut_ptr());
252                let fill = |lo: usize, hi: usize| {
253                    for r in lo..hi {
254                        let (i, j) = (r / self.k, r % self.k);
255                        let src = &x[i * n..(i + 1) * n];
256                        // SAFETY: workers own disjoint rows of `col`.
257                        let dst = unsafe { pc.row(r * out_n, out_n) };
258                        for (t, d) in dst.iter_mut().enumerate() {
259                            let p = (t + j * self.dilation) as isize - self.pad as isize;
260                            *d = if p >= 0 && (p as usize) < n {
261                                src[p as usize]
262                            } else {
263                                0.0
264                            };
265                        }
266                    }
267                };
268                match pool {
269                    Some(p) => p.run_rows(kk, &fill),
270                    None => fill(0, kk),
271                }
272                // colᵀ is [out_n × kk]; the GEMM wants x[n×k]·wᵀ[m×k],
273                // so n = out_n, k = kk, m = out_ch — and `col` is built
274                // row-major over kk, so it is transposed on the way in.
275                let mut colt = vec![0f32; col_len];
276                for r in 0..kk {
277                    for t in 0..out_n {
278                        colt[t * kk + r] = col[r * out_n + t];
279                    }
280                }
281                let mut yt = vec![0f32; out_n * self.out_ch];
282                if crate::gpu::gemm_nt_f32(&colt, &self.w, &mut yt, out_n, kk, self.out_ch) {
283                    for o in 0..self.out_ch {
284                        let bias = self.b.as_ref().map_or(0.0, |b| b[o]);
285                        // SAFETY: single-threaded here.
286                        let dst = unsafe { ptr.row(o * out_n, out_n) };
287                        for (t, d) in dst.iter_mut().enumerate() {
288                            *d = yt[t * self.out_ch + o] + bias;
289                        }
290                    }
291                    return out;
292                }
293            }
294        }
295        let tiles = (128 / self.out_ch.max(1)).max(1);
296        let tile = out_n.div_ceil(tiles.max(1));
297        let rows = self.out_ch * tiles;
298        let work = |lo: usize, hi: usize| {
299            for r in lo..hi {
300                let o = r / tiles;
301                let t0 = (r - o * tiles) * tile;
302                if t0 >= out_n {
303                    continue;
304                }
305                let len = tile.min(out_n - t0);
306                // SAFETY: workers own disjoint (channel, time) slices.
307                let dst = unsafe { ptr.row(o * out_n + t0, len) };
308                let bias = self.b.as_ref().map_or(0.0, |b| b[o]);
309                dst.fill(bias);
310                for i in 0..self.in_ch {
311                    let ker =
312                        &self.w[(o * self.in_ch + i) * self.k..(o * self.in_ch + i + 1) * self.k];
313                    let src = &x[i * n..(i + 1) * n];
314                    for (tt, d) in dst.iter_mut().enumerate() {
315                        let t = t0 + tt;
316                        let mut acc = 0f32;
317                        for (j, &kv) in ker.iter().enumerate() {
318                            let p = (t + j * self.dilation) as isize - self.pad as isize;
319                            if p >= 0 && (p as usize) < n {
320                                acc += kv * src[p as usize];
321                            }
322                        }
323                        *d += acc;
324                    }
325                }
326            }
327        };
328        match pool {
329            Some(p) => p.run_rows(rows, &work),
330            None => work(0, rows),
331        }
332        out
333    }
334}
335
336pub(crate) struct ConvT1d {
337    w: Vec<f32>, // [in, out, k]
338    b: Vec<f32>,
339    in_ch: usize,
340    out_ch: usize,
341    k: usize,
342    pub(crate) stride: usize,
343    pad: usize,
344    /// Extra samples at the end (`output_padding`).
345    out_pad: usize,
346    /// `w` repacked `[out·k × in]` for [`Self::apply_gemm`], built on first use.
347    wt: std::sync::OnceLock<Vec<f32>>,
348}
349
350impl ConvT1d {
351    /// PyTorch's `ConvTranspose1d(.., kernel, stride, padding, output_padding)`.
352    pub(crate) fn load_padded(model: &Arc<CmfModel>, name: &str, stride: usize, pad: usize, out_pad: usize) -> Result<Self, String> {
353        let mut c = Self::load(model, name, stride)?;
354        c.pad = pad;
355        c.out_pad = out_pad;
356        Ok(c)
357    }
358
359    fn load(model: &Arc<CmfModel>, name: &str, stride: usize) -> Result<Self, String> {
360        let e = model
361            .tensor(&format!("{name}.weight"))
362            .ok_or_else(|| format!("missing {name}.weight"))?;
363        let (in_ch, out_ch, k) = (e.shape[0], e.shape[1], e.shape[2]);
364        Ok(Self {
365            w: crate::dit::cmf_f32(model, &format!("{name}.weight"))?,
366            b: crate::dit::cmf_f32(model, &format!("{name}.bias"))?,
367            in_ch,
368            out_ch,
369            k,
370            stride,
371            pad: (k - stride) / 2,
372            out_pad: 0,
373            wt: std::sync::OnceLock::new(),
374        })
375    }
376
377    /// The same transposed convolution as one GEMM and an overlap-add:
378    /// `y[t, (o, j)] = Σ_i x[i, t] · w[i, o, j]`, then
379    /// `out[o, t·stride + j - pad] += y[t, (o, j)]`. The GEMM goes to the
380    /// device when one is up (the repacked weight stays cached there) and
381    /// to the host's blocked GEMM otherwise — both far ahead of the
382    /// scatter loop in [`Self::apply`], which stays the reference.
383    pub(crate) fn apply_gemm(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
384        let (ic, oc, k, s) = (self.in_ch, self.out_ch, self.k, self.stride);
385        let full = (n - 1) * s + k;
386        let out_n = full + self.out_pad - 2 * self.pad;
387        let m = oc * k;
388        let wt = self.wt.get_or_init(|| {
389            let mut wt = vec![0f32; m * ic];
390            for i in 0..ic {
391                for o in 0..oc {
392                    for j in 0..k {
393                        wt[(o * k + j) * ic + i] = self.w[(i * oc + o) * k + j];
394                    }
395                }
396            }
397            wt
398        });
399        // time-major input [n × in]
400        let mut xt = vec![0f32; n * ic];
401        for i in 0..ic {
402            for (t, &v) in x[i * n..(i + 1) * n].iter().enumerate() {
403                xt[t * ic + i] = v;
404            }
405        }
406        // rows of y a pass: 64M floats at most, so no binding nears 2 GiB
407        let span = ((64usize << 20) / m.max(1)).clamp(1, n);
408        let mut y = vec![0f32; n * m];
409        let mut t0 = 0;
410        while t0 < n {
411            let r = span.min(n - t0);
412            let (xs, ys) = (&xt[t0 * ic..(t0 + r) * ic], &mut y[t0 * m..(t0 + r) * m]);
413            if !crate::gpu::gemm_nt_f32(xs, wt, ys, r, ic, m) {
414                crate::fcd_ops::gemm_nt(xs, wt, ys, r, ic, m, pool);
415            }
416            t0 += r;
417        }
418        let mut out = vec![0f32; oc * out_n];
419        let ptr = SendPtr(out.as_mut_ptr());
420        let work = |lo: usize, hi: usize| {
421            for o in lo..hi {
422                // SAFETY: workers own disjoint output channels.
423                let dst = unsafe { ptr.row(o * out_n, out_n) };
424                dst.fill(self.b[o]);
425                for t in 0..n {
426                    let src = &y[t * m + o * k..t * m + (o + 1) * k];
427                    let base = t * s;
428                    for (j, &v) in src.iter().enumerate() {
429                        let p = base + j;
430                        if p >= self.pad && p - self.pad < out_n {
431                            dst[p - self.pad] += v;
432                        }
433                    }
434                }
435            }
436        };
437        match pool {
438            Some(p) => p.run_rows(oc, &work),
439            None => work(0, oc),
440        }
441        out
442    }
443
444    pub(crate) fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
445        let full = (n - 1) * self.stride + self.k;
446        let out_n = full + self.out_pad - 2 * self.pad;
447        let mut out = vec![0f32; self.out_ch * out_n];
448        let ptr = SendPtr(out.as_mut_ptr());
449        let work = |lo: usize, hi: usize| {
450            for o in lo..hi {
451                // SAFETY: workers own disjoint output channels.
452                let dst = unsafe { ptr.row(o * out_n, out_n) };
453                dst.fill(self.b[o]);
454                for i in 0..self.in_ch {
455                    let ker =
456                        &self.w[(i * self.out_ch + o) * self.k..(i * self.out_ch + o + 1) * self.k];
457                    let src = &x[i * n..(i + 1) * n];
458                    for (t, &sv) in src.iter().enumerate() {
459                        if sv == 0.0 {
460                            continue;
461                        }
462                        let base = t * self.stride;
463                        for (j, &kv) in ker.iter().enumerate() {
464                            let p = base + j;
465                            if p >= self.pad && p - self.pad < out_n {
466                                dst[p - self.pad] += sv * kv;
467                            }
468                        }
469                    }
470                }
471            }
472        };
473        match pool {
474            Some(p) => p.run_rows(self.out_ch, &work),
475            None => work(0, self.out_ch),
476        }
477        out
478    }
479}
480
481/// Plain Snake, `x + sin²(α·x)/α`, with α used EXACTLY as stored.
482///
483/// The distinction from `SnakeBeta` below is not cosmetic: H3's BigVGAN
484/// keeps α and β in log scale and this file exponentiates them on load,
485/// while MiniMax-Music-3's decoder reads its α straight
486/// (`(alpha + 1e-9).reciprocal() * sin(alpha * x)**2`). Feeding one
487/// model's parameters to the other's loader silently raises the
488/// activation to an exponent, and the only symptom is worse audio.
489pub(crate) struct Snake {
490    alpha: Vec<f32>,
491}
492
493impl Snake {
494    pub(crate) fn load(model: &Arc<CmfModel>, name: &str) -> Result<Self, String> {
495        Ok(Self {
496            alpha: crate::dit::cmf_f32(model, &format!("{name}.alpha"))?,
497        })
498    }
499
500    pub(crate) fn apply(&self, x: &mut [f32], n: usize) {
501        for (c, row) in x.chunks_exact_mut(n).enumerate() {
502            let a = self.alpha[c];
503            let inv = 1.0 / (a + 1e-9);
504            for v in row.iter_mut() {
505                let s = (a * *v).sin();
506                *v += s * s * inv;
507            }
508        }
509    }
510
511    /// [`Self::apply`] with the channels spread over the pool: the long
512    /// stages of a decoder run 10⁷–10⁸ sines, which one thread takes
513    /// seconds over.
514    pub(crate) fn apply_pool(&self, x: &mut [f32], n: usize, pool: Option<&Pool>) {
515        let Some(p) = pool else { return self.apply(x, n) };
516        let ch = x.len() / n.max(1);
517        let ptr = SendPtr(x.as_mut_ptr());
518        p.run_rows(ch, &|lo, hi| {
519            for c in lo..hi {
520                // SAFETY: workers own disjoint channels.
521                let row = unsafe { ptr.row(c * n, n) };
522                let a = self.alpha[c];
523                let inv = 1.0 / (a + 1e-9);
524                for v in row.iter_mut() {
525                    let s = (a * *v).sin();
526                    *v += s * s * inv;
527                }
528            }
529        });
530    }
531}
532
533/// One residual unit: Snake → dilated 7-tap → Snake → 1-tap, added back.
534struct DavUnit {
535    a1: Snake,
536    c1: Conv1d,
537    a2: Snake,
538    c2: Conv1d,
539}
540
541impl DavUnit {
542    fn load(model: &Arc<CmfModel>, p: &str, dilation: usize) -> Result<Self, String> {
543        Ok(Self {
544            a1: Snake::load(model, &format!("{p}.block.0"))?,
545            c1: Conv1d::load(model, &format!("{p}.block.1"), 3 * dilation, dilation)?,
546            a2: Snake::load(model, &format!("{p}.block.2"))?,
547            c2: Conv1d::load(model, &format!("{p}.block.3"), 0, 1)?,
548        })
549    }
550
551    fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> Vec<f32> {
552        let mut h = x.to_vec();
553        self.a1.apply(&mut h, n);
554        let mut h = self.c1.apply(&h, n, pool);
555        self.a2.apply(&mut h, n);
556        let r = self.c2.apply(&h, n, pool);
557        // Same padding throughout, so the residual lines up without the
558        // reference's centre-crop; assert rather than trust that.
559        debug_assert_eq!(r.len(), x.len());
560        x.iter().zip(&r).map(|(a, b)| a + b).collect()
561    }
562}
563
564/// Snake → transposed conv (×stride) → three residual units at
565/// dilations 1, 3, 9.
566struct DavStage {
567    act: Snake,
568    up: ConvT1d,
569    units: Vec<DavUnit>,
570}
571
572impl DavStage {
573    fn load(model: &Arc<CmfModel>, p: &str, stride: usize) -> Result<Self, String> {
574        Ok(Self {
575            act: Snake::load(model, &format!("{p}.block.0"))?,
576            up: ConvT1d::load(model, &format!("{p}.block.1"), stride)?,
577            units: [1usize, 3, 9]
578                .iter()
579                .enumerate()
580                .map(|(i, &d)| DavUnit::load(model, &format!("{p}.block.{}", i + 2), d))
581                .collect::<Result<_, _>>()?,
582        })
583    }
584
585    fn apply(&self, x: &[f32], n: usize, pool: Option<&Pool>) -> (Vec<f32>, usize) {
586        let mut h = x.to_vec();
587        self.act.apply(&mut h, n);
588        let mut h = self.up.apply(&h, n, pool);
589        let n = n * self.up.stride;
590        for u in &self.units {
591            h = u.apply(&h, n, pool);
592        }
593        (h, n)
594    }
595}
596
597/// MiniMax-Music-3's DAV decoder: latent → 44.1 kHz stereo.
598///
599/// The 128 latent channels are a STEREO PAIR of 64: the reference folds
600/// `[b, 128, t]` to `[b·2, 64, t]`, decodes mono, and unfolds. Reading
601/// 128 as one wide latent — which the vocoder config's `latent_channels`
602/// invites — decodes noise at half the length.
603pub struct Music3Dav {
604    dec_in: Conv1d,
605    conv_pre: Conv1d,
606    stages: Vec<DavStage>,
607    act_post: Snake,
608    conv_post: Conv1d,
609}
610
611impl Music3Dav {
612    pub const STRIDES: [usize; 4] = [8, 8, 4, 2];
613    /// Audio samples per latent frame: 8·8·4·2.
614    pub const HOP: usize = 512;
615    pub const SAMPLE_RATE: usize = 44100;
616
617    pub fn from_cmf(model: &Arc<CmfModel>) -> Result<Self, String> {
618        Ok(Self {
619            dec_in: Conv1d::load(model, "mvae.dec_in_proj", 0, 1)?,
620            conv_pre: Conv1d::load(model, "mvae.decoder.model.0", 3, 1)?,
621            stages: Self::STRIDES
622                .iter()
623                .enumerate()
624                .map(|(i, &s)| DavStage::load(model, &format!("mvae.decoder.model.{}", i + 1), s))
625                .collect::<Result<_, _>>()?,
626            act_post: Snake::load(model, "mvae.decoder.model.5")?,
627            conv_post: Conv1d::load(model, "mvae.decoder.model.6", 3, 1)?,
628        })
629    }
630
631    /// `latent` is `[128, frames]`; the result is interleaved stereo of
632    /// `frames · 512` samples per channel.
633    pub fn decode(&self, latent: &[f32], frames: usize, pool: Option<&Pool>) -> Vec<f32> {
634        let mut chans: Vec<Vec<f32>> = Vec::with_capacity(2);
635        for half in 0..2 {
636            let src = &latent[half * 64 * frames..(half + 1) * 64 * frames];
637            let mut h = self.dec_in.apply(src, frames, pool);
638            h = self.conv_pre.apply(&h, frames, pool);
639            let mut n = frames;
640            for st in &self.stages {
641                let (nh, nn) = st.apply(&h, n, pool);
642                h = nh;
643                n = nn;
644            }
645            self.act_post.apply(&mut h, n);
646            let w = self.conv_post.apply(&h, n, pool);
647            // The reference ends in tanh; without it a loud latent
648            // clips as a wrap rather than a limit.
649            chans.push(w.iter().map(|v| v.tanh()).collect());
650        }
651        let n = chans[0].len();
652        let mut out = vec![0f32; n * 2];
653        for (i, o) in out.chunks_exact_mut(2).enumerate() {
654            o[0] = chans[0][i];
655            o[1] = chans[1][i];
656        }
657        out
658    }
659}
660
661/// `x + sin²(α·x)/β`, with α and β stored in log scale.
662struct SnakeBeta {
663    alpha: Vec<f32>,
664    beta: Vec<f32>,
665}
666
667impl SnakeBeta {
668    fn load(model: &Arc<CmfModel>, name: &str) -> Result<Self, String> {
669        Ok(Self {
670            alpha: crate::dit::cmf_f32(model, &format!("{name}.alpha"))?
671                .iter()
672                .map(|v| v.exp())
673                .collect(),
674            beta: crate::dit::cmf_f32(model, &format!("{name}.beta"))?
675                .iter()
676                .map(|v| v.exp())
677                .collect(),
678        })
679    }
680
681    fn apply(&self, x: &mut [f32], n: usize) {
682        for (c, row) in x.chunks_exact_mut(n).enumerate() {
683            let (a, b) = (self.alpha[c], 1.0 / (self.beta[c] + 1e-9));
684            for v in row.iter_mut() {
685                let s = (a * *v).sin();
686                *v += s * s * b;
687            }
688        }
689    }
690}
691
692fn bessel_i0(x: f64) -> f64 {
693    // Series; the argument here is ~4.7, where a dozen terms is exact
694    // to double precision.
695    let mut sum = 1.0;
696    let mut term = 1.0;
697    for k in 1..40 {
698        term *= (x / (2.0 * k as f64)).powi(2);
699        sum += term;
700        if term < 1e-18 * sum {
701            break;
702        }
703    }
704    sum
705}
706
707fn sinc(x: f64) -> f64 {
708    if x == 0.0 {
709        1.0
710    } else {
711        (std::f64::consts::PI * x).sin() / (std::f64::consts::PI * x)
712    }
713}
714
715/// The reference's `kaiser_sinc_filter1d`, normalized to unit sum.
716fn kaiser_sinc(cutoff: f64, half_width: f64, k: usize) -> Vec<f32> {
717    let half = k / 2;
718    let delta_f = 4.0 * half_width;
719    let a = 2.285 * (half as f64 - 1.0) * std::f64::consts::PI * delta_f + 7.95;
720    let beta = if a > 50.0 {
721        0.1102 * (a - 8.7)
722    } else if a >= 21.0 {
723        0.5842 * (a - 21.0).powf(0.4) + 0.078_86 * (a - 21.0)
724    } else {
725        0.0
726    };
727    let denom = bessel_i0(beta);
728    let n = k as f64 - 1.0;
729    let mut f: Vec<f64> = (0..k)
730        .map(|i| {
731            let r = (2.0 * i as f64 / n) - 1.0;
732            let win = bessel_i0(beta * (1.0 - r * r).max(0.0).sqrt()) / denom;
733            // even length: sample points sit on half-integers
734            let t = -(half as f64) + i as f64 + 0.5;
735            2.0 * cutoff * win * sinc(2.0 * cutoff * t)
736        })
737        .collect();
738    let s: f64 = f.iter().sum();
739    for v in f.iter_mut() {
740        *v /= s;
741    }
742    f.into_iter().map(|v| v as f32).collect()
743}
744
745/// Replicate-pad, then a per-channel FIR.
746///
747/// MEASURED, and smaller than it looked: parallelizing this took the
748/// audio stage 9.2 s → 8.1 s, output bit-identical. So the FIR is not
749/// where that stage's time goes — the rest is in the convolutions,
750/// which DO use the pool but split over OUTPUT CHANNELS, and this
751/// decoder narrows to a handful of them near the output where the
752/// samples are longest. Splitting those over TIME instead is the next
753/// thing to try, and it wants a phase profiler first: this decoder
754/// still has none.
755///
756/// Original note: the audio decoder is 9.2 s of a 95.6 s render — the same share the video decoder had
757/// before its host loops met the thread pool (38.3 s → 16.6 s). This
758/// function is the shape that fix wanted: every channel is independent
759/// and the whole thing runs on one thread. The convolutions above DO
760/// use the pool, but they split over OUTPUT CHANNELS, and this decoder
761/// narrows to a handful of them near the output — where the samples
762/// are longest and the parallelism collapses exactly when it is needed.
763///
764/// It needs a `pool` argument threaded from `Activation1d`/`AudioVae`
765/// and a per-worker `buf` instead of the shared one. Measure first with
766/// a phase profiler like `CMF_VAE3D_PROF`: this decoder has none, and
767/// the video one went untuned for a whole session precisely because
768/// nothing measured it.
769#[allow(clippy::too_many_arguments)]
770fn fir_pad(
771    x: &[f32],
772    ch: usize,
773    n: usize,
774    f: &[f32],
775    pad_l: usize,
776    pad_r: usize,
777    stride: usize,
778    pool: Option<&Pool>,
779) -> (Vec<f32>, usize) {
780    let padded = n + pad_l + pad_r;
781    let out_n = (padded - f.len()) / stride + 1;
782    let mut out = vec![0f32; ch * out_n];
783    struct P(*mut f32);
784    // SAFETY: each channel owns `out[c*out_n .. (c+1)*out_n]` and no
785    // two workers take the same channel.
786    unsafe impl Send for P {}
787    unsafe impl Sync for P {}
788    impl P {
789        // Through a method, so the closure captures the WRAPPER and not
790        // the bare pointer — 2021 captures disjoint fields, and a
791        // captured `*mut f32` is neither Send nor Sync.
792        #[allow(clippy::mut_from_ref)]
793        pub(crate) unsafe fn row(&self, off: usize, len: usize) -> &mut [f32] {
794            unsafe { std::slice::from_raw_parts_mut(self.0.add(off), len) }
795        }
796    }
797    let po = P(out.as_mut_ptr());
798    let work = |lo: usize, hi: usize| {
799        // Per worker, not shared: the old single `buf` is what kept this
800        // on one thread.
801        let mut buf = vec![0f32; padded];
802        for c in lo..hi {
803            let src = &x[c * n..(c + 1) * n];
804            for (i, b) in buf.iter_mut().enumerate() {
805                let p = i as isize - pad_l as isize;
806                *b = src[p.clamp(0, n as isize - 1) as usize];
807            }
808            let dst = unsafe { po.row(c * out_n, out_n) };
809            for (t, d) in dst.iter_mut().enumerate() {
810                let mut acc = 0f32;
811                for (j, &kv) in f.iter().enumerate() {
812                    acc += kv * buf[t * stride + j];
813                }
814                *d = acc;
815            }
816        }
817    };
818    match pool {
819        Some(p) => p.run_rows(ch, &work),
820        None => work(0, ch),
821    }
822    (out, out_n)
823}
824
825/// Upsample ×2, apply, downsample ×2 — the anti-aliased activation.
826struct Activation1d {
827    act: SnakeBeta,
828    up: Vec<f32>,
829    down: Vec<f32>,
830}
831
832impl Activation1d {
833    /// `name` is the Activation1d module, not its `.act`. The release
834    /// ships both resampling filters as buffers — 254 of them — so read
835    /// them rather than re-designing them, and keep `kaiser_sinc` as
836    /// the fallback for a checkpoint that drops them.
837    fn load(model: &Arc<CmfModel>, name: &str) -> Result<Self, String> {
838        let designed = || kaiser_sinc(0.25, 0.3, FILTER_LEN);
839        Ok(Self {
840            act: SnakeBeta::load(model, &format!("{name}.act"))?,
841            up: crate::dit::cmf_f32(model, &format!("{name}.upsample.filter"))
842                .unwrap_or_else(|_| designed()),
843            down: crate::dit::cmf_f32(model, &format!("{name}.downsample.lowpass.filter"))
844                .unwrap_or_else(|_| designed()),
845        })
846    }
847
848    fn apply(&self, x: &[f32], ch: usize, n: usize, pool: Option<&Pool>) -> (Vec<f32>, usize) {
849        // conv_transpose1d(pad(x, 5, 5), filter, stride 2) · 2, then the
850        // 15-sample margins the reference trims off each end.
851        let pad = FILTER_LEN / 2 - 1;
852        let pad_l = pad * 2 + (FILTER_LEN - 2) / 2;
853        let pad_r = pad * 2 + (FILTER_LEN - 2).div_ceil(2);
854        let pn = n + 2 * pad;
855        let full = (pn - 1) * 2 + FILTER_LEN;
856        let mut up = vec![0f32; ch * full];
857        for c in 0..ch {
858            let src = &x[c * n..(c + 1) * n];
859            let dst = &mut up[c * full..(c + 1) * full];
860            for i in 0..pn {
861                let p = i as isize - pad as isize;
862                let v = src[p.clamp(0, n as isize - 1) as usize] * 2.0;
863                if v == 0.0 {
864                    continue;
865                }
866                for (j, &kv) in self.up.iter().enumerate() {
867                    dst[i * 2 + j] += v * kv;
868                }
869            }
870        }
871        let keep = full - pad_l - pad_r;
872        let mut mid = vec![0f32; ch * keep];
873        for c in 0..ch {
874            mid[c * keep..(c + 1) * keep]
875                .copy_from_slice(&up[c * full + pad_l..c * full + pad_l + keep]);
876        }
877        self.act.apply(&mut mid, keep);
878        // LowPassFilter1d at stride 2: even kernel pads 5 left, 6 right.
879        fir_pad(
880            &mid,
881            ch,
882            keep,
883            &self.down,
884            FILTER_LEN / 2 - 1,
885            FILTER_LEN / 2,
886            2,
887            pool,
888        )
889    }
890}
891
892struct AmpBlock {
893    convs1: Vec<Conv1d>,
894    convs2: Vec<Conv1d>,
895    acts: Vec<Activation1d>,
896}
897
898pub struct AudioVae {
899    dec_in: Conv1d,
900    conv_pre: Conv1d,
901    ups: Vec<ConvT1d>,
902    resblocks: Vec<AmpBlock>,
903    act_post: Activation1d,
904    conv_post: Conv1d,
905    latents_mean: Vec<f32>,
906    latents_std: Vec<f32>,
907    pool: Option<Arc<Pool>>,
908    n_kernels: usize,
909    pub sample_rate: usize,
910}
911
912fn get_padding(k: usize, d: usize) -> usize {
913    (k * d - d) / 2
914}
915
916impl AudioVae {
917    pub fn from_cmf(model: &Arc<CmfModel>) -> Result<Self, String> {
918        let cfg: serde_json::Value = serde_json::from_slice(
919            model
920                .tensor_bytes("avae.config_json")
921                .map_err(|e| e.to_string())?,
922        )
923        .map_err(|e| format!("avae.config_json: {e}"))?;
924        let rates: Vec<usize> = cfg["upsample_rates"]
925            .as_array()
926            .ok_or("upsample_rates")?
927            .iter()
928            .map(|v| v.as_u64().unwrap_or(1) as usize)
929            .collect();
930        let rk: Vec<usize> = cfg["resblock_kernel_sizes"]
931            .as_array()
932            .ok_or("resblock_kernel_sizes")?
933            .iter()
934            .map(|v| v.as_u64().unwrap_or(3) as usize)
935            .collect();
936        let rd: Vec<Vec<usize>> = cfg["resblock_dilation_sizes"]
937            .as_array()
938            .ok_or("resblock_dilation_sizes")?
939            .iter()
940            .map(|a| {
941                a.as_array()
942                    .unwrap()
943                    .iter()
944                    .map(|v| v.as_u64().unwrap_or(1) as usize)
945                    .collect()
946            })
947            .collect();
948
949        let mut ups = Vec::new();
950        for (i, &u) in rates.iter().enumerate() {
951            ups.push(ConvT1d::load(model, &format!("avae.decoder.ups.{i}.0"), u)?);
952        }
953        let mut resblocks = Vec::new();
954        for i in 0..rates.len() {
955            for (j, (&k, d)) in rk.iter().zip(&rd).enumerate() {
956                let p = format!("avae.decoder.resblocks.{}", i * rk.len() + j);
957                let convs1 = (0..d.len())
958                    .map(|q| {
959                        Conv1d::load(
960                            model,
961                            &format!("{p}.convs1.{q}"),
962                            get_padding(k, d[q]),
963                            d[q],
964                        )
965                    })
966                    .collect::<Result<Vec<_>, _>>()?;
967                let convs2 = (0..d.len())
968                    .map(|q| Conv1d::load(model, &format!("{p}.convs2.{q}"), get_padding(k, 1), 1))
969                    .collect::<Result<Vec<_>, _>>()?;
970                let acts = (0..convs1.len() + convs2.len())
971                    .map(|q| Activation1d::load(model, &format!("{p}.activations.{q}")))
972                    .collect::<Result<Vec<_>, _>>()?;
973                resblocks.push(AmpBlock {
974                    convs1,
975                    convs2,
976                    acts,
977                });
978            }
979        }
980        Ok(Self {
981            dec_in: Conv1d::load(model, "avae.dec_in_proj", 0, 1)?,
982            conv_pre: Conv1d::load(model, "avae.decoder.conv_pre", 3, 1)?,
983            ups,
984            resblocks,
985            act_post: Activation1d::load(model, "avae.decoder.activation_post")?,
986            conv_post: Conv1d::load(model, "avae.decoder.conv_post", 3, 1)?,
987            latents_mean: crate::dit::cmf_f32(model, "avae.latents_mean")?,
988            latents_std: crate::dit::cmf_f32(model, "avae.latents_std")?,
989            pool: Pool::from_env(),
990            n_kernels: rk.len(),
991            sample_rate: cfg["sample_rate"].as_u64().unwrap_or(32000) as usize,
992        })
993    }
994
995    /// Normalized latents `[C, 2, T]` → stereo `[2, L]` in [-1, 1].
996    ///
997    /// THE REMAINING WIN IS THIS LOOP: the two stereo channels are two
998    /// complete, independent decoder passes and they run one after the
999    /// other. That is a factor of two sitting outside the exact place
1000    /// the inside cannot use — the convolutions parallelize over output
1001    /// channels, and this decoder narrows to a handful of those near the
1002    /// output where the samples are longest (measured: parallelizing the
1003    /// per-channel FIR bought only 9.2 s → 8.1 s, so the time is in the
1004    /// convolutions, not the filter).
1005    ///
1006    /// The nesting question is ANSWERED, and the answer forbids the
1007    /// obvious version: `Pool` keeps ONE job slot (`inner.slot`), and
1008    /// `run()` writes it on the stated assumption that no job is in
1009    /// flight. Two concurrent callers would overwrite each other's job.
1010    /// So wrapping this loop in a `thread::scope` while the passes still
1011    /// call into the pool is a data race, not an optimization.
1012    ///
1013    /// Two shapes remain. Drive the pool from the OUTSIDE — one row per
1014    /// stereo channel, `None` inside — which is correct but caps the
1015    /// whole decode at two threads and would lose the wide layers what
1016    /// it wins the narrow ones. Or split the narrow convolutions over
1017    /// TIME instead of output channels, which keeps every thread busy
1018    /// at both ends. Measure before choosing: this decoder still has no
1019    /// phase profiler, and the FIR already proved the shape of the code
1020    /// is a poor guide to where its seconds are.
1021    pub fn decode(&self, z: &[f32], c: usize, t: usize) -> (Vec<f32>, usize) {
1022        let pool = self.pool.as_deref();
1023        let mut chans: Vec<Vec<f32>> = Vec::with_capacity(2);
1024        for ch in 0..2 {
1025            let mut lat = vec![0f32; c * t];
1026            for ci in 0..c {
1027                let (m, s) = (self.latents_mean[ci], self.latents_std[ci]);
1028                for ti in 0..t {
1029                    lat[ci * t + ti] = z[(ci * 2 + ch) * t + ti] * s + m;
1030                }
1031            }
1032            // `CMF_AVAE_PROF=1`: per-stage rms, to diff against the
1033            // reference stage by stage rather than at the waveform.
1034            let prof = std::env::var_os("CMF_AVAE_PROF").is_some();
1035            let rms = |x: &[f32]| {
1036                (x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / x.len() as f64).sqrt()
1037            };
1038            let tt = std::time::Instant::now();
1039            let mut x = self.dec_in.apply(&lat, t, pool);
1040            atime(0, tt);
1041            let mut n = t;
1042            if prof {
1043                eprintln!("ch{ch} dec_in rms {:.6e} n {n}", rms(&x));
1044            }
1045            let tt = std::time::Instant::now();
1046            x = self.conv_pre.apply(&x, n, pool);
1047            atime(1, tt);
1048            if prof {
1049                eprintln!("ch{ch} conv_pre rms {:.6e} n {n}", rms(&x));
1050            }
1051            for i in 0..self.ups.len() {
1052                let up = &self.ups[i];
1053                let tt = std::time::Instant::now();
1054                x = up.apply(&x, n, pool);
1055                atime(2, tt);
1056                n = (n - 1) * up.stride + up.k - 2 * up.pad;
1057                let ch_n = up.out_ch;
1058                let mut acc = vec![0f32; ch_n * n];
1059                for j in 0..self.n_kernels {
1060                    let tt = std::time::Instant::now();
1061                    let r = self.resblocks[i * self.n_kernels + j].apply(&x, ch_n, n, pool);
1062                    atime(3, tt);
1063                    for (a, b) in acc.iter_mut().zip(&r) {
1064                        *a += b;
1065                    }
1066                }
1067                let inv = 1.0 / self.n_kernels as f32;
1068                for v in acc.iter_mut() {
1069                    *v *= inv;
1070                }
1071                x = acc;
1072                if prof {
1073                    eprintln!("ch{ch} up{i} rms {:.6e} ch {ch_n} n {n}", rms(&x));
1074                }
1075            }
1076            let last_ch = self.ups[self.ups.len() - 1].out_ch;
1077            let tt = std::time::Instant::now();
1078            let (mut y, yn) = self.act_post.apply(&x, last_ch, n, pool);
1079            atime(4, tt);
1080            let tt = std::time::Instant::now();
1081            y = self.conv_post.apply(&y, yn, pool);
1082            atime(5, tt);
1083            for v in y.iter_mut() {
1084                *v = v.clamp(-1.0, 1.0);
1085            }
1086            chans.push(y);
1087            n = yn;
1088            let _ = n;
1089        }
1090        let len = chans[0].len().min(chans[1].len());
1091        let mut out = vec![0f32; 2 * len];
1092        for (ch, c) in chans.iter().enumerate() {
1093            out[ch * len..(ch + 1) * len].copy_from_slice(&c[..len]);
1094        }
1095        (out, len)
1096    }
1097}
1098
1099impl AmpBlock {
1100    fn apply(&self, x: &[f32], ch: usize, n: usize, pool: Option<&Pool>) -> Vec<f32> {
1101        let mut cur = x.to_vec();
1102        for i in 0..self.convs1.len() {
1103            let (a1, a2) = (&self.acts[i * 2], &self.acts[i * 2 + 1]);
1104            let (xt, tn) = a1.apply(&cur, ch, n, pool);
1105            let xt = self.convs1[i].apply(&xt, tn, pool);
1106            let (xt, tn2) = a2.apply(&xt, ch, tn, pool);
1107            let xt = self.convs2[i].apply(&xt, tn2, pool);
1108            for (a, b) in cur.iter_mut().zip(&xt) {
1109                *a += b;
1110            }
1111        }
1112        cur
1113    }
1114}
1115
1116/// Test hook: the designed 12-tap resampling filter.
1117#[doc(hidden)]
1118pub fn kaiser_sinc_for_test() -> Vec<f32> {
1119    kaiser_sinc(0.25, 0.3, FILTER_LEN)
1120}
1121
1122pub(crate) struct SendPtr(pub *mut f32);
1123unsafe impl Send for SendPtr {}
1124unsafe impl Sync for SendPtr {}
1125impl SendPtr {
1126    /// SAFETY: caller guarantees disjoint `[off, off+len)` per worker.
1127    #[allow(clippy::mut_from_ref)]
1128    pub(crate) unsafe fn row(&self, off: usize, len: usize) -> &mut [f32] {
1129        unsafe { std::slice::from_raw_parts_mut(self.0.add(off), len) }
1130    }
1131}
1132
1133#[cfg(test)]
1134mod tests {
1135    use super::*;
1136
1137    /// The GEMM + overlap-add arm of the transposed convolution against the
1138    /// scatter loop, over the strides and paddings the decoders use.
1139    #[test]
1140    fn convt_gemm_matches_the_loop() {
1141        let mut seed = 0x9e37_79b9u32;
1142        let mut rnd = || {
1143            seed ^= seed << 13;
1144            seed ^= seed >> 17;
1145            seed ^= seed << 5;
1146            (seed as f32 / u32::MAX as f32) - 0.5
1147        };
1148        for &(ic, oc, s, n) in &[(16usize, 8usize, 8usize, 7usize), (8, 4, 5, 13), (6, 3, 3, 21), (5, 2, 2, 9)] {
1149            let k = 2 * s;
1150            let c = ConvT1d {
1151                w: (0..ic * oc * k).map(|_| rnd()).collect(),
1152                b: (0..oc).map(|_| rnd()).collect(),
1153                in_ch: ic,
1154                out_ch: oc,
1155                k,
1156                stride: s,
1157                pad: s.div_ceil(2),
1158                out_pad: s % 2,
1159                wt: std::sync::OnceLock::new(),
1160            };
1161            let x: Vec<f32> = (0..ic * n).map(|_| rnd()).collect();
1162            let a = c.apply(&x, n, None);
1163            let b = c.apply_gemm(&x, n, None);
1164            assert_eq!(a.len(), b.len());
1165            let d = a.iter().zip(&b).map(|(p, q)| (p - q).abs()).fold(0f32, f32::max);
1166            assert!(d < 1e-5, "stride {s}: max |Δ| {d}");
1167        }
1168    }
1169
1170    /// Decode through the packed MiniMax-Music-3 vocoder and check the
1171    /// two things the reference fixes exactly: 512 samples per latent
1172    /// frame per side, and a `tanh` range. `CMF_MUSIC3_VAE=<file.cmf>`
1173    /// points at a pack; without it there is nothing to test against.
1174    #[test]
1175    fn music3_dav_decodes_to_the_reference_geometry() {
1176        let Ok(p) = std::env::var("CMF_MUSIC3_VAE") else {
1177            eprintln!("CMF_MUSIC3_VAE unset — skipping Music-3 vocoder test");
1178            return;
1179        };
1180        let model = Arc::new(CmfModel::open(&p).expect("open packed vocoder"));
1181        let dav = Music3Dav::from_cmf(&model).expect("load DAV");
1182        let frames = 12usize;
1183        // A latent with structure rather than noise: a decoder that has
1184        // silently lost a stage still returns *something* for noise.
1185        let latent: Vec<f32> = (0..128 * frames)
1186            .map(|i| {
1187                let (c, t) = (i / frames, i % frames);
1188                0.4 * ((c as f32 * 0.13 + t as f32 * 0.7).sin())
1189            })
1190            .collect();
1191        let pcm = dav.decode(&latent, frames, None);
1192        assert_eq!(
1193            pcm.len(),
1194            frames * Music3Dav::HOP * 2,
1195            "512 samples a frame, two sides interleaved"
1196        );
1197        assert!(pcm.iter().all(|v| v.is_finite()), "non-finite sample");
1198        assert!(
1199            pcm.iter().all(|v| v.abs() <= 1.0),
1200            "tanh range violated: {}",
1201            pcm.iter().fold(0f32, |m, v| m.max(v.abs()))
1202        );
1203        // Silence would also satisfy the above; a working stack moves.
1204        let rms = (pcm.iter().map(|v| v * v).sum::<f32>() / pcm.len() as f32).sqrt();
1205        assert!(rms > 1e-4, "decoded to near-silence, rms {rms}");
1206        let (l, r): (Vec<f32>, Vec<f32>) = pcm.chunks_exact(2).map(|c| (c[0], c[1])).unzip();
1207        let d = l
1208            .iter()
1209            .zip(&r)
1210            .map(|(a, b)| (a - b).abs())
1211            .fold(0f32, f32::max);
1212        assert!(
1213            d > 0.0,
1214            "both sides identical — the 128 latent was not split"
1215        );
1216        eprintln!(
1217            "music3 dav: {} samples/side, rms {rms:.4}, L-R max {d:.4}",
1218            l.len()
1219        );
1220    }
1221
1222    #[test]
1223    fn the_resampling_filter_is_the_references() {
1224        let f = kaiser_sinc(0.25, 0.3, FILTER_LEN);
1225        assert_eq!(f.len(), FILTER_LEN);
1226        // Unit sum: without it a constant input leaks amplitude, which
1227        // is the whole reason the reference normalizes.
1228        assert!((f.iter().sum::<f32>() - 1.0).abs() < 1e-6);
1229        // Symmetric about the centre, and its peak is at the centre.
1230        for i in 0..FILTER_LEN / 2 {
1231            assert!(
1232                (f[i] - f[FILTER_LEN - 1 - i]).abs() < 1e-6,
1233                "asymmetric at {i}"
1234            );
1235        }
1236        let peak = f.iter().cloned().fold(f32::MIN, f32::max);
1237        assert!((f[5] - peak).abs() < 1e-6);
1238    }
1239
1240    #[test]
1241    fn bessel_i0_matches_known_values() {
1242        // The third is the β the 12-tap filter's Kaiser window is
1243        // designed at, so it is the value that actually gets used.
1244        for (x, want) in [(0.0, 1.0), (1.0, 1.266_065_878), (4.664, 20.204_6)] {
1245            let got = bessel_i0(x);
1246            assert!((got - want).abs() < 1e-3 * want.max(1.0), "I0({x}) = {got}");
1247        }
1248    }
1249}