bunsen 0.33.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
use burn::{
    Tensor,
    config::Config,
    module::{
        Module,
        Param,
    },
    nn::{
        Embedding,
        EmbeddingConfig,
        LayerNorm,
        LayerNormConfig,
    },
    prelude::{
        Backend,
        s,
    },
    tensor::{
        Bool,
        DType,
        Distribution,
        Int,
        TensorData,
    },
};

use super::WHISPER_DEFAULT_D_MODEL;
use crate::{
    burner::{
        module::{
            HasDType,
            ModuleInit,
        },
        store::FixPytorchLoadMappers,
        tensor::backend_float_dtype,
    },
    errors::BunsenResult,
    kits::speech::whisper::blocks::{
        ResidualDecoderAttentionBlock,
        ResidualDecoderAttentionBlockConfig,
        ResidualDecoderAttentionBlockMeta,
    },
    ops::{
        embedding::unembed,
        transformers::attention::{
            AttnKvPair,
            causal_mask,
        },
    },
};

/// Common meta for [`TextDecoder`] and [`TextDecoderConfig`].
pub trait TextDecoderMeta {
    /// Returns the size of the vocabulary.
    fn vocab_size(&self) -> usize;

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

    /// Returns the max context size.
    fn max_context(&self) -> usize;

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

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

/// Config for [`TextDecoder`].
#[derive(Config, Debug)]
pub struct TextDecoderConfig {
    /// The size of the vocabulary.
    pub vocab_size: usize,

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

    /// Maximum text context size.
    pub max_context: usize,

    /// The number of layers.
    pub n_layers: usize,

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

    /// Dropout.
    #[config(default = "0.0")]
    pub block_dropout: f64,
}

impl TextDecoderMeta for TextDecoderConfig {
    fn vocab_size(&self) -> usize {
        self.vocab_size
    }

    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<B: Backend> ModuleInit<B, TextDecoder<B>> for TextDecoderConfig {
    fn try_init(
        &self,
        device: &B::Device,
    ) -> BunsenResult<TextDecoder<B>> {
        Ok(TextDecoder {
            token_embedding: EmbeddingConfig::new(self.vocab_size, self.d_model).init(device),

            positional_embedding: Param::from_tensor(Tensor::<B, 2>::random(
                [self.max_context, self.d_model],
                Distribution::Normal(0.0, 1.0),
                device,
            )),

            blocks: (0..self.n_layers)
                .map(|_| {
                    ResidualDecoderAttentionBlockConfig::new(self.d_model)
                        .with_d_head(self.d_head)
                        .with_dropout(self.block_dropout)
                        .try_init(device)
                })
                .collect::<BunsenResult<Vec<ResidualDecoderAttentionBlock<B>>>>()?,

            ln: LayerNormConfig::new(self.d_model).init(device),
            // mask: Param::from_tensor(attn_decoder_mask(self.max_text_context, device)),
        })
    }
}

/// Text decoder module for Whisper speech recognition model.
///
/// Autoregressive token decoder: token plus positional embeddings, a stack of
/// [`ResidualDecoderAttentionBlock`] layers (causally-masked self-attention and
/// cross-attention over the audio encoder output), a final layer norm, and an
/// unembedding into vocabulary logits.
///
/// Built by [`TextDecoderConfig`].
#[derive(Module, Debug)]
pub struct TextDecoder<B: Backend> {
    /// The token embedding.
    pub token_embedding: Embedding<B>,

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

    /// The decoder blocks.
    pub blocks: Vec<ResidualDecoderAttentionBlock<B>>,

    /// The output layer norm.
    pub ln: LayerNorm<B>,
    // mask: Param<Tensor<B, 2>>,
}

impl<B: Backend> FixPytorchLoadMappers for TextDecoder<B> {
    /// Only the attention blocks are affected: the token and positional
    /// embeddings and the final layer norm are stored contiguously.
    fn fix_pytorch_load_mappers(mut self) -> Self {
        self.blocks = self.blocks.fix_pytorch_load_mappers();
        self
    }
}

impl<B: Backend> TextDecoderMeta for TextDecoder<B> {
    fn vocab_size(&self) -> usize {
        self.token_embedding.weight.val().dims()[0]
    }

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

