prometheus04 commited on
Commit
a3bc5bb
·
verified ·
1 Parent(s): bbda1d3

v2: 363M hero run (Muon hybrid, WSD, Liger, SmolLM 75/15/10 mix)

Browse files
.gitignore ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # caches
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ipynb_checkpoints/
6
+
7
+ # data + model artifacts (regenerated; never commit)
8
+ data/
9
+ checkpoints/
10
+ results/
11
+ *.bin
12
+ *.pt
13
+ *.jsonl
14
+ wandb/
15
+
16
+ # env
17
+ .venv/
18
+ venv/
19
+ .env
README.md ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Matilda-Mini
2
+
3
+ A sub-400M-parameter language model **trained from scratch** — and, more to the
4
+ point, the **training infrastructure** around it: distributed-ready training loop,
5
+ crash-safe checkpoint/resume, fault tolerance, observability, and a verifiable
6
+ data pipeline. Built from first principles in PyTorch, no training frameworks.
7
+
8
+ > Not a fine-tune. Not a wrapper. Random init → a working LM, trained by code in
9
+ > this repo. The model is standard-modern; the **systems work is the point**.
10
+
11
+ ## Two configs, one stack
12
+
13
+ | Config | Params | Tokens | Optimizer | Data | Schedule | Purpose |
14
+ |---|---|---|---|---|---|---|
15
+ | `configs/base_124m.json` | 114M | ~3B | AdamW | FineWeb-Edu | warmup+cosine | v1 — original portfolio run |
16
+ | `configs/base_350m.json` | **363M** | **~15B** | **Muon+AdamW hybrid** | **SmolLM-corpus 75/15/10** | **WSD (MiniCPM)** | **v2 — hero run, deep+thin shape, Liger kernels** |
17
+
18
+ The v2 hero run is designed around three claims: (1) **Muon scales to 350M**
19
+ (only validated at 124M publicly + our v1 ablation); (2) **deep+thin × Muon
20
+ interaction** (32L × 960d, ~50% deeper than Pythia-410M at comparable width);
21
+ (3) **Liger Kernel in a custom nn.Module** unlocks BS ~50% larger on A100 40GB,
22
+ which is the cost story. Target comparison: **token-matched vs Pythia-410M's
23
+ published checkpoints**, ~$55-60 on A100 SXM4 vs Pythia's $1000+ to reach the
24
+ same checkpoint.
25
+
26
+ ## Why this exists
27
+
28
+ This is a portfolio project for an LLM **training-infrastructure** role. The
29
+ interesting problems in training large models aren't the architecture (well
30
+ understood) — they're the systems: making multi-day runs reliable, resumable,
31
+ observable, and fast on the hardware you have. So this repo is deliberately
32
+ weighted toward operational excellence over architectural novelty.
33
+
34
+ ## Architecture (`src/matilda/model.py`)
35
+
36
+ A modern dense decoder-only transformer — the same recipe as Llama/Qwen-class
37
+ models. Shape is a runtime knob:
38
+
39
+ | Component | v1 (124M) | v2 (363M, hero) |
40
+ |-----------|-----------|-----------------|
41
+ | Layers × d_model × n_heads | 12 × 768 × 12 | **32 × 960 × 12** |
42
+ | KV heads (GQA) | 4 | 4 |
43
+ | Head dim | 64 | **80** |
44
+ | Seq length | 1024 | **2048** |
45
+ | Positions | RoPE | RoPE (optional Liger fused) |
46
+ | Normalization | RMSNorm (fp32 reduction) | RMSNorm (optional Liger fused) |
47
+ | MLP | SwiGLU (8/3 sizing) | SwiGLU (8/3 sizing) |
48
+ | QK-Norm | on | on |
49
+ | Embedding tying | on | on |
50
+ | Loss | CE | CE **+ z-loss (1e-4)** |
51
+ | Vocab projection | `nn.Linear` + `F.cross_entropy` | **Liger fused linear+CE** (skips logit materialization) |
52
+ | Optimizer | AdamW | **Hybrid Muon (2D) + AdamW (embed/norm)** |
53
+ | LR schedule | warmup + cosine | **warmup + 80% stable + 20% linear decay (WSD)** |
54
+
55
+ ## Training infrastructure (the actual deliverable)
56
+
57
+ | Capability | Where | What it does |
58
+ |-----------|-------|--------------|
59
+ | **Bit-for-bit resume** | `checkpoint.py` | atomic writes; saves model+opt+sched+step+**RNG+dataloader position**; a killed run resumes to a loss curve identical to the uninterrupted one (`< 1e-6`, tested) |
60
+ | **Fault tolerance** | `train.py` | NaN/Inf guard (skip+log+abort-after-N); SIGTERM → checkpoint-and-exit for spot-instance death |
61
+ | **Observability** | `monitor.py` | MFU (incl. attention FLOPs), tokens/s, rolling step-time (catches throttling), grad-norm, peak GPU mem → always-on `metrics.jsonl` + optional W&B |
62
+ | **Throughput** | `train.py` | bf16 autocast, Flash-SDPA, `torch.compile`, fused AdamW, TF32, pinned/non-blocking H2D, grad-accum with DDP `no_sync` |
63
+ | **Data pipeline** | `data.py`, `scripts/prepare_data.py` | streams FineWeb-Edu → tokenizes → `uint16` shards with **SHA-256 manifest**; mmap'd, resumable `BinStream` |
64
+ | **Optimizers** | `optim.py` | AdamW (correct param-group decay) + **Muon** (Newton-Schulz orthogonalization, hybrid with AdamW) |
65
+ | **Reproducibility** | `train.py` | full config + **git SHA** logged per run; deterministic seeding |
66
+
67
+ ## Results
68
+
69
+ **Validated (RTX 3090):** 30/30 tests pass on GPU, smoke + bit-for-bit resume
70
+ clean, **53.4% MFU** at batch_size=24 with `torch.compile` (BS≥28 OOMs on the
71
+ vocab projection — the expected memory hotspot).
72
+
73
+ **Training run + ablations:** pending the A100 run. The ablation harness
74
+ (`scripts/ablate.py`) emits `docs/ABLATIONS.md` — a controlled comparison, one
75
+ change per row:
76
+
77
+ | Variant | What it isolates |
78
+ |---------|------------------|
79
+ | baseline | full modern stack |
80
+ | no_qk_norm | QK-Norm's stability contribution |
81
+ | mha / mqa | GQA ratio vs full multi-head / multi-query |
82
+ | muon | Muon vs AdamW convergence |
83
+
84
+ Target (124M, ~3B tokens, vs Pythia-160M): HellaSwag ~30-35%, ARC-easy ~40-45%,
85
+ PIQA ~60%.
86
+
87
+ ## Quickstart
88
+
89
+ ```bash
90
+ pip install -r requirements.txt # GPU: install torch from cu124 first (see runbook)
91
+ pytest tests/ -q # 35 tests: correctness, resume, NaN guard, data integrity, WSD, z-loss
92
+
93
+ # train (synthetic dry run, no data needed)
94
+ python run.py --config configs/calibration.json --dry-run \
95
+ --set model.d_model=128 model.n_layers=2 train.total_steps=20 train.device=cpu train.compile=false
96
+
97
+ # v1 run (124M / FineWeb-Edu / ~3B tokens)
98
+ python scripts/prepare_data.py --out-dir data/fwedu --target-tokens 3000000000
99
+ python run.py --config configs/base_124m.json --data-dir data/fwedu
100
+
101
+ # v2 hero run (363M / SmolLM 75/15/10 / ~15B tokens) — A100 + liger-kernel required
102
+ pip install liger-kernel
103
+ python scripts/prepare_smollm_data.py --out-dir data/smollm_mix --target-tokens 15000000000
104
+ python run.py --config configs/base_350m.json --data-dir data/smollm_mix
105
+ ```
106
+
107
+ Full GPU procedure (validate → calibrate → ablate → train → eval) is in
108
+ [`docs/INSTANCE_RUNBOOK.md`](docs/INSTANCE_RUNBOOK.md).
109
+
110
+ ## Repository layout
111
+
112
+ ```
113
+ src/matilda/ config, model, optim, checkpoint, monitor, data, train
114
+ scripts/ prepare_data.py (FineWeb-Edu), prepare_smollm_data.py (SmolLM 75/15/10 mix),
115
+ ablate.py (experiments), launch_vast.sh
116
+ configs/ calibration.json (MFU tuning), base_124m.json (v1), base_350m.json (v2 hero)
117
+ tests/ 35 tests — model, checkpoint, train loop, data, optim, ablation, run, WSD, z-loss
118
+ docs/ INSTANCE_RUNBOOK.md (operating manual)
119
+ run.py training entrypoint (--config + --set overrides)
120
+ ```
121
+
122
+ ## Testing
123
+
124
+ 35 tests run on CPU in ~2 min. Highlights: overfit-single-batch (the model can
125
+ learn), causal-mask-no-leak (no future-token leakage), bit-for-bit resume,
126
+ NaN-skip-then-recover, shard checksum corruption detection, Muon overfit, WSD
127
+ three-phase shape, z-loss equals CE + lse² when on. BASE_350M shape test skips
128
+ on CPU dev boxes without `liger-kernel`.
129
+
130
+ ```bash
131
+ pytest tests/ -q
132
+ ```
configs/base_124m.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_comment": "The long run. ~3B tokens = total_steps*batch*grad_accum*seq_len = 5814*24*21*1024 ~= 3.0B. These bs/accum are the VALIDATED 3090 ceiling (BS=24 @ 53.4% MFU; BS>=28 OOMs on the vocab projection). On A100, raise batch_size to its ceiling (expect 64-128) and re-derive grad_accum/total_steps to keep tokens/step ~0.5M and tokens ~3B (see runbook section 6). lr 6e-4; drop to 3e-4 if grad_norm spikes.",
3
+ "model": {
4
+ "vocab_size": 50257,
5
+ "max_seq_len": 1024,
6
+ "d_model": 768,
7
+ "n_layers": 12,
8
+ "n_heads": 12,
9
+ "n_kv_heads": 4,
10
+ "qk_norm": true
11
+ },
12
+ "train": {
13
+ "total_steps": 5814,
14
+ "warmup_steps": 300,
15
+ "grad_accum": 21,
16
+ "batch_size": 24,
17
+ "seq_len": 1024,
18
+ "lr": 6e-4,
19
+ "weight_decay": 0.1,
20
+ "grad_clip": 1.0,
21
+ "min_lr_ratio": 0.1,
22
+ "log_every": 10,
23
+ "ckpt_every": 500,
24
+ "keep_last": 3,
25
+ "device": "cuda",
26
+ "dtype": "bfloat16",
27
+ "compile": true,
28
+ "max_skips": 20,
29
+ "ckpt_dir": "checkpoints/base_124m",
30
+ "wandb_project": "matilda-mini"
31
+ }
32
+ }
configs/base_350m.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_comment": "350M hero run, 15B tokens (~2x Chinchilla). Tokens/step ~= 1.05M (32*16*2048); 15000 steps * 1.05M ~= 15.7B tokens. ETA on A100 SXM4 40GB at the target 50% MFU: ~55-60h, ~$55-60 at $1.017/hr. Re-derive batch_size/grad_accum on the instance: with Liger fused linear+CE we expect to push micro-batch to 32-48; if calibration says 48, drop grad_accum to ~11 to keep tokens/step ~= 1M. lr 3e-4 (AdamW arm); muon_lr 0.02 (validated in v1 ablation). Schedule = WSD with 80%-stable, 20%-linear-decay; min_lr_ratio 0.1 so the tail isn't dead. z_loss 1e-4 for logit stability at scale. use_liger=true is mandatory for the hero throughput claim — fails loudly if liger-kernel not installed.",
3
+ "model": {
4
+ "vocab_size": 50257,
5
+ "max_seq_len": 2048,
6
+ "d_model": 960,
7
+ "n_layers": 32,
8
+ "n_heads": 12,
9
+ "n_kv_heads": 4,
10
+ "mlp_ratio": 2.6666666666666665,
11
+ "mlp_multiple_of": 256,
12
+ "tie_weights": true,
13
+ "qk_norm": true,
14
+ "z_loss_coef": 1e-4,
15
+ "use_liger": true
16
+ },
17
+ "train": {
18
+ "total_steps": 15000,
19
+ "warmup_steps": 2000,
20
+ "grad_accum": 16,
21
+ "batch_size": 32,
22
+ "seq_len": 2048,
23
+ "lr": 3e-4,
24
+ "weight_decay": 0.1,
25
+ "grad_clip": 1.0,
26
+ "min_lr_ratio": 0.1,
27
+ "optimizer": "muon",
28
+ "muon_lr": 0.02,
29
+ "lr_schedule": "wsd",
30
+ "wsd_stable_share": 0.8,
31
+ "log_every": 10,
32
+ "ckpt_every": 1000,
33
+ "keep_last": 20,
34
+ "device": "cuda",
35
+ "dtype": "bfloat16",
36
+ "compile": true,
37
+ "max_skips": 20,
38
+ "ckpt_dir": "checkpoints/base_350m",
39
+ "wandb_project": "matilda-mini"
40
+ }
41
+ }
configs/calibration.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_comment": "15-min A100 smoke test. Goal: maximize MFU before the long run. Sweep batch_size with --set train.batch_size=N and read mfu_avg from the log. Few steps, frequent logging, compile on.",
3
+ "model": {
4
+ "vocab_size": 50257,
5
+ "max_seq_len": 1024,
6
+ "d_model": 768,
7
+ "n_layers": 12,
8
+ "n_heads": 12,
9
+ "n_kv_heads": 4
10
+ },
11
+ "train": {
12
+ "total_steps": 60,
13
+ "warmup_steps": 10,
14
+ "grad_accum": 1,
15
+ "batch_size": 24,
16
+ "seq_len": 1024,
17
+ "lr": 3e-4,
18
+ "log_every": 5,
19
+ "ckpt_every": 60,
20
+ "keep_last": 1,
21
+ "device": "cuda",
22
+ "dtype": "bfloat16",
23
+ "compile": true,
24
+ "ckpt_dir": "checkpoints/calib"
25
+ }
26
+ }
conftest.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ sys.path.insert(0, str(Path(__file__).parent / "src"))
docs/A100_KICKOFF_PROMPT.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A100 Run — Kickoff Prompts (paste into Claude Code on the instance)
2
+
3
+ Two prompts. **Prompt 1** validates + calibrates (cheap, ~$0.50) and stops.
4
+ **Prompt 2** runs the paid training + ablations + eval. Run Prompt 1 first,
5
+ read the calibration result, fill Prompt 2's batch numbers, then run it.
6
+
7
+ GPU: **A100 40GB recommended** (124M model — 80GB is overkill; the memory
8
+ hotspot is the vocab-projection logits, not weights). 3090 also works.
9
+ Attention is PyTorch SDPA (built-in Flash 2) — no `flash-attn` package.
10
+
11
+ ---
12
+
13
+ ## PROMPT 1 — validate + calibrate, then STOP
14
+
15
+ ```
16
+ You're on a remote GPU instance. Validate and calibrate a from-scratch LLM
17
+ training project. Do NOT start paid training or ablations yet — stop and report.
18
+
19
+ 1. git clone https://huggingface.co/prometheus04/matilda-mini && cd matilda-mini
20
+ 2. Read docs/INSTANCE_RUNBOOK.md fully; follow it and respect every "Gate".
21
+ 3. Execute runbook sections 2-6:
22
+ - §2: nvidia-smi (report GPU + VRAM). Install torch from the cu124 index FIRST,
23
+ then `pip install -r requirements.txt`. Confirm CUDA + bf16 available.
24
+ - §3: `pytest tests/ -q` — gate is "30 passed". If a GPU-only failure appears,
25
+ STOP and show the full traceback.
26
+ - §4: tokenize ~20M tokens FineWeb-Edu, verify checksum, run 100 steps — loss
27
+ should fall from ~10.8 toward ~7.
28
+ - §5: rerun to 150 steps — must print "[resume] ... at step 100" and continue
29
+ with no loss spike.
30
+ - §6: sweep batch_size with configs/calibration.json; report batch_size -> MFU.
31
+ 4. STOP and report: (1) GPU+VRAM, (2) pytest result, (3) smoke loss + resume,
32
+ (4) the calibration table and the best batch_size.
33
+ Use tmux for long commands. Never commit data/ or checkpoints/.
34
+ ```
35
+
36
+ ---
37
+
38
+ ## Between prompts — pick batch/accum/total_steps
39
+
40
+ From the calibration sweep, take the `batch_size` (BS) with the best MFU that
41
+ fits, then keep tokens/step ≈ 524288 and total tokens ≈ 3.0B:
42
+
43
+ ```
44
+ grad_accum = round(524288 / (BS * 1024))
45
+ total_steps = round(3.0e9 / (BS * grad_accum * 1024))
46
+ ```
47
+
48
+ Pre-computed safe defaults (use if you don't want to wait on the sweep):
49
+
50
+ | GPU | BS | grad_accum | total_steps | tokens |
51
+ |-----|----|-----------|-------------|--------|
52
+ | A100 40GB | 64 | 8 | 5722 | 3.00B |
53
+ | A100 80GB | 128 | 4 | 5722 | 3.00B |
54
+ | 3090 (validated) | 24 | 21 | 5814 | 3.00B |
55
+
56
+ ---
57
+
58
+ ## PROMPT 2 — the paid run (fill BS / ACCUM / STEPS, then paste)
59
+
60
+ ```
61
+ Continue in the matilda-mini directory on the instance. Calibration is done.
62
+ Run the full training + ablations + eval. This is the paid run.
63
+
64
+ Set these from calibration (A100 40GB defaults shown): BS=64, ACCUM=8, STEPS=5722.
65
+
66
+ 1. Tokenize the full dataset if not already present:
67
+ python scripts/prepare_data.py --out-dir data/fwedu --target-tokens 3000000000
68
+ (verify the manifest checksum after.)
69
+
70
+ 2. Launch the long run inside tmux so an SSH drop can't kill it:
71
+ tmux new -s train
72
+ python run.py --config configs/base_124m.json --data-dir data/fwedu \
73
+ --set train.batch_size=64 train.grad_accum=8 train.total_steps=5722
74
+ Detach with Ctrl-b d. Reattach with `tmux attach -t train`. If it ever dies,
75
+ re-run the same command — it auto-resumes from the latest checkpoint.
76
+ Watch checkpoints/base_124m/metrics.jsonl: loss falling, grad_norm ~0.2-1.5,
77
+ MFU flat, few/no nan_skip events. If grad_norm spikes / many NaN skips, lower
78
+ lr to 3e-4 (--set train.lr=3e-4) and resume.
79
+
80
+ 3. After training completes, run the architecture ablations (~$2):
81
+ python scripts/ablate.py --data-dir data/fwedu --tokens 300000000
82
+ This writes docs/ABLATIONS.md (the results table).
83
+
84
+ 4. Evaluate the final model:
85
+ pip install -q lm-eval
86
+ (export the checkpoint to a HF-style dir if needed, then) lm_eval --model hf \
87
+ --model_args pretrained=<dir>,dtype=bfloat16 \
88
+ --tasks hellaswag,arc_easy,piqa,winogrande --batch_size 32
89
+
90
+ 5. Save artifacts OFF the instance (it's ephemeral): the final ckpt_*.pt,
91
+ checkpoints/base_124m/metrics.jsonl, docs/ABLATIONS.md, and the eval JSON.
92
+ Upload to HF or scp them out. Report the final loss, MFU, and eval numbers.
93
+ ```
94
+
95
+ ---
96
+
97
+ ## Reference
98
+
99
+ **Expected (124M, ~3B tokens):** final loss ~2.7-3.0; MFU ~40-50% (A100, compile
100
+ on); HellaSwag ~30-35%, ARC-easy ~40-45%, PIQA ~60% (vs Pythia-160M: ~30/40/62).
101
+
102
+ **Cost:** A100 40GB long run ~$4-8; ablations ~$2; calibration ~$0.50.
103
+
104
+ **Troubleshooting:** OOM → lower BS, raise grad_accum to keep tokens/step.
105
+ Low MFU (<25%) → confirm compile=true + bf16 engaged. SSH drop → tmux + re-run
106
+ (auto-resume). git_sha "unknown" → only if cloned non-git (HF clone IS git, fine).
107
+
108
+ **After the run:** paste the final loss / MFU / eval numbers + docs/ABLATIONS.md
109
+ back to laptop-Claude to fill the README "Results" section, then flip the repo
110
+ public as the finished portfolio piece.
docs/DEEPSEEK_REVIEW_BUNDLE.md ADDED
@@ -0,0 +1,1520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Review Prompt for DeepSeek
2
+
3
+ > Paste everything below into DeepSeek. DeepSeek cannot read your disk, so after
4
+ > the prompt, paste the contents of the files it asks for (or attach them). The
5
+ > file map and paths are included so you both share a mental model.
6
+
7
+ ---
8
+
9
+ ## ROLE
10
+
11
+ You are a senior LLM training-infrastructure engineer reviewing a from-scratch
12
+ small language model project. Be rigorous and skeptical. I want correctness bugs,
13
+ reliability gaps, and anything that would embarrass me in a technical interview —
14
+ not encouragement. Prioritize findings by severity (CRITICAL / HIGH / MEDIUM / LOW).
15
+
16
+ ## WHY THIS PROJECT EXISTS (the job I'm applying for)
17
+
18
+ I'm building this as a portfolio piece for an **AI Training Infrastructure Engineer**
19
+ role at **Maincode** (Melbourne, Australia). Maincode trains "Matilda", the first
20
+ LLM built and trained from scratch in Australia. Key facts about the role:
21
+
22
+ - It is an **infrastructure** role, NOT a research/architecture role. The work is:
23
+ distributed training pipelines, data ingestion/preprocessing, experiment
24
+ management, checkpointing, reproducibility, monitoring/observability, debugging
25
+ long-running (days–weeks) training jobs, optimizing throughput (compute/memory/
26
+ data), and diagnosing failures that appear hours into a run.
27
+ - Explicitly NOT about: wrapping external APIs, prompt engineering, user-facing apps.
28
+ - Stack: Python, PyTorch/JAX, reliable infra for large compute, debugging
29
+ distributed systems and long jobs.
30
+ - They value engineers who understand how systems behave over long runtimes and
31
+ who prefer understanding internals over relying on abstraction.
32
+
33
+ So the project is **deliberately weighted toward operational excellence**
34
+ (checkpoint/resume, fault tolerance, reproducibility, MFU/observability) over
35
+ architectural breadth. The architecture is modern but standard; the infra is the
36
+ flex. Please judge it through that lens.
37
+
38
+ ## ORIGINAL PLAN & KEY DECISIONS (locked)
39
+
40
+ - **Goal:** train a sub-200M-param modern transformer from scratch, end-to-end,
41
+ with a clean ablation table, on a tight budget.
42
+ - **Hardware:** rent ONE A100 80GB on Vast.ai for the single long paid run.
43
+ - **Long paid run = modernized DENSE ~114M, maximize MFU.** Rationale: MoE on a
44
+ single GPU collapses MFU to ~20% (needs expert parallelism across devices);
45
+ dense hits 45–50%. "DeepSeek-inspired" here means the efficiency stack
46
+ (Flash/SDPA, torch.compile, fused optimizer, bf16, Muon, μP, WSD), NOT sparsity.
47
+ A100 has no FP8 (bf16 ceiling; FP8 would need H100).
48
+ - **MoE is built only as a CHEAP SHORT ablation** (~500M tokens, ~$0.60) with an
49
+ honest write-up of the single-GPU MFU drop. Not the headline run.
50
+ - **Tokenizer:** GPT-2 50257 (tiktoken "gpt2") — fits uint16, comparable to Pythia
51
+ baselines. (We caught and avoided a bug from our source primer that paired
52
+ cl100k ~100k vocab with uint16, which overflows 65535.)
53
+ - **Dataset:** FineWeb-Edu sample-10BT primary (best small-scale benchmark
54
+ movement + Pythia comparability). Loader is dataset-agnostic so DCLM /
55
+ Nemotron-CC are drop-in data-ablation rows.
56
+ - **Cost discipline:** only the ONE long run costs real money (~$5–15). Ablations
57
+ ~$0.60 each. ALL correctness validated FREE on Colab/CPU first; a ~$0.20 A100
58
+ smoke test maximizes MFU before committing to the long run.
59
+
60
+ ### Phase plan
61
+ 1. ✅ Model + sanity tests
62
+ 2. ✅ Infra harness (checkpoint/resume, NaN-guard, monitor/MFU, optimizer, loop)
63
+ 3. ✅ Data pipeline (FineWeb→uint16 shards + checksum, mmap BinStream)
64
+ 4. ⏳ NEXT: Colab GPU correctness pass + $0.20 A100 MFU calibration
65
+ 5. Long dense run (~3B tokens)
66
+ 6. Architecture ablations (RoPE/RMSNorm/SwiGLU/GQA/QK-norm on/off)
67
+ 7. Muon vs AdamW
68
+ 8. MoE ablation
69
+ 9. Eval (lm-eval-harness: HellaSwag / ARC-easy / PIQA vs Pythia-160M)
70
+
71
+ ## WHAT IS BUILT (Phases 1–3 complete; 18/18 tests pass on CPU)
72
+
73
+ Repository root on my machine:
74
+ `C:\Users\Swajay\Downloads\trade\matilda-mini\`
75
+
76
+ File map (line counts):
77
+
78
+ ```
79
+ src/matilda/
80
+ config.py (65) frozen dataclass; DEV_TINY + BASE_124M (114M total / 75.5M non-embed)
81
+ model.py (199) dense decoder: RoPE, RMSNorm, SwiGLU, GQA, QK-Norm, weight tying, residual-scaled init
82
+ optim.py (48) AdamW with param groups (no WD on norms/biases/embeddings); cosine+warmup schedule
83
+ checkpoint.py (95) atomic write (tmp->os.replace), rotation, saves model+opt+sched+step+RNG+dataloader pos
84
+ monitor.py (70) MFU, tokens/s, rolling step-time window, per-GPU peak-TFLOPS table
85
+ data.py (182) ShardWriter (+SHA-256 manifest), verify_manifest, SyntheticStream, BinStream (mmap, resumable)
86
+ train.py (236) loop: bf16 autocast, grad-accum + DDP no_sync, grad-clip, NaN/Inf guard, SIGTERM->checkpoint, auto-resume
87
+ __init__.py (4)
88
+ scripts/
89
+ prepare_data.py (73) stream HF dataset (default FineWeb-Edu sample-10BT) -> tokenize gpt2 -> uint16 shards + verified manifest
90
+ tests/ (18 tests total, all green on CPU/torch 2.7.1)
91
+ test_model.py (86) forward shapes, weight-tying, init-loss≈log(V), CAUSAL-MASK-NO-FUTURE-LEAK, GQA head counts, OVERFIT-SINGLE-BATCH
92
+ test_checkpoint.py(116) BIT-FOR-BIT RESUME (post-resume losses match uninterrupted run <1e-6), rotation/latest
93
+ test_train.py (79) loop runs+checkpoints, loop-level resume, NaN-abort, NaN-skip-then-recover, MFU sanity
94
+ test_data.py (78) shard round-trip, CHECKSUM CORRUPTION DETECTION, BinStream next-token shift, deterministic resume, multi-shard
95
+ conftest.py, pytest.ini, requirements.txt
96
+ ```
97
+
98
+ Verified facts:
99
+ - Overfit-one-batch: loss → <0.1 on a fixed batch (model can learn).
100
+ - Causal mask: perturbing token t leaves all logits at positions < t bit-identical.
101
+ - Resume: interrupt at the halfway point, rebuild fresh model/opt/sched/stream,
102
+ restore, continue → per-step losses match an uninterrupted run to <1e-6.
103
+ - Data: corrupting one byte of a shard is caught by verify_manifest.
104
+ - BinStream → Trainer integration: loss drops on structured data with train.py unchanged.
105
+
106
+ ## WHAT I WANT FROM YOU (review checklist)
107
+
108
+ Please go through these and report concrete findings with file/function references:
109
+
110
+ 1. **Transformer correctness.** RoPE (half-rotation convention, cos/sin build,
111
+ applied to Q/K only, before/after QK-norm ordering), GQA repeat_interleave vs
112
+ repeat semantics, SwiGLU 2/3 sizing, RMSNorm fp32 reduction, weight tying,
113
+ residual-projection init scaling 1/sqrt(2*n_layers). Any subtle bug?
114
+ 2. **Numerical stability for a long bf16 run.** Is QK-norm enough? Should I add
115
+ z-loss / logit soft-cap / attention-logit cap? Embedding init scale?
116
+ 3. **Checkpoint/resume completeness.** Anything that influences the next step that
117
+ I'm NOT saving (RNG, data position, scaler, AMP state)? Atomicity on Vast spot kill.
118
+ 4. **NaN/Inf guard design.** Is skip-batch correct, or should I roll back to last
119
+ checkpoint? Should the guard also catch inf grad-norm before clip (it does)?
120
+ Is consecutive-skip abort the right policy?
121
+ 5. **Throughput / MFU.** Is the 6N FLOPs/token approximation appropriate, or should
122
+ I include attention FLOPs (2*L*T*d term) at seq_len 1024? Will I actually hit
123
+ 45-50% MFU on an A100 with this code, or what's missing (e.g., no torch.compile
124
+ tuning, no fused/foreach, dataloader not overlapped with compute, H2D copies not
125
+ pinned/non_blocking)?
126
+ 6. **DDP correctness.** no_sync usage on non-final micro-steps is wired but DDP
127
+ wrapping isn't applied (single-GPU). If I later wrap in DDP, what breaks
128
+ (checkpoint should save model.module, num_params unwrap, sampler sharding,
129
+ rank-0-only logging/checkpointing)?
130
+ 7. **Data pipeline.** Random-window sampling vs sequential cursor — implications for
131
+ epoch coverage and resume. Cross-document contamination from packing without
132
+ attention masking at seq_len 1024 — does it matter at this scale?
133
+ 8. **Chinchilla / token budget.** For ~114M total (~75M non-embedding), what token
134
+ count is right for a portfolio run (compute-optimal ~20x vs over-train 50-100x)?
135
+ 9. **Anything that would make a Maincode interviewer wince.** Missing observability,
136
+ missing reproducibility (git SHA logging?), config hygiene, test gaps.
137
+ 10. **Highest-ROI additions** before I spend money, ranked, given the infra-role framing.
138
+
139
+ For each finding give: severity, file/location, the problem, and the concrete fix.
140
+
141
+ ---
142
+
143
+ SOURCE FILES FOLLOW. I will paste them below in this order: config.py, model.py,
144
+ optim.py, checkpoint.py, monitor.py, data.py, train.py, then the four test files.
145
+
146
+
147
+ ===== FILE: src/matilda/config.py =====
148
+ ```python
149
+ """Model + run configuration.
150
+
151
+ One frozen dataclass is the single source of truth for a run. It gets logged
152
+ verbatim (alongside the git SHA) so any run is exactly reproducible. Nothing in
153
+ the training stack reads a hyperparameter from anywhere else.
154
+ """
155
+
156
+ from __future__ import annotations
157
+
158
+ from dataclasses import dataclass, field, asdict
159
+
160
+
161
+ @dataclass(frozen=True)
162
+ class ModelConfig:
163
+ # --- vocab / sequence ---
164
+ vocab_size: int = 50257 # GPT-2 (tiktoken "gpt2"); fits uint16
165
+ max_seq_len: int = 1024
166
+
167
+ # --- transformer shape ---
168
+ d_model: int = 768
169
+ n_layers: int = 12
170
+ n_heads: int = 12
171
+ n_kv_heads: int = 4 # GQA: n_heads must be divisible by this
172
+ mlp_ratio: float = 8 / 3 # SwiGLU keeps params ~= 4x dense MLP
173
+ mlp_multiple_of: int = 256 # round hidden dim up to this for kernels
174
+
175
+ # --- numerics / regularization ---
176
+ norm_eps: float = 1e-6
177
+ rope_theta: float = 10000.0
178
+ init_std: float = 0.02
179
+ dropout: float = 0.0 # pretraining: keep at 0
180
+
181
+ # --- structural switches ---
182
+ tie_weights: bool = True # share embedding <-> lm_head
183
+ qk_norm: bool = True # RMSNorm on Q,K before attention
184
+
185
+ @property
186
+ def head_dim(self) -> int:
187
+ assert self.d_model % self.n_heads == 0, "d_model must divide n_heads"
188
+ return self.d_model // self.n_heads
189
+
190
+ def __post_init__(self) -> None:
191
+ assert self.n_heads % self.n_kv_heads == 0, \
192
+ "n_heads must be divisible by n_kv_heads (GQA grouping)"
193
+ assert self.head_dim % 2 == 0, "head_dim must be even for RoPE"
194
+
195
+ def to_dict(self) -> dict:
196
+ d = asdict(self)
197
+ d["head_dim"] = self.head_dim
198
+ return d
199
+
200
+
201
+ # Tiny config for free correctness validation on Colab T4 / RTX 3060.
202
+ # Real vocab kept so tokenizer wiring is exercised; dims shrunk so it runs fast.
203
+ DEV_TINY = ModelConfig(
204
+ vocab_size=50257,
205
+ max_seq_len=256,
206
+ d_model=128,
207
+ n_layers=2,
208
+ n_heads=4,
209
+ n_kv_heads=2,
210
+ )
211
+
212
+ # ~124M params (GPT-2 base footprint). The intended A100 long-run config.
213
+ BASE_124M = ModelConfig()
214
+ ```
215
+
216
+ ===== FILE: src/matilda/model.py =====
217
+ ```python
218
+ """Modernized dense decoder-only transformer.
219
+
220
+ Block recipe (pre-norm): x = x + attn(rmsnorm(x)); x = x + swiglu(rmsnorm(x)).
221
+ Modernizations baked in from the start (validated free on Colab before any
222
+ paid run): RoPE, RMSNorm, SwiGLU, GQA, QK-Norm, weight tying, residual-scaled
223
+ init. This is the architecture the long A100 run uses.
224
+ """
225
+
226
+ from __future__ import annotations
227
+
228
+ import math
229
+
230
+ import torch
231
+ import torch.nn as nn
232
+ import torch.nn.functional as F
233
+
234
+ from .config import ModelConfig
235
+
236
+
237
+ class RMSNorm(nn.Module):
238
+ """RMSNorm with the reduction done in fp32 for mixed-precision safety."""
239
+
240
+ def __init__(self, dim: int, eps: float = 1e-6):
241
+ super().__init__()
242
+ self.eps = eps
243
+ self.weight = nn.Parameter(torch.ones(dim))
244
+
245
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
246
+ dtype = x.dtype
247
+ x = x.float()
248
+ rms = x.pow(2).mean(dim=-1, keepdim=True).add(self.eps).rsqrt()
249
+ return (x * rms).to(dtype) * self.weight
250
+
251
+
252
+ def build_rope_cache(head_dim: int, max_seq_len: int, theta: float,
253
+ device=None, dtype=torch.float32):
254
+ """Precompute (cos, sin) of shape (max_seq_len, head_dim).
255
+
256
+ Half-rotation (Llama) convention: freqs are computed for head_dim/2 pairs
257
+ and concatenated with themselves so they line up with rotate_half.
258
+ """
259
+ i = torch.arange(0, head_dim, 2, device=device, dtype=torch.float32)
260
+ inv_freq = 1.0 / (theta ** (i / head_dim)) # (head_dim/2,)
261
+ t = torch.arange(max_seq_len, device=device, dtype=torch.float32)
262
+ freqs = torch.outer(t, inv_freq) # (T, head_dim/2)
263
+ emb = torch.cat([freqs, freqs], dim=-1) # (T, head_dim)
264
+ return emb.cos().to(dtype), emb.sin().to(dtype)
265
+
266
+
267
+ def _rotate_half(x: torch.Tensor) -> torch.Tensor:
268
+ x1, x2 = x.chunk(2, dim=-1)
269
+ return torch.cat([-x2, x1], dim=-1)
270
+
271
+
272
+ def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
273
+ # x: (B, n_heads, T, head_dim); cos/sin: (T, head_dim) -> broadcast
274
+ cos = cos[None, None, :, :]
275
+ sin = sin[None, None, :, :]
276
+ return (x * cos) + (_rotate_half(x) * sin)
277
+
278
+
279
+ class Attention(nn.Module):
280
+ """Causal grouped-query attention with optional QK-Norm and RoPE."""
281
+
282
+ def __init__(self, cfg: ModelConfig):
283
+ super().__init__()
284
+ self.n_heads = cfg.n_heads
285
+ self.n_kv_heads = cfg.n_kv_heads
286
+ self.head_dim = cfg.head_dim
287
+ self.n_rep = cfg.n_heads // cfg.n_kv_heads
288
+
289
+ self.wq = nn.Linear(cfg.d_model, cfg.n_heads * self.head_dim, bias=False)
290
+ self.wk = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
291
+ self.wv = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
292
+ self.wo = nn.Linear(cfg.n_heads * self.head_dim, cfg.d_model, bias=False)
293
+
294
+ self.qk_norm = cfg.qk_norm
295
+ if cfg.qk_norm:
296
+ self.q_norm = RMSNorm(self.head_dim, cfg.norm_eps)
297
+ self.k_norm = RMSNorm(self.head_dim, cfg.norm_eps)
298
+ self.dropout = cfg.dropout
299
+
300
+ def forward(self, x, cos, sin):
301
+ B, T, _ = x.shape
302
+ q = self.wq(x).view(B, T, self.n_heads, self.head_dim)
303
+ k = self.wk(x).view(B, T, self.n_kv_heads, self.head_dim)
304
+ v = self.wv(x).view(B, T, self.n_kv_heads, self.head_dim)
305
+
306
+ if self.qk_norm:
307
+ q = self.q_norm(q)
308
+ k = self.k_norm(k)
309
+
310
+ # (B, n_heads, T, head_dim)
311
+ q = q.transpose(1, 2)
312
+ k = k.transpose(1, 2)
313
+ v = v.transpose(1, 2)
314
+
315
+ q = apply_rope(q, cos, sin)
316
+ k = apply_rope(k, cos, sin)
317
+
318
+ # expand KV heads to match Q heads (GQA). repeat_interleave on head dim.
319
+ if self.n_rep > 1:
320
+ k = k.repeat_interleave(self.n_rep, dim=1)
321
+ v = v.repeat_interleave(self.n_rep, dim=1)
322
+
323
+ out = F.scaled_dot_product_attention(
324
+ q, k, v, is_causal=True,
325
+ dropout_p=self.dropout if self.training else 0.0,
326
+ )
327
+ out = out.transpose(1, 2).contiguous().view(B, T, -1)
328
+ return self.wo(out)
329
+
330
+
331
+ class SwiGLU(nn.Module):
332
+ def __init__(self, cfg: ModelConfig):
333
+ super().__init__()
334
+ hidden = int(cfg.mlp_ratio * cfg.d_model)
335
+ m = cfg.mlp_multiple_of
336
+ hidden = ((hidden + m - 1) // m) * m
337
+ self.gate = nn.Linear(cfg.d_model, hidden, bias=False)
338
+ self.up = nn.Linear(cfg.d_model, hidden, bias=False)
339
+ self.down = nn.Linear(hidden, cfg.d_model, bias=False)
340
+
341
+ def forward(self, x):
342
+ return self.down(F.silu(self.gate(x)) * self.up(x))
343
+
344
+
345
+ class Block(nn.Module):
346
+ def __init__(self, cfg: ModelConfig):
347
+ super().__init__()
348
+ self.norm1 = RMSNorm(cfg.d_model, cfg.norm_eps)
349
+ self.attn = Attention(cfg)
350
+ self.norm2 = RMSNorm(cfg.d_model, cfg.norm_eps)
351
+ self.mlp = SwiGLU(cfg)
352
+
353
+ def forward(self, x, cos, sin):
354
+ x = x + self.attn(self.norm1(x), cos, sin)
355
+ x = x + self.mlp(self.norm2(x))
356
+ return x
357
+
358
+
359
+ class Transformer(nn.Module):
360
+ def __init__(self, cfg: ModelConfig):
361
+ super().__init__()
362
+ self.cfg = cfg
363
+ self.embed = nn.Embedding(cfg.vocab_size, cfg.d_model)
364
+ self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layers)])
365
+ self.norm_f = RMSNorm(cfg.d_model, cfg.norm_eps)
366
+ self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
367
+ if cfg.tie_weights:
368
+ self.lm_head.weight = self.embed.weight
369
+
370
+ cos, sin = build_rope_cache(cfg.head_dim, cfg.max_seq_len, cfg.rope_theta)
371
+ self.register_buffer("rope_cos", cos, persistent=False)
372
+ self.register_buffer("rope_sin", sin, persistent=False)
373
+
374
+ self.apply(self._init_weights)
375
+ # Residual-projection scaling (GPT-2 trick): keep residual-stream growth
376
+ # bounded with depth by shrinking the layers that write back into it.
377
+ scale = 1.0 / math.sqrt(2 * cfg.n_layers)
378
+ for name, p in self.named_parameters():
379
+ if name.endswith("wo.weight") or name.endswith("down.weight"):
380
+ with torch.no_grad():
381
+ p.mul_(scale)
382
+
383
+ def _init_weights(self, module):
384
+ if isinstance(module, nn.Linear):
385
+ nn.init.normal_(module.weight, mean=0.0, std=self.cfg.init_std)
386
+ if module.bias is not None:
387
+ nn.init.zeros_(module.bias)
388
+ elif isinstance(module, nn.Embedding):
389
+ nn.init.normal_(module.weight, mean=0.0, std=self.cfg.init_std)
390
+
391
+ def forward(self, idx: torch.Tensor, targets: torch.Tensor | None = None):
392
+ B, T = idx.shape
393
+ assert T <= self.cfg.max_seq_len, "sequence longer than rope cache"
394
+ x = self.embed(idx)
395
+ cos = self.rope_cos[:T]
396
+ sin = self.rope_sin[:T]
397
+ for block in self.blocks:
398
+ x = block(x, cos, sin)
399
+ x = self.norm_f(x)
400
+ logits = self.lm_head(x)
401
+
402
+ loss = None
403
+ if targets is not None:
404
+ loss = F.cross_entropy(
405
+ logits.view(-1, logits.size(-1)),
406
+ targets.view(-1),
407
+ ignore_index=-1,
408
+ )
409
+ return logits, loss
410
+
411
+ def num_params(self, non_embedding: bool = True) -> int:
412
+ n = sum(p.numel() for p in self.parameters())
413
+ if non_embedding:
414
+ # tied: lm_head shares embed, so subtract the one embedding table
415
+ n -= self.embed.weight.numel()
416
+ return n
417
+ ```
418
+
419
+ ===== FILE: src/matilda/optim.py =====
420
+ ```python
421
+ """Optimizer + LR schedule construction.
422
+
423
+ Two details that materially affect quality and that most tutorials get wrong:
424
+ 1. No weight decay on 1-D params (norms, biases) or the embedding table.
425
+ Decaying norm/embedding weights quietly hurts.
426
+ 2. The LR schedule includes linear warmup; starting at peak LR on random
427
+ weights diverges.
428
+ """
429
+
430
+ from __future__ import annotations
431
+
432
+ import math
433
+
434
+ import torch
435
+ from torch.optim.lr_scheduler import LambdaLR
436
+
437
+
438
+ def build_adamw(model, lr=3e-4, weight_decay=0.1,
439
+ betas=(0.9, 0.95), eps=1e-8) -> torch.optim.AdamW:
440
+ decay, no_decay = [], []
441
+ for name, p in model.named_parameters():
442
+ if not p.requires_grad:
443
+ continue
444
+ # 2-D matmul weights get decay; norms/biases (1-D) and embeddings don't.
445
+ if p.ndim < 2 or "embed" in name:
446
+ no_decay.append(p)
447
+ else:
448
+ decay.append(p)
449
+ groups = [
450
+ {"params": decay, "weight_decay": weight_decay},
451
+ {"params": no_decay, "weight_decay": 0.0},
452
+ ]
453
+ fused = torch.cuda.is_available()
454
+ return torch.optim.AdamW(groups, lr=lr, betas=betas, eps=eps, fused=fused)
455
+
456
+
457
+ def cosine_warmup_scheduler(optimizer, warmup_steps, total_steps, min_lr_ratio=0.1):
458
+ """Linear warmup then cosine decay to min_lr_ratio * peak."""
459
+ def lr_lambda(step):
460
+ if step < warmup_steps:
461
+ return (step + 1) / max(1, warmup_steps)
462
+ if step >= total_steps:
463
+ return min_lr_ratio
464
+ progress = (step - warmup_steps) / max(1, total_steps - warmup_steps)
465
+ cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
466
+ return min_lr_ratio + (1 - min_lr_ratio) * cosine
467
+
468
+ return LambdaLR(optimizer, lr_lambda)
469
+ ```
470
+
471
+ ===== FILE: src/matilda/checkpoint.py =====
472
+ ```python
473
+ """Crash-safe checkpointing.
474
+
475
+ A resumed run must continue *identically*, not just "without an obvious spike".
476
+ That requires saving everything that influences the next step:
477
+ model, optimizer, scheduler, step, AND all RNG states AND the dataloader
478
+ position. Dropping the RNG or data position is the classic cause of a loss
479
+ blip on resume (you re-see data / re-sample dropout differently).
480
+
481
+ Writes are atomic (write tmp -> os.replace) so an instance dying mid-save can
482
+ never leave a half-written checkpoint that fails to load.
483
+ """
484
+
485
+ from __future__ import annotations
486
+
487
+ import os
488
+ import glob
489
+ import random
490
+ from dataclasses import asdict
491
+
492
+ import numpy as np
493
+ import torch
494
+
495
+
496
+ def _rng_state() -> dict:
497
+ state = {
498
+ "python": random.getstate(),
499
+ "numpy": np.random.get_state(),
500
+ "torch": torch.get_rng_state(),
501
+ }
502
+ if torch.cuda.is_available():
503
+ state["cuda"] = torch.cuda.get_rng_state_all()
504
+ return state
505
+
506
+
507
+ def _set_rng_state(state: dict) -> None:
508
+ random.setstate(state["python"])
509
+ np.random.set_state(state["numpy"])
510
+ torch.set_rng_state(state["torch"])
511
+ if "cuda" in state and torch.cuda.is_available():
512
+ torch.cuda.set_rng_state_all(state["cuda"])
513
+
514
+
515
+ def save_checkpoint(path, *, model, optimizer, scheduler, step,
516
+ config=None, data_state=None) -> None:
517
+ """Atomically write a complete checkpoint to `path`."""
518
+ payload = {
519
+ "model": model.state_dict(),
520
+ "optimizer": optimizer.state_dict(),
521
+ "scheduler": scheduler.state_dict() if scheduler is not None else None,
522
+ "step": step,
523
+ "rng": _rng_state(),
524
+ "data_state": data_state,
525
+ "config": asdict(config) if hasattr(config, "__dataclass_fields__") else config,
526
+ }
527
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
528
+ tmp = f"{path}.tmp.{os.getpid()}"
529
+ torch.save(payload, tmp)
530
+ os.replace(tmp, path) # atomic on POSIX and Windows
531
+
532
+
533
+ def load_checkpoint(path, *, model, optimizer=None, scheduler=None,
534
+ map_location="cpu", restore_rng=True) -> dict:
535
+ """Restore in-place. Returns the raw payload (for step, data_state, config)."""
536
+ ck = torch.load(path, map_location=map_location, weights_only=False)
537
+ model.load_state_dict(ck["model"])
538
+ if optimizer is not None and ck.get("optimizer") is not None:
539
+ optimizer.load_state_dict(ck["optimizer"])
540
+ if scheduler is not None and ck.get("scheduler") is not None:
541
+ scheduler.load_state_dict(ck["scheduler"])
542
+ if restore_rng and ck.get("rng") is not None:
543
+ _set_rng_state(ck["rng"])
544
+ return ck
545
+
546
+
547
+ def latest_checkpoint(directory) -> str | None:
548
+ """Highest-step checkpoint matching ckpt_*.pt, or None."""
549
+ paths = glob.glob(os.path.join(directory, "ckpt_*.pt"))
550
+ if not paths:
551
+ return None
552
+ return max(paths, key=lambda p: int(os.path.basename(p)[5:-3]))
553
+
554
+
555
+ def rotate_checkpoints(directory, keep_last: int, protect: set[str] | None = None) -> None:
556
+ """Delete oldest ckpt_*.pt beyond keep_last. `protect` = basenames to keep."""
557
+ protect = protect or set()
558
+ paths = sorted(
559
+ glob.glob(os.path.join(directory, "ckpt_*.pt")),
560
+ key=lambda p: int(os.path.basename(p)[5:-3]),
561
+ )
562
+ deletable = [p for p in paths if os.path.basename(p) not in protect]
563
+ for p in deletable[:-keep_last] if keep_last > 0 else deletable:
564
+ try:
565
+ os.remove(p)
566
+ except OSError:
567
+ pass
568
+ ```
569
+
570
+ ===== FILE: src/matilda/monitor.py =====
571
+ ```python
572
+ """Throughput / utilization observability.
573
+
574
+ MFU (Model FLOPs Utilization) is the headline number a training engineer lives
575
+ in: what fraction of the GPU's theoretical bf16 throughput you actually extract.
576
+ We also track a rolling step-time window so a *degradation* mid-run (thermal
577
+ throttling, a noisy Vast neighbour) is visible, not just the instantaneous rate.
578
+ """
579
+
580
+ from __future__ import annotations
581
+
582
+ import time
583
+ from collections import deque
584
+
585
+ # Peak bf16 *dense* TFLOPs (no 2:4 sparsity). Substring-matched on device name.
586
+ PEAK_TFLOPS_BF16 = {
587
+ "A100": 312.0,
588
+ "H100": 494.0,
589
+ "H800": 494.0,
590
+ "4090": 165.0,
591
+ "3090": 71.0,
592
+ "3060": 51.0,
593
+ "T4": 65.0, # fp16; T4 has no native bf16 (Turing) -> emulated, ignore MFU
594
+ "A10": 125.0,
595
+ "L4": 121.0,
596
+ }
597
+
598
+
599
+ def peak_tflops(device_name: str, default: float = 312.0) -> float:
600
+ for key, val in PEAK_TFLOPS_BF16.items():
601
+ if key in device_name:
602
+ return val
603
+ return default
604
+
605
+
606
+ def mfu(n_params_active: int, tokens_per_step: int, dt_seconds: float,
607
+ peak_flops_per_sec: float) -> float:
608
+ """6N flops/token (forward+backward, matmul-dominated approximation)."""
609
+ if dt_seconds <= 0:
610
+ return 0.0
611
+ achieved = 6 * n_params_active * tokens_per_step / dt_seconds
612
+ return achieved / peak_flops_per_sec
613
+
614
+
615
+ class Throughput:
616
+ """Rolling step-time tracker; reports tokens/sec and MFU."""
617
+
618
+ def __init__(self, n_params_active, tokens_per_step, peak_flops_per_sec,
619
+ window=50):
620
+ self.n = n_params_active
621
+ self.tps = tokens_per_step
622
+ self.peak = peak_flops_per_sec
623
+ self.times = deque(maxlen=window)
624
+ self._t0 = None
625
+
626
+ def tick(self) -> dict | None:
627
+ now = time.perf_counter()
628
+ if self._t0 is None:
629
+ self._t0 = now
630
+ return None
631
+ dt = now - self._t0
632
+ self._t0 = now
633
+ self.times.append(dt)
634
+ avg = sum(self.times) / len(self.times)
635
+ return {
636
+ "dt_s": dt,
637
+ "dt_avg_s": avg,
638
+ "tokens_per_s": self.tps / dt,
639
+ "mfu": mfu(self.n, self.tps, dt, self.peak),
640
+ "mfu_avg": mfu(self.n, self.tps, avg, self.peak),
641
+ }
642
+ ```
643
+
644
+ ===== FILE: src/matilda/data.py =====
645
+ ```python
646
+ """Data streams + tokenized-shard tooling.
647
+
648
+ All streams expose the same interface so the training loop never changes when
649
+ we swap synthetic data for real tokenized FineWeb shards:
650
+
651
+ x, y = stream.next() # (B, T) input, (B, T) targets
652
+ state = stream.state_dict() # resumable position / RNG
653
+ stream.load_state_dict(state)
654
+
655
+ On-disk format: token ids as a flat `uint16` `.bin` (valid for vocab <= 65535,
656
+ which GPT-2's 50257 satisfies). A `manifest.json` records per-shard token counts
657
+ and SHA-256 so the prepared data is verifiable and reproducible.
658
+ """
659
+
660
+ from __future__ import annotations
661
+
662
+ import os
663
+ import json
664
+ import glob
665
+ import hashlib
666
+
667
+ import numpy as np
668
+ import torch
669
+
670
+ DTYPE = np.uint16
671
+
672
+
673
+ # --------------------------------------------------------------------------
674
+ # shard writing / verification (used by scripts/prepare_data.py, unit-tested)
675
+ # --------------------------------------------------------------------------
676
+ def sha256_file(path, chunk=1 << 20) -> str:
677
+ h = hashlib.sha256()
678
+ with open(path, "rb") as f:
679
+ for block in iter(lambda: f.read(chunk), b""):
680
+ h.update(block)
681
+ return h.hexdigest()
682
+
683
+
684
+ class ShardWriter:
685
+ """Accumulate token ids and flush fixed-size `.bin` shards + a manifest."""
686
+
687
+ def __init__(self, out_dir, shard_tokens=100_000_000, prefix="shard"):
688
+ self.out_dir = out_dir
689
+ self.shard_tokens = shard_tokens
690
+ self.prefix = prefix
691
+ os.makedirs(out_dir, exist_ok=True)
692
+ self._buf: list[np.ndarray] = []
693
+ self._buf_len = 0
694
+ self._shard_idx = 0
695
+ self.total_tokens = 0
696
+ self.manifest_entries: list[dict] = []
697
+
698
+ def add(self, tokens) -> None:
699
+ arr = np.asarray(tokens, dtype=DTYPE)
700
+ self._buf.append(arr)
701
+ self._buf_len += arr.size
702
+ self.total_tokens += arr.size
703
+ while self._buf_len >= self.shard_tokens:
704
+ self._flush(self.shard_tokens)
705
+
706
+ def _flush(self, n) -> None:
707
+ flat = np.concatenate(self._buf) if len(self._buf) > 1 else self._buf[0]
708
+ out, rest = flat[:n], flat[n:]
709
+ path = os.path.join(self.out_dir, f"{self.prefix}_{self._shard_idx:05d}.bin")
710
+ out.tofile(path)
711
+ self.manifest_entries.append({
712
+ "file": os.path.basename(path),
713
+ "tokens": int(out.size),
714
+ "sha256": sha256_file(path),
715
+ })
716
+ self._shard_idx += 1
717
+ self._buf = [rest] if rest.size else []
718
+ self._buf_len = rest.size
719
+
720
+ def close(self, meta: dict | None = None) -> dict:
721
+ if self._buf_len > 0:
722
+ self._flush(self._buf_len) # final partial shard
723
+ manifest = {
724
+ "total_tokens": int(self.total_tokens),
725
+ "shards": self.manifest_entries,
726
+ **(meta or {}),
727
+ }
728
+ with open(os.path.join(self.out_dir, "manifest.json"), "w") as f:
729
+ json.dump(manifest, f, indent=2)
730
+ return manifest
731
+
732
+
733
+ def verify_manifest(out_dir) -> bool:
734
+ """Re-checksum every shard against the manifest. Raises on mismatch."""
735
+ with open(os.path.join(out_dir, "manifest.json")) as f:
736
+ manifest = json.load(f)
737
+ for entry in manifest["shards"]:
738
+ path = os.path.join(out_dir, entry["file"])
739
+ actual = sha256_file(path)
740
+ if actual != entry["sha256"]:
741
+ raise ValueError(f"checksum mismatch for {entry['file']}")
742
+ if os.path.getsize(path) != entry["tokens"] * 2: # uint16 = 2 bytes
743
+ raise ValueError(f"size mismatch for {entry['file']}")
744
+ return True
745
+
746
+
747
+ def shard_paths(out_dir) -> list[str]:
748
+ with open(os.path.join(out_dir, "manifest.json")) as f:
749
+ manifest = json.load(f)
750
+ return [os.path.join(out_dir, e["file"]) for e in manifest["shards"]]
751
+
752
+
753
+ # --------------------------------------------------------------------------
754
+ # streams
755
+ # --------------------------------------------------------------------------
756
+ class SyntheticStream:
757
+ """Deterministic random tokens. For dev/CI and loop testing on CPU."""
758
+
759
+ def __init__(self, vocab_size, batch_size, seq_len, seed=0, device="cpu"):
760
+ self.vocab_size = vocab_size
761
+ self.B = batch_size
762
+ self.T = seq_len
763
+ self.device = device
764
+ self.gen = torch.Generator().manual_seed(seed)
765
+ self.pos = 0
766
+
767
+ def next(self):
768
+ seq = torch.randint(0, self.vocab_size, (self.B, self.T + 1),
769
+ generator=self.gen)
770
+ x = seq[:, :-1].contiguous().to(self.device)
771
+ y = seq[:, 1:].contiguous().to(self.device)
772
+ self.pos += 1
773
+ return x, y
774
+
775
+ def state_dict(self):
776
+ return {"pos": self.pos, "gen": self.gen.get_state()}
777
+
778
+ def load_state_dict(self, s):
779
+ self.pos = s["pos"]
780
+ self.gen.set_state(s["gen"])
781
+
782
+
783
+ class BinStream:
784
+ """Packed windows sampled from memory-mapped uint16 token shards.
785
+
786
+ Each batch element is a random T+1 window from a shard chosen with
787
+ probability proportional to its size; x/y are the next-token shift. Random
788
+ sampling (rather than a sequential cursor) means epochs are implicit and
789
+ resume only needs the RNG state.
790
+ """
791
+
792
+ def __init__(self, bin_paths, batch_size, seq_len, seed=0, device="cpu"):
793
+ assert bin_paths, "no shards provided"
794
+ self.paths = list(bin_paths)
795
+ self.B = batch_size
796
+ self.T = seq_len
797
+ self.device = device
798
+ self.arrays = [np.memmap(p, dtype=DTYPE, mode="r") for p in self.paths]
799
+ self.sizes = torch.tensor([float(a.size) for a in self.arrays])
800
+ assert (self.sizes > seq_len + 1).all(), "a shard is smaller than seq_len+1"
801
+ self.weights = self.sizes / self.sizes.sum()
802
+ self.gen = torch.Generator().manual_seed(seed)
803
+ self.pos = 0
804
+
805
+ def next(self):
806
+ shard_ids = torch.multinomial(self.weights, self.B, replacement=True,
807
+ generator=self.gen)
808
+ xb = np.empty((self.B, self.T), dtype=np.int64)
809
+ yb = np.empty((self.B, self.T), dtype=np.int64)
810
+ for i, sid in enumerate(shard_ids.tolist()):
811
+ arr = self.arrays[sid]
812
+ hi = arr.size - (self.T + 1)
813
+ start = int(torch.randint(0, hi + 1, (1,), generator=self.gen).item())
814
+ window = arr[start:start + self.T + 1].astype(np.int64)
815
+ xb[i] = window[:-1]
816
+ yb[i] = window[1:]
817
+ self.pos += 1
818
+ x = torch.from_numpy(xb).to(self.device)
819
+ y = torch.from_numpy(yb).to(self.device)
820
+ return x, y
821
+
822
+ def state_dict(self):
823
+ return {"pos": self.pos, "gen": self.gen.get_state()}
824
+
825
+ def load_state_dict(self, s):
826
+ self.pos = s["pos"]
827
+ self.gen.set_state(s["gen"])
828
+ ```
829
+
830
+ ===== FILE: src/matilda/train.py =====
831
+ ```python
832
+ """Training loop with the reliability guards a long run needs.
833
+
834
+ Designed so an overnight Vast run survives the things that actually kill runs:
835
+ - one bad batch (NaN/Inf loss or grad) -> skip it, log loudly, keep going
836
+ - spot-instance SIGTERM -> checkpoint before exiting
837
+ - process death -> resume bit-for-bit from latest checkpoint on restart
838
+
839
+ Throughput (MFU, tokens/s, step-time) is logged every `log_every` steps. The
840
+ data source is any object with .next()/.state_dict()/.load_state_dict() (see
841
+ data.py), so swapping synthetic data for real FineWeb shards changes nothing.
842
+ """
843
+
844
+ from __future__ import annotations
845
+
846
+ import os
847
+ import math
848
+ import time
849
+ import signal
850
+ from dataclasses import dataclass, field
851
+
852
+ import torch
853
+
854
+ from .model import Transformer
855
+ from .config import ModelConfig
856
+ from .optim import build_adamw, cosine_warmup_scheduler
857
+ from .monitor import Throughput, peak_tflops
858
+ from .checkpoint import (
859
+ save_checkpoint, load_checkpoint, latest_checkpoint, rotate_checkpoints,
860
+ )
861
+
862
+
863
+ @dataclass
864
+ class TrainConfig:
865
+ total_steps: int = 1000
866
+ warmup_steps: int = 100
867
+ grad_accum: int = 1
868
+ lr: float = 3e-4
869
+ weight_decay: float = 0.1
870
+ grad_clip: float = 1.0
871
+ min_lr_ratio: float = 0.1
872
+
873
+ batch_size: int = 8
874
+ seq_len: int = 1024
875
+
876
+ log_every: int = 10
877
+ ckpt_every: int = 500
878
+ keep_last: int = 3
879
+ ckpt_dir: str = "checkpoints"
880
+
881
+ device: str = "cuda"
882
+ dtype: str = "bfloat16" # bf16 on Ampere+, fp32 fallback on CPU
883
+ compile: bool = False
884
+ seed: int = 1234
885
+ max_skips: int = 20 # abort if too many bad batches in a row
886
+ wandb_project: str | None = None
887
+
888
+
889
+ class Trainer:
890
+ def __init__(self, model_cfg: ModelConfig, train_cfg: TrainConfig, stream):
891
+ self.mcfg = model_cfg
892
+ self.cfg = train_cfg
893
+ self.stream = stream
894
+ self.step = 0
895
+ self.consecutive_skips = 0
896
+ self._interrupted = False
897
+
898
+ torch.manual_seed(train_cfg.seed)
899
+ self.device = torch.device(
900
+ train_cfg.device if torch.cuda.is_available()
901
+ or train_cfg.device == "cpu" else "cpu")
902
+
903
+ self.model = Transformer(model_cfg).to(self.device)
904
+ if train_cfg.compile:
905
+ self.model = torch.compile(self.model)
906
+ self.opt = build_adamw(self.model, lr=train_cfg.lr,
907
+ weight_decay=train_cfg.weight_decay)
908
+ self.sched = cosine_warmup_scheduler(
909
+ self.opt, train_cfg.warmup_steps, train_cfg.total_steps,
910
+ train_cfg.min_lr_ratio)
911
+
912
+ # bf16 only where supported; CPU/T4 fall back to fp32 for correctness.
913
+ want_bf16 = (train_cfg.dtype == "bfloat16"
914
+ and self.device.type == "cuda"
915
+ and torch.cuda.is_bf16_supported())
916
+ self.amp_dtype = torch.bfloat16 if want_bf16 else None
917
+
918
+ tokens_per_step = (train_cfg.batch_size * train_cfg.seq_len
919
+ * train_cfg.grad_accum)
920
+ dev_name = (torch.cuda.get_device_name(self.device)
921
+ if self.device.type == "cuda" else "cpu")
922
+ self.monitor = Throughput(
923
+ n_params_active=self._active_params(),
924
+ tokens_per_step=tokens_per_step,
925
+ peak_flops_per_sec=peak_tflops(dev_name) * 1e12,
926
+ )
927
+ self.wandb = self._init_wandb()
928
+ self._install_signal_handlers()
929
+
930
+ # --- helpers -----------------------------------------------------------
931
+ def _active_params(self):
932
+ m = self.model._orig_mod if hasattr(self.model, "_orig_mod") else self.model
933
+ return m.num_params(non_embedding=True)
934
+
935
+ def _init_wandb(self):
936
+ if not self.cfg.wandb_project:
937
+ return None
938
+ try:
939
+ import wandb
940
+ wandb.init(project=self.cfg.wandb_project,
941
+ config={**self.mcfg.to_dict(), **vars(self.cfg)})
942
+ return wandb
943
+ except Exception as e:
944
+ print(f"[warn] wandb disabled: {e}")
945
+ return None
946
+
947
+ def _install_signal_handlers(self):
948
+ def handler(signum, frame):
949
+ print(f"[signal] {signum} received -> checkpoint and exit")
950
+ self._interrupted = True
951
+ for sig in (signal.SIGINT, signal.SIGTERM):
952
+ try:
953
+ signal.signal(sig, handler)
954
+ except (ValueError, OSError):
955
+ pass # not in main thread (e.g. under pytest) -> skip
956
+
957
+ def _autocast(self):
958
+ if self.amp_dtype is not None:
959
+ return torch.autocast(device_type="cuda", dtype=self.amp_dtype)
960
+ return torch.autocast(device_type="cpu", enabled=False)
961
+
962
+ # --- checkpoint --------------------------------------------------------
963
+ def _ckpt_path(self):
964
+ return os.path.join(self.cfg.ckpt_dir, f"ckpt_{self.step}.pt")
965
+
966
+ def save(self):
967
+ save_checkpoint(self._ckpt_path(), model=self.model, optimizer=self.opt,
968
+ scheduler=self.sched, step=self.step, config=self.mcfg,
969
+ data_state=self.stream.state_dict())
970
+ rotate_checkpoints(self.cfg.ckpt_dir, self.cfg.keep_last)
971
+
972
+ def maybe_resume(self):
973
+ path = latest_checkpoint(self.cfg.ckpt_dir)
974
+ if path is None:
975
+ return False
976
+ ck = load_checkpoint(path, model=self.model, optimizer=self.opt,
977
+ scheduler=self.sched,
978
+ map_location=self.device)
979
+ self.step = ck["step"]
980
+ if ck.get("data_state") is not None:
981
+ self.stream.load_state_dict(ck["data_state"])
982
+ print(f"[resume] from {path} at step {self.step}")
983
+ return True
984
+
985
+ # --- one optimizer step (grad accum + guards) --------------------------
986
+ def _step(self):
987
+ self.opt.zero_grad(set_to_none=True)
988
+ total_loss = 0.0
989
+ for micro in range(self.cfg.grad_accum):
990
+ x, y = self.stream.next()
991
+ x, y = x.to(self.device), y.to(self.device)
992
+ sync = (micro == self.cfg.grad_accum - 1)
993
+ ctx = (self.model.no_sync()
994
+ if (not sync and hasattr(self.model, "no_sync"))
995
+ else _nullcontext())
996
+ with ctx, self._autocast():
997
+ _, loss = self.model(x, y)
998
+ loss = loss / self.cfg.grad_accum
999
+ if not torch.isfinite(loss):
1000
+ return None # bad micro-batch -> abort this step
1001
+ loss.backward()
1002
+ total_loss += loss.item()
1003
+
1004
+ grad_norm = torch.nn.utils.clip_grad_norm_(
1005
+ self.model.parameters(), self.cfg.grad_clip)
1006
+ if not torch.isfinite(grad_norm):
1007
+ return None # non-finite grad -> skip update
1008
+
1009
+ self.opt.step()
1010
+ self.sched.step()
1011
+ return total_loss, grad_norm.item()
1012
+
1013
+ # --- main loop ---------------------------------------------------------
1014
+ def train(self):
1015
+ os.makedirs(self.cfg.ckpt_dir, exist_ok=True)
1016
+ self.maybe_resume()
1017
+ self.model.train()
1018
+ while self.step < self.cfg.total_steps:
1019
+ result = self._step()
1020
+ if result is None:
1021
+ self.consecutive_skips += 1
1022
+ print(f"[nan-guard] step {self.step} skipped "
1023
+ f"({self.consecutive_skips}/{self.cfg.max_skips})")
1024
+ self.opt.zero_grad(set_to_none=True)
1025
+ if self.consecutive_skips >= self.cfg.max_skips:
1026
+ raise RuntimeError("too many non-finite steps; aborting run")
1027
+ continue
1028
+ self.consecutive_skips = 0
1029
+ loss, grad_norm = result
1030
+ self.step += 1
1031
+
1032
+ stats = self.monitor.tick()
1033
+ if self.step % self.cfg.log_every == 0:
1034
+ self._log(loss, grad_norm, stats)
1035
+ if self.step % self.cfg.ckpt_every == 0:
1036
+ self.save()
1037
+ if self._interrupted:
1038
+ self.save()
1039
+ print(f"[exit] checkpointed at step {self.step}")
1040
+ break
1041
+ else:
1042
+ self.save() # final checkpoint on clean completion
1043
+ return self.step
1044
+
1045
+ def _log(self, loss, grad_norm, stats):
1046
+ lr = self.sched.get_last_lr()[0]
1047
+ msg = (f"step {self.step:>6} | loss {loss:7.4f} | lr {lr:.2e} "
1048
+ f"| gnorm {grad_norm:5.2f}")
1049
+ if stats:
1050
+ msg += (f" | {stats['tokens_per_s']:8.0f} tok/s "
1051
+ f"| mfu {stats['mfu_avg']*100:4.1f}%")
1052
+ print(msg)
1053
+ if self.wandb:
1054
+ row = {"loss": loss, "lr": lr, "grad_norm": grad_norm}
1055
+ if stats:
1056
+ row.update({"tokens_per_s": stats["tokens_per_s"],
1057
+ "mfu": stats["mfu_avg"],
1058
+ "step_time_s": stats["dt_avg_s"]})
1059
+ self.wandb.log(row, step=self.step)
1060
+
1061
+
1062
+ class _nullcontext:
1063
+ def __enter__(self):
1064
+ return None
1065
+
1066
+ def __exit__(self, *exc):
1067
+ return False
1068
+ ```
1069
+
1070
+ ===== FILE: scripts/prepare_data.py =====
1071
+ ```python
1072
+ """Tokenize a HuggingFace text dataset into verifiable uint16 shards.
1073
+
1074
+ Default: FineWeb-Edu sample-10BT (best small-scale benchmark movement, max
1075
+ comparability to Pythia/SmolLM). Dataset-agnostic by design so DCLM /
1076
+ Nemotron-CC become drop-in data-ablation rows:
1077
+
1078
+ python scripts/prepare_data.py --target-tokens 3_000_000_000 \
1079
+ --dataset HuggingFaceFW/fineweb-edu --name sample-10BT --out-dir data/fwedu
1080
+
1081
+ # ablation rows (same flags, different source):
1082
+ --dataset mlfoundations/dclm-baseline-1.0 --out-dir data/dclm
1083
+ --dataset nvidia/Nemotron-CC --out-dir data/nemotron
1084
+
1085
+ Streams the source (no full download), so disk holds only the tokenized output.
1086
+ """
1087
+
1088
+ from __future__ import annotations
1089
+
1090
+ import sys
1091
+ import argparse
1092
+ from pathlib import Path
1093
+
1094
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
1095
+
1096
+ from matilda.data import ShardWriter, verify_manifest # noqa: E402
1097
+
1098
+
1099
+ def main():
1100
+ ap = argparse.ArgumentParser()
1101
+ ap.add_argument("--dataset", default="HuggingFaceFW/fineweb-edu")
1102
+ ap.add_argument("--name", default="sample-10BT")
1103
+ ap.add_argument("--split", default="train")
1104
+ ap.add_argument("--text-key", default="text")
1105
+ ap.add_argument("--tokenizer", default="gpt2")
1106
+ ap.add_argument("--target-tokens", type=int, default=3_000_000_000)
1107
+ ap.add_argument("--shard-tokens", type=int, default=100_000_000)
1108
+ ap.add_argument("--out-dir", default="data/fwedu")
1109
+ args = ap.parse_args()
1110
+
1111
+ import tiktoken
1112
+ from datasets import load_dataset
1113
+
1114
+ enc = tiktoken.get_encoding(args.tokenizer)
1115
+ eot = enc.eot_token
1116
+ assert enc.n_vocab <= 65535, "vocab > uint16; use a smaller tokenizer"
1117
+
1118
+ ds = load_dataset(args.dataset, name=args.name, split=args.split,
1119
+ streaming=True)
1120
+ writer = ShardWriter(args.out_dir, shard_tokens=args.shard_tokens)
1121
+
1122
+ n_docs = 0
1123
+ for doc in ds:
1124
+ ids = enc.encode_ordinary(doc[args.text_key])
1125
+ ids.append(eot) # document boundary
1126
+ writer.add(ids)
1127
+ n_docs += 1
1128
+ if n_docs % 1000 == 0:
1129
+ print(f"\rdocs={n_docs:,} tokens={writer.total_tokens:,}", end="")
1130
+ if writer.total_tokens >= args.target_tokens:
1131
+ break
1132
+
1133
+ manifest = writer.close(meta={
1134
+ "dataset": args.dataset, "name": args.name, "split": args.split,
1135
+ "tokenizer": args.tokenizer, "eot_token": eot, "n_docs": n_docs,
1136
+ })
1137
+ print(f"\nwrote {manifest['total_tokens']:,} tokens in "
1138
+ f"{len(manifest['shards'])} shards -> {args.out_dir}")
1139
+ verify_manifest(args.out_dir)
1140
+ print("manifest verified (checksums + sizes OK)")
1141
+
1142
+
1143
+ if __name__ == "__main__":
1144
+ main()
1145
+ ```
1146
+
1147
+ ===== FILE: tests/test_model.py =====
1148
+ ```python
1149
+ """Sanity tests that gate the paid run. All must be green on Colab first.
1150
+
1151
+ - test_forward_shapes / test_weight_tying / test_param_count: wiring is correct
1152
+ - test_causal_mask: no information leaks from future tokens (the bug that
1153
+ silently inflates eval and is invisible in the loss curve)
1154
+ - test_overfit_single_batch: the model can actually learn (loss -> ~0 on one
1155
+ fixed batch). The cheapest, highest-signal correctness check in ML.
1156
+ """
1157
+
1158
+ import torch
1159
+ import pytest
1160
+
1161
+ from matilda import Transformer, ModelConfig, DEV_TINY
1162
+
1163
+
1164
+ def _tiny():
1165
+ return Transformer(DEV_TINY).eval()
1166
+
1167
+
1168
+ def test_forward_shapes():
1169
+ model = _tiny()
1170
+ B, T = 2, 16
1171
+ idx = torch.randint(0, DEV_TINY.vocab_size, (B, T))
1172
+ logits, loss = model(idx)
1173
+ assert logits.shape == (B, T, DEV_TINY.vocab_size)
1174
+ assert loss is None
1175
+ targets = torch.randint(0, DEV_TINY.vocab_size, (B, T))
1176
+ _, loss = model(idx, targets)
1177
+ assert loss is not None and loss.ndim == 0
1178
+
1179
+
1180
+ def test_weight_tying():
1181
+ model = _tiny()
1182
+ assert model.lm_head.weight.data_ptr() == model.embed.weight.data_ptr()
1183
+
1184
+
1185
+ def test_loss_at_init_is_near_uniform():
1186
+ # untrained model should be ~ -log(1/V) = log(V)
1187
+ model = _tiny()
1188
+ idx = torch.randint(0, DEV_TINY.vocab_size, (4, 32))
1189
+ tgt = torch.randint(0, DEV_TINY.vocab_size, (4, 32))
1190
+ _, loss = model(idx, tgt)
1191
+ expected = torch.log(torch.tensor(float(DEV_TINY.vocab_size)))
1192
+ assert abs(loss.item() - expected.item()) < 1.0
1193
+
1194
+
1195
+ def test_causal_mask_no_future_leak():
1196
+ """Changing token at position t must not alter logits at positions < t."""
1197
+ model = _tiny()
1198
+ torch.manual_seed(0)
1199
+ idx = torch.randint(0, DEV_TINY.vocab_size, (1, 24))
1200
+ with torch.no_grad():
1201
+ base, _ = model(idx)
1202
+ idx2 = idx.clone()
1203
+ idx2[0, -1] = (idx2[0, -1] + 1) % DEV_TINY.vocab_size # perturb last token
1204
+ perturbed, _ = model(idx2)
1205
+ # all positions except the last must be identical
1206
+ assert torch.allclose(base[:, :-1], perturbed[:, :-1], atol=1e-5)
1207
+ assert not torch.allclose(base[:, -1], perturbed[:, -1], atol=1e-5)
1208
+
1209
+
1210
+ def test_gqa_kv_head_counts():
1211
+ model = _tiny()
1212
+ attn = model.blocks[0].attn
1213
+ assert attn.wk.out_features == DEV_TINY.n_kv_heads * DEV_TINY.head_dim
1214
+ assert attn.wq.out_features == DEV_TINY.n_heads * DEV_TINY.head_dim
1215
+
1216
+
1217
+ @pytest.mark.slow
1218
+ def test_overfit_single_batch():
1219
+ """The model must drive loss toward zero on one fixed batch."""
1220
+ cfg = ModelConfig(vocab_size=256, max_seq_len=64, d_model=128,
1221
+ n_layers=2, n_heads=4, n_kv_heads=2)
1222
+ model = Transformer(cfg).train()
1223
+ torch.manual_seed(0)
1224
+ idx = torch.randint(0, cfg.vocab_size, (4, 32))
1225
+ tgt = torch.randint(0, cfg.vocab_size, (4, 32))
1226
+ opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
1227
+ losses = []
1228
+ for _ in range(300):
1229
+ _, loss = model(idx, tgt)
1230
+ opt.zero_grad(set_to_none=True)
1231
+ loss.backward()
1232
+ opt.step()
1233
+ losses.append(loss.item())
1234
+ assert losses[-1] < 0.1, f"failed to overfit; final loss={losses[-1]:.3f}"
1235
+ ```
1236
+
1237
+ ===== FILE: tests/test_checkpoint.py =====
1238
+ ```python
1239
+ """Resume must continue *identically* to an uninterrupted run.
1240
+
1241
+ Strategy: run a short reference training. Run it again but checkpoint halfway,
1242
+ throw the objects away, build *fresh* model/optimizer/scheduler/data-stream,
1243
+ restore from the checkpoint, and continue. The post-resume per-step losses must
1244
+ match the reference run's second half exactly. If any piece of state is missing
1245
+ (opt moments, scheduler, RNG, data position) the curves diverge and this fails.
1246
+ """
1247
+
1248
+ import os
1249
+ import random
1250
+
1251
+ import numpy as np
1252
+ import torch
1253
+
1254
+ from matilda import Transformer, ModelConfig
1255
+ from matilda.optim import build_adamw, cosine_warmup_scheduler
1256
+ from matilda.checkpoint import (
1257
+ save_checkpoint, load_checkpoint, latest_checkpoint, rotate_checkpoints,
1258
+ )
1259
+
1260
+ CFG = ModelConfig(vocab_size=128, max_seq_len=32, d_model=64,
1261
+ n_layers=2, n_heads=4, n_kv_heads=2)
1262
+ TOTAL, WARMUP, HALF = 12, 2, 6
1263
+
1264
+
1265
+ class SyntheticStream:
1266
+ """Resumable deterministic batch source (own generator => independent RNG)."""
1267
+
1268
+ def __init__(self, seed, B=4, T=16):
1269
+ self.B, self.T = B, T
1270
+ self.gen = torch.Generator().manual_seed(seed)
1271
+ self.pos = 0
1272
+
1273
+ def next(self):
1274
+ x = torch.randint(0, CFG.vocab_size, (self.B, self.T), generator=self.gen)
1275
+ y = torch.randint(0, CFG.vocab_size, (self.B, self.T), generator=self.gen)
1276
+ self.pos += 1
1277
+ return x, y
1278
+
1279
+ def state_dict(self):
1280
+ return {"pos": self.pos, "gen": self.gen.get_state()}
1281
+
1282
+ def load_state_dict(self, s):
1283
+ self.pos = s["pos"]
1284
+ self.gen.set_state(s["gen"])
1285
+
1286
+
1287
+ def _seed_all(seed=1234):
1288
+ random.seed(seed)
1289
+ np.random.seed(seed)
1290
+ torch.manual_seed(seed)
1291
+
1292
+
1293
+ def _build():
1294
+ model = Transformer(CFG).train()
1295
+ opt = build_adamw(model, lr=1e-3)
1296
+ sched = cosine_warmup_scheduler(opt, WARMUP, TOTAL)
1297
+ return model, opt, sched
1298
+
1299
+
1300
+ def _train_steps(model, opt, sched, stream, n):
1301
+ losses = []
1302
+ for _ in range(n):
1303
+ x, y = stream.next()
1304
+ _, loss = model(x, y)
1305
+ opt.zero_grad(set_to_none=True)
1306
+ loss.backward()
1307
+ opt.step()
1308
+ sched.step()
1309
+ losses.append(loss.item())
1310
+ return losses
1311
+
1312
+
1313
+ def test_resume_is_bit_for_bit(tmp_path):
1314
+ # --- reference: uninterrupted run ---
1315
+ _seed_all()
1316
+ m, o, s = _build()
1317
+ ref_stream = SyntheticStream(seed=42)
1318
+ ref_losses = _train_steps(m, o, s, ref_stream, TOTAL)
1319
+
1320
+ # --- interrupted run: train HALF, checkpoint, drop everything ---
1321
+ _seed_all()
1322
+ m, o, s = _build()
1323
+ stream = SyntheticStream(seed=42)
1324
+ first_half = _train_steps(m, o, s, stream, HALF)
1325
+ assert first_half == ref_losses[:HALF], "training is not deterministic"
1326
+
1327
+ ckpt = os.path.join(tmp_path, f"ckpt_{HALF}.pt")
1328
+ save_checkpoint(ckpt, model=m, optimizer=o, scheduler=s, step=HALF,
1329
+ config=CFG, data_state=stream.state_dict())
1330
+
1331
+ # --- fresh objects, restore, continue ---
1332
+ m2, o2, s2 = _build() # fresh random init + zeroed moments
1333
+ stream2 = SyntheticStream(seed=999) # deliberately wrong seed...
1334
+ ck = load_checkpoint(ckpt, model=m2, optimizer=o2, scheduler=s2)
1335
+ stream2.load_state_dict(ck["data_state"]) # ...corrected by restore
1336
+ assert ck["step"] == HALF
1337
+
1338
+ resumed = _train_steps(m2, o2, s2, stream2, TOTAL - HALF)
1339
+
1340
+ for i, (a, b) in enumerate(zip(resumed, ref_losses[HALF:])):
1341
+ assert abs(a - b) < 1e-6, f"resume diverged at step {HALF+i}: {a} vs {b}"
1342
+
1343
+
1344
+ def test_latest_and_rotation(tmp_path):
1345
+ for step in (10, 20, 30, 40):
1346
+ p = os.path.join(tmp_path, f"ckpt_{step}.pt")
1347
+ torch.save({"step": step}, p)
1348
+ assert latest_checkpoint(tmp_path).endswith("ckpt_40.pt")
1349
+
1350
+ rotate_checkpoints(tmp_path, keep_last=2, protect={"ckpt_10.pt"})
1351
+ remaining = sorted(os.path.basename(p) for p in
1352
+ __import__("glob").glob(os.path.join(tmp_path, "ckpt_*.pt")))
1353
+ # keep last 2 (30, 40) + protected 10; drop 20
1354
+ assert remaining == ["ckpt_10.pt", "ckpt_30.pt", "ckpt_40.pt"]
1355
+ ```
1356
+
1357
+ ===== FILE: tests/test_train.py =====
1358
+ ```python
1359
+ """Training-loop reliability guards (all CPU-testable)."""
1360
+
1361
+ import os
1362
+ import glob
1363
+
1364
+ import torch
1365
+ import pytest
1366
+
1367
+ from matilda import ModelConfig
1368
+ from matilda.data import SyntheticStream
1369
+ from matilda.train import Trainer, TrainConfig
1370
+ from matilda.monitor import mfu, peak_tflops
1371
+
1372
+ MCFG = ModelConfig(vocab_size=128, max_seq_len=32, d_model=64,
1373
+ n_layers=2, n_heads=4, n_kv_heads=2)
1374
+
1375
+
1376
+ def _make(tmp_path, **over):
1377
+ kw = dict(total_steps=20, warmup_steps=2, batch_size=4, seq_len=16,
1378
+ log_every=5, ckpt_every=10, keep_last=2, device="cpu",
1379
+ dtype="float32", ckpt_dir=str(tmp_path))
1380
+ kw.update(over)
1381
+ tc = TrainConfig(**kw)
1382
+ stream = SyntheticStream(MCFG.vocab_size, tc.batch_size, tc.seq_len, seed=0)
1383
+ return Trainer(MCFG, tc, stream)
1384
+
1385
+
1386
+ def test_loop_runs_and_checkpoints(tmp_path):
1387
+ t = _make(tmp_path)
1388
+ final = t.train()
1389
+ assert final == 20
1390
+ # final checkpoint on clean completion + rotation kept <= keep_last
1391
+ ckpts = glob.glob(os.path.join(tmp_path, "ckpt_*.pt"))
1392
+ assert len(ckpts) <= 2
1393
+ assert os.path.exists(os.path.join(tmp_path, "ckpt_20.pt"))
1394
+
1395
+
1396
+ def test_loop_resume_continues(tmp_path):
1397
+ # run only 10 steps, leaving a checkpoint at step 10
1398
+ t1 = _make(tmp_path, total_steps=10, ckpt_every=10)
1399
+ assert t1.train() == 10
1400
+ # a fresh trainer in the same dir must resume from step 10, not restart
1401
+ t2 = _make(tmp_path, total_steps=15, ckpt_every=10)
1402
+ assert t2.maybe_resume() is True
1403
+ assert t2.step == 10
1404
+ assert t2.train() == 15
1405
+
1406
+
1407
+ def test_nan_guard_aborts_after_max_skips(tmp_path):
1408
+ t = _make(tmp_path, total_steps=50, max_skips=3)
1409
+ nan = torch.tensor(float("nan"))
1410
+ t.model.forward = lambda x, targets=None: (None, nan) # shadow bound method
1411
+ with pytest.raises(RuntimeError, match="non-finite"):
1412
+ t.train()
1413
+ assert t.step == 0 # never advanced past a bad batch
1414
+
1415
+
1416
+ def test_nan_guard_skips_then_recovers(tmp_path):
1417
+ t = _make(tmp_path, total_steps=5, max_skips=10)
1418
+ real_forward = t.model.forward
1419
+ calls = {"n": 0}
1420
+
1421
+ def flaky(x, targets=None):
1422
+ calls["n"] += 1
1423
+ if calls["n"] <= 2: # first two micro-batches are bad
1424
+ return None, torch.tensor(float("inf"))
1425
+ return real_forward(x, targets)
1426
+
1427
+ t.model.forward = flaky
1428
+ assert t.train() == 5 # recovered and finished
1429
+ assert t.consecutive_skips == 0
1430
+
1431
+
1432
+ def test_mfu_sanity():
1433
+ # 100M params, 500k tokens/step, 2.0s, A100 -> ~0.48 MFU
1434
+ val = mfu(100_000_000, 500_000, 2.0, peak_tflops("A100") * 1e12)
1435
+ assert 0.0 < val < 1.0
1436
+ assert peak_tflops("A100") == 312.0
1437
+ assert peak_tflops("totally-unknown-gpu") == 312.0 # default
1438
+ ```
1439
+
1440
+ ===== FILE: tests/test_data.py =====
1441
+ ```python
1442
+ """Data pipeline: shard writing/verification + BinStream correctness."""
1443
+
1444
+ import os
1445
+ import json
1446
+
1447
+ import numpy as np
1448
+ import pytest
1449
+ import torch
1450
+
1451
+ from matilda.data import (
1452
+ ShardWriter, verify_manifest, shard_paths, BinStream, DTYPE,
1453
+ )
1454
+
1455
+
1456
+ def test_shardwriter_roundtrip_and_manifest(tmp_path):
1457
+ w = ShardWriter(str(tmp_path), shard_tokens=100)
1458
+ # 250 tokens -> two full shards (100) + one partial (50)
1459
+ w.add(list(range(0, 120)))
1460
+ w.add(list(range(120, 250)))
1461
+ manifest = w.close(meta={"tokenizer": "gpt2"})
1462
+
1463
+ assert manifest["total_tokens"] == 250
1464
+ assert [s["tokens"] for s in manifest["shards"]] == [100, 100, 50]
1465
+ assert manifest["tokenizer"] == "gpt2"
1466
+ assert verify_manifest(str(tmp_path)) is True
1467
+
1468
+ # reconstructed token stream matches the input exactly
1469
+ rebuilt = np.concatenate(
1470
+ [np.fromfile(p, dtype=DTYPE) for p in shard_paths(str(tmp_path))])
1471
+ assert rebuilt.tolist() == list(range(250))
1472
+
1473
+
1474
+ def test_verify_detects_corruption(tmp_path):
1475
+ w = ShardWriter(str(tmp_path), shard_tokens=100)
1476
+ w.add(list(range(150)))
1477
+ w.close()
1478
+ # corrupt the first shard's bytes without changing its size
1479
+ p = shard_paths(str(tmp_path))[0]
1480
+ data = bytearray(open(p, "rb").read())
1481
+ data[0] ^= 0xFF
1482
+ open(p, "wb").write(data)
1483
+ with pytest.raises(ValueError, match="checksum mismatch"):
1484
+ verify_manifest(str(tmp_path))
1485
+
1486
+
1487
+ def _write_ramp_bin(path, n):
1488
+ # values 0..n-1 so a correct next-token window always has y == x + 1
1489
+ np.arange(n, dtype=DTYPE).tofile(path)
1490
+
1491
+
1492
+ def test_binstream_shift_is_next_token(tmp_path):
1493
+ p = os.path.join(tmp_path, "ramp.bin")
1494
+ _write_ramp_bin(p, 5000)
1495
+ s = BinStream([p], batch_size=8, seq_len=32, seed=0)
1496
+ x, y = s.next()
1497
+ assert x.shape == (8, 32) and y.shape == (8, 32)
1498
+ assert torch.equal(y, x + 1) # packed next-token target
1499
+
1500
+
1501
+ def test_binstream_resume_is_deterministic(tmp_path):
1502
+ p = os.path.join(tmp_path, "ramp.bin")
1503
+ _write_ramp_bin(p, 5000)
1504
+ s = BinStream([p], batch_size=4, seq_len=16, seed=7)
1505
+ snap = s.state_dict()
1506
+ x1, y1 = s.next()
1507
+ s.load_state_dict(snap)
1508
+ x2, y2 = s.next()
1509
+ assert torch.equal(x1, x2) and torch.equal(y1, y2)
1510
+
1511
+
1512
+ def test_binstream_multishard_weighting(tmp_path):
1513
+ p1 = os.path.join(tmp_path, "a.bin")
1514
+ p2 = os.path.join(tmp_path, "b.bin")
1515
+ _write_ramp_bin(p1, 2000)
1516
+ _write_ramp_bin(p2, 2000)
1517
+ s = BinStream([p1, p2], batch_size=4, seq_len=8, seed=1)
1518
+ x, y = s.next()
1519
+ assert torch.equal(y, x + 1) # still correct across shards
1520
+ ```
docs/DEEPSEEK_REVIEW_PROMPT.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Review Prompt for DeepSeek
2
+
3
+ > Paste everything below into DeepSeek. DeepSeek cannot read your disk, so after
4
+ > the prompt, paste the contents of the files it asks for (or attach them). The
5
+ > file map and paths are included so you both share a mental model.
6
+
7
+ ---
8
+
9
+ ## ROLE
10
+
11
+ You are a senior LLM training-infrastructure engineer reviewing a from-scratch
12
+ small language model project. Be rigorous and skeptical. I want correctness bugs,
13
+ reliability gaps, and anything that would embarrass me in a technical interview —
14
+ not encouragement. Prioritize findings by severity (CRITICAL / HIGH / MEDIUM / LOW).
15
+
16
+ ## WHY THIS PROJECT EXISTS (the job I'm applying for)
17
+
18
+ I'm building this as a portfolio piece for an **AI Training Infrastructure Engineer**
19
+ role at **Maincode** (Melbourne, Australia). Maincode trains "Matilda", the first
20
+ LLM built and trained from scratch in Australia. Key facts about the role:
21
+
22
+ - It is an **infrastructure** role, NOT a research/architecture role. The work is:
23
+ distributed training pipelines, data ingestion/preprocessing, experiment
24
+ management, checkpointing, reproducibility, monitoring/observability, debugging
25
+ long-running (days–weeks) training jobs, optimizing throughput (compute/memory/
26
+ data), and diagnosing failures that appear hours into a run.
27
+ - Explicitly NOT about: wrapping external APIs, prompt engineering, user-facing apps.
28
+ - Stack: Python, PyTorch/JAX, reliable infra for large compute, debugging
29
+ distributed systems and long jobs.
30
+ - They value engineers who understand how systems behave over long runtimes and
31
+ who prefer understanding internals over relying on abstraction.
32
+
33
+ So the project is **deliberately weighted toward operational excellence**
34
+ (checkpoint/resume, fault tolerance, reproducibility, MFU/observability) over
35
+ architectural breadth. The architecture is modern but standard; the infra is the
36
+ flex. Please judge it through that lens.
37
+
38
+ ## ORIGINAL PLAN & KEY DECISIONS (locked)
39
+
40
+ - **Goal:** train a sub-200M-param modern transformer from scratch, end-to-end,
41
+ with a clean ablation table, on a tight budget.
42
+ - **Hardware:** rent ONE A100 80GB on Vast.ai for the single long paid run.
43
+ - **Long paid run = modernized DENSE ~114M, maximize MFU.** Rationale: MoE on a
44
+ single GPU collapses MFU to ~20% (needs expert parallelism across devices);
45
+ dense hits 45–50%. "DeepSeek-inspired" here means the efficiency stack
46
+ (Flash/SDPA, torch.compile, fused optimizer, bf16, Muon, μP, WSD), NOT sparsity.
47
+ A100 has no FP8 (bf16 ceiling; FP8 would need H100).
48
+ - **MoE is built only as a CHEAP SHORT ablation** (~500M tokens, ~$0.60) with an
49
+ honest write-up of the single-GPU MFU drop. Not the headline run.
50
+ - **Tokenizer:** GPT-2 50257 (tiktoken "gpt2") — fits uint16, comparable to Pythia
51
+ baselines. (We caught and avoided a bug from our source primer that paired
52
+ cl100k ~100k vocab with uint16, which overflows 65535.)
53
+ - **Dataset:** FineWeb-Edu sample-10BT primary (best small-scale benchmark
54
+ movement + Pythia comparability). Loader is dataset-agnostic so DCLM /
55
+ Nemotron-CC are drop-in data-ablation rows.
56
+ - **Cost discipline:** only the ONE long run costs real money (~$5–15). Ablations
57
+ ~$0.60 each. ALL correctness validated FREE on Colab/CPU first; a ~$0.20 A100
58
+ smoke test maximizes MFU before committing to the long run.
59
+
60
+ ### Phase plan
61
+ 1. ✅ Model + sanity tests
62
+ 2. ✅ Infra harness (checkpoint/resume, NaN-guard, monitor/MFU, optimizer, loop)
63
+ 3. ✅ Data pipeline (FineWeb→uint16 shards + checksum, mmap BinStream)
64
+ 4. ⏳ NEXT: Colab GPU correctness pass + $0.20 A100 MFU calibration
65
+ 5. Long dense run (~3B tokens)
66
+ 6. Architecture ablations (RoPE/RMSNorm/SwiGLU/GQA/QK-norm on/off)
67
+ 7. Muon vs AdamW
68
+ 8. MoE ablation
69
+ 9. Eval (lm-eval-harness: HellaSwag / ARC-easy / PIQA vs Pythia-160M)
70
+
71
+ ## WHAT IS BUILT (Phases 1–3 complete; 18/18 tests pass on CPU)
72
+
73
+ Repository root on my machine:
74
+ `C:\Users\Swajay\Downloads\trade\matilda-mini\`
75
+
76
+ File map (line counts):
77
+
78
+ ```
79
+ src/matilda/
80
+ config.py (65) frozen dataclass; DEV_TINY + BASE_124M (114M total / 75.5M non-embed)
81
+ model.py (199) dense decoder: RoPE, RMSNorm, SwiGLU, GQA, QK-Norm, weight tying, residual-scaled init
82
+ optim.py (48) AdamW with param groups (no WD on norms/biases/embeddings); cosine+warmup schedule
83
+ checkpoint.py (95) atomic write (tmp->os.replace), rotation, saves model+opt+sched+step+RNG+dataloader pos
84
+ monitor.py (70) MFU, tokens/s, rolling step-time window, per-GPU peak-TFLOPS table
85
+ data.py (182) ShardWriter (+SHA-256 manifest), verify_manifest, SyntheticStream, BinStream (mmap, resumable)
86
+ train.py (236) loop: bf16 autocast, grad-accum + DDP no_sync, grad-clip, NaN/Inf guard, SIGTERM->checkpoint, auto-resume
87
+ __init__.py (4)
88
+ scripts/
89
+ prepare_data.py (73) stream HF dataset (default FineWeb-Edu sample-10BT) -> tokenize gpt2 -> uint16 shards + verified manifest
90
+ tests/ (18 tests total, all green on CPU/torch 2.7.1)
91
+ test_model.py (86) forward shapes, weight-tying, init-loss≈log(V), CAUSAL-MASK-NO-FUTURE-LEAK, GQA head counts, OVERFIT-SINGLE-BATCH
92
+ test_checkpoint.py(116) BIT-FOR-BIT RESUME (post-resume losses match uninterrupted run <1e-6), rotation/latest
93
+ test_train.py (79) loop runs+checkpoints, loop-level resume, NaN-abort, NaN-skip-then-recover, MFU sanity
94
+ test_data.py (78) shard round-trip, CHECKSUM CORRUPTION DETECTION, BinStream next-token shift, deterministic resume, multi-shard
95
+ conftest.py, pytest.ini, requirements.txt
96
+ ```
97
+
98
+ Verified facts:
99
+ - Overfit-one-batch: loss → <0.1 on a fixed batch (model can learn).
100
+ - Causal mask: perturbing token t leaves all logits at positions < t bit-identical.
101
+ - Resume: interrupt at the halfway point, rebuild fresh model/opt/sched/stream,
102
+ restore, continue → per-step losses match an uninterrupted run to <1e-6.
103
+ - Data: corrupting one byte of a shard is caught by verify_manifest.
104
+ - BinStream → Trainer integration: loss drops on structured data with train.py unchanged.
105
+
106
+ ## WHAT I WANT FROM YOU (review checklist)
107
+
108
+ Please go through these and report concrete findings with file/function references:
109
+
110
+ 1. **Transformer correctness.** RoPE (half-rotation convention, cos/sin build,
111
+ applied to Q/K only, before/after QK-norm ordering), GQA repeat_interleave vs
112
+ repeat semantics, SwiGLU 2/3 sizing, RMSNorm fp32 reduction, weight tying,
113
+ residual-projection init scaling 1/sqrt(2*n_layers). Any subtle bug?
114
+ 2. **Numerical stability for a long bf16 run.** Is QK-norm enough? Should I add
115
+ z-loss / logit soft-cap / attention-logit cap? Embedding init scale?
116
+ 3. **Checkpoint/resume completeness.** Anything that influences the next step that
117
+ I'm NOT saving (RNG, data position, scaler, AMP state)? Atomicity on Vast spot kill.
118
+ 4. **NaN/Inf guard design.** Is skip-batch correct, or should I roll back to last
119
+ checkpoint? Should the guard also catch inf grad-norm before clip (it does)?
120
+ Is consecutive-skip abort the right policy?
121
+ 5. **Throughput / MFU.** Is the 6N FLOPs/token approximation appropriate, or should
122
+ I include attention FLOPs (2*L*T*d term) at seq_len 1024? Will I actually hit
123
+ 45-50% MFU on an A100 with this code, or what's missing (e.g., no torch.compile
124
+ tuning, no fused/foreach, dataloader not overlapped with compute, H2D copies not
125
+ pinned/non_blocking)?
126
+ 6. **DDP correctness.** no_sync usage on non-final micro-steps is wired but DDP
127
+ wrapping isn't applied (single-GPU). If I later wrap in DDP, what breaks
128
+ (checkpoint should save model.module, num_params unwrap, sampler sharding,
129
+ rank-0-only logging/checkpointing)?
130
+ 7. **Data pipeline.** Random-window sampling vs sequential cursor — implications for
131
+ epoch coverage and resume. Cross-document contamination from packing without
132
+ attention masking at seq_len 1024 — does it matter at this scale?
133
+ 8. **Chinchilla / token budget.** For ~114M total (~75M non-embedding), what token
134
+ count is right for a portfolio run (compute-optimal ~20x vs over-train 50-100x)?
135
+ 9. **Anything that would make a Maincode interviewer wince.** Missing observability,
136
+ missing reproducibility (git SHA logging?), config hygiene, test gaps.
137
+ 10. **Highest-ROI additions** before I spend money, ranked, given the infra-role framing.
138
+
139
+ For each finding give: severity, file/location, the problem, and the concrete fix.
140
+
141
+ ---
142
+
143
+ SOURCE FILES FOLLOW. I will paste them below in this order: config.py, model.py,
144
+ optim.py, checkpoint.py, monitor.py, data.py, train.py, then the four test files.
docs/INSTANCE_RUNBOOK.md ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Instance Runbook — Matilda-Mini
2
+
3
+ > This is the operating manual for running Matilda-Mini on a remote GPU instance
4
+ > (RTX 3090 for validation; A100 for the long run). Follow top to bottom. Each
5
+ > step has a **gate** (what success looks like) — do not proceed past a failed gate.
6
+
7
+ ## 0. Context (read first)
8
+
9
+ - **What:** a sub-200M modern dense transformer trained from scratch + production
10
+ training infra. Portfolio piece for a Maincode training-infrastructure role.
11
+ - **Goal of THIS session:** validate the stack on a real CUDA GPU, then (optionally)
12
+ calibrate MFU and run training.
13
+ - **Model (BASE_124M):** 114M params total / 75.5M non-embedding. d_model=768,
14
+ 12 layers, 12 heads / 4 KV heads (GQA), seq_len=1024, GPT-2 50k vocab.
15
+ - **Already proven on CPU (23 tests):** correctness, bit-for-bit resume, NaN guard,
16
+ data checksums. The unknowns the GPU adds: bf16 path, fused AdamW, Flash-SDPA,
17
+ torch.compile. That's what we validate here.
18
+ - **Key files:** `run.py` (entrypoint), `configs/{calibration,base_124m}.json`,
19
+ `scripts/prepare_data.py`, `src/matilda/*`, `tests/*`.
20
+
21
+ ## 1. Get the code onto the instance
22
+
23
+ Use whichever delivery method was set up (see "Code delivery" at bottom):
24
+
25
+ ```bash
26
+ # Option A — public GitHub:
27
+ git clone https://github.com/swajayresources/matilda-mini.git
28
+ cd matilda-mini
29
+
30
+ # Option B — public HF repo:
31
+ git clone https://huggingface.co/prometheus04/matilda-mini
32
+ cd matilda-mini
33
+
34
+ # Option C — scp'd zip:
35
+ unzip -oq matilda-mini.zip -d matilda-mini && cd matilda-mini
36
+ ```
37
+
38
+ **Gate:** `ls src/matilda/model.py` exists.
39
+
40
+ ## 2. Environment setup
41
+
42
+ ```bash
43
+ python --version # expect 3.10+; if 'python3' use that
44
+ nvidia-smi # confirm the GPU + driver; note GPU name + VRAM
45
+ # Install torch FIRST from cu124 — the default pip wheel may be a cu130 build
46
+ # that cannot init CUDA on current drivers (confirmed on the 3090 session).
47
+ pip install -q torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124
48
+ pip install -q -r requirements.txt
49
+ ```
50
+
51
+ Verify torch sees the GPU and bf16:
52
+
53
+ ```bash
54
+ python -c "import torch; print('torch', torch.__version__, '| cuda', torch.cuda.is_available(), '|', torch.cuda.get_device_name(0)); print('bf16 native:', torch.cuda.is_bf16_supported())"
55
+ ```
56
+
57
+ **Gate:** `cuda True`, GPU name printed, `bf16 native: True` (Ampere/3090/A100).
58
+ If torch has no CUDA, install the CUDA wheel: `pip install torch --index-url https://download.pytorch.org/whl/cu121`.
59
+
60
+ ## 3. Test suite (the correctness gate)
61
+
62
+ ```bash
63
+ python -m pytest tests/ -q
64
+ ```
65
+
66
+ **Gate: `23 passed`.** If something fails here that passed on CPU, it's a real
67
+ GPU-only bug — STOP, capture the full traceback, fix before spending on training.
68
+ Likely suspects: `fused=True` AdamW (optim.py), `pin_memory` in BinStream (data.py).
69
+
70
+ ## 4. Tiny real-data smoke (end-to-end on real tokens)
71
+
72
+ ```bash
73
+ # tokenize ~20M tokens of FineWeb-Edu (1-3 min). No HF token needed (public dataset).
74
+ python scripts/prepare_data.py --out-dir data/smoke --target-tokens 20000000 --shard-tokens 20000000
75
+ python -c "import sys; sys.path.insert(0,'src'); from matilda.data import verify_manifest; print('verified:', verify_manifest('data/smoke'))"
76
+
77
+ # short run; loss should fall from ~10.8 toward ~7
78
+ python run.py --config configs/calibration.json --data-dir data/smoke \
79
+ --set train.total_steps=100 train.warmup_steps=10 train.batch_size=8 \
80
+ train.compile=false train.ckpt_dir=checkpoints/smoke
81
+ ```
82
+
83
+ **Gate:** `verified: True`, and loss visibly **decreasing** over the 100 steps
84
+ (not flat, not NaN). Flat loss = data/label bug; NaN spam = stability bug.
85
+
86
+ ## 5. Resume check on GPU
87
+
88
+ ```bash
89
+ # rerun with a higher step count; must print "[resume] ... at step 100" then continue
90
+ python run.py --config configs/calibration.json --data-dir data/smoke \
91
+ --set train.total_steps=150 train.warmup_steps=10 train.batch_size=8 \
92
+ train.compile=false train.ckpt_dir=checkpoints/smoke
93
+ ```
94
+
95
+ **Gate:** logs show `[resume] from checkpoints/smoke/ckpt_100.pt at step 100`,
96
+ then steps 100→150 with **no loss spike** at the seam.
97
+
98
+ > ✅ If steps 3–5 pass, the stack is validated on real hardware. Decide GPU for
99
+ > the long run:
100
+ > - **3090 (24GB):** ~$4 / ~17h — already validated, fully sufficient.
101
+ > - **A100 40GB (recommended):** ~4h, cheaper than 80GB. A 124M model needs
102
+ > nowhere near 80GB — the memory hotspot is the vocab-projection logits, not
103
+ > weights. 40GB fits BS ~48-64; grad_accum reaches the token target regardless.
104
+ > - **A100 80GB:** overkill here; only marginally fewer accum steps.
105
+ >
106
+ > Attention uses PyTorch's built-in SDPA (Flash Attention 2 kernel) — **no
107
+ > `flash-attn` package, no compilation, nothing to version-match.** It can't break.
108
+
109
+ ## 6. MFU calibration (do this on the SAME GPU you'll run long on)
110
+
111
+ Goal: maximize MFU by finding the largest batch that fits + benefits from compile.
112
+ Run the calibration config, sweeping batch_size; read `mfu_avg` from the log tail.
113
+
114
+ ```bash
115
+ for BS in 16 24 32 48; do
116
+ echo "=== batch_size=$BS ==="
117
+ python run.py --config configs/calibration.json --data-dir data/smoke \
118
+ --set train.batch_size=$BS train.ckpt_dir=checkpoints/calib_$BS 2>&1 | tail -5
119
+ done
120
+ ```
121
+
122
+ Notes:
123
+ - `calibration.json` has `compile=true` — the first ~20 steps are slow (compile +
124
+ cuDNN autotune); the monitor excludes warmup ticks, so trust the later `mfu`.
125
+ - If a batch size OOMs, that's your ceiling — back off one. The OOM hotspot is the
126
+ `lm_head` vocab projection (50257-wide), not attention.
127
+ - Pick the batch with the best steady `mfu_avg`. **Record it.**
128
+
129
+ **Validated result (RTX 3090, this stack):** BS=24 → **53.4% MFU** with compile;
130
+ BS>=28 OOMs. `base_124m.json` already ships these (bs=24, grad_accum=21,
131
+ total_steps=5814 ≈ 3.0B tokens).
132
+
133
+ **A100 re-derivation:** the A100 has far more VRAM — raise `batch_size` to its
134
+ ceiling (expect ~64 on 40GB, ~128 on 80GB), then keep tokens/step ≈ 0.5M and
135
+ total tokens ≈ 3B by recomputing the other two:
136
+
137
+ ```
138
+ tokens_per_step = batch_size * grad_accum * seq_len # target ~524288
139
+ grad_accum = round(524288 / (batch_size * 1024))
140
+ total_steps = round(3.0e9 / (batch_size * grad_accum * 1024))
141
+ ```
142
+
143
+ | GPU | batch_size | grad_accum | total_steps | ~tokens |
144
+ |-----|-----------|-----------|-------------|---------|
145
+ | 3090 (validated) | 24 | 21 | 5814 | 3.00B |
146
+ | A100 40GB (est.) | 64 | 8 | 5722 | 3.00B |
147
+ | A100 80GB (est.) | 128 | 4 | 5722 | 3.00B |
148
+
149
+ Apply with `--set` (no file edit needed), e.g. on A100 80GB:
150
+ `--set train.batch_size=128 train.grad_accum=4 train.total_steps=5722`
151
+
152
+ ## 7. The long run
153
+
154
+ Run under tmux so a dropped SSH connection doesn't kill it:
155
+
156
+ ```bash
157
+ tmux new -s train
158
+ # inside tmux:
159
+ export REMOTE="s3://<bucket>/matilda" # optional: checkpoint backup target
160
+ bash scripts/launch_vast.sh configs/base_124m.json
161
+ # detach: Ctrl-b then d ; reattach later: tmux attach -t train
162
+ ```
163
+
164
+ Or directly with nohup:
165
+ ```bash
166
+ nohup python run.py --config configs/base_124m.json --data-dir data/fwedu > train.log 2>&1 &
167
+ tail -f train.log
168
+ ```
169
+
170
+ **Monitor:** `metrics.jsonl` in the ckpt dir has every logged step (loss, lr,
171
+ grad_norm, mfu, tokens_per_s, gpu_mem_peak_gb). Watch for: loss steadily falling,
172
+ grad_norm stable (~0.2-1.5), mfu flat (a drop = throttling/noisy neighbor),
173
+ nan_skip events (a few are fine; many = lower lr).
174
+
175
+ **If it dies / SSH drops:** reconnect, `tmux attach` (or just re-run the same
176
+ launch command) — it auto-resumes from the latest checkpoint, bit-for-bit.
177
+
178
+ ## 7b. Architecture ablations (cheap, high portfolio signal)
179
+
180
+ Each variant trains on the same token budget; one thing changes per row. ~300M
181
+ tokens each (~4 variants ≈ $2 on a 3090). Emits `docs/ABLATIONS.md` + JSON.
182
+
183
+ ```bash
184
+ python scripts/ablate.py --data-dir data/fwedu --tokens 300000000
185
+ # subset: python scripts/ablate.py --data-dir data/fwedu --only baseline mha
186
+ ```
187
+ Variants: `baseline` (full modern), `no_qk_norm` (+softcap), `mha` (no GQA),
188
+ `mqa` (extreme GQA). Read `docs/ABLATIONS.md` — that table is the README centerpiece.
189
+ Save it OFF the instance (section 9). Add more rows by editing the `VARIANTS`
190
+ list in `scripts/ablate.py`.
191
+
192
+ ## 8. Evaluation (after the run)
193
+
194
+ ```bash
195
+ pip install -q lm-eval
196
+ # convert/point lm-eval at the checkpoint, then:
197
+ lm_eval --model hf --model_args pretrained=<exported_dir>,dtype=bfloat16 \
198
+ --tasks hellaswag,arc_easy,piqa,winogrande --batch_size 32
199
+ ```
200
+ Target (124M, ~3B tokens): HellaSwag ~30-35%, ARC-easy ~40-45%, PIQA ~60%.
201
+ Compare to Pythia-160M (HellaSwag ~30, ARC-e ~40, PIQA ~62).
202
+
203
+ ## 9. Save artifacts before killing the instance
204
+
205
+ The instance is ephemeral — pull results off it:
206
+ ```bash
207
+ # the final checkpoint + the full metric history
208
+ ls -la checkpoints/base_124m/
209
+ # copy these OFF the box: latest ckpt_*.pt, metrics.jsonl, train.log
210
+ # either: aws s3 cp ... / huggingface-cli upload ... / scp back to laptop
211
+ ```
212
+ Minimum to keep for the README table: `metrics.jsonl` (the loss/MFU curves) and
213
+ the final eval numbers.
214
+
215
+ ## Gotchas & decisions
216
+
217
+ - **OOM:** lower `train.batch_size`, raise `grad_accum` to keep tokens/step constant.
218
+ - **NaN spam:** lower `lr` (6e-4 → 3e-4). The guard skips bad batches but many
219
+ skips = unstable. The qk_norm=OFF ablation needs `attn_logit_softcap=20`.
220
+ - **Low MFU (<25%):** confirm `compile=true`, bf16 engaged (Ampere+), data not
221
+ starving (it's pinned/non_blocking already).
222
+ - **SSH drop:** always run training in tmux/nohup. Resume is automatic.
223
+ - **git_sha "unknown":** only if the code wasn't cloned via git (zip path). Fine.
224
+ - **Do NOT** commit `data/`, `checkpoints/`, `*.bin`, `*.pt` anywhere.
225
+
226
+ ## Code delivery (how the code got here)
227
+
228
+ - [x] **HF public: `huggingface.co/prometheus04/matilda-mini`** ← v1 (124M):
229
+ `git clone https://huggingface.co/prometheus04/matilda-mini && cd matilda-mini`
230
+ - [x] **HF public: `huggingface.co/prometheus04/matilda-mini-v2`** ← v2 (363M hero):
231
+ `git clone https://huggingface.co/prometheus04/matilda-mini-v2 && cd matilda-mini-v2`
232
+ - [ ] GitHub private: `github.com/swajayresources/matilda-mini` (needs auth)
233
+ - [ ] zip via scp
234
+
235
+ ---
236
+
237
+ # v2 (363M hero run) — operating manual
238
+
239
+ The v2 path supersedes v1 for the actual paid run. Lay out the same as the v1
240
+ sections above, but with these substitutions.
241
+
242
+ ## v2.1 Hardware
243
+
244
+ A100 SXM4 40GB at ≤ $1.05/hr (Vast.ai or equivalent). Confirm spot/interruptible
245
+ is available — bit-for-bit resume is already proven, so spot is the right call.
246
+
247
+ ## v2.2 Environment
248
+
249
+ ```bash
250
+ # v1 setup is unchanged (torch cu124 first, then requirements.txt)
251
+ pip install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124
252
+ pip install -r requirements.txt
253
+
254
+ # v2-specific: liger-kernel is required by BASE_350M (use_liger=true).
255
+ # The model will fail loudly at Transformer __init__ if this is missing.
256
+ pip install liger-kernel
257
+ python -c "from liger_kernel.transformers.rms_norm import LigerRMSNorm; print('liger OK')"
258
+ ```
259
+
260
+ ## v2.3 Gate the run on the existing test suite
261
+
262
+ ```bash
263
+ pytest tests/ -q # 35 passed expected (1 was skipped on CPU)
264
+ # On GPU+liger the BASE_350M shape test should also pass — total 36 passed.
265
+ ```
266
+
267
+ ## v2.4 Tokenize the SmolLM mix
268
+
269
+ ```bash
270
+ # 15B tokens, 75% FineWeb-Edu-dedup / 15% Cosmopedia v2 / 10% Python-Edu.
271
+ # Token-based mixing (not doc-based) — see prepare_smollm_data.py for the
272
+ # argmin-deficit picking that converges to exact ratios.
273
+ python scripts/prepare_smollm_data.py \
274
+ --out-dir data/smollm_mix \
275
+ --target-tokens 15000000000
276
+ ```
277
+
278
+ Disk cost: ~30GB output (15B × 2 bytes/token for uint16). Run-time on the
279
+ GPU instance: ~1-2 hours of streaming + tokenization. Save the resulting
280
+ `data/smollm_mix/` to durable storage if you'll re-launch.
281
+
282
+ ## v2.5 Calibrate batch size on A100 with Liger
283
+
284
+ `base_350m.json` ships with `batch_size=32`, `grad_accum=16` (tokens/step ≈ 1M).
285
+ Liger fused linear+CE removes the (B·T, vocab) logit memory hotspot that capped
286
+ v1 at BS=24 on the 3090, so micro-batch on A100 40GB should land higher. Sweep
287
+ to find the ceiling:
288
+
289
+ ```bash
290
+ # 50-step smoke; watch peak GPU mem and MFU
291
+ python run.py --config configs/base_350m.json --data-dir data/smollm_mix \
292
+ --set train.total_steps=50 train.batch_size=32 train.grad_accum=2 \
293
+ train.ckpt_dir=checkpoints/calib_b32
294
+
295
+ python run.py --config configs/base_350m.json --data-dir data/smollm_mix \
296
+ --set train.total_steps=50 train.batch_size=48 train.grad_accum=2 \
297
+ train.ckpt_dir=checkpoints/calib_b48
298
+ ```
299
+
300
+ Pick the largest BS that doesn't OOM, then re-derive `grad_accum` to keep
301
+ `batch × accum × seq_len ≈ 1M` (e.g. BS=48 → grad_accum=11).
302
+
303
+ ## v2.6 Launch the hero run
304
+
305
+ ```bash
306
+ tmux new -s matilda
307
+ bash scripts/launch_vast.sh configs/base_350m.json
308
+ # If you found BS=48 in calibration:
309
+ # --set train.batch_size=48 train.grad_accum=11
310
+ # (override via the run.py CLI; launch_vast.sh forwards CONFIG only.)
311
+ ```
312
+
313
+ ETA at the target ~50% MFU: 55-60h. Total cost ~$55-60 at $1.017/hr. Checkpoints
314
+ land every 1000 steps (~1B tokens) in `checkpoints/base_350m/`, keeping the last 20.
315
+
316
+ ## v2.7 Eval (token-matched vs Pythia-410M)
317
+
318
+ For each saved checkpoint, run lm-eval-harness against Pythia-410M's published
319
+ checkpoints at the same token count. The plot for the writeup is loss/HellaSwag/
320
+ ARC-e/LAMBADA vs tokens, with our curve overlaid on Pythia-410M's.
321
+
322
+ ```bash
323
+ pip install lm-eval
324
+ lm-eval --model hf --model_args pretrained=./checkpoints/base_350m/ckpt_15000.pt \
325
+ --tasks hellaswag,arc_easy,piqa,lambada_openai \
326
+ --batch_size 32 --device cuda
327
+ ```
328
+
329
+ (Note: lm-eval expects a HF-loadable model; you may need a quick adapter that
330
+ loads our nn.Module + tokenizer. Plan a 1-2h budget for the adapter.)
331
+
332
+ ## v2.8 Gotchas specific to v2
333
+
334
+ - **liger-kernel missing:** Transformer init raises ImportError with the install
335
+ hint. Don't try to silently fall back — the cost story depends on Liger.
336
+ - **head_dim 80 + SDPA:** valid but ~5% slower than 64. We accept this for the
337
+ deep+thin shape signal. Don't "fix" it by switching n_heads.
338
+ - **z_loss spam:** with z_loss_coef=1e-4 the contribution should be <<CE.
339
+ If z-loss dominates loss, lower the coefficient or check logit magnitude.
340
+ - **WSD decay knee:** the LR holds flat for 80% of training then drops sharply.
341
+ Eyeballing the loss curve, expect the "second descent" only in the last 20%.
342
+ This is normal and is the WSD selling point — earlier checkpoints stay useful.
notebooks/colab_validate.ipynb ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Matilda-Mini — Colab GPU validation (Phase 4, part 1: free)\n",
8
+ "\n",
9
+ "Goal: confirm the code is correct on a **real CUDA GPU** before spending money on Vast.\n",
10
+ "This catches anything CPU hid (bf16 paths, fused AdamW, SDPA Flash backend).\n",
11
+ "\n",
12
+ "**Note on T4:** Colab's free T4 is Turing and has *no native bf16* (it emulates, slowly).\n",
13
+ "Validate *correctness* here; do **not** trust T4 speed/MFU numbers. MFU tuning happens\n",
14
+ "in the $0.20 A100 calibration."
15
+ ]
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "execution_count": null,
20
+ "metadata": {},
21
+ "outputs": [],
22
+ "source": [
23
+ "import torch\n",
24
+ "print('cuda:', torch.cuda.is_available())\n",
25
+ "print('device:', torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'cpu')\n",
26
+ "print('bf16 supported:', torch.cuda.is_bf16_supported() if torch.cuda.is_available() else False)"
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "markdown",
31
+ "metadata": {},
32
+ "source": [
33
+ "## Get the code\n",
34
+ "Either `git clone` your pushed repo, or upload+unzip the `matilda-mini` folder, then `cd` in."
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": null,
40
+ "metadata": {},
41
+ "outputs": [],
42
+ "source": [
43
+ "# Option A: from GitHub (after you push)\n",
44
+ "# !git clone https://github.com/<you>/matilda-mini.git\n",
45
+ "# %cd matilda-mini\n",
46
+ "\n",
47
+ "# Option B: upload a zip via the Files panel, then:\n",
48
+ "# !unzip -q matilda-mini.zip && cd matilda-mini\n",
49
+ "\n",
50
+ "!pip install -q -r requirements.txt"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "markdown",
55
+ "metadata": {},
56
+ "source": [
57
+ "## 1. Run the test suite on GPU\n",
58
+ "Expect **23 passed**. If anything fails here that passed on CPU, it's a real GPU-only bug."
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": null,
64
+ "metadata": {},
65
+ "outputs": [],
66
+ "source": [
67
+ "!python -m pytest tests/ -q"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "markdown",
72
+ "metadata": {},
73
+ "source": [
74
+ "## 2. Tiny real-data smoke: tokenize a little FineWeb-Edu and watch loss fall\n",
75
+ "50M tokens is plenty to confirm the end-to-end path. Loss should drop from ~10.8 toward ~7 quickly."
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "execution_count": null,
81
+ "metadata": {},
82
+ "outputs": [],
83
+ "source": [
84
+ "!python scripts/prepare_data.py --out-dir data/smoke --target-tokens 50000000 --shard-tokens 50000000\n",
85
+ "!python -c \"import sys; sys.path.insert(0,'src'); from matilda.data import verify_manifest; print('verified:', verify_manifest('data/smoke'))\""
86
+ ]
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "execution_count": null,
91
+ "metadata": {},
92
+ "outputs": [],
93
+ "source": [
94
+ "# Short real run on the smoke shard. bf16 only engages on Ampere+ (A100/L4), not T4.\n",
95
+ "!python run.py --config configs/calibration.json --data-dir data/smoke \\\n",
96
+ " --set train.total_steps=100 train.warmup_steps=10 train.batch_size=8 \\\n",
97
+ " train.compile=false train.ckpt_dir=checkpoints/smoke"
98
+ ]
99
+ },
100
+ {
101
+ "cell_type": "markdown",
102
+ "metadata": {},
103
+ "source": [
104
+ "## 3. Confirm resume works on GPU\n",
105
+ "Re-run the same command; it should print `[resume] from ... at step 100` and continue,\n",
106
+ "not restart. Bump `total_steps` to 150 to see it progress."
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "execution_count": null,
112
+ "metadata": {},
113
+ "outputs": [],
114
+ "source": [
115
+ "!python run.py --config configs/calibration.json --data-dir data/smoke \\\n",
116
+ " --set train.total_steps=150 train.warmup_steps=10 train.batch_size=8 \\\n",
117
+ " train.compile=false train.ckpt_dir=checkpoints/smoke"
118
+ ]
119
+ },
120
+ {
121
+ "cell_type": "markdown",
122
+ "metadata": {},
123
+ "source": [
124
+ "If 23 tests pass, loss falls on real data, and resume continues cleanly — the code is\n",
125
+ "validated. Next: rent the A100 and run `configs/calibration.json` to tune batch size for\n",
126
+ "max MFU (with `compile=true`), then launch the long run."
127
+ ]
128
+ }
129
+ ],
130
+ "metadata": {
131
+ "accelerator": "GPU",
132
+ "colab": {"provenance": []},
133
+ "kernelspec": {"display_name": "Python 3", "name": "python3"},
134
+ "language_info": {"name": "python"}
135
+ },
136
+ "nbformat": 4,
137
+ "nbformat_minor": 0
138
+ }
pytest.ini ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [pytest]
2
+ markers =
3
+ slow: longer training-based sanity checks (overfit one batch)
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GPU: install torch FIRST from the cu124 index (the default wheel may be a
2
+ # cu130 build that fails CUDA init on current drivers):
3
+ # pip install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124
4
+ torch>=2.4,<3.0
5
+ numpy
6
+ tiktoken
7
+ datasets
8
+ wandb
9
+ pytest
10
+
11
+ # v2 (350M hero) only. liger-kernel needs CUDA Triton, so install LAST and
12
+ # only on the GPU instance. CPU dev boxes leave use_liger=False and skip it.
13
+ liger-kernel>=0.4.0; platform_system != "Windows"
run.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Launch entrypoint: build configs + data stream and train.
2
+
3
+ python run.py --config configs/base_124m.json --data-dir data/fwedu
4
+ python run.py --config configs/calibration.json --data-dir data/fwedu
5
+ python run.py --config configs/calibration.json --dry-run # synthetic, no data
6
+
7
+ A config JSON has two objects, "model" and "train", whose keys map directly onto
8
+ ModelConfig / TrainConfig fields. CLI --set k=v applies last-mile overrides
9
+ (e.g. --set train.batch_size=48) so calibration sweeps don't need new files.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import sys
15
+ import json
16
+ import argparse
17
+ from pathlib import Path
18
+
19
+ sys.path.insert(0, str(Path(__file__).resolve().parent / "src"))
20
+
21
+ from matilda.config import ModelConfig # noqa: E402
22
+ from matilda.train import Trainer, TrainConfig # noqa: E402
23
+ from matilda.data import SyntheticStream, BinStream, shard_paths # noqa: E402
24
+
25
+
26
+ def _coerce(value: str):
27
+ for cast in (int, float):
28
+ try:
29
+ return cast(value)
30
+ except ValueError:
31
+ pass
32
+ if value.lower() in ("true", "false"):
33
+ return value.lower() == "true"
34
+ return value
35
+
36
+
37
+ def apply_overrides(cfg: dict, overrides: list[str]) -> dict:
38
+ """--set train.batch_size=48 -> cfg['train']['batch_size'] = 48"""
39
+ for item in overrides:
40
+ path, _, raw = item.partition("=")
41
+ section, _, key = path.partition(".")
42
+ cfg.setdefault(section, {})[key] = _coerce(raw)
43
+ return cfg
44
+
45
+
46
+ def build(config: dict):
47
+ mcfg = ModelConfig(**config.get("model", {}))
48
+ tcfg = TrainConfig(**config.get("train", {}))
49
+ return mcfg, tcfg
50
+
51
+
52
+ def build_stream(mcfg, tcfg, data_dir: str | None, dry_run: bool):
53
+ if dry_run or not data_dir:
54
+ print("[data] synthetic stream (dry run, no real data)")
55
+ return SyntheticStream(mcfg.vocab_size, tcfg.batch_size, tcfg.seq_len,
56
+ seed=tcfg.seed, device=tcfg.device)
57
+ paths = shard_paths(data_dir)
58
+ print(f"[data] {len(paths)} shards from {data_dir}")
59
+ return BinStream(paths, tcfg.batch_size, tcfg.seq_len, seed=tcfg.seed,
60
+ device=tcfg.device)
61
+
62
+
63
+ def main():
64
+ ap = argparse.ArgumentParser()
65
+ ap.add_argument("--config", required=True)
66
+ ap.add_argument("--data-dir", default=None)
67
+ ap.add_argument("--dry-run", action="store_true")
68
+ ap.add_argument("--set", nargs="*", default=[], dest="overrides")
69
+ args = ap.parse_args()
70
+
71
+ config = json.loads(Path(args.config).read_text())
72
+ config = apply_overrides(config, args.overrides)
73
+ mcfg, tcfg = build(config)
74
+ stream = build_stream(mcfg, tcfg, args.data_dir, args.dry_run)
75
+
76
+ print(f"[run] model={mcfg.d_model}d/{mcfg.n_layers}L "
77
+ f"steps={tcfg.total_steps} bs={tcfg.batch_size}x{tcfg.grad_accum} "
78
+ f"seq={tcfg.seq_len} compile={tcfg.compile} ckpt={tcfg.ckpt_dir}")
79
+ Trainer(mcfg, tcfg, stream).train()
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
scripts/ablate.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Architecture ablation harness.
2
+
3
+ Trains each variant for the SAME fixed token budget on the SAME data, then emits
4
+ a markdown results table + JSON. The point of an ablation is a controlled
5
+ comparison: one thing changes per row, everything else held fixed.
6
+
7
+ python scripts/ablate.py --data-dir data/fwedu --tokens 300000000
8
+ python scripts/ablate.py --dry-run # tiny synthetic, for CI/sanity
9
+ python scripts/ablate.py --data-dir data/fwedu --only baseline no_qk_norm
10
+
11
+ Each variant only overrides what it's testing; the rest inherits from BASE below.
12
+ Results land in results/ablations/<name>/ (checkpoints + metrics.jsonl) and a
13
+ combined docs/ABLATIONS.md + results/ablations.json.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import sys
20
+ import json
21
+ import argparse
22
+ from pathlib import Path
23
+
24
+ ROOT = Path(__file__).resolve().parent.parent
25
+ sys.path.insert(0, str(ROOT / "src"))
26
+
27
+ from matilda.config import ModelConfig # noqa: E402
28
+ from matilda.train import Trainer, TrainConfig # noqa: E402
29
+ from matilda.model import Transformer # noqa: E402
30
+ from matilda.data import SyntheticStream, BinStream, shard_paths # noqa: E402
31
+
32
+ # Base config every variant inherits. Real architecture, short token budget.
33
+ BASE_MODEL = dict(vocab_size=50257, max_seq_len=1024, d_model=768,
34
+ n_layers=12, n_heads=12, n_kv_heads=4)
35
+ import torch # noqa: E402
36
+
37
+ _HAS_CUDA = torch.cuda.is_available()
38
+ BASE_TRAIN = dict(seq_len=1024, batch_size=24, grad_accum=8, warmup_steps=80,
39
+ lr=6e-4, log_every=20, ckpt_every=100000,
40
+ device="cuda" if _HAS_CUDA else "cpu",
41
+ dtype="bfloat16" if _HAS_CUDA else "float32",
42
+ compile=_HAS_CUDA)
43
+
44
+ # One change per row. Inherits BASE; only the listed keys differ.
45
+ VARIANTS = [
46
+ {"name": "baseline", "model": {}},
47
+ {"name": "no_qk_norm", "model": {"qk_norm": False, "attn_logit_softcap": 20.0}},
48
+ {"name": "mha", "model": {"n_kv_heads": 12}}, # full multi-head (no GQA)
49
+ {"name": "mqa", "model": {"n_kv_heads": 1}}, # multi-query (extreme GQA)
50
+ {"name": "muon", "model": {}, "train": {"optimizer": "muon"}},
51
+ ]
52
+
53
+
54
+ def steps_for_tokens(tokens, tcfg: TrainConfig) -> int:
55
+ return max(1, round(tokens / (tcfg.batch_size * tcfg.grad_accum * tcfg.seq_len)))
56
+
57
+
58
+ def final_metrics(ckpt_dir, tail=5) -> dict:
59
+ """Average the last `tail` logged steps from metrics.jsonl."""
60
+ path = os.path.join(ckpt_dir, "metrics.jsonl")
61
+ try:
62
+ with open(path) as f:
63
+ rows = [json.loads(l) for l in f if l.strip()]
64
+ except FileNotFoundError:
65
+ return {"loss": None, "mfu": None} # crashed before logging a step
66
+ steps = [r for r in rows if r.get("event") == "step"]
67
+ if not steps:
68
+ return {"loss": None, "mfu": None}
69
+ last = steps[-tail:]
70
+ avg = lambda k: sum(s[k] for s in last if s.get(k) is not None) / len(last)
71
+ return {"loss": round(avg("loss"), 4), "mfu": round(avg("mfu"), 4),
72
+ "tokens_per_s": round(avg("tokens_per_s"))}
73
+
74
+
75
+ def run_variant(v, tokens, data_dir, dry_run, results_root):
76
+ model = {**BASE_MODEL, **v.get("model", {})}
77
+ train = {**BASE_TRAIN, **v.get("train", {})}
78
+ if dry_run: # shrink for CPU/CI
79
+ model.update(d_model=64, n_layers=2, n_heads=4,
80
+ n_kv_heads=min(4, model.get("n_kv_heads", 4)), max_seq_len=64)
81
+ if v["name"] == "mha":
82
+ model["n_kv_heads"] = 4
83
+ train.update(seq_len=64, batch_size=4, grad_accum=1, warmup_steps=2,
84
+ device="cpu", dtype="float32", compile=False)
85
+ ckpt_dir = os.path.join(results_root, v["name"])
86
+ train["ckpt_dir"] = ckpt_dir
87
+
88
+ mcfg = ModelConfig(**model)
89
+ tcfg = TrainConfig(total_steps=steps_for_tokens(tokens, TrainConfig(**train)),
90
+ **train)
91
+ active = Transformer(mcfg).num_params(non_embedding=True)
92
+
93
+ if dry_run or not data_dir:
94
+ stream = SyntheticStream(mcfg.vocab_size, tcfg.batch_size, tcfg.seq_len,
95
+ seed=0, device=tcfg.device)
96
+ else:
97
+ stream = BinStream(shard_paths(data_dir), tcfg.batch_size, tcfg.seq_len,
98
+ seed=0, device=tcfg.device)
99
+
100
+ print(f"\n=== variant: {v['name']} | steps={tcfg.total_steps} "
101
+ f"active={active/1e6:.1f}M kv_heads={mcfg.n_kv_heads} "
102
+ f"qk_norm={mcfg.qk_norm} ===")
103
+ Trainer(mcfg, tcfg, stream).train()
104
+ m = final_metrics(ckpt_dir)
105
+ return {"name": v["name"], "active_params_m": round(active / 1e6, 1),
106
+ "n_kv_heads": mcfg.n_kv_heads, "qk_norm": mcfg.qk_norm,
107
+ "optimizer": tcfg.optimizer,
108
+ "final_loss": m["loss"], "mfu": m["mfu"],
109
+ "tokens_per_s": m.get("tokens_per_s")}
110
+
111
+
112
+ def write_table(rows, tokens, out_md, out_json):
113
+ os.makedirs(os.path.dirname(out_md), exist_ok=True)
114
+ os.makedirs(os.path.dirname(out_json), exist_ok=True)
115
+ json.dump({"tokens_per_variant": tokens, "rows": rows},
116
+ open(out_json, "w"), indent=2)
117
+ lines = [
118
+ "# Architecture Ablations",
119
+ "",
120
+ f"Each variant trained on **{tokens/1e6:.0f}M tokens** of the same data, "
121
+ "identical except for the column under test.",
122
+ "",
123
+ "| Variant | Active params | n_kv_heads | QK-norm | Optimizer | Final loss | MFU | tok/s |",
124
+ "|---------|--------------|-----------|---------|-----------|-----------|-----|-------|",
125
+ ]
126
+ for r in rows:
127
+ mfu = f"{r['mfu']*100:.1f}%" if r["mfu"] is not None else "—"
128
+ tps = f"{r['tokens_per_s']:,}" if r.get("tokens_per_s") else "—"
129
+ loss = r["final_loss"] if r["final_loss"] is not None else "—"
130
+ lines.append(f"| {r['name']} | {r['active_params_m']}M | {r['n_kv_heads']} "
131
+ f"| {r['qk_norm']} | {r.get('optimizer','adamw')} | {loss} "
132
+ f"| {mfu} | {tps} |")
133
+ open(out_md, "w").write("\n".join(lines) + "\n")
134
+ print(f"\nwrote {out_md} and {out_json}")
135
+
136
+
137
+ def main():
138
+ ap = argparse.ArgumentParser()
139
+ ap.add_argument("--data-dir", default=None)
140
+ ap.add_argument("--tokens", type=int, default=300_000_000)
141
+ ap.add_argument("--dry-run", action="store_true")
142
+ ap.add_argument("--only", nargs="*", default=None,
143
+ help="subset of variant names to run")
144
+ ap.add_argument("--results", default=str(ROOT / "results" / "ablations"))
145
+ args = ap.parse_args()
146
+
147
+ tokens = 50_000 if args.dry_run else args.tokens
148
+ variants = [v for v in VARIANTS
149
+ if args.only is None or v["name"] in args.only]
150
+ rows = [run_variant(v, tokens, args.data_dir, args.dry_run, args.results)
151
+ for v in variants]
152
+ write_table(rows, tokens,
153
+ out_md=str(ROOT / "docs" / "ABLATIONS.md"),
154
+ out_json=str(Path(args.results) / "ablations.json"))
155
+ print("\n".join(f" {r['name']:12} loss={r['final_loss']} mfu={r['mfu']}"
156
+ for r in rows))
157
+
158
+
159
+ if __name__ == "__main__":
160
+ main()
scripts/launch_vast.sh ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Spot-safe launch wrapper for a Vast.ai A100 instance.
3
+ #
4
+ # The trainer itself traps SIGTERM and checkpoints before exit (train.py), so
5
+ # this wrapper's job is environment setup + syncing checkpoints to durable
6
+ # storage so an instance death doesn't lose them.
7
+ #
8
+ # bash scripts/launch_vast.sh configs/calibration.json # MFU smoke test
9
+ # bash scripts/launch_vast.sh configs/base_124m.json # v1: 124M / FineWeb-Edu
10
+ # bash scripts/launch_vast.sh configs/base_350m.json # v2: 350M / SmolLM mix
11
+ #
12
+ # Set REMOTE to an rclone/s3 target to enable checkpoint upload on exit.
13
+ # Set DATA_DIR to override the default per-config data path.
14
+
15
+ set -euo pipefail
16
+
17
+ CONFIG="${1:-configs/base_124m.json}"
18
+ REMOTE="${REMOTE:-}" # e.g. s3://my-bucket/matilda or gdrive:matilda
19
+ CKPT_DIR="$(python -c "import json;print(json.load(open('$CONFIG'))['train']['ckpt_dir'])")"
20
+ USE_LIGER="$(python -c "import json;print(json.load(open('$CONFIG'))['model'].get('use_liger', False))")"
21
+
22
+ # Default DATA_DIR depends on which config is being run.
23
+ if [ -z "${DATA_DIR:-}" ]; then
24
+ case "$CONFIG" in
25
+ *base_350m*) DATA_DIR="data/smollm_mix" ;;
26
+ *) DATA_DIR="data/fwedu" ;;
27
+ esac
28
+ fi
29
+
30
+ sync_checkpoints() {
31
+ [ -z "$REMOTE" ] && { echo "[sync] REMOTE unset, skipping upload"; return; }
32
+ echo "[sync] uploading $CKPT_DIR -> $REMOTE"
33
+ if command -v aws >/dev/null; then aws s3 sync "$CKPT_DIR" "$REMOTE" || true
34
+ elif command -v rclone >/dev/null; then rclone copy "$CKPT_DIR" "$REMOTE" || true
35
+ fi
36
+ }
37
+ trap sync_checkpoints EXIT # runs on normal exit AND on spot kill
38
+
39
+ echo "[setup] installing deps"
40
+ pip install -q -r requirements.txt
41
+ if [ "$USE_LIGER" = "True" ]; then
42
+ echo "[setup] config has use_liger=True; ensuring liger-kernel is importable"
43
+ python -c "import liger_kernel" 2>/dev/null || pip install -q liger-kernel
44
+ fi
45
+
46
+ # Pull checkpoints back first so a relaunched instance resumes (no-op if absent).
47
+ if [ -n "$REMOTE" ]; then
48
+ mkdir -p "$CKPT_DIR"
49
+ (command -v aws >/dev/null && aws s3 sync "$REMOTE" "$CKPT_DIR") || \
50
+ (command -v rclone >/dev/null && rclone copy "$REMOTE" "$CKPT_DIR") || true
51
+ fi
52
+
53
+ if [ ! -f "$DATA_DIR/manifest.json" ]; then
54
+ case "$CONFIG" in
55
+ *base_350m*)
56
+ echo "[data] no manifest in $DATA_DIR; building SmolLM 75/15/10 mix (~15B tokens)"
57
+ python scripts/prepare_smollm_data.py --out-dir "$DATA_DIR" \
58
+ --target-tokens 15000000000
59
+ ;;
60
+ *)
61
+ echo "[data] no manifest in $DATA_DIR; tokenizing FineWeb-Edu (~3B tokens)"
62
+ python scripts/prepare_data.py --out-dir "$DATA_DIR" \
63
+ --target-tokens 3000000000
64
+ ;;
65
+ esac
66
+ fi
67
+
68
+ echo "[train] launching $CONFIG"
69
+ python run.py --config "$CONFIG" --data-dir "$DATA_DIR"
scripts/prepare_data.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenize a HuggingFace text dataset into verifiable uint16 shards.
2
+
3
+ Default: FineWeb-Edu sample-10BT (best small-scale benchmark movement, max
4
+ comparability to Pythia/SmolLM). Dataset-agnostic by design so DCLM /
5
+ Nemotron-CC become drop-in data-ablation rows:
6
+
7
+ python scripts/prepare_data.py --target-tokens 3_000_000_000 \
8
+ --dataset HuggingFaceFW/fineweb-edu --name sample-10BT --out-dir data/fwedu
9
+
10
+ # ablation rows (same flags, different source):
11
+ --dataset mlfoundations/dclm-baseline-1.0 --out-dir data/dclm
12
+ --dataset nvidia/Nemotron-CC --out-dir data/nemotron
13
+
14
+ Streams the source (no full download), so disk holds only the tokenized output.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import sys
20
+ import argparse
21
+ from pathlib import Path
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
24
+
25
+ from matilda.data import ShardWriter, verify_manifest # noqa: E402
26
+
27
+
28
+ def main():
29
+ ap = argparse.ArgumentParser()
30
+ ap.add_argument("--dataset", default="HuggingFaceFW/fineweb-edu")
31
+ ap.add_argument("--name", default="sample-10BT")
32
+ ap.add_argument("--split", default="train")
33
+ ap.add_argument("--text-key", default="text")
34
+ ap.add_argument("--tokenizer", default="gpt2")
35
+ ap.add_argument("--target-tokens", type=int, default=3_000_000_000)
36
+ ap.add_argument("--shard-tokens", type=int, default=100_000_000)
37
+ ap.add_argument("--out-dir", default="data/fwedu")
38
+ args = ap.parse_args()
39
+
40
+ import tiktoken
41
+ from datasets import load_dataset
42
+
43
+ enc = tiktoken.get_encoding(args.tokenizer)
44
+ eot = enc.eot_token
45
+ assert enc.n_vocab <= 65535, "vocab > uint16; use a smaller tokenizer"
46
+
47
+ ds = load_dataset(args.dataset, name=args.name, split=args.split,
48
+ streaming=True)
49
+ writer = ShardWriter(args.out_dir, shard_tokens=args.shard_tokens)
50
+
51
+ n_docs = 0
52
+ for doc in ds:
53
+ ids = enc.encode_ordinary(doc[args.text_key])
54
+ ids.append(eot) # document boundary
55
+ writer.add(ids)
56
+ n_docs += 1
57
+ if n_docs % 1000 == 0:
58
+ print(f"\rdocs={n_docs:,} tokens={writer.total_tokens:,}", end="")
59
+ if writer.total_tokens >= args.target_tokens:
60
+ break
61
+
62
+ manifest = writer.close(meta={
63
+ "dataset": args.dataset, "name": args.name, "split": args.split,
64
+ "tokenizer": args.tokenizer, "eot_token": eot, "n_docs": n_docs,
65
+ })
66
+ print(f"\nwrote {manifest['total_tokens']:,} tokens in "
67
+ f"{len(manifest['shards'])} shards -> {args.out_dir}")
68
+ verify_manifest(args.out_dir)
69
+ print("manifest verified (checksums + sizes OK)")
70
+
71
+
72
+ if __name__ == "__main__":
73
+ main()
scripts/prepare_smollm_data.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the SmolLM-corpus 75/15/10 mix into verifiable uint16 shards.
2
+
3
+ Adopts the SmolLM data recipe (proven sub-1B winner over Pythia-410M /
4
+ MobileLLM-350M / Qwen2-500M) but re-tokenized through our locked GPT-2 BPE so
5
+ that loader, shard format, and tokenizer-comparability with v1 are unchanged.
6
+
7
+ Mix targets are token-based, not document-based: documents have wildly
8
+ different lengths, so picking-by-doc-count would drift far from the intended
9
+ mix. We pick from whichever source is most under-represented in *tokens*
10
+ emitted so far, which converges to exactly the configured weights.
11
+
12
+ Default 15B-token target matches configs/base_350m.json. Streams the three
13
+ HuggingFaceTB/smollm-corpus subsets so disk only holds the tokenized output.
14
+
15
+ Usage (on the GPU instance):
16
+
17
+ python scripts/prepare_smollm_data.py \
18
+ --target-tokens 15_000_000_000 \
19
+ --out-dir data/smollm_mix
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import sys
25
+ import argparse
26
+ import logging
27
+ from pathlib import Path
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
30
+
31
+ from matilda.data import ShardWriter, verify_manifest # noqa: E402
32
+
33
+ log = logging.getLogger("prepare_smollm_data")
34
+
35
+
36
+ SOURCES: tuple[tuple[str, float], ...] = (
37
+ ("fineweb-edu-dedup", 0.75), # bulk: web reading-comprehension signal
38
+ ("cosmopedia-v2", 0.15), # the Cosmopedia premium (synthetic textbooks)
39
+ ("python-edu", 0.10), # code: HumanEval signal, modest cost
40
+ )
41
+ DATASET = "HuggingFaceTB/smollm-corpus"
42
+ TEXT_KEY = "text"
43
+
44
+
45
+ def _open_stream(name: str):
46
+ from datasets import load_dataset
47
+ return iter(load_dataset(DATASET, name=name, split="train", streaming=True))
48
+
49
+
50
+ def _pick_source(accumulated: dict[str, int]) -> str:
51
+ """Return the source whose token deficit relative to its weight is largest.
52
+ Equivalent to argmin(accumulated[s] / weight[s]) over s in SOURCES."""
53
+ return min(
54
+ (name for name, _ in SOURCES),
55
+ key=lambda n: accumulated[n] / next(w for s, w in SOURCES if s == n),
56
+ )
57
+
58
+
59
+ def main() -> None:
60
+ ap = argparse.ArgumentParser()
61
+ ap.add_argument("--target-tokens", type=int, default=15_000_000_000)
62
+ ap.add_argument("--shard-tokens", type=int, default=100_000_000)
63
+ ap.add_argument("--out-dir", default="data/smollm_mix")
64
+ ap.add_argument("--tokenizer", default="gpt2")
65
+ ap.add_argument("--log-every", type=int, default=1000)
66
+ args = ap.parse_args()
67
+
68
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
69
+ import tiktoken
70
+
71
+ enc = tiktoken.get_encoding(args.tokenizer)
72
+ eot = enc.eot_token
73
+ assert enc.n_vocab <= 65535, "vocab > uint16; loader assumes uint16 shards"
74
+
75
+ streams = {name: _open_stream(name) for name, _ in SOURCES}
76
+ accumulated = {name: 0 for name, _ in SOURCES}
77
+ n_docs = {name: 0 for name, _ in SOURCES}
78
+ writer = ShardWriter(args.out_dir, shard_tokens=args.shard_tokens)
79
+
80
+ while writer.total_tokens < args.target_tokens:
81
+ pick = _pick_source(accumulated)
82
+ try:
83
+ doc = next(streams[pick])
84
+ except StopIteration:
85
+ # Defensive: at 15B target with smollm-corpus sizes, this branch
86
+ # shouldn't trigger. If it does, restart the source so the mix
87
+ # ratio is preserved rather than silently rebalancing.
88
+ log.warning("source %s exhausted at %d tokens; restarting stream",
89
+ pick, writer.total_tokens)
90
+ streams[pick] = _open_stream(pick)
91
+ doc = next(streams[pick])
92
+
93
+ ids = enc.encode_ordinary(doc[TEXT_KEY])
94
+ ids.append(eot) # document boundary
95
+ writer.add(ids)
96
+ accumulated[pick] += len(ids)
97
+ n_docs[pick] += 1
98
+
99
+ total_docs = sum(n_docs.values())
100
+ if total_docs % args.log_every == 0:
101
+ mix = {n: f"{accumulated[n] / max(1, writer.total_tokens) * 100:5.2f}%"
102
+ for n in accumulated}
103
+ log.info("docs=%d tokens=%d mix=%s",
104
+ total_docs, writer.total_tokens, mix)
105
+
106
+ manifest = writer.close(meta={
107
+ "dataset": DATASET,
108
+ "splits": [name for name, _ in SOURCES],
109
+ "weights": {name: weight for name, weight in SOURCES},
110
+ "tokenizer": args.tokenizer,
111
+ "eot_token": eot,
112
+ "n_docs_per_source": n_docs,
113
+ "tokens_per_source": accumulated,
114
+ })
115
+ log.info("wrote %d tokens in %d shards -> %s",
116
+ manifest["total_tokens"], len(manifest["shards"]), args.out_dir)
117
+ verify_manifest(args.out_dir)
118
+ log.info("manifest verified (checksums + sizes OK)")
119
+
120
+
121
+ if __name__ == "__main__":
122
+ main()
src/matilda/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .config import ModelConfig, DEV_TINY, BASE_124M, BASE_350M
2
+ from .model import Transformer
3
+
4
+ __all__ = ["ModelConfig", "DEV_TINY", "BASE_124M", "BASE_350M", "Transformer"]
src/matilda/checkpoint.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Crash-safe checkpointing.
2
+
3
+ A resumed run must continue *identically*, not just "without an obvious spike".
4
+ That requires saving everything that influences the next step:
5
+ model, optimizer, scheduler, step, AND all RNG states AND the dataloader
6
+ position. Dropping the RNG or data position is the classic cause of a loss
7
+ blip on resume (you re-see data / re-sample dropout differently).
8
+
9
+ Writes are atomic (write tmp -> os.replace) so an instance dying mid-save can
10
+ never leave a half-written checkpoint that fails to load.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import glob
17
+ import random
18
+ from dataclasses import asdict
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+
24
+ def _rng_state() -> dict:
25
+ state = {
26
+ "python": random.getstate(),
27
+ "numpy": np.random.get_state(),
28
+ "torch": torch.get_rng_state(),
29
+ }
30
+ if torch.cuda.is_available():
31
+ state["cuda"] = torch.cuda.get_rng_state_all()
32
+ return state
33
+
34
+
35
+ def _set_rng_state(state: dict) -> None:
36
+ random.setstate(state["python"])
37
+ np.random.set_state(state["numpy"])
38
+ # RNG states must be CPU ByteTensors. A checkpoint loaded with
39
+ # map_location="cuda" moves them to GPU, which set_rng_state rejects.
40
+ torch.set_rng_state(state["torch"].cpu())
41
+ if "cuda" in state and torch.cuda.is_available():
42
+ torch.cuda.set_rng_state_all([s.cpu() for s in state["cuda"]])
43
+
44
+
45
+ def save_checkpoint(path, *, model, optimizer, scheduler, step,
46
+ config=None, data_state=None, extra=None) -> None:
47
+ """Atomically write a complete checkpoint to `path`.
48
+
49
+ `extra` carries run provenance (TrainConfig, git SHA) so a resume can detect
50
+ a changed schedule rather than silently corrupting the LR curve.
51
+ """
52
+ payload = {
53
+ "model": model.state_dict(),
54
+ "optimizer": optimizer.state_dict(),
55
+ "scheduler": scheduler.state_dict() if scheduler is not None else None,
56
+ "step": step,
57
+ "rng": _rng_state(),
58
+ "data_state": data_state,
59
+ "config": asdict(config) if hasattr(config, "__dataclass_fields__") else config,
60
+ "extra": extra or {},
61
+ }
62
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
63
+ tmp = f"{path}.tmp.{os.getpid()}"
64
+ torch.save(payload, tmp)
65
+ os.replace(tmp, path) # atomic on POSIX and Windows
66
+
67
+
68
+ def load_checkpoint(path, *, model, optimizer=None, scheduler=None,
69
+ map_location="cpu", restore_rng=True) -> dict:
70
+ """Restore in-place. Returns the raw payload (for step, data_state, config).
71
+
72
+ weights_only=False is required to unpickle optimizer state. Safe here (we only
73
+ load our own checkpoints); never point this at an untrusted checkpoint.
74
+ """
75
+ ck = torch.load(path, map_location=map_location, weights_only=False)
76
+ model.load_state_dict(ck["model"])
77
+ if optimizer is not None and ck.get("optimizer") is not None:
78
+ optimizer.load_state_dict(ck["optimizer"])
79
+ if scheduler is not None and ck.get("scheduler") is not None:
80
+ scheduler.load_state_dict(ck["scheduler"])
81
+ if restore_rng and ck.get("rng") is not None:
82
+ _set_rng_state(ck["rng"])
83
+ return ck
84
+
85
+
86
+ def latest_checkpoint(directory) -> str | None:
87
+ """Highest-step checkpoint matching ckpt_*.pt, or None."""
88
+ paths = glob.glob(os.path.join(directory, "ckpt_*.pt"))
89
+ if not paths:
90
+ return None
91
+ return max(paths, key=lambda p: int(os.path.basename(p)[5:-3]))
92
+
93
+
94
+ def rotate_checkpoints(directory, keep_last: int, protect: set[str] | None = None) -> None:
95
+ """Delete oldest ckpt_*.pt beyond keep_last. `protect` = basenames to keep."""
96
+ protect = protect or set()
97
+ paths = sorted(
98
+ glob.glob(os.path.join(directory, "ckpt_*.pt")),
99
+ key=lambda p: int(os.path.basename(p)[5:-3]),
100
+ )
101
+ deletable = [p for p in paths if os.path.basename(p) not in protect]
102
+ for p in deletable[:-keep_last] if keep_last > 0 else deletable:
103
+ try:
104
+ os.remove(p)
105
+ except OSError as e:
106
+ print(f"[warn] checkpoint rotation could not delete {p}: {e}")
src/matilda/config.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model + run configuration.
2
+
3
+ One frozen dataclass is the single source of truth for a run. It gets logged
4
+ verbatim (alongside the git SHA) so any run is exactly reproducible. Nothing in
5
+ the training stack reads a hyperparameter from anywhere else.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field, asdict
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ModelConfig:
15
+ # --- vocab / sequence ---
16
+ vocab_size: int = 50257 # GPT-2 (tiktoken "gpt2"); fits uint16
17
+ max_seq_len: int = 1024
18
+
19
+ # --- transformer shape ---
20
+ d_model: int = 768
21
+ n_layers: int = 12
22
+ n_heads: int = 12
23
+ n_kv_heads: int = 4 # GQA: n_heads must be divisible by this
24
+ mlp_ratio: float = 8 / 3 # SwiGLU keeps params ~= 4x dense MLP
25
+ mlp_multiple_of: int = 256 # round hidden dim up to this for kernels
26
+
27
+ # --- numerics / regularization ---
28
+ norm_eps: float = 1e-6
29
+ rope_theta: float = 10000.0
30
+ init_std: float = 0.02
31
+ dropout: float = 0.0 # pretraining: keep at 0
32
+
33
+ # --- structural switches ---
34
+ tie_weights: bool = True # share embedding <-> lm_head
35
+ qk_norm: bool = True # RMSNorm on Q,K before attention
36
+ attn_logit_softcap: float = 0.0 # >0 caps scores via tanh; needed for the
37
+ # qk_norm=False ablation so it can't NaN.
38
+ # 0 keeps the fast fused SDPA path.
39
+
40
+ # --- loss / kernel knobs (no-op at v1 defaults) ---
41
+ z_loss_coef: float = 0.0 # penalize log-partition (PaLM/Pythia); 0 = off
42
+ use_liger: bool = False # swap RMSNorm / RoPE / linear+CE for Liger
43
+ # fused kernels on GPU. Requires liger-kernel.
44
+
45
+ @property
46
+ def head_dim(self) -> int:
47
+ assert self.d_model % self.n_heads == 0, "d_model must divide n_heads"
48
+ return self.d_model // self.n_heads
49
+
50
+ def __post_init__(self) -> None:
51
+ assert self.n_heads % self.n_kv_heads == 0, \
52
+ "n_heads must be divisible by n_kv_heads (GQA grouping)"
53
+ assert self.head_dim % 2 == 0, "head_dim must be even for RoPE"
54
+
55
+ def to_dict(self) -> dict:
56
+ d = asdict(self)
57
+ d["head_dim"] = self.head_dim
58
+ return d
59
+
60
+
61
+ # Tiny config for free correctness validation on Colab T4 / RTX 3060.
62
+ # Real vocab kept so tokenizer wiring is exercised; dims shrunk so it runs fast.
63
+ DEV_TINY = ModelConfig(
64
+ vocab_size=50257,
65
+ max_seq_len=256,
66
+ d_model=128,
67
+ n_layers=2,
68
+ n_heads=4,
69
+ n_kv_heads=2,
70
+ )
71
+
72
+ # ~124M params (GPT-2 base footprint). The original A100 long-run config.
73
+ BASE_124M = ModelConfig()
74
+
75
+
76
+ # ~363M params total / ~315M non-embed. The 350M-family hero config.
77
+ # Shape rationale: locked GQA-4 + locked n_layer=32 + clean head_dim (80) +
78
+ # embedding tying. Depth ratio 32/960 = 0.033 (vs Pythia-410M's 24/1024 = 0.023)
79
+ # = ~50% deeper than the closest published anchor at comparable width.
80
+ # Liger Kernel + z-loss on; both no-ops if the flags are flipped off.
81
+ BASE_350M = ModelConfig(
82
+ vocab_size=50257,
83
+ max_seq_len=2048,
84
+ d_model=960,
85
+ n_layers=32,
86
+ n_heads=12, # head_dim = 80; 12 % 4 (n_kv_heads) == 0 ✓
87
+ n_kv_heads=4, # GQA: 3 query heads per KV head
88
+ mlp_ratio=8 / 3, # SwiGLU; 8/3 * 960 = 2560 lands on the 256 grid
89
+ mlp_multiple_of=256,
90
+ tie_weights=True,
91
+ qk_norm=True,
92
+ z_loss_coef=1e-4,
93
+ use_liger=True,
94
+ )
src/matilda/data.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Data streams + tokenized-shard tooling.
2
+
3
+ All streams expose the same interface so the training loop never changes when
4
+ we swap synthetic data for real tokenized FineWeb shards:
5
+
6
+ x, y = stream.next() # (B, T) input, (B, T) targets
7
+ state = stream.state_dict() # resumable position / RNG
8
+ stream.load_state_dict(state)
9
+
10
+ On-disk format: token ids as a flat `uint16` `.bin` (valid for vocab <= 65535,
11
+ which GPT-2's 50257 satisfies). A `manifest.json` records per-shard token counts
12
+ and SHA-256 so the prepared data is verifiable and reproducible.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import json
19
+ import glob
20
+ import hashlib
21
+
22
+ import numpy as np
23
+ import torch
24
+
25
+ DTYPE = np.uint16
26
+
27
+
28
+ # --------------------------------------------------------------------------
29
+ # shard writing / verification (used by scripts/prepare_data.py, unit-tested)
30
+ # --------------------------------------------------------------------------
31
+ def sha256_file(path, chunk=1 << 20) -> str:
32
+ h = hashlib.sha256()
33
+ with open(path, "rb") as f:
34
+ for block in iter(lambda: f.read(chunk), b""):
35
+ h.update(block)
36
+ return h.hexdigest()
37
+
38
+
39
+ class ShardWriter:
40
+ """Accumulate token ids and flush fixed-size `.bin` shards + a manifest."""
41
+
42
+ def __init__(self, out_dir, shard_tokens=100_000_000, prefix="shard"):
43
+ self.out_dir = out_dir
44
+ self.shard_tokens = shard_tokens
45
+ self.prefix = prefix
46
+ os.makedirs(out_dir, exist_ok=True)
47
+ self._buf: list[np.ndarray] = []
48
+ self._buf_len = 0
49
+ self._shard_idx = 0
50
+ self.total_tokens = 0
51
+ self.manifest_entries: list[dict] = []
52
+
53
+ def add(self, tokens) -> None:
54
+ arr = np.asarray(tokens, dtype=DTYPE)
55
+ self._buf.append(arr)
56
+ self._buf_len += arr.size
57
+ self.total_tokens += arr.size
58
+ while self._buf_len >= self.shard_tokens:
59
+ self._flush(self.shard_tokens)
60
+
61
+ def _flush(self, n) -> None:
62
+ flat = np.concatenate(self._buf) if len(self._buf) > 1 else self._buf[0]
63
+ out, rest = flat[:n], flat[n:]
64
+ path = os.path.join(self.out_dir, f"{self.prefix}_{self._shard_idx:05d}.bin")
65
+ out.tofile(path)
66
+ self.manifest_entries.append({
67
+ "file": os.path.basename(path),
68
+ "tokens": int(out.size),
69
+ "sha256": sha256_file(path),
70
+ })
71
+ self._shard_idx += 1
72
+ self._buf = [rest] if rest.size else []
73
+ self._buf_len = rest.size
74
+
75
+ def close(self, meta: dict | None = None) -> dict:
76
+ if self._buf_len > 0:
77
+ self._flush(self._buf_len) # final partial shard
78
+ manifest = {
79
+ "total_tokens": int(self.total_tokens),
80
+ "shards": self.manifest_entries,
81
+ **(meta or {}),
82
+ }
83
+ with open(os.path.join(self.out_dir, "manifest.json"), "w") as f:
84
+ json.dump(manifest, f, indent=2)
85
+ return manifest
86
+
87
+
88
+ def verify_manifest(out_dir) -> bool:
89
+ """Re-checksum every shard against the manifest. Raises on mismatch."""
90
+ with open(os.path.join(out_dir, "manifest.json")) as f:
91
+ manifest = json.load(f)
92
+ for entry in manifest["shards"]:
93
+ path = os.path.join(out_dir, entry["file"])
94
+ actual = sha256_file(path)
95
+ if actual != entry["sha256"]:
96
+ raise ValueError(f"checksum mismatch for {entry['file']}")
97
+ if os.path.getsize(path) != entry["tokens"] * 2: # uint16 = 2 bytes
98
+ raise ValueError(f"size mismatch for {entry['file']}")
99
+ return True
100
+
101
+
102
+ def shard_paths(out_dir) -> list[str]:
103
+ with open(os.path.join(out_dir, "manifest.json")) as f:
104
+ manifest = json.load(f)
105
+ return [os.path.join(out_dir, e["file"]) for e in manifest["shards"]]
106
+
107
+
108
+ # --------------------------------------------------------------------------
109
+ # streams
110
+ # --------------------------------------------------------------------------
111
+ class SyntheticStream:
112
+ """Deterministic random tokens. For dev/CI and loop testing on CPU."""
113
+
114
+ def __init__(self, vocab_size, batch_size, seq_len, seed=0, device="cpu"):
115
+ self.vocab_size = vocab_size
116
+ self.B = batch_size
117
+ self.T = seq_len
118
+ self.device = device
119
+ self.gen = torch.Generator().manual_seed(seed)
120
+ self.pos = 0
121
+
122
+ def next(self):
123
+ seq = torch.randint(0, self.vocab_size, (self.B, self.T + 1),
124
+ generator=self.gen)
125
+ x = seq[:, :-1].contiguous().to(self.device)
126
+ y = seq[:, 1:].contiguous().to(self.device)
127
+ self.pos += 1
128
+ return x, y
129
+
130
+ def state_dict(self):
131
+ return {"pos": self.pos, "gen": self.gen.get_state()}
132
+
133
+ def load_state_dict(self, s):
134
+ self.pos = s["pos"]
135
+ # set_state needs a CPU ByteTensor; map_location="cuda" can move it.
136
+ self.gen.set_state(s["gen"].cpu())
137
+
138
+
139
+ class BinStream:
140
+ """Packed windows sampled from memory-mapped uint16 token shards.
141
+
142
+ Each batch element is a random T+1 window from a shard chosen with
143
+ probability proportional to its size; x/y are the next-token shift. Random
144
+ sampling (rather than a sequential cursor) means epochs are implicit and
145
+ resume only needs the RNG state.
146
+ """
147
+
148
+ def __init__(self, bin_paths, batch_size, seq_len, seed=0, device="cpu"):
149
+ assert bin_paths, "no shards provided"
150
+ self.paths = list(bin_paths)
151
+ self.B = batch_size
152
+ self.T = seq_len
153
+ self.device = device
154
+ # Drop shards too small to sample a T+1 window (e.g. the small final
155
+ # overflow shard prepare_data emits). Filter by on-disk size FIRST so we
156
+ # never open mmaps we'll discard (those hold a file lock on Windows).
157
+ min_bytes = (seq_len + 2) * 2 # uint16 = 2 bytes/token
158
+ keep = [p for p in self.paths if os.path.getsize(p) >= min_bytes]
159
+ dropped = len(self.paths) - len(keep)
160
+ if dropped:
161
+ print(f"[data] skipping {dropped} shard(s) smaller than seq_len+1")
162
+ assert keep, "no shard is large enough for seq_len+1"
163
+ self.paths = keep
164
+ self.arrays = [np.memmap(p, dtype=DTYPE, mode="r") for p in keep]
165
+ self.sizes = torch.tensor([float(a.size) for a in self.arrays])
166
+ self.weights = self.sizes / self.sizes.sum()
167
+ self.gen = torch.Generator().manual_seed(seed)
168
+ self.pos = 0
169
+ # int32 halves H2D bytes vs int64; cast to long happens on the GPU.
170
+ # uint16 max (50257 vocab) exceeds int16 range, so int32 is the floor.
171
+ pin = (str(device) != "cpu")
172
+ self._xbuf = torch.empty((batch_size, seq_len), dtype=torch.int32,
173
+ pin_memory=pin)
174
+ self._ybuf = torch.empty((batch_size, seq_len), dtype=torch.int32,
175
+ pin_memory=pin)
176
+
177
+ def next(self):
178
+ # vectorized sampling: one multinomial + one rand call, no per-element sync
179
+ shard_ids = torch.multinomial(self.weights, self.B, replacement=True,
180
+ generator=self.gen)
181
+ u = torch.rand(self.B, generator=self.gen)
182
+ sizes = self.sizes[shard_ids]
183
+ starts = (u * (sizes - (self.T + 1)).clamp(min=0)).long()
184
+ xb = np.empty((self.B, self.T), dtype=np.int32)
185
+ yb = np.empty((self.B, self.T), dtype=np.int32)
186
+ for i in range(self.B):
187
+ arr = self.arrays[int(shard_ids[i])]
188
+ s = int(starts[i])
189
+ window = arr[s:s + self.T + 1].astype(np.int32)
190
+ xb[i] = window[:-1]
191
+ yb[i] = window[1:]
192
+ self.pos += 1
193
+ self._xbuf.copy_(torch.from_numpy(xb))
194
+ self._ybuf.copy_(torch.from_numpy(yb))
195
+ x = self._xbuf.to(self.device, non_blocking=True).long()
196
+ y = self._ybuf.to(self.device, non_blocking=True).long()
197
+ return x, y
198
+
199
+ def state_dict(self):
200
+ return {"pos": self.pos, "gen": self.gen.get_state()}
201
+
202
+ def load_state_dict(self, s):
203
+ self.pos = s["pos"]
204
+ # set_state needs a CPU ByteTensor; map_location="cuda" can move it.
205
+ self.gen.set_state(s["gen"].cpu())
src/matilda/model.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Modernized dense decoder-only transformer.
2
+
3
+ Block recipe (pre-norm): x = x + attn(rmsnorm(x)); x = x + swiglu(rmsnorm(x)).
4
+ Modernizations baked in from the start (validated free on Colab before any
5
+ paid run): RoPE, RMSNorm, SwiGLU, GQA, QK-Norm, weight tying, residual-scaled
6
+ init. This is the architecture the long A100 run uses.
7
+
8
+ Optional knobs for the 350M hero run, all default-off so the CPU/v1 path is
9
+ unchanged:
10
+ - z_loss_coef > 0: PaLM-style log-Z penalty, applied alongside CE
11
+ - use_liger: swap RMSNorm/RoPE/(linear+CE) for Liger Triton kernels. The
12
+ fused linear+CE skips materializing the (B*T, vocab) logit tensor, which
13
+ is the dominant memory cost at 350M with vocab=50257.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from .config import ModelConfig
25
+
26
+
27
+ def _import_liger():
28
+ """Lazy import so CPU tests don't pay for liger-kernel install.
29
+ Raises ImportError with a helpful message if use_liger=True without it."""
30
+ try:
31
+ from liger_kernel.transformers.rms_norm import LigerRMSNorm
32
+ from liger_kernel.transformers.rope import liger_rotary_pos_emb
33
+ from liger_kernel.transformers.fused_linear_cross_entropy import (
34
+ LigerFusedLinearCrossEntropyLoss,
35
+ )
36
+ except ImportError as e:
37
+ raise ImportError(
38
+ "use_liger=True requires liger-kernel. "
39
+ "Install: `pip install liger-kernel` (GPU only)."
40
+ ) from e
41
+ return LigerRMSNorm, liger_rotary_pos_emb, LigerFusedLinearCrossEntropyLoss
42
+
43
+
44
+ class RMSNorm(nn.Module):
45
+ """RMSNorm with the reduction done in fp32 for mixed-precision safety."""
46
+
47
+ def __init__(self, dim: int, eps: float = 1e-6):
48
+ super().__init__()
49
+ self.eps = eps
50
+ self.weight = nn.Parameter(torch.ones(dim))
51
+
52
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
53
+ dtype = x.dtype
54
+ x = x.float()
55
+ rms = x.pow(2).mean(dim=-1, keepdim=True).add(self.eps).rsqrt()
56
+ # keep the scale multiply in fp32, then cast back once
57
+ return ((x * rms) * self.weight.float()).to(dtype)
58
+
59
+
60
+ def build_rope_cache(head_dim: int, max_seq_len: int, theta: float,
61
+ device=None, dtype=torch.float32):
62
+ """Precompute (cos, sin) of shape (max_seq_len, head_dim).
63
+
64
+ Half-rotation (Llama) convention: freqs are computed for head_dim/2 pairs
65
+ and concatenated with themselves so they line up with rotate_half.
66
+ """
67
+ i = torch.arange(0, head_dim, 2, device=device, dtype=torch.float32)
68
+ inv_freq = 1.0 / (theta ** (i / head_dim)) # (head_dim/2,)
69
+ t = torch.arange(max_seq_len, device=device, dtype=torch.float32)
70
+ freqs = torch.outer(t, inv_freq) # (T, head_dim/2)
71
+ emb = torch.cat([freqs, freqs], dim=-1) # (T, head_dim)
72
+ return emb.cos().to(dtype), emb.sin().to(dtype)
73
+
74
+
75
+ def _rotate_half(x: torch.Tensor) -> torch.Tensor:
76
+ x1, x2 = x.chunk(2, dim=-1)
77
+ return torch.cat([-x2, x1], dim=-1)
78
+
79
+
80
+ def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
81
+ # x: (B, n_heads, T, head_dim); cos/sin: (T, head_dim) -> broadcast
82
+ cos = cos[None, None, :, :]
83
+ sin = sin[None, None, :, :]
84
+ return (x * cos) + (_rotate_half(x) * sin)
85
+
86
+
87
+ class Attention(nn.Module):
88
+ """Causal grouped-query attention with optional QK-Norm and RoPE."""
89
+
90
+ def __init__(self, cfg: ModelConfig, liger=None):
91
+ super().__init__()
92
+ self.n_heads = cfg.n_heads
93
+ self.n_kv_heads = cfg.n_kv_heads
94
+ self.head_dim = cfg.head_dim
95
+ self.n_rep = cfg.n_heads // cfg.n_kv_heads
96
+
97
+ self.wq = nn.Linear(cfg.d_model, cfg.n_heads * self.head_dim, bias=False)
98
+ self.wk = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
99
+ self.wv = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
100
+ self.wo = nn.Linear(cfg.n_heads * self.head_dim, cfg.d_model, bias=False)
101
+
102
+ self.qk_norm = cfg.qk_norm
103
+ if cfg.qk_norm:
104
+ norm_cls = liger[0] if liger else RMSNorm
105
+ self.q_norm = norm_cls(self.head_dim, cfg.norm_eps)
106
+ self.k_norm = norm_cls(self.head_dim, cfg.norm_eps)
107
+ self.dropout = cfg.dropout
108
+ self.softcap = cfg.attn_logit_softcap
109
+ self._liger_rope = liger[1] if liger else None
110
+
111
+ def _apply_rope(self, q, k, cos, sin):
112
+ if self._liger_rope is not None:
113
+ return self._liger_rope(q, k, cos, sin)
114
+ return apply_rope(q, cos, sin), apply_rope(k, cos, sin)
115
+
116
+ def forward(self, x, cos, sin):
117
+ B, T, _ = x.shape
118
+ q = self.wq(x).view(B, T, self.n_heads, self.head_dim)
119
+ k = self.wk(x).view(B, T, self.n_kv_heads, self.head_dim)
120
+ v = self.wv(x).view(B, T, self.n_kv_heads, self.head_dim)
121
+
122
+ if self.qk_norm:
123
+ q = self.q_norm(q)
124
+ k = self.k_norm(k)
125
+
126
+ # (B, n_heads, T, head_dim)
127
+ q = q.transpose(1, 2)
128
+ k = k.transpose(1, 2)
129
+ v = v.transpose(1, 2)
130
+
131
+ q, k = self._apply_rope(q, k, cos, sin)
132
+
133
+ # expand KV heads to match Q heads (GQA). repeat_interleave on head dim.
134
+ if self.n_rep > 1:
135
+ k = k.repeat_interleave(self.n_rep, dim=1)
136
+ v = v.repeat_interleave(self.n_rep, dim=1)
137
+
138
+ if self.softcap > 0:
139
+ out = self._attn_softcap(q, k, v, T) # eager path, no Flash
140
+ else:
141
+ out = F.scaled_dot_product_attention(
142
+ q, k, v, is_causal=True,
143
+ dropout_p=self.dropout if self.training else 0.0,
144
+ )
145
+ out = out.transpose(1, 2).contiguous().view(B, T, -1)
146
+ return self.wo(out)
147
+
148
+ def _attn_softcap(self, q, k, v, T):
149
+ # tanh logit soft-cap (Gemma-2 style). Disables the fused SDPA kernel,
150
+ # so only used for the qk_norm=False stability ablation.
151
+ scale = 1.0 / math.sqrt(self.head_dim)
152
+ scores = torch.matmul(q, k.transpose(-2, -1)) * scale
153
+ scores = self.softcap * torch.tanh(scores / self.softcap)
154
+ mask = torch.ones(T, T, dtype=torch.bool, device=q.device).tril()
155
+ scores = scores.masked_fill(~mask, float("-inf"))
156
+ attn = F.softmax(scores, dim=-1)
157
+ return torch.matmul(attn, v)
158
+
159
+
160
+ class SwiGLU(nn.Module):
161
+ def __init__(self, cfg: ModelConfig):
162
+ super().__init__()
163
+ hidden = int(cfg.mlp_ratio * cfg.d_model)
164
+ m = cfg.mlp_multiple_of
165
+ hidden = ((hidden + m - 1) // m) * m
166
+ self.gate = nn.Linear(cfg.d_model, hidden, bias=False)
167
+ self.up = nn.Linear(cfg.d_model, hidden, bias=False)
168
+ self.down = nn.Linear(hidden, cfg.d_model, bias=False)
169
+
170
+ def forward(self, x):
171
+ return self.down(F.silu(self.gate(x)) * self.up(x))
172
+
173
+
174
+ class Block(nn.Module):
175
+ def __init__(self, cfg: ModelConfig, liger=None):
176
+ super().__init__()
177
+ norm_cls = liger[0] if liger else RMSNorm
178
+ self.norm1 = norm_cls(cfg.d_model, cfg.norm_eps)
179
+ self.attn = Attention(cfg, liger=liger)
180
+ self.norm2 = norm_cls(cfg.d_model, cfg.norm_eps)
181
+ self.mlp = SwiGLU(cfg)
182
+
183
+ def forward(self, x, cos, sin):
184
+ x = x + self.attn(self.norm1(x), cos, sin)
185
+ x = x + self.mlp(self.norm2(x))
186
+ return x
187
+
188
+
189
+ class Transformer(nn.Module):
190
+ def __init__(self, cfg: ModelConfig):
191
+ super().__init__()
192
+ self.cfg = cfg
193
+
194
+ # Liger bundle: (RMSNorm class, rope fn, FLCE class) or None.
195
+ # Built once and threaded through Block/Attention so every layer uses
196
+ # the same kernel family — avoids per-layer import cost.
197
+ liger = _import_liger() if cfg.use_liger else None
198
+ self._liger = liger
199
+ self._flce = None
200
+ if liger is not None:
201
+ self._flce = liger[2](
202
+ ignore_index=-1,
203
+ lse_square_scale=cfg.z_loss_coef, # z-loss handled in-kernel
204
+ label_smoothing=0.0,
205
+ reduction="mean",
206
+ )
207
+
208
+ norm_cls = liger[0] if liger else RMSNorm
209
+ self.embed = nn.Embedding(cfg.vocab_size, cfg.d_model)
210
+ self.blocks = nn.ModuleList(
211
+ [Block(cfg, liger=liger) for _ in range(cfg.n_layers)])
212
+ self.norm_f = norm_cls(cfg.d_model, cfg.norm_eps)
213
+ self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
214
+ if cfg.tie_weights:
215
+ self.lm_head.weight = self.embed.weight
216
+
217
+ cos, sin = build_rope_cache(cfg.head_dim, cfg.max_seq_len, cfg.rope_theta)
218
+ self.register_buffer("rope_cos", cos, persistent=False)
219
+ self.register_buffer("rope_sin", sin, persistent=False)
220
+
221
+ self.apply(self._init_weights)
222
+ # Residual-projection scaling (GPT-2 trick): keep residual-stream growth
223
+ # bounded with depth by shrinking the layers that write back into it.
224
+ scale = 1.0 / math.sqrt(2 * cfg.n_layers)
225
+ for name, p in self.named_parameters():
226
+ if name.endswith("wo.weight") or name.endswith("down.weight"):
227
+ with torch.no_grad():
228
+ p.mul_(scale)
229
+
230
+ def _init_weights(self, module):
231
+ if isinstance(module, nn.Linear):
232
+ nn.init.normal_(module.weight, mean=0.0, std=self.cfg.init_std)
233
+ if module.bias is not None:
234
+ nn.init.zeros_(module.bias)
235
+ elif isinstance(module, nn.Embedding):
236
+ nn.init.normal_(module.weight, mean=0.0, std=self.cfg.init_std)
237
+
238
+ def forward(self, idx: torch.Tensor, targets: torch.Tensor | None = None):
239
+ B, T = idx.shape
240
+ assert T <= self.cfg.max_seq_len, "sequence longer than rope cache"
241
+ x = self.embed(idx)
242
+ cos = self.rope_cos[:T]
243
+ sin = self.rope_sin[:T]
244
+ for block in self.blocks:
245
+ x = block(x, cos, sin)
246
+ x = self.norm_f(x)
247
+
248
+ # Fused linear+CE path: skip logit materialization (the 350M+vocab=50k
249
+ # memory hot-spot). Returns logits=None — training never uses them.
250
+ if self._flce is not None and targets is not None:
251
+ loss = self._flce(
252
+ self.lm_head.weight,
253
+ x.view(-1, x.size(-1)),
254
+ targets.view(-1),
255
+ )
256
+ return None, loss
257
+
258
+ logits = self.lm_head(x)
259
+ if targets is None:
260
+ return logits, None
261
+
262
+ loss = F.cross_entropy(
263
+ logits.view(-1, logits.size(-1)),
264
+ targets.view(-1),
265
+ ignore_index=-1,
266
+ )
267
+ if self.cfg.z_loss_coef > 0:
268
+ # PaLM/Pythia-style: penalize log(Z) magnitude to keep logits bounded.
269
+ log_z = logits.logsumexp(dim=-1)
270
+ loss = loss + self.cfg.z_loss_coef * (log_z ** 2).mean()
271
+ return logits, loss
272
+
273
+ def num_params(self, non_embedding: bool = True) -> int:
274
+ n = sum(p.numel() for p in self.parameters())
275
+ if non_embedding:
276
+ # tied: lm_head shares embed, so subtract the one embedding table
277
+ n -= self.embed.weight.numel()
278
+ return n
src/matilda/monitor.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Throughput / utilization observability.
2
+
3
+ MFU (Model FLOPs Utilization) is the headline number a training engineer lives
4
+ in: what fraction of the GPU's theoretical bf16 throughput you actually extract.
5
+ We also track a rolling step-time window so a *degradation* mid-run (thermal
6
+ throttling, a noisy Vast neighbour) is visible, not just the instantaneous rate.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ from collections import deque
13
+
14
+ # Peak bf16 *dense* TFLOPs (no 2:4 sparsity). Substring-matched on device name.
15
+ PEAK_TFLOPS_BF16 = {
16
+ "A100": 312.0,
17
+ "H100": 494.0,
18
+ "H800": 494.0,
19
+ "4090": 165.0,
20
+ "3090": 71.0,
21
+ "3060": 51.0,
22
+ "T4": 65.0, # fp16; T4 has no native bf16 (Turing) -> emulated, ignore MFU
23
+ "A10": 125.0,
24
+ "L4": 121.0,
25
+ }
26
+
27
+
28
+ def peak_tflops(device_name: str, default: float = 312.0) -> float:
29
+ for key, val in PEAK_TFLOPS_BF16.items():
30
+ if key in device_name:
31
+ return val
32
+ return default
33
+
34
+
35
+ def mfu(n_params_active: int, tokens_per_step: int, dt_seconds: float,
36
+ peak_flops_per_sec: float) -> float:
37
+ """Raw 6N-flops/token MFU (no attention term). Kept for quick estimates."""
38
+ if dt_seconds <= 0:
39
+ return 0.0
40
+ achieved = 6 * n_params_active * tokens_per_step / dt_seconds
41
+ return achieved / peak_flops_per_sec
42
+
43
+
44
+ def flops_per_token(n_params, n_layers, d_model, seq_len) -> float:
45
+ """Karpathy/PaLM estimate: 6N (all matmuls incl. QKVO projections) plus the
46
+ attention score+value matmuls that scale with sequence length and are NOT
47
+ captured by the parameter count: 12 * L * d_model * T per token.
48
+ """
49
+ return 6 * n_params + 12 * n_layers * d_model * seq_len
50
+
51
+
52
+ class Throughput:
53
+ """Rolling step-time tracker; reports tokens/sec and MFU.
54
+
55
+ `warmup` ticks are excluded from the running average so torch.compile /
56
+ cuDNN autotuning on the first steps doesn't depress the reported MFU.
57
+ """
58
+
59
+ def __init__(self, flops_per_step, tokens_per_step, peak_flops_per_sec,
60
+ window=50, warmup=10):
61
+ self.fps = flops_per_step
62
+ self.tps = tokens_per_step
63
+ self.peak = peak_flops_per_sec
64
+ self.times = deque(maxlen=window)
65
+ self.warmup = warmup
66
+ self._n = 0
67
+ self._t0 = None
68
+
69
+ def _mfu(self, dt):
70
+ return (self.fps / dt) / self.peak if dt > 0 else 0.0
71
+
72
+ def tick(self) -> dict | None:
73
+ now = time.perf_counter()
74
+ if self._t0 is None:
75
+ self._t0 = now
76
+ return None
77
+ dt = now - self._t0
78
+ self._t0 = now
79
+ self._n += 1
80
+ if self._n > self.warmup:
81
+ self.times.append(dt)
82
+ avg = (sum(self.times) / len(self.times)) if self.times else dt
83
+ return {
84
+ "dt_s": dt,
85
+ "dt_avg_s": avg,
86
+ "tokens_per_s": self.tps / dt,
87
+ "mfu": self._mfu(dt),
88
+ "mfu_avg": self._mfu(avg),
89
+ }
src/matilda/optim.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optimizer + LR schedule construction.
2
+
3
+ Two details that materially affect quality and that most tutorials get wrong:
4
+ 1. No weight decay on 1-D params (norms, biases) or the embedding table.
5
+ Decaying norm/embedding weights quietly hurts.
6
+ 2. The LR schedule includes linear warmup; starting at peak LR on random
7
+ weights diverges.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+
14
+ import torch
15
+
16
+
17
+ def _adamw(groups, lr, betas, eps):
18
+ """AdamW with fused kernel when available, falling back if unsupported."""
19
+ fused = torch.cuda.is_available()
20
+ try:
21
+ return torch.optim.AdamW(groups, lr=lr, betas=betas, eps=eps, fused=fused)
22
+ except (RuntimeError, TypeError):
23
+ return torch.optim.AdamW(groups, lr=lr, betas=betas, eps=eps)
24
+
25
+
26
+ def build_adamw(model, lr=3e-4, weight_decay=0.1,
27
+ betas=(0.9, 0.95), eps=1e-8) -> torch.optim.AdamW:
28
+ decay, no_decay = [], []
29
+ for name, p in model.named_parameters():
30
+ if not p.requires_grad:
31
+ continue
32
+ # 2-D matmul weights get decay; norms/biases (1-D) and embeddings don't.
33
+ if p.ndim < 2 or "embed" in name:
34
+ no_decay.append(p)
35
+ else:
36
+ decay.append(p)
37
+ groups = [
38
+ {"params": decay, "weight_decay": weight_decay},
39
+ {"params": no_decay, "weight_decay": 0.0},
40
+ ]
41
+ return _adamw(groups, lr, betas, eps)
42
+
43
+
44
+ @torch.no_grad()
45
+ def zeropower_via_newtonschulz5(G, steps=5, eps=1e-7):
46
+ """Orthogonalize a 2-D gradient via the quintic Newton-Schulz iteration
47
+ (Keller Jordan). Pushes all singular values toward 1 in ~5 matmuls, so the
48
+ update weights every direction equally instead of being dominated by large
49
+ singular directions. Runs in bf16, as in the reference implementation.
50
+ """
51
+ assert G.ndim == 2
52
+ a, b, c = 3.4445, -4.7750, 2.0315
53
+ X = G.bfloat16()
54
+ X = X / (X.norm() + eps)
55
+ transposed = G.size(0) > G.size(1)
56
+ if transposed:
57
+ X = X.T
58
+ for _ in range(steps):
59
+ A = X @ X.T
60
+ B = b * A + c * (A @ A)
61
+ X = a * X + B @ X
62
+ if transposed:
63
+ X = X.T
64
+ return X.to(G.dtype)
65
+
66
+
67
+ class Muon(torch.optim.Optimizer):
68
+ """Muon: momentum + orthogonalized update for 2-D parameters only.
69
+
70
+ Use ONLY for interior matrices (attn/MLP weights). Embeddings, norms, biases
71
+ must stay on AdamW (see build_optimizer). Muon's natural LR is ~0.02, much
72
+ higher than Adam's, because the orthogonalized update has ~unit scale.
73
+ """
74
+
75
+ def __init__(self, params, lr=0.02, momentum=0.95, nesterov=True, ns_steps=5):
76
+ super().__init__(params, dict(lr=lr, momentum=momentum,
77
+ nesterov=nesterov, ns_steps=ns_steps))
78
+
79
+ @torch.no_grad()
80
+ def step(self):
81
+ for group in self.param_groups:
82
+ lr, mom, nesterov = group["lr"], group["momentum"], group["nesterov"]
83
+ for p in group["params"]:
84
+ if p.grad is None:
85
+ continue
86
+ g = p.grad
87
+ state = self.state[p]
88
+ if "m" not in state:
89
+ state["m"] = torch.zeros_like(g)
90
+ buf = state["m"]
91
+ buf.mul_(mom).add_(g)
92
+ g = g.add(buf, alpha=mom) if nesterov else buf
93
+ g = zeropower_via_newtonschulz5(g, steps=group["ns_steps"])
94
+ # scale so the update RMS matches across differently-shaped matrices
95
+ scale = max(1.0, p.size(0) / p.size(1)) ** 0.5
96
+ p.add_(g, alpha=-lr * scale)
97
+
98
+
99
+ class HybridOptimizer:
100
+ """Presents several optimizers as one (unified step/zero_grad/state_dict and
101
+ a concatenated param_groups so a single LR scheduler drives all of them)."""
102
+
103
+ def __init__(self, optimizers):
104
+ self.optimizers = optimizers
105
+
106
+ @property
107
+ def param_groups(self):
108
+ return [g for o in self.optimizers for g in o.param_groups]
109
+
110
+ def zero_grad(self, set_to_none=True):
111
+ for o in self.optimizers:
112
+ o.zero_grad(set_to_none=set_to_none)
113
+
114
+ def step(self):
115
+ for o in self.optimizers:
116
+ o.step()
117
+
118
+ def state_dict(self):
119
+ return {"opts": [o.state_dict() for o in self.optimizers]}
120
+
121
+ def load_state_dict(self, sd):
122
+ for o, s in zip(self.optimizers, sd["opts"]):
123
+ o.load_state_dict(s)
124
+
125
+
126
+ def build_optimizer(model, name="adamw", lr=3e-4, weight_decay=0.1,
127
+ betas=(0.9, 0.95), eps=1e-8, muon_lr=0.02):
128
+ """Dispatch: 'adamw' (default) or 'muon' (Muon on 2-D interior weights +
129
+ AdamW on embeddings/norms/biases)."""
130
+ if name == "adamw":
131
+ return build_adamw(model, lr, weight_decay, betas, eps)
132
+ if name != "muon":
133
+ raise ValueError(f"unknown optimizer: {name}")
134
+
135
+ muon_p, adamw_decay, adamw_nodecay = [], [], []
136
+ for n, p in model.named_parameters():
137
+ if not p.requires_grad:
138
+ continue
139
+ if p.ndim == 2 and "embed" not in n: # interior matrices -> Muon
140
+ muon_p.append(p)
141
+ elif p.ndim < 2 or "embed" in n: # norms/biases/embeddings -> AdamW
142
+ adamw_nodecay.append(p)
143
+ else:
144
+ adamw_decay.append(p)
145
+ adamw = _adamw(
146
+ [{"params": adamw_decay, "weight_decay": weight_decay},
147
+ {"params": adamw_nodecay, "weight_decay": 0.0}],
148
+ lr, betas, eps)
149
+ return HybridOptimizer([Muon(muon_p, lr=muon_lr), adamw])
150
+
151
+
152
+ class WarmupCosine:
153
+ """Linear warmup then cosine decay to min_lr_ratio * peak.
154
+
155
+ Works on any object exposing `param_groups` (torch optimizers AND our
156
+ HybridOptimizer, which torch's LambdaLR rejects). Applies one multiplier to
157
+ every group, scaling each group's own base lr (so Muon's 0.02 and AdamW's
158
+ 3e-4 warm up/decay together). state_dict captures the step for exact resume.
159
+ """
160
+
161
+ def __init__(self, optimizer, warmup_steps, total_steps, min_lr_ratio=0.1):
162
+ self.opt = optimizer
163
+ self.warmup_steps = warmup_steps
164
+ self.total_steps = total_steps
165
+ self.min_lr_ratio = min_lr_ratio
166
+ self.base_lrs = [g["lr"] for g in optimizer.param_groups]
167
+ self.last_step = -1
168
+ self.step() # apply step 0
169
+
170
+ def _scale(self, step):
171
+ if step < self.warmup_steps:
172
+ return (step + 1) / max(1, self.warmup_steps)
173
+ if step >= self.total_steps:
174
+ return self.min_lr_ratio
175
+ progress = (step - self.warmup_steps) / max(1, self.total_steps - self.warmup_steps)
176
+ cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
177
+ return self.min_lr_ratio + (1 - self.min_lr_ratio) * cosine
178
+
179
+ def step(self):
180
+ self.last_step += 1
181
+ s = self._scale(self.last_step)
182
+ for group, base in zip(self.opt.param_groups, self.base_lrs):
183
+ group["lr"] = base * s
184
+
185
+ def get_last_lr(self):
186
+ return [g["lr"] for g in self.opt.param_groups]
187
+
188
+ def state_dict(self):
189
+ return {"last_step": self.last_step, "base_lrs": self.base_lrs}
190
+
191
+ def load_state_dict(self, sd):
192
+ self.last_step = sd["last_step"]
193
+ self.base_lrs = sd["base_lrs"]
194
+ # re-apply so lrs match the restored step
195
+ s = self._scale(self.last_step)
196
+ for group, base in zip(self.opt.param_groups, self.base_lrs):
197
+ group["lr"] = base * s
198
+
199
+
200
+ def cosine_warmup_scheduler(optimizer, warmup_steps, total_steps, min_lr_ratio=0.1):
201
+ return WarmupCosine(optimizer, warmup_steps, total_steps, min_lr_ratio)
202
+
203
+
204
+ class WarmupStableDecay:
205
+ """Linear warmup -> hold at peak -> linear decay to min_lr_ratio * peak.
206
+
207
+ MiniCPM-style WSD: empirically beats cosine at sub-1B scale, and intermediate
208
+ checkpoints stay useful because they're sampled at peak LR (no slow-roll decay).
209
+ `stable_share` is the fraction of the post-warmup steps spent at peak LR
210
+ (rest is the decay phase). 0.8 is MiniCPM's reported sweet spot.
211
+
212
+ Same interface contract as WarmupCosine so train.py just dispatches by name
213
+ and the rest of the stack (resume, multi-group LRs, HybridOptimizer) is
214
+ unchanged.
215
+ """
216
+
217
+ def __init__(self, optimizer, warmup_steps, total_steps,
218
+ stable_share=0.8, min_lr_ratio=0.1):
219
+ assert 0.0 < stable_share < 1.0, "stable_share must be in (0, 1)"
220
+ self.opt = optimizer
221
+ self.warmup_steps = warmup_steps
222
+ self.total_steps = total_steps
223
+ self.stable_share = stable_share
224
+ self.min_lr_ratio = min_lr_ratio
225
+ post_warm = max(1, total_steps - warmup_steps)
226
+ self.decay_start = warmup_steps + int(stable_share * post_warm)
227
+ self.base_lrs = [g["lr"] for g in optimizer.param_groups]
228
+ self.last_step = -1
229
+ self.step() # apply step 0
230
+
231
+ def _scale(self, step):
232
+ if step < self.warmup_steps:
233
+ return (step + 1) / max(1, self.warmup_steps)
234
+ if step < self.decay_start:
235
+ return 1.0
236
+ if step >= self.total_steps:
237
+ return self.min_lr_ratio
238
+ progress = (step - self.decay_start) / max(
239
+ 1, self.total_steps - self.decay_start)
240
+ return 1.0 - progress * (1.0 - self.min_lr_ratio)
241
+
242
+ def step(self):
243
+ self.last_step += 1
244
+ s = self._scale(self.last_step)
245
+ for group, base in zip(self.opt.param_groups, self.base_lrs):
246
+ group["lr"] = base * s
247
+
248
+ def get_last_lr(self):
249
+ return [g["lr"] for g in self.opt.param_groups]
250
+
251
+ def state_dict(self):
252
+ return {"last_step": self.last_step, "base_lrs": self.base_lrs}
253
+
254
+ def load_state_dict(self, sd):
255
+ self.last_step = sd["last_step"]
256
+ self.base_lrs = sd["base_lrs"]
257
+ s = self._scale(self.last_step)
258
+ for group, base in zip(self.opt.param_groups, self.base_lrs):
259
+ group["lr"] = base * s
260
+
261
+
262
+ def wsd_scheduler(optimizer, warmup_steps, total_steps,
263
+ stable_share=0.8, min_lr_ratio=0.1):
264
+ return WarmupStableDecay(optimizer, warmup_steps, total_steps,
265
+ stable_share, min_lr_ratio)
266
+
267
+
268
+ def build_scheduler(name, optimizer, warmup_steps, total_steps,
269
+ stable_share=0.8, min_lr_ratio=0.1):
270
+ """Dispatch by name: 'cosine' (v1 default) or 'wsd' (MiniCPM)."""
271
+ if name == "cosine":
272
+ return cosine_warmup_scheduler(optimizer, warmup_steps, total_steps,
273
+ min_lr_ratio)
274
+ if name == "wsd":
275
+ return wsd_scheduler(optimizer, warmup_steps, total_steps,
276
+ stable_share, min_lr_ratio)
277
+ raise ValueError(f"unknown lr_schedule: {name}")
src/matilda/train.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training loop with the reliability guards a long run needs.
2
+
3
+ Designed so an overnight Vast run survives the things that actually kill runs:
4
+ - one bad batch (NaN/Inf loss or grad) -> skip it, log loudly, keep going
5
+ - spot-instance SIGTERM -> checkpoint before exiting
6
+ - process death -> resume bit-for-bit from latest checkpoint on restart
7
+
8
+ Throughput (MFU, tokens/s, step-time) is logged every `log_every` steps. The
9
+ data source is any object with .next()/.state_dict()/.load_state_dict() (see
10
+ data.py), so swapping synthetic data for real FineWeb shards changes nothing.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import json
17
+ import signal
18
+ import subprocess
19
+ from dataclasses import dataclass, asdict
20
+
21
+ import torch
22
+
23
+ from .model import Transformer
24
+ from .config import ModelConfig
25
+ from .optim import build_optimizer, build_scheduler
26
+ from .monitor import Throughput, peak_tflops, flops_per_token
27
+ from .checkpoint import (
28
+ save_checkpoint, load_checkpoint, latest_checkpoint, rotate_checkpoints,
29
+ )
30
+
31
+
32
+ def get_git_sha() -> str:
33
+ try:
34
+ return subprocess.check_output(
35
+ ["git", "rev-parse", "HEAD"], text=True,
36
+ stderr=subprocess.DEVNULL).strip()
37
+ except Exception:
38
+ return "unknown"
39
+
40
+
41
+ def setup_backends():
42
+ """Free A100 throughput: TF32 matmuls + cuDNN autotuner."""
43
+ if torch.cuda.is_available():
44
+ torch.set_float32_matmul_precision("high")
45
+ torch.backends.cuda.matmul.allow_tf32 = True
46
+ torch.backends.cudnn.allow_tf32 = True
47
+ torch.backends.cudnn.benchmark = True
48
+
49
+
50
+ @dataclass
51
+ class TrainConfig:
52
+ total_steps: int = 1000
53
+ warmup_steps: int = 100
54
+ grad_accum: int = 1
55
+ lr: float = 3e-4
56
+ weight_decay: float = 0.1
57
+ grad_clip: float = 1.0
58
+ min_lr_ratio: float = 0.1
59
+ optimizer: str = "adamw" # "adamw" or "muon" (Muon+AdamW hybrid)
60
+ muon_lr: float = 0.02
61
+ lr_schedule: str = "cosine" # "cosine" (v1) or "wsd" (MiniCPM, hero)
62
+ wsd_stable_share: float = 0.8 # only used when lr_schedule="wsd"
63
+
64
+ batch_size: int = 8
65
+ seq_len: int = 1024
66
+
67
+ log_every: int = 10
68
+ ckpt_every: int = 500
69
+ keep_last: int = 3
70
+ ckpt_dir: str = "checkpoints"
71
+
72
+ device: str = "cuda"
73
+ dtype: str = "bfloat16" # bf16 on Ampere+, fp32 fallback on CPU
74
+ compile: bool = False
75
+ seed: int = 1234
76
+ max_skips: int = 20 # abort if too many bad batches in a row
77
+ wandb_project: str | None = None
78
+
79
+
80
+ class Trainer:
81
+ def __init__(self, model_cfg: ModelConfig, train_cfg: TrainConfig, stream):
82
+ self.mcfg = model_cfg
83
+ self.cfg = train_cfg
84
+ self.stream = stream
85
+ self.step = 0
86
+ self.consecutive_skips = 0
87
+ self._interrupted = False
88
+
89
+ setup_backends()
90
+ self.git_sha = get_git_sha()
91
+ torch.manual_seed(train_cfg.seed)
92
+ self.device = torch.device(
93
+ train_cfg.device if torch.cuda.is_available()
94
+ or train_cfg.device == "cpu" else "cpu")
95
+
96
+ self.model = Transformer(model_cfg).to(self.device)
97
+ if train_cfg.compile:
98
+ self.model = torch.compile(self.model)
99
+ self.opt = build_optimizer(self.model, name=train_cfg.optimizer,
100
+ lr=train_cfg.lr,
101
+ weight_decay=train_cfg.weight_decay,
102
+ muon_lr=train_cfg.muon_lr)
103
+ self.sched = build_scheduler(
104
+ train_cfg.lr_schedule, self.opt,
105
+ train_cfg.warmup_steps, train_cfg.total_steps,
106
+ stable_share=train_cfg.wsd_stable_share,
107
+ min_lr_ratio=train_cfg.min_lr_ratio)
108
+
109
+ # bf16 only where supported; CPU/T4 fall back to fp32 for correctness.
110
+ want_bf16 = (train_cfg.dtype == "bfloat16"
111
+ and self.device.type == "cuda"
112
+ and torch.cuda.is_bf16_supported())
113
+ self.amp_dtype = torch.bfloat16 if want_bf16 else None
114
+
115
+ tokens_per_step = (train_cfg.batch_size * train_cfg.seq_len
116
+ * train_cfg.grad_accum)
117
+ dev_name = (torch.cuda.get_device_name(self.device)
118
+ if self.device.type == "cuda" else "cpu")
119
+ fps = flops_per_token(self._active_params(), model_cfg.n_layers,
120
+ model_cfg.d_model, train_cfg.seq_len) * tokens_per_step
121
+ self.monitor = Throughput(
122
+ flops_per_step=fps,
123
+ tokens_per_step=tokens_per_step,
124
+ peak_flops_per_sec=peak_tflops(dev_name) * 1e12,
125
+ )
126
+ self.metrics_path = os.path.join(train_cfg.ckpt_dir, "metrics.jsonl")
127
+ self.wandb = self._init_wandb()
128
+ self._install_signal_handlers()
129
+
130
+ # --- helpers -----------------------------------------------------------
131
+ def _unwrap(self):
132
+ m = self.model
133
+ if hasattr(m, "_orig_mod"): # torch.compile
134
+ m = m._orig_mod
135
+ if hasattr(m, "module"): # DDP
136
+ m = m.module
137
+ return m
138
+
139
+ def _active_params(self):
140
+ return self._unwrap().num_params(non_embedding=True)
141
+
142
+ def _init_wandb(self):
143
+ if not self.cfg.wandb_project:
144
+ return None
145
+ try:
146
+ import wandb
147
+ except ImportError:
148
+ print("[warn] wandb not installed; using metrics.jsonl only")
149
+ return None
150
+ try:
151
+ wandb.init(project=self.cfg.wandb_project,
152
+ config={**self.mcfg.to_dict(), **vars(self.cfg)})
153
+ return wandb
154
+ except Exception as e: # network/auth/quota — non-fatal
155
+ print(f"[warn] wandb init failed: {e}")
156
+ return None
157
+
158
+ def _install_signal_handlers(self):
159
+ def handler(signum, frame):
160
+ print(f"[signal] {signum} received -> checkpoint and exit")
161
+ self._interrupted = True
162
+ for sig in (signal.SIGINT, signal.SIGTERM):
163
+ try:
164
+ signal.signal(sig, handler)
165
+ except (ValueError, OSError) as e:
166
+ # not in main thread (e.g. under pytest) -> can't install
167
+ print(f"[warn] could not install handler for signal {sig}: {e}")
168
+
169
+ def _autocast(self):
170
+ if self.amp_dtype is not None:
171
+ return torch.autocast(device_type="cuda", dtype=self.amp_dtype)
172
+ return torch.autocast(device_type="cpu", enabled=False)
173
+
174
+ # --- checkpoint --------------------------------------------------------
175
+ def _ckpt_path(self):
176
+ return os.path.join(self.cfg.ckpt_dir, f"ckpt_{self.step}.pt")
177
+
178
+ def save(self):
179
+ save_checkpoint(self._ckpt_path(), model=self.model, optimizer=self.opt,
180
+ scheduler=self.sched, step=self.step, config=self.mcfg,
181
+ data_state=self.stream.state_dict(),
182
+ extra={"train_config": asdict(self.cfg),
183
+ "git_sha": self.git_sha})
184
+ rotate_checkpoints(self.cfg.ckpt_dir, self.cfg.keep_last)
185
+
186
+ def maybe_resume(self):
187
+ path = latest_checkpoint(self.cfg.ckpt_dir)
188
+ if path is None:
189
+ return False
190
+ ck = load_checkpoint(path, model=self.model, optimizer=self.opt,
191
+ scheduler=self.sched,
192
+ map_location=self.device)
193
+ self.step = ck["step"]
194
+ if ck.get("data_state") is not None:
195
+ self.stream.load_state_dict(ck["data_state"])
196
+ # warn if the schedule changed since the checkpoint (silent LR corruption)
197
+ prev = (ck.get("extra") or {}).get("train_config", {})
198
+ for k in ("total_steps", "warmup_steps", "lr"):
199
+ if k in prev and prev[k] != getattr(self.cfg, k):
200
+ print(f"[warn] {k} changed on resume: {prev[k]} -> "
201
+ f"{getattr(self.cfg, k)}; LR schedule will differ")
202
+ print(f"[resume] from {path} at step {self.step}")
203
+ return True
204
+
205
+ # --- one optimizer step (grad accum + guards) --------------------------
206
+ def _step(self):
207
+ self.opt.zero_grad(set_to_none=True)
208
+ total_loss = 0.0
209
+ for micro in range(self.cfg.grad_accum):
210
+ x, y = self.stream.next()
211
+ x = x.to(self.device, non_blocking=True)
212
+ y = y.to(self.device, non_blocking=True)
213
+ sync = (micro == self.cfg.grad_accum - 1)
214
+ ctx = (self.model.no_sync()
215
+ if (not sync and hasattr(self.model, "no_sync"))
216
+ else _nullcontext())
217
+ with ctx, self._autocast():
218
+ _, loss = self.model(x, y)
219
+ loss = loss / self.cfg.grad_accum
220
+ if not torch.isfinite(loss):
221
+ return None # bad micro-batch -> abort this step
222
+ loss.backward()
223
+ total_loss += loss.item()
224
+
225
+ grad_norm = torch.nn.utils.clip_grad_norm_(
226
+ self.model.parameters(), self.cfg.grad_clip)
227
+ if not torch.isfinite(grad_norm):
228
+ return None # non-finite grad -> skip update
229
+
230
+ self.opt.step()
231
+ self.sched.step()
232
+ return total_loss, grad_norm.item()
233
+
234
+ # --- main loop ---------------------------------------------------------
235
+ def train(self):
236
+ os.makedirs(self.cfg.ckpt_dir, exist_ok=True)
237
+ self.maybe_resume()
238
+ self._record({"event": "start", "git_sha": self.git_sha,
239
+ "model": self.mcfg.to_dict(), "train": asdict(self.cfg),
240
+ "step": self.step})
241
+ self.model.train()
242
+ while self.step < self.cfg.total_steps:
243
+ result = self._step()
244
+ if result is None:
245
+ self.consecutive_skips += 1
246
+ data_pos = self.stream.state_dict().get("pos")
247
+ print(f"[nan-guard] step {self.step} skipped "
248
+ f"({self.consecutive_skips}/{self.cfg.max_skips}) "
249
+ f"near data_pos={data_pos}")
250
+ self._record({"event": "nan_skip", "step": self.step,
251
+ "data_pos": data_pos})
252
+ self.opt.zero_grad(set_to_none=True)
253
+ if self.consecutive_skips >= self.cfg.max_skips:
254
+ raise RuntimeError("too many non-finite steps; aborting run")
255
+ continue
256
+ self.consecutive_skips = 0
257
+ loss, grad_norm = result
258
+ self.step += 1
259
+
260
+ stats = self.monitor.tick()
261
+ if self.step % self.cfg.log_every == 0:
262
+ self._log(loss, grad_norm, stats)
263
+ if self.step % self.cfg.ckpt_every == 0:
264
+ self.save()
265
+ if self._interrupted:
266
+ self.save()
267
+ print(f"[exit] checkpointed at step {self.step}")
268
+ break
269
+ else:
270
+ self.save() # final checkpoint on clean completion
271
+ return self.step
272
+
273
+ def _record(self, row: dict):
274
+ """Always-on JSONL metric log (survives wandb outage)."""
275
+ try:
276
+ with open(self.metrics_path, "a") as f:
277
+ f.write(json.dumps(row) + "\n")
278
+ except OSError as e:
279
+ print(f"[warn] could not write metrics: {e}")
280
+
281
+ def _log(self, loss, grad_norm, stats):
282
+ lr = self.sched.get_last_lr()[0]
283
+ row = {"event": "step", "step": self.step, "loss": loss, "lr": lr,
284
+ "grad_norm": grad_norm}
285
+ if stats:
286
+ row.update({"tokens_per_s": stats["tokens_per_s"],
287
+ "mfu": stats["mfu_avg"], "step_time_s": stats["dt_avg_s"]})
288
+ if self.device.type == "cuda":
289
+ row["gpu_mem_peak_gb"] = torch.cuda.max_memory_allocated() / 1e9
290
+ self._record(row)
291
+
292
+ msg = (f"step {self.step:>6} | loss {loss:7.4f} | lr {lr:.2e} "
293
+ f"| gnorm {grad_norm:5.2f}")
294
+ if stats:
295
+ msg += (f" | {stats['tokens_per_s']:8.0f} tok/s "
296
+ f"| mfu {stats['mfu_avg']*100:4.1f}%")
297
+ print(msg)
298
+ if self.wandb:
299
+ self.wandb.log({k: v for k, v in row.items()
300
+ if k not in ("event",)}, step=self.step)
301
+
302
+
303
+ class _nullcontext:
304
+ def __enter__(self):
305
+ return None
306
+
307
+ def __exit__(self, *exc):
308
+ return False
tests/test_ablate.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ablation harness: variants run, metrics captured, table emitted (dry CPU)."""
2
+
3
+ import os
4
+ import sys
5
+ import json
6
+ from pathlib import Path
7
+
8
+ ROOT = Path(__file__).resolve().parent.parent
9
+ sys.path.insert(0, str(ROOT / "scripts"))
10
+
11
+ import ablate # noqa: E402
12
+
13
+
14
+ def test_steps_for_tokens():
15
+ from matilda.train import TrainConfig
16
+ tc = TrainConfig(batch_size=24, grad_accum=8, seq_len=1024)
17
+ # 300M / (24*8*1024) ~= 1526
18
+ assert ablate.steps_for_tokens(300_000_000, tc) == 1526
19
+
20
+
21
+ def test_run_variant_dry_and_table(tmp_path):
22
+ results = str(tmp_path / "abl")
23
+ rows = []
24
+ for vname in ("baseline", "mqa"):
25
+ v = next(x for x in ablate.VARIANTS if x["name"] == vname)
26
+ row = ablate.run_variant(v, tokens=50_000, data_dir=None,
27
+ dry_run=True, results_root=results)
28
+ rows.append(row)
29
+ assert row["final_loss"] is not None # metrics captured
30
+ assert row["mfu"] is not None
31
+ assert rows[1]["n_kv_heads"] == 1 # mqa override applied
32
+
33
+ md = tmp_path / "ABLATIONS.md"
34
+ js = tmp_path / "ablations.json"
35
+ ablate.write_table(rows, 50_000, str(md), str(js))
36
+ assert md.exists() and js.exists()
37
+ text = md.read_text()
38
+ assert "baseline" in text and "mqa" in text and "MFU" in text
39
+ data = json.loads(js.read_text())
40
+ assert len(data["rows"]) == 2
tests/test_checkpoint.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resume must continue *identically* to an uninterrupted run.
2
+
3
+ Strategy: run a short reference training. Run it again but checkpoint halfway,
4
+ throw the objects away, build *fresh* model/optimizer/scheduler/data-stream,
5
+ restore from the checkpoint, and continue. The post-resume per-step losses must
6
+ match the reference run's second half exactly. If any piece of state is missing
7
+ (opt moments, scheduler, RNG, data position) the curves diverge and this fails.
8
+ """
9
+
10
+ import os
11
+ import random
12
+
13
+ import numpy as np
14
+ import torch
15
+
16
+ from matilda import Transformer, ModelConfig
17
+ from matilda.data import SyntheticStream
18
+ from matilda.optim import build_adamw, cosine_warmup_scheduler
19
+ from matilda.checkpoint import (
20
+ save_checkpoint, load_checkpoint, latest_checkpoint, rotate_checkpoints,
21
+ )
22
+
23
+ CFG = ModelConfig(vocab_size=128, max_seq_len=32, d_model=64,
24
+ n_layers=2, n_heads=4, n_kv_heads=2)
25
+ TOTAL, WARMUP, HALF = 12, 2, 6
26
+
27
+
28
+ def _stream(seed):
29
+ return SyntheticStream(CFG.vocab_size, batch_size=4, seq_len=16, seed=seed)
30
+
31
+
32
+ def _seed_all(seed=1234):
33
+ random.seed(seed)
34
+ np.random.seed(seed)
35
+ torch.manual_seed(seed)
36
+
37
+
38
+ def _build():
39
+ model = Transformer(CFG).train()
40
+ opt = build_adamw(model, lr=1e-3)
41
+ sched = cosine_warmup_scheduler(opt, WARMUP, TOTAL)
42
+ return model, opt, sched
43
+
44
+
45
+ def _train_steps(model, opt, sched, stream, n):
46
+ losses = []
47
+ for _ in range(n):
48
+ x, y = stream.next()
49
+ _, loss = model(x, y)
50
+ opt.zero_grad(set_to_none=True)
51
+ loss.backward()
52
+ opt.step()
53
+ sched.step()
54
+ losses.append(loss.item())
55
+ return losses
56
+
57
+
58
+ def test_resume_is_bit_for_bit(tmp_path):
59
+ # --- reference: uninterrupted run ---
60
+ _seed_all()
61
+ m, o, s = _build()
62
+ ref_stream = _stream(42)
63
+ ref_losses = _train_steps(m, o, s, ref_stream, TOTAL)
64
+
65
+ # --- interrupted run: train HALF, checkpoint, drop everything ---
66
+ _seed_all()
67
+ m, o, s = _build()
68
+ stream = _stream(42)
69
+ first_half = _train_steps(m, o, s, stream, HALF)
70
+ assert first_half == ref_losses[:HALF], "training is not deterministic"
71
+
72
+ ckpt = os.path.join(tmp_path, f"ckpt_{HALF}.pt")
73
+ save_checkpoint(ckpt, model=m, optimizer=o, scheduler=s, step=HALF,
74
+ config=CFG, data_state=stream.state_dict())
75
+
76
+ # --- fresh objects, restore, continue ---
77
+ m2, o2, s2 = _build() # fresh random init + zeroed moments
78
+ stream2 = _stream(999) # deliberately wrong seed...
79
+ ck = load_checkpoint(ckpt, model=m2, optimizer=o2, scheduler=s2)
80
+ stream2.load_state_dict(ck["data_state"]) # ...corrected by restore
81
+ assert ck["step"] == HALF
82
+
83
+ resumed = _train_steps(m2, o2, s2, stream2, TOTAL - HALF)
84
+
85
+ for i, (a, b) in enumerate(zip(resumed, ref_losses[HALF:])):
86
+ assert abs(a - b) < 1e-6, f"resume diverged at step {HALF+i}: {a} vs {b}"
87
+
88
+
89
+ def test_latest_and_rotation(tmp_path):
90
+ for step in (10, 20, 30, 40):
91
+ p = os.path.join(tmp_path, f"ckpt_{step}.pt")
92
+ torch.save({"step": step}, p)
93
+ assert latest_checkpoint(tmp_path).endswith("ckpt_40.pt")
94
+
95
+ rotate_checkpoints(tmp_path, keep_last=2, protect={"ckpt_10.pt"})
96
+ remaining = sorted(os.path.basename(p) for p in
97
+ __import__("glob").glob(os.path.join(tmp_path, "ckpt_*.pt")))
98
+ # keep last 2 (30, 40) + protected 10; drop 20
99
+ assert remaining == ["ckpt_10.pt", "ckpt_30.pt", "ckpt_40.pt"]
tests/test_data.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Data pipeline: shard writing/verification + BinStream correctness."""
2
+
3
+ import os
4
+ import json
5
+
6
+ import numpy as np
7
+ import pytest
8
+ import torch
9
+
10
+ from matilda.data import (
11
+ ShardWriter, verify_manifest, shard_paths, BinStream, DTYPE,
12
+ )
13
+
14
+
15
+ def test_shardwriter_roundtrip_and_manifest(tmp_path):
16
+ w = ShardWriter(str(tmp_path), shard_tokens=100)
17
+ # 250 tokens -> two full shards (100) + one partial (50)
18
+ w.add(list(range(0, 120)))
19
+ w.add(list(range(120, 250)))
20
+ manifest = w.close(meta={"tokenizer": "gpt2"})
21
+
22
+ assert manifest["total_tokens"] == 250
23
+ assert [s["tokens"] for s in manifest["shards"]] == [100, 100, 50]
24
+ assert manifest["tokenizer"] == "gpt2"
25
+ assert verify_manifest(str(tmp_path)) is True
26
+
27
+ # reconstructed token stream matches the input exactly
28
+ rebuilt = np.concatenate(
29
+ [np.fromfile(p, dtype=DTYPE) for p in shard_paths(str(tmp_path))])
30
+ assert rebuilt.tolist() == list(range(250))
31
+
32
+
33
+ def test_verify_detects_corruption(tmp_path):
34
+ w = ShardWriter(str(tmp_path), shard_tokens=100)
35
+ w.add(list(range(150)))
36
+ w.close()
37
+ # corrupt the first shard's bytes without changing its size
38
+ p = shard_paths(str(tmp_path))[0]
39
+ data = bytearray(open(p, "rb").read())
40
+ data[0] ^= 0xFF
41
+ open(p, "wb").write(data)
42
+ with pytest.raises(ValueError, match="checksum mismatch"):
43
+ verify_manifest(str(tmp_path))
44
+
45
+
46
+ def _write_ramp_bin(path, n):
47
+ # values 0..n-1 so a correct next-token window always has y == x + 1
48
+ np.arange(n, dtype=DTYPE).tofile(path)
49
+
50
+
51
+ def test_binstream_shift_is_next_token(tmp_path):
52
+ p = os.path.join(tmp_path, "ramp.bin")
53
+ _write_ramp_bin(p, 5000)
54
+ s = BinStream([p], batch_size=8, seq_len=32, seed=0)
55
+ x, y = s.next()
56
+ assert x.shape == (8, 32) and y.shape == (8, 32)
57
+ assert torch.equal(y, x + 1) # packed next-token target
58
+
59
+
60
+ def test_binstream_resume_is_deterministic(tmp_path):
61
+ p = os.path.join(tmp_path, "ramp.bin")
62
+ _write_ramp_bin(p, 5000)
63
+ s = BinStream([p], batch_size=4, seq_len=16, seed=7)
64
+ snap = s.state_dict()
65
+ x1, y1 = s.next()
66
+ s.load_state_dict(snap)
67
+ x2, y2 = s.next()
68
+ assert torch.equal(x1, x2) and torch.equal(y1, y2)
69
+
70
+
71
+ def test_binstream_skips_too_small_shards(tmp_path):
72
+ # a tiny final shard (< seq_len+1) must be skipped, not crash (regression)
73
+ big = os.path.join(tmp_path, "big.bin")
74
+ tiny = os.path.join(tmp_path, "tiny.bin")
75
+ _write_ramp_bin(big, 5000)
76
+ _write_ramp_bin(tiny, 10) # smaller than seq_len+1
77
+ s = BinStream([big, tiny], batch_size=4, seq_len=32, seed=0)
78
+ assert len(s.arrays) == 1 # tiny dropped
79
+ x, y = s.next()
80
+ assert torch.equal(y, x + 1)
81
+
82
+
83
+ def test_binstream_multishard_weighting(tmp_path):
84
+ p1 = os.path.join(tmp_path, "a.bin")
85
+ p2 = os.path.join(tmp_path, "b.bin")
86
+ _write_ramp_bin(p1, 2000)
87
+ _write_ramp_bin(p2, 2000)
88
+ s = BinStream([p1, p2], batch_size=4, seq_len=8, seed=1)
89
+ x, y = s.next()
90
+ assert torch.equal(y, x + 1) # still correct across shards
tests/test_model.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sanity tests that gate the paid run. All must be green on Colab first.
2
+
3
+ - test_forward_shapes / test_weight_tying / test_param_count: wiring is correct
4
+ - test_causal_mask: no information leaks from future tokens (the bug that
5
+ silently inflates eval and is invisible in the loss curve)
6
+ - test_overfit_single_batch: the model can actually learn (loss -> ~0 on one
7
+ fixed batch). The cheapest, highest-signal correctness check in ML.
8
+ """
9
+
10
+ import torch
11
+ import pytest
12
+
13
+ from matilda import Transformer, ModelConfig, DEV_TINY, BASE_350M
14
+
15
+
16
+ def _tiny():
17
+ return Transformer(DEV_TINY).eval()
18
+
19
+
20
+ def test_forward_shapes():
21
+ model = _tiny()
22
+ B, T = 2, 16
23
+ idx = torch.randint(0, DEV_TINY.vocab_size, (B, T))
24
+ logits, loss = model(idx)
25
+ assert logits.shape == (B, T, DEV_TINY.vocab_size)
26
+ assert loss is None
27
+ targets = torch.randint(0, DEV_TINY.vocab_size, (B, T))
28
+ _, loss = model(idx, targets)
29
+ assert loss is not None and loss.ndim == 0
30
+
31
+
32
+ def test_weight_tying():
33
+ model = _tiny()
34
+ assert model.lm_head.weight.data_ptr() == model.embed.weight.data_ptr()
35
+
36
+
37
+ def test_loss_at_init_is_near_uniform():
38
+ # untrained model should be ~ -log(1/V) = log(V)
39
+ model = _tiny()
40
+ idx = torch.randint(0, DEV_TINY.vocab_size, (4, 32))
41
+ tgt = torch.randint(0, DEV_TINY.vocab_size, (4, 32))
42
+ _, loss = model(idx, tgt)
43
+ expected = torch.log(torch.tensor(float(DEV_TINY.vocab_size)))
44
+ assert abs(loss.item() - expected.item()) < 1.0
45
+
46
+
47
+ def test_causal_mask_no_future_leak():
48
+ """Changing token at position t must not alter logits at positions < t."""
49
+ model = _tiny()
50
+ torch.manual_seed(0)
51
+ idx = torch.randint(0, DEV_TINY.vocab_size, (1, 24))
52
+ with torch.no_grad():
53
+ base, _ = model(idx)
54
+ idx2 = idx.clone()
55
+ idx2[0, -1] = (idx2[0, -1] + 1) % DEV_TINY.vocab_size # perturb last token
56
+ perturbed, _ = model(idx2)
57
+ # all positions except the last must be identical
58
+ assert torch.allclose(base[:, :-1], perturbed[:, :-1], atol=1e-5)
59
+ assert not torch.allclose(base[:, -1], perturbed[:, -1], atol=1e-5)
60
+
61
+
62
+ def test_gqa_kv_head_counts():
63
+ model = _tiny()
64
+ attn = model.blocks[0].attn
65
+ assert attn.wk.out_features == DEV_TINY.n_kv_heads * DEV_TINY.head_dim
66
+ assert attn.wq.out_features == DEV_TINY.n_heads * DEV_TINY.head_dim
67
+
68
+
69
+ def test_softcap_path_is_finite_and_causal():
70
+ # qk_norm OFF + soft-cap ON: the ablation config must stay finite and causal
71
+ cfg = ModelConfig(vocab_size=200, max_seq_len=64, d_model=64, n_layers=2,
72
+ n_heads=4, n_kv_heads=2, qk_norm=False,
73
+ attn_logit_softcap=20.0)
74
+ model = Transformer(cfg).eval()
75
+ idx = torch.randint(0, cfg.vocab_size, (2, 24))
76
+ with torch.no_grad():
77
+ logits, _ = model(idx)
78
+ assert torch.isfinite(logits).all()
79
+ idx2 = idx.clone()
80
+ idx2[0, -1] = (idx2[0, -1] + 1) % cfg.vocab_size
81
+ perturbed, _ = model(idx2)
82
+ assert torch.allclose(logits[:, :-1], perturbed[:, :-1], atol=1e-5)
83
+
84
+
85
+ def test_zloss_off_matches_plain_ce():
86
+ """z_loss_coef=0 must be a perfect no-op vs the v1 loss path."""
87
+ torch.manual_seed(0)
88
+ cfg_off = ModelConfig(vocab_size=128, max_seq_len=32, d_model=64,
89
+ n_layers=2, n_heads=4, n_kv_heads=2, z_loss_coef=0.0)
90
+ model = Transformer(cfg_off).eval()
91
+ idx = torch.randint(0, cfg_off.vocab_size, (2, 16))
92
+ tgt = torch.randint(0, cfg_off.vocab_size, (2, 16))
93
+ with torch.no_grad():
94
+ logits, loss = model(idx, tgt)
95
+ expected = torch.nn.functional.cross_entropy(
96
+ logits.view(-1, logits.size(-1)), tgt.view(-1), ignore_index=-1)
97
+ assert torch.allclose(loss, expected, atol=1e-6)
98
+
99
+
100
+ def test_zloss_adds_lse_square_term():
101
+ """With z_loss_coef>0, loss = CE + coef * mean(logsumexp(logits)^2)."""
102
+ torch.manual_seed(0)
103
+ coef = 1e-3
104
+ cfg = ModelConfig(vocab_size=128, max_seq_len=32, d_model=64, n_layers=2,
105
+ n_heads=4, n_kv_heads=2, z_loss_coef=coef)
106
+ model = Transformer(cfg).eval()
107
+ idx = torch.randint(0, cfg.vocab_size, (2, 16))
108
+ tgt = torch.randint(0, cfg.vocab_size, (2, 16))
109
+ with torch.no_grad():
110
+ logits, loss = model(idx, tgt)
111
+ ce = torch.nn.functional.cross_entropy(
112
+ logits.view(-1, logits.size(-1)), tgt.view(-1), ignore_index=-1)
113
+ log_z = logits.logsumexp(dim=-1)
114
+ z = coef * (log_z ** 2).mean()
115
+ assert torch.allclose(loss, ce + z, atol=1e-6)
116
+ assert loss.item() > ce.item() # z-loss strictly adds to CE
117
+
118
+
119
+ def test_base_350m_shape_validates_and_constructs():
120
+ """BASE_350M is the hero config; must build cleanly with the locked shape.
121
+ Skip if liger isn't installed (use_liger=True requires it on GPU)."""
122
+ cfg = BASE_350M
123
+ assert cfg.head_dim == 80 # 960 / 12
124
+ assert cfg.n_heads % cfg.n_kv_heads == 0 # GQA divides
125
+ assert cfg.tie_weights and cfg.qk_norm
126
+ assert cfg.z_loss_coef > 0
127
+ # Hero config has use_liger=True; on a CPU dev box without liger installed,
128
+ # this asserts the import-error message rather than building the giant model.
129
+ if cfg.use_liger:
130
+ try:
131
+ import liger_kernel # noqa: F401
132
+ except ImportError:
133
+ pytest.skip("liger-kernel not installed (expected on CPU dev boxes)")
134
+ # If we reach here, liger is present; param count check is the cheap part.
135
+ model = Transformer(cfg)
136
+ n = model.num_params(non_embedding=True)
137
+ assert 280_000_000 < n < 360_000_000, \
138
+ f"non-embed params {n:,} outside the 280M-360M sub-1B target band"
139
+
140
+
141
+ @pytest.mark.slow
142
+ def test_overfit_single_batch():
143
+ """The model must drive loss toward zero on one fixed batch."""
144
+ cfg = ModelConfig(vocab_size=256, max_seq_len=64, d_model=128,
145
+ n_layers=2, n_heads=4, n_kv_heads=2)
146
+ model = Transformer(cfg).train()
147
+ torch.manual_seed(0)
148
+ idx = torch.randint(0, cfg.vocab_size, (4, 32))
149
+ tgt = torch.randint(0, cfg.vocab_size, (4, 32))
150
+ opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
151
+ losses = []
152
+ for _ in range(300):
153
+ _, loss = model(idx, tgt)
154
+ opt.zero_grad(set_to_none=True)
155
+ loss.backward()
156
+ opt.step()
157
+ losses.append(loss.item())
158
+ assert losses[-1] < 0.1, f"failed to overfit; final loss={losses[-1]:.3f}"
tests/test_optim.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Muon optimizer + Muon/AdamW hybrid."""
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from matilda import Transformer, ModelConfig
7
+ from matilda.optim import (
8
+ build_optimizer, cosine_warmup_scheduler, build_scheduler,
9
+ wsd_scheduler, WarmupStableDecay, Muon, HybridOptimizer,
10
+ zeropower_via_newtonschulz5,
11
+ )
12
+
13
+
14
+ def test_newtonschulz_orthogonalizes():
15
+ torch.manual_seed(0)
16
+ G = torch.randn(32, 16)
17
+ X = zeropower_via_newtonschulz5(G, steps=5).float()
18
+ # singular values should be pushed toward 1
19
+ s = torch.linalg.svdvals(X)
20
+ assert (s > 0.5).all() and (s < 1.5).all()
21
+
22
+
23
+ def test_hybrid_splits_params():
24
+ cfg = ModelConfig(vocab_size=128, max_seq_len=32, d_model=64,
25
+ n_layers=2, n_heads=4, n_kv_heads=2)
26
+ opt = build_optimizer(Transformer(cfg), name="muon")
27
+ assert isinstance(opt, HybridOptimizer)
28
+ muon, adamw = opt.optimizers
29
+ assert isinstance(muon, Muon)
30
+ # every Muon param is a 2-D matrix
31
+ assert all(p.ndim == 2 for g in muon.param_groups for p in g["params"])
32
+
33
+
34
+ @pytest.mark.slow
35
+ def test_muon_overfits_single_batch():
36
+ cfg = ModelConfig(vocab_size=256, max_seq_len=64, d_model=128,
37
+ n_layers=2, n_heads=4, n_kv_heads=2)
38
+ model = Transformer(cfg).train()
39
+ torch.manual_seed(0)
40
+ idx = torch.randint(0, cfg.vocab_size, (4, 32))
41
+ tgt = torch.randint(0, cfg.vocab_size, (4, 32))
42
+ opt = build_optimizer(model, name="muon", lr=3e-3, muon_lr=0.02)
43
+ sched = cosine_warmup_scheduler(opt, warmup_steps=10, total_steps=300)
44
+ last = None
45
+ for _ in range(300):
46
+ _, loss = model(idx, tgt)
47
+ opt.zero_grad(set_to_none=True)
48
+ loss.backward()
49
+ opt.step()
50
+ sched.step()
51
+ last = loss.item()
52
+ assert last < 0.5, f"Muon failed to overfit; final loss={last:.3f}"
53
+
54
+
55
+ def _dummy_opt(base_lr=1.0):
56
+ """Minimal optimizer just to exercise scheduler interface."""
57
+ p = torch.nn.Parameter(torch.zeros(2, 2))
58
+ return torch.optim.SGD([p], lr=base_lr)
59
+
60
+
61
+ def test_wsd_schedule_three_phases():
62
+ """Warmup ramps linearly to peak, stable holds peak, decay drops to min."""
63
+ base = 1.0
64
+ warmup, total, stable = 10, 100, 0.8
65
+ sched = wsd_scheduler(_dummy_opt(base), warmup_steps=warmup,
66
+ total_steps=total, stable_share=stable,
67
+ min_lr_ratio=0.1)
68
+ lrs = []
69
+ for _ in range(total):
70
+ lrs.append(sched.get_last_lr()[0])
71
+ sched.step()
72
+ # warmup: lr at step warmup-1 should equal base (peak)
73
+ assert lrs[0] == pytest.approx(base / warmup, rel=1e-6)
74
+ assert lrs[warmup - 1] == pytest.approx(base, rel=1e-6)
75
+ # stable phase: held at peak for stable_share of post-warmup
76
+ decay_start = warmup + int(stable * (total - warmup))
77
+ assert lrs[warmup] == pytest.approx(base, rel=1e-6)
78
+ assert lrs[decay_start - 1] == pytest.approx(base, rel=1e-6)
79
+ # decay: monotone non-increasing
80
+ decay_lrs = lrs[decay_start:]
81
+ assert all(decay_lrs[i] >= decay_lrs[i + 1] for i in range(len(decay_lrs) - 1))
82
+ # ends at min_lr_ratio * base (within one-step linear quantum)
83
+ assert lrs[-1] < base # has decayed
84
+ assert lrs[-1] >= 0.1 * base * 0.5 # not below floor
85
+
86
+
87
+ def test_wsd_state_dict_roundtrip():
88
+ """Resume must restore step + base_lrs and re-apply the LR exactly."""
89
+ opt = _dummy_opt(1.0)
90
+ s1 = wsd_scheduler(opt, warmup_steps=10, total_steps=100, stable_share=0.8)
91
+ for _ in range(50):
92
+ s1.step()
93
+ sd = s1.state_dict()
94
+ s2 = wsd_scheduler(_dummy_opt(1.0), warmup_steps=10, total_steps=100,
95
+ stable_share=0.8)
96
+ s2.load_state_dict(sd)
97
+ assert s2.last_step == s1.last_step
98
+ assert s2.get_last_lr()[0] == pytest.approx(s1.get_last_lr()[0], rel=1e-9)
99
+
100
+
101
+ def test_build_scheduler_dispatch():
102
+ assert isinstance(
103
+ build_scheduler("wsd", _dummy_opt(), 10, 100), WarmupStableDecay)
104
+ cos = build_scheduler("cosine", _dummy_opt(), 10, 100)
105
+ assert hasattr(cos, "step") and hasattr(cos, "get_last_lr")
106
+ with pytest.raises(ValueError):
107
+ build_scheduler("bogus", _dummy_opt(), 10, 100)
108
+
109
+
110
+ def test_hybrid_state_dict_roundtrip():
111
+ cfg = ModelConfig(vocab_size=128, max_seq_len=32, d_model=64,
112
+ n_layers=2, n_heads=4, n_kv_heads=2)
113
+ model = Transformer(cfg)
114
+ opt = build_optimizer(model, name="muon")
115
+ # take a step so state is populated
116
+ _, loss = model(torch.randint(0, 128, (2, 16)), torch.randint(0, 128, (2, 16)))
117
+ loss.backward()
118
+ opt.step()
119
+ sd = opt.state_dict()
120
+ opt2 = build_optimizer(Transformer(cfg), name="muon")
121
+ opt2.load_state_dict(sd) # must not raise
122
+ assert len(sd["opts"]) == 2
tests/test_run.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The launch entrypoint: configs parse, build, override, and run."""
2
+
3
+ import sys
4
+ import json
5
+ from pathlib import Path
6
+
7
+ ROOT = Path(__file__).resolve().parent.parent
8
+ sys.path.insert(0, str(ROOT))
9
+
10
+ import run # noqa: E402
11
+
12
+
13
+ def _load(name):
14
+ return json.loads((ROOT / "configs" / name).read_text())
15
+
16
+
17
+ def test_shipped_configs_build():
18
+ for name in ("calibration.json", "base_124m.json"):
19
+ mcfg, tcfg = run.build(_load(name))
20
+ assert mcfg.d_model == 768 and mcfg.n_layers == 12
21
+ assert tcfg.seq_len == 1024
22
+
23
+
24
+ def test_base_config_targets_about_3B_tokens():
25
+ _, tcfg = run.build(_load("base_124m.json"))
26
+ tokens = tcfg.total_steps * tcfg.batch_size * tcfg.grad_accum * tcfg.seq_len
27
+ assert 2.5e9 < tokens < 3.5e9
28
+
29
+
30
+ def test_overrides_coerce_types():
31
+ cfg = {"train": {"batch_size": 24}}
32
+ out = run.apply_overrides(cfg, ["train.batch_size=48", "train.compile=true",
33
+ "train.lr=0.0006"])
34
+ assert out["train"]["batch_size"] == 48 and isinstance(
35
+ out["train"]["batch_size"], int)
36
+ assert out["train"]["compile"] is True
37
+ assert out["train"]["lr"] == 0.0006
38
+
39
+
40
+ def test_dry_run_builds_synthetic_and_steps(tmp_path):
41
+ cfg = _load("calibration.json")
42
+ cfg = run.apply_overrides(cfg, [
43
+ "model.d_model=64", "model.n_layers=2", "model.n_heads=4",
44
+ "model.n_kv_heads=2", "model.vocab_size=256", "model.max_seq_len=64",
45
+ "train.total_steps=4", "train.warmup_steps=1", "train.batch_size=4",
46
+ "train.seq_len=64", "train.device=cpu", "train.dtype=float32",
47
+ "train.compile=false", f"train.ckpt_dir={tmp_path.as_posix()}",
48
+ ])
49
+ mcfg, tcfg = run.build(cfg)
50
+ stream = run.build_stream(mcfg, tcfg, data_dir=None, dry_run=True)
51
+ from matilda.train import Trainer
52
+ assert Trainer(mcfg, tcfg, stream).train() == 4
tests/test_train.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training-loop reliability guards (all CPU-testable)."""
2
+
3
+ import os
4
+ import glob
5
+
6
+ import torch
7
+ import pytest
8
+
9
+ from matilda import ModelConfig
10
+ from matilda.data import SyntheticStream
11
+ from matilda.train import Trainer, TrainConfig
12
+ from matilda.monitor import mfu, peak_tflops
13
+
14
+ MCFG = ModelConfig(vocab_size=128, max_seq_len=32, d_model=64,
15
+ n_layers=2, n_heads=4, n_kv_heads=2)
16
+
17
+
18
+ def _make(tmp_path, **over):
19
+ kw = dict(total_steps=20, warmup_steps=2, batch_size=4, seq_len=16,
20
+ log_every=5, ckpt_every=10, keep_last=2, device="cpu",
21
+ dtype="float32", ckpt_dir=str(tmp_path))
22
+ kw.update(over)
23
+ tc = TrainConfig(**kw)
24
+ stream = SyntheticStream(MCFG.vocab_size, tc.batch_size, tc.seq_len, seed=0)
25
+ return Trainer(MCFG, tc, stream)
26
+
27
+
28
+ def test_loop_runs_and_checkpoints(tmp_path):
29
+ t = _make(tmp_path)
30
+ final = t.train()
31
+ assert final == 20
32
+ # final checkpoint on clean completion + rotation kept <= keep_last
33
+ ckpts = glob.glob(os.path.join(tmp_path, "ckpt_*.pt"))
34
+ assert len(ckpts) <= 2
35
+ assert os.path.exists(os.path.join(tmp_path, "ckpt_20.pt"))
36
+
37
+
38
+ def test_loop_resume_continues(tmp_path):
39
+ # run only 10 steps, leaving a checkpoint at step 10
40
+ t1 = _make(tmp_path, total_steps=10, ckpt_every=10)
41
+ assert t1.train() == 10
42
+ # a fresh trainer in the same dir must resume from step 10, not restart
43
+ t2 = _make(tmp_path, total_steps=15, ckpt_every=10)
44
+ assert t2.maybe_resume() is True
45
+ assert t2.step == 10
46
+ assert t2.train() == 15
47
+
48
+
49
+ def test_nan_guard_aborts_after_max_skips(tmp_path):
50
+ t = _make(tmp_path, total_steps=50, max_skips=3)
51
+ nan = torch.tensor(float("nan"))
52
+ t.model.forward = lambda x, targets=None: (None, nan) # shadow bound method
53
+ with pytest.raises(RuntimeError, match="non-finite"):
54
+ t.train()
55
+ assert t.step == 0 # never advanced past a bad batch
56
+
57
+
58
+ def test_nan_guard_skips_then_recovers(tmp_path):
59
+ t = _make(tmp_path, total_steps=5, max_skips=10)
60
+ real_forward = t.model.forward
61
+ calls = {"n": 0}
62
+
63
+ def flaky(x, targets=None):
64
+ calls["n"] += 1
65
+ if calls["n"] <= 2: # first two micro-batches are bad
66
+ return None, torch.tensor(float("inf"))
67
+ return real_forward(x, targets)
68
+
69
+ t.model.forward = flaky
70
+ assert t.train() == 5 # recovered and finished
71
+ assert t.consecutive_skips == 0
72
+
73
+
74
+ def test_mfu_sanity():
75
+ # 100M params, 500k tokens/step, 2.0s, A100 -> ~0.48 MFU
76
+ val = mfu(100_000_000, 500_000, 2.0, peak_tflops("A100") * 1e12)
77
+ assert 0.0 < val < 1.0
78
+ assert peak_tflops("A100") == 312.0
79
+ assert peak_tflops("totally-unknown-gpu") == 312.0 # default