bunsen 0.41.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
//! Qwen3-ASR as the stream driver core's engine.
use std::sync::Arc;

use burn::{
    Tensor,
    module::Module,
    tensor::Device,
};

use super::{
    Qwen3AsrBundle,
    Qwen3AsrFrontEndMeta,
    Qwen3AsrTranscript,
};
use crate::{
    errors::{
        BunsenError,
        BunsenResult,
    },
    kits::speech::asr_driver::{
        AsrEngine,
        AsrStreamContext,
        AsrStreamDriver,
        DecodeRequest,
        LogMelFeatures,
        MaxLevel,
        SpeakerCutConfig,
        WindowDecode,
        quiet_cut,
        speaker_cut,
    },
};

/// The mel frames a full window's quiet cut must be quiet over: 90 ms.
const QUIET_SPAN_FRAMES: usize = 9;

/// The stream driver of a Qwen3-ASR model: the core's [`AsrStreamDriver`]
/// over a [`Qwen3AsrEngine`].
pub type Qwen3AsrStreamDriver = AsrStreamDriver<Qwen3AsrEngine>;

/// One Qwen3-ASR stream: the core's [`AsrStreamContext`] over a
/// [`Qwen3AsrEngine`].
pub type Qwen3AsrStreamContext = AsrStreamContext<Qwen3AsrEngine>;

/// A [`Qwen3AsrBundle`] as an [`AsrEngine`]: what the stream driver core
/// needs of the model.
///
/// - **Features:** the bundle's log-mels, streamed ([`LogMelFeatures`]), and
///   packaged per window as its front end packages an utterance: floored 8 dB
///   under the window's [`MaxLevel`], scaled, and padded with silence to the
///   front end's 30 s. A window is at most
///   [`MAX_WINDOW_SECONDS`](Qwen3AsrBundle::MAX_WINDOW_SECONDS) of frames by
///   default, and never more
///   ([`with_window_seconds`](Self::with_window_seconds)).
/// - **Decode:** [`transcribe_features`](Qwen3AsrBundle::transcribe_features),
///   one window at a time: the greedy decoder takes one prompt. A reply's
///   transcript is one segment over the window decoded; Qwen3-ASR has no
///   timestamps, so a window is committed whole, and the grid speech regions
///   snap to is one frame. A reply with no transcript (`language None`, for
///   audio without speech) skips its window.
/// - **Cuts:** a window the core cut at its full length is cut again before it
///   is decoded, at its quietest 90 ms in its last third by mean log-mel
///   ([`quiet_cut`]), and the stream moves on from there: a window that ends
///   inside a word loses or repeats it, and the model was seen to repeat
///   phrases decoding audio past a pause.
///   [`with_quiet_cut`](Self::with_quiet_cut) turns this off. With a diarizer
///   attached, any window is first cut at a change of speaker
///   ([`speaker_cut`]), so a window, committed whole, is one speaker's as far
///   as the turns go; [`with_speaker_cut`](Self::with_speaker_cut) sets or
///   turns off the thresholds.
/// - **Carry:** the language, the first a committed reply names.
///
/// A stream's last frame is the end padding's, and goes, as the front end's
/// extractor drops it. The frames before it are the one-shot extractor's,
/// except the last one or two of the stream: streaming reflects at the end,
/// where the one-shot extractor pads the waveform with zeros.
#[derive(Clone, Debug)]
pub struct Qwen3AsrEngine {
    bundle: Arc<Qwen3AsrBundle>,
    window_frames: usize,
    quiet_cut: bool,
    speaker_cut: Option<SpeakerCutConfig>,
    device: Device,
}

impl Qwen3AsrEngine {
    /// The engine of `bundle`, on the model's device, with windows of at most
    /// [`MAX_WINDOW_SECONDS`](Qwen3AsrBundle::MAX_WINDOW_SECONDS), each full
    /// one cut at a quiet point.
    pub fn new(bundle: Arc<Qwen3AsrBundle>) -> Self {
        let device = bundle.model.devices()[0].clone();
        let window_frames = bundle.max_window() / bundle.front_end.hop();
        Self {
            bundle,
            window_frames,
            quiet_cut: true,
            speaker_cut: Some(SpeakerCutConfig::new()),
            device,
        }
    }

