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
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
//! # GPT Module

use burn::{
    Tensor,
    module::{
        Module,
        Param,
    },
    nn::{
        Embedding,
        EmbeddingConfig,
        Initializer,
        Linear,
        LinearConfig,
        norm::RmsNormConfig,
    },
    prelude::{
        Config,
        Int,
        s,
    },
    tensor::{
        Device,
        FloatDType,
        activation::sigmoid,
    },
};

use crate::{
    blocks::{
        activation::BunsenActivationConfig,
        norm::BunsenNormalizationConfig,
        transformers::{
            attention::csa::{
                CausalSelfAttentionConfig,
                CausalSelfAttentionMeta,
                ValueResidualConfig,
            },
            decoders::{
                causal::CausalDecoderBlockConfig,
                stack::{
                    DecoderStackMeta,
                    DecoderStackResidualMix,
                    DecoderStackSides,
                    DecoderStackStructureConfig,
                },
            },
            embedding::{
                RotaryEmbedding,
                RotaryEmbeddingConfig,
                RotaryEmbeddingMeta,
                RotarySet,
                TokenEmbeddingConfig,
                TokenEmbeddingMeta,
            },
            head::{
                LmHeadConfig,
                LmHeadMeta,
            },
            mlp::TransformerMlpConfig,
            models::language_decoder::{
                LmDecoderModel,
                LmDecoderStructureConfig,
            },
        },
    },
    burner::module::{
        CanonicalKeys,
        ModuleInit,
        Rekey,
        ToStructureConfig,
    },
    contracts::{
        assert_shape_contract_periodically,
        unpack_shape_contract,
    },
    errors::{
        BunsenError,
        BunsenResult,
    },
    ops::transformers::attention::{
        KVCache,
        KVCacheConfig,
        KVCacheModel,
    },
};

/// The [`KVCacheConfig`] a `NanoChat` model of `meta`'s geometry decodes with:
/// its KV heads, head width and layer count, `init_seq_len` positions up
/// front, capped at `max_seq_len` (the rotary table's length).
fn kv_cache_config(meta: &impl NanoChatGptMeta) -> KVCacheConfig {
    KVCacheConfig::for_decode(
        meta.n_kv_head(),
        meta.init_seq_len(),
        meta.head_dim(),
        meta.n_layer(),
    )
    .with_max_seq_len(Some(meta.max_seq_len()))
}

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

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

/// A decode's cache is injected state: the caller holds the one
/// [`new_kv_cache`](KVCacheModel::new_kv_cache) builds and passes it to each
/// [`forward`](NanoChatGpt::forward), and the model never owns one.
impl KVCacheModel for NanoChatGpt {
    fn kv_cache_config(&self) -> KVCacheConfig {
        kv_cache_config(self)
    }
}

/// Common meta for [`NanoChatGpt`], [`NanoChatGptStructureConfig`], and
/// [`NanoChatGptContractConfig`].
pub trait NanoChatGptMeta {
    /// 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()
    }

    /// Returns the initial sequence length.
    fn init_seq_len(&self) -> usize;

    /// Returns the maximum sequence length.
    fn max_seq_len(&self) -> usize;

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

    /// Returns the vocabulary size: the logits' width, whatever the
    /// embedding is padded to.
    fn vocab_size(&self) -> usize;
}

/// Whether nanochat's layer `layer` of `n_layer` has a value embedding:
/// every other layer, the last always (upstream's `has_ve`).
pub fn has_value_embed(
    layer: usize,
    n_layer: usize,
) -> bool {
    layer % 2 == (n_layer - 1) % 2
}

/// Each layer's sliding window, in keys (a query and the positions before it
/// it may attend to), from a nanochat window pattern: the pattern's letters,
/// tiled across the layers, `L` the long window and `S` the short, the last
/// layer always long. Upstream's long window is `seq_len` positions back,
/// its short one a quarter of that rounded up to 128; a window of `w`
/// positions back spans `w + 1` keys.
///
/// # Errors
/// If the pattern is empty or holds anything but `S` and `L`.
pub fn window_pattern_windows(
    pattern: &str,
    seq_len: usize,
    n_layer: usize,
) -> BunsenResult<Vec<usize>> {
    let pattern = pattern.to_ascii_uppercase();
    if pattern.is_empty() || !pattern.chars().all(|c| c == 'S' || c == 'L') {
        return Err(BunsenError::illegal(format!(
            "a window pattern is letters S and L; got {pattern:?}"
        )));
    }
    let long = seq_len;
    let short = seq_len.div_ceil(4).div_ceil(128) * 128;
    let letters: Vec<char> = pattern.chars().collect();
    let mut windows: Vec<usize> = (0..n_layer)
        .map(|i| match letters[i % letters.len()] {
            'S' => short + 1,
            _ => long + 1,
        })
        .collect();
    if let Some(last) = windows.last_mut() {
        *last = long + 1;
    }
    Ok(windows)
}

/// High-level GPT Config.
///
/// User-facing configuration for the nanoChat GPT model, exposing the common
/// hyperparameters (sizes, layer/head counts, vocabulary, softcap): the
/// policy of `NanoChatGpt`'s Stacked Config. It implements
/// [`ToStructureConfig`], expanding into a [`NanoChatGptStructureConfig`], and
/// gets [`ModuleInit`] from that trait's blanket impl, so `.init(&device)`
/// builds the [`NanoChatGpt`] module directly.
///
/// The defaults are upstream nanochat's 2025 model. Upstream's 2026 model is
/// the same with the options under "2026" on
/// ([`with_upstream_2026`](Self::with_upstream_2026)), each of which is off
/// by default.
#[derive(Config, Debug)]
pub struct NanoChatGptContractConfig {
    /// Initial sequence Length.
    #[config(default = "1024")]
    pub init_seq_len: usize,

    /// Max `seq_len` factor.
    #[config(default = "10")]
    pub max_seq_len_factor: usize,

    /// Vocabulary Size.
    #[config(default = "50304")]
    pub vocab_size: usize,

    /// Number of Blocks.
    #[config(default = "12")]
    pub n_layer: usize,

    /// Number of Query Heads.
    #[config(default = "6")]
    pub n_head: usize,

    /// Number of KV Heads.
    #[config(default = "6")]
    pub n_kv_head: usize,

