bunsen 0.32.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
use burn::{
    Tensor,
    config::Config,
    module::Module,
    prelude::{
        Backend,
        Int,
    },
};

use super::{
    WHISPER_DEFAULT_D_MODEL,
    WhisperFrontEndConfig,
    WhisperTokenLayoutConfig,
};
use crate::{
    burner::{
        module::ModuleInit,
        store::FixPytorchLoadMappers,
    },
    kits::speech::whisper::blocks::{
        AudioEncoder,
        AudioEncoderConfig,
        AudioEncoderMeta,
        TextDecoder,
        TextDecoderConfig,
        TextDecoderMeta,
    },
};

/// Whisper API config.
///
/// User-facing configuration for the [`Whisper`] model, exposing the flat
/// hyperparameters (Mel resolution, vocabulary, model/head sizes, context
/// limits, and encoder/decoder layer counts). Expands via
/// [`to_structure`](WhisperApiConfig::to_structure) into a
/// [`WhisperStructuralConfig`], and builds the [`Whisper`] module directly via
/// [`ModuleInit`].
#[derive(Config, Debug)]
pub struct WhisperApiConfig {
    /// The Mel-scale frequency resolution.
    pub n_mels: usize,

    /// The audio front end the checkpoint's log-mels were computed
    /// with.
    ///
    /// A checkpoint does not record it; it is the convention of the
    /// pipeline that trained it, and the loader declares it. Every
    /// sample-domain quantity of the front end is derived from it.
    #[config(default = "WhisperFrontEndConfig::new()")]
    pub front_end: WhisperFrontEndConfig,

    /// The token layout the checkpoint's vocabulary follows: what its size
    /// does not say — the language codes, the spellings, the timestamp
    /// grid. Upstream's by default.
    #[config(default = "WhisperTokenLayoutConfig::new()")]
    pub token_layout: WhisperTokenLayoutConfig,

    /// The size of the vocabulary.
    pub vocab_size: usize,

    /// Embedding Size of the Model.
    pub d_model: usize,

    /// Maximum Audio Encoder Context Size.
    pub max_audio_ctx: usize,

    /// Number Audio Encoder of Layers.
    pub n_encoder_layers: usize,

    /// Maximum Text Decoder Context Size.
    pub max_text_ctx: usize,

    /// Number Text Decoder of Layers.
    pub n_decoder_layers: usize,

    /// Head Dimensionality.
    #[config(default = "WHISPER_DEFAULT_D_MODEL")]
    pub d_head: usize,
}

impl WhisperApiConfig {
    /// Converts to a [`WhisperStructuralConfig`].
    pub fn to_structure(&self) -> WhisperStructuralConfig {
        WhisperStructuralConfig {
            front_end: self.front_end.clone(),
            token_layout: self.token_layout.clone(),
            encoder: AudioEncoderConfig::new(
                self.n_mels,
                self.d_model,
                self.max_audio_ctx,
                self.n_encoder_layers,
            )
            .with_d_head(self.d_head),
            decoder: TextDecoderConfig::new(
                self.vocab_size,
                self.d_model,
                self.max_text_ctx,
                self.n_decoder_layers,
            )
            .with_d_head(self.d_head),
        }
    }
}

impl<B: Backend> ModuleInit<B, Whisper<B>> for WhisperApiConfig {
    fn try_init(
        &self,
        device: &B::Device,
    ) -> crate::errors::BunsenResult<Whisper<B>> {
        self.to_structure().try_init(device)
    }
}

/// Common meta for [`Whisper`] and [`WhisperApiConfig`].
pub trait WhisperMeta {
    /// The audio front end the model's log-mels are computed with.
    fn front_end(&self) -> &WhisperFrontEndConfig;

    /// The token layout the model's vocabulary follows.
    fn token_layout(&self) -> &WhisperTokenLayoutConfig;

    /// The sample rate the model's log-mels are computed at, in Hz.
    fn sample_rate(&self) -> usize {
        self.front_end().sample_rate
    }

    /// Returns the Mel-scale frequency resolution.
    fn n_mels(&self) -> usize {
        self.encoder().n_mels()
    }

    /// Returns the vocabulary size.
    fn vocab_size(&self) -> usize {
        self.decoder().vocab_size()
    }

    /// Returns the embedding size of the model.
    fn d_model(&self) -> usize {
        self.encoder().d_model()
    }

    /// The max audio context size.
    fn max_audio_ctx(&self) -> usize {
        self.encoder().max_context()
    }

    /// The max text context size.
    fn max_text_ctx(&self) -> usize {
        self.decoder().max_context()
    }