    /// The engine with a window cut at a change of speaker before it is
    /// decoded, when a diarizer is attached (the default thresholds), or
    /// `None` to decode windows as the core and the quiet cut cut them.
    pub fn with_speaker_cut(
        mut self,
        config: Option<SpeakerCutConfig>,
    ) -> Self {
        self.speaker_cut = config;
        self
    }

    /// The engine with a full window cut at its quietest point before it is
    /// decoded (`true`, the default), or decoded and committed whole.
    pub fn with_quiet_cut(
        mut self,
        on: bool,
    ) -> Self {
        self.quiet_cut = on;
        self
    }

    /// The engine with windows of at most `seconds`, rounded down to whole
    /// frames.
    ///
    /// # Panics
    /// If that is under one frame, or over
    /// [`MAX_WINDOW_SECONDS`](Qwen3AsrBundle::MAX_WINDOW_SECONDS), the most
    /// the model was trained on.
    pub fn with_window_seconds(
        mut self,
        seconds: f64,
    ) -> Self {
        let front_end = &self.bundle.front_end;
        let frames = (seconds * front_end.sample_rate() as f64 / front_end.hop() as f64) as usize;
        let most = self.bundle.max_window() / front_end.hop();
        assert!(
            frames > 0 && frames <= most,
            "a window of {seconds} s is under one frame or over {} s",
            Qwen3AsrBundle::MAX_WINDOW_SECONDS
        );
        self.window_frames = frames;
        self
    }

    /// The bundle.
    pub fn bundle(&self) -> &Arc<Qwen3AsrBundle> {
        &self.bundle
    }

    /// The frames a window is padded out to: the front end's shortest
    /// window.
    fn padded_frames(&self) -> usize {
        let front_end = &self.bundle.front_end;
        front_end.min_samples() / front_end.hop()
    }

    /// Floors a window at the range below its level, scales it, and pads it
    /// with the floor, which is what silence floors to.
    ///
    /// # Arguments
    /// * `window` - `[1, frames, n_mels]` log-mels.
    ///
    /// # Returns
    /// `[n_mels, max(frames, padded_frames)]`.
    fn package(
        &self,
        window: Tensor<3>,
        level: &MaxLevel,
    ) -> Tensor<2> {
        let whisper = &self.bundle.front_end.config.whisper;
        let [_, frames, n_mels] = window.dims();
        let width = frames.max(self.padded_frames());
        let window = if frames < width {
            let floor = level
                .max
                .clone()
                .sub_scalar(whisper.range_clamp_db)
                .reshape([1, 1, 1])
                .expand([1, width - frames, n_mels]);
            Tensor::cat(vec![window, floor], 1)
        } else {
            window
        };
        whisper
            .package_window(window, level.max.clone())
            .reshape([n_mels, width])
    }

    /// Lays a reply out for the core: its transcript, one segment over the
    /// window, or a skip when it has none.
    fn lay_out(
        &self,
        reply: Qwen3AsrTranscript,
        frames: usize,
    ) -> WindowDecode<Qwen3AsrCarry> {
        let (_, text) = self
            .bundle
            .prompt
            .split_reply(&reply.tokens, &self.bundle.decoder.eos);
        let tokens: Vec<i64> = text.iter().map(|&t| t as i64).collect();
        let carry = Qwen3AsrCarry {
            language: reply.language,
        };
        if tokens.is_empty() {
            return WindowDecode {
                tokens,
                skip: true,
                segments: Vec::new(),
                advance: frames,
                tail: None,
                carry,
            };
        }
        WindowDecode::whole(frames, tokens, carry)
    }
}

