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
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
//! # Causal Self-Attention

use burn::{
    Tensor,
    config::Config,
    module::Module,
    nn::{
        Initializer,
        Linear,
        LinearConfig,
        norm::RmsNormConfig,
    },
    prelude::{
        Bool,
        Int,
        s,
    },
    tensor::{
        Device,
        FloatDType,
    },
};

use crate::{
    blocks::{
        norm::{
            BunsenNormalization,
            BunsenNormalizationConfig,
        },
        transformers::{
            embedding::RotaryEmbedding,
            sublayer::{
                ResidualSublayer,
                SublayerBranch,
            },
        },
    },
    contracts::{
        assert_shape_contract_periodically,
        unpack_shape_contract,
    },
    errors::{
        BunsenResult,
        WithOkOrPanic,
    },
    ops::transformers::attention::{
        KVCache,
        ScaledDotProductAttentionConfig,
        causal_window_visible,
        scaled_dot_product_attention,
        sdpa_attn_weight,
        two_sided_window_visible,
    },
};

/// Common meta for [`CausalSelfAttention`] and [`CausalSelfAttentionConfig`].
pub trait CausalSelfAttentionMeta {
    /// Returns the size of the input and output.
    fn n_embed(&self) -> usize;

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

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

    /// Returns the size of each head.
    fn head_dim(&self) -> usize {
        self.n_embed() / self.n_head()
    }

    /// Group Query Attention.
    fn gqa_enabled(&self) -> bool {
        self.n_head() != self.n_kv_head()
    }
}

/// Which keys a [`CausalSelfAttention`]'s query sees.
#[derive(Config, Copy, Debug, PartialEq, Eq)]
pub enum AttentionMask {
    /// The keys at and before its own position: a decoder's attention.
    Causal,

    /// Every key, the ones after its position too: an encoder's attention,
    /// over a whole input at once (it takes no KV cache). Under a sliding
    /// window, the window is two-sided.
    Bidirectional,
}

/// What a [`CausalSelfAttention`]'s
/// [`forward_with`](CausalSelfAttention::forward_with) takes beside its
/// input; each only an attention configured for it takes.
#[derive(Debug, Default)]
pub struct AttentionSides {
    /// The `[B, T, H_kv * head_dim]` value embedding of the input's tokens,
    /// for an attention with a value residual.
    pub value_embed: Option<Tensor<3>>,

    /// `[B, T]`, true at the positions that are not padding: a padding key
    /// is attended to by no query (a padding query's output means nothing).
    pub key_valid: Option<Tensor<2, Bool>>,
}

/// Config for [`CausalSelfAttention`].
#[derive(Config, Debug)]
pub struct CausalSelfAttentionConfig {
    /// Number of Heads.
    pub n_head: usize,

    /// Number of KV Heads.
    pub n_kv_head: usize,

    /// Embedding Size.
    pub n_embed: usize,

    /// The query/key normalization (QK-norm), sized to `head_dim` whatever
    /// feature count it names; `None` normalizes nothing, and builds no norm.
    #[config(default = "Some(BunsenNormalizationConfig::Rms(RmsNormConfig::new(0)))")]
    pub norm: Option<BunsenNormalizationConfig>,

    /// The width of each head; `None` is `n_embed / n_head`.
    ///
    /// A model whose heads are wider or narrower than that (Qwen3's are 128
    /// over 16 heads of a 1024-wide model) names it here; the query and
    /// output projections then map `n_embed` to and from `n_head * head_dim`.
    #[config(default = "None")]
    pub head_dim: Option<usize>,

    /// Whether the query/key normalization applies before or after the
    /// rotary embedding.
    #[config(default = "QkNormPlacement::AfterRope")]
    pub qk_norm: QkNormPlacement,

    /// Whether the query, key and value projections carry a bias.
    #[config(default = "false")]
    pub qkv_bias: bool,

    /// Whether the key projection carries a bias; `None` follows `qkv_bias`.
    ///
    /// Whisper-family stacks bias their queries and values but not their
    /// keys (`Some(false)` under a `qkv_bias`).
    #[config(default = "None")]
    pub key_bias: Option<bool>,

    /// Whether the output projection carries a bias.
    #[config(default = "false")]
    pub output_bias: bool,

    /// The sliding attention window, in positions: a query attends to itself
    /// and to the `sliding_window - 1` positions before it, never further
    /// back; under a [`Bidirectional`](AttentionMask::Bidirectional) mask,
    /// also to the `sliding_window - 1` positions after it (`|i - j| <
    /// sliding_window`). `None` attends to every key the mask shows.
    ///
    /// A two-sided window of `±r` positions is `r + 1` here: `ModernBERT`'s
    /// `local_attention` of 128 (±64) is 65.
    #[config(default = "None")]
    pub sliding_window: Option<usize>,

    /// Which keys a query sees: the ones up to its own position (a
    /// decoder's), or all of them (an encoder's).
    #[config(default = "AttentionMask::Causal")]
    pub mask: AttentionMask,

    /// The dtype the attention's softmax runs in
    /// ([`ScaledDotProductAttentionConfig::softmax_dtype`]); `None` runs it
    /// in the queries' dtype.
    #[config(default = "None")]
    pub softmax_dtype: Option<FloatDType>,

    /// The scores' scale; `None`, `1 / sqrt(head_dim)`. Gemma's is
    /// `query_pre_attn_scalar^-0.5`, which need not be the head width's;
    /// nanochat's 2026 gain `g` on the queries and keys is `g² / sqrt(d)`.
    #[config(default = "None")]
    pub score_scale: Option<f64>,

    /// A soft-cap on the scaled scores before the mask, `c · tanh(s / c)`
    /// (Gemma 2's 50); `None`, none.
    #[config(default = "None")]
    pub attn_softcap: Option<f64>,

    /// A value residual: an embedding of the input tokens, gated per KV head
    /// from the attention input, added to the values
    /// ([`forward_with`](CausalSelfAttention::forward_with)).
    /// `None` adds nothing, and builds no gate.
    #[config(default = "None")]
    pub value_residual: Option<ValueResidualConfig>,

    /// A sigmoid gate on the attention's output, before the output
    /// projection (Qwen3.5's `attn_output_gate`): the query projection is
    /// `[D, 2 H d]`, each head's `d` queries followed by its `d` gates, and
    /// the output is `c_proj(y · σ(gate))`. `false` gates nothing.
    #[config(default = "false")]
    pub output_gate: bool,
}

