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
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
//! The Voxtral Realtime audio encoder.
use burn::{
    Tensor,
    config::Config,
    module::Module,
    nn::{
        PaddingConfig1d,
        conv::Conv1dConfig,
        norm::RmsNormConfig,
    },
    tensor::Device,
};

use crate::{
    blocks::{
        activation::BunsenActivationConfig,
        conv::{
            ConvBlock1dConfig,
            ConvSeq1d,
            ConvSeq1dConfig,
        },
        norm::BunsenNormalizationConfig,
        transformers::{
            attention::csa::CausalSelfAttentionConfig,
            decoders::{
                causal::CausalDecoderBlockConfig,
                stack::{
                    DecoderStack,
                    DecoderStackMeta,
                    DecoderStackStructureConfig,
                    UniformStackConfig,
                },
            },
            embedding::{
                RotaryDirection,
                RotaryEmbeddingConfig,
                RotarySet,
            },
            mlp::TransformerGatedMlpConfig,
        },
    },
    burner::module::{
        CanonicalKeys,
        ModuleInit,
        Rekey,
        ToStructureConfig,
    },
    errors::BunsenResult,
    ops::transformers::attention::{
        KVCache,
        KVCacheConfig,
        KVCacheModel,
    },
};

/// Mel frames per encoder frame: the stem's second convolution has stride 2.
pub const VOXTRAL_STEM_STRIDE: usize = 2;

/// Common meta for [`VoxtralAudioEncoder`] and [`VoxtralAudioEncoderConfig`].
pub trait VoxtralAudioEncoderMeta {
    /// The mel channel count.
    fn n_mels(&self) -> usize;

    /// The model width.
    fn d_model(&self) -> usize;

    /// The layer count.
    fn n_layers(&self) -> usize;

    /// The attention head count (as many key/value heads).
    fn n_heads(&self) -> usize;

    /// The head width.
    fn head_dim(&self) -> usize;

    /// The attention window, in encoder frames, if any.
    fn sliding_window(&self) -> Option<usize>;

    /// The encoder frames `frames` mel frames yield: `ceil(frames / 2)`.
    fn output_len(
        &self,
        frames: usize,
    ) -> usize {
        frames.div_ceil(VOXTRAL_STEM_STRIDE)
    }
}

/// The positions an encoder cache allocates up front by default: 30 s of
/// encoder frames.
pub const VOXTRAL_AUDIO_KV_CACHE_PRE_SIZE: usize = 1536;

fn kv_cache_config(meta: &impl VoxtralAudioEncoderMeta) -> KVCacheConfig {
    KVCacheConfig::for_decode(
        meta.n_heads(),
        VOXTRAL_AUDIO_KV_CACHE_PRE_SIZE,
        meta.head_dim(),
        meta.n_layers(),
    )
}

impl KVCacheModel for VoxtralAudioEncoderConfig {
    fn kv_cache_config(&self) -> KVCacheConfig {
        kv_cache_config(self)
    }
}

impl KVCacheModel for VoxtralAudioEncoder {
    fn kv_cache_config(&self) -> KVCacheConfig {
        self.stack.kv_cache_config(VOXTRAL_AUDIO_KV_CACHE_PRE_SIZE)
    }
}

/// Config for [`VoxtralAudioEncoder`]: `transformers`'
/// `VoxtralRealtimeEncoderConfig`.
///
/// Implements [`VoxtralAudioEncoderMeta`].
#[derive(Config, Debug)]
pub struct VoxtralAudioEncoderConfig {
    /// The mel channel count.
    pub n_mels: usize,

    /// The model width.
    pub d_model: usize,

    /// The attention head count (as many key/value heads).
    pub n_heads: usize,

    /// The head width.
    pub head_dim: usize,

    /// The feed-forward hidden width.
    pub d_ff: usize,

    /// The layer count.
    pub n_layers: usize,

    /// The RMS normalization epsilon.
    #[config(default = "1e-5")]
    pub rms_eps: f64,

    /// The rotary embedding's base.
    #[config(default = "1_000_000")]
    pub rope_theta: usize,

    /// The attention window, in encoder frames; `None` attends to the whole
    /// past.
    #[config(default = "Some(750)")]
    pub sliding_window: Option<usize>,
}

