bunsen 0.39.0

bunsen is a batteries included common library for burn
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! Streaming waveform to log-mel conversion.

use burn::{
    Tensor,
    config::Config,
    module::Module,
};

use crate::{
    errors::{
        BunsenError,
        BunsenResult,
    },
    ops::signal::perceptive_audio::{
        PaddingMode,
        PerceptiveAudioConverter,
        PerceptiveAudioConverterMeta,
    },
};

/// Where a stream sits in its lifecycle.
#[derive(Config, Copy, Debug, PartialEq, Eq)]
pub enum StreamPhase {
    /// Nothing consumed yet; the next chunk receives the start padding.
    Start,

    /// At least one chunk consumed; the next chunk is prefixed by the carry.
    Running,
}

/// Streaming state for waveform to log-mel conversion.
///
/// Binds a carried sample queue to a [`PerceptiveAudioConverter`], so a
/// signal can be fed in hop-aligned chunks and produce exactly the frames it
/// would have produced in one call.
///
/// Built by [`PerceptiveAudioConverter::new_context`], which fixes the batch
/// size. Each batch row is an independent stream.
///
/// [`transform`](Self::transform) takes `self` and hands it back, rather than
/// borrowing mutably, because that is what lets the pipeline be written as a
/// fold over a fixed stack of stages, each shaped `(self, a) -> (b, Self)`.
/// Only the first stage, which prepends the carry and takes off the next one,
/// touches state; the rest delegate to the stateless
/// [`PerceptiveAudioConverter`] stages. [`finish`](Self::finish) consumes the
/// context, so transforming after finishing is a type error.
///
/// Like [`PerceptiveAudioConverter`], this is a `Module` over bare tensors —
/// the carry rides `to_device` but is neither recorded nor visited.
///
/// # Chunking
///
/// Every stage is elementwise or frame-local, so transforming a signal in
/// chunks and concatenating gives the same result as transforming it whole.
/// Dynamic-range packaging that reduces over a whole clip — see
/// [`RangeClamp`](crate::ops::signal::perceptive_audio::RangeClamp) — is
/// deliberately not part of this pipeline; apply it once to the joined result.
#[derive(Module, Debug)]
pub struct PerceptiveAudioConversionContext {
    /// The analysis constants; shared, never mutated.
    converter: PerceptiveAudioConverter,

    /// The samples a future frame still needs: `[batch, carry_len]`.
    ///
    /// `None` before the first chunk. In steady state `carry_len` is
    /// invariant — see [`transform`](Self::transform).
    carry: Option<Tensor<2>>,

    #[module(skip)]
    batch_size: usize,

    #[module(skip)]
    phase: StreamPhase,
}

impl PerceptiveAudioConverterMeta for PerceptiveAudioConversionContext {
    fn sample_rate(&self) -> usize {
        self.converter.sample_rate()
    }

    fn n_fft(&self) -> usize {
        self.converter.n_fft()
    }

    fn hop(&self) -> usize {
        self.converter.hop()
    }

    fn n_mels(&self) -> usize {
        self.converter.n_mels()
    }

    fn pad_to_pow2(&self) -> bool {
        self.converter.pad_to_pow2()
    }

    fn start_padding(&self) -> PaddingMode {
        self.converter.start_padding()
    }

    fn end_padding(&self) -> PaddingMode {
        self.converter.end_padding()
    }
}

impl PerceptiveAudioConversionContext {
    /// The number of independent streams; fixed at construction.
    pub fn batch_size(&self) -> usize {
        self.batch_size
    }

    /// Where this stream sits in its lifecycle.
    pub fn phase(&self) -> StreamPhase {
        self.phase
    }

    /// The converter supplying the analysis constants.
    pub fn converter(&self) -> &PerceptiveAudioConverter {
        &self.converter
    }

    /// The carried samples, if any: `[batch, carry_len]`.
    pub fn carry(&self) -> Option<&Tensor<2>> {
        self.carry.as_ref()
    }

    /// Drops the carry and returns to [`StreamPhase::Start`].
    pub fn reset(&mut self) {
        self.carry = None;
        self.phase = StreamPhase::Start;
    }

