inferencelayer 0.2.13

Kortexya's engine-native inference layer — LLM generation + embedding/encoder family on wgpu (WGSL kernels, any adapter) with a pure-Rust CPU fallback
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! Vocal separation — Open-Unmix `umxhq` (vocals stem). CPU, f32.
//!
//! This exists to make **voiceprint identification survive music**. TitaNet is speech-trained and
//! its embeddings degrade badly when a voice is mixed with instruments, so the identify path runs
//! the vocal stem into the existing [`crate::diarize`] `Diarizer::process` → `TitaNet::embed`
//! pipeline. Separation is a pre-processing stage in front of that pipeline — neither the diarizer
//! nor TitaNet needs any change.
//!
//! The port mirrors the reference (`sigsep/open-unmix-pytorch`, `umxhq` weights) exactly:
//!
//! * **STFT** `n_fft = 4096`, `hop = 1024`, periodic hann, `center = true` with reflect padding,
//!   one-sided → 2049 bins. Radix-2 FFT: the tree's other transforms are naive O(N²) DFTs, which
//!   at `n_fft = 4096` would cost billions of MACs per clip.
//! * **`OpenUnmix.forward`**: crop to the model's 1487-bin bandwidth, `(x + input_mean) *
//!   input_scale`, `fc1`(no bias)+`bn1`+tanh, three stacked **bidirectional LSTMs** (torch **ifgo**
//!   gate order — NOT the ONNX **iofc** order `diarize.rs` uses for pyannote), skip-concat with the
//!   pre-LSTM activation, `fc2`+`bn2`+relu, `fc3`+`bn3`, `* output_scale + output_mean`, relu →
//!   a non-negative mask over all 2049 bins, applied to the mixture magnitude.
//! * **Filtering**: the shipped `Separator` runs `wiener(..., iterations = 0, softmask = false)`,
//!   which reduces to *estimated magnitude × mixture phase* — no iterative refinement. Then
//!   `torch.istft` (window-squared envelope normalization, centre trim, length truncation).
//!
//! The model is **stereo at 44.1 kHz**. [`Separator::vocals`] is the pipeline entry point: it takes
//! the 16 kHz mono mixture the audio stack works in, resamples up, duplicates to two channels,
//! averages the stem back down and resamples to 16 kHz mono for the diarizer.
//!
//! Parity: `tests/separation_parity.rs` against `tests/fixtures/export_separation.py` — magnitude
//! spectrogram, every layer boundary, the mask, and the end-to-end stem vs the torch reference.
//!
//! Honest limitation carried into the UI: TitaNet is speech-trained. Spoken media (interviews,
//! vlogs, podcasts) matches with high confidence; a *singing* voice against a spoken enrollment is
//! best-effort, and the mitigation is multi-sample profiles, not a better separator.

use std::path::Path;

use anyhow::{Context, Result};

use crate::cpu_gemm::{PackedWeight, gemm_packed};
use crate::weights::LazySt;

/// The reference transform size. `umxhq` was trained at these settings; they are not tunable.
const N_FFT: usize = 4096;
const N_HOP: usize = 1024;
/// One-sided bin count, `n_fft / 2 + 1`.
const NB_FFT_BINS: usize = N_FFT / 2 + 1;
/// The model is stereo; mono input is duplicated across both channels.
const NB_CHANNELS: usize = 2;
/// `torch.nn.BatchNorm1d` default.
const BN_EPS: f32 = 1e-5;
/// The rate `umxhq` was trained at.
pub const MODEL_SR: u32 = 44100;
/// The rate the diarizer and TitaNet consume.
pub const PIPELINE_SR: u32 = 16000;

// -------------------------------------------------------------------------------------------
// radix-2 FFT
// -------------------------------------------------------------------------------------------

/// Iterative in-place radix-2 decimation-in-time FFT with precomputed twiddles and bit-reversal.
///
/// Accumulates in f64: the reference runs an f32 FFT, so staying wider here keeps the port's error
/// below the oracle's own rounding noise instead of adding to it.
struct Fft {
    n: usize,
    rev: Vec<u32>,
    /// `tw[j] = exp(-2πi·j/n)` for `j < n/2`.
    tw_re: Vec<f64>,
    tw_im: Vec<f64>,
}