/// Config of a [`CausalSelfAttention`]'s value residual, `ResFormer`'s in
/// nanochat's 2026 form:
///
/// ```text
/// v += gate_scale * sigmoid(gate(x[.., :gate_channels])) * ve
/// ```
///
/// The gate is one scalar per KV head, read from the attention input's first
/// `gate_channels` channels; `ve` is a `[B, T, n_kv_head * head_dim]` value
/// embedding the caller supplies.
#[derive(Config, Debug)]
pub struct ValueResidualConfig {
    /// How many of the attention input's leading channels the gate reads.
    #[config(default = "12")]
    pub gate_channels: usize,

    /// The gate's range: `(0, gate_scale)`.
    #[config(default = "3.0")]
    pub gate_scale: f64,
}

/// Where [`CausalSelfAttention`] normalizes its queries and keys, relative to
/// the rotary embedding.
#[derive(Config, Debug, Copy, PartialEq, Eq)]
pub enum QkNormPlacement {
    /// Rotate, then normalize: `nanochat`'s order.
    AfterRope,

    /// Normalize, then rotate: Qwen3's order.
    BeforeRope,
}

impl QkNormPlacement {
    /// Normalizes and rotates `x`, a `[B, T, H, D]` query or key, in this
    /// order; with no norm, only rotates it.
    pub fn apply(
        self,
        x: Tensor<4>,
        norm: Option<&BunsenNormalization>,
        r_emb: &RotaryEmbedding,
    ) -> Tensor<4> {
        let Some(norm) = norm else {
            return r_emb.apply(x);
        };
        match self {
            Self::AfterRope => norm.forward(r_emb.apply(x)),
            Self::BeforeRope => r_emb.apply(norm.forward(x)),
        }
    }
}

impl CausalSelfAttentionMeta for CausalSelfAttentionConfig {
    fn n_embed(&self) -> usize {
        self.n_embed
    }

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

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

    fn head_dim(&self) -> usize {
        self.head_dim.unwrap_or(self.n_embed / self.n_head.max(1))
    }
}

impl CausalSelfAttentionConfig {
    /// Whether the key projection carries a bias: `key_bias`, else
    /// `qkv_bias`.
    pub fn key_bias(&self) -> bool {
        self.key_bias.unwrap_or(self.qkv_bias)
    }

    /// Validate the config.
    pub fn validate(&self) {
        assert!(
            self.n_head > 0,
            "n_head must be > 0; got n_head={}",
            self.n_head
        );
        assert!(
            self.head_dim.is_some() || self.n_embed.is_multiple_of(self.n_head),
            "n_embed ({}) must be multiple of n_head ({})",
            self.n_embed,
            self.n_head
        );
        assert!(
            self.head_dim.is_some() || self.n_embed.is_multiple_of(self.n_kv_head),
            "n_embed ({}) must be multiple of n_kv_head ({})",
            self.n_embed,
            self.n_kv_head
        );
        assert!(
            self.head_dim() > 0,
            "head_dim must be > 0; got n_embed={}/n_head={}",
            self.n_embed,
            self.n_head
        );
        assert!(
            self.n_kv_head <= self.n_head,
            "n_kv_head must be <= n_head; got n_kv_head={}, n_head={}",
            self.n_kv_head,
            self.n_head
        );
        assert!(
            self.n_head.is_multiple_of(self.n_kv_head),
            "n_head must be divisible by n_kv_head; got n_head={}, n_kv_head={}",
            self.n_head,
            self.n_kv_head
        );
        assert!(
            self.sliding_window != Some(0),
            "sliding_window must be > 0 when set"
        );
        if let Some(vr) = &self.value_residual {
            assert!(
                vr.gate_channels > 0 && vr.gate_channels <= self.n_embed,
                "value_residual.gate_channels must be in 1..=n_embed ({}); got {}",
                self.n_embed,
                vr.gate_channels
            );
        }
    }
}

impl CausalSelfAttentionConfig {
    /// Initializes the module.
    pub fn try_init(
        &self,
        layer_index: usize,
        device: &Device,
    ) -> BunsenResult<CausalSelfAttention> {
        self.validate();
        let head_dim = self.head_dim();
        let norm = || {
            self.norm
                .clone()
                .map(|n| n.with_num_features(head_dim).init(device))
        };
        let linear =
            |d_in, d_out, bias| LinearConfig::new(d_in, d_out).with_bias(bias).init(device);

        Ok(CausalSelfAttention {
            layer_index,
            head_dim,
            qk_norm: self.qk_norm,
            sliding_window: self.sliding_window,
            mask: self.mask,
            softmax_dtype: self.softmax_dtype,
            output_gate: self.output_gate,
            c_q: linear(
                self.n_embed,
                self.n_head * head_dim * if self.output_gate { 2 } else { 1 },
                self.qkv_bias,
            ),
            q_norm: norm(),
            c_k: linear(self.n_embed, self.n_kv_head * head_dim, self.key_bias()),
            k_norm: norm(),
            c_v: linear(self.n_embed, self.n_kv_head * head_dim, self.qkv_bias),
            c_proj: linear(self.n_head * head_dim, self.n_embed, self.output_bias),
            score_scale: self.score_scale,
            attn_softcap: self.attn_softcap,
            value_gate: self.value_residual.as_ref().map(|vr| {
                // As upstream's init: a small positive gate, near half open.
                LinearConfig::new(vr.gate_channels, self.n_kv_head)
                    .with_bias(false)
                    .with_initializer(Initializer::Uniform {
                        min: 0.0,
                        max: 0.02,
                    })
                    .init(device)
            }),
            value_gate_scale: self.value_residual.as_ref().map(|vr| vr.gate_scale),
        })
    }

    /// Initializes the module, or panic.
    pub fn init(
        &self,
        layer_index: usize,
        device: &Device,
    ) -> CausalSelfAttention {
        self.try_init(layer_index, device).ok_or_panic()
    }
}

/// Causal Self-Attention Module
///
/// Multi-head causal self-attention with rotary positional embeddings,
/// optional Group Query Attention (fewer KV heads than query heads), optional
/// per-head query/key normalization, optional projection biases, an
/// optional sliding window, an optional score scale and soft-cap, an
/// optional gated value residual, and an optional output gate. Construct via
/// [`CausalSelfAttentionConfig`] and `.init(layer_index, device)`, then call
/// [`forward`](CausalSelfAttention::forward) with an input sequence, a
/// [`RotaryEmbedding`], and an optional [`KVCache`].
///
/// Built by [`CausalSelfAttentionConfig`].
#[derive(Module, Debug)]
pub struct CausalSelfAttention {
    /// Layer Index.
    pub layer_index: usize,

