bunsen 0.42.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
use burn::{
    Tensor,
    config::Config,
    module::{
        Module,
        Param,
    },
    nn::{
        LayerNorm,
        LayerNormConfig,
        PaddingConfig1d,
        conv::Conv1dConfig,
    },
    prelude::s,
    tensor::{
        Device,
        Distribution,
        FloatDType,
    },
};

use super::WHISPER_DEFAULT_D_MODEL;
use crate::{
    blocks::{
        activation::BunsenActivationConfig,
        conv::{
            ConvBlock1dConfig,
            ConvSeq1d,
            ConvSeq1dConfig,
            ConvSeq1dMeta,
        },
        transformers::encoders::residual::{
            ResidualEncoderAttentionBlock,
            ResidualEncoderAttentionBlockConfig,
            ResidualEncoderAttentionBlockMeta,
        },
    },
    burner::module::{
        CanonicalKeys,
        CoercesInput,
        InputDTypes,
        ModuleInit,
        Rekey,
        ResultDType,
    },
    errors::BunsenResult,
};

/// The conv head's stride: it halves the mel sequence, so one encoder
/// position covers this many mel frames. It is also what makes one
/// timestamp token one encoder position: the token step is this many hops.
pub const AUDIO_ENCODER_STRIDE: usize = 2;

/// Common meta for [`AudioEncoder`] and [`AudioEncoderConfig`].
pub trait AudioEncoderMeta {
    /// Returns the Mel-scale frequency resolution.
    fn n_mels(&self) -> usize;

    /// Returns the max audio context size.
    ///
    /// Due to the stride reduction of the conv layers, the max context is
    /// twice the internal positional embedding.
    fn max_context(&self) -> usize;

    /// The embedding size of the model.
    fn d_model(&self) -> usize;

    /// Returns the number of heads.
    fn n_heads(&self) -> usize;

    /// Returns the number of layers.
    fn n_layers(&self) -> usize;
}

/// Config for [`AudioEncoder`].
#[derive(Config, Debug)]
pub struct AudioEncoderConfig {
    /// The Mel-scale frequency resolution.
    pub n_mels: usize,

    /// The embedding size of the model.
    pub d_model: usize,

    /// Max audio context size.
    ///
    /// Due to the stride reduction of the conv layers, the max context is
    /// twice the internal positional embedding.
    pub max_context: usize,

    /// Number of Audio Layers.
    pub n_layers: usize,

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

    /// Head Activation.
    #[config(default = "BunsenActivationConfig::Gelu")]
    pub head_activation: BunsenActivationConfig,
}

impl AudioEncoderMeta for AudioEncoderConfig {
    fn n_mels(&self) -> usize {
        self.n_mels
    }

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

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

    fn n_heads(&self) -> usize {
        self.d_model / self.d_head
    }

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

impl ModuleInit<AudioEncoder> for AudioEncoderConfig {
    fn try_init(
        &self,
        device: &Device,
    ) -> BunsenResult<AudioEncoder> {
        let pos_ctx = self.max_context / AUDIO_ENCODER_STRIDE;

        Ok(AudioEncoder {
            head: ConvSeq1dConfig::new(vec![
                ConvBlock1dConfig::new(
                    Conv1dConfig::new(self.n_mels, self.d_model, 3)
                        .with_padding(PaddingConfig1d::Explicit(1, 1)),
                ),
                ConvBlock1dConfig::new(
                    Conv1dConfig::new(self.d_model, self.d_model, 3)
                        .with_padding(PaddingConfig1d::Explicit(1, 1))
                        .with_stride(AUDIO_ENCODER_STRIDE),
                ),
            ])
            .with_act(self.head_activation.clone())
            .try_init(device)?,

            positional_embedding: Param::from_tensor(Tensor::random(
                [pos_ctx, self.d_model],
                Distribution::Normal(0.0, 1.0),
                device,
            )),

            blocks: (0..self.n_layers)
                .map(|_| {
                    ResidualEncoderAttentionBlockConfig::new(self.d_model)
                        .with_d_head(self.d_head)
                        .try_init(device)
                })
                .collect::<BunsenResult<Vec<ResidualEncoderAttentionBlock>>>()?,

            ln_post: LayerNormConfig::new(self.d_model).init(device),
        })
    }
}

/// Whisper Audio Encoder.
///
/// Encodes a log-Mel spectrogram into audio feature states.
///
/// Built by [`AudioEncoderConfig`].
#[derive(Module, Debug)]
pub struct AudioEncoder {
    /// The head conv stack; a stride-2 down-sampling sequence of
    /// [`ConvBlock1d`](crate::blocks::conv::ConvBlock1d) modules.
    pub head: ConvSeq1d,

    /// The positional embedding.
    pub positional_embedding: Param<Tensor<2>>,

    /// The audio encoder blocks.
    pub blocks: Vec<ResidualEncoderAttentionBlock>,

    /// The final `LayerNorm`.
    pub ln_post: LayerNorm,
}

impl AudioEncoderMeta for AudioEncoder {
    fn n_mels(&self) -> usize {
        self.head.in_channels()
    }

    fn d_model(&self) -> usize {
        self.blocks[0].d_model()
    }

    fn max_context(&self) -> usize {
        let pos_ctx = self.positional_embedding.val().dims()[0];
        // Due to the stride reduction of the conv layers, the max context is
        // twice the internal positional embedding.
        pos_ctx * AUDIO_ENCODER_STRIDE
    }

    fn n_heads(&self) -> usize {
        self.blocks[0].n_heads()
    }