impl Fft {
    fn new(n: usize) -> Self {
        assert!(n.is_power_of_two(), "radix-2 needs a power of two");
        let bits = n.trailing_zeros();
        let rev = (0..n)
            .map(|i| (i as u32).reverse_bits() >> (32 - bits))
            .collect();
        let (mut tw_re, mut tw_im) = (vec![0f64; n / 2], vec![0f64; n / 2]);
        for j in 0..n / 2 {
            let a = -2.0 * std::f64::consts::PI * j as f64 / n as f64;
            tw_re[j] = a.cos();
            tw_im[j] = a.sin();
        }
        Self { n, rev, tw_re, tw_im }
    }

    /// In-place transform. `inverse` conjugates the twiddles and does NOT scale by `1/n`.
    fn run(&self, re: &mut [f64], im: &mut [f64], inverse: bool) {
        let n = self.n;
        for i in 0..n {
            let j = self.rev[i] as usize;
            if j > i {
                re.swap(i, j);
                im.swap(i, j);
            }
        }
        let sign = if inverse { -1.0 } else { 1.0 };
        let mut len = 2;
        while len <= n {
            let step = n / len;
            let half = len / 2;
            for base in (0..n).step_by(len) {
                for j in 0..half {
                    let (wr, wi) = (self.tw_re[j * step], sign * self.tw_im[j * step]);
                    let (a, b) = (base + j, base + j + half);
                    let (vr, vi) = (re[b] * wr - im[b] * wi, re[b] * wi + im[b] * wr);
                    let (ur, ui) = (re[a], im[a]);
                    re[a] = ur + vr;
                    im[a] = ui + vi;
                    re[b] = ur - vr;
                    im[b] = ui - vi;
                }
            }
            len <<= 1;
        }
    }
}

// -------------------------------------------------------------------------------------------
// layers
// -------------------------------------------------------------------------------------------

/// `y = x·Wᵀ (+ b)` over rows; `W` is `[n, k]` row-major, matching torch's `Linear.weight`.
struct Linear {
    w: Vec<f32>,
    b: Option<Vec<f32>>,
    n: usize,
    k: usize,
    packed: std::sync::OnceLock<PackedWeight>,
}

impl Linear {
    fn load(st: &LazySt, name: &str, n: usize, k: usize) -> Result<Self> {
        let w = st.tensor_f32(name)?;
        anyhow::ensure!(w.len() == n * k, "{name}: expected [{n}, {k}], got {}", w.len());
        Ok(Self { w, b: None, n, k, packed: std::sync::OnceLock::new() })
    }

    fn forward(&self, x: &[f32]) -> Vec<f32> {
        let m = x.len() / self.k;
        let mut out = vec![0f32; m * self.n];
        let packed = self.packed.get_or_init(|| PackedWeight::new(&self.w, self.n, self.k));
        gemm_packed(&mut out, x, packed, m, self.b.as_deref());
        out
    }
}

/// `BatchNorm1d` in inference mode, folded to `y = x·scale + shift`.
struct BatchNorm {
    scale: Vec<f32>,
    shift: Vec<f32>,
}

impl BatchNorm {
    fn load(st: &LazySt, prefix: &str, c: usize) -> Result<Self> {
        let w = st.tensor_f32(&format!("{prefix}.weight"))?;
        let b = st.tensor_f32(&format!("{prefix}.bias"))?;
        let mean = st.tensor_f32(&format!("{prefix}.running_mean"))?;
        let var = st.tensor_f32(&format!("{prefix}.running_var"))?;
        anyhow::ensure!(w.len() == c, "{prefix}: expected {c} channels, got {}", w.len());
        let scale: Vec<f32> = (0..c).map(|i| w[i] / (var[i] + BN_EPS).sqrt()).collect();
        let shift: Vec<f32> = (0..c).map(|i| b[i] - mean[i] * scale[i]).collect();
        Ok(Self { scale, shift })
    }

    /// In place over `[rows, c]`.
    fn apply(&self, x: &mut [f32]) {
        let c = self.scale.len();
        for row in x.chunks_exact_mut(c) {
            for (i, v) in row.iter_mut().enumerate() {
                *v = *v * self.scale[i] + self.shift[i];
            }
        }
    }
}

fn sigmoid(v: f32) -> f32 {
    1.0 / (1.0 + (-v).exp())
}