    /// Head Dimension.
    pub head_dim: usize,

    /// Where the query/key normalization applies.
    #[module(skip)]
    pub qk_norm: QkNormPlacement,

    /// The sliding attention window, in positions, if any: one-sided under a
    /// causal mask, two-sided under a bidirectional one
    /// ([`CausalSelfAttentionConfig::sliding_window`]).
    #[module(skip)]
    pub sliding_window: Option<usize>,

    /// Which keys a query sees.
    #[module(skip)]
    pub mask: AttentionMask,

    /// The dtype the softmax runs in; `None`, the queries'.
    #[module(skip)]
    pub softmax_dtype: Option<FloatDType>,

    /// Whether `c_q` also projects a sigmoid gate on the output
    /// ([`CausalSelfAttentionConfig::output_gate`]).
    #[module(skip)]
    pub output_gate: bool,

    /// Query Linear: `[D, H d]`, or `[D, 2 H d]` under an output gate (each
    /// head's queries, then its gates).
    pub c_q: Linear,

    /// Query Normalization; `None` without QK-norm.
    pub q_norm: Option<BunsenNormalization>,

    /// Key Linear.
    pub c_k: Linear,

    /// Key Normalization; `None` without QK-norm.
    pub k_norm: Option<BunsenNormalization>,

    /// Value Linear.
    pub c_v: Linear,

    /// Output Projection Linear.
    pub c_proj: Linear,

    /// The scores' scale; `None`, `1 / sqrt(head_dim)`.
    #[module(skip)]
    pub score_scale: Option<f64>,

    /// The soft-cap on the scaled scores, if any.
    #[module(skip)]
    pub attn_softcap: Option<f64>,

    /// The value residual's gate: the attention input's first channels to
    /// one scalar per KV head. `None` without a value residual.
    pub value_gate: Option<Linear>,

    /// The value residual's gate range, `(0, value_gate_scale)`.
    #[module(skip)]
    pub value_gate_scale: Option<f64>,
}

impl CausalSelfAttentionMeta for CausalSelfAttention {
    fn n_embed(&self) -> usize {
        self.c_q.weight.dims()[0]
    }

    fn n_head(&self) -> usize {
        self.c_proj.weight.dims()[0] / self.head_dim()
    }

    fn n_kv_head(&self) -> usize {
        self.c_k.weight.dims()[1] / self.head_dim()
    }

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

impl crate::burner::module::InputDTypes for CausalSelfAttention {
    /// Its projections' dtype.
    fn preferred_dtype(&self) -> FloatDType {
        FloatDType::from(self.c_q.weight.val().dtype())
    }
}

impl crate::burner::module::ResultDType for CausalSelfAttention {
    /// Its own: the output projection's.
    fn result_dtype(
        &self,
        _input: FloatDType,
    ) -> FloatDType {
        crate::burner::module::InputDTypes::preferred_dtype(self)
    }
}

impl CausalSelfAttention {
    /// The queries and keys of `input`: projected, normalized and rotated;
    /// and the output gate's logits, under an output gate.
    ///
    /// # Arguments
    /// - `input`: a `[B, T, D]` sequence.
    /// - `r_emb`: a rotary embedding with len ``T``.
    ///
    /// # Returns
    /// - `[B, H_q, T, head_dim]` queries, `[B, H_kv, T, head_dim]` keys, and
    ///   `[B, T, H_q * head_dim]` gate logits (`None` without the gate).
    fn queries_keys(
        &self,
        input: Tensor<3>,
        r_emb: &RotaryEmbedding,
    ) -> (Tensor<4>, Tensor<4>, Option<Tensor<3>>) {
        let [b, t] = unpack_shape_contract!(["B", "T", "D"], &input.dims(), &["B", "T"]);
        let (h, d) = (self.n_head(), self.head_dim());
        let q = self.c_q.forward(input.clone());
        let (q, gate) = if self.output_gate {
            let q = q.reshape([b, t, h, 2 * d]);
            let gate = q.clone().slice(s![.., .., .., d..]).reshape([b, t, h * d]);
            (q.slice(s![.., .., .., ..d]), Some(gate))
        } else {
            (q.reshape([b, t, h, d]), None)
        };
        let q = self
            .qk_norm
            .apply(q, self.q_norm.as_ref(), r_emb)
            .swap_dims(1, 2);
        let k = self
            .c_k
            .forward(input)
            .reshape([b, t, self.n_kv_head(), self.head_dim()]);
        let k = self
            .qk_norm
            .apply(k, self.k_norm.as_ref(), r_emb)
            .swap_dims(1, 2);
        (q, k, gate)
    }

    /// The attention's own sdpa options: the head grouping, the softmax's
    /// dtype, the scores' scale and soft-cap.
    fn sdpa_config(&self) -> ScaledDotProductAttentionConfig {
        ScaledDotProductAttentionConfig::new()
            .with_enable_gqa(self.gqa_enabled())
            .with_softmax_dtype(self.softmax_dtype)
            .with_scale(self.score_scale)
            .with_softcap(self.attn_softcap)
    }

    /// The values of `input`, `[B, H_kv, T, head_dim]`, with the value
    /// residual added when there is one.
    ///
    /// # Panics
    /// If `value_embed` is given to an attention without a value residual,
    /// or withheld from one with a value residual.
    fn values(
        &self,
        input: Tensor<3>,
        value_embed: Option<Tensor<3>>,
    ) -> Tensor<4> {
        let [b, t] = unpack_shape_contract!(["B", "T", "D"], &input.dims(), &["B", "T"]);
        let shape = [b, t, self.n_kv_head(), self.head_dim()];
        let v = self.c_v.forward(input.clone()).reshape(shape);
        let v = match (&self.value_gate, value_embed) {
            (None, None) => v,
            (Some(gate), Some(ve)) => {
                assert_shape_contract_periodically!(
                    ["B", "T", "V"],
                    &ve.dims(),
                    &[
                        ("B", b),
                        ("T", t),
                        ("V", self.n_kv_head() * self.head_dim())
                    ]
                );
                let channels = gate.weight.dims()[0];
                let scale = self.value_gate_scale.unwrap_or(1.0);
                // [B, T, H_kv, 1]: one gate per KV head.
                let g = burn::tensor::activation::sigmoid(gate.forward(input.slice(s![
                    ..,
                    ..,
                    ..channels
                ])))
                .mul_scalar(scale)
                .unsqueeze_dim::<4>(3);
                v + g * ve.reshape(shape)
            }
            (None, Some(_)) => {
                panic!("a value embedding for an attention without a value residual")
            }
            (Some(_), None) => {
                panic!("an attention with a value residual needs its value embedding")
            }
        };
        v.swap_dims(1, 2)
    }