    fn max_context(&self) -> usize {
        self.positional_embedding.val().dims()[0]
    }

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

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

impl<B: Backend> HasDType for TextDecoder<B> {
    fn dtype(&self) -> DType {
        self.token_embedding.weight.dtype()
    }
}

impl<B: Backend> TextDecoder<B> {
    /// Runs the decoder.
    ///
    /// # Arguments
    /// * `x`: `[batch, seq]` token ids.
    /// * `xa`: `[batch, seq, d_model]` encoder features, in any float dtype;
    ///   cast to [`dtype`](Self::dtype) here.
    ///
    /// # Returns
    /// `[batch, seq, n_vocab]` logits, in the backend's default float
    /// ([`backend_float_dtype`]) whatever the decoder's own precision. This
    /// is the model's outward edge: everything past it — the log-softmax,
    /// the samplers, the [`LogitFilter`]s, the host reads — works in the
    /// backend's float, and upstream likewise takes its logits to `float()`
    /// before the search sees them.
    ///
    /// [`LogitFilter`]: crate::kits::speech::whisper::logit_filters::LogitFilter
    pub fn forward(
        &self,
        x: Tensor<B, 2, Int>,
        xa: Tensor<B, 3>,
    ) -> Tensor<B, 3> {
        let xa = xa.cast(self.dtype());

        let [_batch, seq_len] = x.dims();
        assert!(
            seq_len <= self.max_context(),
            "Token sequence length {} must not exceed {}.",
            seq_len,
            self.max_context()
        );

        let x = self.embed(x);

        //let mask = attn_decoder_mask(seq_len);

        let mask: Option<Tensor<B, 3, Bool>> = causal_mask(seq_len, 0, &x.device()).into();

        let mut x = x;
        for b in self.blocks.iter() {
            x = b.forward(x, xa.clone(), mask.clone()).output;
        }

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

        // denorm [batch, seq_len, n_vocab]
        // Needs softmax / beamsearch.
        unembed(&self.token_embedding, x).cast(backend_float_dtype::<B>())
    }

    /// Opens an incremental decode cache against a fixed encoder output.
    ///
    /// Projects the cross-attention keys and values for every block up front;
    /// they are reused unchanged for the whole decode.
    ///
    /// # Arguments
    /// * `xa`: `[batch, cross_len, d_model]` encoder output, in any float
    ///   dtype; the cache is built in [`dtype`](Self::dtype).
    pub fn new_cache(
        &self,
        xa: Tensor<B, 3>,
    ) -> TextDecoderCache<B> {
        self.new_cache_grouped(xa, 1)
    }

    /// [`new_cache`](Self::new_cache) shared by `group` decode rows per
    /// audio: the cross-attention projections are built once per row of
    /// `xa`, and a forward over `xa.batch * group` token rows, laid out
    /// `row = audio * group + member`, attends each member to its audio's
    /// projection. The self-attention cache is at the full row count, and
    /// [`TextDecoderCache::reorder`] permutes it as ever.
    ///
    /// This is what a beam search wants: its beams share their audio's
    /// cross-attention, which is the bulk of the cache, and the copy per
    /// beam that repeating `xa` would cost is never made.
    pub fn new_cache_grouped(
        &self,
        xa: Tensor<B, 3>,
        group: usize,
    ) -> TextDecoderCache<B> {
        assert!(group >= 1, "at least one row per audio");

        // The cross-attention cache is the bulk of the decode's state and is
        // scored against this decoder's weights on every step, so it is
        // built in the decoder's precision whatever the caller handed in.
        let xa = xa.cast(self.dtype());

        TextDecoderCache {
            self_kv: self.blocks.iter().map(|_| None).collect(),
            cross_kv: self
                .blocks
                .iter()
                .map(|block| block.build_cross_kv(xa.clone()))
                .collect(),
            group,
            pos: 0,
        }
    }

    /// Forward pass over the next token(s), against a key/value cache.
    ///
    /// Pass only the **new** tokens: the cache holds everything before them.
    /// Decoding a sequence a token at a time through this gives the same
    /// logits as one [`forward`](Self::forward) over the whole sequence, at a
    /// fraction of the work — the encoder-derived cross-attention keys and
    /// values are projected once by [`new_cache`](Self::new_cache), and
    /// self-attention scores only the new queries.
    ///
    /// The positional embedding is taken from
    /// [`cache.pos()`](TextDecoderCache::pos) rather than from zero, and the
    /// causal mask spans `[seq_new, pos + seq_new]`. A single new token needs
    /// no mask at all, since it may attend to all of its history.
    ///
    /// # Arguments
    /// * `x`: `[batch, seq_new]` the next token(s).
    /// * `cache`: from [`new_cache`](Self::new_cache). Carries the encoder
    ///   output, so it is not passed again.
    ///
    /// # Returns
    /// `[batch, seq_new, n_vocab]` — logits for the new token(s) only, in
    /// the backend's default float, as [`forward`](Self::forward).
    pub fn forward_cached(
        &self,
        x: Tensor<B, 2, Int>,
        cache: &mut TextDecoderCache<B>,
    ) -> Tensor<B, 3> {
        assert_eq!(
            cache.n_layers(),
            self.blocks.len(),
            "cache was built for a different decoder",
        );

        let seq_new = x.dims()[1];
        let past = cache.pos;
        assert!(
            past + seq_new <= self.max_context(),
            "Token sequence length {} must not exceed {}.",
            past + seq_new,
            self.max_context(),
        );

        let mut h = self.embed_at(x, past);

        // One query attends to everything cached, so a mask would be all-false
        // and is skipped.
        let mask: Option<Tensor<B, 3, Bool>> = if seq_new > 1 {
            Some(causal_mask(seq_new, past, &h.device()))
        } else {
            None
        };

        for (i, block) in self.blocks.iter().enumerate() {
            h = block.forward_w_kv_cache_grouped(
                h,
                mask.clone(),
                &mut cache.self_kv[i],
                &cache.cross_kv[i],
                cache.group,
            );
        }

        cache.pos += seq_new;

        unembed(&self.token_embedding, self.ln.forward(h)).cast(backend_float_dtype::<B>())
    }