    /// Converts one hop-aligned chunk of waveform into log-mels.
    ///
    /// A fold over the stage stack; see the `t_stage_*` methods for what each
    /// step does.
    ///
    /// # Frame count
    ///
    /// In steady state this yields exactly `samples / hop` frames, and the
    /// carry length is invariant. That holds because the carry is
    /// `n_fft - hop + r` where `r = (start_pad - n_fft) mod hop` depends only
    /// on the padding and the hop, not on how the signal was chunked.
    ///
    /// The first call is the exception: it also absorbs the start padding, so
    /// it yields `(start_pad + samples - n_fft) / hop + 1`. For the default
    /// geometry over 30 s that is 2999 frames with a 360-sample carry, and
    /// [`finish`](Self::finish) contributes the remaining 2 — 3001 in total,
    /// matching `librosa` with `center=True`.
    ///
    /// # Arguments
    /// * `waves`: `[batch, samples]`, with `samples` a non-zero multiple of
    ///   `hop`.
    ///
    /// # Returns
    /// `[batch, frames, n_mels]` log-mels, and the advanced
    /// context.
    ///
    /// # Errors
    ///
    /// [`Illegal`](crate::errors::BunsenErrorKind::Illegal) if the batch size
    /// does not match, if `samples` is zero or not a multiple of `hop`, or if
    /// the first chunk is too short to produce a frame.
    pub fn transform(
        self,
        waves: Tensor<2>,
    ) -> BunsenResult<(Tensor<3>, Self)> {
        let (x, this) = self.t_stage_extend(waves)?;
        let (x, this) = this.t_stage_preproc(x);
        let (x, this) = this.t_stage_frame(x);
        let (x, this) = this.t_stage_spectrum(x);
        let (x, this) = this.t_stage_mel(x);
        let (mels, this) = this.t_stage_compress(x);

        Ok((mels, this))
    }

    /// Flushes the carry through the end padding, if any is configured.
    ///
    /// Returns `None` when
    /// [`end_padding`](PerceptiveAudioConverterMeta::end_padding) is
    /// [`PaddingMode::None`], or when nothing has been transformed yet.
    ///
    /// Consumes the context: a stream ends once.
    ///
    /// # Returns
    /// `[batch, frames, n_mels]` tail frames.
    pub fn finish(self) -> Option<Tensor<3>> {
        let carry = self.carry.clone()?;

        let pad = self.end_padding().pad_len(self.n_fft());
        if pad == 0 {
            return None;
        }

        let len = carry.dims()[1];

        let tail = match self.end_padding() {
            PaddingMode::None => unreachable!("pad_len is zero for None"),

            PaddingMode::Zero => Tensor::cat(
                vec![
                    carry.clone(),
                    Tensor::zeros([self.batch_size, pad], &carry.device()),
                ],
                1,
            ),

            // Mirror about the final sample: `numpy`'s "reflect" right-pad of
            // `p` takes `x[-2] .. x[-p-1]`, so slice the `p` samples ending
            // one short of the end and reverse them.
            //
            // This reads only the last `p + 1` samples, and the carry is
            // always longer than that, so reflecting the carry is identical to
            // reflecting the whole signal — which is what makes the streaming
            // result match a one-shot `center=True` run.
            PaddingMode::Reflect => {
                debug_assert!(
                    len > pad,
                    "carry ({len}) must exceed the reflect pad ({pad})",
                );
                let mirror = carry
                    .clone()
                    .slice_dim(1, (len - 1 - pad) as isize..(len - 1) as isize)
                    .flip([1]);
                Tensor::cat(vec![carry, mirror], 1)
            }
        };

        if self.converter.frame_count(tail.dims()[1]) == 0 {
            return None;
        }

        Some(self.converter.forward(tail))
    }

    // ---- the stage stack ----------------------------------------------
    //
    // Each stage is `(self, a) -> (b, Self)`. They are `pub(crate)` so the
    // test layer can drive a single stage, or a prefix of the stack, without
    // constructing a whole valid stream — but they are not public API.