    /// The attention weights an uncached [`forward`](Self::forward) of
    /// `input` applies: per query head, `softmax(q k^T / sqrt(head_dim))`
    /// over the keys at and before each query, within the sliding window when
    /// there is one.
    ///
    /// # Arguments
    /// - `input`: a `[B, T, D]` sequence.
    /// - `r_emb`: a rotary embedding with len ``T``.
    ///
    /// # Returns
    /// - `[B, H_q, T, T]`, each row a distribution over the keys; zero at the
    ///   keys the mask and the window hide (above the diagonal, under a causal
    ///   mask).
    pub fn attention_weights(
        &self,
        input: Tensor<3>,
        r_emb: &RotaryEmbedding,
    ) -> Tensor<4> {
        let [b, t] = unpack_shape_contract!(
            ["B", "T", "D"],
            &input.dims(),
            &["B", "T"],
            &[("D", self.n_embed())]
        );
        let (q, k, _) = self.queries_keys(input, r_emb);
        let device = q.device();
        let window = self.sliding_window.filter(|&w| w < t);
        let visible = window.map(|w| match self.mask {
            AttentionMask::Causal => causal_window_visible(t, t, Some(w), &device),
            AttentionMask::Bidirectional => two_sided_window_visible(t, w, &device),
        });
        let weights = sdpa_attn_weight(
            q,
            k,
            None,
            visible,
            None,
            self.sdpa_config()
                .with_is_causal(window.is_none() && self.mask == AttentionMask::Causal),
        );
        assert_shape_contract_periodically!(
            ["B", "H", "T", "T"],
            &weights.dims(),
            &[("B", b), ("H", self.n_head()), ("T", t)]
        );
        weights
    }

    /// Forward Pass.
    ///
    /// # Arguments
    /// - `input`: a `[B, T, D]` sequence.
    /// - `r_emb`: a rotary embedding with len ``T``.
    /// - `kv_cache`: optional KV cache.
    ///
    /// # Returns
    /// - `[B, T, D]` attention.
    ///
    /// # Panics
    /// If the attention has a value residual: that needs
    /// [`forward_with`](Self::forward_with).
    pub fn forward(
        &self,
        input: Tensor<3>,
        r_emb: &RotaryEmbedding,
        kv_cache: &mut Option<&mut KVCache>,
    ) -> Tensor<3> {
        self.forward_with(input, r_emb, kv_cache, AttentionSides::default())
    }

    /// Forward Pass, with the side inputs a configured attention takes.
    ///
    /// # Arguments
    /// - `input`: a `[B, T, D]` sequence.
    /// - `r_emb`: a rotary embedding with len ``T``.
    /// - `kv_cache`: optional KV cache.
    /// - `sides`: the value embedding of an attention with a value residual,
    ///   and the keys that are not padding.
    ///
    /// # Returns
    /// - `[B, T, D]` attention.
    ///
    /// # Panics
    /// If a value embedding is given to an attention without a value
    /// residual, or withheld from one with a value residual; or a KV cache
    /// is given to a bidirectional attention.
    pub fn forward_with(
        &self,
        input: Tensor<3>,
        r_emb: &RotaryEmbedding,
        kv_cache: &mut Option<&mut KVCache>,
        sides: AttentionSides,
    ) -> Tensor<3> {
        let AttentionSides {
            value_embed,
            key_valid,
        } = sides;
        let [b, t_q] = unpack_shape_contract!(
            ["B", "T", "D"],
            &input.dims(),
            &["B", "T"],
            &[("D", self.n_embed())]
        );

        #[cfg(any(debug_assertions, test))]
        crate::burner::module::assert_input_dtype(self, input.dtype(), "causal self-attention");

        let (q, k, gate) = self.queries_keys(input.clone(), r_emb);

        let v = self.values(input, value_embed);

        // B, H_?, T, D

        let mut k = k;
        let mut v = v;

        if let Some(kvc) = kv_cache {
            (k, v) = (*kvc).insert_kv(self.layer_index, k.clone(), v.clone());
        }
        let mut t_kv = k.dims()[2];

        // The window binds only once there are more keys than it spans. One
        // new token sees the window's last keys, which a slice keeps; anything
        // else is masked.
        let window = self.sliding_window.filter(|&w| w < t_kv);
        if let (Some(w), 1) = (window, t_q) {
            k = k.slice(s![.., .., t_kv - w..]);
            v = v.slice(s![.., .., t_kv - w..]);
            t_kv = w;
        }

        let attn_mask: Option<Tensor<2, Bool>>;
        let is_causal: bool;
        if self.mask == AttentionMask::Bidirectional {
            assert!(
                kv_cache.is_none(),
                "a bidirectional attention takes no KV cache"
            );
            attn_mask = window.map(|w| two_sided_window_visible(t_q, w, &q.device()));
            is_causal = false;
        } else if let (Some(w), true) = (window, t_q > 1) {
            attn_mask = Some(causal_window_visible(t_q, t_kv, Some(w), &q.device()));
            is_causal = false;
        } else if kv_cache.is_none() || t_q == t_kv {
            attn_mask = None;
            is_causal = true;
        } else if t_q == 1 {
            attn_mask = None;
            is_causal = false;
        } else {
            let device = q.device();
            let mut mask = Tensor::<2, Bool>::empty([t_q, t_kv], &device);
            let prefix_len = t_kv - t_q;
            if prefix_len > 0 {
                mask = mask.slice_fill(s![.., ..prefix_len], true);
            }
            // Causal within the chunk: each new token sees itself and the
            // new tokens before it.
            let fill = Tensor::<2, Int>::ones([t_q, t_q], &device).tril(0).bool();
            mask = mask.slice_assign(s![.., prefix_len..], fill);

            attn_mask = Some(mask);
            is_causal = false;
        };

        let cfg = self.sdpa_config().with_is_causal(is_causal);

        let y = scaled_dot_product_attention(q, k, v, None, attn_mask, key_valid, cfg)
            .swap_dims(1, 2)
            .reshape([
                b as i32,
                t_q as i32,
                (self.n_head() * self.head_dim()) as i32,
            ]);
        let y = match gate {
            Some(gate) => y * burn::tensor::activation::sigmoid(gate),
            None => y,
        };

        let y = self.c_proj.forward(y);

        assert_shape_contract_periodically!(
            ["B", "T", "D"],
            &y.dims(),
            &[("B", b), ("T", t_q), ("D", self.n_embed())]
        );

        y
    }
}

/// [`CausalSelfAttention`]'s call
/// ([`forward_with`](CausalSelfAttention::forward_with)): the rotary table, the
/// decode's cache if any, and the side inputs.
#[derive(Debug)]
pub struct CausalAttnCall<'a, 'c> {
    /// The rotary table.
    pub r_emb: &'a RotaryEmbedding,