/// What a Qwen3-ASR stream carries from one window to the next.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Qwen3AsrStreamState {
    /// The language of the stream: the first a committed reply names.
    pub language: Option<String>,
}

/// What a Qwen3-ASR decode hands back to its commit.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Qwen3AsrCarry {
    /// The language the reply names, if any.
    pub language: Option<String>,
}

impl AsrEngine for Qwen3AsrEngine {
    type Carry = Qwen3AsrCarry;
    type Features = LogMelFeatures;
    type Level = MaxLevel;
    type StreamState = Qwen3AsrStreamState;

    fn sample_rate(&self) -> usize {
        self.bundle.front_end.sample_rate()
    }

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

    fn window_frames(&self) -> usize {
        self.window_frames
    }

    fn grid_frames(&self) -> usize {
        1
    }

    /// The extractor's `stft[..., :-1]`: the stream's last frame is the end
    /// padding's.
    fn end_frames_dropped(&self) -> usize {
        1
    }

    fn new_features(&self) -> BunsenResult<LogMelFeatures> {
        Ok(LogMelFeatures::new(
            self.bundle.front_end.converter.clone(),
            self.device.clone(),
        ))
    }

    fn new_stream_state(&self) -> Qwen3AsrStreamState {
        Qwen3AsrStreamState::default()
    }

    fn decode(
        &self,
        requests: Vec<DecodeRequest<'_, Self>>,
    ) -> BunsenResult<Vec<WindowDecode<Qwen3AsrCarry>>> {
        requests
            .into_iter()
            .map(|request| {
                let mut window = request.window;
                let mut frames = window.dims()[1];
                let turn = match (&self.speaker_cut, &request.speakers) {
                    (Some(config), Some(activity)) => speaker_cut(
                        activity,
                        request.start,
                        self.hop(),
                        frames,
                        self.sample_rate(),
                        config,
                    ),
                    _ => None,
                };
                if let Some(cut) = turn {
                    frames = cut;
                    window = window.slice_dim(1, 0..frames);
                } else if self.quiet_cut && frames >= self.window_frames {
                    let loudness: Vec<f32> = window
                        .clone()
                        .mean_dim(2)
                        .reshape([frames])
                        .into_data()
                        .convert::<f32>()
                        .try_to_vec()
                        .expect("f32 data");
                    frames = quiet_cut(&loudness, QUIET_SPAN_FRAMES).max(1);
                    window = window.slice_dim(1, 0..frames);
                }
                let features = self.package(window, &request.level);
                let reply = self.bundle.transcribe_features(features, frames)?;
                Ok(self.lay_out(reply, frames))
            })
            .collect()
    }

    fn commit(
        &self,
        state: &mut Qwen3AsrStreamState,
        _transcript: &[i64],
        carry: Qwen3AsrCarry,
    ) {
        if state.language.is_none() {
            state.language = carry.language;
        }
    }

    fn text(
        &self,
        tokens: &[i64],
    ) -> BunsenResult<Option<String>> {
        let ids = tokens
            .iter()
            .map(|&t| {
                usize::try_from(t).map_err(|_| {
                    BunsenError::invalid_resource(format!("{t} is not a Qwen3-ASR token id"))
                })
            })
            .collect::<BunsenResult<Vec<usize>>>()?;
        Ok(Some(self.bundle.vocab.text(&ids)?))
    }
}

impl AsrStreamContext<Qwen3AsrEngine> {
    /// The language of the stream, once a committed reply names one.
    pub fn language(&self) -> Option<&str> {
        self.engine_state().language.as_deref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        burner::module::ModuleInit,
        kits::{
            gpts::qwen3::Qwen3Config,
            speech::{
                asr_driver::{
                    EmissionPolicy,
                    LevelPolicy,
                    LevelStatistic,
                    StreamClock,
                    StreamingFeatures,
                    TimedTokens,
                    TranscriptEvent,
                },
                qwen3_asr::{
                    Qwen3AsrFrontEndConfig,
                    Qwen3AsrGreedyDecoderConfig,
                    Qwen3AsrPromptConfig,
                    blocks::{
                        Qwen3Asr,
                        Qwen3AsrAudioEncoderConfig,
                        Qwen3AsrConfig,
                    },
                },
                testing::ToneConfig,
            },
            tokens::ByteLevelVocabulary,
        },
        support::testing::performance_device,
    };

