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
//! Loading upstream nanochat's own checkpoints into a [`NanoChatGpt`].
//!
//! Upstream's checkpoint manager writes a step as two files: the model's
//! state dict, `model_<step>.pt` (`torch.save`), and its `meta_<step>.json`,
//! whose `model_config` is the model's geometry. [`NanoChatMeta`] reads the
//! meta, [`NanoChatMeta::generation`] tells from the state dict's names which
//! of upstream's models it is, [`NanoChatMeta::gpt_config`] builds the config
//! for both, and [`load_pt_tensors`] loads the state dict through [`pt_rekey`].

use std::path::Path;

use burn::{
    store::{
        ModuleSnapshot,
        PathFilter,
        bridge,
        burn_pack::Tensor as PackTensor,
    },
    tensor::{
        Device,
        FloatDType,
        TensorData,
    },
};
use serde::Deserialize;

use super::{
    NanoChatGpt,
    NanoChatGptContractConfig,
};
use crate::{
    burner::module::{
        ModuleInit,
        Rekey,
    },
    data::formats::{
        NamedTensorsApplied,
        read_pytorch_tensors,
        stored_float_dtype,
    },
    errors::{
        BunsenError,
        BunsenResult,
        ResultContext,
        sys_at,
    },
};

/// A nanochat checkpoint's `meta_<step>.json`: the parts bunsen reads. The
/// rest (the training run's settings, its losses, a chat template some
/// uploads add) is ignored.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct NanoChatMeta {
    /// The training step the checkpoint is of, when the meta says.
    #[serde(default)]
    pub step: Option<u64>,

    /// The model's geometry, as upstream's `GPTConfig`.
    pub model_config: NanoChatModelConfig,
}

/// Upstream's `GPTConfig`, as a checkpoint's meta writes it: upstream's
/// names.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct NanoChatModelConfig {
    /// The training context, in tokens; the rotary table is ten times it.
    pub sequence_len: usize,

    /// The vocabulary size, before any padding.
    pub vocab_size: usize,

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

    /// The number of query heads.
    pub n_head: usize,

    /// The number of key/value heads.
    pub n_kv_head: usize,

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

    /// The 2026 model's sliding-window pattern (`"SSSL"`, `"L"`); absent
    /// in the 2025 model's meta.
    #[serde(default)]
    pub window_pattern: Option<String>,
}

impl NanoChatMeta {
    /// Parses a `meta_<step>.json`.
    ///
    /// # Errors
    /// [`InvalidResource`](crate::errors::BunsenErrorKind::InvalidResource)
    /// when it is not a nanochat meta.
    pub fn from_json(json: &str) -> BunsenResult<Self> {
        serde_json::from_str(json).map_err(|e| {
            BunsenError::invalid_resource("not a nanochat checkpoint meta").with_cause(e)
        })
    }

    /// Reads and parses the `meta_<step>.json` at `path`.
    ///
    /// # Errors
    /// As [`sys_at`] when the file cannot be read; as
    /// [`from_json`](Self::from_json) when it is not a nanochat meta.
    pub fn from_file(path: &Path) -> BunsenResult<Self> {
        let json = std::fs::read_to_string(path).map_err(sys_at("read", path))?;
        Self::from_json(&json).with_context(|| path.display().to_string())
    }
}

/// Which of upstream's models a checkpoint is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NanoChatGeneration {
    /// Upstream's model as of late 2025 (`karpathy/nanochat` at
    /// `a088b7a6`): the policy's defaults.
    Upstream2025,

    /// Upstream's 2026 model (`a3ca42a6`): the 2025 one with
    /// [`with_upstream_2026`](NanoChatGptContractConfig::with_upstream_2026).
    Upstream2026,
}

/// The state-dict names only upstream's 2026 model has: one per 2026 part
/// that carries a parameter.
const UPSTREAM_2026_MARKERS: [&str; 5] = [
    "resid_lambdas",
    "x0_lambdas",
    "smear_gate.weight",
    "smear_lambda",
    "backout_lambda",
];