    /// Embedding Size.
    #[config(default = "768")]
    pub n_embed: usize,

    /// Softcap for the logits.
    #[config(default = "15.0")]
    pub softcap: f64,

    /// MLP Expansion Factor.
    #[config(default = "4")]
    pub expansion_factor: usize,

    /// The MLP's activation, before its square (`relu(x)²` by default).
    #[config(default = "BunsenActivationConfig::Relu")]
    pub activation: BunsenActivationConfig,

    /// Normalization.
    /// This normalization will be adapted to the appropriate feature count.
    #[config(default = "BunsenNormalizationConfig::Rms(RmsNormConfig::new(0).with_epsilon(1e-6))")]
    pub norm: BunsenNormalizationConfig,

    /// The epsilon of the parameter-free RMS norm on the token embedding;
    /// the default [`norm`](Self::norm) uses the same.
    ///
    /// Upstream's norms take fp32's epsilon (≈1.19e-7); 1e-6 is the
    /// `transformers` port's, and differs from upstream's by under 5e-5,
    /// relatively, at a mean square of 0.01.
    #[config(default = "1e-6")]
    pub norm_eps: f64,

    /// The rotary embedding's base: 10000 in upstream's 2025 model, 100000
    /// in its 2026 one.
    #[config(default = "10000")]
    pub rope_base: usize,

    /// Whether the rotary tables are rounded to bf16 values, as upstream's
    /// 2025 model keeps them whatever it computes in (its checkpoints were
    /// trained with them); its 2026 model builds them in the compute dtype.
    #[config(default = "true")]
    pub rope_bf16_tables: bool,

    /// Whether the head carries a bias. Upstream's has none.
    #[config(default = "false")]
    pub head_bias: bool,

    /// 2026: pad the embedding and the head to a multiple of this many
    /// tokens (upstream's 64); the logits are sliced back to `vocab_size`.
    #[config(default = "None")]
    pub pad_vocab_to: Option<usize>,

    /// 2026: before each block `i`, `x = resid_lambdas[i] * x +
    /// x0_lambdas[i] * x0`, `x0` the normalized (and smeared) embedding.
    #[config(default = "false")]
    pub residual_lambdas: bool,

    /// 2026: a value embedding on every other layer, the last always
    /// ([`has_value_embed`]), added to the attention's values through a gate
    /// ([`ValueResidualConfig`]).
    #[config(default = "false")]
    pub value_embeds: bool,

    /// 2026: the smear: each position adds the previous position's
    /// embedding, gated by `smear_lambda * sigmoid(smear_gate(x[..,
    /// :channels]))`; `Some(channels)` (upstream's 24).
    #[config(default = "None")]
    pub smear_channels: Option<usize>,

    /// 2026: the residual stream after block `n_layer / 2`, times
    /// `backout_lambda`, is subtracted before the final norm.
    #[config(default = "false")]
    pub backout: bool,

    /// 2026: the queries' and keys' gain after their norm (upstream's 1.2):
    /// the attention's score scale `g² / sqrt(head_dim)`.
    #[config(default = "None")]
    pub qk_gain: Option<f64>,

    /// 2026: per-layer sliding windows from a pattern of `S` and `L`
    /// ([`window_pattern_windows`]), over a long window of `init_seq_len`;
    /// `None` attends to every earlier position.
    #[config(default = "None")]
    pub window_pattern: Option<String>,
}

impl NanoChatGptMeta for NanoChatGptContractConfig {
    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 init_seq_len(&self) -> usize {
        self.init_seq_len
    }

    fn max_seq_len(&self) -> usize {
        self.init_seq_len() * self.max_seq_len_factor
    }

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

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

impl NanoChatGptContractConfig {
    /// Upstream nanochat's 2026 model (`karpathy/nanochat` at `a3ca42a6`):
    /// this config with rotary base 100000 and exact rotary tables, the
    /// vocabulary padded to 64,
    /// the residual lambdas, the value embeddings, the smear over 24
    /// channels, the backout, a query/key gain of 1.2, and the windows of
    /// `window_pattern`.
    pub fn with_upstream_2026(
        self,
        window_pattern: impl Into<String>,
    ) -> Self {
        self.with_rope_base(100000)
            .with_rope_bf16_tables(false)
            .with_pad_vocab_to(Some(64))
            .with_residual_lambdas(true)
            .with_value_embeds(true)
            .with_smear_channels(Some(24))
            .with_backout(true)
            .with_qk_gain(Some(1.2))
            .with_window_pattern(Some(window_pattern.into()))
    }

    /// The embedding and head's vocabulary: `vocab_size`, padded to a
    /// multiple of `pad_vocab_to` when that is set.
    pub fn padded_vocab_size(&self) -> usize {
        match self.pad_vocab_to {
            Some(m) if m > 0 => self.vocab_size.div_ceil(m) * m,
            _ => self.vocab_size,
        }
    }

    /// Builds the [`CausalDecoderBlockConfig`] for this config, with no
    /// sliding window and no value residual: the layer-independent part.
    pub fn block_config(&self) -> CausalDecoderBlockConfig {
        CausalDecoderBlockConfig::new(
            CausalSelfAttentionConfig::new(self.n_head, self.n_kv_head, self.n_embed)
                .with_norm(Some(self.norm.clone()))
                .with_score_scale(
                    self.qk_gain
                        .map(|g| g * g / (self.head_dim() as f64).sqrt()),
                )
                .into(),
            TransformerMlpConfig::new(self.n_embed)
                .with_expansion_factor(self.expansion_factor)
                .with_activation(BunsenActivationConfig::Chain(vec![
                    self.activation.clone(),
                    BunsenActivationConfig::Pow(2.0),
                ]))
                .into(),
        )
        .with_norm(self.norm.clone())
    }
}

impl ToStructureConfig for NanoChatGptContractConfig {
    type Structure = NanoChatGptStructureConfig;