/// One direction of a torch `nn.LSTM` layer.
///
/// Gate order is torch's **ifgo** — deliberately different from the **iofc** order in
/// `diarize.rs`, which loads pyannote from an ONNX export. Mixing the two silently produces
/// plausible-looking garbage, so the orders are spelled out at both sites.
struct LstmDir {
    w: Vec<f32>, // [4H, in]
    r: Vec<f32>, // [4H, H]
    b: Vec<f32>, // [4H] — bias_ih + bias_hh, pre-summed
    hidden: usize,
    input: usize,
    packed_w: std::sync::OnceLock<PackedWeight>,
}

impl LstmDir {
    /// `x` is `[t, in]` in already-directional order → `[t, H]`.
    ///
    /// The input projection does not depend on the hidden state, so it is hoisted out of the
    /// recurrence as one GEMM over all timesteps; the sequential loop only adds `Wh·h`.
    fn run(&self, x: &[f32], t: usize) -> Vec<f32> {
        let hn = self.hidden;
        let g4 = 4 * hn;
        let packed = self.packed_w.get_or_init(|| PackedWeight::new(&self.w, g4, self.input));
        let mut gates_all = vec![0f32; t * g4];
        gemm_packed(&mut gates_all, x, packed, t, Some(&self.b));

        let mut h = vec![0f32; hn];
        let mut c = vec![0f32; hn];
        let mut out = vec![0f32; t * hn];
        for i in 0..t {
            let gates = &mut gates_all[i * g4..][..g4];
            for (rix, g) in gates.iter_mut().enumerate() {
                let rrow = &self.r[rix * hn..][..hn];
                let mut acc = 0f32;
                for k in 0..hn {
                    acc += rrow[k] * h[k];
                }
                *g += acc;
            }
            for j in 0..hn {
                let ig = sigmoid(gates[j]);
                let fg = sigmoid(gates[hn + j]);
                let cg = gates[2 * hn + j].tanh();
                let og = sigmoid(gates[3 * hn + j]);
                c[j] = fg * c[j] + ig * cg;
                h[j] = og * c[j].tanh();
            }
            out[i * hn..][..hn].copy_from_slice(&h);
        }
        out
    }
}

struct BiLstm {
    fwd: LstmDir,
    bwd: LstmDir,
}

impl BiLstm {
    /// Loads `lstm.{weight,bias}_{ih,hh}_l{layer}` and its `_reverse` twin.
    fn load(st: &LazySt, layer: usize, input: usize, hidden: usize) -> Result<Self> {
        let g4 = 4 * hidden;
        let dir = |suffix: &str| -> Result<LstmDir> {
            let w = st.tensor_f32(&format!("lstm.weight_ih_l{layer}{suffix}"))?;
            let r = st.tensor_f32(&format!("lstm.weight_hh_l{layer}{suffix}"))?;
            let bi = st.tensor_f32(&format!("lstm.bias_ih_l{layer}{suffix}"))?;
            let bh = st.tensor_f32(&format!("lstm.bias_hh_l{layer}{suffix}"))?;
            anyhow::ensure!(
                w.len() == g4 * input && r.len() == g4 * hidden && bi.len() == g4,
                "lstm l{layer}{suffix}: shape mismatch"
            );
            Ok(LstmDir {
                w,
                r,
                b: (0..g4).map(|i| bi[i] + bh[i]).collect(),
                hidden,
                input,
                packed_w: std::sync::OnceLock::new(),
            })
        };
        Ok(Self { fwd: dir("")?, bwd: dir("_reverse")? })
    }

    /// `[t, in]` → `[t, 2H]`, forward ‖ backward per timestep (torch's concatenation order).
    fn run(&self, x: &[f32], t: usize) -> Vec<f32> {
        let hn = self.fwd.hidden;
        let d = self.fwd.input;
        let mut rev = vec![0f32; x.len()];
        for i in 0..t {
            rev[i * d..][..d].copy_from_slice(&x[(t - 1 - i) * d..][..d]);
        }
        let (f, b) = rayon::join(|| self.fwd.run(x, t), || self.bwd.run(&rev, t));
        let mut out = vec![0f32; t * 2 * hn];
        for i in 0..t {
            out[i * 2 * hn..][..hn].copy_from_slice(&f[i * hn..][..hn]);
            out[i * 2 * hn + hn..][..hn].copy_from_slice(&b[(t - 1 - i) * hn..][..hn]);
        }
        out
    }
}