    /// Returns the [`AudioEncoder`] meta.
    fn encoder(&self) -> &impl AudioEncoderMeta;

    /// Returns the [`TextDecoder`] meta.
    fn decoder(&self) -> &impl TextDecoderMeta;
}

/// [`Whisper`] structural config.
///
/// The fully-expanded structural configuration for the [`Whisper`] model,
/// pairing an [`AudioEncoderConfig`] with a [`TextDecoderConfig`]. Builds the
/// [`Whisper`] module via [`ModuleInit`].
#[derive(Config, Debug)]
pub struct WhisperStructuralConfig {
    /// The audio front end the model's log-mels are computed with.
    pub front_end: WhisperFrontEndConfig,

    /// The token layout the model's vocabulary follows.
    pub token_layout: WhisperTokenLayoutConfig,

    /// Encoder config.
    pub encoder: AudioEncoderConfig,

    /// Decoder config.
    pub decoder: TextDecoderConfig,
}

impl WhisperMeta for WhisperStructuralConfig {
    fn front_end(&self) -> &WhisperFrontEndConfig {
        &self.front_end
    }

    fn token_layout(&self) -> &WhisperTokenLayoutConfig {
        &self.token_layout
    }

    fn encoder(&self) -> &impl AudioEncoderMeta {
        &self.encoder
    }

    fn decoder(&self) -> &impl TextDecoderMeta {
        &self.decoder
    }
}

impl<B: Backend> ModuleInit<B, Whisper<B>> for WhisperStructuralConfig {
    fn try_init(
        &self,
        device: &B::Device,
    ) -> crate::errors::BunsenResult<Whisper<B>> {
        let encoder = self.encoder.init(device);
        let decoder = self.decoder.init(device);

        assert_eq!(encoder.d_model(), decoder.d_model());

        Ok(Whisper {
            front_end: self.front_end.clone(),
            token_layout: self.token_layout.clone(),
            encoder,
            decoder,
        })
    }
}

/// Whisper model
///
/// End-to-end Whisper speech recognition model, composing an [`AudioEncoder`]
/// over the input log-Mel spectrogram with a [`TextDecoder`] that
/// cross-attends to the encoder output to produce vocabulary logits.
///
/// Built by [`WhisperApiConfig`].
#[derive(Module, Debug)]
pub struct Whisper<B: Backend> {
    /// The audio front end the log-mels are computed with. A
    /// constant of the module, not part of its record: set by the config at
    /// `init`, it survives a checkpoint load, and the config carries it
    /// across a record round trip.
    #[module(skip)]
    front_end: WhisperFrontEndConfig,

    /// The token layout the vocabulary follows. Likewise not part of the
    /// record.
    #[module(skip)]
    token_layout: WhisperTokenLayoutConfig,

    /// The [`AudioEncoder`].
    pub encoder: AudioEncoder<B>,

    /// The [`TextDecoder`].
    pub decoder: TextDecoder<B>,
}

impl<B: Backend> FixPytorchLoadMappers for Whisper<B> {
    fn fix_pytorch_load_mappers(mut self) -> Self {
        self.encoder = self.encoder.fix_pytorch_load_mappers();
        self.decoder = self.decoder.fix_pytorch_load_mappers();
        self
    }
}

impl<B: Backend> WhisperMeta for Whisper<B> {
    fn front_end(&self) -> &WhisperFrontEndConfig {
        &self.front_end
    }

    fn token_layout(&self) -> &WhisperTokenLayoutConfig {
        &self.token_layout
    }

    fn encoder(&self) -> &impl AudioEncoderMeta {
        &self.encoder
    }

    fn decoder(&self) -> &impl TextDecoderMeta {
        &self.decoder
    }
}

impl<B: Backend> Whisper<B> {
    /// Forward pass through the Whisper model.
    ///
    /// # Arguments
    /// * `mel`: The input audio spectrogram `[batch, n_mels, seq]`.
    /// * `tokens`: `[batch, seq]`.
    ///
    /// # Returns
    /// `[batch, seq, vocab_size]`.
    pub fn forward(
        &self,
        mel: Tensor<B, 3>,
        tokens: Tensor<B, 2, Int>,
    ) -> Tensor<B, 3> {
        self.forward_decoder(tokens, self.forward_encoder(mel))
    }

    /// Forward pass through the Whisper encoder.
    ///
    /// # Arguments
    /// * `mel`: The input audio spectrogram `[batch, n_mels, seq]`.
    ///
    /// # Returns
    /// `[batch, seq, n_audio_states]`.
    pub fn forward_encoder(
        &self,
        mel: Tensor<B, 3>,
    ) -> Tensor<B, 3> {
        self.encoder.forward(mel)
    }