    fn try_to_structure(&self) -> BunsenResult<NanoChatGptStructureConfig> {
        let windows = self
            .window_pattern
            .as_deref()
            .map(|p| window_pattern_windows(p, self.init_seq_len, self.n_layer))
            .transpose()?;
        let h = (0..self.n_layer)
            .map(|i| {
                let mut block = self.block_config();
                block.attn.attention_mut().sliding_window = windows.as_ref().map(|w| w[i]);
                if self.value_embeds && has_value_embed(i, self.n_layer) {
                    block.attn.attention_mut().value_residual = Some(ValueResidualConfig::new());
                }
                block
            })
            .collect();
        let vocab = self.padded_vocab_size();
        let kv_width = self.n_kv_head * self.head_dim();
        Ok(NanoChatGptStructureConfig {
            lm: LmDecoderStructureConfig::new(
                TokenEmbeddingConfig::new(vocab, self.n_embed).with_norm_eps(Some(self.norm_eps)),
                LmHeadConfig::new(self.n_embed, vocab)
                    .with_tied(false)
                    .with_bias(self.head_bias)
                    .with_softcap(Some(self.softcap))
                    .with_vocab(Some(self.vocab_size)),
                DecoderStackStructureConfig::new(
                    h,
                    self.norm.clone(),
                    RotaryEmbeddingConfig::new(self.max_seq_len(), self.head_dim())
                        .with_base(self.rope_base)
                        .with_table_dtype(self.rope_bf16_tables.then_some(FloatDType::BF16)),
                ),
            )
            .with_kv_cache_pre_size(self.init_seq_len),
            residual_lambdas: self.residual_lambdas,
            value_embeds: (0..self.n_layer)
                .map(|i| {
                    (self.value_embeds && has_value_embed(i, self.n_layer))
                        .then(|| EmbeddingConfig::new(vocab, kv_width))
                })
                .collect(),
            smear_channels: self.smear_channels,
            backout: self.backout,
        })
    }
}

/// Low-level GPT Structure Config.
///
/// The fully-expanded structural configuration for the [`NanoChatGpt`] module:
/// its language model's (embedding, per-layer blocks, head, rotary
/// embedding), and upstream's 2026 additions around it.
/// [`NanoChatGptContractConfig`] lowers to it. Directly builds the
/// [`NanoChatGpt`] module via [`ModuleInit`].
///
/// This config has a lot of duplicate information.
#[derive(Config, Debug)]
pub struct NanoChatGptStructureConfig {
    /// The language model: the token embedding and its parameter-free RMS
    /// norm; the decoder stack (the blocks, the final norm, and the rotary
    /// embedding, whose `seq_len` is the model's longest sequence); the head,
    /// a projection of its own onto the padded vocabulary, the logits sliced
    /// back to `vocab_size` and soft-capped; and the initial sequence length,
    /// its `kv_cache_pre_size`.
    pub lm: LmDecoderStructureConfig,

    /// Whether the residual stream is rescaled and mixed with the
    /// embedding before each block.
    #[config(default = "false")]
    pub residual_lambdas: bool,

    /// Each layer's value embedding, if it has one.
    #[config(default = "Vec::new()")]
    pub value_embeds: Vec<Option<EmbeddingConfig>>,

    /// The smear's gate width, if the embedding is smeared.
    #[config(default = "None")]
    pub smear_channels: Option<usize>,

    /// Whether the mid-stack residual is backed out before the final norm.
    #[config(default = "false")]
    pub backout: bool,
}

impl NanoChatGptMeta for NanoChatGptStructureConfig {
    fn n_embed(&self) -> usize {
        self.lm.embedding.d_model
    }

    fn n_head(&self) -> usize {
        self.lm.stack.layers[0].attn.attention().n_head()
    }

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

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

    fn init_seq_len(&self) -> usize {
        self.lm.kv_cache_pre_size
    }

    fn max_seq_len(&self) -> usize {
        self.lm.stack.rotary.seq_len()
    }

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

    fn vocab_size(&self) -> usize {
        self.lm.head.n_vocab()
    }
}

impl ModuleInit<NanoChatGpt> for NanoChatGptStructureConfig {
    fn try_init(
        &self,
        device: &Device,
    ) -> BunsenResult<NanoChatGpt> {
        let n_layer = self.lm.stack.layers.len();
        if !self.value_embeds.is_empty() && self.value_embeds.len() != n_layer {
            return Err(BunsenError::illegal(format!(
                "value_embeds has {} entries for {n_layer} layers",
                self.value_embeds.len()
            )));
        }
        // Upstream's initial values: a stronger residual and more of the
        // embedding at early layers.
        let ramp = |start: f64, drop: f64| {
            let values: Vec<f32> = (0..n_layer)
                .map(|i| (start - drop * i as f64 / (n_layer.max(2) - 1) as f64) as f32)
                .collect();
            Param::from_tensor(Tensor::<1>::from_floats(values.as_slice(), device))
        };
        let scalar = |v: f32| Param::from_tensor(Tensor::<1>::from_floats([v], device));
        Ok(NanoChatGpt {
            lm: self.lm.try_init(device)?,
            r_emb: self.lm.stack.rotary.try_init(device)?,
            resid_lambdas: self.residual_lambdas.then(|| ramp(1.15, 0.10)),
            x0_lambdas: self.residual_lambdas.then(|| ramp(0.20, 0.15)),
            value_embeds: self
                .value_embeds
                .iter()
                .map(|c| c.as_ref().map(|c| c.init(device)))
                .collect(),
            smear_gate: self.smear_channels.map(|channels| {
                LinearConfig::new(channels, 1)
                    .with_bias(false)
                    .with_initializer(Initializer::Uniform {
                        min: 0.0,
                        max: 0.02,
                    })
                    .init(device)
            }),
            smear_lambda: self.smear_channels.map(|_| scalar(0.0)),
            backout_lambda: self.backout.then(|| scalar(0.2)),
        })
    }
}

/// nanoChat GPT language model.
///
/// A decoder-only transformer, an [`LmDecoderModel`]: token embedding,
/// normalized by a parameter-free RMS norm as upstream's is, a
/// [`DecoderStack`](crate::blocks::transformers::decoders::stack::DecoderStack)
/// of causal decoder blocks and a final normalization, and a linear head,
/// not tied to the embedding, producing softcapped vocabulary logits. The
/// normalized embedding starts the residual stream, and each block
/// adds its attention and MLP updates to it.
///
/// Upstream's 2026 additions, each present only when its config option is
/// on: the smear (the previous position's embedding mixed into each
/// position's), per-layer residual and embedding lambdas before each block,
/// value embeddings on every other layer, the mid-stack backout, a
/// query/key gain, sliding windows, and a padded vocabulary.
///
/// Its forward is its own, the 2026 additions around the stack's
/// ([`DecoderStackSides`]), so it is not an
/// [`LmDecoderWrapper`](crate::blocks::transformers::models::language_decoder::LmDecoderWrapper):
/// no blanket forward or decode skips them. Incremental decoding takes a
/// [`KVCache`] the caller holds, from
/// [`new_kv_cache`](KVCacheModel::new_kv_cache) (it implements
/// [`KVCacheModel`], as its configs do).
///
/// Built by [`NanoChatGptContractConfig`] (high-level) or
/// [`NanoChatGptStructureConfig`].
#[derive(Module, Debug)]
pub struct NanoChatGpt {
    /// The language model: the embedding, the blocks and the final norm,
    /// and the head (its own projection, sliced and soft-capped); its
    /// `kv_cache_pre_size` the initial sequence length.
    lm: LmDecoderModel,
    /// The rotary table, covering the longest sequence.
    r_emb: RotaryEmbedding,

