bs-llm-375m-2b / train.py
renatoschust's picture
bs-llm-341m-2b: train.py
41b993d verified
Raw History Blame Contribute Delete
40.7 kB
#!/usr/bin/env python3
"""Single-file, deterministic decoder-only LM trainer (LLaMA-style).
Sprint 0 trainer for the small Bosnian LM. Designed to run unchanged:
* on CPU (smoke test, --dry-run),
* on 2x L40S via `torchrun --nproc_per_node=2 train.py --config configs/125m.yaml`.
Architecture: pre-norm decoder blocks with RMSNorm, RoPE, SwiGLU MLP,
causal self-attention (F.scaled_dot_product_attention), tied embeddings.
Data: raw token shards (.bin, uint16 or uint32), memory-mapped. Documents are
assumed to be pre-concatenated in the shards (no padding); training windows are
sampled uniformly, i.e. windows freely cross document boundaries ("packing").
Reproducibility: `--seed` seeds python/numpy/torch (init + data order).
For the same world size and the same seed, the batch order is identical.
Determinism is not bit-exact across different GPU counts / kernels; see README.
Nothing outside this directory is written, except --out-dir if you point it
somewhere else on purpose. No GPU is touched unless CUDA is available and
--device cuda / auto selects it.
"""
from __future__ import annotations
import argparse
import contextlib
import csv
import glob
import json
import math
import os
import random
import sys
import time
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
try:
import yaml
except ImportError: # pragma: no cover
yaml = None
# --------------------------------------------------------------------------- #
# Model
# --------------------------------------------------------------------------- #
@dataclass
class ModelConfig:
vocab_size: int = 32000
n_layer: int = 12
n_head: int = 12
d_model: int = 768
d_ff: int = 2048
seq_len: int = 1024
rope_theta: float = 10000.0
norm_eps: float = 1e-5
tie_embeddings: bool = True
# Gated attention (Qiu et al., NeurIPS 2025): per-head, per-channel sigmoid
# gate on the SDPA output, applied before the output projection. Off by
# default; when off the module adds no parameters and the code path is
# unchanged (bit-identical baseline).
gated_attn: bool = False
gate_init: float = 3.0 # gate value at init => sigmoid(3.0) = 0.9526 (~= identity)
init_std: float = 0.02
# Width used as the reference for the (approximate) muP scaling.
mup_base_width: int = 768
class RMSNorm(nn.Module):
"""Root-mean-square layer norm (no mean subtraction, no bias)."""
def __init__(self, dim: int, eps: float = 1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
dtype = x.dtype
# Normalise in fp32 for numerical stability (cheap, one reduction).
x = x.float()
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return (self.weight.float() * x).to(dtype)
def rope_cache(seq_len: int, head_dim: int, theta: float, device, dtype) -> tuple[torch.Tensor, torch.Tensor]:
"""cos/sin tables of shape (seq_len, head_dim // 2) in the LLaMA (half-split) layout."""
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
pos = torch.arange(seq_len, device=device).float()
freqs = torch.outer(pos, inv_freq) # (T, D/2)
return freqs.cos().to(dtype), freqs.sin().to(dtype)
def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
"""x: (B, H, T, D) fp32/bf16. cos/sin: (T, D/2). Rotate halves (LLaMA convention)."""
d = x.shape[-1]
x1, x2 = x[..., : d // 2], x[..., d // 2 :]
cos = cos[None, None, :, :].to(x.dtype)
sin = sin[None, None, :, :].to(x.dtype)
return torch.cat((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1)
class Attention(nn.Module):
def __init__(self, cfg: ModelConfig):
super().__init__()
assert cfg.d_model % cfg.n_head == 0, "d_model must be divisible by n_head"
self.n_head = cfg.n_head
self.head_dim = cfg.d_model // cfg.n_head
self.qkv = nn.Linear(cfg.d_model, 3 * cfg.d_model, bias=False)
self.proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False)
self.rope_theta = cfg.rope_theta
# Gate is a constant-initialised parameter, so it consumes no RNG and
# leaves every other weight exactly as in the ungated baseline.
self.gate = (
nn.Parameter(torch.full((cfg.n_head, self.head_dim), float(cfg.gate_init)))
if cfg.gated_attn else None
)
self._cos: torch.Tensor | None = None
self._sin: torch.Tensor | None = None
self._rope_len = 0
def _rope(self, t: int, device, dtype):
if self._rope_len < t or self._cos is None or self._cos.device != device:
cos, sin = rope_cache(max(t, 256), self.head_dim, self.rope_theta, device, dtype)
self._cos, self._sin, self._rope_len = cos, sin, cos.shape[0]
return self._cos[:t], self._sin[:t]
def forward(self, x: torch.Tensor) -> torch.Tensor:
b, t, c = x.shape
q, k, v = self.qkv(x).split(c, dim=2)
q = q.view(b, t, self.n_head, self.head_dim).transpose(1, 2)
k = k.view(b, t, self.n_head, self.head_dim).transpose(1, 2)
v = v.view(b, t, self.n_head, self.head_dim).transpose(1, 2)
cos, sin = self._rope(t, x.device, torch.float32)
q = apply_rope(q, cos, sin)
k = apply_rope(k, cos, sin)
y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=True)
if self.gate is not None:
# (B,H,T,D) * (H,D) broadcast over batch and time: one gate vector
# per head, per head_dim channel, applied before the output proj.
y = y * torch.sigmoid(self.gate)[None, :, None, :]
y = y.transpose(1, 2).contiguous().view(b, t, c)
return self.proj(y)
class SwiGLU(nn.Module):
"""SwiGLU MLP: down(silu(gate(x)) * up(x))."""
def __init__(self, cfg: ModelConfig):
super().__init__()
self.gate = nn.Linear(cfg.d_model, cfg.d_ff, bias=False)
self.up = nn.Linear(cfg.d_model, cfg.d_ff, bias=False)
self.down = nn.Linear(cfg.d_ff, cfg.d_model, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.down(F.silu(self.gate(x)) * self.up(x))
class Block(nn.Module):
def __init__(self, cfg: ModelConfig):
super().__init__()
self.norm1 = RMSNorm(cfg.d_model, cfg.norm_eps)
self.attn = Attention(cfg)
self.norm2 = RMSNorm(cfg.d_model, cfg.norm_eps)
self.mlp = SwiGLU(cfg)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = x + self.attn(self.norm1(x))
return x + self.mlp(self.norm2(x))
class Transformer(nn.Module):
def __init__(self, cfg: ModelConfig):
super().__init__()
self.cfg = cfg
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model)
self.blocks = nn.ModuleList(Block(cfg) for _ in range(cfg.n_layer))
self.norm_f = RMSNorm(cfg.d_model, cfg.norm_eps)
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
if cfg.tie_embeddings:
self.lm_head.weight = self.tok_emb.weight
self.apply(self._init_weights)
def _init_weights(self, m: nn.Module) -> None:
if isinstance(m, nn.Linear):
nn.init.normal_(m.weight, mean=0.0, std=self.cfg.init_std)
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Embedding):
nn.init.normal_(m.weight, mean=0.0, std=self.cfg.init_std)
elif isinstance(m, RMSNorm):
nn.init.ones_(m.weight)
def num_params(self, non_embedding: bool = False) -> int:
n = sum(p.numel() for p in self.parameters())
if non_embedding:
n -= self.tok_emb.weight.numel()
return n
def forward(self, idx: torch.Tensor, targets: torch.Tensor | None = None):
x = self.tok_emb(idx)
for blk in self.blocks:
x = blk(x)
x = self.norm_f(x)
logits = self.lm_head(x)
if targets is None:
return logits, None
loss = F.cross_entropy(
logits.float().view(-1, logits.size(-1)), targets.reshape(-1), reduction="mean"
)
return logits, loss
# --------------------------------------------------------------------------- #
# muP (approximation)
# --------------------------------------------------------------------------- #
def apply_mup(cfg: ModelConfig, lr: float) -> tuple[ModelConfig, float]:
"""CRUDE muP approximation -- documented as such, not exact muP.
* init std ∝ 1 / sqrt(width) => std = base_std * sqrt(base_width / width)
* lr ∝ 1 / width => lr = base_lr * (base_width / width)
Exact muP also rescales attention logits (1/head_dim), output projections
(1/width) and uses per-layer/base-shape learning rates; we deliberately do
not implement those. Treat this as "width-aware init/LR" only.
"""
cfg = ModelConfig(**asdict(cfg))
ratio = cfg.mup_base_width / cfg.d_model
cfg.init_std = cfg.init_std * math.sqrt(ratio)
return cfg, lr * ratio
# --------------------------------------------------------------------------- #
# Data
# --------------------------------------------------------------------------- #
def _np_dtype(name: str) -> np.dtype:
name = name.lower()
if name in ("uint16", "u16", "u16le"):
return np.dtype("<u2")
if name in ("uint32", "u32", "u32le"):
return np.dtype("<u4")
raise ValueError(f"unsupported shard dtype {name!r} (use uint16 or uint32)")
class TokenShards:
"""Read-only view over one or more raw token shards as a single stream.
Shards are concatenated logically; a window may cross a shard boundary.
"""
def __init__(self, paths: list[str], dtype: str):
if isinstance(paths, (str, Path)):
raise SystemExit(f"data.shards must be a list of paths, got {paths!r}")
# Allow shell-style globs: ["data/bins/train_*.bin"].
expanded: list[str] = []
for p in paths:
s = str(p)
if any(ch in s for ch in "*?["):
hits = sorted(glob.glob(s))
if not hits:
raise FileNotFoundError(f"shard glob matched nothing: {s}")
expanded.extend(hits)
else:
expanded.append(s)
self.paths = [Path(p) for p in expanded]
if not self.paths:
raise ValueError("no shards given")
for p in self.paths:
if not p.is_file():
raise FileNotFoundError(f"shard not found: {p}")
self.dtype = _np_dtype(dtype)
self.arrs = [np.memmap(p, dtype=self.dtype, mode="r") for p in self.paths]
self.sizes = [int(a.size) for a in self.arrs]
self.total = int(sum(self.sizes))
self.starts = np.cumsum([0] + self.sizes[:-1]).tolist()
def read(self, start: int, length: int) -> np.ndarray:
"""Read `length` tokens starting at absolute offset `start` (int64 out)."""
assert 0 <= start and start + length <= self.total, (start, length, self.total)
out = np.empty(length, dtype=np.int64)
end = start + length
for i, arr in enumerate(self.arrs):
s = self.starts[i]
e = s + self.sizes[i]
if end <= s or start >= e:
continue
lo, hi = max(start, s), min(end, e)
out[lo - start : hi - start] = arr[lo - s : hi - s]
return out
def sample_tokens(self, n: int, rng: np.random.Generator) -> np.ndarray:
"""Cheap max-token sanity check on random windows."""
starts = rng.integers(0, max(1, self.total - 64), size=min(8, max(1, n // 64)))
chunks = [self.read(int(s), 64) for s in starts]
return np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.int64)
def make_batch(
shards: TokenShards | None,
batch: int,
seq: int,
rng: np.random.Generator,
device: torch.device,
vocab_size: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Sample `batch` packed windows of seq+1 tokens -> (x, y) on device."""
if shards is None: # synthetic dry-run data
buf = rng.integers(0, vocab_size, size=(batch, seq + 1), dtype=np.int64)
else:
hi = shards.total - (seq + 1)
if hi <= 1:
raise ValueError(f"corpus too small: {shards.total} tokens for seq_len={seq}")
starts = rng.integers(0, hi, size=batch)
buf = np.stack([shards.read(int(s), seq + 1) for s in starts])
t = torch.from_numpy(buf)
x = t[:, :-1].to(device, non_blocking=True)
y = t[:, 1:].to(device, non_blocking=True)
return x, y
# --------------------------------------------------------------------------- #
# LR schedule (token-based)
# --------------------------------------------------------------------------- #
def lr_at_tokens(tokens: int, total_tokens: int, warmup_tokens: int, lr_max: float, min_ratio: float) -> float:
"""Linear warmup then cosine decay, both measured in consumed tokens."""
if tokens <= 0:
return 0.0
lr_min = lr_max * min_ratio
if tokens < warmup_tokens:
return lr_max * tokens / max(1, warmup_tokens)
progress = min(1.0, (tokens - warmup_tokens) / max(1, total_tokens - warmup_tokens))
return lr_min + 0.5 * (lr_max - lr_min) * (1.0 + math.cos(math.pi * progress))
# --------------------------------------------------------------------------- #
# Config / CLI
# --------------------------------------------------------------------------- #
DEFAULT_CFG: dict[str, Any] = {
"model": asdict(ModelConfig()),
"data": {
"shards": [], # list of .bin files (train)
"val_shards": [], # list of .bin files (validation)
"dtype": "uint16", # uint16 | uint32
"vocab_size": None, # if set, overrides model.vocab_size
"bytes_per_token": 3.6, # MUST be measured on the real corpus
},
"optim": {
"lr": 6.0e-4,
"min_lr_ratio": 0.1,
"warmup_tokens": 2_000_000,
"weight_decay": 0.1,
"beta1": 0.9,
"beta2": 0.95,
"grad_clip": 1.0,
"max_tokens": 2_000_000_000,
"batch_size": 8, # per rank, per micro-step
"grad_accum": 1,
},
"run": {
"seed": 1337,
"log_every": 10,
"eval_every": 500,
"eval_iters": 20,
"ckpt_every": 500,
"out_dir": "runs/sprint0",
"mu_p": False,
# Strict kernel determinism (torch.use_deterministic_algorithms) is OFF by
# default: it disables the fast SDPA kernel (measured ~6x slower on CPU).
# Seeding alone already fixes init + data order.
"deterministic": False,
"bf16": True,
"compile": False,
# CPU intra-op threads; 0 = auto (OMP_NUM_THREADS if set, else min(4, cores)).
# Oversubscribing a busy shared host can be 10-50x slower, so this is capped.
"threads": 0,
},
}
def _deep_merge(base: dict, extra: dict) -> dict:
out = dict(base)
for k, v in extra.items():
if isinstance(v, dict) and isinstance(out.get(k), dict):
out[k] = _deep_merge(out[k], v)
else:
out[k] = v
return out
def _coerce(text: str):
low = text.lower()
if low in ("true", "false"):
return low == "true"
if low in ("none", "null"):
return None
if text[:1] in "[{" or text[:1] in "\"'":
try:
return json.loads(text)
except json.JSONDecodeError:
pass
try:
return int(text)
except ValueError:
pass
try:
return float(text)
except ValueError:
pass
return text
def apply_overrides(cfg: dict, pairs: list[str]) -> dict:
for item in pairs:
if "=" not in item:
raise SystemExit(f"--set expects key=value, got {item!r}")
key, _, val = item.partition("=")
parts = key.strip().split(".")
node = cfg
for p in parts[:-1]:
node = node.setdefault(p, {})
node[parts[-1]] = _coerce(val.strip())
return cfg
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
p = argparse.ArgumentParser(description="Sprint-0 LLaMA-style LM trainer (single file)")
p.add_argument("--config", type=str, default=None, help="YAML config (configs/125m.yaml)")
p.add_argument("--set", action="append", default=[], metavar="KEY=VALUE",
help="dotted config override, e.g. --set model.n_layer=2 (repeatable)")
p.add_argument("--seed", type=int, default=None)
p.add_argument("--mu-p", dest="mu_p", action="store_true", default=None,
help="approximate muP init/LR scaling (see apply_mup docstring)")
p.add_argument("--max-tokens", type=int, default=None, help="training budget in tokens (not epochs)")
p.add_argument("--batch-size", type=int, default=None, help="micro-batch per rank")
p.add_argument("--grad-accum", type=int, default=None)
p.add_argument("--seq-len", type=int, default=None)
p.add_argument("--lr", type=float, default=None)
p.add_argument("--out-dir", type=str, default=None)
p.add_argument("--resume", type=str, default=None, help="checkpoint path (e.g. runs/x/latest.pt)")
p.add_argument("--device", type=str, default="auto", choices=["auto", "cpu", "cuda"])
p.add_argument("--dry-run", action="store_true", help="synthetic random-token data, no shards needed")
p.add_argument("--ckpt-every", type=int, default=None)
p.add_argument("--log-every", type=int, default=None)
p.add_argument("--eval-every", type=int, default=None)
p.add_argument("--eval-iters", type=int, default=None)
p.add_argument("--no-bf16", dest="bf16", action="store_false", default=None)
p.add_argument("--compile", action="store_true", default=None)
p.add_argument("--deterministic", dest="deterministic", action="store_true", default=None,
help="forbid nondeterministic kernels too (slow: disables fast SDPA)")
p.add_argument("--no-deterministic", dest="deterministic", action="store_false", default=None)
p.add_argument("--no-tie", dest="tie", action="store_false", default=True)
p.add_argument("--gated-attn", dest="gated_attn", action="store_true", default=None,
help="gated attention: per-head sigmoid gate on SDPA output (Qiu et al., NeurIPS 2025)")
p.add_argument("--threads", type=int, default=None, help="CPU threads (0=auto)")
return p.parse_args(argv)
def load_config(args: argparse.Namespace) -> dict:
cfg = json.loads(json.dumps(DEFAULT_CFG)) # deep copy of plain data
if args.config:
if yaml is None:
raise SystemExit("pyyaml is required to read --config")
with open(args.config) as f:
user = yaml.safe_load(f) or {}
cfg = _deep_merge(cfg, user)
cfg = apply_overrides(cfg, args.set)
# Flat CLI flags win over file/--set values.
if args.seed is not None:
cfg["run"]["seed"] = args.seed
if args.mu_p is not None:
cfg["run"]["mu_p"] = args.mu_p
if args.max_tokens is not None:
cfg["optim"]["max_tokens"] = args.max_tokens
if args.batch_size is not None:
cfg["optim"]["batch_size"] = args.batch_size
if args.grad_accum is not None:
cfg["optim"]["grad_accum"] = args.grad_accum
if args.seq_len is not None:
cfg["model"]["seq_len"] = args.seq_len
if args.lr is not None:
cfg["optim"]["lr"] = args.lr
if args.out_dir is not None:
cfg["run"]["out_dir"] = args.out_dir
if args.threads is not None:
cfg["run"]["threads"] = args.threads
if args.ckpt_every is not None:
cfg["run"]["ckpt_every"] = args.ckpt_every
if args.log_every is not None:
cfg["run"]["log_every"] = args.log_every
if args.eval_every is not None:
cfg["run"]["eval_every"] = args.eval_every
if args.eval_iters is not None:
cfg["run"]["eval_iters"] = args.eval_iters
if args.bf16 is not None:
cfg["run"]["bf16"] = args.bf16
if args.compile is not None:
cfg["run"]["compile"] = args.compile
if args.deterministic is not None:
cfg["run"]["deterministic"] = args.deterministic
if not args.tie:
cfg["model"]["tie_embeddings"] = False
if args.gated_attn is not None:
cfg["model"]["gated_attn"] = bool(args.gated_attn)
# A single seq_len must agree in the model section and the data reader.
cfg["model"] = _coerce_model(cfg["model"])
if cfg["data"].get("vocab_size"):
cfg["model"]["vocab_size"] = int(cfg["data"]["vocab_size"])
return cfg
def _coerce_model(d: dict) -> dict:
out = asdict(ModelConfig())
for k, v in (d or {}).items():
if k not in out:
raise SystemExit(f"unknown model key {k!r}")
out[k] = v
out["tie_embeddings"] = bool(out["tie_embeddings"])
out["gated_attn"] = bool(out["gated_attn"])
for k in ("vocab_size", "n_layer", "n_head", "d_model", "d_ff", "seq_len", "mup_base_width"):
out[k] = int(out[k])
for k in ("rope_theta", "norm_eps", "init_std", "gate_init"):
out[k] = float(out[k])
return out
# --------------------------------------------------------------------------- #
# Distribution helpers
# --------------------------------------------------------------------------- #
def setup_dist(args_device: str) -> tuple[int, int, int, torch.device, bool]:
"""Return (rank, world, local_rank, device, is_main)."""
world = int(os.environ.get("WORLD_SIZE", "1"))
rank = int(os.environ.get("RANK", "0"))
local_rank = int(os.environ.get("LOCAL_RANK", "0"))
cuda_ok = torch.cuda.is_available()
if args_device == "cpu":
device = torch.device("cpu")
elif args_device == "cuda":
if not cuda_ok:
raise SystemExit("--device cuda requested but CUDA is not available")
device = torch.device("cuda", local_rank)
else:
device = torch.device("cuda", local_rank) if cuda_ok else torch.device("cpu")
if world > 1:
backend = "nccl" if device.type == "cuda" else "gloo"
if device.type == "cuda":
torch.cuda.set_device(device)
dist.init_process_group(backend=backend, rank=rank, world_size=world)
return rank, world, local_rank, device, rank == 0
def seed_all(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
def autocast_ctx(enabled: bool, device: torch.device):
if enabled and device.type == "cuda":
return torch.autocast(device_type="cuda", dtype=torch.bfloat16)
return contextlib.nullcontext()
# --------------------------------------------------------------------------- #
# Evaluation / logging
# --------------------------------------------------------------------------- #
@torch.no_grad()
def evaluate(model: nn.Module, batches: list[tuple[torch.Tensor, torch.Tensor]],
device: torch.device, bf16: bool) -> float:
"""Mean cross-entropy in nats over pre-generated fixed batches."""
model.eval()
total, count = 0.0, 0
for x, y in batches:
with autocast_ctx(bf16, device):
_, loss = model(x, y)
total += float(loss.detach()) * x.numel()
count += x.numel()
model.train()
return total / max(1, count)
def bpb_from_nats(loss_nats: float, bytes_per_token: float) -> float:
return loss_nats / math.log(2) / bytes_per_token
def gpu_mem_mb() -> float:
if torch.cuda.is_available():
return torch.cuda.max_memory_allocated() / (1024 ** 2)
return 0.0
def fmt_int(n: float) -> str:
return f"{n:,.0f}"
# --------------------------------------------------------------------------- #
# Checkpointing
# --------------------------------------------------------------------------- #
def save_ckpt(path: Path, model: nn.Module, opt: torch.optim.Optimizer, cfg: dict,
step: int, tokens_seen: int, best_bpb: float,
data_rng: np.random.Generator | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
raw = model.module if isinstance(model, DDP) else model
tmp = path.with_suffix(path.suffix + ".tmp")
torch.save(
{
"model": raw.state_dict(),
"optim": opt.state_dict(),
"config": cfg,
"step": step,
"tokens_seen": tokens_seen,
"best_bpb": best_bpb,
"torch_rng": torch.get_rng_state(),
"cuda_rng": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None,
"numpy_rng": np.random.get_state(),
"python_rng": random.getstate(),
"data_rng_state": data_rng.bit_generator.state if data_rng is not None else None,
},
tmp,
)
os.replace(tmp, path)
def load_ckpt(path: str, model: nn.Module, opt: torch.optim.Optimizer) -> dict:
ckpt = torch.load(path, map_location="cpu", weights_only=False)
raw = model.module if isinstance(model, DDP) else model
state = ckpt["model"]
# torch.compile() prefixes keys with "_orig_mod."; accept both directions.
want_compiled = any(k.startswith("_orig_mod.") for k in state)
is_compiled = any(k.startswith("_orig_mod.") for k in raw.state_dict())
if want_compiled and not is_compiled:
state = {k.replace("_orig_mod.", "", 1): v for k, v in state.items()}
elif is_compiled and not want_compiled:
state = {f"_orig_mod.{k}": v for k, v in state.items()}
raw.load_state_dict(state)
if "optim" in ckpt and opt is not None:
opt.load_state_dict(ckpt["optim"])
torch.set_rng_state(ckpt["torch_rng"])
if ckpt.get("cuda_rng") and torch.cuda.is_available():
# RNG_PATCH_V1: checkpoint moze biti snimljen na drugom broju GPU-a
try:
torch.cuda.set_rng_state_all(ckpt["cuda_rng"])
except Exception as _e:
print(f"[resume] rng state preskocen: {_e}", flush=True)
np.random.set_state(ckpt["numpy_rng"])
random.setstate(ckpt["python_rng"])
return ckpt
# --------------------------------------------------------------------------- #
# Main
# --------------------------------------------------------------------------- #
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
cfg = load_config(args)
mc = ModelConfig(**cfg["model"])
data_cfg, opt_cfg, run_cfg = cfg["data"], cfg["optim"], cfg["run"]
rank, world, local_rank, device, is_main = setup_dist(args.device)
# CPU thread budget (see run.threads): avoid thrashing a shared, busy host.
threads = int(run_cfg.get("threads") or 0)
if device.type == "cpu":
if threads <= 0:
threads = int(os.environ.get("OMP_NUM_THREADS") or min(4, os.cpu_count() or 4))
torch.set_num_threads(max(1, threads))
if is_main:
print(f"[cpu] threads={torch.get_num_threads()}", flush=True)
seed = int(run_cfg["seed"])
# Each rank gets its own deterministic stream; identical for a fixed world size.
seed_all(seed + rank)
if run_cfg.get("deterministic"):
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
try:
torch.use_deterministic_algorithms(True, warn_only=True)
except Exception:
pass
out_dir = Path(run_cfg["out_dir"])
if is_main:
out_dir.mkdir(parents=True, exist_ok=True)
# ---- muP (approximate) -------------------------------------------------
lr_max = float(opt_cfg["lr"])
if run_cfg.get("mu_p"):
mc, lr_max = apply_mup(mc, lr_max)
if is_main:
print(f"[mup] init_std={mc.init_std:.6f} lr={lr_max:.6g} "
f"(approx: std~1/sqrt(width), lr~1/width, ref width {mc.mup_base_width})", flush=True)
# ---- data --------------------------------------------------------------
train_shards = val_shards = None
if not args.dry_run:
if not data_cfg.get("shards"):
raise SystemExit("data.shards is empty; pass --dry-run for a synthetic smoke test")
train_shards = TokenShards(data_cfg["shards"], data_cfg["dtype"])
if data_cfg.get("val_shards"):
val_shards = TokenShards(data_cfg["val_shards"], data_cfg["dtype"])
if is_main:
print(f"[data] train tokens={fmt_int(train_shards.total)} "
f"shards={len(data_cfg['shards'])} dtype={data_cfg['dtype']}", flush=True)
# Cheap guard against a mismatched tokenizer/vocab.
probe_rng = np.random.default_rng(seed + 99991)
probe = train_shards.sample_tokens(512, probe_rng)
if probe.size and int(probe.max()) >= mc.vocab_size:
raise SystemExit(
f"token id {int(probe.max())} >= vocab_size {mc.vocab_size}: wrong tokenizer, "
f"vocab_size, or data.dtype (currently {data_cfg['dtype']})"
)
elif is_main:
print("[data] dry-run: synthetic uniform tokens (no shards read)", flush=True)
bytes_per_token = float(data_cfg.get("bytes_per_token") or 0.0)
if bytes_per_token <= 0:
raise SystemExit("data.bytes_per_token must be > 0 (needed for val bpb)")
# ---- model -------------------------------------------------------------
model = Transformer(mc).to(device)
n_params = model.num_params()
if is_main:
print(f"[model] params={n_params/1e6:.2f}M (non-emb {model.num_params(True)/1e6:.2f}M) "
f"L={mc.n_layer} d={mc.d_model} h={mc.n_head} ff={mc.d_ff} seq={mc.seq_len} "
f"vocab={mc.vocab_size} tie={mc.tie_embeddings}", flush=True)
if mc.gated_attn:
extra = sum(p.numel() for n, p in model.named_parameters() if n.endswith("attn.gate"))
print(f"gated_attn=True extra_params={extra} "
f"(per-head vector gate: {mc.n_layer}x{mc.n_head}x{mc.d_model // mc.n_head}, "
f"init sigmoid(gate)={torch.sigmoid(torch.tensor(float(mc.gate_init))).item():.4f})",
flush=True)
# ---- optimizer (AdamW; no decay on 1-D params) -------------------------
decay, no_decay = [], []
for name, p in model.named_parameters():
if not p.requires_grad:
continue
(decay if p.dim() >= 2 else no_decay).append(p)
param_groups = [
{"params": decay, "weight_decay": float(opt_cfg["weight_decay"])},
{"params": no_decay, "weight_decay": 0.0},
]
fused = device.type == "cuda"
opt = torch.optim.AdamW(
param_groups,
lr=lr_max,
betas=(float(opt_cfg["beta1"]), float(opt_cfg["beta2"])),
eps=1e-8,
fused=fused,
)
resume_ckpt = None
if args.resume:
resume_ckpt = load_ckpt(args.resume, model, opt)
if is_main:
print(f"[resume] {args.resume} step={resume_ckpt['step']} "
f"tokens={fmt_int(resume_ckpt['tokens_seen'])}", flush=True)
if run_cfg.get("compile") and hasattr(torch, "compile"):
model = torch.compile(model) # type: ignore[assignment]
if world > 1:
model = DDP(model, device_ids=[device.index] if device.type == "cuda" else None,
find_unused_parameters=False)
# ---- token budget ------------------------------------------------------
tokens_per_step = (int(opt_cfg["batch_size"]) * int(opt_cfg["grad_accum"])
* mc.seq_len * world)
max_tokens = int(opt_cfg["max_tokens"])
total_steps = max(1, max_tokens // tokens_per_step)
warmup_tokens = int(opt_cfg["warmup_tokens"])
if warmup_tokens >= max_tokens and is_main:
print(f"[warn] warmup_tokens={warmup_tokens} >= max_tokens={max_tokens}; clamping", flush=True)
warmup_tokens = max_tokens // 20
start_step = int(resume_ckpt["step"]) if resume_ckpt else 0
tokens_seen = int(resume_ckpt["tokens_seen"]) if resume_ckpt else 0
best_bpb = float(resume_ckpt.get("best_bpb", 1e9)) if resume_ckpt else 1e9
if is_main:
print(
f"[run] device={device} world={world} seed={seed}(+rank) "
f"torch={torch.__version__} numpy={np.__version__}\n"
f"[run] steps={total_steps} tokens/step={tokens_per_step} max_tokens={fmt_int(max_tokens)} "
f"warmup_tokens={fmt_int(warmup_tokens)} lr={lr_max:.3g} bf16={run_cfg['bf16']} "
f"mu_p={run_cfg['mu_p']}",
flush=True,
)
# ---- deterministic data streams ---------------------------------------
data_rng = np.random.default_rng(seed * 1_000_003 + rank)
val_rng = np.random.default_rng(seed + 7_000_019)
# Resume continues rank-0's exact sample stream (the checkpoint holds only
# rank 0's RNG state; other ranks reseed identically to a fresh run).
if resume_ckpt and resume_ckpt.get("data_rng_state") is not None:
data_rng.bit_generator.state = resume_ckpt["data_rng_state"]
eval_batches: list[tuple[torch.Tensor, torch.Tensor]] = []
eval_iters = int(run_cfg["eval_iters"])
if val_shards is not None or args.dry_run:
eval_batches = [
make_batch(val_shards, int(opt_cfg["batch_size"]), mc.seq_len, val_rng, device, mc.vocab_size)
for _ in range(eval_iters)
]
if is_main and not eval_batches:
print("[warn] no val_shards: val bpb will be reported as nan", flush=True)
# never start with fewer than a few steps of eval/log budget
log_every = max(1, int(run_cfg["log_every"]))
eval_every = max(1, int(run_cfg["eval_every"]))
ckpt_every = max(1, int(run_cfg["ckpt_every"]))
log_path = out_dir / "train_log.csv"
log_fields = ["step", "wall_s", "tokens", "lr", "train_loss", "val_loss", "val_bpb",
"tok_per_s", "grad_norm", "gpu_mem_mb"]
if is_main and start_step == 0:
with log_path.open("w", newline="") as f:
csv.writer(f).writerow(log_fields)
def log_row(row: dict) -> None:
if not is_main:
return
with log_path.open("a", newline="") as f:
csv.writer(f).writerow([row.get(k, "") for k in log_fields])
# ---- training loop -----------------------------------------------------
model.train()
t0 = time.perf_counter()
t_last = t0
tokens_at_last_log = tokens_seen
loss_acc, loss_n = 0.0, 0
grad_norm_val = float("nan")
last_train_loss = last_val_loss = last_val_bpb = last_grad_norm = float("nan")
for step in range(start_step, total_steps):
lr = lr_at_tokens(tokens_seen, max_tokens, warmup_tokens, lr_max, float(opt_cfg["min_lr_ratio"]))
for g in opt.param_groups:
g["lr"] = lr
opt.zero_grad(set_to_none=True)
micro_losses = []
accum = int(opt_cfg["grad_accum"])
for mi in range(accum):
x, y = make_batch(train_shards, int(opt_cfg["batch_size"]), mc.seq_len,
data_rng, device, mc.vocab_size)
# Skip the all-reduce on accumulation micro-steps (DDP only).
sync_ctx = (model.no_sync() if isinstance(model, DDP) and mi < accum - 1
else contextlib.nullcontext())
with sync_ctx:
with autocast_ctx(bool(run_cfg["bf16"]), device):
_, loss = model(x, y)
(loss / accum).backward()
micro_losses.append(float(loss.detach()))
loss_acc += sum(micro_losses) / len(micro_losses)
loss_n += 1
last_train_loss = loss_acc / loss_n
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), float(opt_cfg["grad_clip"]))
grad_norm_val = last_grad_norm = float(grad_norm)
opt.step()
tokens_seen += tokens_per_step
step_done = step + 1
do_log = step_done % log_every == 0 or step_done == total_steps
do_eval = (step_done % eval_every == 0) or step_done == total_steps
val_loss = val_bpb = float("nan")
if do_eval and eval_batches:
val_loss = evaluate(model, eval_batches, device, bool(run_cfg["bf16"]))
val_bpb = bpb_from_nats(val_loss, bytes_per_token)
best_bpb = min(best_bpb, val_bpb)
last_val_loss, last_val_bpb = val_loss, val_bpb
if do_log and is_main:
now = time.perf_counter()
dt = max(1e-9, now - t_last)
tok_s = (tokens_seen - tokens_at_last_log) / dt
train_loss = loss_acc / max(1, loss_n)
print(
f"step {step_done:>6}/{total_steps} | tok {fmt_int(tokens_seen):>13} | "
f"lr {lr:.3e} | loss {train_loss:.4f} | val_bpb {val_bpb:.4f} | "
f"tok/s {fmt_int(tok_s):>8} | gnorm {grad_norm_val:.3f} | "
f"mem {gpu_mem_mb():.0f}MB | {now - t0:.0f}s",
flush=True,
)
log_row({
"step": step_done, "wall_s": f"{now - t0:.1f}", "tokens": tokens_seen,
"lr": f"{lr:.6e}", "train_loss": f"{train_loss:.5f}",
"val_loss": f"{val_loss:.5f}", "val_bpb": f"{val_bpb:.5f}",
"tok_per_s": f"{tok_s:.1f}", "grad_norm": f"{grad_norm_val:.4f}",
"gpu_mem_mb": f"{gpu_mem_mb():.1f}",
})
t_last, tokens_at_last_log = now, tokens_seen
loss_acc, loss_n = 0.0, 0
if (step_done % ckpt_every == 0 or step_done == total_steps) and not args.dry_run:
if is_main:
save_ckpt(out_dir / "latest.pt", model, opt, cfg, step_done, tokens_seen,
best_bpb, data_rng)
if step_done == total_steps:
save_ckpt(out_dir / f"ckpt_{step_done:07d}.pt", model, opt, cfg,
step_done, tokens_seen, best_bpb, data_rng)
print(f"[ckpt] step {step_done} -> {out_dir/'latest.pt'}", flush=True)
if world > 1:
dist.barrier() # keep ranks in lockstep across the blocking write
if world > 1:
dist.barrier()
dist.destroy_process_group()
if is_main:
wall_s = time.perf_counter() - t0
flops = 6 * n_params * tokens_seen
print(f"[done] steps={total_steps - start_step} tokens={fmt_int(tokens_seen)} "
f"wall={wall_s:.1f}s approx_flops={flops:.3e} log={log_path}", flush=True)
if tokens_seen:
print(f"[done] tokens/s total={tokens_seen / max(1e-9, wall_s):.0f}", flush=True)
# Contract with infra/run_noise_floor.sh: <out-dir>/metrics.json must
# exist and contain a float "val_bpb" for this run.
metrics = {
"exp_id": out_dir.name,
"arm": str(run_cfg.get("arm") or (Path(args.config).stem if args.config else "custom")),
"seed": seed,
"status": "done",
"dry_run": bool(args.dry_run),
"steps": total_steps - start_step,
"tokens": tokens_seen,
"wall_s": round(wall_s, 2),
"tok_per_s": round(tokens_seen / max(1e-9, wall_s), 1),
"train_loss": last_train_loss,
"val_loss": last_val_loss,
"val_bpb": last_val_bpb,
"best_val_bpb": best_bpb if best_bpb < 1e8 else None,
"grad_norm": last_grad_norm,
"lr_final": lr_at_tokens(tokens_seen, max_tokens, warmup_tokens, lr_max,
float(opt_cfg["min_lr_ratio"])),
"params": n_params,
"flops_approx": flops,
"bytes_per_token": bytes_per_token,
"mu_p": bool(run_cfg.get("mu_p")),
"world_size": world,
"device": str(device),
"gpu_mem_mb": round(gpu_mem_mb(), 1),
"torch": torch.__version__,
"log_csv": str(log_path),
"config": cfg,
}
metrics_path = out_dir / "metrics.json"
tmp = metrics_path.with_suffix(".json.tmp")
tmp.write_text(json.dumps(metrics, indent=2, default=str))
os.replace(tmp, metrics_path)
print(f"[done] metrics -> {metrics_path}", flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())