// -------------------------------------------------------------------------------------------
// the separator
// -------------------------------------------------------------------------------------------

/// One stereo forward pass, with every stage boundary retained so the parity gate can compare
/// against the torch reference layer by layer rather than only end to end.
///
/// Spectral fields are laid out `[channel][bin][frame]`, matching the reference's
/// `(nb_channels, nb_bins, nb_frames)`; dense fields are `[frame][feature]`.
pub struct Pass {
    pub frames: usize,
    /// Mixture magnitude, all 2049 bins.
    pub mag: Vec<f32>,
    pub fc1_tanh: Vec<f32>,
    pub lstm_out: Vec<f32>,
    pub fc2_relu: Vec<f32>,
    /// The non-negative mask, before it meets the mixture.
    pub mask: Vec<f32>,
    /// `mask * mag` — the estimated vocal magnitude.
    pub est_mag: Vec<f32>,
    re: Vec<f32>,
    im: Vec<f32>,
}

pub struct Separator {
    fft: Fft,
    window: Vec<f64>,
    input_mean: Vec<f32>,
    input_scale: Vec<f32>,
    output_mean: Vec<f32>,
    output_scale: Vec<f32>,
    fc1: Linear,
    bn1: BatchNorm,
    lstm: Vec<BiLstm>,
    fc2: Linear,
    bn2: BatchNorm,
    fc3: Linear,
    bn3: BatchNorm,
    /// The model's bandwidth crop (1487 of 2049 bins for `umxhq`).
    nb_bins: usize,
    hidden: usize,
}

impl Separator {
    /// `dir` holds `umxhq_vocals.safetensors` (see `tests/fixtures/export_separation.py`).
    pub fn load(dir: &Path) -> Result<Self> {
        let bytes = std::fs::read(dir.join("umxhq_vocals.safetensors"))
            .with_context(|| format!("umxhq_vocals.safetensors in {}", dir.display()))?;
        let st = LazySt::from_bytes(vec![bytes])?;

        let input_mean = st.tensor_f32("input_mean")?;
        let input_scale = st.tensor_f32("input_scale")?;
        let output_mean = st.tensor_f32("output_mean")?;
        let output_scale = st.tensor_f32("output_scale")?;
        let nb_bins = input_mean.len();
        anyhow::ensure!(
            output_mean.len() == NB_FFT_BINS && nb_bins <= NB_FFT_BINS,
            "unexpected umx bandwidth: {nb_bins} in, {} out",
            output_mean.len()
        );

        let hidden = st.shape("bn1.weight")?[0];
        let fc1 = Linear::load(&st, "fc1.weight", hidden, NB_CHANNELS * nb_bins)?;
        let fc2 = Linear::load(&st, "fc2.weight", hidden, 2 * hidden)?;
        let fc3 = Linear::load(&st, "fc3.weight", NB_CHANNELS * NB_FFT_BINS, hidden)?;
        // Bidirectional halves: the reference builds `nn.LSTM(hidden, hidden // 2, ...)`.
        let half = hidden / 2;
        let lstm = (0..3)
            .map(|l| BiLstm::load(&st, l, hidden, half))
            .collect::<Result<Vec<_>>>()?;

        // torch.hann_window(n) is PERIODIC by default.
        let window = (0..N_FFT)
            .map(|i| 0.5 * (1.0 - (2.0 * std::f64::consts::PI * i as f64 / N_FFT as f64).cos()))
            .collect();

        Ok(Self {
            fft: Fft::new(N_FFT),
            window,
            input_mean,
            input_scale,
            output_mean,
            output_scale,
            fc1,
            bn1: BatchNorm::load(&st, "bn1", hidden)?,
            lstm,
            fc2,
            bn2: BatchNorm::load(&st, "bn2", hidden)?,
            fc3,
            bn3: BatchNorm::load(&st, "bn3", NB_CHANNELS * NB_FFT_BINS)?,
            nb_bins,
            hidden,
        })
    }

    fn frames_for(len: usize) -> usize {
        len / N_HOP + 1
    }