    /// Prepends the start padding or the carry, and takes the new carry off
    /// the tail.
    ///
    /// The only fallible stage, and the only one that touches state. The
    /// carry holds **raw** samples: pre-emphasis needs unfiltered history.
    ///
    /// `[batch, samples]` -> `[batch, extended]`.
    pub(crate) fn t_stage_extend(
        mut self,
        waves: Tensor<2>,
    ) -> BunsenResult<(Tensor<2>, Self)> {
        let [batch, samples] = waves.dims();

        if batch != self.batch_size {
            return Err(BunsenError::illegal(format!(
                "PerceptiveAudioConversionContext: waves batch ({batch}) must \
                 match the context batch size ({})",
                self.batch_size,
            )));
        }

        let hop = self.hop();
        if samples == 0 || samples % hop != 0 {
            return Err(BunsenError::illegal(format!(
                "PerceptiveAudioConversionContext: waves samples ({samples}) \
                 must be a non-zero multiple of hop ({hop})",
            )));
        }

        let extended = match self.phase {
            StreamPhase::Running => match self.carry.take() {
                Some(carry) => Tensor::cat(vec![carry, waves], 1),
                None => waves,
            },

            StreamPhase::Start => {
                let pad = self.start_padding().pad_len(self.n_fft());

                match self.start_padding() {
                    PaddingMode::None => waves,

                    PaddingMode::Zero => {
                        Tensor::cat(vec![Tensor::zeros([batch, pad], &waves.device()), waves], 1)
                    }

                    // Mirror about the first sample: `numpy`'s "reflect"
                    // left-pad of `p` takes `x[p] .. x[1]`, so slice the `p`
                    // samples starting at index 1 and reverse them. That reads
                    // `p + 1` samples, hence `min_first_chunk`.
                    PaddingMode::Reflect => {
                        if samples < self.min_first_chunk() {
                            return Err(BunsenError::illegal(format!(
                                "PerceptiveAudioConversionContext: reflect start \
                                 padding needs at least {} samples in the first \
                                 chunk, got {samples}",
                                self.min_first_chunk(),
                            )));
                        }
                        let mirror = waves.clone().slice_dim(1, 1..(pad + 1) as isize).flip([1]);
                        Tensor::cat(vec![mirror, waves], 1)
                    }
                }
            }
        };

        let frames = self.converter.frame_count(extended.dims()[1]);
        if frames == 0 {
            return Err(BunsenError::illegal(format!(
                "PerceptiveAudioConversionContext: first chunk of {samples} \
                 samples is too short to fill a frame; with {:?} start padding \
                 it needs at least {} samples",
                self.start_padding(),
                self.n_fft() - self.start_padding().pad_len(self.n_fft()),
            )));
        }

        // Everything past the last frame's start belongs to the next call.
        // Deriving it from the frame count keeps this correct on any geometry,
        // rather than depending on a closed form for the carry length.
        let consumed = frames * hop;
        self.carry = Some(extended.clone().slice_dim(1, consumed as isize..));
        self.phase = StreamPhase::Running;

        Ok((extended, self))
    }

    /// Sample-domain preprocessing.
    ///
    /// Currently the identity. This is where pre-emphasis and DC removal will
    /// land; both are rejected by
    /// [`validate`](crate::ops::signal::perceptive_audio::PerceptiveAudioConverterOptions::validate)
    /// until then, so the stage cannot silently drop a configured filter.
    ///
    /// `[batch, extended]` -> `[batch, extended]`.
    pub(crate) fn t_stage_preproc(
        self,
        x: Tensor<2>,
    ) -> (Tensor<2>, Self) {
        (x, self)
    }

    /// Framing and windowing.
    ///
    /// `[batch, extended]` -> `[batch, frames, n_fft]`.
    pub(crate) fn t_stage_frame(
        self,
        x: Tensor<2>,
    ) -> (Tensor<3>, Self) {
        let framed = self.converter.frame(x);
        (framed, self)
    }

    /// Frames to a power or magnitude spectrum.
    ///
    /// `[batch, frames, n_fft]` -> `[batch, frames, n_bins]`.
    pub(crate) fn t_stage_spectrum(
        self,
        x: Tensor<3>,
    ) -> (Tensor<3>, Self) {
        let spectrum = self.converter.spectrum(x);
        (spectrum, self)
    }

    /// Spectrum onto the mel scale.
    ///
    /// `[batch, frames, n_bins]` -> `[batch, frames, n_mels]`.
    pub(crate) fn t_stage_mel(
        self,
        x: Tensor<3>,
    ) -> (Tensor<3>, Self) {
        let mels = self.converter.mel(x);
        (mels, self)
    }

    /// Mel energies to log-mels.
    ///
    /// `[batch, frames, n_mels]` -> `[batch, frames, n_mels]`.
    pub(crate) fn t_stage_compress(
        self,
        x: Tensor<3>,
    ) -> (Tensor<3>, Self) {
        let mels = self.converter.compress(x);
        (mels, self)
    }
}