impl NanoChatMeta {
    /// Which of upstream's models the checkpoint whose state dict holds `names`
    /// and whose meta this is: the 2026 one when the state dict has its
    /// parameters and the meta its window pattern, the 2025 one when it has
    /// neither.
    ///
    /// # Errors
    /// [`Unsupported`](crate::errors::BunsenErrorKind::Unsupported) when it has
    /// some of the 2026 parameters and not others, or when the state dict and
    /// the meta disagree: a checkpoint of one of upstream's commits between the
    /// two, which bunsen does not model.
    pub fn generation<S: AsRef<str>>(
        &self,
        names: &[S],
    ) -> BunsenResult<NanoChatGeneration> {
        let has = |name: &str| names.iter().any(|n| n.as_ref() == name);
        let present: Vec<&str> = UPSTREAM_2026_MARKERS
            .iter()
            .copied()
            .filter(|m| has(m))
            .collect();
        let value_embeds = names
            .iter()
            .any(|n| n.as_ref().starts_with("value_embeds."));
        let windowed = self.model_config.window_pattern.is_some();
        match (present.len(), value_embeds, windowed) {
            (0, false, false) => Ok(NanoChatGeneration::Upstream2025),
            (n, true, true) if n == UPSTREAM_2026_MARKERS.len() => {
                Ok(NanoChatGeneration::Upstream2026)
            }
            _ => Err(BunsenError::unsupported(format!(
                "a nanochat checkpoint between upstream's 2025 and 2026 models: it has {} of \
                 {UPSTREAM_2026_MARKERS:?}, {} value embeddings, and {} window pattern",
                if present.is_empty() {
                    "none".to_string()
                } else {
                    format!("{present:?}")
                },
                if value_embeds { "" } else { "no" },
                if windowed { "a" } else { "no" },
            ))),
        }
    }
}

impl NanoChatMeta {
    /// The config of a checkpoint of `generation` whose meta is `meta`: its
    /// geometry, `sequence_len` the initial sequence length (the rotary table
    /// ten times it, as upstream's), and the generation's options.
    pub fn gpt_config(
        &self,
        generation: NanoChatGeneration,
    ) -> NanoChatGptContractConfig {
        let m = &self.model_config;
        let config = NanoChatGptContractConfig::new()
            .with_init_seq_len(m.sequence_len)
            .with_max_seq_len_factor(10)
            .with_vocab_size(m.vocab_size)
            .with_n_layer(m.n_layer)
            .with_n_head(m.n_head)
            .with_n_kv_head(m.n_kv_head)
            .with_n_embed(m.n_embd);
        match generation {
            NanoChatGeneration::Upstream2025 => config,
            NanoChatGeneration::Upstream2026 => {
                config.with_upstream_2026(m.window_pattern.clone().unwrap_or_else(|| "L".into()))
            }
        }
    }
}

/// Upstream's state-dict names onto a [`NanoChatGpt`]'s module paths: the
/// `transformer.` prefix dropped; onto its language model's (`lm.`), the
/// embedding `wte` its `lm.embedding`, the blocks `h.{i}` the stack's
/// `lm.stack.layers.{i}` (the feed-forward's `c_fc` / `c_proj` its
/// `linear1` / `linear2`, the value gate `ve_gate` its `value_gate`), and the
/// head `lm_head` its projection, `lm.head.proj`; everything else
/// (`attn.c_q`, the lambdas, `value_embeds.{i}`, `smear_gate`) bunsen names
/// as upstream does.
///
/// Unlike the wrappers' rekeys, it names the [`NanoChatGpt`]'s paths, not its
/// language model's alone: the 2026 additions sit beside the language model.
pub fn pt_rekey() -> Rekey {
    Rekey::keep_rest()
        .rename("lm_head.", "lm.head.proj.")
        .mount(
            "transformer.",
            "",
            Rekey::keep_rest()
                .rename("wte.", "lm.embedding.")
                .mount_indexed(
                    "h.",
                    "lm.stack.layers.",
                    Rekey::keep_rest()
                        .rename("mlp.c_fc.", "mlp.linear1.")
                        .rename("mlp.c_proj.", "mlp.linear2.")
                        .rename("attn.ve_gate.", "attn.value_gate."),
                ),
        )
}