    /// `torch.stft(center = true, pad_mode = "reflect", onesided = true, normalized = false)` for
    /// every channel → `re`/`im` laid out `[channel][bin][frame]`.
    fn stft(&self, channels: &[&[f32]]) -> (Vec<f32>, Vec<f32>, usize) {
        let len = channels[0].len();
        let frames = Self::frames_for(len);
        let nch = channels.len();
        let mut re = vec![0f32; nch * NB_FFT_BINS * frames];
        let mut im = vec![0f32; nch * NB_FFT_BINS * frames];
        let l = len as i64;
        for (c, ch) in channels.iter().enumerate() {
            // reflect padding of n_fft/2 on both sides, indexed on the fly
            let at = |i: i64| -> f32 {
                let j = if i < 0 {
                    -i
                } else if i >= l {
                    2 * l - 2 - i
                } else {
                    i
                };
                ch[j.clamp(0, l - 1) as usize]
            };
            let mut buf_re = vec![0f64; N_FFT];
            let mut buf_im = vec![0f64; N_FFT];
            for f in 0..frames {
                let start = f as i64 * N_HOP as i64 - (N_FFT / 2) as i64;
                for j in 0..N_FFT {
                    buf_re[j] = at(start + j as i64) as f64 * self.window[j];
                    buf_im[j] = 0.0;
                }
                self.fft.run(&mut buf_re, &mut buf_im, false);
                let base = c * NB_FFT_BINS * frames;
                for b in 0..NB_FFT_BINS {
                    re[base + b * frames + f] = buf_re[b] as f32;
                    im[base + b * frames + f] = buf_im[b] as f32;
                }
            }
        }
        (re, im, frames)
    }

    /// `torch.istft` of one channel's `[bin][frame]` complex spectrum, trimmed to `length`.
    fn istft(&self, re: &[f32], im: &[f32], frames: usize, length: usize) -> Vec<f32> {
        let full = (frames - 1) * N_HOP + N_FFT;
        let mut y = vec![0f64; full];
        let mut env = vec![0f64; full];
        let inv_n = 1.0 / N_FFT as f64;
        let mut buf_re = vec![0f64; N_FFT];
        let mut buf_im = vec![0f64; N_FFT];
        for f in 0..frames {
            // rebuild the full Hermitian spectrum from the one-sided half
            for b in 0..NB_FFT_BINS {
                buf_re[b] = re[b * frames + f] as f64;
                buf_im[b] = im[b * frames + f] as f64;
            }
            for b in NB_FFT_BINS..N_FFT {
                buf_re[b] = buf_re[N_FFT - b];
                buf_im[b] = -buf_im[N_FFT - b];
            }
            self.fft.run(&mut buf_re, &mut buf_im, true);
            let off = f * N_HOP;
            for j in 0..N_FFT {
                y[off + j] += buf_re[j] * inv_n * self.window[j];
                env[off + j] += self.window[j] * self.window[j];
            }
        }
        let start = N_FFT / 2;
        (0..length)
            .map(|i| {
                let k = start + i;
                if k < full && env[k] > 1e-11 {
                    (y[k] / env[k]) as f32
                } else {
                    0.0
                }
            })
            .collect()
    }

    /// The reference `OpenUnmix.forward`, stage by stage, over a mixture magnitude.
    fn forward(&self, mag: &[f32], frames: usize) -> (Vec<f32>, Vec<f32>, Vec<f32>, Vec<f32>) {
        let nb = self.nb_bins;
        let hidden = self.hidden;

        // crop to the model bandwidth, shift+scale, and pack [frame][channel · bin]
        let mut x = vec![0f32; frames * NB_CHANNELS * nb];
        for f in 0..frames {
            for c in 0..NB_CHANNELS {
                let src = c * NB_FFT_BINS * frames;
                let dst = f * NB_CHANNELS * nb + c * nb;
                for b in 0..nb {
                    x[dst + b] = (mag[src + b * frames + f] + self.input_mean[b])
                        * self.input_scale[b];
                }
            }
        }

        let mut h = self.fc1.forward(&x);
        self.bn1.apply(&mut h);
        for v in h.iter_mut() {
            *v = v.tanh();
        }
        let fc1_tanh = h.clone();

        let mut lstm_out = fc1_tanh.clone();
        for layer in &self.lstm {
            lstm_out = layer.run(&lstm_out, frames);
        }

        // skip connection: concat(pre-LSTM, LSTM) → [frames, 2·hidden]
        let mut cat = vec![0f32; frames * 2 * hidden];
        for f in 0..frames {
            cat[f * 2 * hidden..][..hidden].copy_from_slice(&fc1_tanh[f * hidden..][..hidden]);
            cat[f * 2 * hidden + hidden..][..hidden]
                .copy_from_slice(&lstm_out[f * hidden..][..hidden]);
        }

        let mut d = self.fc2.forward(&cat);
        self.bn2.apply(&mut d);
        for v in d.iter_mut() {
            *v = v.max(0.0);
        }
        let fc2_relu = d.clone();

        let mut o = self.fc3.forward(&fc2_relu);
        self.bn3.apply(&mut o);

        // [frame][channel][bin] → [channel][bin][frame], scaled, relu'd
        let mut mask = vec![0f32; NB_CHANNELS * NB_FFT_BINS * frames];
        for f in 0..frames {
            for c in 0..NB_CHANNELS {
                let src = f * NB_CHANNELS * NB_FFT_BINS + c * NB_FFT_BINS;
                let dst = c * NB_FFT_BINS * frames;
                for b in 0..NB_FFT_BINS {
                    let v = o[src + b] * self.output_scale[b] + self.output_mean[b];
                    mask[dst + b * frames + f] = v.max(0.0);
                }
            }
        }
        (fc1_tanh, lstm_out, fc2_relu, mask)
    }