impl VoxtralAudioEncoderConfig {
    /// `Voxtral-Mini-4B-Realtime-2602`'s: 128 mels, 32 layers of width 1280
    /// with 32 heads of 64, a 5120-wide feed-forward, a 750-frame (15 s)
    /// window.
    pub fn voxtral_mini_4b_realtime() -> Self {
        Self::new(128, 1280, 32, 64, 5120, 32)
    }

    /// The layer stack: `n_layers` alike, after the stem.
    pub fn stack(&self) -> UniformStackConfig {
        let norm = BunsenNormalizationConfig::Rms(RmsNormConfig::new(0).with_epsilon(self.rms_eps));
        UniformStackConfig::new(
            self.n_layers,
            self.layer().with_norm(norm.clone()),
            norm,
            RotaryEmbeddingConfig::new(0, self.head_dim)
                .with_base(self.rope_theta)
                .with_direction(RotaryDirection::Forward),
        )
    }

    /// The layer config.
    fn layer(&self) -> CausalDecoderBlockConfig {
        CausalDecoderBlockConfig::new(
            CausalSelfAttentionConfig::new(self.n_heads, self.n_heads, self.d_model)
                .with_head_dim(Some(self.head_dim))
                .with_norm(None)
                .with_qkv_bias(true)
                .with_key_bias(Some(false))
                .with_output_bias(true)
                .with_sliding_window(self.sliding_window)
                // As `transformers`' eager attention: the softmax in f32.
                .with_softmax_dtype(Some(burn::tensor::FloatDType::F32))
                .into(),
            TransformerGatedMlpConfig::new(self.d_model, self.d_ff)
                .with_down_bias(Some(true))
                .into(),
        )
    }
}

impl VoxtralAudioEncoderMeta for VoxtralAudioEncoderConfig {
    fn n_mels(&self) -> usize {
        self.n_mels
    }

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

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

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

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

    fn sliding_window(&self) -> Option<usize> {
        self.sliding_window
    }
}

impl ToStructureConfig for VoxtralAudioEncoderConfig {
    type Structure = VoxtralAudioEncoderStructureConfig;

    /// # Errors
    /// As the stack's lowering.
    fn try_to_structure(&self) -> BunsenResult<VoxtralAudioEncoderStructureConfig> {
        // Causal: each convolution's whole context is to the left, `kernel -
        // stride` frames of it.
        let conv = |c_in, stride: usize| {
            ConvBlock1dConfig::new(
                Conv1dConfig::new(c_in, self.d_model, 3)
                    .with_stride(stride)
                    .with_padding(PaddingConfig1d::Explicit(3 - stride, 0)),
            )
            .with_act(Some(BunsenActivationConfig::Gelu))
        };
        Ok(VoxtralAudioEncoderStructureConfig::new(
            ConvSeq1dConfig::new(vec![
                conv(self.n_mels, 1),
                conv(self.d_model, VOXTRAL_STEM_STRIDE),
            ]),
            self.stack().try_to_structure()?,
        ))
    }
}

/// Structure config for [`VoxtralAudioEncoder`]: its causal convolution stem
/// and its stack, unrolled. [`VoxtralAudioEncoderConfig`] lowers to it.
#[derive(Config, Debug)]
pub struct VoxtralAudioEncoderStructureConfig {
    /// The causal convolution stem: `n_mels -> d_model -> d_model`.
    pub stem: ConvSeq1dConfig,

    /// The layers, their final norm and their rotary embedding.
    pub stack: DecoderStackStructureConfig,
}

impl ModuleInit<VoxtralAudioEncoder> for VoxtralAudioEncoderStructureConfig {
    fn try_init(
        &self,
        device: &Device,
    ) -> BunsenResult<VoxtralAudioEncoder> {
        Ok(VoxtralAudioEncoder {
            stem: self.stem.try_init(device)?,
            stack: self.stack.try_init(device)?,
        })
    }
}