/// Loads an upstream nanochat state dict (`tensors`, under upstream's names)
/// into `model` by [`pt_rekey`], every floating tensor cast to `dtype`: a
/// bf16 checkpoint loaded at bf16 takes its tensors as they are.
///
/// Upstream's norms carry no learned scale, and bunsen's do: each norm's
/// scale (a [`BunsenNormalization`](crate::blocks::norm::BunsenNormalization)'s
/// `gamma`, found by type) loads as ones, which is upstream's norm exactly,
/// in any dtype. The ones are named by their record paths, which the map's
/// last stage loads them at as they are, ahead of the model's
/// [`canonical_rekey`](crate::burner::module::CanonicalKeys::canonical_rekey).
///
/// # Errors
/// [`Unsupported`](crate::errors::BunsenErrorKind::Unsupported) naming any
/// tensor the model has no parameter for; otherwise as
/// [`Rekey::apply_as`].
pub fn load_pt_tensors(
    model: &mut NanoChatGpt,
    tensors: impl IntoIterator<Item = PackTensor>,
    dtype: FloatDType,
) -> BunsenResult<NamedTensorsApplied> {
    let mut tensors: Vec<PackTensor> = tensors.into_iter().collect();
    let scales: Vec<PackTensor> = model
        .collect(
            Some(PathFilter::new().with_predicate(is_norm_scale)),
            None,
            true,
        )
        .into_iter()
        .map(|t| {
            let n: usize = t.shape.iter().product();
            bridge::from_data(
                TensorData::new(vec![1.0f32; n], t.shape.clone()),
                t.name.clone(),
                None,
            )
        })
        .collect();
    let last = scales
        .iter()
        .fold(Rekey::keep_rest(), |rekey, t| {
            rekey.exact(t.name.clone(), t.name.clone())
        })
        .mount_canonical("", model);
    tensors.extend(scales);
    let rekey = pt_rekey().then(last);
    let applied = rekey.apply_as(model, tensors, Some(dtype.into()))?;
    if !applied.unused.is_empty() {
        return Err(BunsenError::unsupported(format!(
            "a nanochat state dict with tensors the model has no parameter for: {}",
            applied.unused.join(", ")
        )));
    }
    Ok(applied)
}

/// Whether the parameter at `path`, under the module types `containers`
/// (`Struct:NanoChatGpt.…`), is a norm's scale.
fn is_norm_scale(
    path: &str,
    containers: &str,
) -> bool {
    path.ends_with(".gamma")
        && containers
            .split('.')
            .any(|c| c == "Enum:BunsenNormalization")
}