    /// One full stereo pass at [`MODEL_SR`], retaining every stage for the parity gate.
    pub fn pass(&self, left: &[f32], right: &[f32]) -> Pass {
        assert_eq!(left.len(), right.len(), "channels must be the same length");
        let (re, im, frames) = self.stft(&[left, right]);
        let mag: Vec<f32> = re
            .iter()
            .zip(&im)
            .map(|(r, i)| (*r as f64).hypot(*i as f64) as f32)
            .collect();
        let (fc1_tanh, lstm_out, fc2_relu, mask) = self.forward(&mag, frames);
        let est_mag: Vec<f32> = mask.iter().zip(&mag).map(|(m, x)| m * x).collect();
        Pass { frames, mag, fc1_tanh, lstm_out, fc2_relu, mask, est_mag, re, im }
    }

    /// Estimated magnitude × mixture phase, inverted — the reference's `niter = 0` filtering.
    pub fn stem(&self, pass: &Pass, length: usize) -> (Vec<f32>, Vec<f32>) {
        let n = NB_FFT_BINS * pass.frames;
        let mut out = Vec::with_capacity(NB_CHANNELS);
        for c in 0..NB_CHANNELS {
            let (mut yr, mut yi) = (vec![0f32; n], vec![0f32; n]);
            for k in 0..n {
                let (r, i) = (pass.re[c * n + k], pass.im[c * n + k]);
                let m = (r as f64).hypot(i as f64);
                let est = pass.est_mag[c * n + k] as f64;
                // atan2(0, 0) = 0 in the reference, and est is 0 there anyway
                let (cos, sin) = if m > 0.0 { (r as f64 / m, i as f64 / m) } else { (1.0, 0.0) };
                yr[k] = (est * cos) as f32;
                yi[k] = (est * sin) as f32;
            }
            out.push(self.istft(&yr, &yi, pass.frames, length));
        }
        let right = out.pop().unwrap();
        (out.pop().unwrap(), right)
    }

    /// 44.1 kHz stereo mixture → 44.1 kHz stereo vocal stem.
    pub fn separate(&self, left: &[f32], right: &[f32]) -> (Vec<f32>, Vec<f32>) {
        let pass = self.pass(left, right);
        self.stem(&pass, left.len())
    }

    /// The pipeline entry point: 16 kHz mono mixture → 16 kHz mono vocal stem.
    ///
    /// The model is stereo at 44.1 kHz, so this resamples up, duplicates the channel, averages the
    /// separated stem back to mono and resamples down — leaving the diarizer's input contract
    /// (16 kHz mono `&[f32]`) untouched.
    pub fn vocals(&self, mono_16k: &[f32]) -> Vec<f32> {
        if mono_16k.len() < N_FFT {
            return mono_16k.to_vec();
        }
        let up = crate::chatterbox::resample_sinc(mono_16k, PIPELINE_SR, MODEL_SR);
        let (l, r) = self.separate(&up, &up);
        let mono: Vec<f32> = l.iter().zip(&r).map(|(a, b)| 0.5 * (a + b)).collect();
        let mut out = crate::chatterbox::resample_sinc(&mono, MODEL_SR, PIPELINE_SR);
        out.truncate(mono_16k.len());
        out
    }
}