    fn n_layers(&self) -> usize {
        self.blocks.len()
    }
}

impl InputDTypes for AudioEncoder {
    /// The dtype its parameters were loaded in, and so the one it computes
    /// in.
    fn preferred_dtype(&self) -> FloatDType {
        FloatDType::from(self.positional_embedding.dtype())
    }
}

/// [`forward`](AudioEncoder::forward) casts its mel input
/// ([`forward_head`](AudioEncoder::forward_head)).
impl CoercesInput for AudioEncoder {}

impl ResultDType for AudioEncoder {
    /// Its own, whatever the input's: the features stay in the model's dtype
    /// ([`forward`](AudioEncoder::forward)).
    fn result_dtype(
        &self,
        _input: FloatDType,
    ) -> FloatDType {
        self.preferred_dtype()
    }
}

impl AudioEncoder {
    /// Forward pass through the audio encoder.
    ///
    /// # Arguments
    /// * `x`: The input audio spectrogram `[batch, n_mels, seq]`, in any float
    ///   dtype. The mel front end works in the backend's default float;
    ///   [`forward_head`](Self::forward_head) casts to
    ///   [`preferred_dtype`](InputDTypes::preferred_dtype).
    ///
    /// # Returns
    /// `[batch, seq, n_audio_states]`, in the encoder's
    /// [`preferred_dtype`](InputDTypes::preferred_dtype).
    ///
    /// These features are not an interface value: they are the decoder's
    /// input, and the source of its cross-attention cache. Widening them
    /// here would only have the decoder narrow them again, and would put
    /// the bulk of that cache at the wrong precision, so they stay in the
    /// model's.
    pub fn forward(
        &self,
        x: Tensor<3>,
    ) -> Tensor<3> {
        let x = self.forward_head(x);

        let mut x = self.embed(x);

        for b in self.blocks.iter() {
            x = b.forward(x);
        }

        self.ln_post.forward(x)
    }

    /// Forward pass through the audio encoder head.
    ///
    /// The encoder's one tensor entry point: `x` is cast to
    /// [`preferred_dtype`](InputDTypes::preferred_dtype) here, and everything
    /// downstream of it is in the model's precision.
    ///
    /// # Arguments
    /// * `x`: The input audio spectrogram `[batch, n_mels, seq]`, in any float
    ///   dtype.
    ///
    /// # Returns
    /// `[batch, seq, d_model]`.
    pub fn forward_head(
        &self,
        x: Tensor<3>,
    ) -> Tensor<3> {
        let x = self.coerce_input(x);

        #[cfg(any(debug_assertions, test))]
        let [batch] = crate::contracts::unpack_shape_contract!(
            ["batch", "n_mels", "seq_len"],
            &x,
            &["batch"],
            &[("n_mels", self.n_mels())],
        );
        let seq_len = x.dims()[2];

        assert!(
            seq_len <= self.max_context(),
            "Audio length {} cannot exceed {}.",
            seq_len,
            self.max_context()
        );

        let x = self.head.forward(x);

        let x = x.swap_dims(1, 2);

        #[cfg(any(debug_assertions, test))]
        crate::contracts::assert_shape_contract_periodically!(
            ["batch", "len", "d_model"],
            &x,
            &[
                ("batch", batch),
                ("len", self.head.try_output_length(seq_len).unwrap()),
                ("d_model", self.d_model()),
            ],
        );

        x
    }

    /// Add the positional embedding.
    ///
    /// # Arguments
    /// * `x`: The input audio spectrogram `[batch, n_mels, seq]`.
    ///
    /// # Returns
    /// `[batch, seq, d_model]`.
    pub fn embed(
        &self,
        x: Tensor<3>,
    ) -> Tensor<3> {
        let k = x.dims()[1];
        x + self
            .positional_embedding
            .val()
            .slice(s![0..k])
            .unsqueeze::<3>()
    }
}

impl CanonicalKeys for AudioEncoder {
    fn canonical_rekey(&self) -> Rekey {
        Rekey::keep_rest().mount_canonical("blocks.", &self.blocks)
    }
}

#[cfg(test)]
mod tests {
    use serial_test::serial;

    use super::*;
    use crate::{
        contracts::assert_shape_contract,
        support::testing::{
            DeviceMemoryGuard,
            performance_device,
        },
    };

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

        let d_model = 128;
        let n_mels = 256;
        let max_audio_ctx = 100;

        let n_audio_layers = 2;

        let config = AudioEncoderConfig::new(n_mels, d_model, max_audio_ctx, n_audio_layers);
        let n_audio_heads = config.n_heads();

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

        let encoder: AudioEncoder = config.init(&device);

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

        let batch = 2;
        let k = max_audio_ctx / 2;
        let x: Tensor<3> = Tensor::random([batch, n_mels, k], Default::default(), &device);

        let output = encoder.forward(x.clone());

        assert_shape_contract!(
            ["batch", "seq", "d_model"],
            &output,
            &[("batch", batch), ("seq", k / 2), ("d_model", d_model),],
        );
    }

    /// The encoder coerces its mel input: an f32 input to an f16 encoder
    /// gives what an f16 input does.
    #[test]
    fn test_encoder_coerces_its_input() {
        use burn::{
            module::Module,
            tensor::{
                DType,
                Distribution,
            },
        };

        use crate::{
            burner::module::DTypeMapper,
            support::testing::{
                assert_coerces_input,
                cpu_device,
            },
        };

        let device = cpu_device();
        let encoder: AudioEncoder = AudioEncoderConfig::new(8, 64, 16, 1).init(&device);
        let encoder = encoder.map(&mut DTypeMapper::new(DType::F16));
        let mel: Tensor<3> = Tensor::random([1, 8, 16], Distribution::Default, &device);
        assert_coerces_input(&encoder, mel, |e, x| e.forward(x), 0.0);
    }
}