    /// `[n_layer]`: the residual stream's scale before each block.
    resid_lambdas: Option<Param<Tensor<1>>>,
    /// `[n_layer]`: the embedding's weight mixed in before each block.
    x0_lambdas: Option<Param<Tensor<1>>>,
    /// Each layer's value embedding, `[vocab, n_kv_head * head_dim]`, if it
    /// has one.
    value_embeds: Vec<Option<Embedding>>,
    /// The smear's gate, from the embedding's first channels to one scalar.
    smear_gate: Option<Linear>,
    /// `[1]`: the smear's strength.
    smear_lambda: Option<Param<Tensor<1>>>,
    /// `[1]`: how much of the mid-stack residual is backed out.
    backout_lambda: Option<Param<Tensor<1>>>,
}

impl NanoChatGptMeta for NanoChatGpt {
    fn n_embed(&self) -> usize {
        self.lm.embedding.d_model()
    }

    fn n_head(&self) -> usize {
        self.lm.stack.layers[0].attn.branch.attention().n_head()
    }

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

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

    fn init_seq_len(&self) -> usize {
        self.lm.kv_cache_pre_size()
    }

    fn max_seq_len(&self) -> usize {
        self.r_emb.seq_len()
    }

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

    fn vocab_size(&self) -> usize {
        self.lm.head.n_vocab()
    }
}

impl NanoChatGpt {
    /// The float dtype the model's weights are held, and computed, in: its
    /// embedding's (without initializing a lazy parameter).
    pub fn float_dtype(&self) -> burn::tensor::DType {
        self.lm.float_dtype()
    }

    /// Sets a smeared model's smear strength: tests of the smear set it away
    /// from its neutral initial value.
    #[cfg(test)]
    pub(crate) fn set_smear_lambda_for_tests(
        &mut self,
        lambda: f32,
        device: &Device,
    ) {
        self.smear_lambda = Some(Param::from_tensor(Tensor::from_floats([lambda], device)));
    }

    /// Whether the embedding is smeared: then a cached step past the first
    /// position needs the token before it
    /// ([`forward_after`](Self::forward_after)).
    pub fn is_smeared(&self) -> bool {
        self.smear_gate.is_some()
    }

    /// Forward Pass.
    ///
    /// # Arguments
    /// - `idx`: a `[B, T]` tensor of token ids.
    /// - `kv_cache`: the decode's cache, or `None` to run the sequence on its
    ///   own. With a cache, the step's positions start at the cache's position,
    ///   and every layer appends its keys and values.
    ///
    /// # Returns
    /// The `[B, T, vocab_size]` logits, softcapped:
    /// `softcap * tanh(logits / softcap)`.
    ///
    /// # Panics
    /// When the step runs past the rotary table: when the cache's position
    /// (0 without a cache) plus `T` exceeds `max_seq_len`. For a smeared
    /// model, when the cache's position is past 0: that needs
    /// [`forward_after`](Self::forward_after).
    pub fn forward(
        &self,
        idx: Tensor<2, Int>,
        kv_cache: &mut Option<&mut KVCache>,
    ) -> Tensor<3> {
        self.forward_after(idx, None, kv_cache)
    }

    /// Forward Pass, continuing after `prev`: the tokens just before `idx`,
    /// which a smeared model mixes into `idx`'s first position.
    ///
    /// # Arguments
    /// - `idx`: a `[B, T]` tensor of token ids.
    /// - `prev`: the `[B, 1]` token before each row's `idx`, or `None` at the
    ///   start of the sequence. Only a smeared model reads it.
    /// - `kv_cache`: the decode's cache, as for [`forward`](Self::forward).
    ///
    /// # Returns
    /// The `[B, T, vocab_size]` softcapped logits.
    ///
    /// # Panics
    /// As [`forward`](Self::forward); and for a smeared model, when the
    /// cache's position is past 0 and `prev` is `None`.
    pub fn forward_after(
        &self,
        idx: Tensor<2, Int>,
        prev: Option<Tensor<2, Int>>,
        kv_cache: &mut Option<&mut KVCache>,
    ) -> Tensor<3> {
        self.logits(self.hidden_after(idx, prev, kv_cache))
    }

    /// The head's input: the residual stream after the last block (the
    /// backout taken), normalized. As
    /// [`forward_after`](Self::forward_after) without the head.
    ///
    /// # Arguments
    /// As [`forward_after`](Self::forward_after).
    ///
    /// # Returns
    /// The `[B, T, D]` hidden states.
    ///
    /// # Panics
    /// As [`forward_after`](Self::forward_after).
    pub fn hidden_after(
        &self,
        idx: Tensor<2, Int>,
        prev: Option<Tensor<2, Int>>,
        kv_cache: &mut Option<&mut KVCache>,
    ) -> Tensor<3> {
        let [b, t] = unpack_shape_contract!(["B", "T"], &idx.dims());

        let t0 = match kv_cache {
            Some(kv_cache) => kv_cache.pos(),
            None => 0,
        };
        assert!(
            t0 + t <= self.r_emb.seq_len(),
            "Sequence position grew beyond the rotary embeddings table: {t0} + {t} > {}",
            self.r_emb.seq_len()
        );

        // As upstream (`x = norm(wte(idx))`): a parameter-free norm, so the
        // residual stream starts normalized.
        let mut x = self.lm.embedding.forward(idx.clone());

        if let (Some(gate), Some(lambda)) = (&self.smear_gate, &self.smear_lambda) {
            x = self.smear(x, prev, t0, gate, lambda);
        }

        let sides = DecoderStackSides {
            value_embeds: self
                .value_embeds
                .iter()
                .map(|ve| ve.as_ref().map(|ve| ve.forward(idx.clone())))
                .collect(),
            mix: DecoderStackResidualMix {
                resid_x0: self
                    .resid_lambdas
                    .as_ref()
                    .zip(self.x0_lambdas.as_ref())
                    .map(|(resid, x0)| (resid.val(), x0.val())),
                backout: self
                    .backout_lambda
                    .as_ref()
                    .map(|lambda| (self.lm.stack.layers.len() / 2, lambda.val())),
            },
            ..Default::default()
        };
        let hidden = self.lm.stack.forward_with(
            x,
            &RotarySet::from(self.r_emb.clone()),
            kv_cache.as_deref_mut(),
            sides,
        );
        assert_shape_contract_periodically!(
            ["B", "T", "D"],
            &hidden.dims(),
            &[("B", b), ("T", t), ("D", self.n_embed())]
        );
        hidden
    }