impl PerceptiveAudioConverter {
    /// Opens a streaming conversion over these constants.
    ///
    /// # Arguments
    /// * `batch_size`: the number of independent streams; must be non-zero.
    pub fn new_context(
        &self,
        batch_size: usize,
    ) -> PerceptiveAudioConversionContext {
        assert_ne!(
            batch_size, 0,
            "PerceptiveAudioConverter batch_size must be non-zero"
        );

        PerceptiveAudioConversionContext {
            converter: self.clone(),
            carry: None,
            batch_size,
            phase: StreamPhase::Start,
        }
    }
}

#[cfg(test)]
mod tests {
    use burn::tensor::Tolerance;

    use super::*;
    use crate::{
        burner::module::ModuleInit,
        errors::{
            BunsenErrorKind,
            WithOkOrPanic,
            testing::ErrorMatcher,
        },
        ops::signal::perceptive_audio::PerceptiveAudioConverterOptions,
        support::testing::{
            DeviceMemoryGuard,
            assert_close_to_vec,
            assert_tensor_close_to_vec,
            assert_tensors_close,
            performance_device,
        },
    };

    /// Builds a `[batch, samples]` tensor from a row-major host buffer.
    fn from_rows(
        rows: &[Vec<f64>],
        device: &burn::prelude::Device,
    ) -> Tensor<2> {
        let samples = rows[0].len();
        Tensor::from_data(
            burn::prelude::TensorData::new(rows.concat(), [rows.len(), samples]),
            device,
        )
    }

    /// A deterministic sample in `[-1, 1]`.
    fn sample(
        row: usize,
        i: usize,
    ) -> f64 {
        (((row * 7919 + i * 104729) % 2003) as f64 / 1001.0) - 1.0
    }

    fn rows(
        batch: usize,
        samples: usize,
    ) -> Vec<Vec<f64>> {
        (0..batch)
            .map(|r| (0..samples).map(|i| sample(r, i)).collect())
            .collect()
    }

    #[test]
    #[serial_test::serial]
    fn test_context_meta_and_lifecycle() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let opts = PerceptiveAudioConverterOptions::default();
        let conv: PerceptiveAudioConverter = opts.try_init(&device).ok_or_panic();

        let ctx = conv.new_context(2);

        assert_eq!(ctx.batch_size(), 2);
        assert_eq!(ctx.phase(), StreamPhase::Start);
        assert!(ctx.carry().is_none());

        // Meta reads the same through the context as through the converter.
        assert_eq!(ctx.n_fft(), conv.n_fft());
        assert_eq!(ctx.hop(), conv.hop());
        assert_eq!(ctx.n_mels(), conv.n_mels());
        assert_eq!(ctx.n_bins(), conv.n_bins());
        assert_eq!(ctx.min_first_chunk(), conv.min_first_chunk());

        let x = from_rows(&rows(2, 1600), &device);
        let (_, ctx) = ctx.transform(x).unwrap();

        assert_eq!(ctx.phase(), StreamPhase::Running);
        assert!(ctx.carry().is_some());