    fn embed(
        &self,
        x: Tensor<B, 2, Int>,
    ) -> Tensor<B, 3> {
        self.embed_at(x, 0)
    }

    /// Embeds `x`, taking positions from `offset` rather than from zero.
    fn embed_at(
        &self,
        x: Tensor<B, 2, Int>,
        offset: usize,
    ) -> Tensor<B, 3> {
        let seq_len = x.dims()[1];
        self.token_embedding.forward(x)
            + self
                .positional_embedding
                .val()
                .slice(s![offset..offset + seq_len])
                .unsqueeze::<3>()
    }
}

/// Per-layer key/value caches for incremental decoding.
///
/// Built by [`TextDecoder::new_cache`] against a fixed encoder output. Holds,
/// per block, the growing self-attention cache and the fixed cross-attention
/// one, plus how many tokens have been consumed — which is what offsets the
/// positional embedding.
///
/// Deliberately **not** a `Module`: this is per-stream decode state and holds
/// no parameters.
pub struct TextDecoderCache<B: Backend> {
    /// Self-attention keys and values, grown one step at a time.
    self_kv: Vec<Option<AttnKvPair<B>>>,

    /// Cross-attention keys and values, projected once from the encoder
    /// output. This is the bulk of what the cache saves: over 1500 encoder
    /// frames, per layer, per token.
    cross_kv: Vec<AttnKvPair<B>>,

    /// Decode rows per cross-attention row; one unless the cache is shared
    /// by a group, as by a beam search's beams.
    group: usize,

    /// Tokens consumed so far.
    pos: usize,
}

impl<B: Backend> HasDType for TextDecoderCache<B> {
    fn dtype(&self) -> DType {
        self.cross_kv[0].dtype()
    }
}

impl<B: Backend> TextDecoderCache<B> {
    /// The number of tokens consumed so far.
    pub fn pos(&self) -> usize {
        self.pos
    }

    /// Decode rows per cross-attention row.
    pub fn group(&self) -> usize {
        self.group
    }

    /// The number of blocks this cache covers.
    pub fn n_layers(&self) -> usize {
        self.cross_kv.len()
    }

    /// Drops the decoded history, keeping the cross-attention projections.
    ///
    /// Use this to decode a second sequence against the same audio without
    /// re-projecting the encoder output.
    pub fn reset(&mut self) {
        for kv in &mut self.self_kv {
            *kv = None;
        }
        self.pos = 0;
    }

    /// Permutes the rows of the self-attention cache: row `r` becomes what
    /// row `sources[r]` was. A source may appear more than once, which
    /// duplicates that row; that is how a beam search branches.
    ///
    /// The cross-attention cache is left alone. Its rows are identical across
    /// the beams of one audio, so permuting them within a group would be a
    /// no-op that copies the bulk of the cache for nothing; a permutation
    /// that crossed audio groups would be a caller error.
    ///
    /// # Panics
    /// If `sources` is not one entry per cached row.
    pub fn reorder(
        &mut self,
        sources: &[usize],
    ) {
        let Some(first) = self.self_kv.iter().flatten().next() else {
            return;
        };
        assert_eq!(
            sources.len(),
            first.batch_size(),
            "one source row per cached row",
        );
        if sources.iter().enumerate().all(|(r, &s)| r == s) {
            return;
        }

        let device = first.key.device();
        let indices: Tensor<B, 1, Int> = Tensor::from_data(
            TensorData::new(
                sources.iter().map(|&s| s as i64).collect::<Vec<_>>(),
                [sources.len()],
            ),
            &device,
        );

        for kv in self.self_kv.iter_mut().flatten() {
            kv.key = kv.key.clone().select(0, indices.clone());
            kv.value = kv.value.clone().select(0, indices.clone());
        }
    }
}

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

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