    /// The softcapped logits of `hidden`, the head's input
    /// ([`hidden_after`](Self::hidden_after)): the head, sliced to
    /// `vocab_size`, then `softcap * tanh(logits / softcap)`.
    ///
    /// # Arguments
    /// - `hidden`: `[B, T, D]` hidden states.
    ///
    /// # Returns
    /// The `[B, T, vocab_size]` logits.
    pub fn logits(
        &self,
        hidden: Tensor<3>,
    ) -> Tensor<3> {
        let [b, t] = unpack_shape_contract!(
            ["B", "T", "D"],
            &hidden.dims(),
            &["B", "T"],
            &[("D", self.n_embed())]
        );
        let logits = self.lm.head.forward(hidden, &self.lm.embedding.weight);

        assert_shape_contract_periodically!(
            ["B", "T", "V"],
            &logits.dims(),
            &[("B", b), ("T", t), ("V", self.vocab_size())]
        );
        logits
    }

    /// The smear: each position adds the one before it, gated by
    /// `lambda * sigmoid(gate(x[.., :channels]))`, the gate read from the
    /// position itself. The sequence's first position has nothing before it;
    /// a chunk past it takes its first position's predecessor from `prev`.
    fn smear(
        &self,
        x: Tensor<3>,
        prev: Option<Tensor<2, Int>>,
        t0: usize,
        gate: &Linear,
        lambda: &Param<Tensor<1>>,
    ) -> Tensor<3> {
        let [b, t, d] = x.dims();
        let channels = gate.weight.dims()[0];
        let g = sigmoid(gate.forward(x.clone().slice(s![.., .., ..channels])))
            * lambda.val().unsqueeze::<3>();
        let before = match (t0, prev) {
            (_, Some(prev)) => {
                let p = self.lm.embedding.forward(prev);
                Some(Tensor::cat(vec![p, x.clone().slice(s![.., ..t - 1])], 1))
            }
            (0, None) => None,
            (_, None) => panic!(
                "a smeared model continuing a decode at position {t0} needs the token before it"
            ),
        };
        match before {
            Some(before) => x + g * before,
            None if t == 1 => x,
            None => {
                let rest = x.clone().slice(s![.., 1..])
                    + g.slice(s![.., 1..]) * x.clone().slice(s![.., ..t - 1]);
                let out = Tensor::cat(vec![x.slice(s![.., ..1]), rest], 1);
                debug_assert_eq!(out.dims(), [b, t, d]);
                out
            }
        }
    }

    /// Calculates the estimated FLOPs per token for the model.
    ///
    /// Ref: <https://arxiv.org/abs/2204.02311>
    pub fn estimate_flops_per_token(&self) -> usize {
        let nparams = self.num_params();
        let nparams_embedding = self.lm.embedding.num_params()
            + self
                .value_embeds
                .iter()
                .flatten()
                .map(|ve| ve.num_params())
                .sum::<usize>();
        let nparams = nparams - nparams_embedding;

        let l = self.n_layer();
        let h = self.n_head();
        let q = self.head_dim();
        let t = self.init_seq_len();

        6 * nparams + 12 * l * h * q * t
    }
}

/// The call API that says nothing of the forward: the token embedding alone
/// (the smear is the forward's), the head, the rotary tables and the dtype.
/// A [`NanoChatGpt`]'s forward is its own
/// ([`hidden_after`](NanoChatGpt::hidden_after)), so it is not a
/// [`LmPlainStackOps`](crate::blocks::transformers::models::language_decoder::LmPlainStackOps).
impl crate::blocks::transformers::models::language_decoder::LmDecoderOps for NanoChatGpt {
    fn float_dtype(&self) -> burn::tensor::DType {
        NanoChatGpt::float_dtype(self)
    }

    fn rotary(
        &self,
        seq_len: usize,
        device: &Device,
    ) -> RotarySet {
        self.lm.rotary(seq_len, device)
    }

    fn embed(
        &self,
        tokens: Tensor<2, Int>,
    ) -> Tensor<3> {
        self.lm.embed(tokens)
    }

    fn logits(
        &self,
        hidden: Tensor<3>,
    ) -> Tensor<3> {
        NanoChatGpt::logits(self, hidden)
    }
}

/// Its language model's meta: `n_vocab` is the padded table's rows, and
/// `n_logits` its head's, [`vocab_size`](NanoChatGptMeta::vocab_size).
impl crate::blocks::transformers::models::language_decoder::LmDecoderMeta for NanoChatGpt {
    fn n_vocab(&self) -> usize {
        self.lm.n_vocab()
    }

    fn n_logits(&self) -> usize {
        self.lm.n_logits()
    }

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

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

    fn n_kv_heads(&self) -> usize {
        self.lm.n_kv_heads()
    }

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

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

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

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

    #[test]
    fn test_gpt_config() {
        let cfg = NanoChatGptContractConfig::new();
        assert_eq!(cfg.init_seq_len, 1024);
        assert_eq!(cfg.vocab_size, 50304);
        assert_eq!(cfg.n_layer, 12);
        assert_eq!(cfg.n_head, 6);
        assert_eq!(cfg.n_kv_head, 6);
        assert_eq!(cfg.n_embed, 768);
        assert_eq!(cfg.expansion_factor, 4);

        assert_eq!(cfg.n_embed(), 768);
    }