        let mut ctx = ctx;
        ctx.reset();
        assert_eq!(ctx.phase(), StreamPhase::Start);
        assert!(ctx.carry().is_none());
    }

    /// The frame accounting documented under
    /// [`transform`](PerceptiveAudioConversionContext::transform)'s `# Frame
    /// count`, asserted against the real thing.
    #[test]
    #[serial_test::serial]
    fn test_frame_accounting_over_a_30s_window() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let opts = PerceptiveAudioConverterOptions::default();
        let conv: PerceptiveAudioConverter = opts.try_init(&device).ok_or_panic();

        // 30 s at the default 16 kHz sample rate.
        let samples = 480_000;
        let x = from_rows(&rows(1, samples), &device);

        let (mels, ctx) = conv.new_context(1).transform(x).unwrap();

        // Start padding is 200, which is not a hop multiple, so the first call
        // is short of `samples / hop` and leaves a 360-sample carry.
        assert_eq!(mels.dims(), [1, 2999, opts.n_mels]);
        assert_eq!(ctx.carry().unwrap().dims(), [1, 360]);

        let tail = ctx.finish().expect("reflect end padding yields a tail");
        assert_eq!(tail.dims(), [1, 2, opts.n_mels]);

        // 2999 + 2 == 3001, which is what `librosa` gives with center=True.
        assert_eq!(2999 + 2, 3001);
    }

    /// In steady state each chunk yields exactly `samples / hop` frames and
    /// the carry length does not drift.
    #[test]
    #[serial_test::serial]
    fn test_running_frame_count_is_invariant() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let conv: PerceptiveAudioConverter = PerceptiveAudioConverterOptions::default()
            .try_init(&device)
            .ok_or_panic();
        let hop = conv.hop();

        let mut ctx = conv.new_context(2);
        let mut carry_len = None;

        for (step, chunk) in [3200, 1600, 4800, 1600].into_iter().enumerate() {
            let x = from_rows(&rows(2, chunk), &device);
            let (mels, next) = ctx.transform(x).unwrap();
            ctx = next;

            if step > 0 {
                assert_eq!(
                    mels.dims()[1],
                    chunk / hop,
                    "step {step}: running frame count should be samples / hop",
                );
            }

            let len = ctx.carry().unwrap().dims()[1];
            match carry_len {
                None => carry_len = Some(len),
                Some(prev) => assert_eq!(prev, len, "carry length drifted at step {step}"),
            }
        }

        assert_eq!(carry_len, Some(360));
    }

    /// **The milestone.** Splitting a signal into chunks must give bit-equal
    /// output to running it whole.
    #[test]
    #[serial_test::serial]
    fn test_chunked_transform_is_a_homomorphism() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let conv: PerceptiveAudioConverter = PerceptiveAudioConverterOptions::default()
            .try_init(&device)
            .ok_or_panic();

        let (batch, total) = (3, 32_000);
        let host = rows(batch, total);

        // Whole-signal reference, plus its tail.
        let whole = from_rows(&host, &device);
        let (whole_mels, whole_ctx) = conv.new_context(batch).transform(whole).unwrap();
        let whole_tail = whole_ctx.finish().unwrap();

        // Several hop-aligned splits, including a ragged one.
        for split in [
            vec![32_000],
            vec![16_000, 16_000],
            vec![320, 31_680],
            vec![6_400, 3_200, 12_800, 9_600],
        ] {
            assert_eq!(split.iter().sum::<usize>(), total);

            let mut ctx = conv.new_context(batch);
            let mut pieces = Vec::new();
            let mut at = 0;

            for n in &split {
                let chunk: Vec<Vec<f64>> = host.iter().map(|r| r[at..at + n].to_vec()).collect();
                let (mels, next) = ctx.transform(from_rows(&chunk, &device)).unwrap();
                ctx = next;
                pieces.push(mels);
                at += n;
            }

            let joined: Tensor<3> = Tensor::cat(pieces, 1);
            assert_eq!(
                joined.dims(),
                whole_mels.dims(),
                "split {split:?} produced a different frame count",
            );

            // Same backend, same dtype, same arithmetic — but the chunks are
            // concatenated differently, so allow a small float tolerance.
            assert_tensors_close(&joined, &whole_mels, Tolerance::absolute(1e-4));

            let tail = ctx.finish().unwrap();
            assert_tensors_close(&tail, &whole_tail, Tolerance::absolute(1e-4));
        }
    }

    #[test]
    #[serial_test::serial]
    fn test_batch_rows_are_independent() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let conv: PerceptiveAudioConverter = PerceptiveAudioConverterOptions::default()
            .try_init(&device)
            .ok_or_panic();

        let (batch, samples) = (3, 8_000);
        let host = rows(batch, samples);

        let (together, _) = conv
            .new_context(batch)
            .transform(from_rows(&host, &device))
            .unwrap();

        let dims = together.dims();
        let per_row = dims[1] * dims[2];
        let together = together.to_data().try_to_vec_as::<f64>().unwrap();

        for row in 0..batch {
            let (alone, _) = conv
                .new_context(1)
                .transform(from_rows(&host[row..row + 1], &device))
                .unwrap();

            assert_close_to_vec(
                &alone.to_data().try_to_vec_as::<f64>().unwrap(),
                &together[row * per_row..(row + 1) * per_row],
                1e-4,
            );
        }
    }

    #[test]
    #[serial_test::serial]
    fn test_transform_rejects_bad_input() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let conv: PerceptiveAudioConverter = PerceptiveAudioConverterOptions::default()
            .try_init(&device)
            .ok_or_panic();

        // Not a hop multiple.
        let ctx = conv.new_context(2);
        let bad = from_rows(&rows(2, 1601), &device);
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("multiple of hop")
            .assert_err(&ctx.transform(bad));

        // Wrong batch.
        let ctx = conv.new_context(2);
        let bad = from_rows(&rows(3, 1600), &device);
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("batch (3)")
            .assert_err(&ctx.transform(bad));

        // Too short to reflect: `min_first_chunk` is 201, and 160 is the
        // largest hop-aligned chunk below it.
        let ctx = conv.new_context(1);
        let bad = from_rows(&rows(1, 160), &device);
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("reflect start padding")
            .assert_err(&ctx.transform(bad));
    }

    #[test]
    #[serial_test::serial]
    fn test_finish_respects_end_padding() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        // No end padding: nothing to flush.
        let unpadded: PerceptiveAudioConverter = PerceptiveAudioConverterOptions::default()
            .with_end_padding(PaddingMode::None)
            .try_init(&device)
            .ok_or_panic();
        let (_, ctx) = unpadded
            .new_context(1)
            .transform(from_rows(&rows(1, 3200), &device))
            .unwrap();
        assert!(ctx.finish().is_none());

        // Nothing transformed yet: nothing to flush either.
        assert!(unpadded.new_context(1).finish().is_none());

        // Zero end padding produces the same frame count as reflect; only the
        // values differ.
        let zero: PerceptiveAudioConverter = PerceptiveAudioConverterOptions::default()
            .with_end_padding(PaddingMode::Zero)
            .try_init(&device)
            .ok_or_panic();
        let (_, ctx) = zero
            .new_context(1)
            .transform(from_rows(&rows(1, 3200), &device))
            .unwrap();
        assert_eq!(ctx.finish().unwrap().dims()[1], 2);
    }

    /// Driving one stage at a time must match driving the whole fold — the
    /// payoff for the stack being decomposed.
    #[test]
    #[serial_test::serial]
    fn test_stage_stack_matches_transform() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let conv: PerceptiveAudioConverter = PerceptiveAudioConverterOptions::default()
            .try_init(&device)
            .ok_or_panic();

        let x = from_rows(&rows(2, 3200), &device);

        let (folded, _) = conv.new_context(2).transform(x.clone()).unwrap();

        let ctx = conv.new_context(2);
        let (a, ctx) = ctx.t_stage_extend(x).unwrap();
        let (a, ctx) = ctx.t_stage_preproc(a);
        let (a, ctx) = ctx.t_stage_frame(a);
        let (a, ctx) = ctx.t_stage_spectrum(a);
        let (a, ctx) = ctx.t_stage_mel(a);
        let (staged, _) = ctx.t_stage_compress(a);

        assert_tensors_close(&staged, &folded, Tolerance::default());
    }

    /// `t_stage_extend` in isolation: the carry contents must be exactly the
    /// tail of the extended signal, and the extension must start with the
    /// mirrored prefix.
    #[test]
    #[serial_test::serial]
    fn test_extend_stage_carry_contents() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let conv: PerceptiveAudioConverter = PerceptiveAudioConverterOptions::default()
            .try_init(&device)
            .ok_or_panic();
        let (n_fft, hop) = (conv.n_fft(), conv.hop());
        let pad = n_fft / 2;

        let host = rows(1, 1600);
        let x = from_rows(&host, &device);

        let (ext, ctx) = conv.new_context(1).t_stage_extend(x).unwrap();
        let ext_host = ext.to_data().try_to_vec_as::<f64>().unwrap();

        assert_eq!(ext_host.len(), pad + 1600);

        // The first `pad` samples mirror x[1..=pad], reversed.
        let expected_prefix: Vec<f64> = (1..=pad).rev().map(|i| host[0][i]).collect();
        assert_close_to_vec(&ext_host[..pad], &expected_prefix, 1e-6);

        // ...and the rest is the signal itself.
        assert_close_to_vec(&ext_host[pad..], &host[0], 1e-6);

        // The carry is everything past the last frame's start.
        let frames = conv.frame_count(ext_host.len());
        let consumed = frames * hop;
        assert_tensor_close_to_vec(
            &ctx.carry().unwrap(),
            &ext_host[consumed..],
            Tolerance::default(),
        );
    }
}