jayasriii commited on
Commit
da9d1c9
·
verified ·
1 Parent(s): 90e7d69

Copy files from models/jayasriii/390M_5e4

Browse files
Files changed (1) hide show
  1. train_390M_5e4.py +1847 -0
train_390M_5e4.py ADDED
@@ -0,0 +1,1847 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # =============================================================================
3
+ # train_muon.py — the MUON arm of train.py. Same model, same data order, same
4
+ # schedule shape, same seed: the ONLY thing that changes is how a gradient
5
+ # becomes a weight update.
6
+ #
7
+ # Fork discipline — everything outside section 5 is byte-identical to train.py,
8
+ # so `diff train.py train_muon.py` is exactly the experiment being run. If you
9
+ # edit a kernel or the model in one file, port it to the other or the comparison
10
+ # stops meaning anything.
11
+ #
12
+ # The optimizer itself is torch.optim.Muon — stock, not reimplemented. This file
13
+ # supplies only the two things it does not do for you: the ROUTING (which
14
+ # parameters it may have) and the fp32 MASTER WEIGHTS (it updates the master,
15
+ # not the bf16 param). Requires a torch new enough to ship it; main() checks and
16
+ # says so.
17
+ #
18
+ # What Muon does: AdamW rescales each weight ENTRY by its own gradient history.
19
+ # Muon rescales each weight MATRIX by its singular values — it takes the
20
+ # momentum buffer M and replaces it with the nearest semi-orthogonal matrix
21
+ # (all singular values driven to ~1) via a 5-step Newton-Schulz iteration, then
22
+ # steps along that. Directions the gradient has barely explored get the same
23
+ # step size as the dominant ones, which is where the reported speedup comes
24
+ # from. Only 2D hidden weights can be orthogonalized, so this is a HYBRID:
25
+ #
26
+ # Muon : every 2D Linear weight inside the blocks (75.5M params, 66%)
27
+ # AdamW : the token embedding / lm_head (38.6M params)
28
+ # + RMSNorm weights + QK-norm gammas (1D) (22.3k params)
29
+ #
30
+ # The embedding is deliberately NOT given to Muon: its rows are per-token, not a
31
+ # linear map between two feature spaces, and orthogonalizing across the vocab
32
+ # axis mixes unrelated tokens. That split is the standard Muon recipe, and it
33
+ # keeps the AdamW arm's exact update on 34% of the parameters — so a difference
34
+ # in the loss curve is attributable to the hidden matrices alone.
35
+ #
36
+ # Everything train_ddp.py / train_zero1.py import from blu_common / blu_data /
37
+ # blu_kernels / blu_model is inlined here, in that order, so this file runs on
38
+ # its own:
39
+ # section 1 fused QK-norm + RoPE (Triton) <- blu_kernels.py
40
+ # section 2 config + WSD schedule <- blu_common.py
41
+ # section 3 data loader <- blu_data.py
42
+ # section 4 model <- blu_model.py
43
+ # section 5 optimizer / clipping / checkpointing
44
+ # section 6 training
45
+ #
46
+ # Architecture:
47
+ # token embedding
48
+ # -> N x { RMSNorm -> [fused QK-norm + RoPE] -> causal GQA (flash) -> Wo -> +x
49
+ # RMSNorm -> SwiGLU FFN (gate_up -> silu(gate)*up -> down) -> +x }
50
+ # -> final RMSNorm
51
+ # -> lm_head (weight-tied with the token embedding)
52
+ # -> cross-entropy
53
+ # -> backward -> AdamW (decoupled weight decay) on a WSD (warmup / stable /
54
+ # cosine-decay) schedule
55
+ #
56
+ # Kept from the AdamW arm, unchanged, because they are confounds if they move:
57
+ # * fp32 master weights for every non-fp32 param — Muon updates the MASTER,
58
+ # reading the same fp32 landing buffer AdamW reads, so both optimizers see
59
+ # bit-identical gradients;
60
+ # * decoupled weight decay 0.1 on dim>=2 params, applied to the master;
61
+ # * ONE global-norm gradient clip over every parameter, BEFORE the optimizer.
62
+ # (Muon's orthogonalization makes the update scale-invariant, so clipping is
63
+ # nearly a no-op for its group — but it still gates the AdamW group, and
64
+ # removing it would change two things at once.)
65
+ #
66
+ # Memory, at the 114M config this repo actually runs (printed at startup):
67
+ #
68
+ # parameters (bf16 Linear + fp32 embed/norms) 0.28 GiB
69
+ # gradients (same dtypes as the params) 0.28 GiB
70
+ # fp32 master weights (the bf16 Linears) 0.28 GiB
71
+ # fp32 gradient landing buffers 0.28 GiB
72
+ # Muon momentum (75.5M params, fp32 x1) 0.28 GiB
73
+ # AdamW m + v (38.7M params, fp32 x2) 0.29 GiB
74
+ # -------------------------------------------------------
75
+ # static total 1.70 GiB (AdamW arm: 1.98)
76
+ #
77
+ # Muon carries ONE state tensor per param where Adam carries two, so the saving
78
+ # scales with how much of the model is hidden matrices: 0.28 GiB here (14% of
79
+ # static), because this config spends a third of its parameters on a 50304-row
80
+ # embedding that stays on AdamW. At the 1.73B config in the original header the
81
+ # same split saves ~5.5 GiB.
82
+ #
83
+ # Activations dominate either way (63.96 GiB measured at B=16 x T=4096), so the
84
+ # OOM escape hatches are unchanged: --B 8, --loss-chunks 4, --activation-checkpoint.
85
+ #
86
+ # Fidelity notes (why a run here is statistically but not bit-wise identical):
87
+ # * init draws come from torch's Philox, not the C++ single advancing
88
+ # std::mt19937, so the two runs start from different samples of the same
89
+ # distributions;
90
+ # * QK-norm reads the projection output in bf16 here (autocast) where the C++
91
+ # casts it up to fp32 first; the reduction and the rotation are fp32 in both.
92
+ #
93
+ # Determinism: two runs of the same launch line on the same GPU produce
94
+ # bit-identical losses. Seeding is only half of that — the default CUDA kernels
95
+ # for the embedding backward and the flash/mem-efficient attention backward
96
+ # accumulate partial sums with atomicAdd, so the order they land in (and with it
97
+ # the fp32 rounding) follows the scheduler, not the program. --determinism
98
+ # strict (the default) forces the ordered variants of those kernels; it costs a
99
+ # few percent of step time, which --determinism off buys back.
100
+ #
101
+ # Env overrides (the bluscript_single.cpp names, so an existing launch line keeps
102
+ # working; the equivalent CLI flag wins if both are given):
103
+ # BLU_DEVICE=<idx> CUDA device to train on (default 0)
104
+ # BLU_MAX_STEPS=<n> short benchmark run (rescales WSD) (default off)
105
+ # BLU_B=<n> micro-batch size (default 4)
106
+ # BLU_GLOBAL_BATCH=<tokens> tokens per optimizer step (default 524288)
107
+ # BLU_DIAG=1 per-micro-batch loss + depth probes
108
+ #
109
+ # Multi-GPU: DDP, one process per GPU, via torchrun. RANK / LOCAL_RANK /
110
+ # WORLD_SIZE (set by torchrun, not this file) switch the bootstrap in main();
111
+ # their absence is the single-process path above, unchanged. --device /
112
+ # BLU_DEVICE are ignored under torchrun — LOCAL_RANK picks each rank's GPU.
113
+ # --global-batch is still the TOTAL tokens per optimizer step across every
114
+ # rank (grad_accum = global_batch / (B*T*world_size)), so the same
115
+ # --global-batch reproduces the same schedule at any world size. Data is
116
+ # rank-sharded (DataLoaderLite reads a disjoint, rank-offset slice of the
117
+ # shards); gradients and the reported train/val loss are averaged across
118
+ # ranks; only rank 0 writes the CSV and checkpoints. Same launch line as
119
+ # single-GPU otherwise:
120
+ # torchrun --standalone --nproc_per_node=8 train_muon.py
121
+ #
122
+ # Learning rate — the one knob that decides whether the comparison is fair.
123
+ #
124
+ # Muon's update is spectrally normalized, so its natural scale has nothing to do
125
+ # with AdamW's. torch.optim.Muon ships both published conventions behind its
126
+ # `adjust_lr_fn`; --muon-adjust-lr passes the string straight through:
127
+ #
128
+ # match_rms_adamw Moonshot's: gamma <- 0.2 * gamma * sqrt(max(A,B)). The
129
+ # (DEFAULT HERE) Newton-Schulz output has singular values ~1, so its
130
+ # entries have RMS 1/sqrt(max(A,B)); this lifts them to
131
+ # RMS 0.2, which is what a converged AdamW update looks
132
+ # like. The consequence: --muon-lr is on the SAME SCALE
133
+ # as --max-lr, and the default (2e-4, equal to the AdamW
134
+ # arm's max_lr) gives both arms the same step size on the
135
+ # first run — only the update DIRECTION differs. That is
136
+ # the controlled experiment; run it before tuning.
137
+ # original Keller's modded-nanogpt scaling, sqrt(max(1, A/B)).
138
+ # Entries stay at RMS 1/sqrt(max(A,B)), so an equivalent
139
+ # LR is ~5.5x larger at d_model=768 (0.2*sqrt(768)).
140
+ # Use it to reproduce published Muon numbers.
141
+ #
142
+ # NOTE: torch's own default for adjust_lr_fn is `original`. This file defaults
143
+ # to `match_rms_adamw` instead, because an LR-matched first run is the point of
144
+ # having two arms. If you cite a number from here, cite the flag with it.
145
+ #
146
+ # Muon usually tolerates 2-4x more LR than AdamW once it is working, so the
147
+ # honest protocol is: baseline run, matched run, then a short --max-steps 200
148
+ # sweep over --muon-lr before claiming a win.
149
+ #
150
+ # Launch (the two arms; separate CSV + checkpoint dirs so they never collide):
151
+ # python3 train.py # AdamW baseline
152
+ # python3 train_muon.py # Muon, LR-matched
153
+ # python3 train_muon.py --muon-lr 6e-4 # after a sweep
154
+ # python3 train_muon.py --max-steps 200 --muon-lr 4e-4 # short sweep point
155
+ # =============================================================================
156
+
157
+ import argparse
158
+ import glob
159
+ import math
160
+ import os
161
+ import random
162
+ import re
163
+ import signal
164
+ import time
165
+ from contextlib import nullcontext
166
+ from dataclasses import dataclass
167
+
168
+ # cuBLAS reads CUBLAS_WORKSPACE_CONFIG once, when it creates its handle on the
169
+ # first GEMM, and torch refuses to run fp32 cuBLAS GEMMs under
170
+ # use_deterministic_algorithms() unless it is one of the two allowed values. It
171
+ # has to be in the environment before torch touches CUDA, hence: before the
172
+ # import, not inside main(). An explicit setting from the launch line wins.
173
+ os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
174
+
175
+ import numpy as np
176
+ import torch
177
+ import torch.distributed as dist
178
+ import torch.nn as nn
179
+ import torch.nn.functional as F
180
+ from torch.nn.attention import SDPBackend, sdpa_kernel
181
+ from torch.nn.parallel import DistributedDataParallel as DDP
182
+ from torch.utils.checkpoint import checkpoint
183
+
184
+ try:
185
+ import triton
186
+ import triton.language as tl
187
+ _HAS_TRITON = True
188
+ except ImportError: # eager fallback below
189
+ _HAS_TRITON = False
190
+
191
+
192
+ # =============================================================================
193
+ # 1. Fused QK-norm (RMSNorm over head_dim) + RoPE, in Triton.
194
+ #
195
+ # PyTorch counterpart of the C++ `autograd::fused_rms_rope`. One kernel does,
196
+ # per (batch, head, position) row:
197
+ #
198
+ # s = rsqrt(mean(x^2) + eps) # RMS over head_dim
199
+ # y = x * s * gamma # learnable per-head_dim scale
200
+ # o = rope_neox(y, cos[t], sin[t]) # NeoX / Llama half-split rotation
201
+ #
202
+ # Attention is deliberately NOT fused in here — it stays a separate op
203
+ # (F.scaled_dot_product_attention on the flash backend), mirroring the C++ split
204
+ # between `fused_rms_rope` and `gqa_fused_flash_attn_forward/backward`.
205
+ #
206
+ # Why fuse: the eager formulation (`rms_rope_eager`) materialises an fp32 copy of
207
+ # x, the squared tensor, the normalised tensor, the gamma-scaled tensor and a
208
+ # `cat` of the two rotated halves — roughly 6 extra [B,H,T,D] buffers held for
209
+ # backward. The fused version saves only x (which the projection's backward
210
+ # already holds) plus one fp32 scalar per row.
211
+ #
212
+ # Layout notes
213
+ # - x is [B,H,T,D] and may be a non-contiguous transpose of a [B,T,H,D] view;
214
+ # arbitrary (b,h,t) strides are honoured, D must be stride-1.
215
+ # - D must be a power of two (the C++ kernel requires 64 or 128).
216
+ # - cos/sin are [T_ctx, D//2] fp32, as produced by `build_rope_cache`.
217
+ # - the row index is r = (b*H + h)*T + t, so the output is contiguous
218
+ # [B,H,T,D] in that same order.
219
+ # =============================================================================
220
+ if _HAS_TRITON:
221
+
222
+ @triton.jit
223
+ def _fused_rms_rope_fwd(
224
+ X, GAMMA, COS, SIN, OUT, RSTD,
225
+ sx_b, sx_h, sx_t, # input strides, in elements
226
+ T, H, N, # seq len, n_heads, total rows
227
+ eps,
228
+ D: tl.constexpr, HALF: tl.constexpr, BLOCK_R: tl.constexpr,
229
+ ):
230
+ pid = tl.program_id(0)
231
+ rows = pid * BLOCK_R + tl.arange(0, BLOCK_R) # [R]
232
+ mask_r = rows < N
233
+
234
+ # r = (b*H + h)*T + t -> recover t (for RoPE) and the (b, h) base.
235
+ t = rows % T
236
+ bh = rows // T
237
+ b = bh // H
238
+ h = bh % H
239
+ base = b * sx_b + h * sx_h + t * sx_t # [R]
240
+
241
+ dh = tl.arange(0, HALF) # [HALF]
242
+ p1 = X + base[:, None] + dh[None, :]
243
+ x1 = tl.load(p1, mask=mask_r[:, None], other=0.0).to(tl.float32)
244
+ x2 = tl.load(p1 + HALF, mask=mask_r[:, None], other=0.0).to(tl.float32)
245
+
246
+ # RMS over the FULL head_dim (both halves), fp32 accumulation.
247
+ ss = tl.sum(x1 * x1, 1) + tl.sum(x2 * x2, 1) # [R]
248
+ rstd = 1.0 / tl.sqrt(ss / D + eps) # [R]
249
+
250
+ g1 = tl.load(GAMMA + dh).to(tl.float32)
251
+ g2 = tl.load(GAMMA + HALF + dh).to(tl.float32)
252
+ y1 = x1 * rstd[:, None] * g1[None, :]
253
+ y2 = x2 * rstd[:, None] * g2[None, :]
254
+
255
+ cp = t[:, None] * HALF + dh[None, :]
256
+ c = tl.load(COS + cp, mask=mask_r[:, None], other=0.0)
257
+ s = tl.load(SIN + cp, mask=mask_r[:, None], other=0.0)
258
+
259
+ # NeoX half-split rotation.
260
+ o1 = y1 * c - y2 * s
261
+ o2 = y2 * c + y1 * s
262
+
263
+ op = OUT + rows[:, None] * D + dh[None, :]
264
+ tl.store(op, o1.to(OUT.dtype.element_ty), mask=mask_r[:, None])
265
+ tl.store(op + HALF, o2.to(OUT.dtype.element_ty), mask=mask_r[:, None])
266
+ tl.store(RSTD + rows, rstd, mask=mask_r)
267
+
268
+ # -------------------------------------------------------------------------
269
+ # backward
270
+ #
271
+ # RoPE is an orthogonal rotation, so its vjp is the inverse rotation:
272
+ # dy1 = do1*cos + do2*sin ; dy2 = do2*cos - do1*sin
273
+ # then, with n = x * rstd (the normalised row),
274
+ # dgamma += dy * n
275
+ # dn = dy * gamma
276
+ # dx = rstd * (dn - n * mean(dn * n))
277
+ # -------------------------------------------------------------------------
278
+ @triton.jit
279
+ def _fused_rms_rope_bwd(
280
+ X, GAMMA, COS, SIN, DOUT, RSTD, DX, DGP,
281
+ sx_b, sx_h, sx_t, # input strides
282
+ sd_b, sd_h, sd_t, # dx strides
283
+ T, H, N,
284
+ D: tl.constexpr, HALF: tl.constexpr, BLOCK_R: tl.constexpr,
285
+ ):
286
+ pid = tl.program_id(0)
287
+ rows = pid * BLOCK_R + tl.arange(0, BLOCK_R)
288
+ mask_r = rows < N
289
+
290
+ t = rows % T
291
+ bh = rows // T
292
+ b = bh // H
293
+ h = bh % H
294
+ base = b * sx_b + h * sx_h + t * sx_t
295
+
296
+ dh = tl.arange(0, HALF)
297
+ p1 = X + base[:, None] + dh[None, :]
298
+ x1 = tl.load(p1, mask=mask_r[:, None], other=0.0).to(tl.float32)
299
+ x2 = tl.load(p1 + HALF, mask=mask_r[:, None], other=0.0).to(tl.float32)
300
+
301
+ rstd = tl.load(RSTD + rows, mask=mask_r, other=1.0)
302
+ n1 = x1 * rstd[:, None]
303
+ n2 = x2 * rstd[:, None]
304
+
305
+ dp = DOUT + rows[:, None] * D + dh[None, :]
306
+ do1 = tl.load(dp, mask=mask_r[:, None], other=0.0).to(tl.float32)
307
+ do2 = tl.load(dp + HALF, mask=mask_r[:, None], other=0.0).to(tl.float32)
308
+
309
+ cp = t[:, None] * HALF + dh[None, :]
310
+ c = tl.load(COS + cp, mask=mask_r[:, None], other=0.0)
311
+ s = tl.load(SIN + cp, mask=mask_r[:, None], other=0.0)
312
+
313
+ # inverse rotation
314
+ dy1 = do1 * c + do2 * s
315
+ dy2 = do2 * c - do1 * s
316
+
317
+ # per-program partial dgamma; summed by the caller (deterministic, no atomics)
318
+ tl.store(DGP + pid * D + dh, tl.sum(dy1 * n1, 0))
319
+ tl.store(DGP + pid * D + HALF + dh, tl.sum(dy2 * n2, 0))
320
+
321
+ g1 = tl.load(GAMMA + dh).to(tl.float32)
322
+ g2 = tl.load(GAMMA + HALF + dh).to(tl.float32)
323
+ dn1 = dy1 * g1[None, :]
324
+ dn2 = dy2 * g2[None, :]
325
+
326
+ dot = (tl.sum(dn1 * n1, 1) + tl.sum(dn2 * n2, 1)) / D # [R]
327
+ dx1 = rstd[:, None] * (dn1 - n1 * dot[:, None])
328
+ dx2 = rstd[:, None] * (dn2 - n2 * dot[:, None])
329
+
330
+ dbase = b * sd_b + h * sd_h + t * sd_t
331
+ q1 = DX + dbase[:, None] + dh[None, :]
332
+ tl.store(q1, dx1.to(DX.dtype.element_ty), mask=mask_r[:, None])
333
+ tl.store(q1 + HALF, dx2.to(DX.dtype.element_ty), mask=mask_r[:, None])
334
+
335
+
336
+ _BLOCK_R = 16
337
+ _NUM_WARPS = 4
338
+
339
+
340
+ def _launch_fwd(x, gamma, cos, sin, eps):
341
+ B, H, T, D = x.shape
342
+ N = B * H * T
343
+ out = torch.empty((B, H, T, D), dtype=x.dtype, device=x.device)
344
+ rstd = torch.empty(N, dtype=torch.float32, device=x.device)
345
+ grid = (triton.cdiv(N, _BLOCK_R),)
346
+ _fused_rms_rope_fwd[grid](
347
+ x, gamma, cos, sin, out, rstd,
348
+ x.stride(0), x.stride(1), x.stride(2),
349
+ T, H, N, eps,
350
+ D=D, HALF=D // 2, BLOCK_R=_BLOCK_R, num_warps=_NUM_WARPS,
351
+ )
352
+ return out, rstd
353
+
354
+
355
+ def _launch_bwd(x, gamma, cos, sin, dout, rstd):
356
+ B, H, T, D = x.shape
357
+ N = B * H * T
358
+ dout = dout.contiguous()
359
+ dx = torch.empty_like(x)
360
+ nprog = triton.cdiv(N, _BLOCK_R)
361
+ dgp = torch.empty((nprog, D), dtype=torch.float32, device=x.device)
362
+ _fused_rms_rope_bwd[(nprog,)](
363
+ x, gamma, cos, sin, dout, rstd, dx, dgp,
364
+ x.stride(0), x.stride(1), x.stride(2),
365
+ dx.stride(0), dx.stride(1), dx.stride(2),
366
+ T, H, N,
367
+ D=D, HALF=D // 2, BLOCK_R=_BLOCK_R, num_warps=_NUM_WARPS,
368
+ )
369
+ return dx, dgp.sum(0).to(gamma.dtype)
370
+
371
+
372
+ class _FusedRMSRoPE(torch.autograd.Function):
373
+ """QK-norm + RoPE for q and k in one autograd node (two kernel launches).
374
+ Mirrors the C++ `fused_rms_rope(q, k, q_gamma, k_gamma, cache)`: q/k keep
375
+ their incoming dtype (bf16 under autocast), the reduction and the rotation
376
+ run in fp32 internally, gamma and the cache stay fp32.
377
+ """
378
+
379
+ @staticmethod
380
+ def forward(ctx, q, k, q_gamma, k_gamma, cos, sin, eps):
381
+ qo, q_rstd = _launch_fwd(q, q_gamma, cos, sin, eps)
382
+ ko, k_rstd = _launch_fwd(k, k_gamma, cos, sin, eps)
383
+ ctx.save_for_backward(q, k, q_gamma, k_gamma, cos, sin, q_rstd, k_rstd)
384
+ return qo, ko
385
+
386
+ @staticmethod
387
+ def backward(ctx, dqo, dko):
388
+ q, k, q_gamma, k_gamma, cos, sin, q_rstd, k_rstd = ctx.saved_tensors
389
+ dq, dqg = _launch_bwd(q, q_gamma, cos, sin, dqo, q_rstd)
390
+ dk, dkg = _launch_bwd(k, k_gamma, cos, sin, dko, k_rstd)
391
+ return dq, dk, dqg, dkg, None, None, None
392
+
393
+
394
+ def fused_rms_rope(q, k, q_gamma, k_gamma, cos, sin, eps):
395
+ """q: [B,Hq,T,D], k: [B,Hkv,T,D] -> same shapes, contiguous.
396
+ `cos`/`sin` are [>=T, D//2] fp32; only the first T rows are read.
397
+ """
398
+ assert q.shape[-1] == k.shape[-1], "q and k must share head_dim"
399
+ D = q.shape[-1]
400
+ assert D % 2 == 0 and (D & (D - 1)) == 0, f"head_dim must be a power of two, got {D}"
401
+ assert q.stride(-1) == 1 and k.stride(-1) == 1, "head_dim must be stride-1"
402
+ T = q.shape[2]
403
+ return _FusedRMSRoPE.apply(q, k, q_gamma, k_gamma,
404
+ cos[:T].contiguous(), sin[:T].contiguous(), eps)
405
+
406
+
407
+ def rms_rope_eager(x, gamma, cos, sin, eps):
408
+ """Unfused QK-norm then NeoX RoPE, fp32 throughout — the reference the fused
409
+ kernel is measured against (`--rms-rope eager`), and the fallback when
410
+ Triton is unavailable."""
411
+ T, D = x.shape[2], x.shape[-1]
412
+ xf = x.float()
413
+ xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps) * gamma
414
+ x1, x2 = xf[..., : D // 2], xf[..., D // 2:]
415
+ c = cos[:T][None, None, :, :]
416
+ s = sin[:T][None, None, :, :]
417
+ return torch.cat([x1 * c - x2 * s, x2 * c + x1 * s], dim=-1).to(x.dtype)
418
+
419
+
420
+ def build_rope_cache(seq_len, head_dim, theta, device):
421
+ """NeoX / Llama RoPE cache: cos, sin of shape [seq_len, head_dim//2], fp32."""
422
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32,
423
+ device=device) / head_dim))
424
+ pos = torch.arange(seq_len, dtype=torch.float32, device=device)
425
+ freqs = torch.outer(pos, inv_freq) # [T, D/2]
426
+ return torch.cos(freqs).contiguous(), torch.sin(freqs).contiguous()
427
+
428
+
429
+ # =============================================================================
430
+ # 2. Configuration — 1:1 with ModelConfig in bluscript_single.cpp — and the WSD
431
+ # learning-rate schedule.
432
+ # =============================================================================
433
+ @dataclass
434
+ class ModelConfig:
435
+ # ---- model ----
436
+ d_model: int = 960
437
+ n_layers: int = 30
438
+ q_heads: int = 15
439
+ kv_heads: int = 5 # grouped-query: G = q/kv = 4
440
+ head_dim: int = 64 # the fused kernels need 64 or 128
441
+ ffn_hidden: int = 2560 # ~8/3 * d_model, rounded to /256
442
+ context_length: int = 4096 # RoPE cache length; must be >= T
443
+ rope_theta: float = 500000.0
444
+ vocab_size: int = 50304 # 50257 (tiktoken) padded for the GPU
445
+ weight_tying: bool = False
446
+
447
+ rms_eps: float = 1e-5 # block RMSNorm epsilon
448
+ qk_eps: float = 1e-6 # QK-norm (fused) epsilon
449
+
450
+ # ---- optimization / data ----
451
+ B: int = 4 # micro-batch
452
+ T: int = 4096 # sequence length (<= context_length)
453
+ global_batch: int = 524288 # tokens per optimizer step
454
+ grad_clip: float = 1.0
455
+ weight_decay: float = 0.1
456
+
457
+ # WSD: linear warmup -> constant at max_lr -> cosine decay to min_lr.
458
+ # Requires warmup_steps + stable_steps < max_steps - 1 (the remainder is
459
+ # the decay tail).
460
+ max_lr: float = 0.0005
461
+ min_lr: float = 0.00005 # 10% of max_lr
462
+
463
+ muon_lr: float = 0.0005
464
+ muon_min_lr: float = 0.00005
465
+
466
+ max_steps: int = 26703
467
+
468
+ warmup_steps: int = 500
469
+ stable_steps: int = int(max_steps * 0.9) - warmup_steps # steps held at max_lr after warmup
470
+
471
+
472
+ # ---- Muon (hidden 2D weights); the AdamW fields above still drive the
473
+ # embedding / lm_head / 1D group, unchanged from the AdamW arm ----
474
+ # Default == max_lr: under adjust_lr_fn=match_rms_adamw the two are the same unit,
475
+ # so out of the box both arms take the same size step and differ only in
476
+ # direction. Same 10% floor, same WSD shape, so the schedules stay aligned.
477
+
478
+ # The rest are torch.optim.Muon's own arguments, passed through unchanged.
479
+ # momentum/nesterov/ns_steps are torch's defaults; adjust_lr_fn is not (see
480
+ # the header — torch defaults to "original").
481
+ muon_momentum: float = 0.95 # beta on the momentum buffer
482
+ muon_ns_steps: int = 5 # Newton-Schulz iterations
483
+ muon_adjust_lr: str = "match_rms_adamw" # "match_rms_adamw" | "original"
484
+
485
+ val_freq: int = 250
486
+ val_loss_steps: int = 20
487
+
488
+ # ---- checkpointing ----
489
+ checkpointing: bool = True
490
+ ckpt_freq: int = 1000 # save every 1800 optimizer steps
491
+ ckpt_keep: int = 40 # retain the most-recent N checkpoints
492
+ # Separate from the AdamW arm's dir: the two checkpoint formats differ (Muon
493
+ # momentum vs Adam m/v) and auto-resume picks the newest file it finds.
494
+ ckpt_dir: str = "ckpt_blu_muon"
495
+ ckpt_prefix: str = "blumodel_muon"
496
+
497
+ # ---- runtime knobs (not in the C++ struct) ----
498
+ fused_rms_rope: bool = True
499
+ activation_checkpoint: bool = False
500
+ loss_chunks: int = 1
501
+ # Depth probe: which layers --diag reports gradient / weight statistics for.
502
+ probe_layers: tuple = (0, 8, 17, 26, 35)
503
+
504
+
505
+ def get_lr(step, cfg, max_lr=None, min_lr=None):
506
+ """WSD: linear Warmup -> Stable (constant max_lr) -> cosine Decay to min_lr.
507
+ Byte-for-byte the C++ get_lr().
508
+ `max_lr`/`min_lr` override the config pair so the Muon group can ride the
509
+ SAME schedule shape — same warmup length, same stable window, same cosine
510
+ tail — at its own amplitude. Called with no override it is identical to the
511
+ AdamW arm's get_lr(), which is what the embedding/norm group uses.
512
+ """
513
+ max_lr = cfg.max_lr if max_lr is None else max_lr
514
+ min_lr = cfg.min_lr if min_lr is None else min_lr
515
+ if step < cfg.warmup_steps:
516
+ return max_lr * (step + 1) / cfg.warmup_steps
517
+ if step < cfg.stable_steps + cfg.warmup_steps:
518
+ return max_lr
519
+ tail = cfg.max_steps - (cfg.stable_steps + cfg.warmup_steps) - 1
520
+ decay_ratio = (step - (cfg.stable_steps + cfg.warmup_steps)) / max(tail, 1)
521
+ decay_ratio = min(max(decay_ratio, 0.0), 1.0)
522
+ coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) # 1 -> 0
523
+ return min_lr + coeff * (max_lr - min_lr)
524
+
525
+
526
+ # =============================================================================
527
+ # 3. Data — port of the C++ DataLoaderLite (Tensor-Implementations/include/
528
+ # DataLoader.h), including its pinned-host / side-stream prefetch ring.
529
+ #
530
+ # Shards are HEADERLESS flat uint16 token files. A shard is "val" if "val"
531
+ # appears anywhere in its basename, "train" otherwise — this covers both an
532
+ # explicit flux_train_*/flux_val_* naming and an unmarked-train naming like
533
+ # flux_20b_shard_*.bin alongside a separately named *val* shard. For a batch
534
+ # at position p:
535
+ # x = tokens[p : p+B*T] y = tokens[p+1 : p+B*T+1]
536
+ # p strides by B*T (world_size == 1 here). A shard tail that cannot fit a full
537
+ # stride is dropped and the loader wraps to the next shard.
538
+ #
539
+ # The prefetch mirrors the C++ ring: NBUF pinned staging buffers and NBUF device
540
+ # tensors, H2D issued on a side stream, CUDA events ordering producer against
541
+ # consumer. Each slot also carries the (shard, token offset) it was filled from,
542
+ # which is what --diag prints to name the bytes behind a loss spike.
543
+ # =============================================================================
544
+ class DataLoaderLite:
545
+ NBUF = 4
546
+
547
+ def __init__(self, B, T, split, data_root, device, master=True,
548
+ max_tokens_per_shard=100_000_000, rank=0, world_size=1):
549
+ assert split in ("train", "val")
550
+ self.B, self.T = B, T
551
+ self.split = split
552
+ self.max_tokens = max_tokens_per_shard
553
+ self.device = device
554
+ # DDP: every rank reads the SAME shard list but a DISJOINT, interleaved
555
+ # slice of it (offset by rank, strided by world_size), so a training
556
+ # step's world_size*grad_accum micro-batches never repeat a window.
557
+ self.rank = rank
558
+ self.world_size = world_size
559
+
560
+ # Shard naming isn't consistent across datasets: some mark the split
561
+ # explicitly in both names (flux_train_*.bin / flux_val_*.bin), others
562
+ # only mark val and leave train shards unmarked (flux_20b_shard_*.bin
563
+ # + a separate *val* file). Treat "contains val" as the val split and
564
+ # everything else as train so both conventions resolve correctly.
565
+ self.shards = sorted(
566
+ p for p in glob.glob(os.path.join(data_root, "*.bin"))
567
+ if ("val" in os.path.basename(p).lower()) == (split == "val")
568
+ )
569
+ if not self.shards:
570
+ raise RuntimeError(f"no .bin shards found for split {split} in {data_root}")
571
+ if master:
572
+ print(f"found {len(self.shards)} shards for split {split}")
573
+
574
+ BT = B * T
575
+ self.pin_x = [torch.empty(BT, dtype=torch.int64).pin_memory() for _ in range(self.NBUF)]
576
+ self.pin_y = [torch.empty(BT, dtype=torch.int64).pin_memory() for _ in range(self.NBUF)]
577
+ self.dev_x = [torch.empty(B, T, dtype=torch.int64, device=device) for _ in range(self.NBUF)]
578
+ self.dev_y = [torch.empty(B, T, dtype=torch.int64, device=device) for _ in range(self.NBUF)]
579
+ self.copy_stream = torch.cuda.Stream(device=device)
580
+ self.h2d_done = [torch.cuda.Event() for _ in range(self.NBUF)]
581
+ self.h2d_recorded = [False] * self.NBUF
582
+ self.where = [(0, 0)] * self.NBUF # (shard_index, token_offset)
583
+ self.reset()
584
+
585
+ # -- shard plumbing ------------------------------------------------------
586
+ def _load_shard(self, i):
587
+ self.cur = i
588
+ arr = np.memmap(self.shards[i], dtype=np.uint16, mode="r")
589
+ self.tok = arr
590
+ self.ntok = min(len(arr), self.max_tokens)
591
+
592
+ def _advance_shard(self):
593
+ self._load_shard((self.cur + 1) % len(self.shards))
594
+ self.pos = self.B * self.T * self.rank
595
+
596
+ def reset(self):
597
+ self.copy_stream.synchronize()
598
+ self._load_shard(0)
599
+ self.pos = self.B * self.T * self.rank
600
+ self.primed = False
601
+ self.buf = 0
602
+
603
+ # -- prefetch ------------------------------------------------------------
604
+ def _stage(self, idx):
605
+ BT = self.B * self.T
606
+ stride = BT * self.world_size
607
+ if self.ntok < BT + 1:
608
+ raise RuntimeError(f"shard too small for one batch: {self.shards[self.cur]}")
609
+ if self.pos + BT + 1 > self.ntok:
610
+ self._advance_shard()
611
+
612
+ # Host-side WAR guard: the pinned buffer may still be the source of the
613
+ # H2D issued the last time this slot was filled (that copy is gated on
614
+ # the device, not the host, so a host running ahead of the GPU would
615
+ # otherwise overwrite bytes still in flight and hand the model a batch
616
+ # spliced from two different windows).
617
+ if self.h2d_recorded[idx]:
618
+ self.h2d_done[idx].synchronize()
619
+
620
+ self.where[idx] = (self.cur, self.pos)
621
+ buf = np.asarray(self.tok[self.pos: self.pos + BT + 1]).astype(np.int64)
622
+ self.pin_x[idx].copy_(torch.from_numpy(buf[:-1]))
623
+ self.pin_y[idx].copy_(torch.from_numpy(buf[1:]))
624
+
625
+ with torch.cuda.stream(self.copy_stream):
626
+ self.dev_x[idx].view(-1).copy_(self.pin_x[idx], non_blocking=True)
627
+ self.dev_y[idx].view(-1).copy_(self.pin_y[idx], non_blocking=True)
628
+ self.h2d_done[idx].record(self.copy_stream)
629
+ self.h2d_recorded[idx] = True
630
+
631
+ self.pos += stride
632
+ if self.pos + BT + 1 > self.ntok:
633
+ self._advance_shard()
634
+
635
+ def next_batch(self):
636
+ """-> (x, y, shard_index, token_offset), x/y int64 [B,T] on device."""
637
+ if not self.primed:
638
+ for i in range(self.NBUF):
639
+ self._stage(i)
640
+ self.primed = True
641
+ self.buf = 0
642
+ else:
643
+ # Refill the slot returned LAST call. Its consumer's kernels are
644
+ # already queued on the compute stream, so the producer must wait
645
+ # for them before overwriting the device tensor.
646
+ self.copy_stream.wait_stream(torch.cuda.current_stream())
647
+ self._stage((self.buf - 1) % self.NBUF)
648
+
649
+ torch.cuda.current_stream().wait_event(self.h2d_done[self.buf])
650
+ i = self.buf
651
+ self.buf = (self.buf + 1) % self.NBUF
652
+ return self.dev_x[i], self.dev_y[i], self.where[i][0], self.where[i][1]
653
+
654
+ def skip_batches(self, n):
655
+ """Fast-forward `n` batches without touching the GPU (resume path)."""
656
+ self.copy_stream.synchronize()
657
+ self.primed = False
658
+ BT = self.B * self.T
659
+ stride = BT * self.world_size
660
+ for _ in range(n):
661
+ if self.pos + BT + 1 > self.ntok:
662
+ self._advance_shard()
663
+ self.pos += stride
664
+ if self.pos + BT + 1 > self.ntok:
665
+ self._advance_shard()
666
+
667
+
668
+ # =============================================================================
669
+ # 4. Model.
670
+ #
671
+ # Precision (bf16 mixed precision; both --precision modes run under autocast):
672
+ # bf16-params : Linear weights stored bf16, embedding / RMSNorm / QK-norm
673
+ # scales stay fp32, fp32 master weights live in the optimizer
674
+ # — the exact scheme bluscript_single.cpp uses (default).
675
+ # bf16 : all params fp32, autocast casts per-op (standard PyTorch AMP).
676
+ # In both cases: matmuls + attention bf16, RMSNorm / QK-norm reductions, RoPE,
677
+ # softmax and the loss in fp32. No GradScaler (bf16 has fp32's exponent range).
678
+ # =============================================================================
679
+ _FLASH = [SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION]
680
+
681
+
682
+ class RMSNorm(nn.Module):
683
+ """RMSNorm over d_model, fp32 weight. F.rms_norm is a fused ATen op and is
684
+ not autocast-eligible, so it runs in the input dtype — fp32 on the residual
685
+ stream, matching the C++ nn::RMSNorm."""
686
+
687
+ def __init__(self, dim, eps):
688
+ super().__init__()
689
+ self.weight = nn.Parameter(torch.ones(dim))
690
+ self.eps = eps
691
+ self.dim = (dim,)
692
+
693
+ def forward(self, x):
694
+ return F.rms_norm(x, self.dim, self.weight, self.eps)
695
+
696
+
697
+ class CausalGQA(nn.Module):
698
+ """RMSNorm -> fused(QK-norm + RoPE) -> causal grouped-query attention -> Wo -> +x"""
699
+
700
+ def __init__(self, cfg, resid_scale):
701
+ super().__init__()
702
+ self.cfg = cfg
703
+ self.norm = RMSNorm(cfg.d_model, cfg.rms_eps)
704
+ self.wQ = nn.Linear(cfg.d_model, cfg.q_heads * cfg.head_dim, bias=False)
705
+ self.wK = nn.Linear(cfg.d_model, cfg.kv_heads * cfg.head_dim, bias=False)
706
+ self.wV = nn.Linear(cfg.d_model, cfg.kv_heads * cfg.head_dim, bias=False)
707
+ self.wO = nn.Linear(cfg.q_heads * cfg.head_dim, cfg.d_model, bias=False)
708
+ # QK-norm scales, initialised to 1.0 (identity RMS scale), fp32.
709
+ self.q_gamma = nn.Parameter(torch.ones(cfg.head_dim))
710
+ self.k_gamma = nn.Parameter(torch.ones(cfg.head_dim))
711
+ # GPT-2/Llama init: projections std=0.02, residual proj scaled by
712
+ # (2*n_layers)^-0.5 to keep residual-stream variance ~constant.
713
+ for lin in (self.wQ, self.wK, self.wV):
714
+ nn.init.normal_(lin.weight, mean=0.0, std=0.02)
715
+ nn.init.normal_(self.wO.weight, mean=0.0, std=0.02 * resid_scale)
716
+
717
+ def forward(self, x, cos, sin):
718
+ cfg = self.cfg
719
+ B, T, _ = x.shape
720
+ h = self.norm(x)
721
+
722
+ # [B,T,H*D] -> [B,H,T,D]. The transpose stays a view; the fused kernel
723
+ # honours arbitrary (b,h,t) strides, so no .contiguous() is paid here.
724
+ q = self.wQ(h).view(B, T, cfg.q_heads, cfg.head_dim).transpose(1, 2)
725
+ k = self.wK(h).view(B, T, cfg.kv_heads, cfg.head_dim).transpose(1, 2)
726
+ v = self.wV(h).view(B, T, cfg.kv_heads, cfg.head_dim).transpose(1, 2)
727
+
728
+ if cfg.fused_rms_rope:
729
+ q, k = fused_rms_rope(q, k, self.q_gamma, self.k_gamma, cos, sin, cfg.qk_eps)
730
+ else:
731
+ q = rms_rope_eager(q, self.q_gamma, cos, sin, cfg.qk_eps)
732
+ k = rms_rope_eager(k, self.k_gamma, cos, sin, cfg.qk_eps)
733
+
734
+ # Separate fused flash kernel. enable_gqa maps query head i to kv head
735
+ # i // (q_heads/kv_heads), the same grouping as the C++ kernel.
736
+ with sdpa_kernel(_FLASH):
737
+ o = F.scaled_dot_product_attention(
738
+ q.to(v.dtype), k.to(v.dtype), v, is_causal=True, enable_gqa=True)
739
+
740
+ o = o.transpose(1, 2).reshape(B, T, cfg.q_heads * cfg.head_dim)
741
+ return x + self.wO(o)
742
+
743
+
744
+ class SwiGLUMLP(nn.Module):
745
+ """RMSNorm -> gate_up -> silu(gate)*up -> down -> +x ([gate | up] layout)"""
746
+
747
+ def __init__(self, cfg, resid_scale):
748
+ super().__init__()
749
+ self.norm = RMSNorm(cfg.d_model, cfg.rms_eps)
750
+ self.gate_up = nn.Linear(cfg.d_model, 2 * cfg.ffn_hidden, bias=False)
751
+ self.down = nn.Linear(cfg.ffn_hidden, cfg.d_model, bias=False)
752
+ nn.init.normal_(self.gate_up.weight, mean=0.0, std=0.02)
753
+ nn.init.normal_(self.down.weight, mean=0.0, std=0.02 * resid_scale)
754
+
755
+ def forward(self, x):
756
+ gate, up = self.gate_up(self.norm(x)).chunk(2, dim=-1)
757
+ return x + self.down(F.silu(gate) * up)
758
+
759
+
760
+ class Block(nn.Module):
761
+ def __init__(self, cfg, resid_scale):
762
+ super().__init__()
763
+ self.attn = CausalGQA(cfg, resid_scale)
764
+ self.mlp = SwiGLUMLP(cfg, resid_scale)
765
+
766
+ def forward(self, x, cos, sin):
767
+ return self.mlp(self.attn(x, cos, sin))
768
+
769
+
770
+ class BLU(nn.Module):
771
+ def __init__(self, cfg):
772
+ super().__init__()
773
+ self.cfg = cfg
774
+ resid_scale = 1.0 / math.sqrt(2.0 * cfg.n_layers)
775
+
776
+ self.wte = nn.Embedding(cfg.vocab_size, cfg.d_model)
777
+ nn.init.normal_(self.wte.weight, mean=0.0, std=0.02)
778
+
779
+ self.blocks = nn.ModuleList([Block(cfg, resid_scale) for _ in range(cfg.n_layers)])
780
+ self.norm_f = RMSNorm(cfg.d_model, cfg.rms_eps)
781
+ if not cfg.weight_tying:
782
+ self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
783
+ nn.init.normal_(self.lm_head.weight, mean=0.0, std=0.02)
784
+
785
+ cos, sin = build_rope_cache(cfg.context_length, cfg.head_dim, cfg.rope_theta, "cpu")
786
+ self.register_buffer("rope_cos", cos, persistent=False)
787
+ self.register_buffer("rope_sin", sin, persistent=False)
788
+
789
+ def apply_param_dtype(self, mode):
790
+ """`bf16-params`: store Linear weights in bf16 (embedding, RMSNorm and
791
+ QK-norm scales stay fp32) — the two-dtype-group layout of the C++ model.
792
+ Under autocast this is transparent: the cast to bf16 becomes a no-op."""
793
+ if mode != "bf16-params":
794
+ return
795
+ for m in self.modules():
796
+ if isinstance(m, nn.Linear):
797
+ m.weight.data = m.weight.data.to(torch.bfloat16)
798
+
799
+ def forward(self, idx, targets=None):
800
+ cfg = self.cfg
801
+ T = idx.shape[1]
802
+ cos, sin = self.rope_cos[:T], self.rope_sin[:T]
803
+
804
+ x = self.wte(idx) # fp32 [B,T,d_model]
805
+ for blk in self.blocks:
806
+ if cfg.activation_checkpoint and self.training:
807
+ x = checkpoint(blk, x, cos, sin, use_reentrant=False)
808
+ else:
809
+ x = blk(x, cos, sin)
810
+ x = self.norm_f(x)
811
+
812
+ head_w = self.wte.weight if cfg.weight_tying else self.lm_head.weight
813
+ if targets is None:
814
+ return F.linear(x, head_w), None
815
+ if cfg.loss_chunks > 1:
816
+ return None, _chunked_ce(x, head_w, targets, cfg.loss_chunks)
817
+ # Matches the C++: bf16 matmul, logits promoted to fp32 for the loss
818
+ # (cross_entropy is an autocast-fp32 op, so the promotion is implicit).
819
+ logits = F.linear(x, head_w)
820
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.reshape(-1))
821
+ return logits, loss
822
+
823
+
824
+ def _chunked_ce(x, weight, targets, chunks):
825
+ """lm_head + cross-entropy in row chunks, logits recomputed in backward.
826
+ Peak logit memory drops from [B*T, V] to [B*T/chunks, V] at the cost of one
827
+ extra lm_head matmul. Off by default (`--loss-chunks 1`) so the memory
828
+ profile matches the C++ script, which materialises the full fp32 logits.
829
+ """
830
+ xf = x.reshape(-1, x.shape[-1])
831
+ tf = targets.reshape(-1)
832
+ n = xf.shape[0]
833
+ size = (n + chunks - 1) // chunks
834
+ total = xf.new_zeros((), dtype=torch.float32)
835
+ for lo in range(0, n, size):
836
+ hi = min(lo + size, n)
837
+ part = checkpoint(_ce_chunk, xf[lo:hi], weight, tf[lo:hi], use_reentrant=False)
838
+ total = total + part * (hi - lo)
839
+ return total / n
840
+
841
+
842
+ def _ce_chunk(x, weight, targets):
843
+ return F.cross_entropy(F.linear(x, weight).float(), targets)
844
+
845
+
846
+ # =============================================================================
847
+ # 5. Optimizer (Muon on the hidden matrices, AdamW on the rest), gradient
848
+ # clipping, checkpointing.
849
+ # =============================================================================
850
+ def _is_muon_param(name, p):
851
+ """Muon orthogonalizes a matrix, so it needs the parameter to BE a linear
852
+ map between two feature spaces:
853
+ * dim >= 2 — RMSNorm weights and QK-norm gammas are 1D and have no
854
+ singular values to equalise;
855
+ * not the embedding / lm_head — its rows index tokens, not features, so
856
+ the left singular vectors mix unrelated vocabulary entries. Weight
857
+ tying makes this one tensor serving both ends; either way it is AdamW's.
858
+ Everything else — wQ/wK/wV/wO, gate_up, down — is Muon's: 75.5M of the
859
+ 114.2M parameters at the default config.
860
+ """
861
+ return p.dim() >= 2 and not name.startswith(("wte.", "lm_head."))
862
+
863
+
864
+ def _state_bytes(opt):
865
+ """Bytes held in a torch optimizer's per-parameter state — Adam's m/v, or
866
+ Muon's momentum buffer. Reads 0 before the first step(): both allocate
867
+ lazily."""
868
+ return sum(v.numel() * v.element_size()
869
+ for st in opt.state.values()
870
+ for v in st.values() if torch.is_tensor(v))
871
+
872
+
873
+ class MasterMuon:
874
+ """torch.optim.Muon on the hidden matrices + torch.optim.AdamW on the rest,
875
+ both driving fp32 master weights.
876
+ Neither optimizer is reimplemented here. What this class owns is the part
877
+ torch cannot know about:
878
+ * ROUTING — torch.optim.Muon accepts whatever you hand it and the docs are
879
+ explicit that only 2D hidden weights belong ("bias, and embedding,
880
+ should be optimized by a standard method such as AdamW"). The split is
881
+ `_is_muon_param`.
882
+ * MASTER WEIGHTS — the parameters are bf16 under --precision bf16-params,
883
+ and a bf16 tensor cannot absorb an lr*update of 1e-4 relative size. So
884
+ both optimizers are constructed over the fp32 MASTERS, fed from the fp32
885
+ landing buffers, and the masters are cast back over the params after the
886
+ step. Unchanged from the AdamW arm — that machinery is what makes the
887
+ two arms comparable, since both optimizers then read a bit-identical
888
+ fp32 gradient and write a bit-identical bf16 parameter.
889
+ Weight decay is decoupled in both (torch.optim.Muon applies it before the
890
+ update, as AdamW does) and is applied to the master for the same reason: a
891
+ decay written to the bf16 param is overwritten by the master write-back
892
+ microseconds later and silently no-ops.
893
+ State cost: Muon holds one momentum buffer per param, against Adam's two.
894
+ """
895
+
896
+ def __init__(self, named_params, cfg):
897
+ self.cfg = cfg
898
+ self.triples = [] # (param, master, landing_grad), ALL params
899
+ self.muon_masters = [] # masters routed to Muon
900
+ decay, nodecay = [], []
901
+ self.n_muon = self.n_decay = self.n_nodecay = 0
902
+ for name, p in named_params:
903
+ if p.dtype == torch.float32:
904
+ m, g = p, None
905
+ else:
906
+ m = p.detach().float().clone()
907
+ g = torch.zeros_like(m)
908
+ m.grad = g
909
+ self.triples.append((p, m, g))
910
+ if _is_muon_param(name, p):
911
+ self.muon_masters.append(m)
912
+ self.n_muon += m.numel()
913
+ elif p.dim() >= 2:
914
+ decay.append(m)
915
+ self.n_decay += m.numel()
916
+ else:
917
+ nodecay.append(m)
918
+ self.n_nodecay += m.numel()
919
+ self.opt = torch.optim.AdamW(
920
+ [{"params": decay, "weight_decay": cfg.weight_decay},
921
+ {"params": nodecay, "weight_decay": 0.0}],
922
+ lr=cfg.max_lr, betas=(0.9, 0.95), eps=1e-8, fused=True)
923
+ # Everything below is a torch.optim.Muon default except adjust_lr_fn
924
+ # (torch: "original") and weight_decay, which is pinned to the AdamW
925
+ # arm's 0.1 so the decay is identical across both groups and both arms.
926
+ self.muon = torch.optim.Muon(
927
+ self.muon_masters,
928
+ lr=cfg.muon_lr,
929
+ weight_decay=cfg.weight_decay,
930
+ momentum=cfg.muon_momentum,
931
+ nesterov=True,
932
+ ns_steps=cfg.muon_ns_steps,
933
+ adjust_lr_fn=cfg.muon_adjust_lr)
934
+
935
+ @torch.no_grad()
936
+ def step(self, lr, muon_lr):
937
+ for p, m, g in self.triples:
938
+ if g is not None:
939
+ g.copy_(p.grad) # bf16 grad -> fp32 landing buffer
940
+ # AdamW group (embedding / lm_head / norms / gammas) — identical to the
941
+ # baseline's update, on identical gradients.
942
+ for grp in self.opt.param_groups:
943
+ grp["lr"] = lr
944
+ self.opt.step()
945
+ # Muon group. Its nesterov path may consume the gradient in place; that
946
+ # is harmless here because grad_norm and the --diag probes are read
947
+ # before step() and the landing buffers are overwritten wholesale on the
948
+ # next one.
949
+ for grp in self.muon.param_groups:
950
+ grp["lr"] = muon_lr
951
+ self.muon.step()
952
+ for p, m, g in self.triples:
953
+ if g is not None:
954
+ p.data.copy_(m) # fp32 master -> bf16 param
955
+
956
+ def state_breakdown(self):
957
+ """-> (master_bytes, landing_grad_bytes, adam_mv_bytes, muon_mom_bytes).
958
+ The first two are zero under --precision bf16, where the master IS the
959
+ parameter and the gradient is already fp32. Both optimizers allocate
960
+ their state lazily on the first step(), so the last two read 0 until
961
+ then — the startup report uses the expected_* predictors instead.
962
+ """
963
+ master = landing = 0
964
+ for p, m, g in self.triples:
965
+ if m is not p:
966
+ master += m.numel() * m.element_size()
967
+ landing += g.numel() * g.element_size()
968
+ mv = _state_bytes(self.opt)
969
+ mom = _state_bytes(self.muon)
970
+ return master, landing, mv, mom
971
+
972
+ def state_bytes(self):
973
+ return sum(self.state_breakdown())
974
+
975
+ def expected_mv_bytes(self):
976
+ """Adam m/v are lazily allocated, so the startup report has to predict
977
+ them rather than measure them. Muon's params are excluded — they carry a
978
+ momentum buffer instead, reported separately."""
979
+ muon_ids = {id(m) for m in self.muon_masters}
980
+ return sum(m.numel() * m.element_size() * 2
981
+ for _, m, _ in self.triples if id(m) not in muon_ids)
982
+
983
+ def expected_muon_mom_bytes(self):
984
+ """One fp32 momentum buffer per Muon parameter — the prediction the
985
+ startup report prints before step 0 has allocated it."""
986
+ return sum(m.numel() * m.element_size() for m in self.muon_masters)
987
+
988
+ # -- checkpointing -------------------------------------------------------
989
+ def state_dict(self):
990
+ # `optimizer` tags the arm: resuming a Muon run from an AdamW checkpoint
991
+ # would restore the weights and then silently drop the momentum, so
992
+ # CheckpointManager refuses on a mismatch rather than producing a run
993
+ # that looks fine and is not comparable to either arm.
994
+ return {"optimizer": "muon",
995
+ "adam": self.opt.state_dict(),
996
+ "muon": self.muon.state_dict(),
997
+ "masters": [None if m is p else m for p, m, g in self.triples]}
998
+
999
+ @torch.no_grad()
1000
+ def load_state_dict(self, blob):
1001
+ """-> True if the fp32 masters were restored from the checkpoint."""
1002
+ if blob.get("optimizer") != "muon":
1003
+ raise SystemExit(
1004
+ "ERROR: this checkpoint was written by the AdamW arm (train.py). "
1005
+ "Point --ckpt-dir somewhere else, or resume it with train.py.")
1006
+ self.opt.load_state_dict(blob["adam"])
1007
+ if blob.get("muon") is not None:
1008
+ self.muon.load_state_dict(blob["muon"])
1009
+ masters = blob.get("masters")
1010
+ if masters is None or len(masters) != len(self.triples):
1011
+ return False
1012
+ for (p, m, g), saved in zip(self.triples, masters):
1013
+ if saved is not None and m is not p:
1014
+ m.copy_(saved.to(m.device))
1015
+ return True
1016
+
1017
+ @torch.no_grad()
1018
+ def resync_masters(self):
1019
+ """Re-seed every master from its parameter.
1020
+ Needed after loading a checkpoint that carries no masters: the masters
1021
+ were built in __init__ from the RANDOM INIT, so without this the first
1022
+ step() would write them straight back over the restored weights and
1023
+ silently throw the run away.
1024
+ """
1025
+ for p, m, g in self.triples:
1026
+ if m is not p:
1027
+ m.copy_(p.detach().float())
1028
+
1029
+
1030
+ def clip_grads_(params, max_norm):
1031
+ """ONE global L2 norm over every parameter, then one rescale — the textbook
1032
+ definition. (It differs from the ZeRO script, which clips each dtype group
1033
+ against its own norm and can therefore let the true global norm reach
1034
+ sqrt(n_groups) * grad_clip.) The per-tensor norms are promoted to fp32
1035
+ before they are combined, or a reduction over ~250 bf16 norms would lose
1036
+ ~3 digits."""
1037
+ grads = [p.grad for p in params if p.grad is not None]
1038
+ norms = torch._foreach_norm(grads)
1039
+ total = torch.linalg.vector_norm(torch.stack([n.float() for n in norms]))
1040
+ if max_norm and max_norm > 0:
1041
+ clip = (max_norm / (total + 1e-6)).clamp(max=1.0)
1042
+ torch._foreach_mul_(grads, clip)
1043
+ return total
1044
+
1045
+
1046
+ class CheckpointManager:
1047
+ """Synchronous save / keep-N / auto-resume, mirroring the C++
1048
+ CheckpointManager. A checkpoint holds the model parameters, Adam's m/v, the
1049
+ fp32 masters, and the step it should resume at."""
1050
+
1051
+ def __init__(self, ckpt_dir, prefix, keep):
1052
+ self.dir, self.prefix, self.keep = ckpt_dir, prefix, keep
1053
+ os.makedirs(ckpt_dir, exist_ok=True)
1054
+
1055
+ def _path(self, step):
1056
+ return os.path.join(self.dir, f"{self.prefix}_step{step:08d}.pt")
1057
+
1058
+ def _existing(self):
1059
+ out = []
1060
+ for p in glob.glob(os.path.join(self.dir, f"{self.prefix}_step*.pt")):
1061
+ m = re.search(r"_step(\d+)\.pt$", os.path.basename(p))
1062
+ if m:
1063
+ out.append((int(m.group(1)), p))
1064
+ return sorted(out)
1065
+
1066
+ def save(self, step, model, opt, loss, last_val, cfg):
1067
+ tmp = self._path(step) + ".tmp"
1068
+ torch.save({"step": step, "loss": loss, "last_val": last_val,
1069
+ # B/T/global_batch pin the data stride this checkpoint's
1070
+ # step count assumes. world_size is deliberately NOT
1071
+ # recorded: grad_accum = global_batch // (B*T*world_size)
1072
+ # already makes tokens-per-step (and skip_batches'
1073
+ # target offset) independent of how many ranks are
1074
+ # running, so a GPU-count change alone is not a mismatch.
1075
+ "run_cfg": {"B": cfg.B, "T": cfg.T,
1076
+ "global_batch": cfg.global_batch},
1077
+ "model": model.state_dict(),
1078
+ "opt": opt.state_dict()}, tmp)
1079
+ # Rename last: a crash mid-write leaves a .tmp, never a truncated
1080
+ # checkpoint that the next load_latest would pick as the newest.
1081
+ os.replace(tmp, self._path(step))
1082
+ if self.keep > 0:
1083
+ for _, stale in self._existing()[:-self.keep]:
1084
+ os.remove(stale)
1085
+
1086
+ def load_latest(self, model, opt, cfg, master=True):
1087
+ """-> (start_step, loss, last_val). (0, 0.0, nan) when there is
1088
+ nothing to resume."""
1089
+ existing = self._existing()
1090
+ if not existing:
1091
+ return 0, 0.0, float("nan")
1092
+ _, path = existing[-1]
1093
+ return self.load(path, model, opt, cfg, master)
1094
+
1095
+ def load(self, path, model, opt, cfg, master=True):
1096
+ """Load a specific checkpoint file (e.g. from --resume-from), rather
1097
+ than auto-discovering the latest one in self.dir.
1098
+ -> (start_step, loss, last_val)."""
1099
+ blob = torch.load(path, map_location="cpu", weights_only=True)
1100
+ model.load_state_dict(blob["model"])
1101
+ if not opt.load_state_dict(blob["opt"]):
1102
+ opt.resync_masters()
1103
+ run_cfg = blob.get("run_cfg")
1104
+ if master and run_cfg is not None:
1105
+ mismatches = [f"{k} checkpoint={v!r} current={getattr(cfg, k)!r}"
1106
+ for k, v in run_cfg.items() if getattr(cfg, k) != v]
1107
+ if mismatches:
1108
+ print("[WARN] resume config differs from the checkpoint's — "
1109
+ "the data offset this step count assumes will be wrong:")
1110
+ for m in mismatches:
1111
+ print(f" {m}")
1112
+ print(f"[resume] loaded {path}")
1113
+ return (int(blob["step"]), float(blob["loss"]),
1114
+ float(blob.get("last_val", float("nan"))))
1115
+
1116
+
1117
+ # =============================================================================
1118
+ # 6. Training.
1119
+ # =============================================================================
1120
+ def _env_int(name, default=0):
1121
+ v = os.environ.get(name)
1122
+ if v in (None, ""):
1123
+ return default
1124
+ try:
1125
+ return int(v)
1126
+ except ValueError:
1127
+ print(f"[WARN] ignoring non-integer {name}={v!r}")
1128
+ return default
1129
+
1130
+
1131
+ def seed_everything(seed):
1132
+ """Every RNG the run can draw from, off one seed.
1133
+ torch's CPU generator is the one that matters here (the model is built on
1134
+ CPU and moved), but `random` / numpy are seeded too so that anything added
1135
+ later — a shuffled shard order, a sampled probe — is reproducible by
1136
+ default rather than by accident.
1137
+ """
1138
+ random.seed(seed)
1139
+ np.random.seed(seed)
1140
+ torch.manual_seed(seed)
1141
+ torch.cuda.manual_seed_all(seed)
1142
+
1143
+
1144
+ def apply_determinism(mode):
1145
+ """Pin the run-to-run drift that seeding does not cover.
1146
+ Three sources, all on the backward pass:
1147
+ * nn.Embedding's dense backward scatters one atomicAdd per token into
1148
+ [vocab, d_model]; with weight tying that is also the lm_head gradient,
1149
+ so it is the largest reduction in the step;
1150
+ * the flash / mem-efficient attention backward splits dq over the key
1151
+ blocks and atomicAdds them together;
1152
+ * cuDNN picks kernels by wall-clock timing when `benchmark` is on, so the
1153
+ chosen algorithm can differ between runs of the same shape.
1154
+ Each is a float reduction in an order the scheduler chooses, so two runs
1155
+ diverge in the last mantissa bits of the first step and, through the
1156
+ optimizer, visibly by a few hundred steps.
1157
+ `strict` raises if some op has no deterministic kernel — better than
1158
+ reporting a reproducible run that is not one. `warn` downgrades that to a
1159
+ warning and keeps training; `off` restores the default fast kernels.
1160
+ """
1161
+ if mode == "off":
1162
+ return
1163
+ torch.backends.cudnn.benchmark = False
1164
+ torch.backends.cudnn.deterministic = True
1165
+ # Routes embedding-backward and SDPA-backward to their ordered variants, and
1166
+ # enforces the cuBLAS workspace setting made at the top of this file.
1167
+ torch.use_deterministic_algorithms(True, warn_only=(mode == "warn"))
1168
+
1169
+
1170
+ def build_argparser():
1171
+ ap = argparse.ArgumentParser(
1172
+ description="BLU single-GPU training — PyTorch port of bluscript_single.cpp")
1173
+ ap.add_argument("--data-root",
1174
+ default=("/root/.cache/huggingface/hub/datasets--jayasriii--flux_20b/"
1175
+ "/snapshots/ddc6cc7e43365a6b9096c30053df0fb001c94f4c"))
1176
+ ap.add_argument("--device", type=int, default=None,
1177
+ help="CUDA device index (env: BLU_DEVICE)")
1178
+ ap.add_argument("--precision", choices=["bf16-params", "bf16"], default="bf16-params",
1179
+ help="bf16-params (default): Linear weights stored bf16 with "
1180
+ "fp32 master weights in the optimizer — the C++ scheme. "
1181
+ "bf16: fp32 params + autocast (standard PyTorch AMP).")
1182
+ ap.add_argument("--rms-rope", choices=["fused", "eager"], default="fused",
1183
+ help="fused = Triton QK-norm+RoPE kernel (default), "
1184
+ "eager = unfused reference, for A/B on the kernel")
1185
+ ap.add_argument("--compile", action="store_true", help="torch.compile each block")
1186
+ ap.add_argument("--activation-checkpoint", action="store_true",
1187
+ help="recompute each block in backward (trades ~30%% time for memory)")
1188
+ ap.add_argument("--loss-chunks", type=int, default=1,
1189
+ help="chunk lm_head+CE into N pieces with recompute; 1 (default) "
1190
+ "materialises the full logits, as the C++ does")
1191
+ # bluscript_single.cpp defaults unless overridden.
1192
+ ap.add_argument("--B", type=int, default=None, help="micro-batch (env: BLU_B)")
1193
+ ap.add_argument("--T", type=int, default=None)
1194
+ ap.add_argument("--d-model", type=int, default=None, help="smoke-test override")
1195
+ ap.add_argument("--n-layers", type=int, default=None, help="smoke-test override")
1196
+ ap.add_argument("--q-heads", type=int, default=None, help="smoke-test override")
1197
+ ap.add_argument("--kv-heads", type=int, default=None, help="smoke-test override")
1198
+ ap.add_argument("--ffn-hidden", type=int, default=None, help="smoke-test override")
1199
+ ap.add_argument("--vocab-size", type=int, default=None, help="smoke-test override")
1200
+ ap.add_argument("--global-batch", type=int, default=None,
1201
+ help="tokens per optimizer step (env: BLU_GLOBAL_BATCH)")
1202
+ ap.add_argument("--max-steps", type=int, default=None,
1203
+ help="caps the run for benchmarking; warmup/stable shrink "
1204
+ "proportionally so the WSD decay tail stays non-empty "
1205
+ "(env: BLU_MAX_STEPS)")
1206
+ # ---- Muon ----
1207
+ ap.add_argument("--muon-lr", type=float, default=None,
1208
+ help="peak LR for the hidden 2D weights. Under the default "
1209
+ "--muon-adjust-lr match_rms_adamw this is the same unit as "
1210
+ "--max-lr, and defaults to the same value (2e-4) so "
1211
+ "both arms take a matched first run; sweep it upward "
1212
+ "from there (Muon usually takes 2-4x AdamW's LR).")
1213
+ ap.add_argument("--muon-min-lr", type=float, default=None,
1214
+ help="floor of the Muon cosine tail (default 10%% of --muon-lr)")
1215
+ ap.add_argument("--muon-momentum", type=float, default=None,
1216
+ help="torch.optim.Muon momentum (default 0.95, torch's own)")
1217
+ ap.add_argument("--muon-ns-steps", type=int, default=None,
1218
+ help="torch.optim.Muon ns_steps, Newton-Schulz iterations "
1219
+ "(default 5, torch's own); fewer = looser "
1220
+ "orthogonalization, cheaper")
1221
+ ap.add_argument("--muon-adjust-lr", choices=["match_rms_adamw", "original"],
1222
+ default=None,
1223
+ help="torch.optim.Muon adjust_lr_fn. match_rms_adamw "
1224
+ "(default HERE): 0.2*sqrt(max(A,B)), putting --muon-lr "
1225
+ "on the same scale as --max-lr. original (default in "
1226
+ "torch): sqrt(max(1,A/B)), needs a ~5.5x larger "
1227
+ "--muon-lr at d_model=768.")
1228
+ ap.add_argument("--val-freq", type=int, default=None)
1229
+ ap.add_argument("--val-loss-steps", type=int, default=None)
1230
+ ap.add_argument("--diag", action="store_true",
1231
+ help="per-micro-batch loss + depth probes (env: BLU_DIAG=1)")
1232
+ ap.add_argument("--warmup-measure", type=int, default=3,
1233
+ help="steps excluded from the steady-state throughput summary")
1234
+ ap.add_argument("--csv", default="blu_muon_log.csv",
1235
+ help="CSV log path; appended (not truncated) on resume. The "
1236
+ "first 8 columns match the AdamW arm's CSV exactly, so "
1237
+ "the two files plot against each other directly; "
1238
+ "muon_lr is appended as a 9th.")
1239
+ ap.add_argument("--seed", type=int, default=1234)
1240
+ ap.add_argument("--determinism", choices=["strict", "warn", "off"], default="strict",
1241
+ help="strict (default): deterministic CUDA kernels, so a rerun "
1242
+ "of the same launch line reproduces the loss curve bit for "
1243
+ "bit; raises if an op has no deterministic implementation. "
1244
+ "warn: same, but non-deterministic ops warn instead of "
1245
+ "raising. off: fastest kernels, results drift between runs.")
1246
+ # checkpointing
1247
+ ap.add_argument("--no-checkpointing", action="store_true")
1248
+ ap.add_argument("--ckpt-dir", default=None)
1249
+ ap.add_argument("--ckpt-prefix", default=None)
1250
+ ap.add_argument("--ckpt-freq", type=int, default=None)
1251
+ ap.add_argument("--ckpt-keep", type=int, default=None)
1252
+ ap.add_argument("--resume-from", default=None,
1253
+ help="path to a specific *_step*.pt checkpoint to resume "
1254
+ "from, overriding auto-discovery of the latest "
1255
+ "checkpoint in --ckpt-dir")
1256
+ return ap
1257
+
1258
+
1259
+ def config_from_args(args):
1260
+ cfg = ModelConfig()
1261
+ for f in ("B", "T", "d_model", "n_layers", "q_heads", "kv_heads", "ffn_hidden",
1262
+ "vocab_size", "global_batch", "val_freq", "val_loss_steps",
1263
+ "ckpt_dir", "ckpt_prefix", "ckpt_freq", "ckpt_keep",
1264
+ "muon_lr", "muon_min_lr", "muon_momentum", "muon_ns_steps",
1265
+ "muon_adjust_lr"):
1266
+ v = getattr(args, f, None)
1267
+ if v is not None:
1268
+ setattr(cfg, f, v)
1269
+ # A --muon-lr given without a floor keeps the 10% ratio the WSD tail assumes,
1270
+ # instead of silently decaying to the default 2e-5 from wherever it starts.
1271
+ if args.muon_lr is not None and args.muon_min_lr is None:
1272
+ cfg.muon_min_lr = 0.1 * cfg.muon_lr
1273
+ cfg.fused_rms_rope = (args.rms_rope == "fused")
1274
+ cfg.activation_checkpoint = args.activation_checkpoint
1275
+ cfg.loss_chunks = args.loss_chunks
1276
+ cfg.checkpointing = not args.no_checkpointing
1277
+ cfg.context_length = max(cfg.context_length, cfg.T)
1278
+
1279
+ # Mirrors the BLU_MAX_STEPS branch in bluscript_single.cpp: shrink warmup and
1280
+ # stable with the run, or a short benchmark leaves no decay tail (the C++
1281
+ # asserts on it; get_lr here would clamp, which is worse — it would silently
1282
+ # report a schedule the config does not describe).
1283
+ if args.max_steps is not None:
1284
+ ms = args.max_steps
1285
+ cfg.max_steps = ms
1286
+ cfg.warmup_steps = max(1, ms // 10)
1287
+ cfg.stable_steps = max(1, ms // 2)
1288
+ if cfg.warmup_steps + cfg.stable_steps >= cfg.max_steps - 1:
1289
+ cfg.stable_steps = max(1, cfg.max_steps - cfg.warmup_steps - 2)
1290
+ print(f"[bench] max_steps={ms} (warmup={cfg.warmup_steps} "
1291
+ f"stable={cfg.stable_steps})")
1292
+ return cfg
1293
+
1294
+
1295
+ def validate_config(cfg, world_size=1, master=True):
1296
+ """Cheap checks; each one is a silent-corruption or out-of-bounds failure
1297
+ mode if it does not hold."""
1298
+ bad = []
1299
+ if cfg.T > cfg.context_length:
1300
+ bad.append(f"T ({cfg.T}) > context_length ({cfg.context_length}): "
1301
+ "the RoPE cache is too short")
1302
+ if cfg.q_heads % cfg.kv_heads != 0:
1303
+ bad.append(f"q_heads ({cfg.q_heads}) not divisible by kv_heads ({cfg.kv_heads})")
1304
+ if cfg.head_dim not in (64, 128):
1305
+ bad.append(f"the fused kernels support head_dim 64 or 128, got {cfg.head_dim}")
1306
+ # Under DDP each rank runs B*T tokens per micro-step, so the world's tokens
1307
+ # per micro-step are B*T*world_size; global_batch must land on a whole
1308
+ # number of those or grad_accum below truncates and quietly under-shoots
1309
+ # the configured optimizer-step token count.
1310
+ if cfg.global_batch % (cfg.B * cfg.T * world_size) != 0:
1311
+ bad.append(f"global_batch ({cfg.global_batch}) not divisible by "
1312
+ f"B*T*world_size ({cfg.B * cfg.T * world_size})")
1313
+ if cfg.warmup_steps < 1:
1314
+ bad.append("warmup_steps must be >= 1 (get_lr divides by it)")
1315
+ if cfg.warmup_steps + cfg.stable_steps >= cfg.max_steps - 1:
1316
+ bad.append(f"warmup_steps + stable_steps "
1317
+ f"({cfg.warmup_steps + cfg.stable_steps}) leaves no decay tail "
1318
+ f"before max_steps ({cfg.max_steps})")
1319
+ if not hasattr(torch.optim, "Muon"):
1320
+ bad.append(f"torch {torch.__version__} has no torch.optim.Muon — it first "
1321
+ "appears in the 2.9 docs. Upgrade torch, or run the AdamW "
1322
+ "arm (train.py).")
1323
+ if cfg.muon_ns_steps < 1:
1324
+ bad.append("muon_ns_steps must be >= 1 (0 leaves the update unorthogonalized, "
1325
+ "which is not Muon)")
1326
+ if cfg.muon_momentum <= 0.0 or cfg.muon_momentum >= 1.0:
1327
+ bad.append(f"muon_momentum must be in (0,1), got {cfg.muon_momentum}")
1328
+ if cfg.q_heads * cfg.head_dim != cfg.d_model and master:
1329
+ print(f"WARNING: q_heads*head_dim ({cfg.q_heads * cfg.head_dim}) "
1330
+ f"!= d_model ({cfg.d_model})")
1331
+ if bad:
1332
+ raise SystemExit("ERROR: " + "\nERROR: ".join(bad))
1333
+
1334
+
1335
+ def main():
1336
+ args = build_argparser().parse_args()
1337
+
1338
+ # Env overrides, for parity with the C++ launch line. An explicit CLI flag
1339
+ # wins over the environment.
1340
+ if args.B is None:
1341
+ args.B = _env_int("BLU_B", 0) or None
1342
+ if args.global_batch is None:
1343
+ args.global_batch = _env_int("BLU_GLOBAL_BATCH", 0) or None
1344
+ if args.max_steps is None:
1345
+ args.max_steps = _env_int("BLU_MAX_STEPS", 0) or None
1346
+ diag = args.diag or _env_int("BLU_DIAG", 0) != 0
1347
+
1348
+ if not torch.cuda.is_available():
1349
+ raise SystemExit("ERROR: no CUDA device available")
1350
+
1351
+ # ---- DDP bootstrap ----
1352
+ # torchrun sets RANK/LOCAL_RANK/WORLD_SIZE; their absence means a plain
1353
+ # single-process launch, where --device / BLU_DEVICE pick the GPU instead.
1354
+ # torch.cuda.set_device MUST happen before init_process_group: NCCL creates
1355
+ # its context on whatever device is current at that call, so doing it after
1356
+ # would leave every rank on this node contending for device 0.
1357
+ ddp = int(os.environ.get("RANK", -1)) != -1
1358
+ if ddp:
1359
+ ddp_rank = int(os.environ["RANK"])
1360
+ ddp_local_rank = int(os.environ["LOCAL_RANK"])
1361
+ ddp_world_size = int(os.environ["WORLD_SIZE"])
1362
+ master_process = ddp_rank == 0
1363
+ if ddp_local_rank >= torch.cuda.device_count():
1364
+ raise SystemExit(f"ERROR: LOCAL_RANK={ddp_local_rank} but only "
1365
+ f"{torch.cuda.device_count()} CUDA device(s) visible")
1366
+ torch.cuda.set_device(ddp_local_rank)
1367
+ device = torch.device("cuda", ddp_local_rank)
1368
+ dist.init_process_group(backend="nccl")
1369
+ if master_process and (args.device is not None
1370
+ or os.environ.get("BLU_DEVICE") not in (None, "")):
1371
+ print("[WARN] --device / BLU_DEVICE is ignored under torchrun — "
1372
+ "LOCAL_RANK selects each rank's GPU.")
1373
+ else:
1374
+ ddp_rank, ddp_local_rank, ddp_world_size = 0, 0, 1
1375
+ master_process = True
1376
+ if args.device is None:
1377
+ args.device = _env_int("BLU_DEVICE", 0)
1378
+ if args.device >= torch.cuda.device_count():
1379
+ raise SystemExit(f"ERROR: BLU_DEVICE={args.device} but only "
1380
+ f"{torch.cuda.device_count()} CUDA device(s) visible")
1381
+ torch.cuda.set_device(args.device)
1382
+ device = torch.device("cuda", args.device)
1383
+
1384
+ seed_everything(args.seed)
1385
+ apply_determinism(args.determinism)
1386
+ # TF32 loses mantissa bits but is deterministic, so it is orthogonal to the
1387
+ # setting above and stays on.
1388
+ torch.set_float32_matmul_precision("high")
1389
+
1390
+ cfg = config_from_args(args)
1391
+ if cfg.fused_rms_rope and not _HAS_TRITON:
1392
+ if master_process:
1393
+ print("[WARN] Triton not available — falling back to the eager QK-norm+RoPE")
1394
+ cfg.fused_rms_rope = False
1395
+ validate_config(cfg, ddp_world_size, master_process)
1396
+
1397
+ # Tokens consumed per optimizer step = B * T * grad_accum * world_size.
1398
+ grad_accum = cfg.global_batch // (cfg.B * cfg.T * ddp_world_size)
1399
+ tokens_per_step = cfg.B * cfg.T * grad_accum * ddp_world_size
1400
+
1401
+ if master_process:
1402
+ print("================ Configuration ================")
1403
+ mode_str = (f"DDP x{ddp_world_size} (torchrun, NCCL)" if ddp
1404
+ else "SINGLE GPU (no torchrun / DDP / ZeRO)")
1405
+ print(f" mode : {mode_str}")
1406
+ print(f" cuda device : {ddp_local_rank if ddp else args.device} "
1407
+ f"({torch.cuda.get_device_name(device)})")
1408
+ print(f" d_model : {cfg.d_model}")
1409
+ print(f" n_layers : {cfg.n_layers}")
1410
+ print(f" q_heads/kv_heads: {cfg.q_heads} / {cfg.kv_heads} "
1411
+ f"(G={cfg.q_heads // cfg.kv_heads})")
1412
+ print(f" head_dim : {cfg.head_dim}")
1413
+ print(f" ffn_hidden : {cfg.ffn_hidden} (SwiGLU)")
1414
+ print(f" context_length : {cfg.context_length}")
1415
+ print(f" rope_theta : {cfg.rope_theta:g} (NeoX half-split)")
1416
+ print(f" vocab_size : {cfg.vocab_size}")
1417
+ print(f" weight_tying : {'ON' if cfg.weight_tying else 'OFF'}")
1418
+ print(f" B x T : {cfg.B} x {cfg.T}")
1419
+ print(f" global_batch : {cfg.global_batch} (grad_accum={grad_accum}, "
1420
+ f"world_size={ddp_world_size})")
1421
+ print(" optimizer : MUON (hidden 2D) + AdamW (embed/head/1D)")
1422
+ print(f" max_lr / min_lr : {cfg.max_lr:g} / {cfg.min_lr:g} (AdamW group)")
1423
+ print(f" muon lr / min : {cfg.muon_lr:g} / {cfg.muon_min_lr:g} "
1424
+ f"(adjust_lr_fn={cfg.muon_adjust_lr})")
1425
+ print(f" muon momentum : {cfg.muon_momentum:g} | NS steps {cfg.muon_ns_steps}")
1426
+ print(f" warmup / steps : {cfg.warmup_steps} / {cfg.max_steps}")
1427
+ print(f" WSD stable_steps: {cfg.stable_steps} "
1428
+ f"(decay tail={cfg.max_steps - cfg.warmup_steps - cfg.stable_steps})")
1429
+ print(f" precision : {args.precision}")
1430
+ print(f" seed / determ. : {args.seed} / {args.determinism}")
1431
+ print(f" rms+rope : {'fused' if cfg.fused_rms_rope else 'eager'}"
1432
+ f" | compile {args.compile} | act-ckpt {cfg.activation_checkpoint}"
1433
+ f" | loss_chunks {cfg.loss_chunks}")
1434
+ print("===============================================", flush=True)
1435
+
1436
+ # ---- model ----
1437
+ # Built and seeded identically on every rank (same seed, deterministic CPU
1438
+ # init); DDP's constructor broadcasts rank 0's parameters/buffers anyway,
1439
+ # so this is belt-and-suspenders against any future source of divergence.
1440
+ if master_process:
1441
+ print(f"Initializing model on CUDA device {device.index}...", flush=True)
1442
+ raw_model = BLU(cfg).to(device)
1443
+ raw_model.apply_param_dtype(args.precision)
1444
+ params = list(raw_model.parameters())
1445
+ n_params = sum(p.numel() for p in params)
1446
+ if master_process:
1447
+ print(f"Number of parameters: {n_params}")
1448
+ if args.compile:
1449
+ for blk in raw_model.blocks:
1450
+ blk.compile()
1451
+
1452
+ # DDP wraps the (already dtype-cast, already compiled) raw module. Buffer
1453
+ # broadcasting is off: rope_cos/rope_sin are deterministic functions of
1454
+ # cfg, identical on every rank already, so syncing them every forward
1455
+ # would just be wasted communication.
1456
+ # if ddp:
1457
+ # model = DDP(raw_model, device_ids=[ddp_local_rank], broadcast_buffers=False)
1458
+ # else:
1459
+ # model = raw_model
1460
+
1461
+ if ddp:
1462
+ model = DDP(raw_model, device_ids=[ddp_local_rank], broadcast_buffers=False)
1463
+ torch.cuda.synchronize() # let DDP's constructor-time NCCL broadcast fully land
1464
+ # before DataLoaderLite's independent copy_stream starts
1465
+ # issuing its own async H2D work — see [crash investigation]
1466
+ else:
1467
+ model = raw_model
1468
+
1469
+
1470
+ # ---- optimizer ----
1471
+ # named_parameters(), not parameters(): the routing is by name (the
1472
+ # embedding and lm_head stay on AdamW). Duplicates are dropped by default,
1473
+ # so a weight-tied head is visited once, as `wte.weight`. Built from
1474
+ # raw_model so names never carry DDP's "module." prefix.
1475
+ opt = MasterMuon(raw_model.named_parameters(), cfg)
1476
+ if master_process:
1477
+ print(f"muon params: {opt.n_muon} | adamw decayed: {opt.n_decay}, "
1478
+ f"non-decayed: {opt.n_nodecay}")
1479
+ # Static footprint. Nothing here is sharded — plain DDP replicates the
1480
+ # full optimizer state on every rank (the whole cost of not running
1481
+ # ZeRO-1), so this is the per-GPU charge before a single activation is
1482
+ # allocated.
1483
+ gb = 2 ** 30
1484
+ param_bytes = sum(p.numel() * p.element_size() for p in params)
1485
+ grad_bytes = param_bytes # grads share the param dtype
1486
+ master_bytes, landing_bytes, _, _ = opt.state_breakdown()
1487
+ # Both optimizers allocate their state on the first step(), so at this point
1488
+ # the measured values are 0 and the report has to predict them.
1489
+ mv_bytes = opt.expected_mv_bytes()
1490
+ mom_bytes = opt.expected_muon_mom_bytes()
1491
+ static_bytes = (param_bytes + grad_bytes + master_bytes + landing_bytes
1492
+ + mv_bytes + mom_bytes)
1493
+ if master_process:
1494
+ print(f"[{'ddp' if ddp else 'single'}] static footprint (per GPU: "
1495
+ f"params + grads + optimizer state)")
1496
+ print(f" parameters : {param_bytes / gb:7.2f} GiB")
1497
+ print(f" gradients : {grad_bytes / gb:7.2f} GiB")
1498
+ print(f" fp32 master weights : {master_bytes / gb:7.2f} GiB")
1499
+ print(f" fp32 grad landing bufs : {landing_bytes / gb:7.2f} GiB")
1500
+ print(f" Muon momentum : {mom_bytes / gb:7.2f} GiB")
1501
+ print(f" Adam exp_avg + exp_avg_sq: {mv_bytes / gb:6.2f} GiB")
1502
+ print(f" static total : {static_bytes / gb:7.2f} GiB", flush=True)
1503
+
1504
+ # ---- data ----
1505
+ # Sharded by rank: each rank reads a disjoint, interleaved slice of the
1506
+ # same shard list (see DataLoaderLite), so DDP's cross-rank gradient
1507
+ # average is over world_size DIFFERENT windows, not world_size copies of
1508
+ # the same one.
1509
+ train_loader = DataLoaderLite(cfg.B, cfg.T, "train", args.data_root, device,
1510
+ master=master_process, rank=ddp_rank,
1511
+ world_size=ddp_world_size)
1512
+ # rank=0, world_size=1 UNCONDITIONALLY, on every rank: val_loss_steps
1513
+ # windows at fixed token offsets 0, BT, 2BT, ... Sharding this by
1514
+ # ddp_rank/ddp_world_size like the train loader would make the reported
1515
+ # val_loss a function of how many GPUs happen to be running (world_size=2
1516
+ # averages 2x as many, differently-offset windows as world_size=1) —
1517
+ # the two numbers would not be comparable across a GPU-count change, which
1518
+ # is what produced the apparent val_loss jump on the 2-GPU -> 1-GPU
1519
+ # resume. Every rank now redundantly evaluates the identical fixed
1520
+ # windows, so the metric means the same thing regardless of world_size.
1521
+ val_loader = DataLoaderLite(cfg.B, cfg.T, "val", args.data_root, device,
1522
+ master=master_process, rank=0, world_size=1)
1523
+
1524
+ # ---- checkpointing: manager + auto-resume ----
1525
+ # Every rank independently loads the same checkpoint file from the same
1526
+ # (assumed shared) filesystem — a read, so no race — which keeps model,
1527
+ # optimizer state, and start_step identical across ranks without an
1528
+ # explicit broadcast. Only rank 0 ever WRITES one (below).
1529
+ start_step, ckpt = 0, None
1530
+ last_val = float("nan")
1531
+ if cfg.checkpointing or args.resume_from:
1532
+ ckpt = CheckpointManager(cfg.ckpt_dir, cfg.ckpt_prefix, cfg.ckpt_keep)
1533
+ if args.resume_from:
1534
+ if master_process:
1535
+ print(f"[resume] loading explicit checkpoint: {args.resume_from}")
1536
+ start_step, resume_loss, last_val = ckpt.load(
1537
+ args.resume_from, raw_model, opt, cfg, master_process)
1538
+ else:
1539
+ start_step, resume_loss, last_val = ckpt.load_latest(
1540
+ raw_model, opt, cfg, master_process)
1541
+ if start_step > 0:
1542
+ if master_process:
1543
+ print(f"[resume] at step {start_step} (loss {resume_loss:.6f}, "
1544
+ f"last val {last_val:.6f})")
1545
+ # Skip the batches already consumed by steps [0, start_step).
1546
+ # global_batch // (B*T*world_size) makes tokens-per-step (and so
1547
+ # this target offset) independent of world_size, so a GPU-count
1548
+ # change alone lands on the correct byte offset as long as B, T,
1549
+ # and global_batch are unchanged (checked above).
1550
+ train_loader.skip_batches(start_step * grad_accum)
1551
+
1552
+ # ---- CSV log ----
1553
+ # Appended (not truncated) when resuming so a restart does not erase the
1554
+ # history of the run it is continuing. Rank 0 only — every rank would
1555
+ # otherwise open and write the same path.
1556
+ log_file = None
1557
+ if args.csv and master_process:
1558
+ resuming = start_step > 0 and os.path.exists(args.csv)
1559
+ log_file = open(args.csv, "a" if resuming else "w")
1560
+ if not resuming:
1561
+ log_file.write("step,train_loss,val_loss,tok_per_sec,grad_norm,dt_ms,lr,"
1562
+ "elapsed_min,muon_lr\n")
1563
+ log_file.flush()
1564
+
1565
+ amp = torch.autocast(device_type="cuda", dtype=torch.bfloat16)
1566
+ probes = [L for L in cfg.probe_layers if L < cfg.n_layers]
1567
+ steady_dts = []
1568
+ t_train_start = time.perf_counter()
1569
+
1570
+ # ---- Ctrl-C: finish the in-flight step, save a checkpoint, exit clean ----
1571
+ # Registered here (not earlier) so a Ctrl-C during setup/data-loading still
1572
+ # gets Python's default immediate-abort behaviour — only the training loop
1573
+ # below gets the graceful path. A second Ctrl-C re-arms the default handler
1574
+ # and re-raises, for when the checkpoint save itself needs interrupting.
1575
+ interrupted = False
1576
+
1577
+ def _handle_sigint(signum, frame):
1578
+ nonlocal interrupted
1579
+ if interrupted:
1580
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
1581
+ raise KeyboardInterrupt
1582
+ interrupted = True
1583
+ if master_process:
1584
+ print("\n[ctrl-c] finishing this step, then checkpointing and exiting "
1585
+ "(press again to abort immediately)...", flush=True)
1586
+
1587
+ # A terminal Ctrl-C is delivered to every process in the foreground
1588
+ # process group, so under torchrun every rank sets `interrupted` at
1589
+ # roughly the same time and the ranks stay in lockstep for the collective
1590
+ # ops (DDP's grad all-reduce, the checkpoint barrier below) still ahead.
1591
+ signal.signal(signal.SIGINT, _handle_sigint)
1592
+
1593
+ if master_process:
1594
+ print("\nStarting training" +
1595
+ (f" (resumed at step {start_step})" if start_step else "") + "...\n", flush=True)
1596
+
1597
+ for step in range(start_step, cfg.max_steps):
1598
+ # ---------- periodic validation ----------
1599
+ if cfg.val_loss_steps > 0 and (step % cfg.val_freq == 0 or step == cfg.max_steps - 1):
1600
+ model.eval()
1601
+ val_loader.reset()
1602
+ acc = 0.0
1603
+ with torch.no_grad(), amp:
1604
+ for _ in range(cfg.val_loss_steps):
1605
+ x, y, _, _ = val_loader.next_batch()
1606
+ acc += model(x, y)[1].item() / cfg.val_loss_steps
1607
+ model.train()
1608
+ # val_loader is rank=0/world_size=1 on every rank (see its
1609
+ # construction above), so every rank just computed the identical
1610
+ # fixed windows redundantly — no cross-rank reduction needed, and
1611
+ # val_loss no longer depends on how many ranks are running.
1612
+ last_val = acc
1613
+ if master_process:
1614
+ print(f" [val] step {step} | val_loss {last_val:.6f}", flush=True)
1615
+
1616
+ # ---------- training step ----------
1617
+ t0 = time.perf_counter()
1618
+ model.zero_grad(set_to_none=True)
1619
+ # Fresh zeros rather than an in-place scale of last step's accumulator:
1620
+ # multiplying by zero does NOT clear a NaN, so a single non-finite
1621
+ # micro-batch would poison the accumulator for the rest of the run.
1622
+ loss_accum = torch.zeros((), device=device)
1623
+ micro_loss, micro_where = [], []
1624
+
1625
+ for micro in range(grad_accum):
1626
+ x, y, shard, offset = train_loader.next_batch()
1627
+ # DDP allreduces gradients on every .backward(); for grad_accum > 1
1628
+ # only the LAST micro-batch of the step should pay for that — the
1629
+ # others accumulate purely locally under no_sync().
1630
+ sync_ctx = (nullcontext() if (not ddp or micro == grad_accum - 1)
1631
+ else model.no_sync())
1632
+ with sync_ctx:
1633
+ with amp:
1634
+ _, loss = model(x, y)
1635
+ loss_accum += loss.detach()
1636
+ # Per-micro-batch loss (--diag). The reported train loss is the mean
1637
+ # over grad_accum micro-steps, so a single pathological micro-batch
1638
+ # is diluted while its gradient dominates the accumulated norm
1639
+ # almost undiluted — which is how a modest loss bump can sit next to
1640
+ # a large norm spike. `micro_where` names the shard and token offset
1641
+ # so the responsible bytes can be decoded offline.
1642
+ #
1643
+ # Costs a device sync per micro-step, so it is off by default.
1644
+ if diag:
1645
+ micro_loss.append(loss.item())
1646
+ micro_where.append((shard, offset))
1647
+ (loss / grad_accum).backward()
1648
+
1649
+ if ddp:
1650
+ # Average each rank's accumulated (summed) loss BEFORE dividing by
1651
+ # grad_accum, so loss_val is the mean over world_size*grad_accum
1652
+ # micro-batches — the true loss behind this optimizer step, not
1653
+ # just rank 0's slice. Also doubles as a sync point: a NaN on any
1654
+ # rank poisons the average for every rank, so the check below
1655
+ # raises everywhere instead of only where it originated (which
1656
+ # would otherwise hang the survivors on the next collective).
1657
+ dist.all_reduce(loss_accum, op=dist.ReduceOp.AVG)
1658
+ loss_val = loss_accum.item() / grad_accum
1659
+ if math.isnan(loss_val) or math.isinf(loss_val):
1660
+ if log_file:
1661
+ log_file.close()
1662
+ # Every rank reaches this identically (the all_reduce above is a
1663
+ # sync point and NaN propagates through AVG), so every rank exits
1664
+ # here together rather than the survivors hanging on the next
1665
+ # collective.
1666
+ if ddp:
1667
+ dist.destroy_process_group()
1668
+ raise SystemExit(f"ERROR: NaN/Inf loss at step {step}")
1669
+
1670
+ # Depth probe (--diag), read BEFORE the update, so these are the
1671
+ # pre-update gradients. Compare the profile on a spiking step against a
1672
+ # quiet one: a blow-up that begins mid-stack and grows toward the loss
1673
+ # points at the forward, while a flat multiplicative lift across all
1674
+ # depths points at the optimizer/update.
1675
+ depth = []
1676
+ if diag:
1677
+ for L in probes:
1678
+ a = raw_model.blocks[L].attn
1679
+ gn = a.wQ.weight.grad
1680
+ depth.append((L,
1681
+ gn.float().norm().item() if gn is not None else -1.0,
1682
+ a.q_gamma.abs().max().item(),
1683
+ a.wQ.weight.abs().max().float().item()))
1684
+
1685
+ grad_norm = clip_grads_(params, cfg.grad_clip).item()
1686
+ lr = get_lr(step, cfg) # AdamW group
1687
+ muon_lr = get_lr(step, cfg, cfg.muon_lr, cfg.muon_min_lr)
1688
+ opt.step(lr, muon_lr)
1689
+
1690
+ torch.cuda.synchronize() # make the per-step timing reflect completed GPU work
1691
+ dt = time.perf_counter() - t0
1692
+ tok_per_sec = tokens_per_step / dt
1693
+ elapsed_min = (time.perf_counter() - t_train_start) / 60.0
1694
+ if step - start_step >= args.warmup_measure:
1695
+ steady_dts.append(dt)
1696
+
1697
+ # ---------- per-step report (rank 0 only — every rank's numbers agree
1698
+ # on loss/grad_norm post-allreduce, so printing from every rank would
1699
+ # only duplicate lines, not add information) ----------
1700
+ if master_process:
1701
+ vs = " - " if last_val != last_val else f"{last_val:.6f}"
1702
+ print(f"step {step:6d} | train {loss_val:.6f} | val {vs} "
1703
+ f"| tok/s {tok_per_sec:10.2f} | norm {grad_norm:.4f} "
1704
+ f"| dt {dt * 1e3:8.2f} ms | lr {lr:.4e} | mlr {muon_lr:.4e} "
1705
+ f"| mem {torch.cuda.max_memory_allocated() / gb:5.2f}/"
1706
+ f"{torch.cuda.max_memory_reserved() / gb:5.2f} GiB", flush=True)
1707
+
1708
+ if diag and micro_loss:
1709
+ # Flag micro-batches that stand out against this step's own median.
1710
+ med = sorted(micro_loss)[len(micro_loss) // 2]
1711
+ marks = " ".join(("*" if m > med + 0.5 else "") + f"{m:.3f}"
1712
+ for m in micro_loss)
1713
+ print(f" [micro] med {med:.4f} | {marks}")
1714
+ for m, (ml, (shard, offset)) in enumerate(zip(micro_loss, micro_where)):
1715
+ if ml > med + 0.5:
1716
+ print(f" [micro] OUTLIER m={m} loss {ml:.4f} (median {med:.4f}) "
1717
+ f"from shard {shard} token offset {offset}")
1718
+ if diag and depth:
1719
+ print(" [depth] ||g(wQ)|| by layer:"
1720
+ + "".join(f" L{L} {g:.3e}" for L, g, _, _ in depth)
1721
+ + " | max|q_gamma|:"
1722
+ + "".join(f" L{L} {gm:.4f}" for L, _, gm, _ in depth)
1723
+ + " | max|wQ|:"
1724
+ + "".join(f" L{L} {w:.4f}" for L, _, _, w in depth), flush=True)
1725
+
1726
+ if log_file:
1727
+ log_file.write(f"{step},{loss_val:.6f},{last_val:.6f},{tok_per_sec:.6f},"
1728
+ f"{grad_norm:.6f},{dt * 1e3:.6f},{lr:.6f},{elapsed_min:.6f},"
1729
+ f"{muon_lr:.6f}\n")
1730
+ log_file.flush()
1731
+
1732
+ if ddp:
1733
+ # `interrupted` is set by this process's own SIGINT handler, so in
1734
+ # principle one rank could see it before another (a signal isn't
1735
+ # guaranteed simultaneous delivery, even though in practice a
1736
+ # terminal Ctrl-C hits every rank in the same process group at
1737
+ # once). Left asymmetric, it would desync the checkpoint barrier
1738
+ # and the `break` below against ranks still issuing DDP's regular
1739
+ # per-step collectives — a hang, not just a wrong answer. This
1740
+ # runs unconditionally every step (never gated on a per-rank
1741
+ # value), so it can never itself mismatch across ranks.
1742
+ flag = torch.tensor(1.0 if interrupted else 0.0, device=device)
1743
+ dist.all_reduce(flag, op=dist.ReduceOp.MAX)
1744
+ interrupted = flag.item() > 0
1745
+
1746
+ # ---------- periodic checkpoint (also fires once on Ctrl-C) ----------
1747
+ # Labeled step+1 (the next iteration to run) so load_latest resumes
1748
+ # exactly where this save left off — no duplicated or skipped iteration.
1749
+ # Captures weights + Adam m/v AFTER this step's update. Rank 0 only —
1750
+ # every rank's raw_model/opt state is identical post-allreduce, so a
1751
+ # second writer would only race the first on the same path. The
1752
+ # barrier holds every rank at this point until the save (or its
1753
+ # failure) is done, so a slow write can't let other ranks race ahead
1754
+ # into the next step's collectives before the checkpoint is durable.
1755
+ if cfg.checkpointing and ((step + 1) % cfg.ckpt_freq == 0
1756
+ or step == cfg.max_steps - 1
1757
+ or interrupted):
1758
+ if master_process:
1759
+ try:
1760
+ ckpt.save(step + 1, raw_model, opt, loss_val, last_val, cfg)
1761
+ except Exception as e: # noqa: BLE001 — advisory
1762
+ print(f"[WARN] checkpoint save at step {step + 1} failed: {e}")
1763
+ if ddp:
1764
+ dist.barrier()
1765
+
1766
+ if interrupted:
1767
+ if not cfg.checkpointing and master_process:
1768
+ print(f"[ctrl-c] checkpointing is disabled (--no-checkpointing); "
1769
+ f"stopping at step {step} without saving.", flush=True)
1770
+ break
1771
+
1772
+ # Reclaim the extra allocator high-water mark from the first couple of
1773
+ # steps' one-time warmup allocations (autograd graph caches, etc.).
1774
+ if step in (start_step, start_step + 1):
1775
+ torch.cuda.synchronize()
1776
+ torch.cuda.empty_cache()
1777
+ torch.cuda.reset_peak_memory_stats()
1778
+
1779
+ torch.cuda.synchronize()
1780
+ if log_file:
1781
+ log_file.close()
1782
+
1783
+ # ---- steady-state summary ----
1784
+ # dt/throughput are this rank's own timing; under DDP all ranks run in
1785
+ # lockstep (grad sync + the checkpoint barrier), so rank 0's numbers are
1786
+ # representative and `tokens_per_step` already counts every rank's tokens.
1787
+ if steady_dts and master_process:
1788
+ xs = sorted(steady_dts)
1789
+ med = xs[len(xs) // 2]
1790
+ mean = sum(xs) / len(xs)
1791
+ alloc = torch.cuda.max_memory_allocated() / gb
1792
+ reserved = torch.cuda.max_memory_reserved() / gb
1793
+ # Measured now that Adam's m/v exist, rather than the startup estimate.
1794
+ static = (param_bytes + grad_bytes + opt.state_bytes()) / gb
1795
+ mode_str = f"DDP x{ddp_world_size}" if ddp else "single GPU"
1796
+ print("\n" + "=" * 78)
1797
+ print(f" STEADY-STATE SUMMARY — {mode_str} optimizer=muon+adamw "
1798
+ f"precision={args.precision} "
1799
+ f"rms+rope={'fused' if cfg.fused_rms_rope else 'eager'}")
1800
+ print(f" torch.optim.Muon lr={cfg.muon_lr:g} "
1801
+ f"adjust_lr_fn={cfg.muon_adjust_lr} "
1802
+ f"momentum={cfg.muon_momentum:g} ns_steps={cfg.muon_ns_steps}")
1803
+ print(f" ({len(xs)} steps, first {args.warmup_measure} excluded)")
1804
+ print("=" * 78)
1805
+ print(f" step time : {med * 1e3:10.2f} ms (mean {mean * 1e3:.2f})")
1806
+ print(f" throughput : {tokens_per_step / med:10.1f} tok/s")
1807
+ print(f" tokens / step : {tokens_per_step:10d}")
1808
+ print(f" static (p+g+opt) : {static:10.2f} GiB (per GPU)")
1809
+ print(f" activations (peak) : {max(alloc - static, 0.0):10.2f} GiB")
1810
+ print(f" peak mem allocated : {alloc:10.2f} GiB")
1811
+ print(f" peak mem reserved : {reserved:10.2f} GiB")
1812
+ print("=" * 78)
1813
+
1814
+ if ddp:
1815
+ dist.destroy_process_group()
1816
+ if master_process:
1817
+ print("\n=== Training complete ===")
1818
+
1819
+
1820
+ if __name__ == "__main__":
1821
+ main()
1822
+
1823
+
1824
+
1825
+
1826
+
1827
+
1828
+
1829
+
1830
+
1831
+
1832
+
1833
+
1834
+
1835
+
1836
+
1837
+
1838
+
1839
+
1840
+
1841
+
1842
+
1843
+
1844
+
1845
+
1846
+
1847
+