    /// The defaults are upstream's 2025 model: an unbiased head, rotary base
    /// 10000, an explicit norm epsilon, and none of the 2026 options.
    #[test]
    fn test_defaults_are_upstream_2025() {
        let device = cpu_device();
        let gpt: NanoChatGpt = NanoChatGptContractConfig::new()
            .with_vocab_size(64)
            .with_n_layer(2)
            .with_n_head(2)
            .with_n_kv_head(2)
            .with_n_embed(16)
            .with_init_seq_len(8)
            .init(&device);
        assert!(gpt.lm.head.proj.as_ref().is_some_and(|p| p.bias.is_none()));
        assert_eq!(gpt.lm.embedding.norm_eps, Some(1e-6));
        assert!(gpt.resid_lambdas.is_none() && gpt.x0_lambdas.is_none());
        assert!(gpt.value_embeds.iter().all(Option::is_none));
        assert!(!gpt.is_smeared() && gpt.backout_lambda.is_none());
        assert!(gpt.lm.stack.layers.iter().all(|b| {
            b.attn.branch.attention().score_scale.is_none()
                && b.attn.branch.attention().sliding_window.is_none()
                && b.attn.branch.attention().value_gate.is_none()
        }));

        let structure = NanoChatGptContractConfig::new().to_structure();
        assert_eq!(structure.lm.stack.rotary.base, 10000);
        assert_eq!(
            structure.lm.stack.rotary.table_dtype,
            Some(FloatDType::BF16)
        );
        assert_eq!(structure.vocab_size(), 50304);
    }

    /// Upstream's `has_ve`: every other layer, the last always.
    #[test]
    fn test_has_value_embed() {
        let layers = |n: usize| {
            (0..n)
                .filter(|&i| has_value_embed(i, n))
                .collect::<Vec<_>>()
        };
        assert_eq!(layers(18), vec![1, 3, 5, 7, 9, 11, 13, 15, 17]);
        assert_eq!(layers(5), vec![0, 2, 4]);
        assert_eq!(layers(1), vec![0]);
    }

    /// Upstream's `_compute_window_sizes`: the pattern tiled, the last layer
    /// long, the short window a quarter of the long one rounded up to 128;
    /// `w` positions back is `w + 1` keys.
    #[test]
    fn test_window_pattern_windows() {
        assert_eq!(
            window_pattern_windows("SSSL", 2048, 6).unwrap(),
            vec![513, 513, 513, 2049, 513, 2049]
        );
        assert_eq!(window_pattern_windows("l", 2048, 3).unwrap(), vec![2049; 3]);
        assert_eq!(window_pattern_windows("S", 4, 2).unwrap(), vec![129, 5]);
        assert!(window_pattern_windows("", 2048, 2).is_err());
        assert!(window_pattern_windows("SXL", 2048, 2).is_err());
    }

    /// `with_upstream_2026` turns on every 2026 option, with upstream's
    /// values, and the structure builds the parts each needs.
    #[test]
    fn test_upstream_2026_structure() {
        let policy = NanoChatGptContractConfig::new()
            .with_vocab_size(60)
            .with_n_layer(3)
            .with_n_head(2)
            .with_n_kv_head(1)
            .with_n_embed(32)
            .with_init_seq_len(4)
            .with_upstream_2026("SL");
        assert_eq!(policy.padded_vocab_size(), 64);
        let structure = policy.to_structure();
        assert_eq!(structure.lm.stack.rotary.base, 100000);
        assert_eq!(structure.lm.stack.rotary.table_dtype, None);
        assert_eq!(structure.lm.embedding.n_vocab, 64);
        assert_eq!(structure.vocab_size(), 60);
        assert_eq!(
            structure
                .lm
                .stack
                .layers
                .iter()
                .map(|b| b.attn.attention().sliding_window)
                .collect::<Vec<_>>(),
            vec![Some(129), Some(5), Some(5)]
        );
        assert_eq!(
            structure
                .value_embeds
                .iter()
                .map(|ve| ve.as_ref().map(|c| (c.n_embedding, c.d_model)))
                .collect::<Vec<_>>(),
            vec![Some((64, 16)), None, Some((64, 16))]
        );
        assert!(
            structure
                .lm
                .stack
                .layers
                .iter()
                .all(|b| b.attn.attention().score_scale
                    == Some(1.2 * 1.2 / (structure.head_dim() as f64).sqrt()))
        );
        assert_eq!(structure.smear_channels, Some(24));
        assert!(structure.residual_lambdas && structure.backout);
    }

    /// A tiny 2026 model whose options all bind: its smear, value gates and
    /// backout set away from their (neutral or near-neutral) initial values,
    /// and windows shorter than the sequences it is run on.
    fn tiny_2026(device: &Device) -> NanoChatGpt {
        let mut gpt: NanoChatGpt = NanoChatGptContractConfig::new()
            .with_vocab_size(30)
            .with_n_layer(3)
            .with_n_head(4)
            .with_n_kv_head(2)
            .with_n_embed(32)
            .with_init_seq_len(4)
            .with_max_seq_len_factor(4)
            .with_upstream_2026("SL")
            .init(device);
        gpt.smear_lambda = Some(Param::from_tensor(Tensor::from_floats([0.7], device)));
        gpt.backout_lambda = Some(Param::from_tensor(Tensor::from_floats([0.3], device)));
        for block in gpt.lm.stack.layers.iter_mut() {
            if let Some(gate) = block.attn.branch.attention_mut().value_gate.as_mut() {
                gate.weight = Param::from_tensor(seeded_tensor(
                    7,
                    gate.weight.dims(),
                    Distribution::Normal(0.0, 1.0),
                    device,
                ));
            }
        }
        if let Some(gate) = gpt.smear_gate.as_mut() {
            gate.weight = Param::from_tensor(seeded_tensor(
                11,
                gate.weight.dims(),
                Distribution::Normal(0.0, 1.0),
                device,
            ));
        }
        gpt
    }