    /// The toy's token count.
    const VOCAB: usize = 50;

    /// An untrained toy bundle: a 16-mel encoder, a 50-token text model and
    /// vocabulary, a prompt of small ids.
    fn toy_bundle(
        text_token: usize,
        eos: Vec<usize>,
        device: &Device,
    ) -> Qwen3AsrBundle {
        let config = Qwen3AsrConfig::new(
            Qwen3AsrAudioEncoderConfig::new(16, 32, 4, 64, 2, 8).with_n_window_infer(200),
            Qwen3Config::new(VOCAB, 24, 2, 4, 2, 8, 48),
        )
        .with_audio_token(7);
        let model: Qwen3Asr = config.init(device);
        let entries: Vec<String> = (0..VOCAB).map(|i| format!("\"t{i}\": {i}")).collect();
        let vocab =
            ByteLevelVocabulary::from_vocab_json(&format!("{{{}}}", entries.join(", ")), None)
                .unwrap();
        Qwen3AsrBundle {
            model,
            front_end: Qwen3AsrFrontEndConfig::new().with_n_mels(16).init(device),
            vocab,
            prompt: Qwen3AsrPromptConfig::new()
                .with_prefix(vec![1, 2])
                .with_suffix(vec![3])
                .with_text_token(text_token),
            decoder: Qwen3AsrGreedyDecoderConfig::new()
                .with_max_new_tokens(3)
                .with_eos(eos),
        }
    }

    /// A window is set in seconds, rounded down to whole frames, and never
    /// past the model's range.
    #[test]
    fn test_window_seconds() {
        let device = performance_device();
        let engine = Qwen3AsrEngine::new(Arc::new(toy_bundle(4, vec![5], &device)));
        assert_eq!(engine.window_frames(), 3000);
        assert_eq!(
            engine.clone().with_window_seconds(12.345).window_frames(),
            1234
        );
        assert_eq!(engine.with_window_seconds(30.0).window_frames(), 3000);
    }

    #[test]
    #[should_panic(expected = "over 30 s")]
    fn test_window_past_the_range_panics() {
        let device = performance_device();
        Qwen3AsrEngine::new(Arc::new(toy_bundle(4, vec![5], &device))).with_window_seconds(30.5);
    }

    /// A streamed window, packaged, is the front end's one-shot features,
    /// padding included, but for the frames either side of the stream's
    /// end, where streaming reflects and the one-shot extractor pads with
    /// zeros.
    #[test]
    fn test_packaging_matches_the_one_shot_front_end() {
        let device = performance_device();
        let engine = Qwen3AsrEngine::new(Arc::new(toy_bundle(4, vec![5], &device)));
        assert_eq!(engine.window_frames(), 3000);
        let samples = ToneConfig::Duration {
            seconds: 2.0,
            hz: 16_000.0,
        }
        .build();

        let (one_shot, valid) = engine
            .bundle()
            .front_end
            .forward(&samples, &device)
            .unwrap();
        assert_eq!(one_shot.dims(), [16, 3000]);

        let mut features = engine.new_features().unwrap();
        let mut frames: Vec<Tensor<3>> = features.push(&samples).unwrap().into_iter().collect();
        frames.extend(features.finish().unwrap());
        let frames = Tensor::cat(frames, 1);
        let n = frames.dims()[1] - engine.end_frames_dropped();
        let window = frames.slice_dim(1, 0..n);
        assert_eq!(n, valid);

        let level = MaxLevel::of(window.clone());
        let packaged = engine.package(window, &level);
        assert_eq!(packaged.dims(), one_shot.dims());

        for range in [0..valid - 2, valid + 2..3000] {
            packaged
                .clone()
                .slice_dim(1, range.clone())
                .to_data()
                .assert_approx_eq::<f32>(
                    &one_shot.clone().slice_dim(1, range).to_data(),
                    burn::tensor::Tolerance::absolute(1e-4),
                );
        }
    }