/// Voxtral Realtime's audio encoder: a causal convolution stem, then a stack
/// of causal rotary self-attention layers.
///
/// The stem's two convolutions (kernel 3, GELU, the second of stride 2) see
/// only the frames before them, so 100 Hz log-mels become 50 Hz encoder
/// frames that never look ahead. The layers are a generic [`DecoderStack`]
/// ([`VoxtralAudioEncoderConfig::stack`]): pre-norm RMS, causal self-attention
/// with rotary embeddings, biased queries, values and output but unbiased keys,
/// no QK-norm, a sliding window; a `SwiGLU` whose down projection alone is
/// biased. A final RMS norm closes it. Because every part is causal, the
/// encoder streams: a caller that runs it chunk by chunk through a
/// [`KVCache`] gets the frames a whole-utterance pass gets.
///
/// `transformers`' names map onto the fields by
/// [`weights::transformers_rekey`](crate::kits::speech::asr::voxtral::weights::transformers_rekey):
/// its `embedder.conv1` and `conv2` are the blocks of [`stem`](Self::stem).
///
/// Built by [`VoxtralAudioEncoderConfig`] (high-level) or
/// [`VoxtralAudioEncoderStructureConfig`].
/// Implements [`VoxtralAudioEncoderMeta`].
#[derive(Module, Debug)]
pub struct VoxtralAudioEncoder {
    /// The causal convolution stem: `n_mels -> d_model -> d_model`.
    pub stem: ConvSeq1d,

    /// The layers, their final norm and their rotary embedding.
    pub stack: DecoderStack,
}

impl VoxtralAudioEncoderMeta for VoxtralAudioEncoder {
    fn n_mels(&self) -> usize {
        self.stem.blocks[0].conv.weight.dims()[1]
    }

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

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

    fn n_heads(&self) -> usize {
        use crate::blocks::transformers::attention::csa::CausalSelfAttentionMeta;
        self.stack.layers[0].attn.branch.attention().n_head()
    }

    fn head_dim(&self) -> usize {
        self.stack.head_dim()
    }

    fn sliding_window(&self) -> Option<usize> {
        self.stack.layers[0].attn.branch.attention().sliding_window
    }
}

impl crate::burner::module::InputDTypes for VoxtralAudioEncoder {
    /// Its stem's dtype: the dtype its parameters were loaded in.
    fn preferred_dtype(&self) -> burn::tensor::FloatDType {
        crate::burner::module::module_float_dtype(&self.stem)
            .unwrap_or(burn::tensor::FloatDType::F32)
    }
}

/// [`stem`](VoxtralAudioEncoder::stem) casts its features, which a front end
/// makes in f32.
impl crate::burner::module::CoercesInput for VoxtralAudioEncoder {}

impl crate::burner::module::ResultDType for VoxtralAudioEncoder {
    /// Its own: the encoder's features stay in the model's dtype.
    fn result_dtype(
        &self,
        _input: burn::tensor::FloatDType,
    ) -> burn::tensor::FloatDType {
        crate::burner::module::InputDTypes::preferred_dtype(self)
    }
}

impl VoxtralAudioEncoder {
    /// The rotary embedding for encoder frames `0..seq_len`.
    pub fn rotary(
        &self,
        seq_len: usize,
        device: &Device,
    ) -> RotarySet {
        self.stack.rotary(seq_len, device)
    }

    /// The convolution stem.
    ///
    /// # Arguments
    /// * `features` - `[batch, n_mels, frames]` log-mels, from the stream's
    ///   first frame.
    ///
    /// # Returns
    /// `[batch, ceil(frames/2), d_model]`.
    pub fn stem(
        &self,
        features: Tensor<3>,
    ) -> Tensor<3> {
        let [batch, frames] = crate::contracts::unpack_shape_contract!(
            ["batch", "n_mels", "frames"],
            &features.dims(),
            &["batch", "frames"],
            &[("n_mels", self.n_mels())]
        );
        let features = crate::burner::module::InputDTypes::coerce_input(self, features);
        let y = self.stem.forward(features).swap_dims(1, 2);
        #[cfg(any(debug_assertions, test))]
        crate::contracts::assert_shape_contract_periodically!(
            ["batch", "seq", "d_model"],
            &y.dims(),
            &[
                ("batch", batch),
                ("seq", self.output_len(frames)),
                ("d_model", self.d_model())
            ]
        );
        #[cfg(not(any(debug_assertions, test)))]
        let _ = (batch, frames);
        y
    }