    /// The decode's cache, or `None` for a prefill without one.
    pub kv_cache: &'a mut Option<&'c mut KVCache>,

    /// The side inputs.
    pub sides: AttentionSides,
}

impl SublayerBranch<CausalAttnCall<'_, '_>, 3> for CausalSelfAttention {
    type Output = Tensor<3>;

    fn call_branch(
        &self,
        z: Tensor<3>,
        ctx: CausalAttnCall<'_, '_>,
    ) -> Tensor<3> {
        self.forward_with(z, ctx.r_emb, ctx.kv_cache, ctx.sides)
    }
}

/// A causal self-attention sublayer ([`CausalAttnCall`]).
pub trait CausalAttnSublayer {
    /// The residual update, the branch attending causally under `r_emb`,
    /// over `kv_cache` when a decode has one, with the side inputs.
    fn causal_attn(
        &self,
        x: Tensor<3>,
        r_emb: &RotaryEmbedding,
        kv_cache: &mut Option<&mut KVCache>,
        sides: AttentionSides,
    ) -> Tensor<3>;
}

impl<M> CausalAttnSublayer for ResidualSublayer<M>
where
    M: Module + for<'a, 'c> SublayerBranch<CausalAttnCall<'a, 'c>, 3, Output = Tensor<3>>,
{
    fn causal_attn(
        &self,
        x: Tensor<3>,
        r_emb: &RotaryEmbedding,
        kv_cache: &mut Option<&mut KVCache>,
        sides: AttentionSides,
    ) -> Tensor<3> {
        self.residual_update(
            x,
            CausalAttnCall {
                r_emb,
                kv_cache,
                sides,
            },
        )
    }
}

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

    use super::*;
    use crate::{
        blocks::transformers::embedding::{
            RotaryEmbedding,
            RotaryEmbeddingConfig,
        },
        burner::module::ModuleInit,
        contracts::assert_shape_contract,
        ops::transformers::attention::KVCacheConfig,
        support::testing::{
            DeviceMemoryGuard,
            assert_tensors_close,
            cpu_device,
            performance_device,
            seeded_tensor,
        },
    };

    #[test]
    fn test_csa_config() {
        let cfg = CausalSelfAttentionConfig::new(3, 2, 4);
        assert_eq!(cfg.n_embed, 4);
        assert_eq!(cfg.n_head, 3);
        assert_eq!(cfg.n_kv_head, 2);
        assert_eq!(cfg.n_embed(), 4);
        assert_eq!(cfg.n_head(), 3);
        assert_eq!(cfg.n_kv_head(), 2);
        assert_eq!(cfg.head_dim(), 1);
    }

    #[test]
    #[allow(unused)]
    fn test_csa_forward() {
        let device = cpu_device();

        let batch = 1;
        let seq_len = 10;

        let n_embed = 1024;
        let n_head = 128;
        let n_kv_head = 64;
        let layer_index = 12;

        let cfg = CausalSelfAttentionConfig::new(n_head, n_kv_head, n_embed);
        let csa: CausalSelfAttention = cfg.init(layer_index, &device);

        let head_dim = csa.head_dim();

        let re_cfg = RotaryEmbeddingConfig::new(seq_len, csa.head_dim());
        let r_emb: RotaryEmbedding = re_cfg.init(&device);

        let input: Tensor<3> =
            Tensor::random([batch, seq_len, n_embed], Distribution::Default, &device);

        let mut kv_cache: Option<&mut KVCache> = None;

        let output = csa.forward(input.clone(), &r_emb, &mut kv_cache);
        assert_shape_contract!(
            ["B", "T", "D"],
            &output.dims(),
            &[("B", batch), ("T", seq_len), ("D", n_embed)]
        );
    }

    /// The weights are what the forward pass applies: each row a causal
    /// distribution, and the values they weigh, projected, the output.
    #[test]
    fn test_attention_weights_are_the_forwards() {
        let device = cpu_device();
        let (batch, seq_len, n_embed, n_head, n_kv_head) = (2, 6, 32, 4, 2);
        let csa: CausalSelfAttention =
            CausalSelfAttentionConfig::new(n_head, n_kv_head, n_embed).init(0, &device);
        let head_dim = csa.head_dim();
        let r_emb: RotaryEmbedding = RotaryEmbeddingConfig::new(seq_len, head_dim).init(&device);
        let input: Tensor<3> =
            Tensor::random([batch, seq_len, n_embed], Distribution::Default, &device);

        let weights = csa.attention_weights(input.clone(), &r_emb);
        assert_eq!(weights.dims(), [batch, n_head, seq_len, seq_len]);
        let sums = weights.clone().sum_dim(3);
        assert_tensors_close(&sums, &Tensor::ones_like(&sums), Tolerance::default());
        let upper = weights.clone().triu(1).abs().max().into_scalar::<f32>();
        assert_eq!(upper, 0.0);

        let v = csa
            .c_v
            .forward(input.clone())
            .reshape([batch, seq_len, n_kv_head, head_dim])
            .swap_dims(1, 2);
        let v = crate::ops::repeat::repeat_interleave::<4, 5, _>(v, n_head / n_kv_head, 1);
        let applied = csa
            .c_proj
            .forward(weights.matmul(v).swap_dims(1, 2).reshape([
                batch,
                seq_len,
                n_head * head_dim,
            ]));
        let forward = csa.forward(input, &r_emb, &mut None);
        assert_tensors_close(&applied, &forward, Tolerance::default());
    }