    /// A reply's transcript is one segment over the window; a reply without
    /// one skips it; the stream keeps the first language a commit names.
    #[test]
    fn test_lay_out_and_commit() {
        let device = performance_device();
        let engine = Qwen3AsrEngine::new(Arc::new(toy_bundle(4, vec![5], &device)));
        let reply = |tokens: Vec<usize>, language: Option<&str>| Qwen3AsrTranscript {
            tokens,
            language: language.map(String::from),
            text: String::new(),
        };

        let decode = engine.lay_out(reply(vec![10, 4, 12, 13, 5, 9], Some("English")), 100);
        assert!(!decode.skip);
        assert_eq!(decode.tokens, [12, 13]);
        assert_eq!(
            decode.segments,
            [TimedTokens {
                start: 0,
                end: 100,
                tokens: vec![12, 13],
            }]
        );
        assert_eq!((decode.advance, decode.tail), (100, None));

        let silent = engine.lay_out(reply(vec![10, 4, 5], None), 100);
        assert!(silent.skip);
        assert!(silent.segments.is_empty());
        assert_eq!(silent.advance, 100);

        let mut state = engine.new_stream_state();
        engine.commit(&mut state, &[], silent.carry);
        assert_eq!(state.language, None);
        engine.commit(&mut state, &[12, 13], decode.carry);
        assert_eq!(state.language.as_deref(), Some("English"));
        engine.commit(
            &mut state,
            &[12, 13],
            Qwen3AsrCarry {
                language: Some("German".into()),
            },
        );
        assert_eq!(state.language.as_deref(), Some("English"));

        assert_eq!(engine.text(&[12, 13]).unwrap().as_deref(), Some("t12t13"));
        assert!(engine.text(&[-1]).is_err());
    }

    /// Streamed in pieces under the offline policy, a clip shorter than a
    /// window is one committed segment over all of it.
    #[test]
    fn test_streams_through_the_core() {
        let device = performance_device();
        // No end token, and a text token the model cannot produce: every
        // reply is three tokens of transcript.
        let engine = Qwen3AsrEngine::new(Arc::new(toy_bundle(VOCAB, Vec::new(), &device)));
        let driver = Qwen3AsrStreamDriver::new(engine, EmissionPolicy::offline()).unwrap();
        let mut stream = driver
            .new_context(StreamClock::uniform(16_000), LevelPolicy::PerWindow)
            .unwrap();

        let samples = ToneConfig::Duration {
            seconds: 2.5,
            hz: 16_000.0,
        }
        .build();
        let mut events = Vec::new();
        for piece in samples.chunks(1_000) {
            events.extend(stream.write_read(piece).unwrap());
        }
        events.extend(stream.end_read().unwrap());

        let [TranscriptEvent::Committed(segment)] = events.as_slice() else {
            panic!("one committed segment, got {events:?}");
        };
        assert_eq!(segment.tokens.len(), 3);
        assert_eq!(segment.start, 0.0);
        assert!((segment.end - 2.5).abs() < 0.011, "{}", segment.end);
        assert_eq!(segment.text, driver.engine().text(&segment.tokens).unwrap());
        assert_eq!(stream.language(), None);
    }