/// An upstream nanochat checkpoint, its `meta_<step>.json` at `meta` and its
/// `model_<step>.pt` at `model`, as a [`NanoChatGpt`] on `device`: its
/// config from the meta and the state dict's names
/// ([`NanoChatMeta::generation`], [`NanoChatMeta::gpt_config`]), built, and
/// loaded ([`load_pt_tensors`]) at the dtype `policy` resolves the state
/// dict's stored dtype to on `device`
/// ([`LoadPolicy::resolve`](crate::data::formats::LoadPolicy::resolve)).
///
/// # Errors
/// As [`NanoChatMeta::from_file`],
/// [`read_pytorch_tensors`], [`NanoChatMeta::generation`],
/// [`LoadPolicy::resolve`](crate::data::formats::LoadPolicy::resolve)
/// and [`load_pt_tensors`]; each names the file it is about.
pub fn load_pt_checkpoint(
    meta: &Path,
    model: &Path,
    device: &Device,
    policy: crate::data::formats::LoadPolicy,
) -> BunsenResult<(NanoChatGpt, NanoChatGeneration)> {
    let meta_data = NanoChatMeta::from_file(meta)?;
    let tensors = read_pytorch_tensors(model)?;
    let names: Vec<&str> = tensors.iter().map(|t| t.name.as_str()).collect();
    let generation = meta_data
        .generation(&names)
        .with_context(|| format!("{} and {}", meta.display(), model.display()))?;
    let stored = stored_float_dtype(&tensors).unwrap_or(FloatDType::F32);
    let dtype = policy
        .resolve(stored, device, |_| true)
        .with_context(|| model.display().to_string())?;
    let mut gpt: NanoChatGpt = meta_data.gpt_config(generation).try_init(device)?;
    load_pt_tensors(&mut gpt, tensors, dtype).with_context(|| model.display().to_string())?;
    Ok((gpt, generation))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::errors::{
        BunsenErrorKind,
        testing::ErrorMatcher,
    };

    fn meta(window: Option<&str>) -> NanoChatMeta {
        NanoChatMeta {
            step: Some(1),
            model_config: NanoChatModelConfig {
                sequence_len: 2048,
                vocab_size: 65536,
                n_layer: 20,
                n_head: 10,
                n_kv_head: 10,
                n_embd: 1280,
                window_pattern: window.map(str::to_string),
            },
        }
    }

    /// The pinned checkpoints' metas parse, the extra keys some uploads add
    /// ignored.
    #[test]
    fn test_meta_from_json() {
        let m = NanoChatMeta::from_json(
            r#"{"step": 650, "val_loss": 1.07, "model_config": {"sequence_len": 2048,
            "vocab_size": 65536, "n_layer": 20, "n_head": 10, "n_kv_head": 10, "n_embd": 1280,
            "bos_token": "<|bos|>", "chat_template": "..."}}"#,
        )
        .unwrap();
        assert_eq!(m.step, Some(650));
        assert_eq!(
            m,
            NanoChatMeta {
                step: Some(650),
                ..meta(None)
            }
        );

        let err = NanoChatMeta::from_json(r#"{"step": 1}"#).unwrap_err();
        ErrorMatcher::kind(BunsenErrorKind::InvalidResource).assert(&err);
    }

    /// The generation follows the state dict and the meta together, and a
    /// checkpoint between the two is refused.
    #[test]
    fn test_generation() {
        let v2025 = ["transformer.wte.weight", "lm_head.weight"];
        assert_eq!(
            meta(None).generation(&v2025).unwrap(),
            NanoChatGeneration::Upstream2025
        );
        let mut v2026: Vec<&str> = v2025.to_vec();
        v2026.extend(UPSTREAM_2026_MARKERS);
        v2026.push("value_embeds.1.weight");
        assert_eq!(
            meta(Some("L")).generation(&v2026).unwrap(),
            NanoChatGeneration::Upstream2026
        );

        let unsupported = ErrorMatcher::kind(BunsenErrorKind::Unsupported)
            .message_contains("between upstream's 2025 and 2026 models");
        // The meta says 2026, the state dict 2025; and the other way round.
        unsupported.assert(&meta(Some("L")).generation(&v2025).unwrap_err());
        unsupported.assert(&meta(None).generation(&v2026).unwrap_err());
        // Some 2026 parts and not others: an intermediate upstream commit.
        let partial = ["transformer.wte.weight", "resid_lambdas", "x0_lambdas"];
        unsupported.assert(&meta(Some("L")).generation(&partial).unwrap_err());
    }

    /// The config takes the meta's geometry, the rotary table ten times its
    /// context, and the generation's options.
    #[test]
    fn test_config() {
        let c = meta(None).gpt_config(NanoChatGeneration::Upstream2025);
        assert_eq!(
            (
                c.init_seq_len,
                c.max_seq_len_factor,
                c.vocab_size,
                c.n_layer,
                c.n_embed
            ),
            (2048, 10, 65536, 20, 1280)
        );
        assert!(!c.residual_lambdas && c.window_pattern.is_none() && c.rope_base == 10000);

        let c = meta(Some("SSSL")).gpt_config(NanoChatGeneration::Upstream2026);
        assert_eq!(c.window_pattern.as_deref(), Some("SSSL"));
        assert!(c.residual_lambdas && c.value_embeds && c.backout && c.rope_base == 100000);
    }

    /// Upstream's names land where bunsen keeps each part.
    #[test]
    fn test_pt_rekey() {
        let r = pt_rekey();
        for (from, to) in [
            ("transformer.wte.weight", "lm.embedding.weight"),
            (
                "transformer.h.3.attn.c_q.weight",
                "lm.stack.layers.3.attn.c_q.weight",
            ),
            (
                "transformer.h.3.attn.c_proj.weight",
                "lm.stack.layers.3.attn.c_proj.weight",
            ),
            (
                "transformer.h.0.mlp.c_fc.weight",
                "lm.stack.layers.0.mlp.linear1.weight",
            ),
            (
                "transformer.h.0.mlp.c_proj.weight",
                "lm.stack.layers.0.mlp.linear2.weight",
            ),
            (
                "transformer.h.17.attn.ve_gate.weight",
                "lm.stack.layers.17.attn.value_gate.weight",
            ),
            ("lm_head.weight", "lm.head.proj.weight"),
            ("value_embeds.17.weight", "value_embeds.17.weight"),
            ("smear_gate.weight", "smear_gate.weight"),
            ("resid_lambdas", "resid_lambdas"),
        ] {
            assert_eq!(r.apply(from).as_deref(), Some(to), "{from}");
        }
    }
}