    /// The layers and the final norm, over stem frames at positions
    /// `start..start + seq`, through the cache when there is one.
    ///
    /// # Arguments
    /// * `x` - `[batch, seq, d_model]` stem frames.
    /// * `r_emb` - a rotary embedding covering `start + seq` positions.
    /// * `kv_cache` - the cache, at position `start`; `None` means `start` is 0
    ///   and nothing is kept.
    ///
    /// # Returns
    /// `[batch, seq, d_model]`, normalized.
    pub fn forward_frames(
        &self,
        x: Tensor<3>,
        r_emb: &RotarySet,
        kv_cache: Option<&mut KVCache>,
    ) -> Tensor<3> {
        self.stack.forward_hidden(x, r_emb, kv_cache)
    }

    /// Encodes a whole utterance: the stem, then the layers.
    ///
    /// # Arguments
    /// * `features` - `[batch, n_mels, frames]` log-mels.
    ///
    /// # Returns
    /// `[batch, ceil(frames/2), d_model]`.
    pub fn forward(
        &self,
        features: Tensor<3>,
    ) -> Tensor<3> {
        let x = self.stem(features);
        let r_emb = self.rotary(x.dims()[1], &x.device());
        self.forward_frames(x, &r_emb, None)
    }
}

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

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

    use super::*;
    use crate::support::testing::{
        assert_tensors_close,
        cpu_device,
        seeded_tensor,
    };

    fn toy() -> VoxtralAudioEncoderConfig {
        VoxtralAudioEncoderConfig::new(6, 16, 2, 6, 24, 2)
            .with_rms_eps(1e-6)
            .with_rope_theta(10_000)
            .with_sliding_window(Some(4))
    }

    /// A config non-default in every field, and the encoder built from it,
    /// answer the meta alike.
    #[test]
    fn test_meta() {
        let config = toy();
        let encoder: VoxtralAudioEncoder = config.init(&cpu_device());
        assert_eq!(encoder.n_mels(), config.n_mels());
        assert_eq!(encoder.d_model(), config.d_model());
        assert_eq!(encoder.n_layers(), config.n_layers());
        assert_eq!(encoder.n_heads(), config.n_heads());
        assert_eq!(encoder.head_dim(), config.head_dim());
        assert_eq!(encoder.sliding_window(), config.sliding_window());
        assert_eq!(encoder.stack.rotary.base, config.rope_theta);
        assert_eq!(encoder.stack.norm.epsilon(), Some(1e-6));
        assert_eq!(config.output_len(7), 4);
        assert_eq!(encoder.kv_cache_config().num_layers, 2);

        let preset = VoxtralAudioEncoderConfig::voxtral_mini_4b_realtime();
        assert_eq!(preset.sliding_window(), Some(750));
        assert_eq!(preset.rope_theta, 1_000_000);
    }

    /// The stem halves the frame rate and is causal: a frame's output does
    /// not change when later input does.
    #[test]
    fn test_stem_is_causal() {
        let device = cpu_device();
        let encoder: VoxtralAudioEncoder = toy().init(&device);
        let a = seeded_tensor::<3>(1, [1, 6, 12], Distribution::Default, &device);
        let b = Tensor::cat(
            vec![
                a.clone().slice_dim(2, 0..8),
                seeded_tensor::<3>(2, [1, 6, 4], Distribution::Default, &device),
            ],
            2,
        );
        let ya = encoder.stem(a);
        let yb = encoder.stem(b);
        assert_eq!(ya.dims(), [1, 6, 16]);
        assert_tensors_close(
            &ya.slice_dim(1, 0..4),
            &yb.slice_dim(1, 0..4),
            Tolerance::default(),
        );
    }

    /// Stem frames run through the cache in chunks give the whole pass's
    /// output: the encoder streams.
    #[test]
    fn test_chunked_through_the_cache() {
        let device = cpu_device();
        let encoder: VoxtralAudioEncoder = toy().init(&device);
        let features = seeded_tensor::<3>(3, [1, 6, 20], Distribution::Default, &device);
        let whole = encoder.forward(features.clone());

        let x = encoder.stem(features);
        let r_emb = encoder.rotary(10, &device);
        let mut cache = encoder.kv_cache_config().with_seq_len(10).init();
        let parts: Vec<Tensor<3>> = [0..3, 3..4, 4..10]
            .into_iter()
            .map(|r| encoder.forward_frames(x.clone().slice_dim(1, r), &r_emb, Some(&mut cache)))
            .collect();
        assert_tensors_close(&Tensor::cat(parts, 1), &whole, Tolerance::default());
    }
}