m1b commited on
Commit
0ec7495
·
verified ·
1 Parent(s): a3af850

Upload reference/baseline_train_gpt.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. reference/baseline_train_gpt.py +1126 -0
reference/baseline_train_gpt.py ADDED
@@ -0,0 +1,1126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The `train_gpt.py` and `train_gpt_mlx.py` scripts are intended as good launching-off points for new participants, not SOTA configs. We'll accept PRs that tune, improve, or simplify these scripts without significantly increasing complexity, but competitive submissions should stay in the `/records` folder.
3
+
4
+ Hard stop: To keep readable for newcomers, let's make sure `train_gpt.py` and `train_gpt_mlx.py` never are longer than 1500 lines.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import glob
11
+ import io
12
+ import math
13
+ import os
14
+ import random
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ import uuid
19
+ import zlib
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+ import sentencepiece as spm
24
+ import torch
25
+ import torch.distributed as dist
26
+ import torch.nn.functional as F
27
+ from torch import Tensor, nn
28
+ from torch.nn.parallel import DistributedDataParallel as DDP
29
+
30
+ # -----------------------------
31
+ # HYPERPARAMETERS
32
+ # -----------------------------
33
+ # Default Simple Baseline run:
34
+ # - 9 transformer blocks at width 512
35
+ # - 8 attention heads with 4 KV heads (GQA) and 2x MLP expansion
36
+ # - vocab size 1024, sequence length 1024, tied embeddings
37
+ # - 524,288 train tokens per step for 20,000 iterations with a ~10 minute cap
38
+
39
+ class Hyperparameters:
40
+ # Data paths are shard globs produced by the existing preprocessing pipeline.
41
+ data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024")
42
+ train_files = os.path.join(data_path, "fineweb_train_*.bin")
43
+ val_files = os.path.join(data_path, "fineweb_val_*.bin")
44
+ tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model")
45
+ run_id = os.environ.get("RUN_ID", str(uuid.uuid4()))
46
+ seed = int(os.environ.get("SEED", 1337))
47
+
48
+ # Validation cadence and batch size. Validation always uses the full fineweb_val split.
49
+ val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288))
50
+ val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000))
51
+ train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200))
52
+
53
+ # Training length.
54
+ iterations = int(os.environ.get("ITERATIONS", 20000))
55
+ warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 1200))
56
+ warmup_steps = int(os.environ.get("WARMUP_STEPS", 20))
57
+ train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 524_288))
58
+ train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 1024))
59
+ max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0))
60
+ qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5))
61
+
62
+ # Model shape.
63
+ vocab_size = int(os.environ.get("VOCAB_SIZE", 1024))
64
+ num_layers = int(os.environ.get("NUM_LAYERS", 9))
65
+ num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 4))
66
+ model_dim = int(os.environ.get("MODEL_DIM", 512))
67
+ num_heads = int(os.environ.get("NUM_HEADS", 8))
68
+ mlp_mult = int(os.environ.get("MLP_MULT", 2))
69
+ tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1")))
70
+ rope_base = float(os.environ.get("ROPE_BASE", 10000.0))
71
+ logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0))
72
+
73
+ # Optimizer hyperparameters.
74
+ embed_lr = float(os.environ.get("EMBED_LR", 0.6))
75
+ head_lr = float(os.environ.get("HEAD_LR", 0.008))
76
+ tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.05))
77
+ tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005))
78
+ matrix_lr = float(os.environ.get("MATRIX_LR", 0.04))
79
+ scalar_lr = float(os.environ.get("SCALAR_LR", 0.04))
80
+ muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.95))
81
+ muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5))
82
+ muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.85))
83
+ muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 500))
84
+ beta1 = float(os.environ.get("BETA1", 0.9))
85
+ beta2 = float(os.environ.get("BETA2", 0.95))
86
+ adam_eps = float(os.environ.get("ADAM_EPS", 1e-8))
87
+ grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.0))
88
+
89
+ # -----------------------------
90
+ # MUON OPTIMIZER
91
+ # -----------------------------
92
+ #
93
+ # As borrowed from modded-nanogpt
94
+ # Background on Muon: https://kellerjordan.github.io/posts/muon/
95
+
96
+ def zeropower_via_newtonschulz5(G: Tensor, steps: int = 10, eps: float = 1e-7) -> Tensor:
97
+ # Orthogonalize a 2D update matrix with a fast Newton-Schulz iteration.
98
+ # Muon uses this to normalize matrix-shaped gradients before applying them.
99
+ a, b, c = (3.4445, -4.7750, 2.0315)
100
+ X = G.bfloat16()
101
+ X /= X.norm() + eps
102
+ transposed = G.size(0) > G.size(1)
103
+ if transposed:
104
+ X = X.T
105
+ for _ in range(steps):
106
+ A = X @ X.T
107
+ B = b * A + c * A @ A
108
+ X = a * X + B @ X
109
+ return X.T if transposed else X
110
+
111
+
112
+ class Muon(torch.optim.Optimizer):
113
+ def __init__(self, params, lr: float, momentum: float, backend_steps: int, nesterov: bool = True):
114
+ super().__init__(
115
+ params,
116
+ dict(lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov),
117
+ )
118
+
119
+ @torch.no_grad()
120
+ def step(self, closure=None):
121
+ loss = None
122
+ if closure is not None:
123
+ with torch.enable_grad():
124
+ loss = closure()
125
+
126
+ distributed = dist.is_available() and dist.is_initialized()
127
+ world_size = dist.get_world_size() if distributed else 1
128
+ rank = dist.get_rank() if distributed else 0
129
+
130
+ for group in self.param_groups:
131
+ params = group["params"]
132
+ if not params:
133
+ continue
134
+ lr = group["lr"]
135
+ momentum = group["momentum"]
136
+ backend_steps = group["backend_steps"]
137
+ nesterov = group["nesterov"]
138
+
139
+ total_params = sum(int(p.numel()) for p in params)
140
+ updates_flat = torch.zeros(total_params, device=params[0].device, dtype=torch.bfloat16)
141
+
142
+ curr = 0
143
+ for i, p in enumerate(params):
144
+ if i % world_size == rank and p.grad is not None:
145
+ g = p.grad
146
+ state = self.state[p]
147
+ if "momentum_buffer" not in state:
148
+ state["momentum_buffer"] = torch.zeros_like(g)
149
+ buf = state["momentum_buffer"]
150
+ buf.mul_(momentum).add_(g)
151
+ if nesterov:
152
+ g = g.add(buf, alpha=momentum)
153
+ g = zeropower_via_newtonschulz5(g, steps=backend_steps)
154
+ # Scale correction from Muon reference implementations.
155
+ g *= max(1, g.size(0) / g.size(1)) ** 0.5
156
+ updates_flat[curr : curr + p.numel()] = g.reshape(-1)
157
+ curr += p.numel()
158
+
159
+ if distributed:
160
+ dist.all_reduce(updates_flat, op=dist.ReduceOp.SUM)
161
+
162
+ curr = 0
163
+ for p in params:
164
+ g = updates_flat[curr : curr + p.numel()].view_as(p).to(dtype=p.dtype)
165
+ p.add_(g, alpha=-lr)
166
+ curr += p.numel()
167
+
168
+ return loss
169
+
170
+
171
+ # -----------------------------
172
+ # TOKENIZER-AGNOSTIC EVALUATION SETUP
173
+ # -----------------------------
174
+ #
175
+ # It's common for small models have a large fraction of their parameters be embeddings, since the 2 * d_model * d_vocab vectors can be gigantic.
176
+ # Instead of locking the tokenizer, we let you bring your own and calculate our validation metrics on the average compression of the validation set.
177
+ # We calculate BPB (bits-per-byte) instead of validation loss, so we need methods to count the number of bits per token in the tokenizer.
178
+ # Note: Submissions that edit the tokenizer will be examined more carefully, since screwing this up might unjustly improve your score.
179
+
180
+ def build_sentencepiece_luts(
181
+ sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device
182
+ ) -> tuple[Tensor, Tensor, Tensor]:
183
+ sp_vocab_size = int(sp.vocab_size())
184
+ table_size = max(sp_vocab_size, vocab_size)
185
+ base_bytes_np = np.zeros((table_size,), dtype=np.int16)
186
+ has_leading_space_np = np.zeros((table_size,), dtype=np.bool_)
187
+ is_boundary_token_np = np.ones((table_size,), dtype=np.bool_)
188
+ for token_id in range(sp_vocab_size):
189
+ if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id):
190
+ continue
191
+ is_boundary_token_np[token_id] = False
192
+ if sp.is_byte(token_id):
193
+ base_bytes_np[token_id] = 1
194
+ continue
195
+ piece = sp.id_to_piece(token_id)
196
+ if piece.startswith("▁"):
197
+ has_leading_space_np[token_id] = True
198
+ piece = piece[1:]
199
+ base_bytes_np[token_id] = len(piece.encode("utf-8"))
200
+ return (
201
+ torch.tensor(base_bytes_np, dtype=torch.int16, device=device),
202
+ torch.tensor(has_leading_space_np, dtype=torch.bool, device=device),
203
+ torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device),
204
+ )
205
+
206
+
207
+ def load_validation_tokens(pattern: str, seq_len: int) -> Tensor:
208
+ files = [Path(p) for p in sorted(glob.glob(pattern))]
209
+ if not files:
210
+ raise FileNotFoundError(f"No files found for pattern: {pattern}")
211
+ # The export pipeline writes the fixed first-50k-doc validation set to fineweb_val_*.
212
+ tokens = torch.cat([load_data_shard(file) for file in files]).contiguous()
213
+ usable = ((tokens.numel() - 1) // seq_len) * seq_len
214
+ if usable <= 0:
215
+ raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}")
216
+ return tokens[: usable + 1]
217
+
218
+
219
+ def eval_val(
220
+ args: Hyperparameters,
221
+ model: nn.Module,
222
+ rank: int,
223
+ world_size: int,
224
+ device: torch.device,
225
+ grad_accum_steps: int,
226
+ val_tokens: Tensor,
227
+ base_bytes_lut: Tensor,
228
+ has_leading_space_lut: Tensor,
229
+ is_boundary_token_lut: Tensor,
230
+ ) -> tuple[float, float]:
231
+ # Validation computes two metrics:
232
+ # - val_loss: token cross-entropy (natural log)
233
+ # - val_bpb: tokenizer-agnostic compression metric used by the challenge
234
+ local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps)
235
+ if local_batch_tokens < args.train_seq_len:
236
+ raise ValueError(
237
+ "VAL_BATCH_SIZE must provide at least one sequence per rank; "
238
+ f"got VAL_BATCH_SIZE={args.val_batch_size}, WORLD_SIZE={world_size}, "
239
+ f"GRAD_ACCUM_STEPS={grad_accum_steps}, TRAIN_SEQ_LEN={args.train_seq_len}"
240
+ )
241
+ local_batch_seqs = local_batch_tokens // args.train_seq_len
242
+ total_seqs = (val_tokens.numel() - 1) // args.train_seq_len
243
+ seq_start = (total_seqs * rank) // world_size
244
+ seq_end = (total_seqs * (rank + 1)) // world_size
245
+ val_loss_sum = torch.zeros((), device=device, dtype=torch.float64)
246
+ val_token_count = torch.zeros((), device=device, dtype=torch.float64)
247
+ val_byte_count = torch.zeros((), device=device, dtype=torch.float64)
248
+
249
+ model.eval()
250
+ with torch.inference_mode():
251
+ for batch_seq_start in range(seq_start, seq_end, local_batch_seqs):
252
+ batch_seq_end = min(batch_seq_start + local_batch_seqs, seq_end)
253
+ raw_start = batch_seq_start * args.train_seq_len
254
+ raw_end = batch_seq_end * args.train_seq_len + 1
255
+ local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True)
256
+ x = local[:-1].reshape(-1, args.train_seq_len)
257
+ y = local[1:].reshape(-1, args.train_seq_len)
258
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
259
+ batch_loss = model(x, y).detach()
260
+ batch_token_count = float(y.numel())
261
+ val_loss_sum += batch_loss.to(torch.float64) * batch_token_count
262
+ val_token_count += batch_token_count
263
+ prev_ids = x.reshape(-1)
264
+ tgt_ids = y.reshape(-1)
265
+ token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16)
266
+ token_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int16)
267
+ val_byte_count += token_bytes.to(torch.float64).sum()
268
+
269
+ if dist.is_available() and dist.is_initialized():
270
+ dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM)
271
+ dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM)
272
+ dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM)
273
+
274
+ val_loss = val_loss_sum / val_token_count
275
+ bits_per_token = val_loss.item() / math.log(2.0)
276
+ tokens_per_byte = val_token_count.item() / val_byte_count.item()
277
+ model.train()
278
+ return float(val_loss.item()), float(bits_per_token * tokens_per_byte)
279
+
280
+ # -----------------------------
281
+ # POST-TRAINING QUANTIZATION
282
+ # -----------------------------
283
+ #
284
+ # It's silly to export our model, which is trained in bf16 and fp32, at that same precision.
285
+ # Instead, we get approximately the same model (with a small hit) by quantizing the model to int8 & zlib compressing.
286
+ # We can then decompress the model and run in higher precision for evaluation, after closing in under the size limit.
287
+
288
+ CONTROL_TENSOR_NAME_PATTERNS = tuple(
289
+ pattern
290
+ for pattern in os.environ.get(
291
+ "CONTROL_TENSOR_NAME_PATTERNS",
292
+ "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights",
293
+ ).split(",")
294
+ if pattern
295
+ )
296
+ INT8_KEEP_FLOAT_FP32_NAME_PATTERNS = tuple(
297
+ pattern
298
+ for pattern in os.environ.get(
299
+ "INT8_KEEP_FLOAT_FP32_NAME_PATTERNS",
300
+ ",".join(CONTROL_TENSOR_NAME_PATTERNS),
301
+ ).split(",")
302
+ if pattern
303
+ )
304
+ INT8_KEEP_FLOAT_MAX_NUMEL = 65_536
305
+ INT8_KEEP_FLOAT_STORE_DTYPE = torch.float16
306
+ INT8_PER_ROW_SCALE_DTYPE = torch.float16
307
+ INT8_CLIP_PERCENTILE = 99.99984
308
+ INT8_CLIP_Q = INT8_CLIP_PERCENTILE / 100.0
309
+
310
+ def tensor_nbytes(t: Tensor) -> int:
311
+ return int(t.numel()) * int(t.element_size())
312
+
313
+ def keep_float_tensor(name: str, t: Tensor, passthrough_orig_dtypes: dict[str, str]) -> Tensor:
314
+ if any(pattern in name for pattern in INT8_KEEP_FLOAT_FP32_NAME_PATTERNS):
315
+ return t.float().contiguous()
316
+ if t.dtype in {torch.float32, torch.bfloat16}:
317
+ passthrough_orig_dtypes[name] = str(t.dtype).removeprefix("torch.")
318
+ return t.to(dtype=INT8_KEEP_FLOAT_STORE_DTYPE).contiguous()
319
+ return t
320
+
321
+ def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]:
322
+ t32 = t.float()
323
+ if t32.ndim == 2:
324
+ # Matrices get one scale per row, which usually tracks output-channel
325
+ # ranges much better than a single tensor-wide scale.
326
+ clip_abs = (
327
+ torch.quantile(t32.abs(), INT8_CLIP_Q, dim=1)
328
+ if t32.numel()
329
+ else torch.empty((t32.shape[0],), dtype=torch.float32)
330
+ )
331
+ clipped = torch.maximum(torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None])
332
+ scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0)
333
+ q = torch.clamp(torch.round(clipped / scale[:, None]), -127, 127).to(torch.int8).contiguous()
334
+ return q, scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous()
335
+
336
+ # Vectors / scalars use a simpler per-tensor scale.
337
+ clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0
338
+ scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32)
339
+ q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127).to(torch.int8).contiguous()
340
+ return q, scale
341
+
342
+ def quantize_state_dict_int8(state_dict: dict[str, Tensor]):
343
+ # Single supported clean-script export format:
344
+ # - per-row int8 for 2D float tensors
345
+ # - per-tensor int8 for other float tensors
346
+ # - exact passthrough for non-floats
347
+ # - passthrough for small float tensors, stored as fp16 to save bytes
348
+ quantized: dict[str, Tensor] = {}
349
+ scales: dict[str, Tensor] = {}
350
+ dtypes: dict[str, str] = {}
351
+ passthrough: dict[str, Tensor] = {}
352
+ passthrough_orig_dtypes: dict[str, str] = {}
353
+ qmeta: dict[str, dict[str, object]] = {}
354
+ stats = dict.fromkeys(
355
+ ("param_count", "num_tensors", "num_float_tensors", "num_nonfloat_tensors", "baseline_tensor_bytes", "int8_payload_bytes"),
356
+ 0,
357
+ )
358
+
359
+ for name, tensor in state_dict.items():
360
+ t = tensor.detach().to("cpu").contiguous()
361
+ stats["param_count"] += int(t.numel())
362
+ stats["num_tensors"] += 1
363
+ stats["baseline_tensor_bytes"] += tensor_nbytes(t)
364
+
365
+ if not t.is_floating_point():
366
+ stats["num_nonfloat_tensors"] += 1
367
+ passthrough[name] = t
368
+ stats["int8_payload_bytes"] += tensor_nbytes(t)
369
+ continue
370
+
371
+ # Small float tensors are cheap enough to keep directly. We still downcast
372
+ # fp32/bf16 passthrough tensors to fp16 so metadata does not dominate size.
373
+ if t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL:
374
+ kept = keep_float_tensor(name, t, passthrough_orig_dtypes)
375
+ passthrough[name] = kept
376
+ stats["int8_payload_bytes"] += tensor_nbytes(kept)
377
+ continue
378
+
379
+ stats["num_float_tensors"] += 1
380
+ q, s = quantize_float_tensor(t)
381
+ if s.ndim > 0:
382
+ qmeta[name] = {"scheme": "per_row", "axis": 0}
383
+ quantized[name] = q
384
+ scales[name] = s
385
+ dtypes[name] = str(t.dtype).removeprefix("torch.")
386
+ stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s)
387
+
388
+ obj: dict[str, object] = {
389
+ "__quant_format__": "int8_clean_per_row_v1",
390
+ "quantized": quantized,
391
+ "scales": scales,
392
+ "dtypes": dtypes,
393
+ "passthrough": passthrough,
394
+ }
395
+ if qmeta:
396
+ obj["qmeta"] = qmeta
397
+ if passthrough_orig_dtypes:
398
+ obj["passthrough_orig_dtypes"] = passthrough_orig_dtypes
399
+ return obj, stats
400
+
401
+ def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]:
402
+ out: dict[str, Tensor] = {}
403
+ qmeta = obj.get("qmeta", {})
404
+ passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {})
405
+ for name, q in obj["quantized"].items():
406
+ dtype = getattr(torch, obj["dtypes"][name])
407
+ s = obj["scales"][name]
408
+ if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0:
409
+ s = s.to(dtype=torch.float32)
410
+ # Broadcast the saved row scale back across trailing dimensions.
411
+ out[name] = (q.float() * s.view(q.shape[0], *([1] * (q.ndim - 1)))).to(dtype=dtype).contiguous()
412
+ else:
413
+ scale = float(s.item())
414
+ out[name] = (q.float() * scale).to(dtype=dtype).contiguous()
415
+ for name, t in obj["passthrough"].items():
416
+ # Restore small tensors, undoing the temporary fp16 storage cast if needed.
417
+ out_t = t.detach().to("cpu").contiguous()
418
+ orig_dtype = passthrough_orig_dtypes.get(name)
419
+ if isinstance(orig_dtype, str):
420
+ out_t = out_t.to(dtype=getattr(torch, orig_dtype)).contiguous()
421
+ out[name] = out_t
422
+ return out
423
+
424
+
425
+ # -----------------------------
426
+ # DATA LOADING
427
+ # -----------------------------
428
+
429
+ def load_data_shard(file: Path) -> Tensor:
430
+ header_bytes = 256 * np.dtype("<i4").itemsize
431
+ token_bytes = np.dtype("<u2").itemsize
432
+ header = np.fromfile(file, dtype="<i4", count=256)
433
+ # SHARD HEADER INTS & SHARD_MAGIC
434
+ if header.size != 256 or int(header[0]) != 20240520 or int(header[1]) != 1:
435
+ raise ValueError(f"Unexpected shard header for {file}")
436
+ num_tokens = int(header[2])
437
+ expected_size = header_bytes + num_tokens * token_bytes
438
+ if file.stat().st_size != expected_size:
439
+ raise ValueError(f"Shard size mismatch for {file}: expected {expected_size} bytes")
440
+ tokens_np = np.fromfile(file, dtype="<u2", count=num_tokens, offset=header_bytes)
441
+ if tokens_np.size != num_tokens:
442
+ raise ValueError(f"Short read for {file}")
443
+ return torch.from_numpy(tokens_np.astype(np.uint16, copy=False))
444
+
445
+
446
+ class TokenStream:
447
+ # Reads shards sequentially and wraps around forever. The training loop therefore
448
+ # has deterministic, simple streaming behavior with no sampling or workers.
449
+ def __init__(self, pattern: str):
450
+ self.files = [Path(p) for p in sorted(glob.glob(pattern))]
451
+ if not self.files:
452
+ raise FileNotFoundError(f"No files found for pattern: {pattern}")
453
+ self.file_idx = 0
454
+ self.tokens = load_data_shard(self.files[0])
455
+ self.pos = 0
456
+
457
+ def _advance_file(self) -> None:
458
+ self.file_idx = (self.file_idx + 1) % len(self.files)
459
+ self.tokens = load_data_shard(self.files[self.file_idx])
460
+ self.pos = 0
461
+
462
+ def take(self, n: int) -> Tensor:
463
+ chunks: list[Tensor] = []
464
+ remaining = n
465
+ while remaining > 0:
466
+ avail = self.tokens.numel() - self.pos
467
+ if avail <= 0:
468
+ self._advance_file()
469
+ continue
470
+ k = min(remaining, avail)
471
+ chunks.append(self.tokens[self.pos : self.pos + k])
472
+ self.pos += k
473
+ remaining -= k
474
+ return chunks[0] if len(chunks) == 1 else torch.cat(chunks)
475
+
476
+
477
+ class DistributedTokenLoader:
478
+ # Each call consumes a contiguous chunk from the shared token stream, then slices out
479
+ # one disjoint span per rank. The extra "+1" token lets us build (x, y) by shifting.
480
+ def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device):
481
+ self.rank = rank
482
+ self.world_size = world_size
483
+ self.device = device
484
+ self.stream = TokenStream(pattern)
485
+
486
+ def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> tuple[Tensor, Tensor]:
487
+ local_tokens = global_tokens // (self.world_size * grad_accum_steps)
488
+ per_rank_span = local_tokens + 1
489
+ chunk = self.stream.take(per_rank_span * self.world_size)
490
+ start = self.rank * per_rank_span
491
+ local = chunk[start : start + per_rank_span].to(dtype=torch.int64)
492
+ x = local[:-1].reshape(-1, seq_len)
493
+ y = local[1:].reshape(-1, seq_len)
494
+ return x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True)
495
+
496
+ # -----------------------------
497
+ # TRANSFORMER MODULES
498
+ # -----------------------------
499
+
500
+ class RMSNorm(nn.Module):
501
+ def __init__(self, eps: float | None = None):
502
+ super().__init__()
503
+ self.eps = eps
504
+
505
+ def forward(self, x: Tensor) -> Tensor:
506
+ return F.rms_norm(x, (x.size(-1),), eps=self.eps)
507
+
508
+
509
+ class CastedLinear(nn.Linear):
510
+ # Keep weights in fp32 for optimizer/state quality, cast at matmul time for bf16 compute.
511
+ def forward(self, x: Tensor) -> Tensor:
512
+ bias = self.bias.to(x.dtype) if self.bias is not None else None
513
+ return F.linear(x, self.weight.to(x.dtype), bias)
514
+
515
+
516
+ def restore_low_dim_params_to_fp32(module: nn.Module) -> None:
517
+ # Keep small/control parameters in fp32 even when the model body runs in bf16.
518
+ with torch.no_grad():
519
+ for name, param in module.named_parameters():
520
+ if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32:
521
+ param.data = param.data.float()
522
+
523
+
524
+ class Rotary(nn.Module):
525
+ # Caches cos/sin tables per sequence length on the current device.
526
+ def __init__(self, dim: int, base: float = 10000.0):
527
+ super().__init__()
528
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
529
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
530
+ self._seq_len_cached = 0
531
+ self._cos_cached: Tensor | None = None
532
+ self._sin_cached: Tensor | None = None
533
+
534
+ def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]:
535
+ if (
536
+ self._cos_cached is None
537
+ or self._sin_cached is None
538
+ or self._seq_len_cached != seq_len
539
+ or self._cos_cached.device != device
540
+ ):
541
+ t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype)
542
+ freqs = torch.outer(t, self.inv_freq.to(device))
543
+ self._cos_cached = freqs.cos()[None, None, :, :]
544
+ self._sin_cached = freqs.sin()[None, None, :, :]
545
+ self._seq_len_cached = seq_len
546
+ return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype)
547
+
548
+
549
+ def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor:
550
+ half = x.size(-1) // 2
551
+ x1, x2 = x[..., :half], x[..., half:]
552
+ return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1)
553
+
554
+
555
+ class CausalSelfAttention(nn.Module):
556
+ def __init__(
557
+ self,
558
+ dim: int,
559
+ num_heads: int,
560
+ num_kv_heads: int,
561
+ rope_base: float,
562
+ qk_gain_init: float,
563
+ ):
564
+ super().__init__()
565
+ if dim % num_heads != 0:
566
+ raise ValueError("model_dim must be divisible by num_heads")
567
+ if num_heads % num_kv_heads != 0:
568
+ raise ValueError("num_heads must be divisible by num_kv_heads")
569
+ self.num_heads = num_heads
570
+ self.num_kv_heads = num_kv_heads
571
+ self.head_dim = dim // num_heads
572
+ if self.head_dim % 2 != 0:
573
+ raise ValueError("head_dim must be even for RoPE")
574
+ kv_dim = self.num_kv_heads * self.head_dim
575
+ self.c_q = CastedLinear(dim, dim, bias=False)
576
+ self.c_k = CastedLinear(dim, kv_dim, bias=False)
577
+ self.c_v = CastedLinear(dim, kv_dim, bias=False)
578
+ self.proj = CastedLinear(dim, dim, bias=False)
579
+ self.proj._zero_init = True
580
+ self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32))
581
+ self.rotary = Rotary(self.head_dim, base=rope_base)
582
+
583
+ def forward(self, x: Tensor) -> Tensor:
584
+ bsz, seqlen, dim = x.shape
585
+ q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2)
586
+ k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
587
+ v = self.c_v(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
588
+ q = F.rms_norm(q, (q.size(-1),))
589
+ k = F.rms_norm(k, (k.size(-1),))
590
+ cos, sin = self.rotary(seqlen, x.device, q.dtype)
591
+ q = apply_rotary_emb(q, cos, sin)
592
+ k = apply_rotary_emb(k, cos, sin)
593
+ q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None]
594
+ y = F.scaled_dot_product_attention(
595
+ q,
596
+ k,
597
+ v,
598
+ attn_mask=None,
599
+ is_causal=True,
600
+ enable_gqa=(self.num_kv_heads != self.num_heads),
601
+ )
602
+ y = y.transpose(1, 2).contiguous().reshape(bsz, seqlen, dim)
603
+ return self.proj(y)
604
+
605
+
606
+ class MLP(nn.Module):
607
+ # relu^2 MLP from the original modded-nanogpt setup
608
+ def __init__(self, dim: int, mlp_mult: int):
609
+ super().__init__()
610
+ hidden = mlp_mult * dim
611
+ self.fc = CastedLinear(dim, hidden, bias=False)
612
+ self.proj = CastedLinear(hidden, dim, bias=False)
613
+ self.proj._zero_init = True
614
+
615
+ def forward(self, x: Tensor) -> Tensor:
616
+ x = torch.relu(self.fc(x))
617
+ return self.proj(x.square())
618
+
619
+
620
+ class Block(nn.Module):
621
+ def __init__(
622
+ self,
623
+ dim: int,
624
+ num_heads: int,
625
+ num_kv_heads: int,
626
+ mlp_mult: int,
627
+ rope_base: float,
628
+ qk_gain_init: float,
629
+ ):
630
+ super().__init__()
631
+ self.attn_norm = RMSNorm()
632
+ self.mlp_norm = RMSNorm()
633
+ self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init)
634
+ self.mlp = MLP(dim, mlp_mult)
635
+ self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32))
636
+ self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32))
637
+ self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float())
638
+
639
+ def forward(self, x: Tensor, x0: Tensor) -> Tensor:
640
+ mix = self.resid_mix.to(dtype=x.dtype)
641
+ x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0
642
+ attn_out = self.attn(self.attn_norm(x))
643
+ x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out
644
+ x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x))
645
+ return x
646
+
647
+
648
+ class GPT(nn.Module):
649
+ def __init__(
650
+ self,
651
+ vocab_size: int,
652
+ num_layers: int,
653
+ model_dim: int,
654
+ num_heads: int,
655
+ num_kv_heads: int,
656
+ mlp_mult: int,
657
+ tie_embeddings: bool,
658
+ tied_embed_init_std: float,
659
+ logit_softcap: float,
660
+ rope_base: float,
661
+ qk_gain_init: float,
662
+ ):
663
+ super().__init__()
664
+ if logit_softcap <= 0.0:
665
+ raise ValueError(f"logit_softcap must be positive, got {logit_softcap}")
666
+ self.tie_embeddings = tie_embeddings
667
+ self.tied_embed_init_std = tied_embed_init_std
668
+ self.logit_softcap = logit_softcap
669
+ self.tok_emb = nn.Embedding(vocab_size, model_dim)
670
+ self.num_encoder_layers = num_layers // 2
671
+ self.num_decoder_layers = num_layers - self.num_encoder_layers
672
+ self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers)
673
+ self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32))
674
+ self.blocks = nn.ModuleList(
675
+ [
676
+ Block(
677
+ model_dim,
678
+ num_heads,
679
+ num_kv_heads,
680
+ mlp_mult,
681
+ rope_base,
682
+ qk_gain_init,
683
+ )
684
+ for i in range(num_layers)
685
+ ]
686
+ )
687
+ self.final_norm = RMSNorm()
688
+ self.lm_head = None if tie_embeddings else CastedLinear(model_dim, vocab_size, bias=False)
689
+ if self.lm_head is not None:
690
+ self.lm_head._zero_init = True
691
+ self._init_weights()
692
+
693
+ def _init_weights(self) -> None:
694
+ if self.tie_embeddings:
695
+ nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std)
696
+ for module in self.modules():
697
+ if isinstance(module, nn.Linear) and getattr(module, "_zero_init", False):
698
+ nn.init.zeros_(module.weight)
699
+
700
+ def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor:
701
+ x = self.tok_emb(input_ids)
702
+ x = F.rms_norm(x, (x.size(-1),))
703
+ x0 = x
704
+ skips: list[Tensor] = []
705
+
706
+ # First half stores skips; second half reuses them in reverse order.
707
+ for i in range(self.num_encoder_layers):
708
+ x = self.blocks[i](x, x0)
709
+ skips.append(x)
710
+ for i in range(self.num_decoder_layers):
711
+ if skips:
712
+ x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop()
713
+ x = self.blocks[self.num_encoder_layers + i](x, x0)
714
+
715
+ x = self.final_norm(x).reshape(-1, x.size(-1))
716
+ targets = target_ids.reshape(-1)
717
+ if self.tie_embeddings:
718
+ logits_proj = F.linear(x, self.tok_emb.weight)
719
+ else:
720
+ if self.lm_head is None:
721
+ raise RuntimeError("lm_head is required when tie_embeddings=False")
722
+ logits_proj = self.lm_head(x)
723
+ logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap)
724
+ return F.cross_entropy(logits.float(), targets, reduction="mean")
725
+
726
+
727
+ # -----------------------------
728
+ # TRAINING
729
+ # -----------------------------
730
+
731
+ def main() -> None:
732
+ global zeropower_via_newtonschulz5
733
+
734
+ code = Path(__file__).read_text(encoding="utf-8")
735
+ args = Hyperparameters()
736
+ zeropower_via_newtonschulz5 = torch.compile(zeropower_via_newtonschulz5)
737
+
738
+ # -----------------------------
739
+ # DISTRIBUTED + CUDA SETUP
740
+ # -----------------------------
741
+
742
+ distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ
743
+ rank = int(os.environ.get("RANK", "0"))
744
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
745
+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
746
+ if world_size <= 0:
747
+ raise ValueError(f"WORLD_SIZE must be positive, got {world_size}")
748
+ if 8 % world_size != 0:
749
+ raise ValueError(f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral")
750
+ grad_accum_steps = 8 // world_size
751
+ grad_scale = 1.0 / grad_accum_steps
752
+ if not torch.cuda.is_available():
753
+ raise RuntimeError("CUDA is required")
754
+ device = torch.device("cuda", local_rank)
755
+ torch.cuda.set_device(device)
756
+ if distributed:
757
+ dist.init_process_group(backend="nccl", device_id=device)
758
+ dist.barrier()
759
+ master_process = rank == 0
760
+
761
+ # Fast math knobs
762
+ torch.backends.cuda.matmul.allow_tf32 = True
763
+ torch.backends.cudnn.allow_tf32 = True
764
+ from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp
765
+
766
+ enable_cudnn_sdp(False)
767
+ enable_flash_sdp(True)
768
+ enable_mem_efficient_sdp(False)
769
+ enable_math_sdp(False)
770
+
771
+ logfile = None
772
+ if master_process:
773
+ os.makedirs("logs", exist_ok=True)
774
+ logfile = f"logs/{args.run_id}.txt"
775
+ print(logfile)
776
+
777
+ def log0(msg: str, console: bool = True) -> None:
778
+ if not master_process:
779
+ return
780
+ if console:
781
+ print(msg)
782
+ if logfile is not None:
783
+ with open(logfile, "a", encoding="utf-8") as f:
784
+ print(msg, file=f)
785
+
786
+ log0(code, console=False)
787
+ log0("=" * 100, console=False)
788
+ log0(f"Running Python {sys.version}", console=False)
789
+ log0(f"Running PyTorch {torch.__version__}", console=False)
790
+ log0(
791
+ subprocess.run(["nvidia-smi"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout,
792
+ console=False,
793
+ )
794
+ log0("=" * 100, console=False)
795
+
796
+ # -----------------------------
797
+ # TOKENIZER + VALIDATION METRIC SETUP
798
+ # -----------------------------
799
+
800
+ random.seed(args.seed)
801
+ np.random.seed(args.seed)
802
+ torch.manual_seed(args.seed)
803
+ torch.cuda.manual_seed_all(args.seed)
804
+
805
+ if not args.tokenizer_path.endswith(".model"):
806
+ raise ValueError(f"Script only setup for SentencePiece .model file: {args.tokenizer_path}")
807
+ sp = spm.SentencePieceProcessor(model_file=args.tokenizer_path)
808
+ if int(sp.vocab_size()) != args.vocab_size:
809
+ raise ValueError(
810
+ f"VOCAB_SIZE={args.vocab_size} does not match tokenizer vocab_size={int(sp.vocab_size())}"
811
+ )
812
+ dataset_dir = Path(args.data_path).resolve()
813
+ actual_train_files = len(list(dataset_dir.glob("fineweb_train_*.bin")))
814
+ val_tokens = load_validation_tokens(args.val_files, args.train_seq_len)
815
+ base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = build_sentencepiece_luts(
816
+ sp, args.vocab_size, device
817
+ )
818
+ log0(f"val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path={args.tokenizer_path}")
819
+ log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}")
820
+ log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}")
821
+
822
+ # -----------------------------
823
+ # MODEL + OPTIMIZER SETUP
824
+ # -----------------------------
825
+
826
+ base_model = GPT(
827
+ vocab_size=args.vocab_size,
828
+ num_layers=args.num_layers,
829
+ model_dim=args.model_dim,
830
+ num_heads=args.num_heads,
831
+ num_kv_heads=args.num_kv_heads,
832
+ mlp_mult=args.mlp_mult,
833
+ tie_embeddings=args.tie_embeddings,
834
+ tied_embed_init_std=args.tied_embed_init_std,
835
+ logit_softcap=args.logit_softcap,
836
+ rope_base=args.rope_base,
837
+ qk_gain_init=args.qk_gain_init,
838
+ ).to(device).bfloat16()
839
+ for module in base_model.modules():
840
+ if isinstance(module, CastedLinear):
841
+ module.float()
842
+ restore_low_dim_params_to_fp32(base_model)
843
+ compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True)
844
+ model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if distributed else compiled_model
845
+
846
+ # Optimizer split:
847
+ # - token embedding (Adam) uses EMBED_LR
848
+ # - untied lm_head (Adam) uses HEAD_LR
849
+ # - matrix params in transformer blocks use MATRIX_LR via Muon
850
+ # - vectors/scalars use SCALAR_LR via Adam
851
+ block_named_params = list(base_model.blocks.named_parameters())
852
+ matrix_params = [
853
+ p
854
+ for name, p in block_named_params
855
+ if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)
856
+ ]
857
+ scalar_params = [
858
+ p
859
+ for name, p in block_named_params
860
+ if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)
861
+ ]
862
+ if base_model.skip_weights.numel() > 0:
863
+ scalar_params.append(base_model.skip_weights)
864
+ token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr
865
+ optimizer_tok = torch.optim.Adam(
866
+ [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}],
867
+ betas=(args.beta1, args.beta2),
868
+ eps=args.adam_eps,
869
+ fused=True,
870
+ )
871
+ optimizer_muon = Muon(
872
+ matrix_params,
873
+ lr=args.matrix_lr,
874
+ momentum=args.muon_momentum,
875
+ backend_steps=args.muon_backend_steps,
876
+ )
877
+ for group in optimizer_muon.param_groups:
878
+ group["base_lr"] = args.matrix_lr
879
+ optimizer_scalar = torch.optim.Adam(
880
+ [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}],
881
+ betas=(args.beta1, args.beta2),
882
+ eps=args.adam_eps,
883
+ fused=True,
884
+ )
885
+ optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar]
886
+ if base_model.lm_head is not None:
887
+ optimizer_head = torch.optim.Adam(
888
+ [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}],
889
+ betas=(args.beta1, args.beta2),
890
+ eps=args.adam_eps,
891
+ fused=True,
892
+ )
893
+ optimizers.insert(1, optimizer_head)
894
+
895
+ n_params = sum(p.numel() for p in base_model.parameters())
896
+ log0(f"model_params:{n_params}")
897
+ log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}")
898
+ log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False")
899
+ log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}")
900
+ log0(
901
+ f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} "
902
+ f"head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} "
903
+ f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}"
904
+ )
905
+ log0(
906
+ f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} "
907
+ f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} "
908
+ f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}"
909
+ )
910
+ log0(f"seed:{args.seed}")
911
+
912
+ # -----------------------------
913
+ # DATA LOADER & MODEL WARMUP
914
+ # -----------------------------
915
+
916
+ train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device)
917
+
918
+ def zero_grad_all() -> None:
919
+ for opt in optimizers:
920
+ opt.zero_grad(set_to_none=True)
921
+
922
+ max_wallclock_ms = 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None
923
+
924
+ def lr_mul(step: int, elapsed_ms: float) -> float:
925
+ if args.warmdown_iters <= 0:
926
+ return 1.0
927
+ if max_wallclock_ms is None:
928
+ warmdown_start = max(args.iterations - args.warmdown_iters, 0)
929
+ return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0
930
+ step_ms = elapsed_ms / max(step, 1)
931
+ warmdown_ms = args.warmdown_iters * step_ms
932
+ remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0)
933
+ return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0
934
+
935
+ # Warmup primes the compiled forward/backward/optimizer paths, then we restore the
936
+ # initial weights/optimizer state so measured training starts from the true init.
937
+ if args.warmup_steps > 0:
938
+ initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()}
939
+ initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers]
940
+ model.train()
941
+ for warmup_step in range(args.warmup_steps):
942
+ zero_grad_all()
943
+ for micro_step in range(grad_accum_steps):
944
+ if distributed:
945
+ model.require_backward_grad_sync = micro_step == grad_accum_steps - 1
946
+ x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps)
947
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
948
+ warmup_loss = model(x, y)
949
+ (warmup_loss * grad_scale).backward()
950
+ for opt in optimizers:
951
+ opt.step()
952
+ zero_grad_all()
953
+ if args.warmup_steps <= 20 or (warmup_step + 1) % 10 == 0 or warmup_step + 1 == args.warmup_steps:
954
+ log0(f"warmup_step:{warmup_step + 1}/{args.warmup_steps}")
955
+ base_model.load_state_dict(initial_model_state, strict=True)
956
+ for opt, state in zip(optimizers, initial_optimizer_states, strict=True):
957
+ opt.load_state_dict(state)
958
+ zero_grad_all()
959
+ if distributed:
960
+ model.require_backward_grad_sync = True
961
+ train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device)
962
+
963
+ # -----------------------------
964
+ # MAIN TRAINING LOOP
965
+ # -----------------------------
966
+
967
+ training_time_ms = 0.0
968
+ stop_after_step: int | None = None
969
+ torch.cuda.synchronize()
970
+ t0 = time.perf_counter()
971
+
972
+ step = 0
973
+ while True:
974
+ last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step)
975
+
976
+ should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0)
977
+ if should_validate:
978
+ torch.cuda.synchronize()
979
+ training_time_ms += 1000.0 * (time.perf_counter() - t0)
980
+ val_loss, val_bpb = eval_val(
981
+ args,
982
+ model,
983
+ rank,
984
+ world_size,
985
+ device,
986
+ grad_accum_steps,
987
+ val_tokens,
988
+ base_bytes_lut,
989
+ has_leading_space_lut,
990
+ is_boundary_token_lut,
991
+ )
992
+ log0(
993
+ f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} "
994
+ f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms"
995
+ )
996
+ torch.cuda.synchronize()
997
+ t0 = time.perf_counter()
998
+
999
+ if last_step:
1000
+ if stop_after_step is not None and step < args.iterations:
1001
+ log0(
1002
+ f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms "
1003
+ f"step:{step}/{args.iterations}"
1004
+ )
1005
+ break
1006
+
1007
+ elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0)
1008
+ scale = lr_mul(step, elapsed_ms)
1009
+ zero_grad_all()
1010
+ train_loss = torch.zeros((), device=device)
1011
+ for micro_step in range(grad_accum_steps):
1012
+ if distributed:
1013
+ model.require_backward_grad_sync = micro_step == grad_accum_steps - 1
1014
+ x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps)
1015
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True):
1016
+ loss = model(x, y)
1017
+ train_loss += loss.detach()
1018
+ (loss * grad_scale).backward()
1019
+ train_loss /= grad_accum_steps
1020
+
1021
+ frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0
1022
+ muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum
1023
+ for group in optimizer_muon.param_groups:
1024
+ group["momentum"] = muon_momentum
1025
+
1026
+ for opt in optimizers:
1027
+ for group in opt.param_groups:
1028
+ group["lr"] = group["base_lr"] * scale
1029
+
1030
+ if args.grad_clip_norm > 0:
1031
+ torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm)
1032
+ for opt in optimizers:
1033
+ opt.step()
1034
+ zero_grad_all()
1035
+
1036
+ step += 1
1037
+ approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0)
1038
+ should_log_train = (
1039
+ args.train_log_every > 0
1040
+ and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None)
1041
+ )
1042
+ if should_log_train:
1043
+ log0(
1044
+ f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} "
1045
+ f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms"
1046
+ )
1047
+
1048
+ # Needed to sync whether we've reached the wallclock cap.
1049
+ reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms
1050
+ if distributed and max_wallclock_ms is not None:
1051
+ reached_cap_tensor = torch.tensor(int(reached_cap), device=device)
1052
+ dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX)
1053
+ reached_cap = bool(reached_cap_tensor.item())
1054
+ if stop_after_step is None and reached_cap:
1055
+ stop_after_step = step
1056
+
1057
+ log0(
1058
+ f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB "
1059
+ f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB"
1060
+ )
1061
+
1062
+ # -----------------------------
1063
+ # SERIALIZATION + ROUNDTRIP VALIDATION
1064
+ # -----------------------------
1065
+ # Save the raw state (useful for debugging/loading in PyTorch directly), then always produce
1066
+ # the compressed int8+zlib artifact and validate the round-tripped weights.
1067
+
1068
+ if master_process:
1069
+ torch.save(base_model.state_dict(), "final_model.pt")
1070
+ model_bytes = os.path.getsize("final_model.pt")
1071
+ code_bytes = len(code.encode("utf-8"))
1072
+ log0(f"Serialized model: {model_bytes} bytes")
1073
+ log0(f"Code size: {code_bytes} bytes")
1074
+ log0(f"Total submission size: {model_bytes + code_bytes} bytes")
1075
+
1076
+ quant_obj, quant_stats = quantize_state_dict_int8(base_model.state_dict())
1077
+ quant_buf = io.BytesIO()
1078
+ torch.save(quant_obj, quant_buf)
1079
+ quant_raw = quant_buf.getvalue()
1080
+ quant_blob = zlib.compress(quant_raw, level=9)
1081
+ quant_raw_bytes = len(quant_raw)
1082
+ if master_process:
1083
+ with open("final_model.int8.ptz", "wb") as f:
1084
+ f.write(quant_blob)
1085
+ quant_file_bytes = os.path.getsize("final_model.int8.ptz")
1086
+ code_bytes = len(code.encode("utf-8"))
1087
+ ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int8_payload_bytes"], 1)
1088
+ log0(
1089
+ f"Serialized model int8+zlib: {quant_file_bytes} bytes "
1090
+ f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)"
1091
+ )
1092
+ log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes")
1093
+
1094
+ if distributed:
1095
+ dist.barrier()
1096
+ with open("final_model.int8.ptz", "rb") as f:
1097
+ quant_blob_disk = f.read()
1098
+ quant_state = torch.load(io.BytesIO(zlib.decompress(quant_blob_disk)), map_location="cpu")
1099
+ base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True)
1100
+ torch.cuda.synchronize()
1101
+ t_qeval = time.perf_counter()
1102
+ q_val_loss, q_val_bpb = eval_val(
1103
+ args,
1104
+ model,
1105
+ rank,
1106
+ world_size,
1107
+ device,
1108
+ grad_accum_steps,
1109
+ val_tokens,
1110
+ base_bytes_lut,
1111
+ has_leading_space_lut,
1112
+ is_boundary_token_lut,
1113
+ )
1114
+ torch.cuda.synchronize()
1115
+ log0(
1116
+ f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} "
1117
+ f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms"
1118
+ )
1119
+ log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}")
1120
+
1121
+ if distributed:
1122
+ dist.destroy_process_group()
1123
+
1124
+
1125
+ if __name__ == "__main__":
1126
+ main()