    /// A cached decode of a 2026 model, one token at a time after a prefill,
    /// each step given the token before it, computes the logits the whole
    /// sequence does: the smear, the value embeddings and the windows carry
    /// across steps.
    #[test]
    #[serial]
    fn test_upstream_2026_cached_decode_matches_full_pass() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        let gpt = tiny_2026(&device);
        assert!(gpt.is_smeared());
        let ids: Tensor<2, Int> =
            Tensor::from_data([[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8]], &device);
        let n = ids.dims()[1];
        let full = gpt.forward(ids.clone(), &mut None);
        assert_eq!(full.dims(), [1, n, 30]);

        let prefill = 3;
        let mut cache = gpt.new_kv_cache(1);
        let mut steps =
            vec![gpt.forward(ids.clone().slice(s![.., ..prefill]), &mut Some(&mut cache))];
        for i in prefill..n {
            steps.push(gpt.forward_after(
                ids.clone().slice(s![.., i..i + 1]),
                Some(ids.clone().slice(s![.., i - 1..i])),
                &mut Some(&mut cache),
            ));
        }
        let cached = Tensor::cat(steps, 1);
        cached
            .into_data()
            .assert_approx_eq::<f32>(&full.into_data(), Tolerance::rel_abs(1e-3, 1e-4));
    }