    #[test]
    #[serial]
    fn test_text_decoder_forward() {
        type B = PerformanceBackend;
        let device = default_device();
        let _memory = DeviceMemoryGuard::<B>::new(&device);

        let d_model = 128;
        let vocab_size = 64;
        let max_context = 128;
        let n_layers = 2;

        let config = TextDecoderConfig::new(vocab_size, d_model, max_context, n_layers);

        assert_eq!(config.vocab_size(), vocab_size);
        assert_eq!(config.d_model(), d_model);
        assert_eq!(config.max_context(), max_context);

        let decoder: TextDecoder<B> = config.init(&device);

        assert_eq!(decoder.vocab_size(), vocab_size);
        assert_eq!(decoder.d_model(), d_model);
        assert_eq!(decoder.max_context(), max_context);

        let batch = 2;
        let seq_len = max_context / 2;

        let x: Tensor<B, 2, Int> = Tensor::zeros([batch, seq_len], &device);
        let xa: Tensor<B, 3> =
            Tensor::random([batch, seq_len, d_model], Default::default(), &device);

        let output = decoder.forward(x.clone(), xa.clone());

        assert_shape_contract!(
            ["batch", "seq", "n_vocab"],
            &output,
            &[("batch", batch), ("seq", seq_len), ("n_vocab", vocab_size),],
        );
    }
    /// **The cache contract.** Decoding a token at a time must give the same
    /// logits as one uncached pass over the whole sequence.
    ///
    /// This is what the cache exists to preserve, and what a wrong positional
    /// offset, a mis-shaped causal mask, or a stale key/value append would
    /// break — none of which a shape check would catch.
    #[test]
    #[serial]
    fn test_forward_cached_matches_forward() {
        use burn::{
            prelude::TensorData,
            tensor::{
                Distribution,
                Tolerance,
                backend::BackendTypes,
            },
        };

        use crate::burner::tensor::TensorElemOpExt;

        type B = PerformanceBackend;
        type F = <B as BackendTypes>::FloatElem;

        let device = default_device();
        let _memory = DeviceMemoryGuard::<B>::new(&device);

        // `n_heads` is `d_model / d_head` with `d_head` defaulting to 64, so
        // a smaller `d_model` would give the attention zero heads.
        let (vocab, d_model, max_ctx, layers) = (64, 128, 16, 2);
        let (batch, cross_len, seq) = (2, 5, 6);

        let decoder: TextDecoder<B> =
            TextDecoderConfig::new(vocab, d_model, max_ctx, layers).init(&device);

        let tokens: Tensor<B, 2, Int> = Tensor::from_data(
            TensorData::new(
                (0..batch * seq)
                    .map(|k| (k % vocab) as i64)
                    .collect::<Vec<_>>(),
                [batch, seq],
            ),
            &device,
        );
        let xa: Tensor<B, 3> =
            Tensor::random([batch, cross_len, d_model], Distribution::Default, &device);

        let whole = decoder.forward(tokens.clone(), xa.clone());

        // One new token per step, as an autoregressive loop would.
        let mut cache = decoder.new_cache(xa);
        let mut steps = Vec::with_capacity(seq);
        for t in 0..seq {
            let step = tokens.clone().slice_dim(1, t as isize..(t + 1) as isize);
            steps.push(decoder.forward_cached(step, &mut cache));
        }
        assert_eq!(cache.pos(), seq);

        let stepped: Tensor<B, 3> = Tensor::cat(steps, 1);
        assert_eq!(stepped.dims(), whole.dims());

        stepped
            .to_data_as::<F>()
            .assert_approx_eq::<F>(&whole.to_data_as::<F>(), Tolerance::permissive());
    }