    /// A bidirectional attention sees every key, the ones after a query
    /// too, but an item's padding: the forward is the softmax over an
    /// item's valid keys, so a valid query's output does not depend on what
    /// the padding holds.
    #[test]
    fn test_bidirectional_with_padding() {
        let device = cpu_device();
        let (seq_len, n_embed, n_head) = (5, 16, 2);
        let csa: CausalSelfAttention = CausalSelfAttentionConfig::new(n_head, n_head, n_embed)
            .with_norm(None)
            .with_mask(AttentionMask::Bidirectional)
            .init(0, &device);
        let r_emb: RotaryEmbedding =
            RotaryEmbeddingConfig::new(seq_len, csa.head_dim()).init(&device);
        let input = seeded_tensor::<3>(4, [2, seq_len, n_embed], Distribution::Default, &device);

        let weights = csa.attention_weights(input.clone(), &r_emb);
        let upper = weights.triu(1).abs().max().into_scalar::<f32>();
        assert!(upper > 0.0, "a query sees the keys after it");

        // Item 1 is 3 long: its last two positions are padding, so changing
        // them changes none of its first three outputs.
        let valid =
            crate::ops::transformers::attention::length_mask(&[seq_len, 3], seq_len, &device);
        let forward = |x: Tensor<3>| {
            csa.forward_with(
                x,
                &r_emb,
                &mut None,
                AttentionSides {
                    key_valid: Some(valid.clone()),
                    ..Default::default()
                },
            )
        };
        let noise = seeded_tensor::<3>(5, [1, 2, n_embed], Distribution::Default, &device);
        let changed = input.clone().slice_assign([1..2, 3..5, 0..n_embed], noise);
        assert_tensors_close(
            &forward(input.clone()).slice([1..2, 0..3, 0..n_embed]),
            &forward(changed.clone()).slice([1..2, 0..3, 0..n_embed]),
            Tolerance::default(),
        );
        // Item 0, all valid, does depend on its last positions.
        let changed0 = input.clone().slice_assign(
            [0..1, 3..5, 0..n_embed],
            seeded_tensor::<3>(6, [1, 2, n_embed], Distribution::Default, &device),
        );
        assert!(!forward(input).slice([0..1, 0..3, 0..n_embed]).all_close(
            forward(changed0).slice([0..1, 0..3, 0..n_embed]),
            None,
            None
        ));
    }

    /// A bidirectional attention under a two-sided window: each query's
    /// output is the output an unwindowed pass computes over only the
    /// window centred on it (`|i - j| < w`), the keys after it too; the
    /// weights are zero outside the band.
    #[test]
    fn test_two_sided_window_is_the_window_alone() {
        let device = cpu_device();
        let (seq_len, window) = (9, 3);
        let csa: CausalSelfAttention = CausalSelfAttentionConfig::new(4, 2, 16)
            .with_norm(None)
            .with_mask(AttentionMask::Bidirectional)
            .with_sliding_window(Some(window))
            .init(0, &device);
        let r_emb = RotaryEmbeddingConfig::new(seq_len, csa.head_dim()).init(&device);
        let input = seeded_tensor::<3>(7, [2, seq_len, 16], Distribution::Default, &device);
        let full = csa.forward(input.clone(), &r_emb, &mut None);

        let mut unwindowed = csa.clone();
        unwindowed.sliding_window = None;
        for i in 0..seq_len {
            let (start, end) = ((i + 1).saturating_sub(window), (i + window).min(seq_len));
            let alone = unwindowed.forward(
                input.clone().slice(s![.., start..end]),
                &r_emb.clip_range(start..end),
                &mut None,
            );
            assert_tensors_close(
                &full.clone().slice(s![.., i..=i]),
                &alone.slice(s![.., i - start..=i - start]),
                Tolerance::default(),
            );
        }

        let weights = csa.attention_weights(input, &r_emb);
        let sums = weights.clone().sum_dim(3);
        assert_tensors_close(&sums, &Tensor::ones_like(&sums), Tolerance::default());
        let outside = weights
            .clone()
            .triu(window as i64)
            .abs()
            .max()
            .into_scalar::<f32>()
            + weights
                .clone()
                .tril(-(window as i64))
                .abs()
                .max()
                .into_scalar::<f32>();
        assert_eq!(outside, 0.0);
        let after = weights.triu(1).abs().max().into_scalar::<f32>();
        assert!(after > 0.0, "a query sees the keys after it");
    }

    /// The two-sided window and an item's padding mask together: a valid
    /// query's output is the unwindowed pass over the valid keys of its
    /// window, whatever the padding holds.
    #[test]
    fn test_two_sided_window_with_padding() {
        let device = cpu_device();
        let (seq_len, window, valid_len) = (7, 3, 5);
        let csa: CausalSelfAttention = CausalSelfAttentionConfig::new(2, 2, 16)
            .with_norm(None)
            .with_mask(AttentionMask::Bidirectional)
            .with_sliding_window(Some(window))
            .init(0, &device);
        let r_emb = RotaryEmbeddingConfig::new(seq_len, csa.head_dim()).init(&device);
        let input = seeded_tensor::<3>(3, [1, seq_len, 16], Distribution::Default, &device);
        let valid =
            crate::ops::transformers::attention::length_mask(&[valid_len], seq_len, &device);
        let padded = csa.forward_with(
            input.clone(),
            &r_emb,
            &mut None,
            AttentionSides {
                key_valid: Some(valid),
                ..Default::default()
            },
        );
        let mut unwindowed = csa.clone();
        unwindowed.sliding_window = None;
        for i in 0..valid_len {
            let (start, end) = ((i + 1).saturating_sub(window), (i + window).min(valid_len));
            let alone = unwindowed.forward(
                input.clone().slice(s![.., start..end]),
                &r_emb.clip_range(start..end),
                &mut None,
            );
            assert_tensors_close(
                &padded.clone().slice(s![.., i..=i]),
                &alone.slice(s![.., i - start..=i - start]),
                Tolerance::default(),
            );
        }
    }

    #[test]
    #[should_panic(expected = "takes no KV cache")]
    fn test_bidirectional_takes_no_cache() {
        let device = cpu_device();
        let csa: CausalSelfAttention = CausalSelfAttentionConfig::new(2, 2, 16)
            .with_mask(AttentionMask::Bidirectional)
            .init(0, &device);
        let r_emb: RotaryEmbedding = RotaryEmbeddingConfig::new(3, csa.head_dim()).init(&device);
        let mut cache = KVCacheConfig::new(1, 2, 3, csa.head_dim(), 1).init();
        let _ = csa.forward(
            Tensor::zeros([1, 3, 16], &device),
            &r_emb,
            &mut Some(&mut cache),
        );
    }