    /// A 2026 model, every part on, saved as a `.bpk` and loaded into a
    /// fresh one of the same config, computes the same logits: the record
    /// follows the module tree (`stack.layers.{i}`, `stack.norm`), as
    /// `examples/train-chat` writes it.
    #[test]
    #[serial]
    fn test_bpk_round_trip() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let gpt = tiny_2026(&device);
        let ids: Tensor<2, Int> = Tensor::from_data([[3, 1, 4, 1, 5, 9]], &device);
        let expected = gpt.forward(ids.clone(), &mut None);

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("model.bpk");
        gpt.save_file(&path).unwrap();
        device.seed(99);
        let fresh = tiny_2026(&device);
        assert!(
            !fresh
                .forward(ids.clone(), &mut None)
                .all_close(expected.clone(), None, None),
            "a fresh model computes otherwise"
        );
        let loaded = fresh.load_file(&path);
        loaded
            .forward(ids, &mut None)
            .into_data()
            .assert_approx_eq::<f32>(&expected.into_data(), Tolerance::rel_abs(1e-5, 1e-6));
    }

    /// A chunk of several tokens after a cached prefix, given the token
    /// before it, computes what the whole sequence does too.
    #[test]
    #[serial]
    fn test_upstream_2026_cached_chunk_matches_full_pass() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        let gpt = tiny_2026(&device);
        let ids: Tensor<2, Int> = Tensor::from_data([[7, 2, 9, 4, 4, 1, 0, 3]], &device);
        let full = gpt.forward(ids.clone(), &mut None);

        let mut cache = gpt.new_kv_cache(1);
        let head = gpt.forward(ids.clone().slice(s![.., ..2]), &mut Some(&mut cache));
        let tail = gpt.forward_after(
            ids.clone().slice(s![.., 2..]),
            Some(ids.clone().slice(s![.., 1..2])),
            &mut Some(&mut cache),
        );
        Tensor::cat(vec![head, tail], 1)
            .into_data()
            .assert_approx_eq::<f32>(&full.into_data(), Tolerance::rel_abs(1e-3, 1e-4));
    }

    /// A smeared model continuing a decode without the token before the
    /// step would silently drop the smear: it panics instead.
    #[test]
    #[serial]
    #[should_panic(expected = "needs the token before it")]
    fn test_smeared_continuation_needs_the_previous_token() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        let gpt = tiny_2026(&device);
        let mut cache = gpt.new_kv_cache(1);
        gpt.forward(Tensor::zeros([1, 2], &device), &mut Some(&mut cache));
        gpt.forward(Tensor::zeros([1, 1], &device), &mut Some(&mut cache));
    }

    /// Each 2026 option changes the logits: none of them is dead code.
    #[test]
    #[serial]
    fn test_upstream_2026_options_bind() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        let ids: Tensor<2, Int> = Tensor::from_data([[3, 1, 4, 1, 5, 9, 2, 6, 5, 3]], &device);
        let gpt = tiny_2026(&device);
        let base = gpt.forward(ids.clone(), &mut None);

        let differs = |other: &NanoChatGpt, what: &str| {
            let diff = (other.forward(ids.clone(), &mut None) - base.clone())
                .abs()
                .max()
                .into_scalar::<f32>();
            assert!(diff > 1e-4, "{what} changed nothing ({diff})");
        };
        let mut g = tiny_2026(&device);
        g.smear_lambda = Some(Param::from_tensor(Tensor::from_floats([0.0], &device)));
        differs(&g, "the smear");
        let mut g = tiny_2026(&device);
        g.backout_lambda = Some(Param::from_tensor(Tensor::from_floats([0.0], &device)));
        differs(&g, "the backout");
        let mut g = tiny_2026(&device);
        g.x0_lambdas = Some(Param::from_tensor(Tensor::zeros([3], &device)));
        differs(&g, "the x0 lambdas");
        let mut g = tiny_2026(&device);
        for block in g.lm.stack.layers.iter_mut() {
            block.attn.branch.attention_mut().score_scale = None;
        }
        differs(&g, "the qk gain");
        let mut g = tiny_2026(&device);
        for block in g.lm.stack.layers.iter_mut() {
            block.attn.branch.attention_mut().sliding_window = None;
        }
        differs(&g, "the windows");
        let mut g = tiny_2026(&device);
        for block in g.lm.stack.layers.iter_mut() {
            if let Some(gate) = block.attn.branch.attention_mut().value_gate.as_mut() {
                gate.weight = Param::from_tensor(gate.weight.val().zeros_like().sub_scalar(30.0));
            }
        }
        differs(&g, "the value embeddings");
    }

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

        let batch_size = 1;
        let seq_len = 100;
        let n_layer = 4;
        let n_embed = 36;

        let vocab_size = 1000;

        let cfg = NanoChatGptContractConfig::new()
            .with_vocab_size(vocab_size)
            .with_n_embed(n_embed)
            .with_n_layer(n_layer);
        let gpt: NanoChatGpt = cfg.init(&device);

        let mut kv_cache = gpt.new_kv_cache(batch_size);

        let input_tokens = Tensor::<2>::random(
            [batch_size, seq_len],
            Distribution::Uniform(0.0, vocab_size as f64),
            &device,
        )
        .int();

        let logits = gpt.forward(input_tokens, &mut Some(&mut kv_cache));
        assert_shape_contract!(
            ["B", "T", "V"],
            &logits.dims(),
            &[("B", batch_size), ("T", seq_len), ("V", vocab_size)]
        );
        assert_eq!(gpt.n_embed(), n_embed);
    }

    /// Asserts that `a` and `b` answer every [`NanoChatGptMeta`] method alike.
    fn assert_meta_agrees(
        a: &impl NanoChatGptMeta,
        b: &impl NanoChatGptMeta,
    ) {
        assert_eq!(a.n_embed(), b.n_embed());
        assert_eq!(a.n_head(), b.n_head());
        assert_eq!(a.n_kv_head(), b.n_kv_head());
        assert_eq!(a.head_dim(), b.head_dim());
        assert_eq!(a.init_seq_len(), b.init_seq_len());
        assert_eq!(a.max_seq_len(), b.max_seq_len());
        assert_eq!(a.n_layer(), b.n_layer());
    }

    /// The policy builds the same `NanoChatGpt` through its structure as
    /// through the blanket `init`, and the module reads back the geometry
    /// its configs declare.
    #[test]
    #[serial]
    fn test_policy_pathways_agree() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        let policy = NanoChatGptContractConfig::new()
            .with_init_seq_len(16)
            .with_max_seq_len_factor(2)
            .with_vocab_size(64)
            .with_n_layer(2)
            .with_n_head(4)
            .with_n_kv_head(2)
            .with_n_embed(32);

        let structure = policy.to_structure();
        assert_meta_agrees(&policy, &structure);
        assert_eq!(structure.max_seq_len(), 32);
        assert_eq!(structure.head_dim(), 8);

        let lowered: NanoChatGpt = structure.init(&device);
        let direct: NanoChatGpt = policy.init(&device);

        assert_meta_agrees(&direct, &lowered);
        assert_meta_agrees(&structure, &lowered);
        assert_eq!(lowered.n_embed(), 32);
    }

    /// A tiny model whose rotary table, `max_seq_len`, is 8 positions.
    fn tiny_gpt(device: &Device) -> NanoChatGpt {
        let gpt: NanoChatGpt = NanoChatGptContractConfig::new()
            .with_init_seq_len(4)
            .with_max_seq_len_factor(2)
            .with_vocab_size(16)
            .with_n_layer(2)
            .with_n_head(2)
            .with_n_kv_head(2)
            .with_n_embed(16)
            .init(device);
        assert_eq!(gpt.max_seq_len(), 8);
        gpt
    }

    /// A cached decode may fill the rotary table exactly.
    #[test]
    #[serial]
    fn test_cached_decode_fills_rotary_table() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        let gpt = tiny_gpt(&device);
        let mut cache = gpt.new_kv_cache(1);
        gpt.forward(Tensor::zeros([1, 7], &device), &mut Some(&mut cache));
        let logits = gpt.forward(Tensor::zeros([1, 1], &device), &mut Some(&mut cache));
        assert_eq!(logits.dims(), [1, 1, 16]);
        assert_eq!(cache.pos(), 8);
    }

    /// A cached decode that runs past the rotary table fails at the guard,
    /// which counts the cache's position plus the step's length.
    #[test]
    #[serial]
    #[should_panic(expected = "beyond the rotary embeddings table: 8 + 1 > 8")]
    fn test_cached_decode_past_rotary_table_panics() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        let gpt = tiny_gpt(&device);
        let mut cache = gpt.new_kv_cache(1);
        gpt.forward(Tensor::zeros([1, 8], &device), &mut Some(&mut cache));
        gpt.forward(Tensor::zeros([1, 1], &device), &mut Some(&mut cache));
    }

    /// Upstream normalizes the embedding before the first block
    /// (`x = norm(wte(idx))`), so the first block sees the same input, and the
    /// logits are the same, whatever the embedding table's scale. Fed a known
    /// embedding table and the same table times 8, the model must agree.
    #[test]
    #[serial]
    fn test_forward_normalizes_the_embedding() {
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);

        let mut gpt = tiny_gpt(&device);
        let table: Tensor<2> = Tensor::random([16, 16], Distribution::Normal(0.0, 1.0), &device);
        let tokens: Tensor<2, Int> = Tensor::from_data([[3, 1, 4, 1, 5, 9]], &device);

        gpt.lm.embedding.weight = Param::from_tensor(table.clone());
        let logits = gpt.forward(tokens.clone(), &mut None);

        gpt.lm.embedding.weight = Param::from_tensor(table.mul_scalar(8.0));
        let scaled = gpt.forward(tokens, &mut None);

        scaled
            .into_data()
            .assert_approx_eq::<f32>(&logits.into_data(), Tolerance::rel_abs(1e-3, 1e-4));
    }

    /// The forward-free call API is the model's own: the head over its hidden
    /// states gives its forward's logits, and the embedding is the table's,
    /// unsmeared.
    #[test]
    #[serial]
    fn test_lm_decoder_ops() {
        use crate::blocks::transformers::models::language_decoder::{
            LmDecoderMeta,
            LmDecoderOps,
        };
        let device = performance_device();
        let _memory = DeviceMemoryGuard::new(&device);
        let gpt = tiny_2026(&device);
        let ids: Tensor<2, Int> = Tensor::from_data([[3, 1, 4, 1, 5]], &device);
        let hidden = gpt.hidden_after(ids.clone(), None, &mut None);
        crate::support::testing::assert_tensors_close(
            &LmDecoderOps::logits(&gpt, hidden),
            &gpt.forward(ids.clone(), &mut None),
            burn::tensor::Tolerance::default(),
        );
        crate::support::testing::assert_tensors_close(
            &LmDecoderOps::embed(&gpt, ids.clone()),
            &gpt.lm.embedding.forward(ids),
            burn::tensor::Tolerance::default(),
        );
        assert_eq!(LmDecoderMeta::n_vocab(&gpt), 64, "the padded table");
        assert_eq!(LmDecoderMeta::n_logits(&gpt), 30, "the head's slice");
        assert_eq!(gpt.vocab_size(), 30);
        assert_eq!(
            LmDecoderOps::rotary(&gpt, 5, &device).tables[0].cos.dims()[1],
            5
        );
    }
}