    /// A full window is decoded up to its quietest stretch in its last
    /// third, and the stream moves on from there; turned off, it is decoded
    /// whole.
    #[test]
    fn test_full_windows_are_cut_quiet() {
        let device = performance_device();
        // A tone, silent from 0.8 s to 0.9 s, then sounding again to 1.6 s.
        let mut samples = ToneConfig::Duration {
            seconds: 1.6,
            hz: 16_000.0,
        }
        .build();
        samples[12_800..14_400].fill(0.0);
        let commits = |engine: Qwen3AsrEngine| {
            let driver = Qwen3AsrStreamDriver::new(engine, EmissionPolicy::offline()).unwrap();
            let mut stream = driver
                .new_context(StreamClock::uniform(16_000), LevelPolicy::PerWindow)
                .unwrap();
            let mut events = Vec::new();
            for piece in samples.chunks(1_000) {
                events.extend(stream.write_read(piece).unwrap());
            }
            events.extend(stream.end_read().unwrap());
            events
                .into_iter()
                .map(|e| {
                    let TranscriptEvent::Committed(segment) = e else {
                        panic!("the offline policy only commits: {e:?}");
                    };
                    (segment.start, segment.end)
                })
                .collect::<Vec<_>>()
        };
        let engine = Qwen3AsrEngine::new(Arc::new(toy_bundle(VOCAB, Vec::new(), &device)))
            .with_window_seconds(1.0);

        let cut = commits(engine.clone());
        assert!(cut.len() >= 2, "{cut:?}");
        assert!((0.8..=0.9).contains(&cut[0].1), "{cut:?}");
        assert_eq!(cut[1].0, cut[0].1);

        let whole = commits(engine.with_quiet_cut(false));
        assert!((whole[0].1 - 1.0).abs() < 1e-9, "{whole:?}");
    }

    /// With a diarizer, a window is cut where the speaker changes, past the
    /// minimum, and each segment is the one speaker's; turned off, or with
    /// the turn before the minimum, the window is decoded whole.
    #[test]
    fn test_windows_are_cut_at_speaker_turns() {
        use crate::kits::speech::{
            asr_driver::{
                MeanActivity,
                SpeakerCutConfig,
            },
            testing::ScriptedDiarizer,
        };

        let device = performance_device();
        let samples = ToneConfig::Duration {
            seconds: 4.0,
            hz: 16_000.0,
        }
        .build();
        let diarizer = Arc::new(ScriptedDiarizer {
            sample_rate: 16_000,
            frame_samples: 160,
            n_speakers: 2,
            latency: 3_200,
            script: vec![(0, Some(0)), (24_000, Some(1))],
        });
        let commits = |engine: Qwen3AsrEngine| {
            let driver = Qwen3AsrStreamDriver::new(engine, EmissionPolicy::offline())
                .unwrap()
                .with_speakers(diarizer.clone(), Arc::new(MeanActivity::default()))
                .unwrap();
            let mut stream = driver
                .new_context(StreamClock::uniform(16_000), LevelPolicy::PerWindow)
                .unwrap();
            let mut events = Vec::new();
            for piece in samples.chunks(1_000) {
                events.extend(stream.write_read(piece).unwrap());
            }
            events.extend(stream.end_read().unwrap());
            events
                .into_iter()
                .map(|e| {
                    let s = e.segment().clone();
                    (s.start, s.end, s.speaker.map(|l| l.index))
                })
                .collect::<Vec<_>>()
        };
        let engine = Qwen3AsrEngine::new(Arc::new(toy_bundle(VOCAB, Vec::new(), &device)));

        let cut = commits(
            engine
                .clone()
                .with_speaker_cut(Some(SpeakerCutConfig::new().with_min_window_seconds(1.0))),
        );
        assert_eq!(cut.len(), 2, "{cut:?}");
        assert_eq!((cut[0].0, cut[0].2), (0.0, Some(0)));
        assert!((cut[0].1 - 1.5).abs() < 1e-9, "{cut:?}");
        assert_eq!((cut[1].0, cut[1].2), (cut[0].1, Some(1)));

        let whole = commits(engine.clone().with_speaker_cut(None));
        assert_eq!(whole.len(), 1, "{whole:?}");

        // The default minimum is 2 s: a turn at 1.5 s does not cut.
        let late = commits(engine);
        assert_eq!(
            late.len(),
            1,
            "a turn before the minimum does not cut: {late:?}"
        );
    }
}