    /// The scores' scale and soft-cap reach the softmax: the weights are
    /// `softmax(c · tanh(q kᵀ · scale / c))` over the visible keys, and the
    /// forward still applies them.
    #[test]
    fn test_score_scale_and_softcap() {
        let device = cpu_device();
        let (batch, seq_len, n_embed, n_head, n_kv_head) = (1, 5, 16, 2, 1);
        let (scale, cap) = (0.9, 0.7);
        let csa: CausalSelfAttention = CausalSelfAttentionConfig::new(n_head, n_kv_head, n_embed)
            .with_score_scale(Some(scale))
            .with_attn_softcap(Some(cap))
            .init(0, &device);
        let r_emb: RotaryEmbedding =
            RotaryEmbeddingConfig::new(seq_len, csa.head_dim()).init(&device);
        let input =
            seeded_tensor::<3>(3, [batch, seq_len, n_embed], Distribution::Default, &device);

        let (q, k, _) = csa.queries_keys(input.clone(), &r_emb);
        let k = crate::ops::repeat::repeat_interleave::<4, 5, _>(k, n_head / n_kv_head, 1);
        let scores = q.matmul(k.swap_dims(2, 3)).mul_scalar(scale);
        assert!(
            scores.clone().abs().max().into_scalar::<f32>() > cap as f32,
            "the cap binds"
        );
        let capped = scores.div_scalar(cap).tanh().mul_scalar(cap);
        let visible = Tensor::<2, Int>::ones([seq_len, seq_len], &device)
            .tril(0)
            .bool();
        let expected = burn::tensor::activation::softmax(
            capped.mask_fill(visible.bool_not().unsqueeze::<4>(), f32::NEG_INFINITY),
            3,
        );
        assert_tensors_close(
            &csa.attention_weights(input.clone(), &r_emb),
            &expected,
            Tolerance::default(),
        );

        let plain: CausalSelfAttention =
            CausalSelfAttentionConfig::new(n_head, n_kv_head, n_embed).init(0, &device);
        assert!(plain.score_scale.is_none() && plain.attn_softcap.is_none());
    }

    /// A chunk of several new tokens after a cached prefix attends as the
    /// uncached pass does: each new token sees the prefix, the earlier new
    /// tokens, and itself.
    #[test]
    #[serial]
    fn test_csa_cached_chunk_matches_full_pass() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        let [batch, seq_len, n_embed] = [2, 6, 16];
        let prefix = 3;