    /// Forward pass through the Whisper decoder.
    ///
    /// # Arguments
    /// * `tokens`: `[batch, seq]`.
    /// * `encoder_output`: `[batch, seq, d_model]`.
    ///
    /// # Returns
    /// `[batch, seq, vocab_size]`.
    pub fn forward_decoder(
        &self,
        tokens: Tensor<B, 2, Int>,
        encoder_output: Tensor<B, 3>,
    ) -> Tensor<B, 3> {
        self.decoder.forward(tokens, encoder_output)
    }
}

#[cfg(test)]
mod tests {
    use burn::{
        module::Param,
        prelude::{
            Device,
            TensorData,
        },
        tensor::DType,
    };
    use serial_test::serial;

    use super::*;
    use crate::{
        contracts::assert_shape_contract,
        support::testing::{
            CpuBackend,
            PerformanceBackend,
            param_load_mapping,
        },
    };

    /// Whether `param` carries a load-path mapping, read through a `[2, 3]`
    /// probe that the repair visibly reorders.
    fn is_mapped(
        param: &Param<Tensor<CpuBackend, 2>>,
        device: &Device<CpuBackend>,
    ) -> bool {
        let probe: Tensor<CpuBackend, 2> = Tensor::from_data(
            TensorData::new((0..6).map(|v| v as f64).collect::<Vec<_>>(), [2, 3]),
            device,
        );

        let flat = |t: Tensor<CpuBackend, 2>| -> Vec<f32> {
            t.cast(DType::F32).to_data().to_vec().unwrap()
        };

        flat(param_load_mapping(param, probe.clone())) != flat(probe)
    }

    /// **The walk's coverage.** Every `Linear` weight in the model must carry
    /// the repair, and nothing else may: a missed projection loads scrambled,
    /// and an extra one — on a parameter the checkpoint stores contiguously —
    /// is a silent transpose.
    #[test]
    fn test_fix_pytorch_load_mappers_covers_the_projections() {
        type B = CpuBackend;

        let device: Device<B> = Default::default();

        // `n_heads` is `d_model / d_head`, and `d_head` defaults to 64.
        let model: Whisper<B> = WhisperApiConfig::new(8, 16, 128, 16, 1, 16, 1)
            .try_init(&device)
            .unwrap();

        // Initialization leaves the parameters alone; the repair is attached
        // only on the way to a PyTorch load.
        assert!(!is_mapped(
            &model.encoder.blocks[0].attn.query.weight,
            &device
        ));

        let model = model.fix_pytorch_load_mappers();

        let encoder = &model.encoder.blocks[0];
        let decoder = &model.decoder.blocks[0];
        for weight in [
            &encoder.attn.query.weight,
            &encoder.attn.key.weight,
            &encoder.attn.value.weight,
            &encoder.attn.output.weight,
            &encoder.mlp.linear1.weight,
            &encoder.mlp.linear2.weight,
            &decoder.attn.query.weight,
            &decoder.attn.key.weight,
            &decoder.attn.value.weight,
            &decoder.attn.output.weight,
            &decoder.cross_attn.query.weight,
            &decoder.cross_attn.key.weight,
            &decoder.cross_attn.value.weight,
            &decoder.cross_attn.output.weight,
            &decoder.mlp.linear1.weight,
            &decoder.mlp.linear2.weight,
        ] {
            assert!(is_mapped(weight, &device));
        }

        // The embeddings are stored contiguously — the conv head's weights
        // are rank-3, which the repair cannot reach at all.
        assert!(!is_mapped(&model.encoder.positional_embedding, &device));
        assert!(!is_mapped(&model.decoder.positional_embedding, &device));
        assert!(!is_mapped(&model.decoder.token_embedding.weight, &device));
    }