    /// Prefilling a prompt then stepping must match stepping throughout —
    /// the shape a real decode has.
    #[test]
    #[serial]
    fn test_cached_prefill_then_step() {
        use burn::{
            prelude::TensorData,
            tensor::{
                Distribution,
                Tolerance,
                backend::BackendTypes,
            },
        };

        use crate::burner::tensor::TensorElemOpExt;

        type B = PerformanceBackend;
        type F = <B as BackendTypes>::FloatElem;

        let device = default_device();
        let _memory = DeviceMemoryGuard::<B>::new(&device);
        let (vocab, d_model, max_ctx, layers) = (64, 128, 16, 1);
        let (cross_len, seq, prompt) = (4, 5, 3);

        let decoder: TextDecoder<B> =
            TextDecoderConfig::new(vocab, d_model, max_ctx, layers).init(&device);

        let tokens: Tensor<B, 2, Int> = Tensor::from_data(
            TensorData::new((0..seq).map(|k| k as i64).collect::<Vec<_>>(), [1, seq]),
            &device,
        );
        let xa: Tensor<B, 3> =
            Tensor::random([1, cross_len, d_model], Distribution::Default, &device);

        let whole = decoder.forward(tokens.clone(), xa.clone());

        let mut cache = decoder.new_cache(xa);
        let mut parts = vec![
            decoder.forward_cached(tokens.clone().slice_dim(1, 0..prompt as isize), &mut cache),
        ];
        for t in prompt..seq {
            let step = tokens.clone().slice_dim(1, t as isize..(t + 1) as isize);
            parts.push(decoder.forward_cached(step, &mut cache));
        }

        let mixed: Tensor<B, 3> = Tensor::cat(parts, 1);
        mixed
            .to_data_as::<F>()
            .assert_approx_eq::<F>(&whole.to_data_as::<F>(), Tolerance::permissive());
    }

    /// **Both caches are the decoder's precision**, whatever the encoder
    /// features were handed over in.
    ///
    /// The cross-attention cache is the bulk of a decode's state and the
    /// self-attention cache is scored against it every step; a cache at the
    /// caller's precision rather than the model's would be re-cast on every
    /// use at best, and silently wrong at worst.
    #[test]
    #[serial]
    fn test_caches_take_the_decoders_dtype() {
        use burn::{
            module::Module,
            prelude::Device,
            tensor::Distribution,
        };

        use crate::burner::{
            module::DTypeMapper,
            tensor::backend_float_dtype,
        };

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

        let float = backend_float_dtype::<B>();
        let decoder: TextDecoder<B> = TextDecoderConfig::new(32, 128, 8, 1).init(&device);
        let decoder = decoder.map(&mut DTypeMapper::new(DType::F16));
        assert_eq!(decoder.dtype(), DType::F16);

        // Features at the *caller's* precision, as a caller that widened
        // them, or built them by hand, would have.
        let xa: Tensor<B, 3> = Tensor::random([1, 4, 128], Distribution::Default, &device);
        assert_eq!(xa.dtype(), float);

        let mut cache = decoder.new_cache(xa);
        assert_eq!(cache.dtype(), DType::F16, "cross-attention cache");
        for kv in &cache.cross_kv {
            assert_eq!(kv.dtype(), DType::F16);
        }

        let tokens: Tensor<B, 2, Int> =
            Tensor::from_data(TensorData::new(vec![3i64, 5], [1, 2]), &device);
        let logits = decoder.forward_cached(tokens, &mut cache);

        assert_eq!(logits.dtype(), float, "logits are the interface's");
        assert!(cache.self_kv.iter().any(|kv| kv.is_some()));
        for kv in cache.self_kv.iter().flatten() {
            assert_eq!(kv.dtype(), DType::F16, "self-attention cache");
        }
    }

    /// `reset` rewinds the decode while keeping the encoder projections, so a
    /// second sequence over the same audio does not re-project them.
    #[test]
    #[serial]
    fn test_cache_reset_restarts_the_stream() {
        use burn::{
            prelude::TensorData,
            tensor::{
                Distribution,
                Tolerance,
                backend::BackendTypes,
            },
        };

        use crate::burner::tensor::TensorElemOpExt;

        type B = PerformanceBackend;
        type F = <B as BackendTypes>::FloatElem;

        let device = default_device();
        let _memory = DeviceMemoryGuard::<B>::new(&device);
        let (vocab, d_model, max_ctx, layers) = (32, 128, 8, 1);

        let decoder: TextDecoder<B> =
            TextDecoderConfig::new(vocab, d_model, max_ctx, layers).init(&device);

        let tokens: Tensor<B, 2, Int> =
            Tensor::from_data(TensorData::new(vec![3i64, 5], [1, 2]), &device);
        let xa: Tensor<B, 3> = Tensor::random([1, 4, d_model], Distribution::Default, &device);

        let mut cache = decoder.new_cache(xa);
        let first = decoder.forward_cached(tokens.clone(), &mut cache);
        assert_eq!(cache.pos(), 2);

        cache.reset();
        assert_eq!(cache.pos(), 0);

        let second = decoder.forward_cached(tokens, &mut cache);
        first
            .to_data_as::<F>()
            .assert_approx_eq::<F>(&second.to_data_as::<F>(), Tolerance::permissive());
    }
}