        for output_gate in [false, true] {
            let csa: CausalSelfAttention = CausalSelfAttentionConfig::new(4, 2, n_embed)
                .with_output_gate(output_gate)
                .init(0, &device);
            let r_emb: RotaryEmbedding =
                RotaryEmbeddingConfig::new(seq_len, csa.head_dim()).init(&device);
            let input =
                seeded_tensor::<3>(1, [batch, seq_len, n_embed], Distribution::Default, &device);

            let full = csa.forward(input.clone(), &r_emb, &mut None);

            let mut cache: KVCache =
                KVCacheConfig::new(batch, csa.n_kv_head(), seq_len, csa.head_dim(), 1).init();
            let head = csa.forward(
                input.clone().slice(s![.., ..prefix]),
                &r_emb.clip_range(0..prefix),
                &mut Some(&mut cache),
            );
            let chunk = csa.forward(
                input.slice(s![.., prefix..]),
                &r_emb.clip_range(prefix..seq_len),
                &mut Some(&mut cache),
            );

            assert_tensors_close(
                &head,
                &full.clone().slice(s![.., ..prefix]),
                Tolerance::default(),
            );
            assert_tensors_close(&chunk, &full.slice(s![.., prefix..]), Tolerance::default());
        }
    }

    /// Heads wider than `n_embed / n_head` project to and from
    /// `n_head * head_dim`; either norm placement keeps the shape.
    #[test]
    fn test_explicit_head_dim() {
        use crate::{
            blocks::transformers::embedding::RotaryEmbeddingConfig,
            burner::module::ModuleInit,
            support::testing::cpu_device,
        };
        let device = cpu_device();
        for placement in [QkNormPlacement::AfterRope, QkNormPlacement::BeforeRope] {
            let cfg = CausalSelfAttentionConfig::new(2, 1, 12)
                .with_head_dim(Some(8))
                .with_qk_norm(placement);
            assert_eq!(cfg.head_dim(), 8);
            let attn = cfg.init(0, &device);
            assert_eq!(attn.n_head(), 2);
            assert_eq!(attn.n_kv_head(), 1);
            assert_eq!(attn.c_proj.weight.dims(), [16, 12]);
            let r_emb = RotaryEmbeddingConfig::new(5, 8).init(&device);
            let y = attn.forward(Tensor::zeros([2, 5, 12], &device), &r_emb, &mut None);
            assert_eq!(y.dims(), [2, 5, 12]);
        }
    }

    /// A config non-default in every field, and the layer built from it,
    /// answer the meta alike, and the layer builds what the config names.
    #[test]
    fn test_meta_and_options() {
        let device = cpu_device();
        let cfg = CausalSelfAttentionConfig::new(4, 2, 12)
            .with_head_dim(Some(5))
            .with_norm(None)
            .with_qk_norm(QkNormPlacement::BeforeRope)
            .with_qkv_bias(true)
            .with_key_bias(Some(false))
            .with_output_bias(true)
            .with_sliding_window(Some(3));
        let csa: CausalSelfAttention = cfg.init(1, &device);
        assert_eq!(csa.n_embed(), cfg.n_embed());
        assert_eq!(csa.n_head(), cfg.n_head());
        assert_eq!(csa.n_kv_head(), cfg.n_kv_head());
        assert_eq!(csa.head_dim(), cfg.head_dim());
        assert_eq!(csa.qk_norm, cfg.qk_norm);
        assert_eq!(csa.sliding_window, cfg.sliding_window);
        assert!(csa.q_norm.is_none() && csa.k_norm.is_none());
        assert!(csa.c_q.bias.is_some());
        assert!(!cfg.key_bias());
        assert!(csa.c_k.bias.is_none());
        assert!(csa.c_v.bias.is_some());
        assert!(csa.c_proj.bias.is_some());

        let defaults: CausalSelfAttention =
            CausalSelfAttentionConfig::new(4, 2, 12).init(0, &device);
        assert!(defaults.q_norm.is_some() && defaults.k_norm.is_some());
        for linear in [
            &defaults.c_q,
            &defaults.c_k,
            &defaults.c_v,
            &defaults.c_proj,
        ] {
            assert!(linear.bias.is_none());
        }
        assert_eq!(defaults.sliding_window, None);
    }

    /// Under an output gate, `c_q` holds each head's queries, then its
    /// gates: the forward is the ungated attention over the query columns,
    /// times `σ` of the gate columns, before `c_proj`. With `c_proj` the
    /// identity, the two outputs differ by exactly that factor.
    #[test]
    fn test_output_gate() {
        let device = cpu_device();
        let (batch, seq_len, n_embed, n_head, n_kv_head) = (2, 5, 16, 4, 2);
        let cfg = CausalSelfAttentionConfig::new(n_head, n_kv_head, n_embed);
        let mut gated: CausalSelfAttention = cfg.clone().with_output_gate(true).init(0, &device);
        let d = gated.head_dim();
        assert_eq!(gated.c_q.weight.dims(), [n_embed, 2 * n_head * d]);
        assert_eq!(gated.n_head(), n_head);
        assert_eq!(gated.n_kv_head(), n_kv_head);

        let identity = Param::from_tensor(Tensor::<2>::eye(n_embed, &device));
        gated.c_proj.weight = identity.clone();
        let w = gated.c_q.weight.val().reshape([n_embed, n_head, 2 * d]);
        let query_cols = w
            .clone()
            .slice(s![.., .., ..d])
            .reshape([n_embed, n_head * d]);
        let gate_cols = w.slice(s![.., .., d..]).reshape([n_embed, n_head * d]);

        let mut plain: CausalSelfAttention = cfg.init(0, &device);
        plain.c_q.weight = Param::from_tensor(query_cols);
        plain.c_k = gated.c_k.clone();
        plain.c_v = gated.c_v.clone();
        plain.q_norm = gated.q_norm.clone();
        plain.k_norm = gated.k_norm.clone();
        plain.c_proj.weight = identity;

        let r_emb = RotaryEmbeddingConfig::new(seq_len, d).init(&device);
        let input =
            seeded_tensor::<3>(8, [batch, seq_len, n_embed], Distribution::Default, &device);
        let gate = burn::tensor::activation::sigmoid(input.clone().matmul(gate_cols.unsqueeze()));
        let expected = plain.forward(input.clone(), &r_emb, &mut None) * gate;
        let actual = gated.forward(input.clone(), &r_emb, &mut None);
        assert_tensors_close(&actual, &expected, Tolerance::default());

        // The weights the gate follows are the ungated attention's.
        assert_tensors_close(
            &gated.attention_weights(input.clone(), &r_emb),
            &plain.attention_weights(input, &r_emb),
            Tolerance::default(),
        );
    }

    fn windowed(window: usize) -> (CausalSelfAttention, RotaryEmbedding, Tensor<3>) {
        let device = cpu_device();
        let csa: CausalSelfAttention = CausalSelfAttentionConfig::new(4, 2, 16)
            .with_norm(None)
            .with_qkv_bias(true)
            .with_key_bias(Some(false))
            .with_output_bias(true)
            .with_sliding_window(Some(window))
            .init(0, &device);
        let r_emb = RotaryEmbeddingConfig::new(9, csa.head_dim()).init(&device);
        let input = seeded_tensor::<3>(7, [2, 9, 16], Distribution::Default, &device);
        (csa, r_emb, input)
    }

    /// Under a sliding window, each query's output is the output an
    /// unwindowed pass computes over only the window ending at it: the
    /// window masks exactly the keys it should.
    #[test]
    fn test_sliding_window_is_the_window_alone() {
        let window = 3;
        let (csa, r_emb, input) = windowed(window);
        let full = csa.forward(input.clone(), &r_emb, &mut None);

        let mut unwindowed = csa.clone();
        unwindowed.sliding_window = None;
        for i in 0..9 {
            let start = (i + 1usize).saturating_sub(window);
            let alone = unwindowed.forward(
                input.clone().slice(s![.., start..=i]),
                &r_emb.clip_range(start..i + 1),
                &mut None,
            );
            assert_tensors_close(
                &full.clone().slice(s![.., i..=i]),
                &alone.slice(s![.., i - start..=i - start]),
                Tolerance::default(),
            );
        }

        // The weights agree: zero outside the window, each row a
        // distribution.
        let weights = csa.attention_weights(input, &r_emb);
        let sums = weights.clone().sum_dim(3);
        assert_tensors_close(&sums, &Tensor::ones_like(&sums), Tolerance::default());
        let outside = weights.clone().triu(1).abs().max().into_scalar::<f32>()
            + weights
                .tril(-(window as i64))
                .abs()
                .max()
                .into_scalar::<f32>();
        assert_eq!(outside, 0.0);
    }

    /// A windowed decode through the cache, one token at a time or a chunk
    /// after a prefix, is the windowed uncached pass.
    #[test]
    fn test_sliding_window_through_the_cache() {
        let (csa, r_emb, input) = windowed(3);
        let full = csa.forward(input.clone(), &r_emb, &mut None);

        let mut cache: KVCache = KVCacheConfig::new(2, 2, 9, csa.head_dim(), 1).init();
        let steps: Vec<Tensor<3>> = (0..9)
            .map(|i| {
                csa.forward(
                    input.clone().slice(s![.., i..=i]),
                    &r_emb.clip_range(i..i + 1),
                    &mut Some(&mut cache),
                )
            })
            .collect();
        assert_tensors_close(&Tensor::cat(steps, 1), &full, Tolerance::default());

        let mut cache: KVCache = KVCacheConfig::new(2, 2, 9, csa.head_dim(), 1).init();
        let head = csa.forward(
            input.clone().slice(s![.., ..4]),
            &r_emb.clip_range(0..4),
            &mut Some(&mut cache),
        );
        let chunk = csa.forward(
            input.slice(s![.., 4..]),
            &r_emb.clip_range(4..9),
            &mut Some(&mut cache),
        );
        assert_tensors_close(
            &Tensor::cat(vec![head, chunk], 1),
            &full,
            Tolerance::default(),
        );
    }
}