    /// The front end and the token layout default to upstream's and ride
    /// config -> structure -> module.
    #[test]
    fn test_front_end_and_layout_propagate() {
        type B = CpuBackend;
        let device: Device<B> = Default::default();

        let config = WhisperApiConfig::new(8, 16, 128, 16, 1, 16, 1);
        assert_eq!(config.front_end, WhisperFrontEndConfig::new());
        assert_eq!(config.token_layout, WhisperTokenLayoutConfig::new());
        assert_eq!(config.to_structure().sample_rate(), 16_000);
        let model: Whisper<B> = config.try_init(&device).unwrap();
        assert_eq!(model.sample_rate(), 16_000);
        assert_eq!(model.token_layout().languages.len(), 100);

        let config = config
            .with_front_end(WhisperFrontEndConfig::new().with_sample_rate(8_000))
            .with_token_layout(WhisperTokenLayoutConfig::new().with_timestamp_tokens(751));
        assert_eq!(config.to_structure().sample_rate(), 8_000);
        let model: Whisper<B> = config.try_init(&device).unwrap();
        assert_eq!(model.sample_rate(), 8_000);
        assert_eq!(model.front_end().hop(), 80);
        assert_eq!(model.token_layout().timestamp_tokens, 751);
    }

    #[test]
    #[serial]
    fn test_whisper_forward() {
        type B = PerformanceBackend;
        let device = Default::default();

        let d_model = 128;
        let n_mels = 80;
        let vocab_size = 64;

        let max_audio_ctx = 128;
        let n_audio_layers = 2;

        let max_text_context = 128;
        let n_text_layers = 2;

        let config = WhisperApiConfig::new(
            n_mels,
            vocab_size,
            d_model,
            max_audio_ctx,
            n_audio_layers,
            max_text_context,
            n_text_layers,
        );

        let structural = config.to_structure();

        let n_audio_heads = structural.encoder.n_heads();
        let n_text_heads = structural.decoder.n_heads();

        assert_eq!(structural.n_mels(), n_mels);
        assert_eq!(structural.vocab_size(), vocab_size);
        assert_eq!(structural.d_model(), d_model);
        assert_eq!(structural.max_audio_ctx(), max_audio_ctx);
        assert_eq!(structural.max_text_ctx(), max_text_context);

        assert_eq!(structural.encoder().n_mels(), n_mels);
        assert_eq!(structural.encoder().d_model(), d_model);
        assert_eq!(structural.encoder().max_context(), max_audio_ctx);
        assert_eq!(structural.encoder().n_heads(), n_audio_heads);
        assert_eq!(structural.encoder().n_layers(), n_audio_layers);

        assert_eq!(structural.decoder().vocab_size(), vocab_size);
        assert_eq!(structural.decoder().d_model(), d_model);
        assert_eq!(structural.decoder().max_context(), max_text_context);
        assert_eq!(structural.decoder().n_heads(), n_text_heads);
        assert_eq!(structural.decoder().n_layers(), n_text_layers);

        let model: Whisper<B> = structural.try_init(&device).unwrap();

        assert_eq!(model.n_mels(), n_mels);
        assert_eq!(model.vocab_size(), vocab_size);
        assert_eq!(model.d_model(), d_model);
        assert_eq!(model.max_audio_ctx(), max_audio_ctx);
        assert_eq!(model.max_text_ctx(), max_text_context);

        assert_eq!(model.encoder().n_mels(), n_mels);
        assert_eq!(model.encoder().d_model(), d_model);
        assert_eq!(model.encoder().max_context(), max_audio_ctx);
        assert_eq!(model.encoder().n_heads(), n_audio_heads);
        assert_eq!(model.encoder().n_layers(), n_audio_layers);

        assert_eq!(model.decoder().vocab_size(), vocab_size);
        assert_eq!(model.decoder().d_model(), d_model);
        assert_eq!(model.decoder().max_context(), max_text_context);
        assert_eq!(model.decoder().n_heads(), n_text_heads);
        assert_eq!(model.decoder().n_layers(), n_text_layers);

        let batch = 2;
        let audio_len = max_audio_ctx / 2;
        // The encoder halves the audio sequence (conv stride 2); the decoder's
        // cross-attention expects the token sequence to match that length.
        let token_len = audio_len / 2;

        let mel: Tensor<B, 3> =
            Tensor::random([batch, n_mels, audio_len], Default::default(), &device);
        let tokens: Tensor<B, 2, Int> = Tensor::zeros([batch, token_len], &device);

        // The encoder halves the audio sequence length (conv stride 2).
        let encoder_output = model.forward_encoder(mel.clone());
        assert_shape_contract!(
            ["batch", "seq", "d_model"],
            &encoder_output,
            &[
                ("batch", batch),
                ("seq", audio_len / 2),
                ("d_model", d_model),
            ],
        );

        // The full forward pass produces vocab logits per input token.
        let output = model.forward(mel, tokens);
        assert_shape_contract!(
            ["batch", "seq", "vocab_size"],
            &output,
            &[
                ("batch", batch),
                ("seq", token_len),
                ("vocab_size", vocab_size)
            ],
        );
    }
}