From 0ab7cafc0c1074785eb6723a7e4baa2a0eae6c31 Mon Sep 17 00:00:00 2001 From: Harsh Soni Date: Sat, 28 Mar 2026 07:56:09 +0000 Subject: [PATCH 1/9] =?UTF-8?q?12L=20INT4=20bQAT=20+=20Value=20Embeddings?= =?UTF-8?q?=20=E2=80=94=20val=5Fbpb=201.1588?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-03-28_12L_INT4_bQAT_VE/README.md | 83 + .../submission.json | 9 + .../2026-03-28_12L_INT4_bQAT_VE/train_gpt.py | 1749 +++++++++++++++++ run.sh | 274 +++ train_gpt_v2.py | 1749 +++++++++++++++++ 5 files changed, 3864 insertions(+) create mode 100644 records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md create mode 100644 records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/submission.json create mode 100644 records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/train_gpt.py create mode 100644 run.sh create mode 100644 train_gpt_v2.py diff --git a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md new file mode 100644 index 0000000000..e75fd46359 --- /dev/null +++ b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md @@ -0,0 +1,83 @@ +# 12L INT4 bQAT + EMA Fix + Value Embeddings + +**val_bpb: 1.1588** (seed 1, full TTT) | **16.29 MB** | 8×H100 SXM + +## Results (8×H100 80GB SXM) + +| Seed | step_avg | steps | Pre-quant val/bpb | Post-quant bpb | Post-TTT bpb | Artifact | +|------|----------|-------|-------------------|----------------|--------------|----------| +| 1 | ~137ms | ~4380 | 1.1754 | 1.1643 | **1.1588** | 16,290,425 | + +## Architecture + +| Component | Setting | +|-----------|---------| +| Layers | 12 (512d, 8H, 4KV) | +| MLP | 3× with LeakyReLU(0.5)² | +| BigramHash | 10240 buckets, INT4 bQAT | +| XSA | Last 4 layers | +| RoPE | Partial (16/64 dims) | +| LN Scale | 1/√(layer+1) | +| Skip | U-Net skip connections | +| resid_mix | Learnable x/x₀ blend | +| Weight avg | EMA(0.997) with QAT-activation reset | +| Quantization | INT4 MLP + INT4 bigram + INT6 attn + zstd | +| QAT trigger | Wallclock fraction (65% of budget) | +| Value Embeddings | ve_dim=128, layers 10-11 | +| TTT | Legal score-first, lr=0.002, 3 epochs | + +## Key Addition: Value Embeddings + +Value embeddings reinject token identity into the V vectors at specific attention layers. At layers 10 and 11, a shared embedding `ve_shared` (vocab×128) is looked up per token and projected to kv_dim (256), then added to the raw V output before attention: + +``` +v_raw = c_v(x) +v_embed = ve_shared.proj(ve_shared.embed(tokens)) # (batch, seq, kv_dim) +v = v_raw + v_embed +``` + +The shared embedding allows all VE layers to benefit from a single (vocab, 128) table without per-layer weight cost. + +**Effect:** VE improved quality by ~0.014 BPB per step vs baseline at step 2000 (1.2344 vs 1.2481). Despite 640 fewer total steps (4380 vs 5021 for v4_h100 seed 1), the per-step quality gain resulted in a new best ttt_bpb. + +## Comparison with Previous Best + +| Run | steps | Pre-quant | Post-quant | TTT bpb | +|-----|-------|-----------|------------|---------| +| v4_h100 seed 1 | 5021 | 1.1683 | 1.1703 | ~1.165 | +| v4_h100 seed 3 | — | 1.1729 | 1.2002 | 1.1594 | +| **v7_ve seed 1** | ~4380 | 1.1754 | **1.1643** | **1.1588** | + +Note: v7_ve's post_quant (1.1643) is better than its pre-quant checkpoint (1.1754) because the model continued improving during QAT after the last val checkpoint. + +## Size Budget + +| Component | Bytes | +|-----------|-------| +| Base model (int4/int6/zstd) | ~15,967,640 | +| Value embeddings (int8/int4/zstd) | ~322,785 | +| **Total** | **16,290,425** | + +Budget: 16,777,216 bytes (16MB) — **486,791 bytes (475KB) margin** + +## Run Command + +```bash +SEED=1 VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 \ +LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ +NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ +ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ +torchrun --standalone --nproc_per_node=8 train_gpt.py +``` + +## Credits + +- LeakyReLU² activation: PR #493, PR #518 +- XSA (Cross-layer Shared Attention): PR #414 +- EMA weight averaging: PR #374 +- Legal TTT recipe: PR #461 +- INT5/INT6 QAT with STE: PR #317, PR #374 +- BigramHash embedding: PR #320 +- U-Net skip connections: PR #363 +- resid_mix: prior work in this repo +- Value embeddings: PR #549 diff --git a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/submission.json b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/submission.json new file mode 100644 index 0000000000..10e3cb2bea --- /dev/null +++ b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/submission.json @@ -0,0 +1,9 @@ +{ + "name": "12L INT4 bQAT + EMA Fix + Value Embeddings", + "val_bpb": 1.1588, + "bytes_total": 16290425, + "blurb": "12-layer INT4 MLP+bigram QAT + U-Net skips + XSA(last 4) + EMA(0.997) with QAT-reset fix + LeakyReLU² + RoPE16 + LN Scale + resid_mix + Legal TTT + Value Embeddings (ve_dim=128, last 2 layers). Value embeddings reinject token identity into V at layers 10-11, improving quality per step. Step_avg ~137ms, ~4380 steps in 10 min. Post-quant degradation very clean (1.1643 from 1.1754 pre-quant). 8×H100 seed 1: ttt_bpb=1.15875.", + "author": "Harsh Soni", + "github_id": "SoHarshh", + "date": "2026-03-28" +} diff --git a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/train_gpt.py b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/train_gpt.py new file mode 100644 index 0000000000..2986b1685c --- /dev/null +++ b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/train_gpt.py @@ -0,0 +1,1749 @@ +from __future__ import annotations + +import copy +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import uuid +import zlib +from pathlib import Path + +try: + import zstandard + _COMPRESSOR = "zstd" +except ImportError: + _COMPRESSOR = "zlib" + +try: + import wandb + _WANDB_AVAILABLE = True +except ImportError: + _WANDB_AVAILABLE = False + +import numpy as np +import sentencepiece as spm +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import Tensor, nn +from torch.nn.parallel import DistributedDataParallel as DDP + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- + +class Hyperparameters: + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024") + train_files = os.path.join(data_path, "fineweb_train_*.bin") + val_files = os.path.join(data_path, "fineweb_val_*.bin") + tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 42)) + + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 500)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 100)) + + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3000)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 786_432)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2048)) + max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + + vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) + num_layers = int(os.environ.get("NUM_LAYERS", 10)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 4)) + model_dim = int(os.environ.get("MODEL_DIM", 512)) + num_heads = int(os.environ.get("NUM_HEADS", 8)) + mlp_mult = float(os.environ.get("MLP_MULT", 3.0)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.008)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.03)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.02)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.02)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.3)) + weight_decay = float(os.environ.get("WEIGHT_DECAY", 0.04)) + + eval_stride = int(os.environ.get("EVAL_STRIDE", 64)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 32)) + + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + trigram_vocab_size = int(os.environ.get("TRIGRAM_VOCAB_SIZE", 0)) # 0 = disabled + trigram_dim = int(os.environ.get("TRIGRAM_DIM", 64)) + + swa_enabled = bool(int(os.environ.get("SWA_ENABLED", "1"))) + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.4)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + + # EMA: exponential moving average of weights (replaces SWA when enabled) + ema_enabled = bool(int(os.environ.get("EMA_ENABLED", "0"))) + ema_decay = float(os.environ.get("EMA_DECAY", "0.997")) + + # QAT: fake-quantize weights during training to match PTQ targets + # MLP precision: INT4 (clip=7) or INT5 (clip=15, default); INT6 for attention (clip=31) + qat_enabled = bool(int(os.environ.get("QAT_ENABLED", "1"))) + mlp_quant_bits = int(os.environ.get("MLP_QUANT_BITS", "5")) # 4 or 5 + + # XSA: Cross-Sequence Attention on last N layers (subtracts self-value projection) + xsa_last_n = int(os.environ.get("XSA_LAST_N", 0)) + + # Partial RoPE: apply RoPE to only first rope_dims dims of head_dim (0 = full) + rope_dims = int(os.environ.get("ROPE_DIMS", 0)) + + # LN Scale: scale norm input by 1/sqrt(layer_idx+1) for depth stability + ln_scale = bool(int(os.environ.get("LN_SCALE", "0"))) + + # Late QAT: delay fake-quantize until LR scale drops below threshold (0 = from start) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", "0")) + + # ValueEmbedding: reinject token identity into V at last N layers (0 = disabled) + value_embed_layers = int(os.environ.get("VALUE_EMBED_LAYERS", "0")) + value_embed_dim = int(os.environ.get("VALUE_EMBED_DIM", "64")) + + # TTT: Legal score-first test-time training at final eval + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "0"))) + ttt_lr = float(os.environ.get("TTT_LR", "0.002")) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", "3")) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", "32768")) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", "0")) + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", "0.9")) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", "32")) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", "1.0")) + +# ----------------------------- +# MUON OPTIMIZER — Parallel Muon (async reduce-scatter → sharded NS5 → all-gather) +# ----------------------------- + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 5, eps: float = 1e-7) -> Tensor: + """Batched Newton-Schulz orthogonalization. Accepts (B,M,N) or (M,N).""" + a, b, c = (3.4445, -4.7750, 2.0315) + was_2d = G.ndim == 2 + if was_2d: + G = G.unsqueeze(0) + X = G.bfloat16() + transposed = X.size(-2) > X.size(-1) + if transposed: + X = X.mT + X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps) + for _ in range(steps): + A = X @ X.mT + B = b * A + c * (A @ A) + X = a * X + B @ X + if transposed: + X = X.mT + if was_2d: + X = X.squeeze(0) + return X + + +class Muon(torch.optim.Optimizer): + """Muon — MomentUm Orthogonalized by Newton-schulz. + + Works with DDP: DDP handles gradient averaging during backward. + NS5 runs sequentially on the already-averaged gradients. + launch_reduce_scatters() is a no-op stub (DDP handles sync). + + Falls back identically on single-GPU proxy runs. + """ + def __init__(self, params, lr: float, momentum: float, backend_steps: int, + nesterov: bool = True, weight_decay: float = 0.0): + super().__init__( + params, + dict(lr=lr, momentum=momentum, backend_steps=backend_steps, + nesterov=nesterov, weight_decay=weight_decay), + ) + + def launch_reduce_scatters(self) -> None: + pass # No-op: DDP handles gradient sync during backward + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + for group in self.param_groups: + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + wd = group.get("weight_decay", 0.0) + for p in group["params"]: + if p.grad is None: + continue + g = p.grad.bfloat16() + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(g) + update = g.add(buf, alpha=momentum) if nesterov else buf.clone() + update = zeropower_via_newtonschulz5(update, steps=backend_steps) + if wd > 0.0: + p.data.mul_(1.0 - lr * wd) + scale = max(1, p.shape[-2] / p.shape[-1]) ** 0.5 + p.add_(update.to(dtype=p.dtype), alpha=-lr * scale) + return loss + + +def _apply_vbank_update(vb: dict, lr: float, wd: float) -> None: + pass # unused stub kept for import compatibility + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION +# ----------------------------- + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("\u2581"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return ( + torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device), + ) + + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError( + "VAL_BATCH_SIZE must provide at least one sequence per rank; " + f"got VAL_BATCH_SIZE={args.val_batch_size}, WORLD_SIZE={world_size}, " + f"GRAD_ACCUM_STEPS={grad_accum_steps}, TRAIN_SEQ_LEN={args.train_seq_len}" + ) + local_batch_seqs = local_batch_tokens // args.train_seq_len + total_seqs = (val_tokens.numel() - 1) // args.train_seq_len + seq_start = (total_seqs * rank) // world_size + seq_end = (total_seqs * (rank + 1)) // world_size + val_loss_sum = torch.zeros((), device=device, dtype=torch.float64) + val_token_count = torch.zeros((), device=device, dtype=torch.float64) + val_byte_count = torch.zeros((), device=device, dtype=torch.float64) + model.eval() + with torch.inference_mode(): + for batch_seq_start in range(seq_start, seq_end, local_batch_seqs): + batch_seq_end = min(batch_seq_start + local_batch_seqs, seq_end) + raw_start = batch_seq_start * args.train_seq_len + raw_end = batch_seq_end * args.train_seq_len + 1 + local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True) + x = local[:-1].reshape(-1, args.train_seq_len) + y = local[1:].reshape(-1, args.train_seq_len) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + batch_loss = model(x, y).detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +# ----------------------------- +# QUANTIZATION (INT5 MLP / INT6 ATTN mixed PTQ) +# ----------------------------- + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights,smear,bigram.scale,trigram.scale,ve_layer_scales,ve_shared.scale", + ).split(",") + if pattern +) +FP16_KEEP_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get("FP16_KEEP_NAME_PATTERNS", "tok_emb,blocks.8.attn.c_k").split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 + +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + INT8_CLIP_Q = 99.99984 / 100.0 + t32 = t.float() + if t32.ndim == 2: + clip_abs = ( + torch.quantile(t32.abs(), INT8_CLIP_Q, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + clipped = torch.maximum(torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None]) + scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) + q = torch.clamp(torch.round(clipped / scale[:, None]), -127, 127).to(torch.int8).contiguous() + return q, scale.to(dtype=torch.float16).contiguous() + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127).to(torch.int8).contiguous() + return q, scale + + +def _classify_param(name: str) -> str: + if "tok_emb" in name or "lm_head" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if "bigram" in name: + return "bigram" + if "trigram" in name: + return "trigram" + if ".attn." in name or (".proj." in name and ".mlp." not in name): + return "attn" + return "other" + + +def quantize_intN_per_row(t: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + """Quantize with GPTQ-lite: search 5 clip percentiles, pick best MSE.""" + t32 = t.float() + if t32.ndim == 2: + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 0.99999, 1.0]: + if pct < 1.0: + row_clip = torch.quantile(t32.abs(), pct, dim=1) + else: + row_clip = t32.abs().amax(dim=1) + scale = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + scale = scale.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(t32 / scale.float()[:, None]), -(clip_range + 1), clip_range).to(torch.int8) + err = (t32 - q.float() * scale.float()[:, None]).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, scale, err + return best_q, best_s + amax = t32.abs().max().item() + scale = torch.tensor(max(amax / clip_range, 1e-12), dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -(clip_range + 1), clip_range).to(torch.int8) + return q, scale + + +def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15): + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param(name) + if not t.is_floating_point() or t.numel() <= 8192: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + if any(pattern in name for pattern in FP16_KEEP_NAME_PATTERNS): + result[name] = t.to(dtype=torch.float16).contiguous() + meta[name] = "passthrough_fp16" + continue + if cat in int6_cats and t.ndim >= 1: + # MLP: always uses mlp_clip (INT4 or INT5) + # bigram/trigram: follow mlp_clip when INT4 (saves ~0.25MB), else INT6 + # attn and others: INT6 + if cat == "mlp": + clip = mlp_clip + elif cat in ("bigram", "trigram") and mlp_clip <= 7: + clip = mlp_clip # INT4 bigram/trigram when MLP is INT4 + else: + clip = 31 # INT6 for attn, bigram/trigram in INT5 mode + q, s = quantize_intN_per_row(t, clip_range=clip) + result[name + ".q"] = q + result[name + ".scale"] = s + bits = clip.bit_length() + 1 # clip=31→int6, clip=15→int5, clip=7→int4 + meta[name] = {"type": f"int{bits}"} + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return result, meta + + +def dequantize_mixed_int6(result: dict[str, Tensor], meta: dict[str, object], + template_sd: dict[str, Tensor]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + for name, orig in template_sd.items(): + info = meta[name] + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl", "passthrough_fp16"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + + +# ----------------------------- +# DATA LOADING +# ----------------------------- + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = rank + self.world_size = world_size + self.device = device + self.stream = TokenStream(pattern) + + def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> tuple[Tensor, Tensor]: + local_tokens = global_tokens // (self.world_size * grad_accum_steps) + per_rank_span = local_tokens + 1 + chunk = self.stream.take(per_rank_span * self.world_size) + start = self.rank * per_rank_span + local = chunk[start : start + per_rank_span].to(dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + return x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) + + +# ----------------------------- +# TRANSFORMER MODULES +# ----------------------------- + +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + + +class CastedLinear(nn.Linear): + # _qat_clip_range: 127=off/INT8, 31=INT6, 15=INT5 + _qat_clip_range: int = 127 + + def forward(self, x: Tensor) -> Tensor: + w = self.weight + if self.training and self._qat_clip_range < 127 and w.ndim == 2: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w.to(x.dtype), bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int = 0): + super().__init__() + self.rope_dims = rope_dims if rope_dims > 0 else dim + rd = self.rope_dims + inv_freq = 1.0 / (base ** (torch.arange(0, rd, 2, dtype=torch.float32) / rd)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + rd = cos.size(-1) * 2 + if rd < x.size(-1): # partial RoPE: rotate first rd dims, pass rest unchanged + x_rope, x_pass = x[..., :rd], x[..., rd:] + half = rd // 2 + x1, x2 = x_rope[..., :half], x_rope[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + + +class CausalSelfAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, rope_base: float, qk_gain_init: float, rope_dims: int = 0): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base, rope_dims=rope_dims) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + """XSA: subtract self-value projection, forcing heads to attend to OTHER tokens.""" + B, T, H, D = y.shape + Hkv = v.size(2) # v is [B, T, Hkv, D] + group = H // Hkv + y_g = y.reshape(B, T, Hkv, group, D) + vn = F.normalize(v, dim=-1).unsqueeze(3) # [B, T, Hkv, 1, D] + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v_raw = self.c_v(x) + if v_embed is not None: + v_raw = v_raw + v_embed + v_bthd = v_raw.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + v = v_bthd.transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention( + q, k, v, attn_mask=None, is_causal=True, + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + y = y.transpose(1, 2).contiguous() # [B, T, H, D] + if self.use_xsa: + y = self._xsa_efficient(y, v_bthd) + y = y.reshape(bsz, seqlen, dim) + return self.proj(y) + + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: float): + super().__init__() + hidden = int(mlp_mult * dim) + self.fc = CastedLinear(dim, hidden, bias=False) + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + + def forward(self, x: Tensor) -> Tensor: + x = F.leaky_relu(self.fc(x), negative_slope=0.5) + return self.proj(x.square()) + + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate.to(dtype=x.dtype))[None, None, :] + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1 - g) * x + g * x_prev + + +class BigramHashEmbedding(nn.Module): + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, bigram_vocab_size: int, bigram_dim: int, model_dim: int): + super().__init__() + self.bigram_vocab_size = bigram_vocab_size + self.embed = nn.Embedding(bigram_vocab_size, bigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(bigram_dim, model_dim, bias=False) if bigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.05, dtype=torch.float32)) + + def bigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.bigram_vocab_size - 1 + out = torch.empty_like(t) + out[..., 0] = mod + out[..., 1:] = torch.bitwise_xor(36313 * t[..., 1:], 27191 * t[..., :-1]) % mod + return out.long() + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.bigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class TrigramHashEmbedding(nn.Module): + """3-gram context embedding: (prev2, prev1, curr) → hashed bucket → learned embedding.""" + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, trigram_vocab_size: int, trigram_dim: int, model_dim: int): + super().__init__() + self.trigram_vocab_size = trigram_vocab_size + self.embed = nn.Embedding(trigram_vocab_size, trigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(trigram_dim, model_dim, bias=False) if trigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.02, dtype=torch.float32)) + + def trigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.trigram_vocab_size - 1 + out = torch.full_like(t, mod, dtype=torch.long) # sentinel for positions without full context + out[..., 2:] = ( + torch.bitwise_xor( + torch.bitwise_xor(17291 * t[..., 2:], 36313 * t[..., 1:-1]), + 27191 * t[..., :-2], + ) % mod + ) + return out + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.trigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class ValueEmbedding(nn.Module): + """Reinject token identity into attention values at specific layers. + Shared embedding table + per-layer learned scale. Applied at last N layers.""" + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int): + super().__init__() + self.embed = nn.Embedding(vocab_size, ve_dim) + nn.init.normal_(self.embed.weight, std=0.01) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) if ve_dim != kv_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.1, dtype=torch.float32)) + + def forward(self, token_ids: Tensor) -> Tensor: + h = self.embed(token_ids) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class Block(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, mlp_mult: float, rope_base: float, qk_gain_init: float, rope_dims: int = 0, ln_scale: bool = False, layer_idx: int = 0): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, rope_dims=rope_dims) + self.mlp = MLP(dim, mlp_mult) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + + def forward(self, x: Tensor, x0: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + s = self.ln_scale_factor + attn_out = self.attn(self.attn_norm(x) * s, v_embed=v_embed) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * s) + return x + + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_layers: int, + model_dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: float, + tie_embeddings: bool, + tied_embed_init_std: float, + logit_softcap: float, + rope_base: float, + qk_gain_init: float, + bigram_vocab_size: int = 0, + bigram_dim: int = 128, + trigram_vocab_size: int = 0, + trigram_dim: int = 64, + rope_dims: int = 0, + ln_scale: bool = False, + xsa_last_n: int = 0, + value_embed_layers: int = 0, + value_embed_dim: int = 64, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.bigram = BigramHashEmbedding(bigram_vocab_size, bigram_dim, model_dim) if bigram_vocab_size > 0 else None + self.trigram = TrigramHashEmbedding(trigram_vocab_size, trigram_dim, model_dim) if trigram_vocab_size > 0 else None + self.num_encoder_layers = num_layers // 2 + self.num_decoder_layers = num_layers - self.num_encoder_layers + self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers) + self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32)) + self.smear = SmearGate(model_dim) + self.blocks = nn.ModuleList( + [ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init, + rope_dims=rope_dims, ln_scale=ln_scale, layer_idx=i) + for i in range(num_layers) + ] + ) + if xsa_last_n > 0: + for i in range(max(0, num_layers - xsa_last_n), num_layers): + self.blocks[i].attn.use_xsa = True + # ValueEmbedding: shared table + per-layer scales for last N layers + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve_layer_indices = list(range(max(0, num_layers - value_embed_layers), num_layers)) if value_embed_layers > 0 else [] + if self.ve_layer_indices: + self.ve_shared = ValueEmbedding(vocab_size, value_embed_dim, kv_dim) + self.ve_layer_scales = nn.ParameterList( + [nn.Parameter(torch.ones(1, dtype=torch.float32)) for _ in self.ve_layer_indices] + ) + else: + self.ve_shared = None + self.ve_layer_scales = nn.ParameterList() + self.final_norm = RMSNorm() + self.lm_head = None if tie_embeddings else CastedLinear(model_dim, vocab_size, bias=False) + if self.lm_head is not None: + self.lm_head._zero_init = True + self._init_weights() + + def _init_weights(self) -> None: + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) + num_layers = len(self.blocks) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and module.weight.shape[0] >= 64 and module.weight.shape[1] >= 64: + nn.init.orthogonal_(module.weight, gain=1.0) + if ".proj." in name or name.endswith(".proj"): + with torch.no_grad(): + module.weight.mul_(1.0 / math.sqrt(2 * num_layers)) + + def _get_ve(self, layer_idx: int, ve_base: "Tensor | None") -> "Tensor | None": + if ve_base is None or layer_idx not in self.ve_layer_indices: + return None + idx = self.ve_layer_indices.index(layer_idx) + return ve_base * self.ve_layer_scales[idx].to(dtype=ve_base.dtype) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x = self.blocks[self.num_encoder_layers + i](x, x0, v_embed=self._get_ve(self.num_encoder_layers + i, ve_base)) + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x = self.blocks[self.num_encoder_layers + i](x, x0, v_embed=self._get_ve(self.num_encoder_layers + i, ve_base)) + x = self.final_norm(x) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + logits_proj = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + + +def eval_val_sliding( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, + stride: int, + batch_seqs: int = 32, +) -> tuple[float, float]: + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + total_windows = len(window_starts) + my_s = (total_windows * rank) // world_size + my_e = (total_windows * (rank + 1)) // world_size + my_windows = window_starts[my_s:my_e] + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk[:-1] + y_batch[i, :wlen] = chunk[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt = y_batch[i, s:wlen] + prev = x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + running_bpb = 0.0 + if token_count.item() > 0: + rl = (loss_sum / token_count).item() + running_bpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) + print(f" sliding_eval [{pct:5.1f}%] {done}/{len(my_windows)} windows running_bpb={running_bpb:.6f}", flush=True) + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + bits_per_token = val_loss / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + base_model.train() + return val_loss, bits_per_token * tokens_per_byte + + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: nn.Module, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + """Legal score-first TTT: score each chunk with sliding windows, then train on it. + Every token is scored BEFORE any update that could use it (PR #461 recipe).""" + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + ttt_chunk = args.ttt_chunk_tokens + + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + + num_chunks = (total_tokens + ttt_chunk - 1) // ttt_chunk + chunk_windows: list[list[int]] = [[] for _ in range(num_chunks)] + for ws in window_starts: + end = min(ws + seq_len, total_tokens) + wlen = end - ws + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_start = ws + s + ci = min(scored_start // ttt_chunk, num_chunks - 1) + chunk_windows[ci].append(ws) + + log0(f"ttt_sliding:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"total_windows={len(window_starts)} stride={stride} " + f"ttt_lr={args.ttt_lr} ttt_epochs={args.ttt_epochs} " + f"freeze_blocks={args.ttt_freeze_blocks}") + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + log0(f"ttt_sliding:params unfrozen={sum(p.numel() for p in ttt_params)} " + f"frozen={sum(p.numel() for p in base_model.parameters() if not p.requires_grad)}") + + optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) + t0 = time.perf_counter() + + for ci in range(num_chunks): + windows = chunk_windows[ci] + if not windows: + continue + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + my_s = (len(windows) * rank) // world_size + my_e = (len(windows) * (rank + 1)) // world_size + my_windows = windows[my_s:my_e] + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk_tok = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk_tok[:-1] + y_batch[i, :wlen] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt, prev = y_batch[i, s:wlen], x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + my_seq_s = (chunk_seqs * rank) // world_size + my_seq_e = (chunk_seqs * (rank + 1)) // world_size + my_chunk_seqs = my_seq_e - my_seq_s + for _ep in range(args.ttt_epochs): + for bs in range(0, my_chunk_seqs, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_chunk_seqs) + actual_bs = my_seq_s + bs + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + (my_seq_s + be) * seq_len + 1 + if end_tok > val_tokens.numel(): + continue + local = val_tokens[start_tok:end_tok].to(device=device, dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + optimizer.zero_grad(set_to_none=True) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + loss = base_model(x, y) + loss.backward() + if world_size > 1: + for p in ttt_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) if token_count.item() > 0 else 0.0 + log0(f" ttt_chunk [{ci+1}/{num_chunks}] bpb={rbpb:.6f} time={elapsed:.1f}s") + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + val_bpb = val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.eval() + + log0(f"ttt_sliding:done val_loss={val_loss:.6f} val_bpb={val_bpb:.6f} " + f"elapsed={time.perf_counter() - t0:.1f}s") + return val_loss, val_bpb + + +# ----------------------------- +# TRAINING +# ----------------------------- + +def main() -> None: + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + # Parallel Muon uses batched bmm — do NOT torch.compile NS5 (bmm is already efficient) + + distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size <= 0: + raise ValueError(f"WORLD_SIZE must be positive, got {world_size}") + if 8 % world_size != 0: + raise ValueError(f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral") + grad_accum_steps = 8 // world_size + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + + logfile = None + wandb_enabled = False + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + if _WANDB_AVAILABLE and bool(int(os.environ.get("WANDB_ENABLED", "1"))): + wandb.init( + project=os.environ.get("WANDB_PROJECT", "parameter-golf"), + name=args.run_id, + config={ + "num_layers": args.num_layers, + "model_dim": args.model_dim, + "mlp_mult": args.mlp_mult, + "num_heads": args.num_heads, + "num_kv_heads": args.num_kv_heads, + "mlp_quant_bits": args.mlp_quant_bits, + "iterations": args.iterations, + "train_batch_tokens": args.train_batch_tokens, + "train_seq_len": args.train_seq_len, + "xsa_last_n": args.xsa_last_n, + "ema_enabled": args.ema_enabled, + "rope_dims": args.rope_dims, + "ln_scale": args.ln_scale, + "late_qat_threshold": args.late_qat_threshold, + "ttt_enabled": args.ttt_enabled, + "bigram_vocab_size": args.bigram_vocab_size, + "value_embed_layers": args.value_embed_layers, + "value_embed_dim": args.value_embed_dim, + "seed": args.seed, + }, + resume="allow", + ) + wandb_enabled = True + + def log0(msg: str, console: bool = True) -> None: + if not master_process: + return + if console: + print(msg) + if logfile is not None: + with open(logfile, "a", encoding="utf-8") as f: + print(msg, file=f) + + log0(code, console=False) + log0("=" * 100, console=False) + log0(f"Running Python {sys.version}", console=False) + log0(f"Running PyTorch {torch.__version__}", console=False) + log0( + subprocess.run(["nvidia-smi"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout, + console=False, + ) + log0("=" * 100, console=False) + + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + + if not args.tokenizer_path.endswith(".model"): + raise ValueError(f"Script only setup for SentencePiece .model file: {args.tokenizer_path}") + sp = spm.SentencePieceProcessor(model_file=args.tokenizer_path) + if int(sp.vocab_size()) != args.vocab_size: + raise ValueError( + f"VOCAB_SIZE={args.vocab_size} does not match tokenizer vocab_size={int(sp.vocab_size())}" + ) + dataset_dir = Path(args.data_path).resolve() + actual_train_files = len(list(dataset_dir.glob("fineweb_train_*.bin"))) + val_tokens = load_validation_tokens(args.val_files, args.train_seq_len) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = build_sentencepiece_luts( + sp, args.vocab_size, device + ) + log0(f"val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path={args.tokenizer_path}") + log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}") + log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}") + + # MODEL SETUP + base_model = GPT( + vocab_size=args.vocab_size, + num_layers=args.num_layers, + model_dim=args.model_dim, + num_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + mlp_mult=args.mlp_mult, + tie_embeddings=args.tie_embeddings, + tied_embed_init_std=args.tied_embed_init_std, + logit_softcap=args.logit_softcap, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + bigram_vocab_size=args.bigram_vocab_size, + bigram_dim=args.bigram_dim, + trigram_vocab_size=args.trigram_vocab_size, + trigram_dim=args.trigram_dim, + rope_dims=args.rope_dims, + ln_scale=args.ln_scale, + xsa_last_n=args.xsa_last_n, + value_embed_layers=args.value_embed_layers, + value_embed_dim=args.value_embed_dim, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + + # QAT: set per-layer fake-quantization targets + # MLP precision controlled by MLP_QUANT_BITS (4=INT4 clip=7, 5=INT5 clip=15) + mlp_clip = (1 << (args.mlp_quant_bits - 1)) - 1 # 5→15, 4→7 + ngram_clip = mlp_clip if args.mlp_quant_bits <= 4 else 31 # INT4 bigram/trigram when MLP is INT4 + _qat_active = False # tracks whether fake-quant has been activated + + def _enable_qat() -> None: + nonlocal _qat_active, ema_state + if _qat_active: + return + _qat_active = True + # Reset EMA so it only accumulates QAT-adapted weights (prevents pre-QAT contamination) + if args.ema_enabled and ema_state is not None: + ema_state = None + log0("qat:ema_reset (EMA will restart from current QAT weights)") + for name, module in base_model.named_modules(): + if isinstance(module, CastedLinear): + if ".mlp." in name: + module._qat_clip_range = mlp_clip + elif ".attn." in name: + module._qat_clip_range = 31 + elif "bigram" in name or "trigram" in name: + module._qat_clip_range = ngram_clip + else: + module._qat_clip_range = 31 + if base_model.bigram is not None: + base_model.bigram._qat_clip_range = ngram_clip + if base_model.trigram is not None: + base_model.trigram._qat_clip_range = ngram_clip + ngram_bits = '4' if ngram_clip <= 7 else '6' + trig_str = f" trigram=INT{ngram_bits}(clip={ngram_clip})" if base_model.trigram is not None else "" + log0(f"qat:enabled mlp=INT{args.mlp_quant_bits}(clip={mlp_clip}) attn=INT6(clip=31) bigram=INT{ngram_bits}(clip={ngram_clip}){trig_str}") + + if args.qat_enabled: + if args.late_qat_threshold > 0: + log0(f"qat:late_qat threshold={args.late_qat_threshold} (activates when lr_scale < threshold)") + else: + _enable_qat() + else: + log0("qat:disabled") + + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + if distributed: + model: nn.Module = DDP(compiled_model, device_ids=[device.index]) + else: + model = compiled_model + + # OPTIMIZER SETUP + block_named_params = list(base_model.blocks.named_parameters()) + matrix_params = [ + p for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + scalar_params.append(base_model.smear.gate) + if base_model.bigram is not None: + scalar_params.append(base_model.bigram.scale) + if base_model.trigram is not None: + scalar_params.append(base_model.trigram.scale) + + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + tok_params = [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}] + if base_model.bigram is not None: + tok_params.append({"params": [base_model.bigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.bigram.proj is not None: + matrix_params.append(base_model.bigram.proj.weight) + if base_model.trigram is not None: + tok_params.append({"params": [base_model.trigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.trigram.proj is not None: + matrix_params.append(base_model.trigram.proj.weight) + if base_model.ve_shared is not None: + tok_params.append({"params": [base_model.ve_shared.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.ve_shared.proj is not None: + matrix_params.append(base_model.ve_shared.proj.weight) + scalar_params.append(base_model.ve_shared.scale) + for s in base_model.ve_layer_scales: + scalar_params.append(s) + + optimizer_tok = torch.optim.AdamW( + tok_params, + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=0.04, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params}") + if base_model.ve_shared is not None: + log0(f"value_embed:layers={base_model.ve_layer_indices} ve_dim={args.value_embed_dim} kv_dim={base_model.ve_shared.proj.out_features if base_model.ve_shared.proj else args.value_embed_dim}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0(f"sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + # DATA LOADER & WARMUP + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + + max_wallclock_ms = 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0 + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 + + if args.warmup_steps > 0: + initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()} + initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers] + model.train() + for warmup_step in range(args.warmup_steps): + zero_grad_all() + for micro_step in range(grad_accum_steps): + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + warmup_loss = model(x, y) + (warmup_loss * grad_scale).backward() + # Without DDP: manually all-reduce all grads for warmup (simple, only 20 steps) + if distributed: + for p in base_model.parameters(): + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + for opt in optimizers: + opt.step() + zero_grad_all() + if args.warmup_steps <= 20 or (warmup_step + 1) % 10 == 0 or warmup_step + 1 == args.warmup_steps: + log0(f"warmup_step:{warmup_step + 1}/{args.warmup_steps}") + base_model.load_state_dict(initial_model_state, strict=True) + for opt, state in zip(optimizers, initial_optimizer_states, strict=True): + opt.load_state_dict(state) + zero_grad_all() + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + # MAIN TRAINING LOOP + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + # EMA state: kept on GPU for efficiency, initialized on first step + ema_state: dict[str, Tensor] | None = None + # QAT timing: use wallclock fraction for deterministic triggering (immune to step_ms estimate noise) + # LATE_QAT_FRAC=0.65 fires QAT at 65% of budget (~390s), giving ~1400 QAT steps. + # Falls back to LR-scale method if LATE_QAT_FRAC is unset or 0. + _late_qat_frac = float(os.environ.get("LATE_QAT_FRAC", "0.0")) + _late_qat_trigger_ms = (_late_qat_frac * max_wallclock_ms) if (max_wallclock_ms and _late_qat_frac > 0) else None + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + if wandb_enabled: + wandb.log({"val/loss": val_loss, "val/bpb": val_bpb}, step=step) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_active: + if _late_qat_trigger_ms is not None: + if elapsed_ms >= _late_qat_trigger_ms: + _enable_qat() + elif args.late_qat_threshold > 0 and scale < args.late_qat_threshold: + _enable_qat() + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + + # EMA: update running average of weights (GPU, no extra transfer) + if args.ema_enabled: + if ema_state is None: + ema_state = {name: t.detach().clone() for name, t in base_model.state_dict().items()} + else: + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(args.ema_decay).add_(t.detach(), alpha=1.0 - args.ema_decay) + + # SWA: collect checkpoints during warmdown + if args.swa_enabled and scale < args.swa_start_frac and step % args.swa_every == 0: + if swa_state is None: + swa_state = {name: t.detach().cpu().clone() for name, t in base_model.state_dict().items()} + swa_count = 1 + log0(f"swa:start step:{step}") + else: + for name, t in base_model.state_dict().items(): + swa_state[name] += t.detach().cpu() + swa_count += 1 + + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + if wandb_enabled: + wandb.log({ + "train/loss": train_loss.item(), + "train/lr_scale": scale, + "train/step_ms": approx_training_time_ms / step, + }, step=step) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + # Apply SWA if collected + if args.swa_enabled and swa_state is not None and swa_count > 1: + log0(f"swa:applying averaged {swa_count} checkpoints") + current_state = base_model.state_dict() + avg_state = { + name: (tensor / swa_count).to(dtype=current_state[name].dtype) + for name, tensor in swa_state.items() + } + base_model.load_state_dict(avg_state, strict=True) + + # Apply EMA: use smooth running average as final weights (overrides SWA if both enabled) + if args.ema_enabled and ema_state is not None: + log0(f"ema:applying (decay={args.ema_decay})") + current_state = base_model.state_dict() + ema_cpu = {name: t.cpu().to(dtype=current_state[name].dtype) for name, t in ema_state.items()} + base_model.load_state_dict(ema_cpu, strict=True) + + # SERIALIZATION + QUANTIZATION + if master_process: + torch.save(base_model.state_dict(), f"final_model_{args.run_id}.pt") + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total uncompressed: {model_bytes + code_bytes} bytes") + + # Magnitude pruning: zero smallest 3% of large weight matrices to aid compression + with torch.no_grad(): + for name, param in base_model.named_parameters(): + if param.ndim == 2 and param.numel() > 65536: + threshold = torch.quantile(param.abs().float().flatten(), 0.03) + mask = param.abs() < threshold + param.masked_fill_(mask, 0.0) + + # Dynamically set FP16_KEEP to keep last attention layer's c_k in FP16 (reduces late-layer quant penalty) + # Default "blocks.8.attn.c_k" is correct for 9L; override here for other depths + global FP16_KEEP_NAME_PATTERNS + last_layer_ck = f"blocks.{args.num_layers - 1}.attn.c_k" + FP16_KEEP_NAME_PATTERNS = tuple( + p for p in set(list(FP16_KEEP_NAME_PATTERNS) + [last_layer_ck]) + if p and not p.startswith("blocks.") or p == last_layer_ck + ) + + # INT5/INT4 MLP + INT6/INT4 Attn/Bigram/Trigram mixed quantization + zstd-22 / zlib-9 export + int6_cats = {"mlp", "attn", "bigram"} + if base_model.trigram is not None: + int6_cats.add("trigram") + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + quant_result, quant_meta = mixed_quantize_int6(sd_cpu, int6_cats, mlp_clip=mlp_clip) + quant_buf = io.BytesIO() + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + quant_raw = quant_buf.getvalue() + if _COMPRESSOR == "zstd": + quant_blob = zstandard.ZstdCompressor(level=22).compress(quant_raw) + else: + quant_blob = zlib.compress(quant_raw, 9) + if master_process: + with open(f"final_model_{args.run_id}.int8.ptz", "wb") as f: + f.write(quant_blob) + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int5mlp+int6attn+{_COMPRESSOR}: {quant_file_bytes} bytes") + log0(f"Total submission size: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + if _COMPRESSOR == "zstd": + decompressed = zstandard.ZstdDecompressor().decompress(quant_blob_disk) + else: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + deq_state = dequantize_mixed_int6(quant_state["w"], quant_state["m"], sd_cpu) + base_model.load_state_dict(deq_state, strict=True) + + # Final eval on roundtripped weights with sliding window + torch.cuda.synchronize() + t_qeval = time.perf_counter() + if args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window stride:{args.eval_stride} batch_seqs:{args.eval_batch_seqs}") + q_val_loss, q_val_bpb = eval_val_sliding( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, + ) + else: + log0("final_eval_mode:standard") + q_val_loss, q_val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + if wandb_enabled: + wandb.log({ + "final/post_quant_bpb": q_val_bpb, + "final/post_quant_loss": q_val_loss, + "final/artifact_mb": quant_file_bytes / 1e6, + }) + + if args.ttt_enabled: + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, log0=log0, + ) + torch.cuda.synchronize() + log0(f"legal_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms") + log0(f"legal_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + if wandb_enabled: + wandb.log({"final/ttt_bpb": ttt_bpb, "final/ttt_loss": ttt_loss}) + + if wandb_enabled: + wandb.finish() + + if distributed: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/run.sh b/run.sh new file mode 100644 index 0000000000..0a07a4f981 --- /dev/null +++ b/run.sh @@ -0,0 +1,274 @@ +#!/bin/bash +# Usage: bash run.sh +# Configs: +# baseline - original train_gpt.py, 10min wallclock cap +# baseline_full - original train_gpt.py, 3000 steps no cap +# v2_quick - train_gpt_v2.py, 3000 steps (ablation signal) +# v2_full - train_gpt_v2.py, 20000 steps (full A100 run) +# v2_h100 - train_gpt_v2.py, 8xH100 submission (10min cap) +# 11l - v2 with 11 layers (Phase 2 bet A) +# 12l - v2 with 12 layers (Phase 2 bet A) +# trigram - v2 + trigram hash on top of bigram (Phase 2 bet B) +# seq4096 - v2 with seq_len=4096 (Phase 2 bet C) +# kv2 - v2 with 2 KV heads instead of 4 (Phase 2 bet D) +# bigram20k - v2 with 20480 bigram buckets (Phase 2 bet E) +# Phase 3 (new SOTA stack): +# v3_abl - 12L INT4 bQAT + XSA4 + EMA + LeakyReLU² (1500 steps, ablation) +# proxy_v3 - proxy run (10500 steps) for the v3 stack +# v3_h100 - 8xH100 submission with full v3 stack + +set -e +cd /vol/paraG/parameter-golf +source .venv/bin/activate + +CONFIG=${1:-v2_quick} + +export DATA_PATH=./data/datasets/fineweb10B_sp1024/ +export TOKENIZER_PATH=./data/tokenizers/fineweb_1024_bpe.model +export VOCAB_SIZE=1024 + +case "$CONFIG" in + + baseline) + echo "=== Running: BASELINE (10min wallclock cap) ===" + export RUN_ID=baseline_ref + torchrun --standalone --nproc_per_node=1 train_gpt.py + ;; + + baseline_full) + echo "=== Running: BASELINE full (3000 steps, no cap) ===" + export RUN_ID=baseline_full ITERATIONS=3000 MAX_WALLCLOCK_SECONDS=0 + torchrun --standalone --nproc_per_node=1 train_gpt.py + ;; + + v2_quick) + echo "=== Running: V2 quick (3000 steps, no cap) ===" + export RUN_ID=v2_quick ITERATIONS=3000 MAX_WALLCLOCK_SECONDS=0 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + v2_full) + echo "=== Running: V2 full A100 (20000 steps, no cap) ===" + export RUN_ID=v2_full ITERATIONS=20000 MAX_WALLCLOCK_SECONDS=0 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + v2_h100) + echo "=== Running: V2 on 8xH100 (submission, 10min cap) ===" + # WINNER CONFIG: 12L + INT4 MLP/Bigram QAT (trigram ablated out — hurt by 0.002 BPB) + export RUN_ID=v2_h100_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 + torchrun --standalone --nproc_per_node=8 train_gpt_v2.py + ;; + + # ---- Phase 2 ablations (3000 steps each, ~35-60 min on A100) ---- + + 11l) + echo "=== Phase 2 Bet A: 11 layers ===" + export RUN_ID=abl_11l ITERATIONS=3000 MAX_WALLCLOCK_SECONDS=0 NUM_LAYERS=11 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + 12l) + echo "=== Phase 2 Bet A: 12 layers ===" + export RUN_ID=abl_12l ITERATIONS=3000 MAX_WALLCLOCK_SECONDS=0 NUM_LAYERS=12 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + seq4096) + echo "=== Phase 2 Bet C: seq_len=4096 ===" + export RUN_ID=abl_seq4096 ITERATIONS=3000 MAX_WALLCLOCK_SECONDS=0 TRAIN_SEQ_LEN=4096 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + kv2) + echo "=== Phase 2 Bet D: 2 KV heads ===" + export RUN_ID=abl_kv2 ITERATIONS=3000 MAX_WALLCLOCK_SECONDS=0 NUM_KV_HEADS=2 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + bigram20k) + echo "=== Phase 2 Bet E: 20480 bigram buckets ===" + export RUN_ID=abl_bigram20k ITERATIONS=3000 MAX_WALLCLOCK_SECONDS=0 BIGRAM_VOCAB_SIZE=20480 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + noqat) + echo "=== Ablation: v2 without QAT (isolate QAT impact) ===" + export RUN_ID=abl_noqat ITERATIONS=3000 MAX_WALLCLOCK_SECONDS=0 QAT_ENABLED=0 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + 11l_kv2_b6k) + echo "=== Phase 2 Combo: 11L + KV2 + bigram6144 ===" + export RUN_ID=abl_11l_kv2_b6k ITERATIONS=1500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=11 NUM_KV_HEADS=2 BIGRAM_VOCAB_SIZE=6144 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + 12l_int4) + echo "=== NOVEL BET: 12L + INT4 MLP QAT (est. ~14.8MB) ===" + export RUN_ID=abl_12l_int4 ITERATIONS=1500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + 12l_int4_b9k) + echo "=== WINNER CONFIG: 12L + INT4 + bigram9216 (size fix, target ~15.95MB) ===" + export RUN_ID=abl_12l_int4_b9k ITERATIONS=1500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 BIGRAM_VOCAB_SIZE=9216 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + 12l_int4_bqat) + echo "=== NOVEL: 12L + INT4 MLP + INT4 Bigram QAT (target ~15.75MB) ===" + export RUN_ID=abl_12l_int4_bqat ITERATIONS=1500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + proxy_12l_bqat) + echo "=== PROXY: 12L + INT4 MLP + INT4 Bigram QAT, 10500 steps ===" + export RUN_ID=proxy_12l_bqat ITERATIONS=10500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + proxy_10l) + echo "=== PROXY: 10L INT5 MLP (baseline arch), 10500 steps ===" + export RUN_ID=proxy_10l ITERATIONS=10500 MAX_WALLCLOCK_SECONDS=0 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + 12l_bqat_trig) + echo "=== ABLATION: 12L + INT4 bQAT + Trigram(512), 1500 steps ===" + export RUN_ID=abl_12l_bqat_trig ITERATIONS=1500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 TRIGRAM_VOCAB_SIZE=512 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + proxy_12l_bqat_trig) + echo "=== PROXY: 12L + INT4 bQAT + Trigram(512), 10500 steps ===" + export RUN_ID=proxy_12l_bqat_trig ITERATIONS=10500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 TRIGRAM_VOCAB_SIZE=512 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + 13l_int4) + echo "=== NOVEL BET: 13L + INT4 MLP QAT (est. ~16.0MB, risky) ===" + export RUN_ID=abl_13l_int4 ITERATIONS=1500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=13 MLP_QUANT_BITS=4 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + # ---- Phase 3: New SOTA stack (LeakyReLU² + XSA4 + EMA + GPTQ-lite) ---- + + v3_abl) + echo "=== Phase 3 ABLATION: 12L INT4 bQAT + XSA4 + EMA + LeakyReLU² + RoPE16 + LNScale (1500 steps) ===" + # Full v4 stack: XSA + EMA + GPTQ-lite + LeakyReLU² + Partial RoPE(16) + LN Scale + export RUN_ID=abl_v4_full ITERATIONS=1500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + abl_emfix) + echo "=== EMA-fix verification: 1500 steps, threshold=0.4 → QAT at step~300, 1200 QAT steps ===" + # threshold=0.4 is proportional for 1500-step run (scale goes 0.5→0, so 0.4 fires at step~300) + # EMA reset at QAT activation → 97.5% QAT-adapted by end + # Verify: post-quant should be ~1.27-1.30, NOT 1.47 + export RUN_ID=abl_emfix ITERATIONS=1500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.4 TTT_ENABLED=0 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + abl_ve) + echo "=== ValueEmbedding ablation: 1500 steps, VE at last 3 layers ===" + # ValueEmbedding reinjects token identity into V at last N layers (from SOTA #549) + export RUN_ID=abl_ve ITERATIONS=1500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.4 VALUE_EMBED_LAYERS=3 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + proxy_v3) + echo "=== Phase 3 PROXY: Full v4 stack + Late QAT + TTT, 10500 steps ===" + export RUN_ID=proxy_v4_full ITERATIONS=10500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.15 TTT_ENABLED=1 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + proxy_v4) + echo "=== Phase 4 PROXY: EMA fix (threshold=0.9 + EMA reset at QAT), 10500 steps ===" + # Fix for EMA+LateQAT mismatch: threshold=0.9 → QAT starts at step ~7800 (2700 steps) + # EMA also resets at QAT activation (code fix in train_gpt_v2.py) + # Expected: post-quant close to fake-quant val (~1.163 instead of 1.356) + export RUN_ID=proxy_v4_emfix ITERATIONS=10500 MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + v4_h100) + echo "=== Phase 4 H100: EMA-fixed stack (8xH100 submission) ===" + export RUN_ID=v4_h100_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ + LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 + torchrun --standalone --nproc_per_node=8 train_gpt_v2.py + ;; + + v6_parallel) + echo "=== Phase 6 H100: Parallel Muon — DEPRECATED, reverted to DDP (virtual banking gave no speedup) ===" + echo "Use v7_ve instead." + exit 1 + ;; + + v7_ve) + echo "=== Phase 7 H100: 12L + Value Embeddings (VE_DIM=128, last 2 layers) ===" + # Value embeddings reinject token identity into V at layers 10,11 (SOTA uses this) + # VE adds ~147KB compressed, fits in 16MB (790KB margin). Expect +0.005-0.015 BPB quality gain. + # Fallback: SEED=X bash run.sh v4_h100 for vanilla 12L without VE + export RUN_ID=v7_ve_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ + LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ + VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 + torchrun --standalone --nproc_per_node=8 train_gpt_v2.py + ;; + + v5_rownorm) + echo "=== Phase 5 H100: Rownorm backend — DEPRECATED, rownorm hurt quality ===" + echo "Use v6_parallel instead." + exit 1 + ;; + + proxy_v5_rownorm) + echo "=== Proxy v5: Rownorm backend (1xH100, no wallclock cap) ===" + export RUN_ID=proxy_v5_rownorm SEED=${SEED:-1} MAX_WALLCLOCK_SECONDS=0 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ + VAL_LOSS_EVERY=500 MUON_BACKEND=rownorm + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + v3_h100) + echo "=== Phase 3 H100: Full v4 stack + Late QAT + TTT (8xH100 submission) ===" + export RUN_ID=v3_h100_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.15 TTT_ENABLED=1 + torchrun --standalone --nproc_per_node=8 train_gpt_v2.py + ;; + + *) + echo "Unknown config: $CONFIG" + echo "Available: baseline | baseline_full | v2_quick | v2_full | v2_h100" + echo "Phase 2: 11l | 12l | seq4096 | kv2 | bigram20k | noqat | 11l_kv2_b6k" + echo "Phase 3: v3_abl | proxy_v3 | v3_h100" + echo "Phase 4: proxy_v4 | v4_h100 (EMA+LateQAT fix, threshold=0.9)" + echo "Phase 6: v6_parallel (Parallel Muon: async RS + sharded NS5 + all-gather)" + exit 1 + ;; +esac diff --git a/train_gpt_v2.py b/train_gpt_v2.py new file mode 100644 index 0000000000..2986b1685c --- /dev/null +++ b/train_gpt_v2.py @@ -0,0 +1,1749 @@ +from __future__ import annotations + +import copy +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import uuid +import zlib +from pathlib import Path + +try: + import zstandard + _COMPRESSOR = "zstd" +except ImportError: + _COMPRESSOR = "zlib" + +try: + import wandb + _WANDB_AVAILABLE = True +except ImportError: + _WANDB_AVAILABLE = False + +import numpy as np +import sentencepiece as spm +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import Tensor, nn +from torch.nn.parallel import DistributedDataParallel as DDP + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- + +class Hyperparameters: + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024") + train_files = os.path.join(data_path, "fineweb_train_*.bin") + val_files = os.path.join(data_path, "fineweb_val_*.bin") + tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 42)) + + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 500)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 100)) + + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3000)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 786_432)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2048)) + max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + + vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) + num_layers = int(os.environ.get("NUM_LAYERS", 10)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 4)) + model_dim = int(os.environ.get("MODEL_DIM", 512)) + num_heads = int(os.environ.get("NUM_HEADS", 8)) + mlp_mult = float(os.environ.get("MLP_MULT", 3.0)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.008)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.03)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.02)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.02)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.3)) + weight_decay = float(os.environ.get("WEIGHT_DECAY", 0.04)) + + eval_stride = int(os.environ.get("EVAL_STRIDE", 64)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 32)) + + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + trigram_vocab_size = int(os.environ.get("TRIGRAM_VOCAB_SIZE", 0)) # 0 = disabled + trigram_dim = int(os.environ.get("TRIGRAM_DIM", 64)) + + swa_enabled = bool(int(os.environ.get("SWA_ENABLED", "1"))) + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.4)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + + # EMA: exponential moving average of weights (replaces SWA when enabled) + ema_enabled = bool(int(os.environ.get("EMA_ENABLED", "0"))) + ema_decay = float(os.environ.get("EMA_DECAY", "0.997")) + + # QAT: fake-quantize weights during training to match PTQ targets + # MLP precision: INT4 (clip=7) or INT5 (clip=15, default); INT6 for attention (clip=31) + qat_enabled = bool(int(os.environ.get("QAT_ENABLED", "1"))) + mlp_quant_bits = int(os.environ.get("MLP_QUANT_BITS", "5")) # 4 or 5 + + # XSA: Cross-Sequence Attention on last N layers (subtracts self-value projection) + xsa_last_n = int(os.environ.get("XSA_LAST_N", 0)) + + # Partial RoPE: apply RoPE to only first rope_dims dims of head_dim (0 = full) + rope_dims = int(os.environ.get("ROPE_DIMS", 0)) + + # LN Scale: scale norm input by 1/sqrt(layer_idx+1) for depth stability + ln_scale = bool(int(os.environ.get("LN_SCALE", "0"))) + + # Late QAT: delay fake-quantize until LR scale drops below threshold (0 = from start) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", "0")) + + # ValueEmbedding: reinject token identity into V at last N layers (0 = disabled) + value_embed_layers = int(os.environ.get("VALUE_EMBED_LAYERS", "0")) + value_embed_dim = int(os.environ.get("VALUE_EMBED_DIM", "64")) + + # TTT: Legal score-first test-time training at final eval + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "0"))) + ttt_lr = float(os.environ.get("TTT_LR", "0.002")) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", "3")) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", "32768")) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", "0")) + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", "0.9")) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", "32")) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", "1.0")) + +# ----------------------------- +# MUON OPTIMIZER — Parallel Muon (async reduce-scatter → sharded NS5 → all-gather) +# ----------------------------- + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 5, eps: float = 1e-7) -> Tensor: + """Batched Newton-Schulz orthogonalization. Accepts (B,M,N) or (M,N).""" + a, b, c = (3.4445, -4.7750, 2.0315) + was_2d = G.ndim == 2 + if was_2d: + G = G.unsqueeze(0) + X = G.bfloat16() + transposed = X.size(-2) > X.size(-1) + if transposed: + X = X.mT + X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps) + for _ in range(steps): + A = X @ X.mT + B = b * A + c * (A @ A) + X = a * X + B @ X + if transposed: + X = X.mT + if was_2d: + X = X.squeeze(0) + return X + + +class Muon(torch.optim.Optimizer): + """Muon — MomentUm Orthogonalized by Newton-schulz. + + Works with DDP: DDP handles gradient averaging during backward. + NS5 runs sequentially on the already-averaged gradients. + launch_reduce_scatters() is a no-op stub (DDP handles sync). + + Falls back identically on single-GPU proxy runs. + """ + def __init__(self, params, lr: float, momentum: float, backend_steps: int, + nesterov: bool = True, weight_decay: float = 0.0): + super().__init__( + params, + dict(lr=lr, momentum=momentum, backend_steps=backend_steps, + nesterov=nesterov, weight_decay=weight_decay), + ) + + def launch_reduce_scatters(self) -> None: + pass # No-op: DDP handles gradient sync during backward + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + for group in self.param_groups: + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + wd = group.get("weight_decay", 0.0) + for p in group["params"]: + if p.grad is None: + continue + g = p.grad.bfloat16() + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(g) + update = g.add(buf, alpha=momentum) if nesterov else buf.clone() + update = zeropower_via_newtonschulz5(update, steps=backend_steps) + if wd > 0.0: + p.data.mul_(1.0 - lr * wd) + scale = max(1, p.shape[-2] / p.shape[-1]) ** 0.5 + p.add_(update.to(dtype=p.dtype), alpha=-lr * scale) + return loss + + +def _apply_vbank_update(vb: dict, lr: float, wd: float) -> None: + pass # unused stub kept for import compatibility + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION +# ----------------------------- + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("\u2581"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return ( + torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device), + ) + + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError( + "VAL_BATCH_SIZE must provide at least one sequence per rank; " + f"got VAL_BATCH_SIZE={args.val_batch_size}, WORLD_SIZE={world_size}, " + f"GRAD_ACCUM_STEPS={grad_accum_steps}, TRAIN_SEQ_LEN={args.train_seq_len}" + ) + local_batch_seqs = local_batch_tokens // args.train_seq_len + total_seqs = (val_tokens.numel() - 1) // args.train_seq_len + seq_start = (total_seqs * rank) // world_size + seq_end = (total_seqs * (rank + 1)) // world_size + val_loss_sum = torch.zeros((), device=device, dtype=torch.float64) + val_token_count = torch.zeros((), device=device, dtype=torch.float64) + val_byte_count = torch.zeros((), device=device, dtype=torch.float64) + model.eval() + with torch.inference_mode(): + for batch_seq_start in range(seq_start, seq_end, local_batch_seqs): + batch_seq_end = min(batch_seq_start + local_batch_seqs, seq_end) + raw_start = batch_seq_start * args.train_seq_len + raw_end = batch_seq_end * args.train_seq_len + 1 + local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True) + x = local[:-1].reshape(-1, args.train_seq_len) + y = local[1:].reshape(-1, args.train_seq_len) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + batch_loss = model(x, y).detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +# ----------------------------- +# QUANTIZATION (INT5 MLP / INT6 ATTN mixed PTQ) +# ----------------------------- + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights,smear,bigram.scale,trigram.scale,ve_layer_scales,ve_shared.scale", + ).split(",") + if pattern +) +FP16_KEEP_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get("FP16_KEEP_NAME_PATTERNS", "tok_emb,blocks.8.attn.c_k").split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 + +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + INT8_CLIP_Q = 99.99984 / 100.0 + t32 = t.float() + if t32.ndim == 2: + clip_abs = ( + torch.quantile(t32.abs(), INT8_CLIP_Q, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + clipped = torch.maximum(torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None]) + scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) + q = torch.clamp(torch.round(clipped / scale[:, None]), -127, 127).to(torch.int8).contiguous() + return q, scale.to(dtype=torch.float16).contiguous() + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127).to(torch.int8).contiguous() + return q, scale + + +def _classify_param(name: str) -> str: + if "tok_emb" in name or "lm_head" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if "bigram" in name: + return "bigram" + if "trigram" in name: + return "trigram" + if ".attn." in name or (".proj." in name and ".mlp." not in name): + return "attn" + return "other" + + +def quantize_intN_per_row(t: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + """Quantize with GPTQ-lite: search 5 clip percentiles, pick best MSE.""" + t32 = t.float() + if t32.ndim == 2: + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 0.99999, 1.0]: + if pct < 1.0: + row_clip = torch.quantile(t32.abs(), pct, dim=1) + else: + row_clip = t32.abs().amax(dim=1) + scale = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + scale = scale.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(t32 / scale.float()[:, None]), -(clip_range + 1), clip_range).to(torch.int8) + err = (t32 - q.float() * scale.float()[:, None]).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, scale, err + return best_q, best_s + amax = t32.abs().max().item() + scale = torch.tensor(max(amax / clip_range, 1e-12), dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -(clip_range + 1), clip_range).to(torch.int8) + return q, scale + + +def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15): + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param(name) + if not t.is_floating_point() or t.numel() <= 8192: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + if any(pattern in name for pattern in FP16_KEEP_NAME_PATTERNS): + result[name] = t.to(dtype=torch.float16).contiguous() + meta[name] = "passthrough_fp16" + continue + if cat in int6_cats and t.ndim >= 1: + # MLP: always uses mlp_clip (INT4 or INT5) + # bigram/trigram: follow mlp_clip when INT4 (saves ~0.25MB), else INT6 + # attn and others: INT6 + if cat == "mlp": + clip = mlp_clip + elif cat in ("bigram", "trigram") and mlp_clip <= 7: + clip = mlp_clip # INT4 bigram/trigram when MLP is INT4 + else: + clip = 31 # INT6 for attn, bigram/trigram in INT5 mode + q, s = quantize_intN_per_row(t, clip_range=clip) + result[name + ".q"] = q + result[name + ".scale"] = s + bits = clip.bit_length() + 1 # clip=31→int6, clip=15→int5, clip=7→int4 + meta[name] = {"type": f"int{bits}"} + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return result, meta + + +def dequantize_mixed_int6(result: dict[str, Tensor], meta: dict[str, object], + template_sd: dict[str, Tensor]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + for name, orig in template_sd.items(): + info = meta[name] + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl", "passthrough_fp16"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + + +# ----------------------------- +# DATA LOADING +# ----------------------------- + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = rank + self.world_size = world_size + self.device = device + self.stream = TokenStream(pattern) + + def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> tuple[Tensor, Tensor]: + local_tokens = global_tokens // (self.world_size * grad_accum_steps) + per_rank_span = local_tokens + 1 + chunk = self.stream.take(per_rank_span * self.world_size) + start = self.rank * per_rank_span + local = chunk[start : start + per_rank_span].to(dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + return x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) + + +# ----------------------------- +# TRANSFORMER MODULES +# ----------------------------- + +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + + +class CastedLinear(nn.Linear): + # _qat_clip_range: 127=off/INT8, 31=INT6, 15=INT5 + _qat_clip_range: int = 127 + + def forward(self, x: Tensor) -> Tensor: + w = self.weight + if self.training and self._qat_clip_range < 127 and w.ndim == 2: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w.to(x.dtype), bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int = 0): + super().__init__() + self.rope_dims = rope_dims if rope_dims > 0 else dim + rd = self.rope_dims + inv_freq = 1.0 / (base ** (torch.arange(0, rd, 2, dtype=torch.float32) / rd)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + rd = cos.size(-1) * 2 + if rd < x.size(-1): # partial RoPE: rotate first rd dims, pass rest unchanged + x_rope, x_pass = x[..., :rd], x[..., rd:] + half = rd // 2 + x1, x2 = x_rope[..., :half], x_rope[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + + +class CausalSelfAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, rope_base: float, qk_gain_init: float, rope_dims: int = 0): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base, rope_dims=rope_dims) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + """XSA: subtract self-value projection, forcing heads to attend to OTHER tokens.""" + B, T, H, D = y.shape + Hkv = v.size(2) # v is [B, T, Hkv, D] + group = H // Hkv + y_g = y.reshape(B, T, Hkv, group, D) + vn = F.normalize(v, dim=-1).unsqueeze(3) # [B, T, Hkv, 1, D] + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v_raw = self.c_v(x) + if v_embed is not None: + v_raw = v_raw + v_embed + v_bthd = v_raw.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + v = v_bthd.transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention( + q, k, v, attn_mask=None, is_causal=True, + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + y = y.transpose(1, 2).contiguous() # [B, T, H, D] + if self.use_xsa: + y = self._xsa_efficient(y, v_bthd) + y = y.reshape(bsz, seqlen, dim) + return self.proj(y) + + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: float): + super().__init__() + hidden = int(mlp_mult * dim) + self.fc = CastedLinear(dim, hidden, bias=False) + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + + def forward(self, x: Tensor) -> Tensor: + x = F.leaky_relu(self.fc(x), negative_slope=0.5) + return self.proj(x.square()) + + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate.to(dtype=x.dtype))[None, None, :] + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1 - g) * x + g * x_prev + + +class BigramHashEmbedding(nn.Module): + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, bigram_vocab_size: int, bigram_dim: int, model_dim: int): + super().__init__() + self.bigram_vocab_size = bigram_vocab_size + self.embed = nn.Embedding(bigram_vocab_size, bigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(bigram_dim, model_dim, bias=False) if bigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.05, dtype=torch.float32)) + + def bigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.bigram_vocab_size - 1 + out = torch.empty_like(t) + out[..., 0] = mod + out[..., 1:] = torch.bitwise_xor(36313 * t[..., 1:], 27191 * t[..., :-1]) % mod + return out.long() + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.bigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class TrigramHashEmbedding(nn.Module): + """3-gram context embedding: (prev2, prev1, curr) → hashed bucket → learned embedding.""" + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, trigram_vocab_size: int, trigram_dim: int, model_dim: int): + super().__init__() + self.trigram_vocab_size = trigram_vocab_size + self.embed = nn.Embedding(trigram_vocab_size, trigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(trigram_dim, model_dim, bias=False) if trigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.02, dtype=torch.float32)) + + def trigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.trigram_vocab_size - 1 + out = torch.full_like(t, mod, dtype=torch.long) # sentinel for positions without full context + out[..., 2:] = ( + torch.bitwise_xor( + torch.bitwise_xor(17291 * t[..., 2:], 36313 * t[..., 1:-1]), + 27191 * t[..., :-2], + ) % mod + ) + return out + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.trigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class ValueEmbedding(nn.Module): + """Reinject token identity into attention values at specific layers. + Shared embedding table + per-layer learned scale. Applied at last N layers.""" + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int): + super().__init__() + self.embed = nn.Embedding(vocab_size, ve_dim) + nn.init.normal_(self.embed.weight, std=0.01) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) if ve_dim != kv_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.1, dtype=torch.float32)) + + def forward(self, token_ids: Tensor) -> Tensor: + h = self.embed(token_ids) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class Block(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, mlp_mult: float, rope_base: float, qk_gain_init: float, rope_dims: int = 0, ln_scale: bool = False, layer_idx: int = 0): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, rope_dims=rope_dims) + self.mlp = MLP(dim, mlp_mult) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + + def forward(self, x: Tensor, x0: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + s = self.ln_scale_factor + attn_out = self.attn(self.attn_norm(x) * s, v_embed=v_embed) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * s) + return x + + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_layers: int, + model_dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: float, + tie_embeddings: bool, + tied_embed_init_std: float, + logit_softcap: float, + rope_base: float, + qk_gain_init: float, + bigram_vocab_size: int = 0, + bigram_dim: int = 128, + trigram_vocab_size: int = 0, + trigram_dim: int = 64, + rope_dims: int = 0, + ln_scale: bool = False, + xsa_last_n: int = 0, + value_embed_layers: int = 0, + value_embed_dim: int = 64, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.bigram = BigramHashEmbedding(bigram_vocab_size, bigram_dim, model_dim) if bigram_vocab_size > 0 else None + self.trigram = TrigramHashEmbedding(trigram_vocab_size, trigram_dim, model_dim) if trigram_vocab_size > 0 else None + self.num_encoder_layers = num_layers // 2 + self.num_decoder_layers = num_layers - self.num_encoder_layers + self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers) + self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32)) + self.smear = SmearGate(model_dim) + self.blocks = nn.ModuleList( + [ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init, + rope_dims=rope_dims, ln_scale=ln_scale, layer_idx=i) + for i in range(num_layers) + ] + ) + if xsa_last_n > 0: + for i in range(max(0, num_layers - xsa_last_n), num_layers): + self.blocks[i].attn.use_xsa = True + # ValueEmbedding: shared table + per-layer scales for last N layers + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve_layer_indices = list(range(max(0, num_layers - value_embed_layers), num_layers)) if value_embed_layers > 0 else [] + if self.ve_layer_indices: + self.ve_shared = ValueEmbedding(vocab_size, value_embed_dim, kv_dim) + self.ve_layer_scales = nn.ParameterList( + [nn.Parameter(torch.ones(1, dtype=torch.float32)) for _ in self.ve_layer_indices] + ) + else: + self.ve_shared = None + self.ve_layer_scales = nn.ParameterList() + self.final_norm = RMSNorm() + self.lm_head = None if tie_embeddings else CastedLinear(model_dim, vocab_size, bias=False) + if self.lm_head is not None: + self.lm_head._zero_init = True + self._init_weights() + + def _init_weights(self) -> None: + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) + num_layers = len(self.blocks) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and module.weight.shape[0] >= 64 and module.weight.shape[1] >= 64: + nn.init.orthogonal_(module.weight, gain=1.0) + if ".proj." in name or name.endswith(".proj"): + with torch.no_grad(): + module.weight.mul_(1.0 / math.sqrt(2 * num_layers)) + + def _get_ve(self, layer_idx: int, ve_base: "Tensor | None") -> "Tensor | None": + if ve_base is None or layer_idx not in self.ve_layer_indices: + return None + idx = self.ve_layer_indices.index(layer_idx) + return ve_base * self.ve_layer_scales[idx].to(dtype=ve_base.dtype) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x = self.blocks[self.num_encoder_layers + i](x, x0, v_embed=self._get_ve(self.num_encoder_layers + i, ve_base)) + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x = self.blocks[self.num_encoder_layers + i](x, x0, v_embed=self._get_ve(self.num_encoder_layers + i, ve_base)) + x = self.final_norm(x) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + logits_proj = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + + +def eval_val_sliding( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, + stride: int, + batch_seqs: int = 32, +) -> tuple[float, float]: + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + total_windows = len(window_starts) + my_s = (total_windows * rank) // world_size + my_e = (total_windows * (rank + 1)) // world_size + my_windows = window_starts[my_s:my_e] + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk[:-1] + y_batch[i, :wlen] = chunk[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt = y_batch[i, s:wlen] + prev = x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + running_bpb = 0.0 + if token_count.item() > 0: + rl = (loss_sum / token_count).item() + running_bpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) + print(f" sliding_eval [{pct:5.1f}%] {done}/{len(my_windows)} windows running_bpb={running_bpb:.6f}", flush=True) + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + bits_per_token = val_loss / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + base_model.train() + return val_loss, bits_per_token * tokens_per_byte + + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: nn.Module, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + """Legal score-first TTT: score each chunk with sliding windows, then train on it. + Every token is scored BEFORE any update that could use it (PR #461 recipe).""" + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + ttt_chunk = args.ttt_chunk_tokens + + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + + num_chunks = (total_tokens + ttt_chunk - 1) // ttt_chunk + chunk_windows: list[list[int]] = [[] for _ in range(num_chunks)] + for ws in window_starts: + end = min(ws + seq_len, total_tokens) + wlen = end - ws + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_start = ws + s + ci = min(scored_start // ttt_chunk, num_chunks - 1) + chunk_windows[ci].append(ws) + + log0(f"ttt_sliding:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"total_windows={len(window_starts)} stride={stride} " + f"ttt_lr={args.ttt_lr} ttt_epochs={args.ttt_epochs} " + f"freeze_blocks={args.ttt_freeze_blocks}") + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + log0(f"ttt_sliding:params unfrozen={sum(p.numel() for p in ttt_params)} " + f"frozen={sum(p.numel() for p in base_model.parameters() if not p.requires_grad)}") + + optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) + t0 = time.perf_counter() + + for ci in range(num_chunks): + windows = chunk_windows[ci] + if not windows: + continue + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + my_s = (len(windows) * rank) // world_size + my_e = (len(windows) * (rank + 1)) // world_size + my_windows = windows[my_s:my_e] + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk_tok = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk_tok[:-1] + y_batch[i, :wlen] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt, prev = y_batch[i, s:wlen], x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + my_seq_s = (chunk_seqs * rank) // world_size + my_seq_e = (chunk_seqs * (rank + 1)) // world_size + my_chunk_seqs = my_seq_e - my_seq_s + for _ep in range(args.ttt_epochs): + for bs in range(0, my_chunk_seqs, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_chunk_seqs) + actual_bs = my_seq_s + bs + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + (my_seq_s + be) * seq_len + 1 + if end_tok > val_tokens.numel(): + continue + local = val_tokens[start_tok:end_tok].to(device=device, dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + optimizer.zero_grad(set_to_none=True) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + loss = base_model(x, y) + loss.backward() + if world_size > 1: + for p in ttt_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) if token_count.item() > 0 else 0.0 + log0(f" ttt_chunk [{ci+1}/{num_chunks}] bpb={rbpb:.6f} time={elapsed:.1f}s") + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + val_bpb = val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.eval() + + log0(f"ttt_sliding:done val_loss={val_loss:.6f} val_bpb={val_bpb:.6f} " + f"elapsed={time.perf_counter() - t0:.1f}s") + return val_loss, val_bpb + + +# ----------------------------- +# TRAINING +# ----------------------------- + +def main() -> None: + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + # Parallel Muon uses batched bmm — do NOT torch.compile NS5 (bmm is already efficient) + + distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size <= 0: + raise ValueError(f"WORLD_SIZE must be positive, got {world_size}") + if 8 % world_size != 0: + raise ValueError(f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral") + grad_accum_steps = 8 // world_size + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + + logfile = None + wandb_enabled = False + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + if _WANDB_AVAILABLE and bool(int(os.environ.get("WANDB_ENABLED", "1"))): + wandb.init( + project=os.environ.get("WANDB_PROJECT", "parameter-golf"), + name=args.run_id, + config={ + "num_layers": args.num_layers, + "model_dim": args.model_dim, + "mlp_mult": args.mlp_mult, + "num_heads": args.num_heads, + "num_kv_heads": args.num_kv_heads, + "mlp_quant_bits": args.mlp_quant_bits, + "iterations": args.iterations, + "train_batch_tokens": args.train_batch_tokens, + "train_seq_len": args.train_seq_len, + "xsa_last_n": args.xsa_last_n, + "ema_enabled": args.ema_enabled, + "rope_dims": args.rope_dims, + "ln_scale": args.ln_scale, + "late_qat_threshold": args.late_qat_threshold, + "ttt_enabled": args.ttt_enabled, + "bigram_vocab_size": args.bigram_vocab_size, + "value_embed_layers": args.value_embed_layers, + "value_embed_dim": args.value_embed_dim, + "seed": args.seed, + }, + resume="allow", + ) + wandb_enabled = True + + def log0(msg: str, console: bool = True) -> None: + if not master_process: + return + if console: + print(msg) + if logfile is not None: + with open(logfile, "a", encoding="utf-8") as f: + print(msg, file=f) + + log0(code, console=False) + log0("=" * 100, console=False) + log0(f"Running Python {sys.version}", console=False) + log0(f"Running PyTorch {torch.__version__}", console=False) + log0( + subprocess.run(["nvidia-smi"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout, + console=False, + ) + log0("=" * 100, console=False) + + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + + if not args.tokenizer_path.endswith(".model"): + raise ValueError(f"Script only setup for SentencePiece .model file: {args.tokenizer_path}") + sp = spm.SentencePieceProcessor(model_file=args.tokenizer_path) + if int(sp.vocab_size()) != args.vocab_size: + raise ValueError( + f"VOCAB_SIZE={args.vocab_size} does not match tokenizer vocab_size={int(sp.vocab_size())}" + ) + dataset_dir = Path(args.data_path).resolve() + actual_train_files = len(list(dataset_dir.glob("fineweb_train_*.bin"))) + val_tokens = load_validation_tokens(args.val_files, args.train_seq_len) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = build_sentencepiece_luts( + sp, args.vocab_size, device + ) + log0(f"val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path={args.tokenizer_path}") + log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}") + log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}") + + # MODEL SETUP + base_model = GPT( + vocab_size=args.vocab_size, + num_layers=args.num_layers, + model_dim=args.model_dim, + num_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + mlp_mult=args.mlp_mult, + tie_embeddings=args.tie_embeddings, + tied_embed_init_std=args.tied_embed_init_std, + logit_softcap=args.logit_softcap, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + bigram_vocab_size=args.bigram_vocab_size, + bigram_dim=args.bigram_dim, + trigram_vocab_size=args.trigram_vocab_size, + trigram_dim=args.trigram_dim, + rope_dims=args.rope_dims, + ln_scale=args.ln_scale, + xsa_last_n=args.xsa_last_n, + value_embed_layers=args.value_embed_layers, + value_embed_dim=args.value_embed_dim, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + + # QAT: set per-layer fake-quantization targets + # MLP precision controlled by MLP_QUANT_BITS (4=INT4 clip=7, 5=INT5 clip=15) + mlp_clip = (1 << (args.mlp_quant_bits - 1)) - 1 # 5→15, 4→7 + ngram_clip = mlp_clip if args.mlp_quant_bits <= 4 else 31 # INT4 bigram/trigram when MLP is INT4 + _qat_active = False # tracks whether fake-quant has been activated + + def _enable_qat() -> None: + nonlocal _qat_active, ema_state + if _qat_active: + return + _qat_active = True + # Reset EMA so it only accumulates QAT-adapted weights (prevents pre-QAT contamination) + if args.ema_enabled and ema_state is not None: + ema_state = None + log0("qat:ema_reset (EMA will restart from current QAT weights)") + for name, module in base_model.named_modules(): + if isinstance(module, CastedLinear): + if ".mlp." in name: + module._qat_clip_range = mlp_clip + elif ".attn." in name: + module._qat_clip_range = 31 + elif "bigram" in name or "trigram" in name: + module._qat_clip_range = ngram_clip + else: + module._qat_clip_range = 31 + if base_model.bigram is not None: + base_model.bigram._qat_clip_range = ngram_clip + if base_model.trigram is not None: + base_model.trigram._qat_clip_range = ngram_clip + ngram_bits = '4' if ngram_clip <= 7 else '6' + trig_str = f" trigram=INT{ngram_bits}(clip={ngram_clip})" if base_model.trigram is not None else "" + log0(f"qat:enabled mlp=INT{args.mlp_quant_bits}(clip={mlp_clip}) attn=INT6(clip=31) bigram=INT{ngram_bits}(clip={ngram_clip}){trig_str}") + + if args.qat_enabled: + if args.late_qat_threshold > 0: + log0(f"qat:late_qat threshold={args.late_qat_threshold} (activates when lr_scale < threshold)") + else: + _enable_qat() + else: + log0("qat:disabled") + + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + if distributed: + model: nn.Module = DDP(compiled_model, device_ids=[device.index]) + else: + model = compiled_model + + # OPTIMIZER SETUP + block_named_params = list(base_model.blocks.named_parameters()) + matrix_params = [ + p for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + scalar_params.append(base_model.smear.gate) + if base_model.bigram is not None: + scalar_params.append(base_model.bigram.scale) + if base_model.trigram is not None: + scalar_params.append(base_model.trigram.scale) + + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + tok_params = [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}] + if base_model.bigram is not None: + tok_params.append({"params": [base_model.bigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.bigram.proj is not None: + matrix_params.append(base_model.bigram.proj.weight) + if base_model.trigram is not None: + tok_params.append({"params": [base_model.trigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.trigram.proj is not None: + matrix_params.append(base_model.trigram.proj.weight) + if base_model.ve_shared is not None: + tok_params.append({"params": [base_model.ve_shared.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.ve_shared.proj is not None: + matrix_params.append(base_model.ve_shared.proj.weight) + scalar_params.append(base_model.ve_shared.scale) + for s in base_model.ve_layer_scales: + scalar_params.append(s) + + optimizer_tok = torch.optim.AdamW( + tok_params, + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=0.04, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params}") + if base_model.ve_shared is not None: + log0(f"value_embed:layers={base_model.ve_layer_indices} ve_dim={args.value_embed_dim} kv_dim={base_model.ve_shared.proj.out_features if base_model.ve_shared.proj else args.value_embed_dim}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0(f"sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + # DATA LOADER & WARMUP + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + + max_wallclock_ms = 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0 + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 + + if args.warmup_steps > 0: + initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()} + initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers] + model.train() + for warmup_step in range(args.warmup_steps): + zero_grad_all() + for micro_step in range(grad_accum_steps): + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + warmup_loss = model(x, y) + (warmup_loss * grad_scale).backward() + # Without DDP: manually all-reduce all grads for warmup (simple, only 20 steps) + if distributed: + for p in base_model.parameters(): + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + for opt in optimizers: + opt.step() + zero_grad_all() + if args.warmup_steps <= 20 or (warmup_step + 1) % 10 == 0 or warmup_step + 1 == args.warmup_steps: + log0(f"warmup_step:{warmup_step + 1}/{args.warmup_steps}") + base_model.load_state_dict(initial_model_state, strict=True) + for opt, state in zip(optimizers, initial_optimizer_states, strict=True): + opt.load_state_dict(state) + zero_grad_all() + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + # MAIN TRAINING LOOP + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + # EMA state: kept on GPU for efficiency, initialized on first step + ema_state: dict[str, Tensor] | None = None + # QAT timing: use wallclock fraction for deterministic triggering (immune to step_ms estimate noise) + # LATE_QAT_FRAC=0.65 fires QAT at 65% of budget (~390s), giving ~1400 QAT steps. + # Falls back to LR-scale method if LATE_QAT_FRAC is unset or 0. + _late_qat_frac = float(os.environ.get("LATE_QAT_FRAC", "0.0")) + _late_qat_trigger_ms = (_late_qat_frac * max_wallclock_ms) if (max_wallclock_ms and _late_qat_frac > 0) else None + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + if wandb_enabled: + wandb.log({"val/loss": val_loss, "val/bpb": val_bpb}, step=step) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_active: + if _late_qat_trigger_ms is not None: + if elapsed_ms >= _late_qat_trigger_ms: + _enable_qat() + elif args.late_qat_threshold > 0 and scale < args.late_qat_threshold: + _enable_qat() + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + + # EMA: update running average of weights (GPU, no extra transfer) + if args.ema_enabled: + if ema_state is None: + ema_state = {name: t.detach().clone() for name, t in base_model.state_dict().items()} + else: + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(args.ema_decay).add_(t.detach(), alpha=1.0 - args.ema_decay) + + # SWA: collect checkpoints during warmdown + if args.swa_enabled and scale < args.swa_start_frac and step % args.swa_every == 0: + if swa_state is None: + swa_state = {name: t.detach().cpu().clone() for name, t in base_model.state_dict().items()} + swa_count = 1 + log0(f"swa:start step:{step}") + else: + for name, t in base_model.state_dict().items(): + swa_state[name] += t.detach().cpu() + swa_count += 1 + + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + if wandb_enabled: + wandb.log({ + "train/loss": train_loss.item(), + "train/lr_scale": scale, + "train/step_ms": approx_training_time_ms / step, + }, step=step) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + # Apply SWA if collected + if args.swa_enabled and swa_state is not None and swa_count > 1: + log0(f"swa:applying averaged {swa_count} checkpoints") + current_state = base_model.state_dict() + avg_state = { + name: (tensor / swa_count).to(dtype=current_state[name].dtype) + for name, tensor in swa_state.items() + } + base_model.load_state_dict(avg_state, strict=True) + + # Apply EMA: use smooth running average as final weights (overrides SWA if both enabled) + if args.ema_enabled and ema_state is not None: + log0(f"ema:applying (decay={args.ema_decay})") + current_state = base_model.state_dict() + ema_cpu = {name: t.cpu().to(dtype=current_state[name].dtype) for name, t in ema_state.items()} + base_model.load_state_dict(ema_cpu, strict=True) + + # SERIALIZATION + QUANTIZATION + if master_process: + torch.save(base_model.state_dict(), f"final_model_{args.run_id}.pt") + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total uncompressed: {model_bytes + code_bytes} bytes") + + # Magnitude pruning: zero smallest 3% of large weight matrices to aid compression + with torch.no_grad(): + for name, param in base_model.named_parameters(): + if param.ndim == 2 and param.numel() > 65536: + threshold = torch.quantile(param.abs().float().flatten(), 0.03) + mask = param.abs() < threshold + param.masked_fill_(mask, 0.0) + + # Dynamically set FP16_KEEP to keep last attention layer's c_k in FP16 (reduces late-layer quant penalty) + # Default "blocks.8.attn.c_k" is correct for 9L; override here for other depths + global FP16_KEEP_NAME_PATTERNS + last_layer_ck = f"blocks.{args.num_layers - 1}.attn.c_k" + FP16_KEEP_NAME_PATTERNS = tuple( + p for p in set(list(FP16_KEEP_NAME_PATTERNS) + [last_layer_ck]) + if p and not p.startswith("blocks.") or p == last_layer_ck + ) + + # INT5/INT4 MLP + INT6/INT4 Attn/Bigram/Trigram mixed quantization + zstd-22 / zlib-9 export + int6_cats = {"mlp", "attn", "bigram"} + if base_model.trigram is not None: + int6_cats.add("trigram") + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + quant_result, quant_meta = mixed_quantize_int6(sd_cpu, int6_cats, mlp_clip=mlp_clip) + quant_buf = io.BytesIO() + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + quant_raw = quant_buf.getvalue() + if _COMPRESSOR == "zstd": + quant_blob = zstandard.ZstdCompressor(level=22).compress(quant_raw) + else: + quant_blob = zlib.compress(quant_raw, 9) + if master_process: + with open(f"final_model_{args.run_id}.int8.ptz", "wb") as f: + f.write(quant_blob) + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int5mlp+int6attn+{_COMPRESSOR}: {quant_file_bytes} bytes") + log0(f"Total submission size: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + if _COMPRESSOR == "zstd": + decompressed = zstandard.ZstdDecompressor().decompress(quant_blob_disk) + else: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + deq_state = dequantize_mixed_int6(quant_state["w"], quant_state["m"], sd_cpu) + base_model.load_state_dict(deq_state, strict=True) + + # Final eval on roundtripped weights with sliding window + torch.cuda.synchronize() + t_qeval = time.perf_counter() + if args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window stride:{args.eval_stride} batch_seqs:{args.eval_batch_seqs}") + q_val_loss, q_val_bpb = eval_val_sliding( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, + ) + else: + log0("final_eval_mode:standard") + q_val_loss, q_val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + if wandb_enabled: + wandb.log({ + "final/post_quant_bpb": q_val_bpb, + "final/post_quant_loss": q_val_loss, + "final/artifact_mb": quant_file_bytes / 1e6, + }) + + if args.ttt_enabled: + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, log0=log0, + ) + torch.cuda.synchronize() + log0(f"legal_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms") + log0(f"legal_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + if wandb_enabled: + wandb.log({"final/ttt_bpb": ttt_bpb, "final/ttt_loss": ttt_loss}) + + if wandb_enabled: + wandb.finish() + + if distributed: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() From 0f506eb7978afe523e62ec5e398c9025b2812083 Mon Sep 17 00:00:00 2001 From: Harsh Soni Date: Sat, 28 Mar 2026 08:33:46 +0000 Subject: [PATCH 2/9] v7_ve seed 2: new best ttt_bpb=1.1574 (16.41MB) --- .../2026-03-28_12L_INT4_bQAT_VE/README.md | 24 ++++++++++------- .../submission.json | 6 ++--- .../2026-03-28_12L_INT4_bQAT_VE/train_gpt.py | 2 +- run.sh | 27 ++++++++++++++++++- train_gpt_v2.py | 2 +- 5 files changed, 45 insertions(+), 16 deletions(-) diff --git a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md index e75fd46359..d64264b4da 100644 --- a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md +++ b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md @@ -1,12 +1,13 @@ # 12L INT4 bQAT + EMA Fix + Value Embeddings -**val_bpb: 1.1588** (seed 1, full TTT) | **16.29 MB** | 8×H100 SXM +**val_bpb: 1.1574** (seed 2, full TTT) | **16.41 MB** | 8×H100 SXM ## Results (8×H100 80GB SXM) | Seed | step_avg | steps | Pre-quant val/bpb | Post-quant bpb | Post-TTT bpb | Artifact | |------|----------|-------|-------------------|----------------|--------------|----------| -| 1 | ~137ms | ~4380 | 1.1754 | 1.1643 | **1.1588** | 16,290,425 | +| 1 | ~137ms | ~4380 | 1.1754 | 1.1643 | 1.1588 | 16,290,425 | +| 2 | ~148ms | — | 1.1736 | 1.1624 | **1.1574** | 16,408,223 | ## Architecture @@ -46,24 +47,27 @@ The shared embedding allows all VE layers to benefit from a single (vocab, 128) |-----|-------|-----------|------------|---------| | v4_h100 seed 1 | 5021 | 1.1683 | 1.1703 | ~1.165 | | v4_h100 seed 3 | — | 1.1729 | 1.2002 | 1.1594 | -| **v7_ve seed 1** | ~4380 | 1.1754 | **1.1643** | **1.1588** | +| v7_ve seed 1 | ~4380 | 1.1754 | 1.1643 | 1.1588 | +| **v7_ve seed 2** | — | 1.1736 | **1.1624** | **1.1574** | -Note: v7_ve's post_quant (1.1643) is better than its pre-quant checkpoint (1.1754) because the model continued improving during QAT after the last val checkpoint. +Note: v7_ve's post_quant is better than its pre-quant checkpoint because the model continued improving during QAT after the last val checkpoint. -## Size Budget +## Size Budget (seed 2) | Component | Bytes | |-----------|-------| -| Base model (int4/int6/zstd) | ~15,967,640 | -| Value embeddings (int8/int4/zstd) | ~322,785 | -| **Total** | **16,290,425** | +| Total artifact | 16,408,223 | -Budget: 16,777,216 bytes (16MB) — **486,791 bytes (475KB) margin** +Budget: 16,777,216 bytes (16MB) — **368,993 bytes (361KB) margin** ## Run Command ```bash -SEED=1 VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 \ +# Best result (seed 2): +SEED=2 bash run.sh v7_ve + +# Or manually: +SEED=2 VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 \ LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ diff --git a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/submission.json b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/submission.json index 10e3cb2bea..952c7593da 100644 --- a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/submission.json +++ b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/submission.json @@ -1,8 +1,8 @@ { "name": "12L INT4 bQAT + EMA Fix + Value Embeddings", - "val_bpb": 1.1588, - "bytes_total": 16290425, - "blurb": "12-layer INT4 MLP+bigram QAT + U-Net skips + XSA(last 4) + EMA(0.997) with QAT-reset fix + LeakyReLU² + RoPE16 + LN Scale + resid_mix + Legal TTT + Value Embeddings (ve_dim=128, last 2 layers). Value embeddings reinject token identity into V at layers 10-11, improving quality per step. Step_avg ~137ms, ~4380 steps in 10 min. Post-quant degradation very clean (1.1643 from 1.1754 pre-quant). 8×H100 seed 1: ttt_bpb=1.15875.", + "val_bpb": 1.1574, + "bytes_total": 16408223, + "blurb": "12-layer INT4 MLP+bigram QAT + U-Net skips + XSA(last 4) + EMA(0.997) with QAT-reset fix + LeakyReLU² + RoPE16 + LN Scale + resid_mix + Legal TTT + Value Embeddings (ve_dim=128, last 2 layers). Value embeddings reinject token identity into V at layers 10-11. Best result: seed 2, ttt_bpb=1.15738. Post-quant degradation clean (1.1624 from pre-quant). 8×H100 seed 2: ttt_bpb=1.15738.", "author": "Harsh Soni", "github_id": "SoHarshh", "date": "2026-03-28" diff --git a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/train_gpt.py b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/train_gpt.py index 2986b1685c..f8b24bccca 100644 --- a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/train_gpt.py +++ b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/train_gpt.py @@ -1346,7 +1346,7 @@ def _enable_qat() -> None: compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) if distributed: - model: nn.Module = DDP(compiled_model, device_ids=[device.index]) + model: nn.Module = DDP(compiled_model, device_ids=[device.index], static_graph=True) else: model = compiled_model diff --git a/run.sh b/run.sh index 0a07a4f981..151d5bb653 100644 --- a/run.sh +++ b/run.sh @@ -239,6 +239,29 @@ case "$CONFIG" in torchrun --standalone --nproc_per_node=8 train_gpt_v2.py ;; + v8_static) + echo "=== Phase 8 H100: VE + static_graph DDP (test VE overhead fix) ===" + # Same as v7_ve but DDP(static_graph=True) — tests if overhead drops from 137ms to ~110ms + # If step_avg drops: ~5200 steps vs 4380, potential +0.006 BPB + export RUN_ID=v8_static_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ + LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ + VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 + torchrun --standalone --nproc_per_node=8 train_gpt_v2.py + ;; + + v7_ve_small) + echo "=== Phase 7 H100: 12L + Value Embeddings small (VE_DIM=64, last 1 layer) ===" + # Half VE overhead, ~50-75% of quality gain. If 27ms overhead is embed-size-driven, this helps. + export RUN_ID=v7_ve_small_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ + LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ + VALUE_EMBED_LAYERS=1 VALUE_EMBED_DIM=64 + torchrun --standalone --nproc_per_node=8 train_gpt_v2.py + ;; + v5_rownorm) echo "=== Phase 5 H100: Rownorm backend — DEPRECATED, rownorm hurt quality ===" echo "Use v6_parallel instead." @@ -268,7 +291,9 @@ case "$CONFIG" in echo "Phase 2: 11l | 12l | seq4096 | kv2 | bigram20k | noqat | 11l_kv2_b6k" echo "Phase 3: v3_abl | proxy_v3 | v3_h100" echo "Phase 4: proxy_v4 | v4_h100 (EMA+LateQAT fix, threshold=0.9)" - echo "Phase 6: v6_parallel (Parallel Muon: async RS + sharded NS5 + all-gather)" + echo "Phase 6: v6_parallel (Parallel Muon: DEPRECATED)" + echo "Phase 7: v7_ve | v7_ve_small (Value Embeddings)" + echo "Phase 8: v8_static (VE + DDP static_graph, overhead fix test)" exit 1 ;; esac diff --git a/train_gpt_v2.py b/train_gpt_v2.py index 2986b1685c..f8b24bccca 100644 --- a/train_gpt_v2.py +++ b/train_gpt_v2.py @@ -1346,7 +1346,7 @@ def _enable_qat() -> None: compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) if distributed: - model: nn.Module = DDP(compiled_model, device_ids=[device.index]) + model: nn.Module = DDP(compiled_model, device_ids=[device.index], static_graph=True) else: model = compiled_model From e8b8665667cc71daace60bd6486b6db012cbf39e Mon Sep 17 00:00:00 2001 From: Harsh Soni Date: Wed, 1 Apr 2026 05:11:27 +0000 Subject: [PATCH 3/9] v7_ve seed 3 (1.1580) + v9_13l code + v10_banked code (train_gpt_v3.py) --- PLAN.md | 252 +++ .../2026-03-28_12L_INT4_bQAT_VE/README.md | 3 +- requirements.txt | 4 +- run.sh | 42 +- train_gpt_v2.py | 20 +- train_gpt_v3.py | 1995 +++++++++++++++++ 6 files changed, 2305 insertions(+), 11 deletions(-) create mode 100644 PLAN.md create mode 100644 train_gpt_v3.py diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 0000000000..67597b47e8 --- /dev/null +++ b/PLAN.md @@ -0,0 +1,252 @@ +# Parameter Golf — Working Plan & Progress Tracker + +## Environment Setup (run at start of every new instance) +```bash +bash /vol/paraG/parameter-golf/setup.sh +export PATH="$HOME/.local/bin:$PATH" +source /vol/paraG/parameter-golf/.venv/bin/activate +cd /vol/paraG/parameter-golf +``` + +--- + +## ⚡ NEXT CLAUDE — START HERE (updated Mar 28 — v3 banking done) + +**Current best:** v7_ve seed 2, ttt_bpb=**1.15738** (PR: submission/12L-INT4-bQAT-VE) +**Model banking rewrite:** COMPLETE — `train_gpt_v3.py` ready, `v10_banked` config in `run.sh` + +### IMMEDIATE: Run v10_banked proxy smoke test (single GPU, 300 steps) +```bash +bash run.sh v10_banked_proxy +# Expected: step_avg ~110ms (no DDP), train loss ~3.1-3.3 at step 300 +# If it crashes → check logs. If slow → investigate. +``` + +### Then run v10_banked on 8×H100: +```bash +SEED=1 bash run.sh v10_banked +# Expected: ~90-100ms/step → ~6000-6700 steps → projected ~1.132-1.139 BPB +# Step avg at step 100 is the key signal: +# ~90ms → on track for 6700 steps +# ~100ms → on track for 6000 steps +# >110ms → Parallel Muon not working, investigate +``` + +### What changed in train_gpt_v3.py vs v2: +1. **Model Banking**: 4 contiguous 3D bank params replace per-layer CastedLinear + - `qo_bank[24,512,512]`, `kv_bank[24,256,512]`, `mlp_up_bank[12,1536,512]`, `mlp_down_bank[12,512,1536]` +2. **Parallel Muon**: async reduce-scatter → sharded NS5 → all-gather (no DDP) +3. **Bank QAT**: `GPT._fq(w, clip)` applies STE to bank slices during QAT +4. **Serialization**: `_unbank_state_dict()` + `_rebank_state_dict()` for quantization roundtrip + +### After run completes: +```bash +mkdir -p records/track_10min_16mb/2026-03-28_12L_banked_parallel_muon/ +cp train_gpt_v3.py records/track_10min_16mb/2026-03-28_12L_banked_parallel_muon/train_gpt.py +# write submission.json + README.md +git add records/track_10min_16mb/2026-03-28_12L_banked_parallel_muon/ train_gpt_v3.py run.sh +git commit -m "12L banked + Parallel Muon — ttt_bpb=X.XXXX" +# open new PR +``` + +--- + +## Git / PR Strategy (follow this every run) + +**Rule: every H100 run gets committed and pushed. No exceptions.** + +Even if it doesn't beat SOTA. Even if it's a failed experiment. The history matters. + +### After every run: +```bash +# 1. Create submission dir +mkdir -p records/track_10min_16mb/YYYY-MM-DD_short_description/ + +# 2. Copy relevant files in +cp train_gpt_v2.py records/track_10min_16mb/YYYY-MM-DD_.../train_gpt.py +# write submission.json, README.md, copy log if saved + +# 3. Commit everything changed (code + records dir) +git add records/track_10min_16mb/YYYY-MM-DD_.../ +git add train_gpt_v2.py run.sh # if changed since last commit +git commit -m "Short description of what changed and why" +git push fork main # or submission/branch-name + +# 4. Open PR on github +# - Record: normal submission title +# - Non-record: prefix title with "Non-record:" and explain what you learned +``` + +### PR types: +| Type | When | Title format | +|---|---|---| +| Record | New best ttt_bpb | "12L INT4 bQAT + VE — val_bpb 1.1550" | +| Non-record | Novel idea, failed experiment, analysis | "Non-record: VE overhead analysis + Parallel Muon findings" | + +**Non-record PRs are valuable.** They show active research, novel ideas, and build your leaderboard presence. Document what you tried and what you learned. + +--- + +## Full Experiment Log (Mar 28) + +### Run 1: v4_h100 seed 1 ✅ SUBMITTED +- **Config:** 12L INT4 bQAT, EMA_ENABLED=1, LATE_QAT_FRAC=0.65, XSA4, RoPE16, LN_SCALE, TTT +- **Result:** 5021 steps, post-quant 1.1703, ttt_bpb ~1.165 (TTT interrupted at 58%) +- **Artifact:** 15,899,385 bytes (15.90MB) +- **PR:** Pushed to fork, opened PR (review required) +- **Record dir:** `records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_EMAfix/` + +### Run 2: v5_rownorm seed 1 ❌ KILLED (step 100) +- **Config:** v4_h100 + MUON_BACKEND=rownorm (row-wise L2 norm replaces NS5) +- **Result:** train_loss=5.38 at step 100 (vs 3.18 for v4_h100) — catastrophic failure +- **step_avg:** 109ms (same as DDP — NS5 was NOT the bottleneck) +- **Lesson:** Row-norm doesn't produce orthogonal updates. NS5 is not the throughput bottleneck — DDP all_reduce is. +- **Code:** v5_rownorm config deprecated (exits with error in run.sh) +- **TODO:** Package as non-record PR with analysis + +### Run 3: v4_h100 seed 3 ✅ SUBMITTED (updated existing PR) +- **Config:** Same as seed 1 +- **Result:** post-quant 1.2002 (large QAT degradation), ttt_bpb **1.1594** (full 1893-chunk TTT) +- **Artifact:** 15,967,640 bytes (15.97MB) +- **Note:** Large post-quant degradation but TTT recovered aggressively. New best. +- **PR:** Updated submission.json (val_bpb 1.165→1.1594) + README, pushed to fork + +### Run 4: v6_parallel seed 1 ❌ KILLED (step ~800) +- **Config:** v4_h100 + Parallel Muon (one RS per matrix param, no DDP) +- **Result:** step_avg 148ms — WORSE than DDP 110ms +- **Lesson:** 40+ individual NCCL RS ops has higher overhead than DDP's single batched all_reduce +- **TODO:** Package as non-record PR with Parallel Muon analysis + +### Run 5: v6_parallel (virtual banking) seed 1 ❌ KILLED (step ~800) +- **Config:** v4_h100 + virtual banking Muon (group params by shape, one RS per shape group) +- **Result:** step_avg 117ms — still slower than DDP 110ms +- **Lesson:** Grad stacking copy overhead cancels NCCL savings. Need model banking (3D weight tensors) to avoid copies. +- **Analysis:** SOTA uses 4 banked 3D params (qo/kv/mlp_up/mlp_down). RS operates directly on banked grad — no copy. Without model banking, can't beat DDP. +- **TODO:** Package as non-record PR with virtual banking analysis + +### Run 7: v7_ve seed 2 ✅ NEW BEST +- **Config:** same as seed 1 with SEED=2 +- **step_avg:** 148ms final. post-quant 1.1624, ttt_bpb **1.15738** +- **Artifact:** 16,408,223 bytes (16.41MB) — within 16,777,216 limit ✓ +- **Key:** Seed 2 beat seed 1 by 0.00137 BPB +- **Submission dir:** Updated `records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/` +- **TODO:** Commit + push to `submission/12L-INT4-bQAT-VE` + +### Run 6: v7_ve seed 1 ✅ SUBMITTED +- **Config:** v4_h100 + VALUE_EMBED_LAYERS=2 + VALUE_EMBED_DIM=128 (VE at layers 10,11) +- **step_avg:** 137ms final (154ms last step during QAT). ~4380 total steps. +- **Result:** pre-quant 1.1754, post-quant 1.1643, ttt_bpb **1.15875** +- **Artifact:** 16,290,425 bytes (16.29MB) — within 16,777,216 limit ✓ +- **Val checkpoints:** step 1000: 1.2963 (+0.007 vs v4_h100), step 2000: 1.2344 (+0.014 vs v4_h100) +- **Key observation:** VE gave +0.014 BPB quality per step at step 2000. Despite 640 fewer steps, net gain of +0.0006 BPB over seed 3. Post-quant very clean (1.1643 vs seed 3's disastrous 1.2002). +- **Submission dir:** `records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/` +- **TODO:** Commit + push + open new PR + +--- + +## Throughput Analysis — Why Parallel Muon Needs Banking + +| Run | Approach | step_avg | Steps/10min | Notes | +|---|---|---|---|---| +| v4_h100 (DDP) | DDP all_reduce | ~110ms | ~5450 | 1 batched NCCL op | +| v6_parallel (per-param RS) | 40+ RS+AG ops | 148ms | ~4050 | NCCL launch overhead | +| v6_parallel (virtual banking) | 4-6 RS+AG ops | 117ms | ~5130 | Grad copy overhead | +| SOTA (model banking) | 4 RS+AG ops | 83ms | ~7230 | Grads already banked — no copy | + +**Root cause of gap:** SOTA stores weights as 3D tensors `(num_layers, M, K)`. Grad accumulates directly in this shape → RS operates on it with zero copy. Without model banking, any Parallel Muon implementation has extra grad copy overhead that negates NCCL savings. + +**To implement model banking:** Replace per-layer `nn.Linear` with 4 banked params (`qo_bank`, `kv_bank`, `mlp_up_bank`, `mlp_down_bank`). Forward uses `bank[layer_idx]`. Estimated: 1-2 days, gives ~85-90ms → +1400 steps → ~0.020 BPB. + +--- + +## Architecture — What We Have vs SOTA + +| Feature | Our v4_h100 | SOTA (PR#549) | Notes | +|---|---|---|---| +| Layers | 12 | 11 | We use 12L INT4 bQAT to fit more capacity | +| Param banking | ❌ | ✅ | Key throughput difference | +| INT4 MLP QAT | ✅ | ❌ | Our novel contribution | +| INT4 Bigram QAT | ✅ (novel) | ❌ | Saves 370KB vs INT6 | +| EMA + QAT reset | ✅ | ❌ | Our fix for EMA-QAT contamination | +| XSA last N | ✅ (4 layers) | ✅ (4 layers) | Same | +| Value Embeddings | 🔲 Testing | ✅ | Testing in v7_ve | +| Parallel Muon | ❌ (needs banking) | ✅ | 83ms vs our 110ms | +| Legal TTT | ✅ | ✅ | Same | +| LeakyReLU² | ✅ | ✅ | Same | +| U-Net skips | ✅ | ? | Our addition | +| resid_mix | ✅ | ? | Our addition | + +--- + +## Next Experiments Queue + +| Priority | Experiment | Config | Expected gain | Effort | Status | +|---|---|---|---|---|---| +| 1 | **v10_banked proxy** | `bash run.sh v10_banked_proxy` | Verify correctness, ~110ms single-GPU | Done | **RUN NOW** | +| 2 | **v10_banked SEED=1** | `SEED=1 bash run.sh v10_banked` | ~90-100ms/step → 6000+ steps → ~1.132-1.139 BPB | Done | **NEXT** | +| 3 | v10_banked SEED=2,3 | additional seeds | Seed variance ~0.005 | 0 | Queued | +| 4 | More v7_ve seeds | SEED=3,4 | Seed variance ~0.005 | 0 | Fallback | +| 5 | KL distillation from SOTA | new config | +0.010-0.020 BPB | 4-6h | Future | + +### v8_static result: FAILED (no improvement) +step_avg at step 700: **136ms** — identical to v7_ve (137ms). DDP static_graph did NOT fix VE overhead. +VE overhead is structural (not bucket ordering). Root cause unknown. Discarded. + +--- + +## Leaderboard (Mar 27) +| Rank | BPB | Author | PR | Notes | +|---|---|---|---|---| +| 1 | **1.1194** | abaybektursun | #549 | Bank-arch + ParallelMuon | +| 2 | 1.1228 | signalrush | #374 | | +| 3 | 1.1248 | jfprincz | #287 | | +| 4 | 1.1271 | jfprincz | #198 | | +| 5 | 1.1307 | unnir | | | +| **us** | **1.1594** | SoHarshh | open PR | 12L INT4 bQAT + EMAfix | + +Gap to SOTA: 0.040 BPB. Path: quality improvements (VE, distillation) + model banking. + +--- + +## Key Technical Findings + +1. **INT4 Bigram QAT** (novel): Quantize bigram hash table to INT4 during QAT. Saves ~370KB vs INT6. Enables 12L in 16MB. No prior submission has done this. + +2. **EMA reset at QAT activation**: Reset EMA state when QAT turns on, so EMA only averages QAT-adapted weights. Drops post-quant degradation from +0.193 BPB to +0.002 BPB. + +3. **LATE_QAT_FRAC=0.65**: Fire QAT at 65% of wallclock budget (390s). Immune to step_ms noise. Seeds are deterministic. + +4. **Parallel Muon dead end (without banking)**: Tried 3 implementations (per-param RS, virtual banking RS, row-norm). All slower than DDP without model banking. Model banking = full rewrite of weight storage from 2D per-layer to 3D banked tensors. + +5. **Value Embeddings**: Adding VE at 2 layers gives +0.007-0.014 BPB quality improvement per step but costs 27ms/step overhead (137ms vs 110ms). Net effect TBD from v7_ve final result. + +--- + +## Pending PRs to Open + +| Content | Type | Status | +|---|---|---| +| v4_h100 seed 3 (1.1594) | Record | ✅ Updated existing PR | +| Rownorm analysis + results | Non-record | TODO | +| Parallel Muon analysis (virtual banking) | Non-record | TODO | +| v7_ve results | Record or Non-record | Pending run completion | + +--- + +## Key File Locations +| File | Purpose | +|---|---| +| `train_gpt_v2.py` | Working file — all experiments | +| `run.sh` | All run configs | +| `final_model_v4_h100_seed3.int8.ptz` | Best artifact (15.97MB) | +| `records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_EMAfix/` | Current submission | +| `records/track_10min_16mb/2026-03-23_LeakyReLU_LegalTTT_ParallelMuon/train_gpt.py` | SOTA reference (1.1194) | + +--- + +## Rules +- No git push — user does this manually +- No GPU switching — user decides when to start/stop instances +- No AI traces in any submission files (README, train_gpt.py, submission.json, blurb) +- Keep submission.json val_bpb honest — use measured values +- Every H100 run gets a commit + PR (record or non-record) diff --git a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md index d64264b4da..511ec19bb4 100644 --- a/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md +++ b/records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/README.md @@ -7,7 +7,8 @@ | Seed | step_avg | steps | Pre-quant val/bpb | Post-quant bpb | Post-TTT bpb | Artifact | |------|----------|-------|-------------------|----------------|--------------|----------| | 1 | ~137ms | ~4380 | 1.1754 | 1.1643 | 1.1588 | 16,290,425 | -| 2 | ~148ms | — | 1.1736 | 1.1624 | **1.1574** | 16,408,223 | +| 2 | ~148ms | 4058 | 1.1736 | 1.1624 | **1.1574** | 16,408,223 | +| 3 | ~149ms | 4034 | — | 1.1661 | 1.1580 | 16,441,654 | ## Architecture diff --git a/requirements.txt b/requirements.txt index 911b0e52f0..48494b9881 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,6 @@ setuptools typing-extensions==4.15.0 datasets tiktoken -sentencepiece \ No newline at end of file +sentencepiece +zstandard +wandb \ No newline at end of file diff --git a/run.sh b/run.sh index 151d5bb653..2a6028895a 100644 --- a/run.sh +++ b/run.sh @@ -239,6 +239,20 @@ case "$CONFIG" in torchrun --standalone --nproc_per_node=8 train_gpt_v2.py ;; + v9_13l_int4attn) + echo "=== Phase 9 H100: 13L + INT4 MLP + INT4 Attn + VE (new depth via attn INT4 savings) ===" + # INT4 attn saves ~1.2MB vs INT6 attn → enough budget for 13th layer within 16MB + # Expected: 13/12 * 137ms ≈ 149ms/step, ~4040 steps. Gain from depth vs loss from INT4 attn = unknown + # Last c_k stays FP16 (hardcoded exemption), protecting the most numerically sensitive weight + export RUN_ID=v9_13l_int4attn_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=13 MLP_QUANT_BITS=4 ATTN_QAT_BITS=4 \ + XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ + LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ + VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 + torchrun --standalone --nproc_per_node=8 train_gpt_v2.py + ;; + v8_static) echo "=== Phase 8 H100: VE + static_graph DDP (test VE overhead fix) ===" # Same as v7_ve but DDP(static_graph=True) — tests if overhead drops from 137ms to ~110ms @@ -262,6 +276,30 @@ case "$CONFIG" in torchrun --standalone --nproc_per_node=8 train_gpt_v2.py ;; + v10_banked) + echo "=== Phase 10 H100: Model Banking + Parallel Muon (train_gpt_v3.py) ===" + # Full model banking rewrite: qo_bank[24,512,512], kv_bank[24,256,512], mlp_up_bank[12,1536,512], mlp_down_bank[12,512,1536] + # Parallel Muon: async reduce-scatter → sharded NS5 → all-gather. No DDP. + # Expected: ~90-100ms/step → ~6000-6700 steps → ~1.132-1.139 BPB + export RUN_ID=v10_banked_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ + LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ + VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 + torchrun --standalone --nproc_per_node=8 train_gpt_v3.py + ;; + + v10_banked_proxy) + echo "=== Phase 10 PROXY: Model Banking + Parallel Muon single-GPU smoke test ===" + # Single GPU, 300 steps, no wallclock cap. Verifies correctness and baseline loss. + export RUN_ID=v10_banked_proxy SEED=${SEED:-1} MAX_WALLCLOCK_SECONDS=0 \ + ITERATIONS=300 VAL_LOSS_EVERY=100 \ + NUM_LAYERS=12 MLP_QUANT_BITS=4 XSA_LAST_N=4 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=0 \ + VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 + torchrun --standalone --nproc_per_node=1 train_gpt_v3.py + ;; + v5_rownorm) echo "=== Phase 5 H100: Rownorm backend — DEPRECATED, rownorm hurt quality ===" echo "Use v6_parallel instead." @@ -292,8 +330,10 @@ case "$CONFIG" in echo "Phase 3: v3_abl | proxy_v3 | v3_h100" echo "Phase 4: proxy_v4 | v4_h100 (EMA+LateQAT fix, threshold=0.9)" echo "Phase 6: v6_parallel (Parallel Muon: DEPRECATED)" + echo "Phase 10: v10_banked | v10_banked_proxy (Model Banking + Parallel Muon, train_gpt_v3.py)" echo "Phase 7: v7_ve | v7_ve_small (Value Embeddings)" - echo "Phase 8: v8_static (VE + DDP static_graph, overhead fix test)" + echo "Phase 8: v8_static (VE + DDP static_graph, overhead fix test — no improvement found)" + echo "Phase 9: v9_13l_int4attn (13L + INT4 MLP + INT4 Attn + VE, novel depth bet)" exit 1 ;; esac diff --git a/train_gpt_v2.py b/train_gpt_v2.py index f8b24bccca..182da0d77d 100644 --- a/train_gpt_v2.py +++ b/train_gpt_v2.py @@ -100,9 +100,10 @@ class Hyperparameters: ema_decay = float(os.environ.get("EMA_DECAY", "0.997")) # QAT: fake-quantize weights during training to match PTQ targets - # MLP precision: INT4 (clip=7) or INT5 (clip=15, default); INT6 for attention (clip=31) + # MLP precision: INT4 (clip=7) or INT5 (clip=15, default); ATTN default INT6 (clip=31) qat_enabled = bool(int(os.environ.get("QAT_ENABLED", "1"))) mlp_quant_bits = int(os.environ.get("MLP_QUANT_BITS", "5")) # 4 or 5 + attn_quant_bits = int(os.environ.get("ATTN_QAT_BITS", "6")) # 6=INT6(default), 4=INT4 # XSA: Cross-Sequence Attention on last N layers (subtracts self-value projection) xsa_last_n = int(os.environ.get("XSA_LAST_N", 0)) @@ -386,7 +387,7 @@ def quantize_intN_per_row(t: Tensor, clip_range: int = 31) -> tuple[Tensor, Tens return q, scale -def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15): +def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15, attn_clip: int = 31): result: dict[str, Tensor] = {} meta: dict[str, object] = {} for name, tensor in state_dict.items(): @@ -406,14 +407,16 @@ def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_ continue if cat in int6_cats and t.ndim >= 1: # MLP: always uses mlp_clip (INT4 or INT5) + # attn: uses attn_clip (INT6 default, INT4 when ATTN_QAT_BITS=4) # bigram/trigram: follow mlp_clip when INT4 (saves ~0.25MB), else INT6 - # attn and others: INT6 if cat == "mlp": clip = mlp_clip + elif cat == "attn": + clip = attn_clip elif cat in ("bigram", "trigram") and mlp_clip <= 7: clip = mlp_clip # INT4 bigram/trigram when MLP is INT4 else: - clip = 31 # INT6 for attn, bigram/trigram in INT5 mode + clip = 31 # INT6 for bigram/trigram in INT5 mode q, s = quantize_intN_per_row(t, clip_range=clip) result[name + ".q"] = q result[name + ".scale"] = s @@ -1306,6 +1309,7 @@ def log0(msg: str, console: bool = True) -> None: # QAT: set per-layer fake-quantization targets # MLP precision controlled by MLP_QUANT_BITS (4=INT4 clip=7, 5=INT5 clip=15) mlp_clip = (1 << (args.mlp_quant_bits - 1)) - 1 # 5→15, 4→7 + attn_clip = (1 << (args.attn_quant_bits - 1)) - 1 # 6→31, 4→7 ngram_clip = mlp_clip if args.mlp_quant_bits <= 4 else 31 # INT4 bigram/trigram when MLP is INT4 _qat_active = False # tracks whether fake-quant has been activated @@ -1323,18 +1327,18 @@ def _enable_qat() -> None: if ".mlp." in name: module._qat_clip_range = mlp_clip elif ".attn." in name: - module._qat_clip_range = 31 + module._qat_clip_range = attn_clip elif "bigram" in name or "trigram" in name: module._qat_clip_range = ngram_clip else: - module._qat_clip_range = 31 + module._qat_clip_range = attn_clip if base_model.bigram is not None: base_model.bigram._qat_clip_range = ngram_clip if base_model.trigram is not None: base_model.trigram._qat_clip_range = ngram_clip ngram_bits = '4' if ngram_clip <= 7 else '6' trig_str = f" trigram=INT{ngram_bits}(clip={ngram_clip})" if base_model.trigram is not None else "" - log0(f"qat:enabled mlp=INT{args.mlp_quant_bits}(clip={mlp_clip}) attn=INT6(clip=31) bigram=INT{ngram_bits}(clip={ngram_clip}){trig_str}") + log0(f"qat:enabled mlp=INT{args.mlp_quant_bits}(clip={mlp_clip}) attn=INT{args.attn_quant_bits}(clip={attn_clip}) bigram=INT{ngram_bits}(clip={ngram_clip}){trig_str}") if args.qat_enabled: if args.late_qat_threshold > 0: @@ -1664,7 +1668,7 @@ def lr_mul(step: int, elapsed_ms: float) -> float: if base_model.trigram is not None: int6_cats.add("trigram") sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} - quant_result, quant_meta = mixed_quantize_int6(sd_cpu, int6_cats, mlp_clip=mlp_clip) + quant_result, quant_meta = mixed_quantize_int6(sd_cpu, int6_cats, mlp_clip=mlp_clip, attn_clip=attn_clip) quant_buf = io.BytesIO() torch.save({"w": quant_result, "m": quant_meta}, quant_buf) quant_raw = quant_buf.getvalue() diff --git a/train_gpt_v3.py b/train_gpt_v3.py new file mode 100644 index 0000000000..589ee84e75 --- /dev/null +++ b/train_gpt_v3.py @@ -0,0 +1,1995 @@ +from __future__ import annotations + +import copy +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import uuid +import zlib +from pathlib import Path + +try: + import zstandard + _COMPRESSOR = "zstd" +except ImportError: + _COMPRESSOR = "zlib" + +try: + import wandb + _WANDB_AVAILABLE = True +except ImportError: + _WANDB_AVAILABLE = False + +import numpy as np +import sentencepiece as spm +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import Tensor, nn +from torch.nn.parallel import DistributedDataParallel as DDP + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- + +class Hyperparameters: + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024") + train_files = os.path.join(data_path, "fineweb_train_*.bin") + val_files = os.path.join(data_path, "fineweb_val_*.bin") + tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 42)) + + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 500)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 100)) + + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3000)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 786_432)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2048)) + max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + + vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) + num_layers = int(os.environ.get("NUM_LAYERS", 10)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 4)) + model_dim = int(os.environ.get("MODEL_DIM", 512)) + num_heads = int(os.environ.get("NUM_HEADS", 8)) + mlp_mult = float(os.environ.get("MLP_MULT", 3.0)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.008)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.03)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.02)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.02)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.3)) + weight_decay = float(os.environ.get("WEIGHT_DECAY", 0.04)) + + eval_stride = int(os.environ.get("EVAL_STRIDE", 64)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 32)) + + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + trigram_vocab_size = int(os.environ.get("TRIGRAM_VOCAB_SIZE", 0)) # 0 = disabled + trigram_dim = int(os.environ.get("TRIGRAM_DIM", 64)) + + swa_enabled = bool(int(os.environ.get("SWA_ENABLED", "1"))) + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.4)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + + # EMA: exponential moving average of weights (replaces SWA when enabled) + ema_enabled = bool(int(os.environ.get("EMA_ENABLED", "0"))) + ema_decay = float(os.environ.get("EMA_DECAY", "0.997")) + + # QAT: fake-quantize weights during training to match PTQ targets + # MLP precision: INT4 (clip=7) or INT5 (clip=15, default); ATTN default INT6 (clip=31) + qat_enabled = bool(int(os.environ.get("QAT_ENABLED", "1"))) + mlp_quant_bits = int(os.environ.get("MLP_QUANT_BITS", "5")) # 4 or 5 + attn_quant_bits = int(os.environ.get("ATTN_QAT_BITS", "6")) # 6=INT6(default), 4=INT4 + + # XSA: Cross-Sequence Attention on last N layers (subtracts self-value projection) + xsa_last_n = int(os.environ.get("XSA_LAST_N", 0)) + + # Partial RoPE: apply RoPE to only first rope_dims dims of head_dim (0 = full) + rope_dims = int(os.environ.get("ROPE_DIMS", 0)) + + # LN Scale: scale norm input by 1/sqrt(layer_idx+1) for depth stability + ln_scale = bool(int(os.environ.get("LN_SCALE", "0"))) + + # Late QAT: delay fake-quantize until LR scale drops below threshold (0 = from start) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", "0")) + + # ValueEmbedding: reinject token identity into V at last N layers (0 = disabled) + value_embed_layers = int(os.environ.get("VALUE_EMBED_LAYERS", "0")) + value_embed_dim = int(os.environ.get("VALUE_EMBED_DIM", "64")) + + # TTT: Legal score-first test-time training at final eval + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "0"))) + ttt_lr = float(os.environ.get("TTT_LR", "0.002")) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", "3")) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", "32768")) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", "0")) + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", "0.9")) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", "32")) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", "1.0")) + +# ----------------------------- +# MUON OPTIMIZER — Parallel Muon (async reduce-scatter → sharded NS5 → all-gather) +# ----------------------------- + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 5, eps: float = 1e-7) -> Tensor: + """Batched Newton-Schulz orthogonalization. Accepts (B,M,N) or (M,N).""" + a, b, c = (3.4445, -4.7750, 2.0315) + was_2d = G.ndim == 2 + if was_2d: + G = G.unsqueeze(0) + X = G.bfloat16() + transposed = X.size(-2) > X.size(-1) + if transposed: + X = X.mT + X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps) + for _ in range(steps): + A = X @ X.mT + B = b * A + c * (A @ A) + X = a * X + B @ X + if transposed: + X = X.mT + if was_2d: + X = X.squeeze(0) + return X + + +class Muon(torch.optim.Optimizer): + """Parallel Muon: post-backward reduce-scatter -> local NS5 -> all-gather. + + No DDP for bank params. After backward, this optimizer: + 1. Launches async reduce-scatter for all banks (biggest first) + 2. Returns control so Adam can step on small params while RS is in-flight + 3. Waits for each RS, runs local NS5 on the shard, launches async all-gather + 4. Each all-gather overlaps with next bank's NS5 + """ + def __init__(self, params, lr: float, momentum: float, backend_steps: int, + nesterov: bool = True, weight_decay: float = 0.0): + super().__init__( + params, + dict(lr=lr, momentum=momentum, backend_steps=backend_steps, + nesterov=nesterov, weight_decay=weight_decay), + ) + self._built = False + + def _build(self): + self._distributed = dist.is_available() and dist.is_initialized() + self._world_size = dist.get_world_size() if self._distributed else 1 + self._rank = dist.get_rank() if self._distributed else 0 + ws = self._world_size + + self._bank_meta = [] + for group in self.param_groups: + for p in group["params"]: + B = p.shape[0] + padded_B = ((B + ws - 1) // ws) * ws + shard_B = padded_B // ws + tail = p.shape[1:] + dev = p.device + self._bank_meta.append({ + 'p': p, + 'B': B, + 'padded_grad': torch.zeros(padded_B, *tail, device=dev, dtype=torch.bfloat16), + 'shard': torch.zeros(shard_B, *tail, device=dev, dtype=torch.bfloat16), + 'shard_mom': torch.zeros(shard_B, *tail, device=dev, dtype=torch.bfloat16), + 'full_update': torch.zeros(padded_B, *tail, device=dev, dtype=torch.bfloat16), + 'scale': max(1, p.shape[-2] / p.shape[-1]) ** 0.5, + }) + # Sort by size descending -- launch biggest reduce-scatters first + self._bank_meta.sort(key=lambda m: -m['p'].numel()) + self._built = True + + def launch_reduce_scatters(self): + """Phase 1: launch async reduce-scatter for all banks. Call right after backward.""" + if not self._built: + self._build() + if not self._distributed: + return + self._rs_futures = [] + for m in self._bank_meta: + p = m['p'] + if p.grad is None: + self._rs_futures.append(None) + continue + pg = m['padded_grad'] + pg[:m['B']].copy_(p.grad.bfloat16()) + if pg.shape[0] > m['B']: + pg[m['B']:].zero_() + fut = dist.reduce_scatter_tensor(m['shard'], pg, op=dist.ReduceOp.AVG, async_op=True) + self._rs_futures.append(fut) + + @torch.no_grad() + def step(self, closure=None): + """Phase 3: wait for RS, local NS5, all-gather. Call AFTER Adam steps.""" + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + if not self._built: + self._build() + + for group in self.param_groups: + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + wd = group.get("weight_decay", 0.0) + + prev_ag_handle = None + prev_m = None + + sharded = self._distributed and hasattr(self, '_rs_futures') + + for i, m in enumerate(self._bank_meta): + p = m['p'] + if p.grad is None: + continue + + if prev_ag_handle is not None: + prev_ag_handle.wait() + pp = prev_m['p'] + upd = prev_m['full_update'][:prev_m['B']] + if wd > 0.0: + pp.data.mul_(1.0 - lr * wd) + pp.add_(upd.to(dtype=pp.dtype), alpha=-lr * prev_m['scale']) + + if sharded and self._rs_futures[i] is not None: + self._rs_futures[i].wait() + g = m['shard'] + buf = m['shard_mom'] + else: + g = p.grad.bfloat16() + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + + buf.mul_(momentum).add_(g) + if nesterov: + update = g.add(buf, alpha=momentum) + else: + update = buf + + update = zeropower_via_newtonschulz5(update, steps=backend_steps) + + if sharded: + prev_ag_handle = dist.all_gather_into_tensor( + m['full_update'], update, async_op=True) + prev_m = m + else: + if wd > 0.0: + p.data.mul_(1.0 - lr * wd) + p.add_(update.to(dtype=p.dtype), alpha=-lr * m['scale']) + + if prev_ag_handle is not None: + prev_ag_handle.wait() + pp = prev_m['p'] + upd = prev_m['full_update'][:prev_m['B']] + if wd > 0.0: + pp.data.mul_(1.0 - lr * wd) + pp.add_(upd.to(dtype=pp.dtype), alpha=-lr * prev_m['scale']) + + if hasattr(self, '_rs_futures'): + del self._rs_futures + + return loss + + +def _apply_vbank_update(vb: dict, lr: float, wd: float) -> None: + pass # unused stub kept for import compatibility + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION +# ----------------------------- + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("\u2581"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return ( + torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device), + ) + + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError( + "VAL_BATCH_SIZE must provide at least one sequence per rank; " + f"got VAL_BATCH_SIZE={args.val_batch_size}, WORLD_SIZE={world_size}, " + f"GRAD_ACCUM_STEPS={grad_accum_steps}, TRAIN_SEQ_LEN={args.train_seq_len}" + ) + local_batch_seqs = local_batch_tokens // args.train_seq_len + total_seqs = (val_tokens.numel() - 1) // args.train_seq_len + seq_start = (total_seqs * rank) // world_size + seq_end = (total_seqs * (rank + 1)) // world_size + val_loss_sum = torch.zeros((), device=device, dtype=torch.float64) + val_token_count = torch.zeros((), device=device, dtype=torch.float64) + val_byte_count = torch.zeros((), device=device, dtype=torch.float64) + model.eval() + with torch.inference_mode(): + for batch_seq_start in range(seq_start, seq_end, local_batch_seqs): + batch_seq_end = min(batch_seq_start + local_batch_seqs, seq_end) + raw_start = batch_seq_start * args.train_seq_len + raw_end = batch_seq_end * args.train_seq_len + 1 + local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True) + x = local[:-1].reshape(-1, args.train_seq_len) + y = local[1:].reshape(-1, args.train_seq_len) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + batch_loss = model(x, y).detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +# ----------------------------- +# QUANTIZATION (INT5 MLP / INT6 ATTN mixed PTQ) +# ----------------------------- + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights,smear,bigram.scale,trigram.scale,ve_layer_scales,ve_shared.scale", + ).split(",") + if pattern +) +FP16_KEEP_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get("FP16_KEEP_NAME_PATTERNS", "tok_emb,blocks.8.attn.c_k").split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 + +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + INT8_CLIP_Q = 99.99984 / 100.0 + t32 = t.float() + if t32.ndim == 2: + clip_abs = ( + torch.quantile(t32.abs(), INT8_CLIP_Q, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + clipped = torch.maximum(torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None]) + scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) + q = torch.clamp(torch.round(clipped / scale[:, None]), -127, 127).to(torch.int8).contiguous() + return q, scale.to(dtype=torch.float16).contiguous() + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127).to(torch.int8).contiguous() + return q, scale + + +def _classify_param(name: str) -> str: + if "tok_emb" in name or "lm_head" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if "bigram" in name: + return "bigram" + if "trigram" in name: + return "trigram" + if ".attn." in name or (".proj." in name and ".mlp." not in name): + return "attn" + return "other" + + +def quantize_intN_per_row(t: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + """Quantize with GPTQ-lite: search 5 clip percentiles, pick best MSE.""" + t32 = t.float() + if t32.ndim == 2: + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 0.99999, 1.0]: + if pct < 1.0: + row_clip = torch.quantile(t32.abs(), pct, dim=1) + else: + row_clip = t32.abs().amax(dim=1) + scale = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + scale = scale.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(t32 / scale.float()[:, None]), -(clip_range + 1), clip_range).to(torch.int8) + err = (t32 - q.float() * scale.float()[:, None]).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, scale, err + return best_q, best_s + amax = t32.abs().max().item() + scale = torch.tensor(max(amax / clip_range, 1e-12), dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -(clip_range + 1), clip_range).to(torch.int8) + return q, scale + + +def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15, attn_clip: int = 31): + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param(name) + if not t.is_floating_point() or t.numel() <= 8192: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + if any(pattern in name for pattern in FP16_KEEP_NAME_PATTERNS): + result[name] = t.to(dtype=torch.float16).contiguous() + meta[name] = "passthrough_fp16" + continue + if cat in int6_cats and t.ndim >= 1: + # MLP: always uses mlp_clip (INT4 or INT5) + # attn: uses attn_clip (INT6 default, INT4 when ATTN_QAT_BITS=4) + # bigram/trigram: follow mlp_clip when INT4 (saves ~0.25MB), else INT6 + if cat == "mlp": + clip = mlp_clip + elif cat == "attn": + clip = attn_clip + elif cat in ("bigram", "trigram") and mlp_clip <= 7: + clip = mlp_clip # INT4 bigram/trigram when MLP is INT4 + else: + clip = 31 # INT6 for bigram/trigram in INT5 mode + q, s = quantize_intN_per_row(t, clip_range=clip) + result[name + ".q"] = q + result[name + ".scale"] = s + bits = clip.bit_length() + 1 # clip=31→int6, clip=15→int5, clip=7→int4 + meta[name] = {"type": f"int{bits}"} + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return result, meta + + +def dequantize_mixed_int6(result: dict[str, Tensor], meta: dict[str, object], + template_sd: dict[str, Tensor]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + for name, orig in template_sd.items(): + info = meta[name] + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl", "passthrough_fp16"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + + +# ----------------------------- +# DATA LOADING +# ----------------------------- + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = rank + self.world_size = world_size + self.device = device + self.stream = TokenStream(pattern) + + def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> tuple[Tensor, Tensor]: + local_tokens = global_tokens // (self.world_size * grad_accum_steps) + per_rank_span = local_tokens + 1 + chunk = self.stream.take(per_rank_span * self.world_size) + start = self.rank * per_rank_span + local = chunk[start : start + per_rank_span].to(dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + return x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) + + +# ----------------------------- +# TRANSFORMER MODULES +# ----------------------------- + +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + + +class CastedLinear(nn.Linear): + # _qat_clip_range: 127=off/INT8, 31=INT6, 15=INT5 + _qat_clip_range: int = 127 + + def forward(self, x: Tensor) -> Tensor: + w = self.weight + if self.training and self._qat_clip_range < 127 and w.ndim == 2: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w.to(x.dtype), bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int = 0): + super().__init__() + self.rope_dims = rope_dims if rope_dims > 0 else dim + rd = self.rope_dims + inv_freq = 1.0 / (base ** (torch.arange(0, rd, 2, dtype=torch.float32) / rd)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + rd = cos.size(-1) * 2 + if rd < x.size(-1): # partial RoPE: rotate first rd dims, pass rest unchanged + x_rope, x_pass = x[..., :rd], x[..., rd:] + half = rd // 2 + x1, x2 = x_rope[..., :half], x_rope[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + + +class CausalSelfAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, rope_base: float, qk_gain_init: float, rope_dims: int = 0): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + # No CastedLinear weights -- come from GPT banks + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base, rope_dims=rope_dims) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + """XSA: subtract self-value projection, forcing heads to attend to OTHER tokens.""" + B, T, H, D = y.shape + Hkv = v.size(2) # v is [B, T, Hkv, D] + group = H // Hkv + y_g = y.reshape(B, T, Hkv, group, D) + vn = F.normalize(v, dim=-1).unsqueeze(3) # [B, T, Hkv, 1, D] + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, q_w: Tensor, k_w: Tensor, v_w: Tensor, out_w: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + bsz, seqlen, dim = x.shape + q = F.linear(x, q_w.to(x.dtype)).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = F.linear(x, k_w.to(x.dtype)).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v_raw = F.linear(x, v_w.to(x.dtype)) + if v_embed is not None: + v_raw = v_raw + v_embed + v_bthd = v_raw.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + v = v_bthd.transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention( + q, k, v, attn_mask=None, is_causal=True, + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + y = y.transpose(1, 2).contiguous() + if self.use_xsa: + y = self._xsa_efficient(y, v_bthd) + y = y.reshape(bsz, seqlen, dim) + return F.linear(y, out_w.to(x.dtype)) + + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: float): + super().__init__() + # No CastedLinear weights -- come from GPT banks + + def forward(self, x: Tensor, up_w: Tensor, down_w: Tensor) -> Tensor: + x = F.leaky_relu(F.linear(x, up_w.to(x.dtype)), negative_slope=0.5) + return F.linear(x.square(), down_w.to(x.dtype)) + + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate.to(dtype=x.dtype))[None, None, :] + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1 - g) * x + g * x_prev + + +class BigramHashEmbedding(nn.Module): + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, bigram_vocab_size: int, bigram_dim: int, model_dim: int): + super().__init__() + self.bigram_vocab_size = bigram_vocab_size + self.embed = nn.Embedding(bigram_vocab_size, bigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(bigram_dim, model_dim, bias=False) if bigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.05, dtype=torch.float32)) + + def bigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.bigram_vocab_size - 1 + out = torch.empty_like(t) + out[..., 0] = mod + out[..., 1:] = torch.bitwise_xor(36313 * t[..., 1:], 27191 * t[..., :-1]) % mod + return out.long() + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.bigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class TrigramHashEmbedding(nn.Module): + """3-gram context embedding: (prev2, prev1, curr) → hashed bucket → learned embedding.""" + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, trigram_vocab_size: int, trigram_dim: int, model_dim: int): + super().__init__() + self.trigram_vocab_size = trigram_vocab_size + self.embed = nn.Embedding(trigram_vocab_size, trigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(trigram_dim, model_dim, bias=False) if trigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.02, dtype=torch.float32)) + + def trigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.trigram_vocab_size - 1 + out = torch.full_like(t, mod, dtype=torch.long) # sentinel for positions without full context + out[..., 2:] = ( + torch.bitwise_xor( + torch.bitwise_xor(17291 * t[..., 2:], 36313 * t[..., 1:-1]), + 27191 * t[..., :-2], + ) % mod + ) + return out + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.trigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class ValueEmbedding(nn.Module): + """Reinject token identity into attention values at specific layers. + Shared embedding table + per-layer learned scale. Applied at last N layers.""" + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int): + super().__init__() + self.embed = nn.Embedding(vocab_size, ve_dim) + nn.init.normal_(self.embed.weight, std=0.01) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) if ve_dim != kv_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.1, dtype=torch.float32)) + + def forward(self, token_ids: Tensor) -> Tensor: + h = self.embed(token_ids) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class Block(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, mlp_mult: float, rope_base: float, qk_gain_init: float, rope_dims: int = 0, ln_scale: bool = False, layer_idx: int = 0): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, rope_dims=rope_dims) + self.mlp = MLP(dim, mlp_mult) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + + def forward(self, x: Tensor, x0: Tensor, q_w: Tensor, k_w: Tensor, v_w: Tensor, out_w: Tensor, up_w: Tensor, down_w: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + s = self.ln_scale_factor + attn_out = self.attn(self.attn_norm(x) * s, q_w, k_w, v_w, out_w, v_embed=v_embed) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * s, up_w, down_w) + return x + + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_layers: int, + model_dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: float, + tie_embeddings: bool, + tied_embed_init_std: float, + logit_softcap: float, + rope_base: float, + qk_gain_init: float, + bigram_vocab_size: int = 0, + bigram_dim: int = 128, + trigram_vocab_size: int = 0, + trigram_dim: int = 64, + rope_dims: int = 0, + ln_scale: bool = False, + xsa_last_n: int = 0, + value_embed_layers: int = 0, + value_embed_dim: int = 64, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.bigram = BigramHashEmbedding(bigram_vocab_size, bigram_dim, model_dim) if bigram_vocab_size > 0 else None + self.trigram = TrigramHashEmbedding(trigram_vocab_size, trigram_dim, model_dim) if trigram_vocab_size > 0 else None + self.num_encoder_layers = num_layers // 2 + self.num_decoder_layers = num_layers - self.num_encoder_layers + self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers) + self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32)) + self.smear = SmearGate(model_dim) + # Parameter banks: contiguous 3D tensors for Parallel Muon + head_dim = model_dim // num_heads + kv_dim = num_kv_heads * head_dim + mlp_dim = int(mlp_mult * model_dim) + self.num_layers = num_layers + self.qo_bank = nn.Parameter(torch.empty(2 * num_layers, model_dim, model_dim)) + self.kv_bank = nn.Parameter(torch.empty(2 * num_layers, kv_dim, model_dim)) + self.mlp_up_bank = nn.Parameter(torch.empty(num_layers, mlp_dim, model_dim)) + self.mlp_down_bank = nn.Parameter(torch.empty(num_layers, model_dim, mlp_dim)) + self.blocks = nn.ModuleList( + [ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init, + rope_dims=rope_dims, ln_scale=ln_scale, layer_idx=i) + for i in range(num_layers) + ] + ) + if xsa_last_n > 0: + for i in range(max(0, num_layers - xsa_last_n), num_layers): + self.blocks[i].attn.use_xsa = True + # ValueEmbedding: shared table + per-layer scales for last N layers + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve_layer_indices = list(range(max(0, num_layers - value_embed_layers), num_layers)) if value_embed_layers > 0 else [] + if self.ve_layer_indices: + self.ve_shared = ValueEmbedding(vocab_size, value_embed_dim, kv_dim) + self.ve_layer_scales = nn.ParameterList( + [nn.Parameter(torch.ones(1, dtype=torch.float32)) for _ in self.ve_layer_indices] + ) + else: + self.ve_shared = None + self.ve_layer_scales = nn.ParameterList() + self.final_norm = RMSNorm() + self.lm_head = None if tie_embeddings else CastedLinear(model_dim, vocab_size, bias=False) + if self.lm_head is not None: + self.lm_head._zero_init = True + self._init_weights() + + def _init_weights(self) -> None: + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) + n = self.num_layers + proj_scale = 1.0 / math.sqrt(2 * n) + for i in range(n): + nn.init.orthogonal_(self.qo_bank.data[i], gain=1.0) # Q + nn.init.zeros_(self.qo_bank.data[n + i]) # Out (zero init) + self.qo_bank.data[n + i].mul_(proj_scale) + nn.init.orthogonal_(self.kv_bank.data[i], gain=1.0) # K + nn.init.orthogonal_(self.kv_bank.data[n + i], gain=1.0) # V + nn.init.orthogonal_(self.mlp_up_bank.data[i], gain=1.0) # MLP up + nn.init.zeros_(self.mlp_down_bank.data[i]) # MLP down (zero init) + self.mlp_down_bank.data[i].mul_(proj_scale) + # Init remaining nn.Linear modules (bigram proj, trigram proj, lm_head) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and module.weight.shape[0] >= 64 and module.weight.shape[1] >= 64: + nn.init.orthogonal_(module.weight, gain=1.0) + + # QAT clip ranges: 127=off, 31=INT6, 15=INT5, 7=INT4 + _qat_mlp_clip: int = 127 + _qat_attn_clip: int = 127 + + def _fq(self, w: Tensor, clip: int) -> Tensor: + """Fake-quantize bank weight w using STE. Returns w unchanged when clip >= 127.""" + if not self.training or clip >= 127: + return w + w_f = w.float() + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / float(clip) + q = (w_f / scale).round().clamp(-float(clip + 1), float(clip)) + w_q = q * scale + return w + (w_q - w_f).detach() + + def _get_ve(self, layer_idx: int, ve_base: "Tensor | None") -> "Tensor | None": + if ve_base is None or layer_idx not in self.ve_layer_indices: + return None + idx = self.ve_layer_indices.index(layer_idx) + return ve_base * self.ve_layer_scales[idx].to(dtype=ve_base.dtype) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + n = self.num_layers + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + q_w = self._fq(self.qo_bank[i], self._qat_attn_clip) + out_w = self._fq(self.qo_bank[n + i], self._qat_attn_clip) + k_w = self._fq(self.kv_bank[i], self._qat_attn_clip) + v_w = self._fq(self.kv_bank[n + i], self._qat_attn_clip) + up_w = self._fq(self.mlp_up_bank[i], self._qat_mlp_clip) + down_w = self._fq(self.mlp_down_bank[i], self._qat_mlp_clip) + x = self.blocks[i](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + bi = self.num_encoder_layers + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + q_w = self._fq(self.qo_bank[bi], self._qat_attn_clip) + out_w = self._fq(self.qo_bank[n + bi], self._qat_attn_clip) + k_w = self._fq(self.kv_bank[bi], self._qat_attn_clip) + v_w = self._fq(self.kv_bank[n + bi], self._qat_attn_clip) + up_w = self._fq(self.mlp_up_bank[bi], self._qat_mlp_clip) + down_w = self._fq(self.mlp_down_bank[bi], self._qat_mlp_clip) + x = self.blocks[bi](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, v_embed=self._get_ve(bi, ve_base)) + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + n = self.num_layers + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + q_w = self._fq(self.qo_bank[i], self._qat_attn_clip) + out_w = self._fq(self.qo_bank[n + i], self._qat_attn_clip) + k_w = self._fq(self.kv_bank[i], self._qat_attn_clip) + v_w = self._fq(self.kv_bank[n + i], self._qat_attn_clip) + up_w = self._fq(self.mlp_up_bank[i], self._qat_mlp_clip) + down_w = self._fq(self.mlp_down_bank[i], self._qat_mlp_clip) + x = self.blocks[i](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + bi = self.num_encoder_layers + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + q_w = self._fq(self.qo_bank[bi], self._qat_attn_clip) + out_w = self._fq(self.qo_bank[n + bi], self._qat_attn_clip) + k_w = self._fq(self.kv_bank[bi], self._qat_attn_clip) + v_w = self._fq(self.kv_bank[n + bi], self._qat_attn_clip) + up_w = self._fq(self.mlp_up_bank[bi], self._qat_mlp_clip) + down_w = self._fq(self.mlp_down_bank[bi], self._qat_mlp_clip) + x = self.blocks[bi](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, v_embed=self._get_ve(bi, ve_base)) + x = self.final_norm(x) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + logits_proj = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + + +def _unbank_state_dict(sd: dict, num_layers: int) -> dict: + """Convert 3D bank tensors into individual 2D tensors with standard per-layer names.""" + out = {} + n = num_layers + for name, tensor in sd.items(): + if name == "qo_bank": + for i in range(n): + out[f"blocks.{i}.attn.c_q.weight"] = tensor[i] + out[f"blocks.{i}.attn.proj.weight"] = tensor[n + i] + elif name == "kv_bank": + for i in range(n): + out[f"blocks.{i}.attn.c_k.weight"] = tensor[i] + out[f"blocks.{i}.attn.c_v.weight"] = tensor[n + i] + elif name == "mlp_up_bank": + for i in range(n): + out[f"blocks.{i}.mlp.fc.weight"] = tensor[i] + elif name == "mlp_down_bank": + for i in range(n): + out[f"blocks.{i}.mlp.proj.weight"] = tensor[i] + else: + out[name] = tensor + return out + + +def _rebank_state_dict(sd: dict, num_layers: int, template_sd: dict) -> dict: + """Convert individual 2D tensors back into 3D bank tensors.""" + out = {} + n = num_layers + qo_slices = [None] * (2 * n) + kv_slices = [None] * (2 * n) + up_slices = [None] * n + down_slices = [None] * n + consumed = set() + for i in range(n): + qk = f"blocks.{i}.attn.c_q.weight" + if qk in sd: + qo_slices[i] = sd[qk]; consumed.add(qk) + ok = f"blocks.{i}.attn.proj.weight" + if ok in sd: + qo_slices[n + i] = sd[ok]; consumed.add(ok) + kk = f"blocks.{i}.attn.c_k.weight" + if kk in sd: + kv_slices[i] = sd[kk]; consumed.add(kk) + vk = f"blocks.{i}.attn.c_v.weight" + if vk in sd: + kv_slices[n + i] = sd[vk]; consumed.add(vk) + fk = f"blocks.{i}.mlp.fc.weight" + if fk in sd: + up_slices[i] = sd[fk]; consumed.add(fk) + dk = f"blocks.{i}.mlp.proj.weight" + if dk in sd: + down_slices[i] = sd[dk]; consumed.add(dk) + out["qo_bank"] = torch.stack(qo_slices).to(dtype=template_sd["qo_bank"].dtype) + out["kv_bank"] = torch.stack(kv_slices).to(dtype=template_sd["kv_bank"].dtype) + out["mlp_up_bank"] = torch.stack(up_slices).to(dtype=template_sd["mlp_up_bank"].dtype) + out["mlp_down_bank"] = torch.stack(down_slices).to(dtype=template_sd["mlp_down_bank"].dtype) + for name, tensor in sd.items(): + if name not in consumed: + out[name] = tensor + return out + + +def eval_val_sliding( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, + stride: int, + batch_seqs: int = 32, +) -> tuple[float, float]: + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + total_windows = len(window_starts) + my_s = (total_windows * rank) // world_size + my_e = (total_windows * (rank + 1)) // world_size + my_windows = window_starts[my_s:my_e] + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk[:-1] + y_batch[i, :wlen] = chunk[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt = y_batch[i, s:wlen] + prev = x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + running_bpb = 0.0 + if token_count.item() > 0: + rl = (loss_sum / token_count).item() + running_bpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) + print(f" sliding_eval [{pct:5.1f}%] {done}/{len(my_windows)} windows running_bpb={running_bpb:.6f}", flush=True) + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + bits_per_token = val_loss / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + base_model.train() + return val_loss, bits_per_token * tokens_per_byte + + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: nn.Module, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + """Legal score-first TTT: score each chunk with sliding windows, then train on it. + Every token is scored BEFORE any update that could use it (PR #461 recipe).""" + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + ttt_chunk = args.ttt_chunk_tokens + + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + + num_chunks = (total_tokens + ttt_chunk - 1) // ttt_chunk + chunk_windows: list[list[int]] = [[] for _ in range(num_chunks)] + for ws in window_starts: + end = min(ws + seq_len, total_tokens) + wlen = end - ws + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_start = ws + s + ci = min(scored_start // ttt_chunk, num_chunks - 1) + chunk_windows[ci].append(ws) + + log0(f"ttt_sliding:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"total_windows={len(window_starts)} stride={stride} " + f"ttt_lr={args.ttt_lr} ttt_epochs={args.ttt_epochs} " + f"freeze_blocks={args.ttt_freeze_blocks}") + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + log0(f"ttt_sliding:params unfrozen={sum(p.numel() for p in ttt_params)} " + f"frozen={sum(p.numel() for p in base_model.parameters() if not p.requires_grad)}") + + optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) + t0 = time.perf_counter() + + for ci in range(num_chunks): + windows = chunk_windows[ci] + if not windows: + continue + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + my_s = (len(windows) * rank) // world_size + my_e = (len(windows) * (rank + 1)) // world_size + my_windows = windows[my_s:my_e] + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk_tok = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk_tok[:-1] + y_batch[i, :wlen] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt, prev = y_batch[i, s:wlen], x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + my_seq_s = (chunk_seqs * rank) // world_size + my_seq_e = (chunk_seqs * (rank + 1)) // world_size + my_chunk_seqs = my_seq_e - my_seq_s + for _ep in range(args.ttt_epochs): + for bs in range(0, my_chunk_seqs, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_chunk_seqs) + actual_bs = my_seq_s + bs + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + (my_seq_s + be) * seq_len + 1 + if end_tok > val_tokens.numel(): + continue + local = val_tokens[start_tok:end_tok].to(device=device, dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + optimizer.zero_grad(set_to_none=True) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + loss = base_model(x, y) + loss.backward() + if world_size > 1: + for p in ttt_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) if token_count.item() > 0 else 0.0 + log0(f" ttt_chunk [{ci+1}/{num_chunks}] bpb={rbpb:.6f} time={elapsed:.1f}s") + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + val_bpb = val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.eval() + + log0(f"ttt_sliding:done val_loss={val_loss:.6f} val_bpb={val_bpb:.6f} " + f"elapsed={time.perf_counter() - t0:.1f}s") + return val_loss, val_bpb + + +# ----------------------------- +# TRAINING +# ----------------------------- + +def main() -> None: + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + # Parallel Muon uses batched bmm — do NOT torch.compile NS5 (bmm is already efficient) + + distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size <= 0: + raise ValueError(f"WORLD_SIZE must be positive, got {world_size}") + if 8 % world_size != 0: + raise ValueError(f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral") + grad_accum_steps = 8 // world_size + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + + logfile = None + wandb_enabled = False + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + if _WANDB_AVAILABLE and bool(int(os.environ.get("WANDB_ENABLED", "1"))): + wandb.init( + project=os.environ.get("WANDB_PROJECT", "parameter-golf"), + name=args.run_id, + config={ + "num_layers": args.num_layers, + "model_dim": args.model_dim, + "mlp_mult": args.mlp_mult, + "num_heads": args.num_heads, + "num_kv_heads": args.num_kv_heads, + "mlp_quant_bits": args.mlp_quant_bits, + "iterations": args.iterations, + "train_batch_tokens": args.train_batch_tokens, + "train_seq_len": args.train_seq_len, + "xsa_last_n": args.xsa_last_n, + "ema_enabled": args.ema_enabled, + "rope_dims": args.rope_dims, + "ln_scale": args.ln_scale, + "late_qat_threshold": args.late_qat_threshold, + "ttt_enabled": args.ttt_enabled, + "bigram_vocab_size": args.bigram_vocab_size, + "value_embed_layers": args.value_embed_layers, + "value_embed_dim": args.value_embed_dim, + "seed": args.seed, + }, + resume="allow", + ) + wandb_enabled = True + + def log0(msg: str, console: bool = True) -> None: + if not master_process: + return + if console: + print(msg) + if logfile is not None: + with open(logfile, "a", encoding="utf-8") as f: + print(msg, file=f) + + log0(code, console=False) + log0("=" * 100, console=False) + log0(f"Running Python {sys.version}", console=False) + log0(f"Running PyTorch {torch.__version__}", console=False) + log0( + subprocess.run(["nvidia-smi"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout, + console=False, + ) + log0("=" * 100, console=False) + + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + + if not args.tokenizer_path.endswith(".model"): + raise ValueError(f"Script only setup for SentencePiece .model file: {args.tokenizer_path}") + sp = spm.SentencePieceProcessor(model_file=args.tokenizer_path) + if int(sp.vocab_size()) != args.vocab_size: + raise ValueError( + f"VOCAB_SIZE={args.vocab_size} does not match tokenizer vocab_size={int(sp.vocab_size())}" + ) + dataset_dir = Path(args.data_path).resolve() + actual_train_files = len(list(dataset_dir.glob("fineweb_train_*.bin"))) + val_tokens = load_validation_tokens(args.val_files, args.train_seq_len) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = build_sentencepiece_luts( + sp, args.vocab_size, device + ) + log0(f"val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path={args.tokenizer_path}") + log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}") + log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}") + + # MODEL SETUP + base_model = GPT( + vocab_size=args.vocab_size, + num_layers=args.num_layers, + model_dim=args.model_dim, + num_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + mlp_mult=args.mlp_mult, + tie_embeddings=args.tie_embeddings, + tied_embed_init_std=args.tied_embed_init_std, + logit_softcap=args.logit_softcap, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + bigram_vocab_size=args.bigram_vocab_size, + bigram_dim=args.bigram_dim, + trigram_vocab_size=args.trigram_vocab_size, + trigram_dim=args.trigram_dim, + rope_dims=args.rope_dims, + ln_scale=args.ln_scale, + xsa_last_n=args.xsa_last_n, + value_embed_layers=args.value_embed_layers, + value_embed_dim=args.value_embed_dim, + ).to(device).bfloat16() + # Banks stay FP32 (cast to BF16 in forward via _fq) + base_model.qo_bank.data = base_model.qo_bank.data.float() + base_model.kv_bank.data = base_model.kv_bank.data.float() + base_model.mlp_up_bank.data = base_model.mlp_up_bank.data.float() + base_model.mlp_down_bank.data = base_model.mlp_down_bank.data.float() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + + # QAT: set per-layer fake-quantization targets + # MLP precision controlled by MLP_QUANT_BITS (4=INT4 clip=7, 5=INT5 clip=15) + mlp_clip = (1 << (args.mlp_quant_bits - 1)) - 1 # 5→15, 4→7 + attn_clip = (1 << (args.attn_quant_bits - 1)) - 1 # 6→31, 4→7 + ngram_clip = mlp_clip if args.mlp_quant_bits <= 4 else 31 # INT4 bigram/trigram when MLP is INT4 + _qat_active = False # tracks whether fake-quant has been activated + + def _enable_qat() -> None: + nonlocal _qat_active, ema_state + if _qat_active: + return + _qat_active = True + # Reset EMA so it only accumulates QAT-adapted weights (prevents pre-QAT contamination) + if args.ema_enabled and ema_state is not None: + ema_state = None + log0("qat:ema_reset (EMA will restart from current QAT weights)") + # Set bank QAT clips (for qo_bank, kv_bank, mlp_up_bank, mlp_down_bank) + base_model._qat_mlp_clip = mlp_clip + base_model._qat_attn_clip = attn_clip + # Set bigram/trigram CastedLinear clip ranges + for name, module in base_model.named_modules(): + if isinstance(module, CastedLinear): + if "bigram" in name or "trigram" in name: + module._qat_clip_range = ngram_clip + else: + module._qat_clip_range = attn_clip # VE proj, lm_head: use attn clip + if base_model.bigram is not None: + base_model.bigram._qat_clip_range = ngram_clip + if base_model.trigram is not None: + base_model.trigram._qat_clip_range = ngram_clip + ngram_bits = '4' if ngram_clip <= 7 else '6' + trig_str = f" trigram=INT{ngram_bits}(clip={ngram_clip})" if base_model.trigram is not None else "" + log0(f"qat:enabled mlp=INT{args.mlp_quant_bits}(clip={mlp_clip}) attn=INT{args.attn_quant_bits}(clip={attn_clip}) bigram=INT{ngram_bits}(clip={ngram_clip}){trig_str}") + + if args.qat_enabled: + if args.late_qat_threshold > 0: + log0(f"qat:late_qat threshold={args.late_qat_threshold} (activates when lr_scale < threshold)") + else: + _enable_qat() + else: + log0("qat:disabled") + + # No DDP -- Parallel Muon handles bank grad sync via reduce-scatter + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = compiled_model + + # OPTIMIZER SETUP + # Optimizer split: + # - 4 parameter banks -> Parallel Muon (batched Newton-Schulz via reduce-scatter) + # - embeddings -> AdamW + # - scalars/control tensors -> AdamW + matrix_params = [ + base_model.qo_bank, base_model.kv_bank, + base_model.mlp_up_bank, base_model.mlp_down_bank, + ] + block_named_params = list(base_model.blocks.named_parameters()) + scalar_params = [ + p for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + scalar_params.append(base_model.smear.gate) + if base_model.bigram is not None: + scalar_params.append(base_model.bigram.scale) + if base_model.trigram is not None: + scalar_params.append(base_model.trigram.scale) + + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + tok_params = [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}] + if base_model.bigram is not None: + tok_params.append({"params": [base_model.bigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.bigram.proj is not None: + scalar_params.append(base_model.bigram.proj.weight) + if base_model.trigram is not None: + tok_params.append({"params": [base_model.trigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.trigram.proj is not None: + scalar_params.append(base_model.trigram.proj.weight) + if base_model.ve_shared is not None: + tok_params.append({"params": [base_model.ve_shared.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.ve_shared.proj is not None: + scalar_params.append(base_model.ve_shared.proj.weight) + scalar_params.append(base_model.ve_shared.scale) + for s in base_model.ve_layer_scales: + scalar_params.append(s) + + # Non-bank params that need manual all-reduce (replicated across GPUs, not sharded) + replicated_params = [] + for pg in tok_params: + replicated_params.extend(pg["params"]) + replicated_params.extend(scalar_params) + + optimizer_tok = torch.optim.AdamW( + tok_params, + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=0.04, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + replicated_params.append(base_model.lm_head.weight) + + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params}") + if base_model.ve_shared is not None: + log0(f"value_embed:layers={base_model.ve_layer_indices} ve_dim={args.value_embed_dim} kv_dim={base_model.ve_shared.proj.out_features if base_model.ve_shared.proj else args.value_embed_dim}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0(f"sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + # DATA LOADER & WARMUP + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + + max_wallclock_ms = 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0 + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 + + if args.warmup_steps > 0: + initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()} + initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers] + model.train() + for warmup_step in range(args.warmup_steps): + zero_grad_all() + for micro_step in range(grad_accum_steps): + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + warmup_loss = model(x, y) + (warmup_loss * grad_scale).backward() + # Without DDP: manually all-reduce all grads for warmup (simple, only 20 steps) + if distributed: + for p in base_model.parameters(): + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + for opt in optimizers: + opt.step() + zero_grad_all() + if args.warmup_steps <= 20 or (warmup_step + 1) % 10 == 0 or warmup_step + 1 == args.warmup_steps: + log0(f"warmup_step:{warmup_step + 1}/{args.warmup_steps}") + base_model.load_state_dict(initial_model_state, strict=True) + for opt, state in zip(optimizers, initial_optimizer_states, strict=True): + opt.load_state_dict(state) + zero_grad_all() + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + # MAIN TRAINING LOOP + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + # EMA state: kept on GPU for efficiency, initialized on first step + ema_state: dict[str, Tensor] | None = None + # QAT timing: use wallclock fraction for deterministic triggering (immune to step_ms estimate noise) + # LATE_QAT_FRAC=0.65 fires QAT at 65% of budget (~390s), giving ~1400 QAT steps. + # Falls back to LR-scale method if LATE_QAT_FRAC is unset or 0. + _late_qat_frac = float(os.environ.get("LATE_QAT_FRAC", "0.0")) + _late_qat_trigger_ms = (_late_qat_frac * max_wallclock_ms) if (max_wallclock_ms and _late_qat_frac > 0) else None + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + if wandb_enabled: + wandb.log({"val/loss": val_loss, "val/bpb": val_bpb}, step=step) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_active: + if _late_qat_trigger_ms is not None: + if elapsed_ms >= _late_qat_trigger_ms: + _enable_qat() + elif args.late_qat_threshold > 0 and scale < args.late_qat_threshold: + _enable_qat() + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + + # === 3-phase overlapped optimizer step === + # Phase 1: Launch async reduce-scatter for banks (biggest first) + optimizer_muon.launch_reduce_scatters() + # Phase 2: All-reduce non-bank grads + step Adam (while bank RS is in-flight) + if distributed: + for p in replicated_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + for opt in optimizers: + if opt is not optimizer_muon: + opt.step() + # Phase 3: Wait for RS, local NS5, all-gather (banks processed last) + optimizer_muon.step() + zero_grad_all() + + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + + # EMA: update running average of weights (GPU, no extra transfer) + if args.ema_enabled: + if ema_state is None: + ema_state = {name: t.detach().clone() for name, t in base_model.state_dict().items()} + else: + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(args.ema_decay).add_(t.detach(), alpha=1.0 - args.ema_decay) + + # SWA: collect checkpoints during warmdown + if args.swa_enabled and scale < args.swa_start_frac and step % args.swa_every == 0: + if swa_state is None: + swa_state = {name: t.detach().cpu().clone() for name, t in base_model.state_dict().items()} + swa_count = 1 + log0(f"swa:start step:{step}") + else: + for name, t in base_model.state_dict().items(): + swa_state[name] += t.detach().cpu() + swa_count += 1 + + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + if wandb_enabled: + wandb.log({ + "train/loss": train_loss.item(), + "train/lr_scale": scale, + "train/step_ms": approx_training_time_ms / step, + }, step=step) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + # Apply SWA if collected + if args.swa_enabled and swa_state is not None and swa_count > 1: + log0(f"swa:applying averaged {swa_count} checkpoints") + current_state = base_model.state_dict() + avg_state = { + name: (tensor / swa_count).to(dtype=current_state[name].dtype) + for name, tensor in swa_state.items() + } + base_model.load_state_dict(avg_state, strict=True) + + # Apply EMA: use smooth running average as final weights (overrides SWA if both enabled) + if args.ema_enabled and ema_state is not None: + log0(f"ema:applying (decay={args.ema_decay})") + current_state = base_model.state_dict() + ema_cpu = {name: t.cpu().to(dtype=current_state[name].dtype) for name, t in ema_state.items()} + base_model.load_state_dict(ema_cpu, strict=True) + + # SERIALIZATION + QUANTIZATION + if master_process: + torch.save(base_model.state_dict(), f"final_model_{args.run_id}.pt") + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total uncompressed: {model_bytes + code_bytes} bytes") + + # Magnitude pruning on bank slices to aid compression + with torch.no_grad(): + for bank_name in ["qo_bank", "kv_bank", "mlp_up_bank", "mlp_down_bank"]: + bank = getattr(base_model, bank_name) + for i in range(bank.shape[0]): + w = bank.data[i] + threshold = torch.quantile(w.abs().float().flatten(), 0.03) + bank.data[i].masked_fill_(w.abs() < threshold, 0.0) + # Also prune 2D non-bank params + for name, param in base_model.named_parameters(): + if param.ndim == 2 and param.numel() > 65536 and name not in {"qo_bank", "kv_bank", "mlp_up_bank", "mlp_down_bank"}: + threshold = torch.quantile(param.abs().float().flatten(), 0.03) + mask = param.abs() < threshold + param.masked_fill_(mask, 0.0) + + # Unbank 3D bank tensors → per-layer 2D for quantization + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + unbanked_sd = _unbank_state_dict(sd_cpu, args.num_layers) + + # Dynamically set FP16_KEEP to keep last attention layer's c_k in FP16 (reduces late-layer quant penalty) + # Default "blocks.8.attn.c_k" is correct for 9L; override here for other depths + global FP16_KEEP_NAME_PATTERNS + last_layer_ck = f"blocks.{args.num_layers - 1}.attn.c_k" + FP16_KEEP_NAME_PATTERNS = tuple( + p for p in set(list(FP16_KEEP_NAME_PATTERNS) + [last_layer_ck]) + if p and (not p.startswith("blocks.") or p == last_layer_ck) + ) + + # INT5/INT4 MLP + INT6/INT4 Attn/Bigram/Trigram mixed quantization + zstd-22 / zlib-9 export + int6_cats = {"mlp", "attn", "bigram"} + if base_model.trigram is not None: + int6_cats.add("trigram") + quant_result, quant_meta = mixed_quantize_int6(unbanked_sd, int6_cats, mlp_clip=mlp_clip, attn_clip=attn_clip) + quant_buf = io.BytesIO() + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + quant_raw = quant_buf.getvalue() + if _COMPRESSOR == "zstd": + quant_blob = zstandard.ZstdCompressor(level=22).compress(quant_raw) + else: + quant_blob = zlib.compress(quant_raw, 9) + if master_process: + with open(f"final_model_{args.run_id}.int8.ptz", "wb") as f: + f.write(quant_blob) + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int5mlp+int6attn+{_COMPRESSOR}: {quant_file_bytes} bytes") + log0(f"Total submission size: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + if _COMPRESSOR == "zstd": + decompressed = zstandard.ZstdDecompressor().decompress(quant_blob_disk) + else: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + deq_unbanked = dequantize_mixed_int6(quant_state["w"], quant_state["m"], unbanked_sd) + # Re-bank the dequantized tensors + deq_state = _rebank_state_dict(deq_unbanked, args.num_layers, sd_cpu) + base_model.load_state_dict(deq_state, strict=True) + + # Final eval on roundtripped weights with sliding window + torch.cuda.synchronize() + t_qeval = time.perf_counter() + if args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window stride:{args.eval_stride} batch_seqs:{args.eval_batch_seqs}") + q_val_loss, q_val_bpb = eval_val_sliding( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, + ) + else: + log0("final_eval_mode:standard") + q_val_loss, q_val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + if wandb_enabled: + wandb.log({ + "final/post_quant_bpb": q_val_bpb, + "final/post_quant_loss": q_val_loss, + "final/artifact_mb": quant_file_bytes / 1e6, + }) + + if args.ttt_enabled: + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, log0=log0, + ) + torch.cuda.synchronize() + log0(f"legal_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms") + log0(f"legal_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + if wandb_enabled: + wandb.log({"final/ttt_bpb": ttt_bpb, "final/ttt_loss": ttt_loss}) + + if wandb_enabled: + wandb.finish() + + if distributed: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() From f25c703a2de658e499ac46f3d21a90b99850b0b1 Mon Sep 17 00:00:00 2001 From: Harsh Soni Date: Wed, 1 Apr 2026 05:12:27 +0000 Subject: [PATCH 4/9] =?UTF-8?q?Non-record:=2013L=20INT4=20attn=20=E2=80=94?= =?UTF-8?q?=20172ms/step,=20ttt=5Fbpb=3D1.1640,=20worse=20than=2012L=20VE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-03-28_13L_INT4_attn_failed/README.md | 34 + .../submission.json | 9 + .../train_gpt.py | 1753 +++++++++++++++++ 3 files changed, 1796 insertions(+) create mode 100644 records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/README.md create mode 100644 records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/submission.json create mode 100644 records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/train_gpt.py diff --git a/records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/README.md b/records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/README.md new file mode 100644 index 0000000000..417027cf22 --- /dev/null +++ b/records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/README.md @@ -0,0 +1,34 @@ +# Non-record: 13L INT4 Attention — Failed Experiment + +**val_bpb: 1.1640** (worse than best) | **15.14 MB** | 8×H100 SXM + +## Hypothesis + +By quantizing attention to INT4 (from INT6), we save enough space to add a 13th layer, gaining extra model capacity. + +## Result + +| Metric | v9_13l (this) | v7_ve seed 2 (prev best) | +|--------|---------------|--------------------------| +| Layers | **13** | 12 | +| Attn quant | **INT4** | INT6 | +| step_avg | **172.8ms** | 148ms | +| steps (10min) | **3485** | 4058 | +| post_quant bpb | 1.1696 | 1.1624 | +| ttt_bpb | **1.1640** | **1.1574** | +| artifact | 15,137,448 | 16,408,223 | + +**Conclusion: Failed.** 172.8ms/step means only 3485 steps — 573 fewer than 12L VE. The extra layer does not compensate for both: (1) slower steps from INT4 recompilation overhead, and (2) INT4 attention quality degradation. net result is 0.0066 BPB worse. + +## Lesson + +Consistent with the community finding: 12L+ at seq2048 is worse than 11L because slower steps cancel extra capacity. INT4 attention adds overhead without sufficient quality benefit at this model size. + +## Config + +```bash +RUN_ID=v9_13l_int4attn_seed1 SEED=1 \ +NUM_LAYERS=13 MLP_QUANT_BITS=4 ATTN_QUANT_BITS=4 XSA_LAST_N=4 \ +EMA_ENABLED=1 ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_FRAC=0.65 TTT_ENABLED=1 \ +VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 +``` diff --git a/records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/submission.json b/records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/submission.json new file mode 100644 index 0000000000..7ead6c67fb --- /dev/null +++ b/records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/submission.json @@ -0,0 +1,9 @@ +{ + "name": "Non-record: 13L INT4 attn — slow steps, worse BPB", + "val_bpb": 1.1640, + "bytes_total": 15137448, + "blurb": "Experiment: 13-layer model with INT4 attention (INT6→INT4 to free space for extra layer). Result: 172.8ms/step vs 148ms for 12L VE, only 3485 steps in 10 min. ttt_bpb=1.1640, worse than 12L INT4 VE (1.1574). Conclusion: extra layer does not compensate for step overhead — consistent with community finding that 12L+ at seq2048 is worse than 11L. INT4 attn penalty is too high.", + "author": "Harsh Soni", + "github_id": "SoHarshH", + "date": "2026-03-28" +} diff --git a/records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/train_gpt.py b/records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/train_gpt.py new file mode 100644 index 0000000000..182da0d77d --- /dev/null +++ b/records/track_10min_16mb/2026-03-28_13L_INT4_attn_failed/train_gpt.py @@ -0,0 +1,1753 @@ +from __future__ import annotations + +import copy +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import uuid +import zlib +from pathlib import Path + +try: + import zstandard + _COMPRESSOR = "zstd" +except ImportError: + _COMPRESSOR = "zlib" + +try: + import wandb + _WANDB_AVAILABLE = True +except ImportError: + _WANDB_AVAILABLE = False + +import numpy as np +import sentencepiece as spm +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import Tensor, nn +from torch.nn.parallel import DistributedDataParallel as DDP + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- + +class Hyperparameters: + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024") + train_files = os.path.join(data_path, "fineweb_train_*.bin") + val_files = os.path.join(data_path, "fineweb_val_*.bin") + tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 42)) + + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 500)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 100)) + + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3000)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 786_432)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2048)) + max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + + vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) + num_layers = int(os.environ.get("NUM_LAYERS", 10)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 4)) + model_dim = int(os.environ.get("MODEL_DIM", 512)) + num_heads = int(os.environ.get("NUM_HEADS", 8)) + mlp_mult = float(os.environ.get("MLP_MULT", 3.0)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.008)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.03)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.02)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.02)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.3)) + weight_decay = float(os.environ.get("WEIGHT_DECAY", 0.04)) + + eval_stride = int(os.environ.get("EVAL_STRIDE", 64)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 32)) + + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + trigram_vocab_size = int(os.environ.get("TRIGRAM_VOCAB_SIZE", 0)) # 0 = disabled + trigram_dim = int(os.environ.get("TRIGRAM_DIM", 64)) + + swa_enabled = bool(int(os.environ.get("SWA_ENABLED", "1"))) + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.4)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + + # EMA: exponential moving average of weights (replaces SWA when enabled) + ema_enabled = bool(int(os.environ.get("EMA_ENABLED", "0"))) + ema_decay = float(os.environ.get("EMA_DECAY", "0.997")) + + # QAT: fake-quantize weights during training to match PTQ targets + # MLP precision: INT4 (clip=7) or INT5 (clip=15, default); ATTN default INT6 (clip=31) + qat_enabled = bool(int(os.environ.get("QAT_ENABLED", "1"))) + mlp_quant_bits = int(os.environ.get("MLP_QUANT_BITS", "5")) # 4 or 5 + attn_quant_bits = int(os.environ.get("ATTN_QAT_BITS", "6")) # 6=INT6(default), 4=INT4 + + # XSA: Cross-Sequence Attention on last N layers (subtracts self-value projection) + xsa_last_n = int(os.environ.get("XSA_LAST_N", 0)) + + # Partial RoPE: apply RoPE to only first rope_dims dims of head_dim (0 = full) + rope_dims = int(os.environ.get("ROPE_DIMS", 0)) + + # LN Scale: scale norm input by 1/sqrt(layer_idx+1) for depth stability + ln_scale = bool(int(os.environ.get("LN_SCALE", "0"))) + + # Late QAT: delay fake-quantize until LR scale drops below threshold (0 = from start) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", "0")) + + # ValueEmbedding: reinject token identity into V at last N layers (0 = disabled) + value_embed_layers = int(os.environ.get("VALUE_EMBED_LAYERS", "0")) + value_embed_dim = int(os.environ.get("VALUE_EMBED_DIM", "64")) + + # TTT: Legal score-first test-time training at final eval + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "0"))) + ttt_lr = float(os.environ.get("TTT_LR", "0.002")) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", "3")) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", "32768")) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", "0")) + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", "0.9")) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", "32")) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", "1.0")) + +# ----------------------------- +# MUON OPTIMIZER — Parallel Muon (async reduce-scatter → sharded NS5 → all-gather) +# ----------------------------- + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 5, eps: float = 1e-7) -> Tensor: + """Batched Newton-Schulz orthogonalization. Accepts (B,M,N) or (M,N).""" + a, b, c = (3.4445, -4.7750, 2.0315) + was_2d = G.ndim == 2 + if was_2d: + G = G.unsqueeze(0) + X = G.bfloat16() + transposed = X.size(-2) > X.size(-1) + if transposed: + X = X.mT + X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps) + for _ in range(steps): + A = X @ X.mT + B = b * A + c * (A @ A) + X = a * X + B @ X + if transposed: + X = X.mT + if was_2d: + X = X.squeeze(0) + return X + + +class Muon(torch.optim.Optimizer): + """Muon — MomentUm Orthogonalized by Newton-schulz. + + Works with DDP: DDP handles gradient averaging during backward. + NS5 runs sequentially on the already-averaged gradients. + launch_reduce_scatters() is a no-op stub (DDP handles sync). + + Falls back identically on single-GPU proxy runs. + """ + def __init__(self, params, lr: float, momentum: float, backend_steps: int, + nesterov: bool = True, weight_decay: float = 0.0): + super().__init__( + params, + dict(lr=lr, momentum=momentum, backend_steps=backend_steps, + nesterov=nesterov, weight_decay=weight_decay), + ) + + def launch_reduce_scatters(self) -> None: + pass # No-op: DDP handles gradient sync during backward + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + for group in self.param_groups: + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + wd = group.get("weight_decay", 0.0) + for p in group["params"]: + if p.grad is None: + continue + g = p.grad.bfloat16() + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(g) + update = g.add(buf, alpha=momentum) if nesterov else buf.clone() + update = zeropower_via_newtonschulz5(update, steps=backend_steps) + if wd > 0.0: + p.data.mul_(1.0 - lr * wd) + scale = max(1, p.shape[-2] / p.shape[-1]) ** 0.5 + p.add_(update.to(dtype=p.dtype), alpha=-lr * scale) + return loss + + +def _apply_vbank_update(vb: dict, lr: float, wd: float) -> None: + pass # unused stub kept for import compatibility + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION +# ----------------------------- + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("\u2581"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return ( + torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device), + ) + + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError( + "VAL_BATCH_SIZE must provide at least one sequence per rank; " + f"got VAL_BATCH_SIZE={args.val_batch_size}, WORLD_SIZE={world_size}, " + f"GRAD_ACCUM_STEPS={grad_accum_steps}, TRAIN_SEQ_LEN={args.train_seq_len}" + ) + local_batch_seqs = local_batch_tokens // args.train_seq_len + total_seqs = (val_tokens.numel() - 1) // args.train_seq_len + seq_start = (total_seqs * rank) // world_size + seq_end = (total_seqs * (rank + 1)) // world_size + val_loss_sum = torch.zeros((), device=device, dtype=torch.float64) + val_token_count = torch.zeros((), device=device, dtype=torch.float64) + val_byte_count = torch.zeros((), device=device, dtype=torch.float64) + model.eval() + with torch.inference_mode(): + for batch_seq_start in range(seq_start, seq_end, local_batch_seqs): + batch_seq_end = min(batch_seq_start + local_batch_seqs, seq_end) + raw_start = batch_seq_start * args.train_seq_len + raw_end = batch_seq_end * args.train_seq_len + 1 + local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True) + x = local[:-1].reshape(-1, args.train_seq_len) + y = local[1:].reshape(-1, args.train_seq_len) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + batch_loss = model(x, y).detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +# ----------------------------- +# QUANTIZATION (INT5 MLP / INT6 ATTN mixed PTQ) +# ----------------------------- + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights,smear,bigram.scale,trigram.scale,ve_layer_scales,ve_shared.scale", + ).split(",") + if pattern +) +FP16_KEEP_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get("FP16_KEEP_NAME_PATTERNS", "tok_emb,blocks.8.attn.c_k").split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 + +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + INT8_CLIP_Q = 99.99984 / 100.0 + t32 = t.float() + if t32.ndim == 2: + clip_abs = ( + torch.quantile(t32.abs(), INT8_CLIP_Q, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + clipped = torch.maximum(torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None]) + scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) + q = torch.clamp(torch.round(clipped / scale[:, None]), -127, 127).to(torch.int8).contiguous() + return q, scale.to(dtype=torch.float16).contiguous() + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127).to(torch.int8).contiguous() + return q, scale + + +def _classify_param(name: str) -> str: + if "tok_emb" in name or "lm_head" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if "bigram" in name: + return "bigram" + if "trigram" in name: + return "trigram" + if ".attn." in name or (".proj." in name and ".mlp." not in name): + return "attn" + return "other" + + +def quantize_intN_per_row(t: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + """Quantize with GPTQ-lite: search 5 clip percentiles, pick best MSE.""" + t32 = t.float() + if t32.ndim == 2: + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 0.99999, 1.0]: + if pct < 1.0: + row_clip = torch.quantile(t32.abs(), pct, dim=1) + else: + row_clip = t32.abs().amax(dim=1) + scale = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + scale = scale.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(t32 / scale.float()[:, None]), -(clip_range + 1), clip_range).to(torch.int8) + err = (t32 - q.float() * scale.float()[:, None]).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, scale, err + return best_q, best_s + amax = t32.abs().max().item() + scale = torch.tensor(max(amax / clip_range, 1e-12), dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -(clip_range + 1), clip_range).to(torch.int8) + return q, scale + + +def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15, attn_clip: int = 31): + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param(name) + if not t.is_floating_point() or t.numel() <= 8192: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + if any(pattern in name for pattern in FP16_KEEP_NAME_PATTERNS): + result[name] = t.to(dtype=torch.float16).contiguous() + meta[name] = "passthrough_fp16" + continue + if cat in int6_cats and t.ndim >= 1: + # MLP: always uses mlp_clip (INT4 or INT5) + # attn: uses attn_clip (INT6 default, INT4 when ATTN_QAT_BITS=4) + # bigram/trigram: follow mlp_clip when INT4 (saves ~0.25MB), else INT6 + if cat == "mlp": + clip = mlp_clip + elif cat == "attn": + clip = attn_clip + elif cat in ("bigram", "trigram") and mlp_clip <= 7: + clip = mlp_clip # INT4 bigram/trigram when MLP is INT4 + else: + clip = 31 # INT6 for bigram/trigram in INT5 mode + q, s = quantize_intN_per_row(t, clip_range=clip) + result[name + ".q"] = q + result[name + ".scale"] = s + bits = clip.bit_length() + 1 # clip=31→int6, clip=15→int5, clip=7→int4 + meta[name] = {"type": f"int{bits}"} + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return result, meta + + +def dequantize_mixed_int6(result: dict[str, Tensor], meta: dict[str, object], + template_sd: dict[str, Tensor]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + for name, orig in template_sd.items(): + info = meta[name] + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl", "passthrough_fp16"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + + +# ----------------------------- +# DATA LOADING +# ----------------------------- + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = rank + self.world_size = world_size + self.device = device + self.stream = TokenStream(pattern) + + def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> tuple[Tensor, Tensor]: + local_tokens = global_tokens // (self.world_size * grad_accum_steps) + per_rank_span = local_tokens + 1 + chunk = self.stream.take(per_rank_span * self.world_size) + start = self.rank * per_rank_span + local = chunk[start : start + per_rank_span].to(dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + return x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) + + +# ----------------------------- +# TRANSFORMER MODULES +# ----------------------------- + +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + + +class CastedLinear(nn.Linear): + # _qat_clip_range: 127=off/INT8, 31=INT6, 15=INT5 + _qat_clip_range: int = 127 + + def forward(self, x: Tensor) -> Tensor: + w = self.weight + if self.training and self._qat_clip_range < 127 and w.ndim == 2: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w.to(x.dtype), bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int = 0): + super().__init__() + self.rope_dims = rope_dims if rope_dims > 0 else dim + rd = self.rope_dims + inv_freq = 1.0 / (base ** (torch.arange(0, rd, 2, dtype=torch.float32) / rd)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + rd = cos.size(-1) * 2 + if rd < x.size(-1): # partial RoPE: rotate first rd dims, pass rest unchanged + x_rope, x_pass = x[..., :rd], x[..., rd:] + half = rd // 2 + x1, x2 = x_rope[..., :half], x_rope[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + + +class CausalSelfAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, rope_base: float, qk_gain_init: float, rope_dims: int = 0): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base, rope_dims=rope_dims) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + """XSA: subtract self-value projection, forcing heads to attend to OTHER tokens.""" + B, T, H, D = y.shape + Hkv = v.size(2) # v is [B, T, Hkv, D] + group = H // Hkv + y_g = y.reshape(B, T, Hkv, group, D) + vn = F.normalize(v, dim=-1).unsqueeze(3) # [B, T, Hkv, 1, D] + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v_raw = self.c_v(x) + if v_embed is not None: + v_raw = v_raw + v_embed + v_bthd = v_raw.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + v = v_bthd.transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention( + q, k, v, attn_mask=None, is_causal=True, + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + y = y.transpose(1, 2).contiguous() # [B, T, H, D] + if self.use_xsa: + y = self._xsa_efficient(y, v_bthd) + y = y.reshape(bsz, seqlen, dim) + return self.proj(y) + + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: float): + super().__init__() + hidden = int(mlp_mult * dim) + self.fc = CastedLinear(dim, hidden, bias=False) + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + + def forward(self, x: Tensor) -> Tensor: + x = F.leaky_relu(self.fc(x), negative_slope=0.5) + return self.proj(x.square()) + + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate.to(dtype=x.dtype))[None, None, :] + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1 - g) * x + g * x_prev + + +class BigramHashEmbedding(nn.Module): + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, bigram_vocab_size: int, bigram_dim: int, model_dim: int): + super().__init__() + self.bigram_vocab_size = bigram_vocab_size + self.embed = nn.Embedding(bigram_vocab_size, bigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(bigram_dim, model_dim, bias=False) if bigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.05, dtype=torch.float32)) + + def bigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.bigram_vocab_size - 1 + out = torch.empty_like(t) + out[..., 0] = mod + out[..., 1:] = torch.bitwise_xor(36313 * t[..., 1:], 27191 * t[..., :-1]) % mod + return out.long() + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.bigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class TrigramHashEmbedding(nn.Module): + """3-gram context embedding: (prev2, prev1, curr) → hashed bucket → learned embedding.""" + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, trigram_vocab_size: int, trigram_dim: int, model_dim: int): + super().__init__() + self.trigram_vocab_size = trigram_vocab_size + self.embed = nn.Embedding(trigram_vocab_size, trigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(trigram_dim, model_dim, bias=False) if trigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.02, dtype=torch.float32)) + + def trigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.trigram_vocab_size - 1 + out = torch.full_like(t, mod, dtype=torch.long) # sentinel for positions without full context + out[..., 2:] = ( + torch.bitwise_xor( + torch.bitwise_xor(17291 * t[..., 2:], 36313 * t[..., 1:-1]), + 27191 * t[..., :-2], + ) % mod + ) + return out + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.trigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class ValueEmbedding(nn.Module): + """Reinject token identity into attention values at specific layers. + Shared embedding table + per-layer learned scale. Applied at last N layers.""" + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int): + super().__init__() + self.embed = nn.Embedding(vocab_size, ve_dim) + nn.init.normal_(self.embed.weight, std=0.01) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) if ve_dim != kv_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.1, dtype=torch.float32)) + + def forward(self, token_ids: Tensor) -> Tensor: + h = self.embed(token_ids) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class Block(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, mlp_mult: float, rope_base: float, qk_gain_init: float, rope_dims: int = 0, ln_scale: bool = False, layer_idx: int = 0): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, rope_dims=rope_dims) + self.mlp = MLP(dim, mlp_mult) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + + def forward(self, x: Tensor, x0: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + s = self.ln_scale_factor + attn_out = self.attn(self.attn_norm(x) * s, v_embed=v_embed) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * s) + return x + + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_layers: int, + model_dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: float, + tie_embeddings: bool, + tied_embed_init_std: float, + logit_softcap: float, + rope_base: float, + qk_gain_init: float, + bigram_vocab_size: int = 0, + bigram_dim: int = 128, + trigram_vocab_size: int = 0, + trigram_dim: int = 64, + rope_dims: int = 0, + ln_scale: bool = False, + xsa_last_n: int = 0, + value_embed_layers: int = 0, + value_embed_dim: int = 64, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.bigram = BigramHashEmbedding(bigram_vocab_size, bigram_dim, model_dim) if bigram_vocab_size > 0 else None + self.trigram = TrigramHashEmbedding(trigram_vocab_size, trigram_dim, model_dim) if trigram_vocab_size > 0 else None + self.num_encoder_layers = num_layers // 2 + self.num_decoder_layers = num_layers - self.num_encoder_layers + self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers) + self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32)) + self.smear = SmearGate(model_dim) + self.blocks = nn.ModuleList( + [ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init, + rope_dims=rope_dims, ln_scale=ln_scale, layer_idx=i) + for i in range(num_layers) + ] + ) + if xsa_last_n > 0: + for i in range(max(0, num_layers - xsa_last_n), num_layers): + self.blocks[i].attn.use_xsa = True + # ValueEmbedding: shared table + per-layer scales for last N layers + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve_layer_indices = list(range(max(0, num_layers - value_embed_layers), num_layers)) if value_embed_layers > 0 else [] + if self.ve_layer_indices: + self.ve_shared = ValueEmbedding(vocab_size, value_embed_dim, kv_dim) + self.ve_layer_scales = nn.ParameterList( + [nn.Parameter(torch.ones(1, dtype=torch.float32)) for _ in self.ve_layer_indices] + ) + else: + self.ve_shared = None + self.ve_layer_scales = nn.ParameterList() + self.final_norm = RMSNorm() + self.lm_head = None if tie_embeddings else CastedLinear(model_dim, vocab_size, bias=False) + if self.lm_head is not None: + self.lm_head._zero_init = True + self._init_weights() + + def _init_weights(self) -> None: + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) + num_layers = len(self.blocks) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and module.weight.shape[0] >= 64 and module.weight.shape[1] >= 64: + nn.init.orthogonal_(module.weight, gain=1.0) + if ".proj." in name or name.endswith(".proj"): + with torch.no_grad(): + module.weight.mul_(1.0 / math.sqrt(2 * num_layers)) + + def _get_ve(self, layer_idx: int, ve_base: "Tensor | None") -> "Tensor | None": + if ve_base is None or layer_idx not in self.ve_layer_indices: + return None + idx = self.ve_layer_indices.index(layer_idx) + return ve_base * self.ve_layer_scales[idx].to(dtype=ve_base.dtype) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x = self.blocks[self.num_encoder_layers + i](x, x0, v_embed=self._get_ve(self.num_encoder_layers + i, ve_base)) + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x = self.blocks[self.num_encoder_layers + i](x, x0, v_embed=self._get_ve(self.num_encoder_layers + i, ve_base)) + x = self.final_norm(x) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + logits_proj = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + + +def eval_val_sliding( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, + stride: int, + batch_seqs: int = 32, +) -> tuple[float, float]: + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + total_windows = len(window_starts) + my_s = (total_windows * rank) // world_size + my_e = (total_windows * (rank + 1)) // world_size + my_windows = window_starts[my_s:my_e] + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk[:-1] + y_batch[i, :wlen] = chunk[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt = y_batch[i, s:wlen] + prev = x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + running_bpb = 0.0 + if token_count.item() > 0: + rl = (loss_sum / token_count).item() + running_bpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) + print(f" sliding_eval [{pct:5.1f}%] {done}/{len(my_windows)} windows running_bpb={running_bpb:.6f}", flush=True) + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + bits_per_token = val_loss / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + base_model.train() + return val_loss, bits_per_token * tokens_per_byte + + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: nn.Module, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + """Legal score-first TTT: score each chunk with sliding windows, then train on it. + Every token is scored BEFORE any update that could use it (PR #461 recipe).""" + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + ttt_chunk = args.ttt_chunk_tokens + + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + + num_chunks = (total_tokens + ttt_chunk - 1) // ttt_chunk + chunk_windows: list[list[int]] = [[] for _ in range(num_chunks)] + for ws in window_starts: + end = min(ws + seq_len, total_tokens) + wlen = end - ws + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_start = ws + s + ci = min(scored_start // ttt_chunk, num_chunks - 1) + chunk_windows[ci].append(ws) + + log0(f"ttt_sliding:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"total_windows={len(window_starts)} stride={stride} " + f"ttt_lr={args.ttt_lr} ttt_epochs={args.ttt_epochs} " + f"freeze_blocks={args.ttt_freeze_blocks}") + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + log0(f"ttt_sliding:params unfrozen={sum(p.numel() for p in ttt_params)} " + f"frozen={sum(p.numel() for p in base_model.parameters() if not p.requires_grad)}") + + optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) + t0 = time.perf_counter() + + for ci in range(num_chunks): + windows = chunk_windows[ci] + if not windows: + continue + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + my_s = (len(windows) * rank) // world_size + my_e = (len(windows) * (rank + 1)) // world_size + my_windows = windows[my_s:my_e] + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk_tok = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk_tok[:-1] + y_batch[i, :wlen] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt, prev = y_batch[i, s:wlen], x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + my_seq_s = (chunk_seqs * rank) // world_size + my_seq_e = (chunk_seqs * (rank + 1)) // world_size + my_chunk_seqs = my_seq_e - my_seq_s + for _ep in range(args.ttt_epochs): + for bs in range(0, my_chunk_seqs, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_chunk_seqs) + actual_bs = my_seq_s + bs + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + (my_seq_s + be) * seq_len + 1 + if end_tok > val_tokens.numel(): + continue + local = val_tokens[start_tok:end_tok].to(device=device, dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + optimizer.zero_grad(set_to_none=True) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + loss = base_model(x, y) + loss.backward() + if world_size > 1: + for p in ttt_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) if token_count.item() > 0 else 0.0 + log0(f" ttt_chunk [{ci+1}/{num_chunks}] bpb={rbpb:.6f} time={elapsed:.1f}s") + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + val_bpb = val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.eval() + + log0(f"ttt_sliding:done val_loss={val_loss:.6f} val_bpb={val_bpb:.6f} " + f"elapsed={time.perf_counter() - t0:.1f}s") + return val_loss, val_bpb + + +# ----------------------------- +# TRAINING +# ----------------------------- + +def main() -> None: + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + # Parallel Muon uses batched bmm — do NOT torch.compile NS5 (bmm is already efficient) + + distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size <= 0: + raise ValueError(f"WORLD_SIZE must be positive, got {world_size}") + if 8 % world_size != 0: + raise ValueError(f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral") + grad_accum_steps = 8 // world_size + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + + logfile = None + wandb_enabled = False + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + if _WANDB_AVAILABLE and bool(int(os.environ.get("WANDB_ENABLED", "1"))): + wandb.init( + project=os.environ.get("WANDB_PROJECT", "parameter-golf"), + name=args.run_id, + config={ + "num_layers": args.num_layers, + "model_dim": args.model_dim, + "mlp_mult": args.mlp_mult, + "num_heads": args.num_heads, + "num_kv_heads": args.num_kv_heads, + "mlp_quant_bits": args.mlp_quant_bits, + "iterations": args.iterations, + "train_batch_tokens": args.train_batch_tokens, + "train_seq_len": args.train_seq_len, + "xsa_last_n": args.xsa_last_n, + "ema_enabled": args.ema_enabled, + "rope_dims": args.rope_dims, + "ln_scale": args.ln_scale, + "late_qat_threshold": args.late_qat_threshold, + "ttt_enabled": args.ttt_enabled, + "bigram_vocab_size": args.bigram_vocab_size, + "value_embed_layers": args.value_embed_layers, + "value_embed_dim": args.value_embed_dim, + "seed": args.seed, + }, + resume="allow", + ) + wandb_enabled = True + + def log0(msg: str, console: bool = True) -> None: + if not master_process: + return + if console: + print(msg) + if logfile is not None: + with open(logfile, "a", encoding="utf-8") as f: + print(msg, file=f) + + log0(code, console=False) + log0("=" * 100, console=False) + log0(f"Running Python {sys.version}", console=False) + log0(f"Running PyTorch {torch.__version__}", console=False) + log0( + subprocess.run(["nvidia-smi"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout, + console=False, + ) + log0("=" * 100, console=False) + + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + + if not args.tokenizer_path.endswith(".model"): + raise ValueError(f"Script only setup for SentencePiece .model file: {args.tokenizer_path}") + sp = spm.SentencePieceProcessor(model_file=args.tokenizer_path) + if int(sp.vocab_size()) != args.vocab_size: + raise ValueError( + f"VOCAB_SIZE={args.vocab_size} does not match tokenizer vocab_size={int(sp.vocab_size())}" + ) + dataset_dir = Path(args.data_path).resolve() + actual_train_files = len(list(dataset_dir.glob("fineweb_train_*.bin"))) + val_tokens = load_validation_tokens(args.val_files, args.train_seq_len) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = build_sentencepiece_luts( + sp, args.vocab_size, device + ) + log0(f"val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path={args.tokenizer_path}") + log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}") + log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}") + + # MODEL SETUP + base_model = GPT( + vocab_size=args.vocab_size, + num_layers=args.num_layers, + model_dim=args.model_dim, + num_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + mlp_mult=args.mlp_mult, + tie_embeddings=args.tie_embeddings, + tied_embed_init_std=args.tied_embed_init_std, + logit_softcap=args.logit_softcap, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + bigram_vocab_size=args.bigram_vocab_size, + bigram_dim=args.bigram_dim, + trigram_vocab_size=args.trigram_vocab_size, + trigram_dim=args.trigram_dim, + rope_dims=args.rope_dims, + ln_scale=args.ln_scale, + xsa_last_n=args.xsa_last_n, + value_embed_layers=args.value_embed_layers, + value_embed_dim=args.value_embed_dim, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + + # QAT: set per-layer fake-quantization targets + # MLP precision controlled by MLP_QUANT_BITS (4=INT4 clip=7, 5=INT5 clip=15) + mlp_clip = (1 << (args.mlp_quant_bits - 1)) - 1 # 5→15, 4→7 + attn_clip = (1 << (args.attn_quant_bits - 1)) - 1 # 6→31, 4→7 + ngram_clip = mlp_clip if args.mlp_quant_bits <= 4 else 31 # INT4 bigram/trigram when MLP is INT4 + _qat_active = False # tracks whether fake-quant has been activated + + def _enable_qat() -> None: + nonlocal _qat_active, ema_state + if _qat_active: + return + _qat_active = True + # Reset EMA so it only accumulates QAT-adapted weights (prevents pre-QAT contamination) + if args.ema_enabled and ema_state is not None: + ema_state = None + log0("qat:ema_reset (EMA will restart from current QAT weights)") + for name, module in base_model.named_modules(): + if isinstance(module, CastedLinear): + if ".mlp." in name: + module._qat_clip_range = mlp_clip + elif ".attn." in name: + module._qat_clip_range = attn_clip + elif "bigram" in name or "trigram" in name: + module._qat_clip_range = ngram_clip + else: + module._qat_clip_range = attn_clip + if base_model.bigram is not None: + base_model.bigram._qat_clip_range = ngram_clip + if base_model.trigram is not None: + base_model.trigram._qat_clip_range = ngram_clip + ngram_bits = '4' if ngram_clip <= 7 else '6' + trig_str = f" trigram=INT{ngram_bits}(clip={ngram_clip})" if base_model.trigram is not None else "" + log0(f"qat:enabled mlp=INT{args.mlp_quant_bits}(clip={mlp_clip}) attn=INT{args.attn_quant_bits}(clip={attn_clip}) bigram=INT{ngram_bits}(clip={ngram_clip}){trig_str}") + + if args.qat_enabled: + if args.late_qat_threshold > 0: + log0(f"qat:late_qat threshold={args.late_qat_threshold} (activates when lr_scale < threshold)") + else: + _enable_qat() + else: + log0("qat:disabled") + + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + if distributed: + model: nn.Module = DDP(compiled_model, device_ids=[device.index], static_graph=True) + else: + model = compiled_model + + # OPTIMIZER SETUP + block_named_params = list(base_model.blocks.named_parameters()) + matrix_params = [ + p for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + scalar_params.append(base_model.smear.gate) + if base_model.bigram is not None: + scalar_params.append(base_model.bigram.scale) + if base_model.trigram is not None: + scalar_params.append(base_model.trigram.scale) + + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + tok_params = [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}] + if base_model.bigram is not None: + tok_params.append({"params": [base_model.bigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.bigram.proj is not None: + matrix_params.append(base_model.bigram.proj.weight) + if base_model.trigram is not None: + tok_params.append({"params": [base_model.trigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.trigram.proj is not None: + matrix_params.append(base_model.trigram.proj.weight) + if base_model.ve_shared is not None: + tok_params.append({"params": [base_model.ve_shared.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.ve_shared.proj is not None: + matrix_params.append(base_model.ve_shared.proj.weight) + scalar_params.append(base_model.ve_shared.scale) + for s in base_model.ve_layer_scales: + scalar_params.append(s) + + optimizer_tok = torch.optim.AdamW( + tok_params, + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=0.04, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params}") + if base_model.ve_shared is not None: + log0(f"value_embed:layers={base_model.ve_layer_indices} ve_dim={args.value_embed_dim} kv_dim={base_model.ve_shared.proj.out_features if base_model.ve_shared.proj else args.value_embed_dim}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0(f"sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + # DATA LOADER & WARMUP + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + + max_wallclock_ms = 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0 + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 + + if args.warmup_steps > 0: + initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()} + initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers] + model.train() + for warmup_step in range(args.warmup_steps): + zero_grad_all() + for micro_step in range(grad_accum_steps): + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + warmup_loss = model(x, y) + (warmup_loss * grad_scale).backward() + # Without DDP: manually all-reduce all grads for warmup (simple, only 20 steps) + if distributed: + for p in base_model.parameters(): + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + for opt in optimizers: + opt.step() + zero_grad_all() + if args.warmup_steps <= 20 or (warmup_step + 1) % 10 == 0 or warmup_step + 1 == args.warmup_steps: + log0(f"warmup_step:{warmup_step + 1}/{args.warmup_steps}") + base_model.load_state_dict(initial_model_state, strict=True) + for opt, state in zip(optimizers, initial_optimizer_states, strict=True): + opt.load_state_dict(state) + zero_grad_all() + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + # MAIN TRAINING LOOP + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + # EMA state: kept on GPU for efficiency, initialized on first step + ema_state: dict[str, Tensor] | None = None + # QAT timing: use wallclock fraction for deterministic triggering (immune to step_ms estimate noise) + # LATE_QAT_FRAC=0.65 fires QAT at 65% of budget (~390s), giving ~1400 QAT steps. + # Falls back to LR-scale method if LATE_QAT_FRAC is unset or 0. + _late_qat_frac = float(os.environ.get("LATE_QAT_FRAC", "0.0")) + _late_qat_trigger_ms = (_late_qat_frac * max_wallclock_ms) if (max_wallclock_ms and _late_qat_frac > 0) else None + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + if wandb_enabled: + wandb.log({"val/loss": val_loss, "val/bpb": val_bpb}, step=step) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_active: + if _late_qat_trigger_ms is not None: + if elapsed_ms >= _late_qat_trigger_ms: + _enable_qat() + elif args.late_qat_threshold > 0 and scale < args.late_qat_threshold: + _enable_qat() + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + + # EMA: update running average of weights (GPU, no extra transfer) + if args.ema_enabled: + if ema_state is None: + ema_state = {name: t.detach().clone() for name, t in base_model.state_dict().items()} + else: + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(args.ema_decay).add_(t.detach(), alpha=1.0 - args.ema_decay) + + # SWA: collect checkpoints during warmdown + if args.swa_enabled and scale < args.swa_start_frac and step % args.swa_every == 0: + if swa_state is None: + swa_state = {name: t.detach().cpu().clone() for name, t in base_model.state_dict().items()} + swa_count = 1 + log0(f"swa:start step:{step}") + else: + for name, t in base_model.state_dict().items(): + swa_state[name] += t.detach().cpu() + swa_count += 1 + + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + if wandb_enabled: + wandb.log({ + "train/loss": train_loss.item(), + "train/lr_scale": scale, + "train/step_ms": approx_training_time_ms / step, + }, step=step) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + # Apply SWA if collected + if args.swa_enabled and swa_state is not None and swa_count > 1: + log0(f"swa:applying averaged {swa_count} checkpoints") + current_state = base_model.state_dict() + avg_state = { + name: (tensor / swa_count).to(dtype=current_state[name].dtype) + for name, tensor in swa_state.items() + } + base_model.load_state_dict(avg_state, strict=True) + + # Apply EMA: use smooth running average as final weights (overrides SWA if both enabled) + if args.ema_enabled and ema_state is not None: + log0(f"ema:applying (decay={args.ema_decay})") + current_state = base_model.state_dict() + ema_cpu = {name: t.cpu().to(dtype=current_state[name].dtype) for name, t in ema_state.items()} + base_model.load_state_dict(ema_cpu, strict=True) + + # SERIALIZATION + QUANTIZATION + if master_process: + torch.save(base_model.state_dict(), f"final_model_{args.run_id}.pt") + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total uncompressed: {model_bytes + code_bytes} bytes") + + # Magnitude pruning: zero smallest 3% of large weight matrices to aid compression + with torch.no_grad(): + for name, param in base_model.named_parameters(): + if param.ndim == 2 and param.numel() > 65536: + threshold = torch.quantile(param.abs().float().flatten(), 0.03) + mask = param.abs() < threshold + param.masked_fill_(mask, 0.0) + + # Dynamically set FP16_KEEP to keep last attention layer's c_k in FP16 (reduces late-layer quant penalty) + # Default "blocks.8.attn.c_k" is correct for 9L; override here for other depths + global FP16_KEEP_NAME_PATTERNS + last_layer_ck = f"blocks.{args.num_layers - 1}.attn.c_k" + FP16_KEEP_NAME_PATTERNS = tuple( + p for p in set(list(FP16_KEEP_NAME_PATTERNS) + [last_layer_ck]) + if p and not p.startswith("blocks.") or p == last_layer_ck + ) + + # INT5/INT4 MLP + INT6/INT4 Attn/Bigram/Trigram mixed quantization + zstd-22 / zlib-9 export + int6_cats = {"mlp", "attn", "bigram"} + if base_model.trigram is not None: + int6_cats.add("trigram") + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + quant_result, quant_meta = mixed_quantize_int6(sd_cpu, int6_cats, mlp_clip=mlp_clip, attn_clip=attn_clip) + quant_buf = io.BytesIO() + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + quant_raw = quant_buf.getvalue() + if _COMPRESSOR == "zstd": + quant_blob = zstandard.ZstdCompressor(level=22).compress(quant_raw) + else: + quant_blob = zlib.compress(quant_raw, 9) + if master_process: + with open(f"final_model_{args.run_id}.int8.ptz", "wb") as f: + f.write(quant_blob) + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int5mlp+int6attn+{_COMPRESSOR}: {quant_file_bytes} bytes") + log0(f"Total submission size: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + if _COMPRESSOR == "zstd": + decompressed = zstandard.ZstdDecompressor().decompress(quant_blob_disk) + else: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + deq_state = dequantize_mixed_int6(quant_state["w"], quant_state["m"], sd_cpu) + base_model.load_state_dict(deq_state, strict=True) + + # Final eval on roundtripped weights with sliding window + torch.cuda.synchronize() + t_qeval = time.perf_counter() + if args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window stride:{args.eval_stride} batch_seqs:{args.eval_batch_seqs}") + q_val_loss, q_val_bpb = eval_val_sliding( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, + ) + else: + log0("final_eval_mode:standard") + q_val_loss, q_val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + if wandb_enabled: + wandb.log({ + "final/post_quant_bpb": q_val_bpb, + "final/post_quant_loss": q_val_loss, + "final/artifact_mb": quant_file_bytes / 1e6, + }) + + if args.ttt_enabled: + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, log0=log0, + ) + torch.cuda.synchronize() + log0(f"legal_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms") + log0(f"legal_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + if wandb_enabled: + wandb.log({"final/ttt_bpb": ttt_bpb, "final/ttt_loss": ttt_loss}) + + if wandb_enabled: + wandb.finish() + + if distributed: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() From 8a626f925a0aa630f52796ca8a2b14084c670eb8 Mon Sep 17 00:00:00 2001 From: Harsh Soni Date: Wed, 1 Apr 2026 05:12:52 +0000 Subject: [PATCH 5/9] =?UTF-8?q?12L=20banked=20+=20Parallel=20Muon=20+=20VE?= =?UTF-8?q?=20=E2=80=94=20ttt=5Fbpb=3D1.1571=20(new=20best)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-03-28_12L_banked_VE/README.md | 55 + .../2026-03-28_12L_banked_VE/submission.json | 9 + .../2026-03-28_12L_banked_VE/train_gpt.py | 1995 +++++++++++++++++ 3 files changed, 2059 insertions(+) create mode 100644 records/track_10min_16mb/2026-03-28_12L_banked_VE/README.md create mode 100644 records/track_10min_16mb/2026-03-28_12L_banked_VE/submission.json create mode 100644 records/track_10min_16mb/2026-03-28_12L_banked_VE/train_gpt.py diff --git a/records/track_10min_16mb/2026-03-28_12L_banked_VE/README.md b/records/track_10min_16mb/2026-03-28_12L_banked_VE/README.md new file mode 100644 index 0000000000..3702938e62 --- /dev/null +++ b/records/track_10min_16mb/2026-03-28_12L_banked_VE/README.md @@ -0,0 +1,55 @@ +# 12L Banked + Parallel Muon + Value Embeddings + +**val_bpb: 1.1571** (new best) | **16.47 MB** | 8×H100 SXM + +## Results + +| Seed | step_avg | steps | Post-quant bpb | Post-TTT bpb | Artifact | +|------|----------|-------|----------------|--------------|----------| +| 1 | 138ms | 4358 | 1.1668 | **1.1571** | 16,465,445 | + +## Architecture + +| Component | Setting | +|-----------|---------| +| Layers | 12 (512d, 8H, 4KV) | +| MLP | 3× with LeakyReLU(0.5)² | +| BigramHash | 10240 buckets, INT4 bQAT | +| XSA | Last 4 layers | +| RoPE | Partial (16/64 dims) | +| LN Scale | 1/√(layer+1) | +| Weight avg | EMA(0.997) with QAT-activation reset | +| Quantization | INT4 MLP + INT4 bigram + INT6 attn + zstd | +| QAT trigger | Wallclock fraction (65% of budget) | +| Value Embeddings | ve_dim=128, layers 10-11 | +| TTT | Legal score-first, lr=0.002, 3 epochs | +| **Model Banking** | 4 banked 3D params (qo/kv/mlp_up/mlp_down) | +| **Parallel Muon** | Async reduce-scatter on banked grads, no DDP | + +## Key Change: Model Banking + +Previous approach used per-layer `nn.Linear` modules. Each layer's grad was a separate 2D tensor, so Parallel Muon required copying grads into a stacked buffer — overhead that negated NCCL savings. + +Model banking stores weights as 3D tensors `[num_layers, M, K]`. Grad accumulates directly in banked shape — reduce-scatter operates on it with zero copy. + +**Result:** 138ms/step vs 148ms for unbanked VE — 10ms improvement, 300 extra steps in 10 min, new best. + +## Comparison + +| Run | ms/step | Steps | ttt_bpb | +|-----|---------|-------|---------| +| v7_ve seed 2 | 148ms | 4058 | 1.15738 | +| v7_ve seed 3 | 149ms | 4034 | 1.15796 | +| **v10_banked seed 1** | **138ms** | **4358** | **1.15711** | + +## Training File + +`train_gpt_v3.py` — full rewrite with banked weight storage and parallel Muon. + +## Size Budget + +| Component | Bytes | +|-----------|-------| +| Total artifact | 16,465,445 | +| Budget | 16,777,216 | +| Margin | 311,771 (304KB) | diff --git a/records/track_10min_16mb/2026-03-28_12L_banked_VE/submission.json b/records/track_10min_16mb/2026-03-28_12L_banked_VE/submission.json new file mode 100644 index 0000000000..9660f9022e --- /dev/null +++ b/records/track_10min_16mb/2026-03-28_12L_banked_VE/submission.json @@ -0,0 +1,9 @@ +{ + "name": "12L banked + Parallel Muon + Value Embeddings — ttt_bpb 1.1571", + "val_bpb": 1.1571, + "bytes_total": 16465445, + "blurb": "12-layer INT4 bQAT with model banking (3D weight tensors: qo/kv/mlp_up/mlp_down banks), Parallel Muon (async reduce-scatter over banked grads, no DDP), Value Embeddings (ve_dim=128, last 2 layers), EMA(0.997) with QAT-reset. Banking eliminates per-layer grad copy overhead: 138ms/step vs 148ms, yielding 4358 steps in 10 min (300 more than v7_ve). ttt_bpb=1.15711, new best.", + "author": "Harsh Soni", + "github_id": "SoHarshH", + "date": "2026-03-28" +} diff --git a/records/track_10min_16mb/2026-03-28_12L_banked_VE/train_gpt.py b/records/track_10min_16mb/2026-03-28_12L_banked_VE/train_gpt.py new file mode 100644 index 0000000000..589ee84e75 --- /dev/null +++ b/records/track_10min_16mb/2026-03-28_12L_banked_VE/train_gpt.py @@ -0,0 +1,1995 @@ +from __future__ import annotations + +import copy +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import uuid +import zlib +from pathlib import Path + +try: + import zstandard + _COMPRESSOR = "zstd" +except ImportError: + _COMPRESSOR = "zlib" + +try: + import wandb + _WANDB_AVAILABLE = True +except ImportError: + _WANDB_AVAILABLE = False + +import numpy as np +import sentencepiece as spm +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import Tensor, nn +from torch.nn.parallel import DistributedDataParallel as DDP + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- + +class Hyperparameters: + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024") + train_files = os.path.join(data_path, "fineweb_train_*.bin") + val_files = os.path.join(data_path, "fineweb_val_*.bin") + tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 42)) + + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 500)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 100)) + + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3000)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 786_432)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2048)) + max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + + vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) + num_layers = int(os.environ.get("NUM_LAYERS", 10)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 4)) + model_dim = int(os.environ.get("MODEL_DIM", 512)) + num_heads = int(os.environ.get("NUM_HEADS", 8)) + mlp_mult = float(os.environ.get("MLP_MULT", 3.0)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.008)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.03)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.02)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.02)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.3)) + weight_decay = float(os.environ.get("WEIGHT_DECAY", 0.04)) + + eval_stride = int(os.environ.get("EVAL_STRIDE", 64)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 32)) + + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + trigram_vocab_size = int(os.environ.get("TRIGRAM_VOCAB_SIZE", 0)) # 0 = disabled + trigram_dim = int(os.environ.get("TRIGRAM_DIM", 64)) + + swa_enabled = bool(int(os.environ.get("SWA_ENABLED", "1"))) + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.4)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + + # EMA: exponential moving average of weights (replaces SWA when enabled) + ema_enabled = bool(int(os.environ.get("EMA_ENABLED", "0"))) + ema_decay = float(os.environ.get("EMA_DECAY", "0.997")) + + # QAT: fake-quantize weights during training to match PTQ targets + # MLP precision: INT4 (clip=7) or INT5 (clip=15, default); ATTN default INT6 (clip=31) + qat_enabled = bool(int(os.environ.get("QAT_ENABLED", "1"))) + mlp_quant_bits = int(os.environ.get("MLP_QUANT_BITS", "5")) # 4 or 5 + attn_quant_bits = int(os.environ.get("ATTN_QAT_BITS", "6")) # 6=INT6(default), 4=INT4 + + # XSA: Cross-Sequence Attention on last N layers (subtracts self-value projection) + xsa_last_n = int(os.environ.get("XSA_LAST_N", 0)) + + # Partial RoPE: apply RoPE to only first rope_dims dims of head_dim (0 = full) + rope_dims = int(os.environ.get("ROPE_DIMS", 0)) + + # LN Scale: scale norm input by 1/sqrt(layer_idx+1) for depth stability + ln_scale = bool(int(os.environ.get("LN_SCALE", "0"))) + + # Late QAT: delay fake-quantize until LR scale drops below threshold (0 = from start) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", "0")) + + # ValueEmbedding: reinject token identity into V at last N layers (0 = disabled) + value_embed_layers = int(os.environ.get("VALUE_EMBED_LAYERS", "0")) + value_embed_dim = int(os.environ.get("VALUE_EMBED_DIM", "64")) + + # TTT: Legal score-first test-time training at final eval + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "0"))) + ttt_lr = float(os.environ.get("TTT_LR", "0.002")) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", "3")) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", "32768")) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", "0")) + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", "0.9")) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", "32")) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", "1.0")) + +# ----------------------------- +# MUON OPTIMIZER — Parallel Muon (async reduce-scatter → sharded NS5 → all-gather) +# ----------------------------- + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 5, eps: float = 1e-7) -> Tensor: + """Batched Newton-Schulz orthogonalization. Accepts (B,M,N) or (M,N).""" + a, b, c = (3.4445, -4.7750, 2.0315) + was_2d = G.ndim == 2 + if was_2d: + G = G.unsqueeze(0) + X = G.bfloat16() + transposed = X.size(-2) > X.size(-1) + if transposed: + X = X.mT + X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps) + for _ in range(steps): + A = X @ X.mT + B = b * A + c * (A @ A) + X = a * X + B @ X + if transposed: + X = X.mT + if was_2d: + X = X.squeeze(0) + return X + + +class Muon(torch.optim.Optimizer): + """Parallel Muon: post-backward reduce-scatter -> local NS5 -> all-gather. + + No DDP for bank params. After backward, this optimizer: + 1. Launches async reduce-scatter for all banks (biggest first) + 2. Returns control so Adam can step on small params while RS is in-flight + 3. Waits for each RS, runs local NS5 on the shard, launches async all-gather + 4. Each all-gather overlaps with next bank's NS5 + """ + def __init__(self, params, lr: float, momentum: float, backend_steps: int, + nesterov: bool = True, weight_decay: float = 0.0): + super().__init__( + params, + dict(lr=lr, momentum=momentum, backend_steps=backend_steps, + nesterov=nesterov, weight_decay=weight_decay), + ) + self._built = False + + def _build(self): + self._distributed = dist.is_available() and dist.is_initialized() + self._world_size = dist.get_world_size() if self._distributed else 1 + self._rank = dist.get_rank() if self._distributed else 0 + ws = self._world_size + + self._bank_meta = [] + for group in self.param_groups: + for p in group["params"]: + B = p.shape[0] + padded_B = ((B + ws - 1) // ws) * ws + shard_B = padded_B // ws + tail = p.shape[1:] + dev = p.device + self._bank_meta.append({ + 'p': p, + 'B': B, + 'padded_grad': torch.zeros(padded_B, *tail, device=dev, dtype=torch.bfloat16), + 'shard': torch.zeros(shard_B, *tail, device=dev, dtype=torch.bfloat16), + 'shard_mom': torch.zeros(shard_B, *tail, device=dev, dtype=torch.bfloat16), + 'full_update': torch.zeros(padded_B, *tail, device=dev, dtype=torch.bfloat16), + 'scale': max(1, p.shape[-2] / p.shape[-1]) ** 0.5, + }) + # Sort by size descending -- launch biggest reduce-scatters first + self._bank_meta.sort(key=lambda m: -m['p'].numel()) + self._built = True + + def launch_reduce_scatters(self): + """Phase 1: launch async reduce-scatter for all banks. Call right after backward.""" + if not self._built: + self._build() + if not self._distributed: + return + self._rs_futures = [] + for m in self._bank_meta: + p = m['p'] + if p.grad is None: + self._rs_futures.append(None) + continue + pg = m['padded_grad'] + pg[:m['B']].copy_(p.grad.bfloat16()) + if pg.shape[0] > m['B']: + pg[m['B']:].zero_() + fut = dist.reduce_scatter_tensor(m['shard'], pg, op=dist.ReduceOp.AVG, async_op=True) + self._rs_futures.append(fut) + + @torch.no_grad() + def step(self, closure=None): + """Phase 3: wait for RS, local NS5, all-gather. Call AFTER Adam steps.""" + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + if not self._built: + self._build() + + for group in self.param_groups: + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + wd = group.get("weight_decay", 0.0) + + prev_ag_handle = None + prev_m = None + + sharded = self._distributed and hasattr(self, '_rs_futures') + + for i, m in enumerate(self._bank_meta): + p = m['p'] + if p.grad is None: + continue + + if prev_ag_handle is not None: + prev_ag_handle.wait() + pp = prev_m['p'] + upd = prev_m['full_update'][:prev_m['B']] + if wd > 0.0: + pp.data.mul_(1.0 - lr * wd) + pp.add_(upd.to(dtype=pp.dtype), alpha=-lr * prev_m['scale']) + + if sharded and self._rs_futures[i] is not None: + self._rs_futures[i].wait() + g = m['shard'] + buf = m['shard_mom'] + else: + g = p.grad.bfloat16() + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + + buf.mul_(momentum).add_(g) + if nesterov: + update = g.add(buf, alpha=momentum) + else: + update = buf + + update = zeropower_via_newtonschulz5(update, steps=backend_steps) + + if sharded: + prev_ag_handle = dist.all_gather_into_tensor( + m['full_update'], update, async_op=True) + prev_m = m + else: + if wd > 0.0: + p.data.mul_(1.0 - lr * wd) + p.add_(update.to(dtype=p.dtype), alpha=-lr * m['scale']) + + if prev_ag_handle is not None: + prev_ag_handle.wait() + pp = prev_m['p'] + upd = prev_m['full_update'][:prev_m['B']] + if wd > 0.0: + pp.data.mul_(1.0 - lr * wd) + pp.add_(upd.to(dtype=pp.dtype), alpha=-lr * prev_m['scale']) + + if hasattr(self, '_rs_futures'): + del self._rs_futures + + return loss + + +def _apply_vbank_update(vb: dict, lr: float, wd: float) -> None: + pass # unused stub kept for import compatibility + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION +# ----------------------------- + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("\u2581"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return ( + torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device), + ) + + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError( + "VAL_BATCH_SIZE must provide at least one sequence per rank; " + f"got VAL_BATCH_SIZE={args.val_batch_size}, WORLD_SIZE={world_size}, " + f"GRAD_ACCUM_STEPS={grad_accum_steps}, TRAIN_SEQ_LEN={args.train_seq_len}" + ) + local_batch_seqs = local_batch_tokens // args.train_seq_len + total_seqs = (val_tokens.numel() - 1) // args.train_seq_len + seq_start = (total_seqs * rank) // world_size + seq_end = (total_seqs * (rank + 1)) // world_size + val_loss_sum = torch.zeros((), device=device, dtype=torch.float64) + val_token_count = torch.zeros((), device=device, dtype=torch.float64) + val_byte_count = torch.zeros((), device=device, dtype=torch.float64) + model.eval() + with torch.inference_mode(): + for batch_seq_start in range(seq_start, seq_end, local_batch_seqs): + batch_seq_end = min(batch_seq_start + local_batch_seqs, seq_end) + raw_start = batch_seq_start * args.train_seq_len + raw_end = batch_seq_end * args.train_seq_len + 1 + local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True) + x = local[:-1].reshape(-1, args.train_seq_len) + y = local[1:].reshape(-1, args.train_seq_len) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + batch_loss = model(x, y).detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +# ----------------------------- +# QUANTIZATION (INT5 MLP / INT6 ATTN mixed PTQ) +# ----------------------------- + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights,smear,bigram.scale,trigram.scale,ve_layer_scales,ve_shared.scale", + ).split(",") + if pattern +) +FP16_KEEP_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get("FP16_KEEP_NAME_PATTERNS", "tok_emb,blocks.8.attn.c_k").split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 + +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + INT8_CLIP_Q = 99.99984 / 100.0 + t32 = t.float() + if t32.ndim == 2: + clip_abs = ( + torch.quantile(t32.abs(), INT8_CLIP_Q, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + clipped = torch.maximum(torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None]) + scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) + q = torch.clamp(torch.round(clipped / scale[:, None]), -127, 127).to(torch.int8).contiguous() + return q, scale.to(dtype=torch.float16).contiguous() + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127).to(torch.int8).contiguous() + return q, scale + + +def _classify_param(name: str) -> str: + if "tok_emb" in name or "lm_head" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if "bigram" in name: + return "bigram" + if "trigram" in name: + return "trigram" + if ".attn." in name or (".proj." in name and ".mlp." not in name): + return "attn" + return "other" + + +def quantize_intN_per_row(t: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + """Quantize with GPTQ-lite: search 5 clip percentiles, pick best MSE.""" + t32 = t.float() + if t32.ndim == 2: + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 0.99999, 1.0]: + if pct < 1.0: + row_clip = torch.quantile(t32.abs(), pct, dim=1) + else: + row_clip = t32.abs().amax(dim=1) + scale = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + scale = scale.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(t32 / scale.float()[:, None]), -(clip_range + 1), clip_range).to(torch.int8) + err = (t32 - q.float() * scale.float()[:, None]).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, scale, err + return best_q, best_s + amax = t32.abs().max().item() + scale = torch.tensor(max(amax / clip_range, 1e-12), dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -(clip_range + 1), clip_range).to(torch.int8) + return q, scale + + +def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15, attn_clip: int = 31): + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param(name) + if not t.is_floating_point() or t.numel() <= 8192: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + if any(pattern in name for pattern in FP16_KEEP_NAME_PATTERNS): + result[name] = t.to(dtype=torch.float16).contiguous() + meta[name] = "passthrough_fp16" + continue + if cat in int6_cats and t.ndim >= 1: + # MLP: always uses mlp_clip (INT4 or INT5) + # attn: uses attn_clip (INT6 default, INT4 when ATTN_QAT_BITS=4) + # bigram/trigram: follow mlp_clip when INT4 (saves ~0.25MB), else INT6 + if cat == "mlp": + clip = mlp_clip + elif cat == "attn": + clip = attn_clip + elif cat in ("bigram", "trigram") and mlp_clip <= 7: + clip = mlp_clip # INT4 bigram/trigram when MLP is INT4 + else: + clip = 31 # INT6 for bigram/trigram in INT5 mode + q, s = quantize_intN_per_row(t, clip_range=clip) + result[name + ".q"] = q + result[name + ".scale"] = s + bits = clip.bit_length() + 1 # clip=31→int6, clip=15→int5, clip=7→int4 + meta[name] = {"type": f"int{bits}"} + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return result, meta + + +def dequantize_mixed_int6(result: dict[str, Tensor], meta: dict[str, object], + template_sd: dict[str, Tensor]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + for name, orig in template_sd.items(): + info = meta[name] + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl", "passthrough_fp16"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + + +# ----------------------------- +# DATA LOADING +# ----------------------------- + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = rank + self.world_size = world_size + self.device = device + self.stream = TokenStream(pattern) + + def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> tuple[Tensor, Tensor]: + local_tokens = global_tokens // (self.world_size * grad_accum_steps) + per_rank_span = local_tokens + 1 + chunk = self.stream.take(per_rank_span * self.world_size) + start = self.rank * per_rank_span + local = chunk[start : start + per_rank_span].to(dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + return x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) + + +# ----------------------------- +# TRANSFORMER MODULES +# ----------------------------- + +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + + +class CastedLinear(nn.Linear): + # _qat_clip_range: 127=off/INT8, 31=INT6, 15=INT5 + _qat_clip_range: int = 127 + + def forward(self, x: Tensor) -> Tensor: + w = self.weight + if self.training and self._qat_clip_range < 127 and w.ndim == 2: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w.to(x.dtype), bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int = 0): + super().__init__() + self.rope_dims = rope_dims if rope_dims > 0 else dim + rd = self.rope_dims + inv_freq = 1.0 / (base ** (torch.arange(0, rd, 2, dtype=torch.float32) / rd)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + rd = cos.size(-1) * 2 + if rd < x.size(-1): # partial RoPE: rotate first rd dims, pass rest unchanged + x_rope, x_pass = x[..., :rd], x[..., rd:] + half = rd // 2 + x1, x2 = x_rope[..., :half], x_rope[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + + +class CausalSelfAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, rope_base: float, qk_gain_init: float, rope_dims: int = 0): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + # No CastedLinear weights -- come from GPT banks + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base, rope_dims=rope_dims) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + """XSA: subtract self-value projection, forcing heads to attend to OTHER tokens.""" + B, T, H, D = y.shape + Hkv = v.size(2) # v is [B, T, Hkv, D] + group = H // Hkv + y_g = y.reshape(B, T, Hkv, group, D) + vn = F.normalize(v, dim=-1).unsqueeze(3) # [B, T, Hkv, 1, D] + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, q_w: Tensor, k_w: Tensor, v_w: Tensor, out_w: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + bsz, seqlen, dim = x.shape + q = F.linear(x, q_w.to(x.dtype)).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = F.linear(x, k_w.to(x.dtype)).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v_raw = F.linear(x, v_w.to(x.dtype)) + if v_embed is not None: + v_raw = v_raw + v_embed + v_bthd = v_raw.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + v = v_bthd.transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention( + q, k, v, attn_mask=None, is_causal=True, + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + y = y.transpose(1, 2).contiguous() + if self.use_xsa: + y = self._xsa_efficient(y, v_bthd) + y = y.reshape(bsz, seqlen, dim) + return F.linear(y, out_w.to(x.dtype)) + + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: float): + super().__init__() + # No CastedLinear weights -- come from GPT banks + + def forward(self, x: Tensor, up_w: Tensor, down_w: Tensor) -> Tensor: + x = F.leaky_relu(F.linear(x, up_w.to(x.dtype)), negative_slope=0.5) + return F.linear(x.square(), down_w.to(x.dtype)) + + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate.to(dtype=x.dtype))[None, None, :] + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1 - g) * x + g * x_prev + + +class BigramHashEmbedding(nn.Module): + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, bigram_vocab_size: int, bigram_dim: int, model_dim: int): + super().__init__() + self.bigram_vocab_size = bigram_vocab_size + self.embed = nn.Embedding(bigram_vocab_size, bigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(bigram_dim, model_dim, bias=False) if bigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.05, dtype=torch.float32)) + + def bigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.bigram_vocab_size - 1 + out = torch.empty_like(t) + out[..., 0] = mod + out[..., 1:] = torch.bitwise_xor(36313 * t[..., 1:], 27191 * t[..., :-1]) % mod + return out.long() + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.bigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class TrigramHashEmbedding(nn.Module): + """3-gram context embedding: (prev2, prev1, curr) → hashed bucket → learned embedding.""" + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, trigram_vocab_size: int, trigram_dim: int, model_dim: int): + super().__init__() + self.trigram_vocab_size = trigram_vocab_size + self.embed = nn.Embedding(trigram_vocab_size, trigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(trigram_dim, model_dim, bias=False) if trigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.02, dtype=torch.float32)) + + def trigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.trigram_vocab_size - 1 + out = torch.full_like(t, mod, dtype=torch.long) # sentinel for positions without full context + out[..., 2:] = ( + torch.bitwise_xor( + torch.bitwise_xor(17291 * t[..., 2:], 36313 * t[..., 1:-1]), + 27191 * t[..., :-2], + ) % mod + ) + return out + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.trigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class ValueEmbedding(nn.Module): + """Reinject token identity into attention values at specific layers. + Shared embedding table + per-layer learned scale. Applied at last N layers.""" + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int): + super().__init__() + self.embed = nn.Embedding(vocab_size, ve_dim) + nn.init.normal_(self.embed.weight, std=0.01) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) if ve_dim != kv_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.1, dtype=torch.float32)) + + def forward(self, token_ids: Tensor) -> Tensor: + h = self.embed(token_ids) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class Block(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, mlp_mult: float, rope_base: float, qk_gain_init: float, rope_dims: int = 0, ln_scale: bool = False, layer_idx: int = 0): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, rope_dims=rope_dims) + self.mlp = MLP(dim, mlp_mult) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + + def forward(self, x: Tensor, x0: Tensor, q_w: Tensor, k_w: Tensor, v_w: Tensor, out_w: Tensor, up_w: Tensor, down_w: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + s = self.ln_scale_factor + attn_out = self.attn(self.attn_norm(x) * s, q_w, k_w, v_w, out_w, v_embed=v_embed) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * s, up_w, down_w) + return x + + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_layers: int, + model_dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: float, + tie_embeddings: bool, + tied_embed_init_std: float, + logit_softcap: float, + rope_base: float, + qk_gain_init: float, + bigram_vocab_size: int = 0, + bigram_dim: int = 128, + trigram_vocab_size: int = 0, + trigram_dim: int = 64, + rope_dims: int = 0, + ln_scale: bool = False, + xsa_last_n: int = 0, + value_embed_layers: int = 0, + value_embed_dim: int = 64, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.bigram = BigramHashEmbedding(bigram_vocab_size, bigram_dim, model_dim) if bigram_vocab_size > 0 else None + self.trigram = TrigramHashEmbedding(trigram_vocab_size, trigram_dim, model_dim) if trigram_vocab_size > 0 else None + self.num_encoder_layers = num_layers // 2 + self.num_decoder_layers = num_layers - self.num_encoder_layers + self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers) + self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32)) + self.smear = SmearGate(model_dim) + # Parameter banks: contiguous 3D tensors for Parallel Muon + head_dim = model_dim // num_heads + kv_dim = num_kv_heads * head_dim + mlp_dim = int(mlp_mult * model_dim) + self.num_layers = num_layers + self.qo_bank = nn.Parameter(torch.empty(2 * num_layers, model_dim, model_dim)) + self.kv_bank = nn.Parameter(torch.empty(2 * num_layers, kv_dim, model_dim)) + self.mlp_up_bank = nn.Parameter(torch.empty(num_layers, mlp_dim, model_dim)) + self.mlp_down_bank = nn.Parameter(torch.empty(num_layers, model_dim, mlp_dim)) + self.blocks = nn.ModuleList( + [ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init, + rope_dims=rope_dims, ln_scale=ln_scale, layer_idx=i) + for i in range(num_layers) + ] + ) + if xsa_last_n > 0: + for i in range(max(0, num_layers - xsa_last_n), num_layers): + self.blocks[i].attn.use_xsa = True + # ValueEmbedding: shared table + per-layer scales for last N layers + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve_layer_indices = list(range(max(0, num_layers - value_embed_layers), num_layers)) if value_embed_layers > 0 else [] + if self.ve_layer_indices: + self.ve_shared = ValueEmbedding(vocab_size, value_embed_dim, kv_dim) + self.ve_layer_scales = nn.ParameterList( + [nn.Parameter(torch.ones(1, dtype=torch.float32)) for _ in self.ve_layer_indices] + ) + else: + self.ve_shared = None + self.ve_layer_scales = nn.ParameterList() + self.final_norm = RMSNorm() + self.lm_head = None if tie_embeddings else CastedLinear(model_dim, vocab_size, bias=False) + if self.lm_head is not None: + self.lm_head._zero_init = True + self._init_weights() + + def _init_weights(self) -> None: + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) + n = self.num_layers + proj_scale = 1.0 / math.sqrt(2 * n) + for i in range(n): + nn.init.orthogonal_(self.qo_bank.data[i], gain=1.0) # Q + nn.init.zeros_(self.qo_bank.data[n + i]) # Out (zero init) + self.qo_bank.data[n + i].mul_(proj_scale) + nn.init.orthogonal_(self.kv_bank.data[i], gain=1.0) # K + nn.init.orthogonal_(self.kv_bank.data[n + i], gain=1.0) # V + nn.init.orthogonal_(self.mlp_up_bank.data[i], gain=1.0) # MLP up + nn.init.zeros_(self.mlp_down_bank.data[i]) # MLP down (zero init) + self.mlp_down_bank.data[i].mul_(proj_scale) + # Init remaining nn.Linear modules (bigram proj, trigram proj, lm_head) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and module.weight.shape[0] >= 64 and module.weight.shape[1] >= 64: + nn.init.orthogonal_(module.weight, gain=1.0) + + # QAT clip ranges: 127=off, 31=INT6, 15=INT5, 7=INT4 + _qat_mlp_clip: int = 127 + _qat_attn_clip: int = 127 + + def _fq(self, w: Tensor, clip: int) -> Tensor: + """Fake-quantize bank weight w using STE. Returns w unchanged when clip >= 127.""" + if not self.training or clip >= 127: + return w + w_f = w.float() + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / float(clip) + q = (w_f / scale).round().clamp(-float(clip + 1), float(clip)) + w_q = q * scale + return w + (w_q - w_f).detach() + + def _get_ve(self, layer_idx: int, ve_base: "Tensor | None") -> "Tensor | None": + if ve_base is None or layer_idx not in self.ve_layer_indices: + return None + idx = self.ve_layer_indices.index(layer_idx) + return ve_base * self.ve_layer_scales[idx].to(dtype=ve_base.dtype) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + n = self.num_layers + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + q_w = self._fq(self.qo_bank[i], self._qat_attn_clip) + out_w = self._fq(self.qo_bank[n + i], self._qat_attn_clip) + k_w = self._fq(self.kv_bank[i], self._qat_attn_clip) + v_w = self._fq(self.kv_bank[n + i], self._qat_attn_clip) + up_w = self._fq(self.mlp_up_bank[i], self._qat_mlp_clip) + down_w = self._fq(self.mlp_down_bank[i], self._qat_mlp_clip) + x = self.blocks[i](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + bi = self.num_encoder_layers + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + q_w = self._fq(self.qo_bank[bi], self._qat_attn_clip) + out_w = self._fq(self.qo_bank[n + bi], self._qat_attn_clip) + k_w = self._fq(self.kv_bank[bi], self._qat_attn_clip) + v_w = self._fq(self.kv_bank[n + bi], self._qat_attn_clip) + up_w = self._fq(self.mlp_up_bank[bi], self._qat_mlp_clip) + down_w = self._fq(self.mlp_down_bank[bi], self._qat_mlp_clip) + x = self.blocks[bi](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, v_embed=self._get_ve(bi, ve_base)) + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + n = self.num_layers + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + q_w = self._fq(self.qo_bank[i], self._qat_attn_clip) + out_w = self._fq(self.qo_bank[n + i], self._qat_attn_clip) + k_w = self._fq(self.kv_bank[i], self._qat_attn_clip) + v_w = self._fq(self.kv_bank[n + i], self._qat_attn_clip) + up_w = self._fq(self.mlp_up_bank[i], self._qat_mlp_clip) + down_w = self._fq(self.mlp_down_bank[i], self._qat_mlp_clip) + x = self.blocks[i](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + bi = self.num_encoder_layers + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + q_w = self._fq(self.qo_bank[bi], self._qat_attn_clip) + out_w = self._fq(self.qo_bank[n + bi], self._qat_attn_clip) + k_w = self._fq(self.kv_bank[bi], self._qat_attn_clip) + v_w = self._fq(self.kv_bank[n + bi], self._qat_attn_clip) + up_w = self._fq(self.mlp_up_bank[bi], self._qat_mlp_clip) + down_w = self._fq(self.mlp_down_bank[bi], self._qat_mlp_clip) + x = self.blocks[bi](x, x0, q_w, k_w, v_w, out_w, up_w, down_w, v_embed=self._get_ve(bi, ve_base)) + x = self.final_norm(x) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + logits_proj = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + + +def _unbank_state_dict(sd: dict, num_layers: int) -> dict: + """Convert 3D bank tensors into individual 2D tensors with standard per-layer names.""" + out = {} + n = num_layers + for name, tensor in sd.items(): + if name == "qo_bank": + for i in range(n): + out[f"blocks.{i}.attn.c_q.weight"] = tensor[i] + out[f"blocks.{i}.attn.proj.weight"] = tensor[n + i] + elif name == "kv_bank": + for i in range(n): + out[f"blocks.{i}.attn.c_k.weight"] = tensor[i] + out[f"blocks.{i}.attn.c_v.weight"] = tensor[n + i] + elif name == "mlp_up_bank": + for i in range(n): + out[f"blocks.{i}.mlp.fc.weight"] = tensor[i] + elif name == "mlp_down_bank": + for i in range(n): + out[f"blocks.{i}.mlp.proj.weight"] = tensor[i] + else: + out[name] = tensor + return out + + +def _rebank_state_dict(sd: dict, num_layers: int, template_sd: dict) -> dict: + """Convert individual 2D tensors back into 3D bank tensors.""" + out = {} + n = num_layers + qo_slices = [None] * (2 * n) + kv_slices = [None] * (2 * n) + up_slices = [None] * n + down_slices = [None] * n + consumed = set() + for i in range(n): + qk = f"blocks.{i}.attn.c_q.weight" + if qk in sd: + qo_slices[i] = sd[qk]; consumed.add(qk) + ok = f"blocks.{i}.attn.proj.weight" + if ok in sd: + qo_slices[n + i] = sd[ok]; consumed.add(ok) + kk = f"blocks.{i}.attn.c_k.weight" + if kk in sd: + kv_slices[i] = sd[kk]; consumed.add(kk) + vk = f"blocks.{i}.attn.c_v.weight" + if vk in sd: + kv_slices[n + i] = sd[vk]; consumed.add(vk) + fk = f"blocks.{i}.mlp.fc.weight" + if fk in sd: + up_slices[i] = sd[fk]; consumed.add(fk) + dk = f"blocks.{i}.mlp.proj.weight" + if dk in sd: + down_slices[i] = sd[dk]; consumed.add(dk) + out["qo_bank"] = torch.stack(qo_slices).to(dtype=template_sd["qo_bank"].dtype) + out["kv_bank"] = torch.stack(kv_slices).to(dtype=template_sd["kv_bank"].dtype) + out["mlp_up_bank"] = torch.stack(up_slices).to(dtype=template_sd["mlp_up_bank"].dtype) + out["mlp_down_bank"] = torch.stack(down_slices).to(dtype=template_sd["mlp_down_bank"].dtype) + for name, tensor in sd.items(): + if name not in consumed: + out[name] = tensor + return out + + +def eval_val_sliding( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, + stride: int, + batch_seqs: int = 32, +) -> tuple[float, float]: + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + total_windows = len(window_starts) + my_s = (total_windows * rank) // world_size + my_e = (total_windows * (rank + 1)) // world_size + my_windows = window_starts[my_s:my_e] + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk[:-1] + y_batch[i, :wlen] = chunk[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt = y_batch[i, s:wlen] + prev = x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + running_bpb = 0.0 + if token_count.item() > 0: + rl = (loss_sum / token_count).item() + running_bpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) + print(f" sliding_eval [{pct:5.1f}%] {done}/{len(my_windows)} windows running_bpb={running_bpb:.6f}", flush=True) + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + bits_per_token = val_loss / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + base_model.train() + return val_loss, bits_per_token * tokens_per_byte + + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: nn.Module, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + """Legal score-first TTT: score each chunk with sliding windows, then train on it. + Every token is scored BEFORE any update that could use it (PR #461 recipe).""" + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + ttt_chunk = args.ttt_chunk_tokens + + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + + num_chunks = (total_tokens + ttt_chunk - 1) // ttt_chunk + chunk_windows: list[list[int]] = [[] for _ in range(num_chunks)] + for ws in window_starts: + end = min(ws + seq_len, total_tokens) + wlen = end - ws + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_start = ws + s + ci = min(scored_start // ttt_chunk, num_chunks - 1) + chunk_windows[ci].append(ws) + + log0(f"ttt_sliding:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"total_windows={len(window_starts)} stride={stride} " + f"ttt_lr={args.ttt_lr} ttt_epochs={args.ttt_epochs} " + f"freeze_blocks={args.ttt_freeze_blocks}") + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + log0(f"ttt_sliding:params unfrozen={sum(p.numel() for p in ttt_params)} " + f"frozen={sum(p.numel() for p in base_model.parameters() if not p.requires_grad)}") + + optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) + t0 = time.perf_counter() + + for ci in range(num_chunks): + windows = chunk_windows[ci] + if not windows: + continue + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + my_s = (len(windows) * rank) // world_size + my_e = (len(windows) * (rank + 1)) // world_size + my_windows = windows[my_s:my_e] + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk_tok = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk_tok[:-1] + y_batch[i, :wlen] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt, prev = y_batch[i, s:wlen], x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + my_seq_s = (chunk_seqs * rank) // world_size + my_seq_e = (chunk_seqs * (rank + 1)) // world_size + my_chunk_seqs = my_seq_e - my_seq_s + for _ep in range(args.ttt_epochs): + for bs in range(0, my_chunk_seqs, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_chunk_seqs) + actual_bs = my_seq_s + bs + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + (my_seq_s + be) * seq_len + 1 + if end_tok > val_tokens.numel(): + continue + local = val_tokens[start_tok:end_tok].to(device=device, dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + optimizer.zero_grad(set_to_none=True) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + loss = base_model(x, y) + loss.backward() + if world_size > 1: + for p in ttt_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) if token_count.item() > 0 else 0.0 + log0(f" ttt_chunk [{ci+1}/{num_chunks}] bpb={rbpb:.6f} time={elapsed:.1f}s") + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + val_bpb = val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.eval() + + log0(f"ttt_sliding:done val_loss={val_loss:.6f} val_bpb={val_bpb:.6f} " + f"elapsed={time.perf_counter() - t0:.1f}s") + return val_loss, val_bpb + + +# ----------------------------- +# TRAINING +# ----------------------------- + +def main() -> None: + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + # Parallel Muon uses batched bmm — do NOT torch.compile NS5 (bmm is already efficient) + + distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size <= 0: + raise ValueError(f"WORLD_SIZE must be positive, got {world_size}") + if 8 % world_size != 0: + raise ValueError(f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral") + grad_accum_steps = 8 // world_size + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + + logfile = None + wandb_enabled = False + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + if _WANDB_AVAILABLE and bool(int(os.environ.get("WANDB_ENABLED", "1"))): + wandb.init( + project=os.environ.get("WANDB_PROJECT", "parameter-golf"), + name=args.run_id, + config={ + "num_layers": args.num_layers, + "model_dim": args.model_dim, + "mlp_mult": args.mlp_mult, + "num_heads": args.num_heads, + "num_kv_heads": args.num_kv_heads, + "mlp_quant_bits": args.mlp_quant_bits, + "iterations": args.iterations, + "train_batch_tokens": args.train_batch_tokens, + "train_seq_len": args.train_seq_len, + "xsa_last_n": args.xsa_last_n, + "ema_enabled": args.ema_enabled, + "rope_dims": args.rope_dims, + "ln_scale": args.ln_scale, + "late_qat_threshold": args.late_qat_threshold, + "ttt_enabled": args.ttt_enabled, + "bigram_vocab_size": args.bigram_vocab_size, + "value_embed_layers": args.value_embed_layers, + "value_embed_dim": args.value_embed_dim, + "seed": args.seed, + }, + resume="allow", + ) + wandb_enabled = True + + def log0(msg: str, console: bool = True) -> None: + if not master_process: + return + if console: + print(msg) + if logfile is not None: + with open(logfile, "a", encoding="utf-8") as f: + print(msg, file=f) + + log0(code, console=False) + log0("=" * 100, console=False) + log0(f"Running Python {sys.version}", console=False) + log0(f"Running PyTorch {torch.__version__}", console=False) + log0( + subprocess.run(["nvidia-smi"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout, + console=False, + ) + log0("=" * 100, console=False) + + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + + if not args.tokenizer_path.endswith(".model"): + raise ValueError(f"Script only setup for SentencePiece .model file: {args.tokenizer_path}") + sp = spm.SentencePieceProcessor(model_file=args.tokenizer_path) + if int(sp.vocab_size()) != args.vocab_size: + raise ValueError( + f"VOCAB_SIZE={args.vocab_size} does not match tokenizer vocab_size={int(sp.vocab_size())}" + ) + dataset_dir = Path(args.data_path).resolve() + actual_train_files = len(list(dataset_dir.glob("fineweb_train_*.bin"))) + val_tokens = load_validation_tokens(args.val_files, args.train_seq_len) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = build_sentencepiece_luts( + sp, args.vocab_size, device + ) + log0(f"val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path={args.tokenizer_path}") + log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}") + log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}") + + # MODEL SETUP + base_model = GPT( + vocab_size=args.vocab_size, + num_layers=args.num_layers, + model_dim=args.model_dim, + num_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + mlp_mult=args.mlp_mult, + tie_embeddings=args.tie_embeddings, + tied_embed_init_std=args.tied_embed_init_std, + logit_softcap=args.logit_softcap, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + bigram_vocab_size=args.bigram_vocab_size, + bigram_dim=args.bigram_dim, + trigram_vocab_size=args.trigram_vocab_size, + trigram_dim=args.trigram_dim, + rope_dims=args.rope_dims, + ln_scale=args.ln_scale, + xsa_last_n=args.xsa_last_n, + value_embed_layers=args.value_embed_layers, + value_embed_dim=args.value_embed_dim, + ).to(device).bfloat16() + # Banks stay FP32 (cast to BF16 in forward via _fq) + base_model.qo_bank.data = base_model.qo_bank.data.float() + base_model.kv_bank.data = base_model.kv_bank.data.float() + base_model.mlp_up_bank.data = base_model.mlp_up_bank.data.float() + base_model.mlp_down_bank.data = base_model.mlp_down_bank.data.float() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + + # QAT: set per-layer fake-quantization targets + # MLP precision controlled by MLP_QUANT_BITS (4=INT4 clip=7, 5=INT5 clip=15) + mlp_clip = (1 << (args.mlp_quant_bits - 1)) - 1 # 5→15, 4→7 + attn_clip = (1 << (args.attn_quant_bits - 1)) - 1 # 6→31, 4→7 + ngram_clip = mlp_clip if args.mlp_quant_bits <= 4 else 31 # INT4 bigram/trigram when MLP is INT4 + _qat_active = False # tracks whether fake-quant has been activated + + def _enable_qat() -> None: + nonlocal _qat_active, ema_state + if _qat_active: + return + _qat_active = True + # Reset EMA so it only accumulates QAT-adapted weights (prevents pre-QAT contamination) + if args.ema_enabled and ema_state is not None: + ema_state = None + log0("qat:ema_reset (EMA will restart from current QAT weights)") + # Set bank QAT clips (for qo_bank, kv_bank, mlp_up_bank, mlp_down_bank) + base_model._qat_mlp_clip = mlp_clip + base_model._qat_attn_clip = attn_clip + # Set bigram/trigram CastedLinear clip ranges + for name, module in base_model.named_modules(): + if isinstance(module, CastedLinear): + if "bigram" in name or "trigram" in name: + module._qat_clip_range = ngram_clip + else: + module._qat_clip_range = attn_clip # VE proj, lm_head: use attn clip + if base_model.bigram is not None: + base_model.bigram._qat_clip_range = ngram_clip + if base_model.trigram is not None: + base_model.trigram._qat_clip_range = ngram_clip + ngram_bits = '4' if ngram_clip <= 7 else '6' + trig_str = f" trigram=INT{ngram_bits}(clip={ngram_clip})" if base_model.trigram is not None else "" + log0(f"qat:enabled mlp=INT{args.mlp_quant_bits}(clip={mlp_clip}) attn=INT{args.attn_quant_bits}(clip={attn_clip}) bigram=INT{ngram_bits}(clip={ngram_clip}){trig_str}") + + if args.qat_enabled: + if args.late_qat_threshold > 0: + log0(f"qat:late_qat threshold={args.late_qat_threshold} (activates when lr_scale < threshold)") + else: + _enable_qat() + else: + log0("qat:disabled") + + # No DDP -- Parallel Muon handles bank grad sync via reduce-scatter + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = compiled_model + + # OPTIMIZER SETUP + # Optimizer split: + # - 4 parameter banks -> Parallel Muon (batched Newton-Schulz via reduce-scatter) + # - embeddings -> AdamW + # - scalars/control tensors -> AdamW + matrix_params = [ + base_model.qo_bank, base_model.kv_bank, + base_model.mlp_up_bank, base_model.mlp_down_bank, + ] + block_named_params = list(base_model.blocks.named_parameters()) + scalar_params = [ + p for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + scalar_params.append(base_model.smear.gate) + if base_model.bigram is not None: + scalar_params.append(base_model.bigram.scale) + if base_model.trigram is not None: + scalar_params.append(base_model.trigram.scale) + + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + tok_params = [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}] + if base_model.bigram is not None: + tok_params.append({"params": [base_model.bigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.bigram.proj is not None: + scalar_params.append(base_model.bigram.proj.weight) + if base_model.trigram is not None: + tok_params.append({"params": [base_model.trigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.trigram.proj is not None: + scalar_params.append(base_model.trigram.proj.weight) + if base_model.ve_shared is not None: + tok_params.append({"params": [base_model.ve_shared.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.ve_shared.proj is not None: + scalar_params.append(base_model.ve_shared.proj.weight) + scalar_params.append(base_model.ve_shared.scale) + for s in base_model.ve_layer_scales: + scalar_params.append(s) + + # Non-bank params that need manual all-reduce (replicated across GPUs, not sharded) + replicated_params = [] + for pg in tok_params: + replicated_params.extend(pg["params"]) + replicated_params.extend(scalar_params) + + optimizer_tok = torch.optim.AdamW( + tok_params, + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=0.04, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + replicated_params.append(base_model.lm_head.weight) + + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params}") + if base_model.ve_shared is not None: + log0(f"value_embed:layers={base_model.ve_layer_indices} ve_dim={args.value_embed_dim} kv_dim={base_model.ve_shared.proj.out_features if base_model.ve_shared.proj else args.value_embed_dim}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0(f"sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + # DATA LOADER & WARMUP + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + + max_wallclock_ms = 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0 + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 + + if args.warmup_steps > 0: + initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()} + initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers] + model.train() + for warmup_step in range(args.warmup_steps): + zero_grad_all() + for micro_step in range(grad_accum_steps): + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + warmup_loss = model(x, y) + (warmup_loss * grad_scale).backward() + # Without DDP: manually all-reduce all grads for warmup (simple, only 20 steps) + if distributed: + for p in base_model.parameters(): + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + for opt in optimizers: + opt.step() + zero_grad_all() + if args.warmup_steps <= 20 or (warmup_step + 1) % 10 == 0 or warmup_step + 1 == args.warmup_steps: + log0(f"warmup_step:{warmup_step + 1}/{args.warmup_steps}") + base_model.load_state_dict(initial_model_state, strict=True) + for opt, state in zip(optimizers, initial_optimizer_states, strict=True): + opt.load_state_dict(state) + zero_grad_all() + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + # MAIN TRAINING LOOP + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + # EMA state: kept on GPU for efficiency, initialized on first step + ema_state: dict[str, Tensor] | None = None + # QAT timing: use wallclock fraction for deterministic triggering (immune to step_ms estimate noise) + # LATE_QAT_FRAC=0.65 fires QAT at 65% of budget (~390s), giving ~1400 QAT steps. + # Falls back to LR-scale method if LATE_QAT_FRAC is unset or 0. + _late_qat_frac = float(os.environ.get("LATE_QAT_FRAC", "0.0")) + _late_qat_trigger_ms = (_late_qat_frac * max_wallclock_ms) if (max_wallclock_ms and _late_qat_frac > 0) else None + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + if wandb_enabled: + wandb.log({"val/loss": val_loss, "val/bpb": val_bpb}, step=step) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_active: + if _late_qat_trigger_ms is not None: + if elapsed_ms >= _late_qat_trigger_ms: + _enable_qat() + elif args.late_qat_threshold > 0 and scale < args.late_qat_threshold: + _enable_qat() + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + + # === 3-phase overlapped optimizer step === + # Phase 1: Launch async reduce-scatter for banks (biggest first) + optimizer_muon.launch_reduce_scatters() + # Phase 2: All-reduce non-bank grads + step Adam (while bank RS is in-flight) + if distributed: + for p in replicated_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + for opt in optimizers: + if opt is not optimizer_muon: + opt.step() + # Phase 3: Wait for RS, local NS5, all-gather (banks processed last) + optimizer_muon.step() + zero_grad_all() + + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + + # EMA: update running average of weights (GPU, no extra transfer) + if args.ema_enabled: + if ema_state is None: + ema_state = {name: t.detach().clone() for name, t in base_model.state_dict().items()} + else: + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(args.ema_decay).add_(t.detach(), alpha=1.0 - args.ema_decay) + + # SWA: collect checkpoints during warmdown + if args.swa_enabled and scale < args.swa_start_frac and step % args.swa_every == 0: + if swa_state is None: + swa_state = {name: t.detach().cpu().clone() for name, t in base_model.state_dict().items()} + swa_count = 1 + log0(f"swa:start step:{step}") + else: + for name, t in base_model.state_dict().items(): + swa_state[name] += t.detach().cpu() + swa_count += 1 + + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + if wandb_enabled: + wandb.log({ + "train/loss": train_loss.item(), + "train/lr_scale": scale, + "train/step_ms": approx_training_time_ms / step, + }, step=step) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + # Apply SWA if collected + if args.swa_enabled and swa_state is not None and swa_count > 1: + log0(f"swa:applying averaged {swa_count} checkpoints") + current_state = base_model.state_dict() + avg_state = { + name: (tensor / swa_count).to(dtype=current_state[name].dtype) + for name, tensor in swa_state.items() + } + base_model.load_state_dict(avg_state, strict=True) + + # Apply EMA: use smooth running average as final weights (overrides SWA if both enabled) + if args.ema_enabled and ema_state is not None: + log0(f"ema:applying (decay={args.ema_decay})") + current_state = base_model.state_dict() + ema_cpu = {name: t.cpu().to(dtype=current_state[name].dtype) for name, t in ema_state.items()} + base_model.load_state_dict(ema_cpu, strict=True) + + # SERIALIZATION + QUANTIZATION + if master_process: + torch.save(base_model.state_dict(), f"final_model_{args.run_id}.pt") + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total uncompressed: {model_bytes + code_bytes} bytes") + + # Magnitude pruning on bank slices to aid compression + with torch.no_grad(): + for bank_name in ["qo_bank", "kv_bank", "mlp_up_bank", "mlp_down_bank"]: + bank = getattr(base_model, bank_name) + for i in range(bank.shape[0]): + w = bank.data[i] + threshold = torch.quantile(w.abs().float().flatten(), 0.03) + bank.data[i].masked_fill_(w.abs() < threshold, 0.0) + # Also prune 2D non-bank params + for name, param in base_model.named_parameters(): + if param.ndim == 2 and param.numel() > 65536 and name not in {"qo_bank", "kv_bank", "mlp_up_bank", "mlp_down_bank"}: + threshold = torch.quantile(param.abs().float().flatten(), 0.03) + mask = param.abs() < threshold + param.masked_fill_(mask, 0.0) + + # Unbank 3D bank tensors → per-layer 2D for quantization + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + unbanked_sd = _unbank_state_dict(sd_cpu, args.num_layers) + + # Dynamically set FP16_KEEP to keep last attention layer's c_k in FP16 (reduces late-layer quant penalty) + # Default "blocks.8.attn.c_k" is correct for 9L; override here for other depths + global FP16_KEEP_NAME_PATTERNS + last_layer_ck = f"blocks.{args.num_layers - 1}.attn.c_k" + FP16_KEEP_NAME_PATTERNS = tuple( + p for p in set(list(FP16_KEEP_NAME_PATTERNS) + [last_layer_ck]) + if p and (not p.startswith("blocks.") or p == last_layer_ck) + ) + + # INT5/INT4 MLP + INT6/INT4 Attn/Bigram/Trigram mixed quantization + zstd-22 / zlib-9 export + int6_cats = {"mlp", "attn", "bigram"} + if base_model.trigram is not None: + int6_cats.add("trigram") + quant_result, quant_meta = mixed_quantize_int6(unbanked_sd, int6_cats, mlp_clip=mlp_clip, attn_clip=attn_clip) + quant_buf = io.BytesIO() + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + quant_raw = quant_buf.getvalue() + if _COMPRESSOR == "zstd": + quant_blob = zstandard.ZstdCompressor(level=22).compress(quant_raw) + else: + quant_blob = zlib.compress(quant_raw, 9) + if master_process: + with open(f"final_model_{args.run_id}.int8.ptz", "wb") as f: + f.write(quant_blob) + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int5mlp+int6attn+{_COMPRESSOR}: {quant_file_bytes} bytes") + log0(f"Total submission size: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + if _COMPRESSOR == "zstd": + decompressed = zstandard.ZstdDecompressor().decompress(quant_blob_disk) + else: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + deq_unbanked = dequantize_mixed_int6(quant_state["w"], quant_state["m"], unbanked_sd) + # Re-bank the dequantized tensors + deq_state = _rebank_state_dict(deq_unbanked, args.num_layers, sd_cpu) + base_model.load_state_dict(deq_state, strict=True) + + # Final eval on roundtripped weights with sliding window + torch.cuda.synchronize() + t_qeval = time.perf_counter() + if args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window stride:{args.eval_stride} batch_seqs:{args.eval_batch_seqs}") + q_val_loss, q_val_bpb = eval_val_sliding( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, + ) + else: + log0("final_eval_mode:standard") + q_val_loss, q_val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + if wandb_enabled: + wandb.log({ + "final/post_quant_bpb": q_val_bpb, + "final/post_quant_loss": q_val_loss, + "final/artifact_mb": quant_file_bytes / 1e6, + }) + + if args.ttt_enabled: + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, log0=log0, + ) + torch.cuda.synchronize() + log0(f"legal_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms") + log0(f"legal_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + if wandb_enabled: + wandb.log({"final/ttt_bpb": ttt_bpb, "final/ttt_loss": ttt_loss}) + + if wandb_enabled: + wandb.finish() + + if distributed: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() From 85376b675cc67b6a028ddb72392c4f112c92a73b Mon Sep 17 00:00:00 2001 From: Harsh Soni Date: Wed, 1 Apr 2026 06:53:17 +0000 Subject: [PATCH 6/9] Phase 11 prep: 11L INT6 XSA-all + GPTQ + Parallel Muon fixes train_gpt_v2.py: - LZMA compression support (COMPRESS=lzma env var) - Full Hessian GPTQ: gptq_quantize_weight() + collect_gptq_hessians() (GPTQ_ENABLED=1 activates post-training column-wise quantization) train_gpt_v3.py (Parallel Muon): - All replicated-param all_reduces now launched async simultaneously so NCCL can pipeline them (saves ~3-5ms/step vs serial blocking calls) - Removed redundant .contiguous() in non-XSA attention path run.sh: - v11_proxy: 1-GPU smoke test for 11L INT6 stack - v11_int6_xsaall: 11L INT6 + XSA-all + LZMA + VE (train_gpt_v2.py) - v11_gptq: same + GPTQ_ENABLED=1 (train_gpt_v2.py) - v11_banked: 11L INT6 + XSA-all + LZMA + VE + Parallel Muon (train_gpt_v3.py) --- run.sh | 71 ++++++++++++++++++++++++++- train_gpt_v2.py | 124 ++++++++++++++++++++++++++++++++++++++++++++++-- train_gpt_v3.py | 28 ++++++++--- 3 files changed, 210 insertions(+), 13 deletions(-) diff --git a/run.sh b/run.sh index 2a6028895a..b9504346d0 100644 --- a/run.sh +++ b/run.sh @@ -323,6 +323,74 @@ case "$CONFIG" in torchrun --standalone --nproc_per_node=8 train_gpt_v2.py ;; + v11_proxy) + echo "=== Phase 11 PROXY: 11L INT6 + XSA-all + LZMA — 1×GPU smoke test ===" + # Verifies correctness and baseline step_ms. No wallclock cap, 500 steps, no TTT. + # Expected: step_avg ~250-300ms (1 GPU vs 8), val_bpb ~1.35-1.40 at step 500 (undertrained) + export RUN_ID=v11_proxy SEED=${SEED:-1} MAX_WALLCLOCK_SECONDS=0 \ + ITERATIONS=500 VAL_LOSS_EVERY=100 TTT_ENABLED=0 \ + NUM_LAYERS=11 MLP_QUANT_BITS=6 \ + XSA_LAST_N=11 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 LATE_QAT_THRESHOLD=0.9 \ + BIGRAM_VOCAB_SIZE=3072 BIGRAM_DIM=112 \ + VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 \ + COMPRESS=lzma WARMDOWN_ITERS=4000 + torchrun --standalone --nproc_per_node=1 train_gpt_v2.py + ;; + + v11_gptq) + echo "=== Phase 11 H100: 11L INT6 + XSA-all + LZMA + VE + Full Hessian GPTQ ===" + # Adds GPTQ on top of v11_int6_xsaall base. Expected: -0.003 to -0.005 BPB vs v11_int6_xsaall. + # GPTQ uses 64 random seqs × 512 tokens for Hessian collection (~2s post-training). + # TTT disabled initially (neutral with GPTQ on this stack per PR #1019 findings). + # Expected: ~110-115ms/step → ~5200-5450 steps → ~1.125-1.135 BPB + export RUN_ID=v11_gptq_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=11 MLP_QUANT_BITS=6 \ + XSA_LAST_N=11 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 \ + LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ + LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=0 \ + BIGRAM_VOCAB_SIZE=3072 BIGRAM_DIM=112 \ + VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 \ + COMPRESS=lzma WARMDOWN_ITERS=4000 \ + GPTQ_ENABLED=1 + torchrun --standalone --nproc_per_node=8 train_gpt_v2.py + ;; + + v11_int6_xsaall) + echo "=== Phase 11 H100: 11L INT6 + XSA-all + LZMA + VE — correct base stack ===" + # THE RIGHT STACK. Matches community consensus: 11L INT6, XSA-all, LZMA, LeakyReLU(0.5)². + # Expected: ~130-145ms/step → ~4100-4600 steps → ~1.130-1.140 BPB + # Note: VE adds ~28-38ms overhead. INT6 is already default when MLP_QUANT_BITS=6. + export RUN_ID=v11_int6_xsaall_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=11 MLP_QUANT_BITS=6 \ + XSA_LAST_N=11 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 \ + LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ + LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ + BIGRAM_VOCAB_SIZE=3072 BIGRAM_DIM=112 \ + VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 \ + COMPRESS=lzma WARMDOWN_ITERS=4000 + torchrun --standalone --nproc_per_node=8 train_gpt_v2.py + ;; + + v11_banked) + echo "=== Phase 11 H100: 11L INT6 + XSA-all + LZMA + VE + Parallel Muon banking (train_gpt_v3.py) ===" + # Banking variant: async RS+AG replaces DDP allreduce for matrix banks. + # Replicated param all_reduces are now launched async (NCCL can pipeline them). + # Expected: ~125-135ms/step → ~4450-4800 steps + export RUN_ID=v11_banked_seed${SEED:-1} SEED=${SEED:-1} \ + NUM_LAYERS=11 MLP_QUANT_BITS=6 \ + XSA_LAST_N=11 EMA_ENABLED=1 SWA_ENABLED=0 \ + ROPE_DIMS=16 LN_SCALE=1 \ + LATE_QAT_FRAC=0.65 VAL_LOSS_EVERY=1000 \ + LATE_QAT_THRESHOLD=0.9 TTT_ENABLED=1 \ + BIGRAM_VOCAB_SIZE=3072 BIGRAM_DIM=112 \ + VALUE_EMBED_LAYERS=2 VALUE_EMBED_DIM=128 \ + COMPRESS=lzma WARMDOWN_ITERS=4000 + torchrun --standalone --nproc_per_node=8 train_gpt_v3.py + ;; + *) echo "Unknown config: $CONFIG" echo "Available: baseline | baseline_full | v2_quick | v2_full | v2_h100" @@ -330,9 +398,10 @@ case "$CONFIG" in echo "Phase 3: v3_abl | proxy_v3 | v3_h100" echo "Phase 4: proxy_v4 | v4_h100 (EMA+LateQAT fix, threshold=0.9)" echo "Phase 6: v6_parallel (Parallel Muon: DEPRECATED)" - echo "Phase 10: v10_banked | v10_banked_proxy (Model Banking + Parallel Muon, train_gpt_v3.py)" + echo "Phase 10: v10_banked | v10_banked_proxy (Model Banking + Parallel Muon, train_gpt_v3.py)" echo "Phase 7: v7_ve | v7_ve_small (Value Embeddings)" echo "Phase 8: v8_static (VE + DDP static_graph, overhead fix test — no improvement found)" + echo "Phase 11: v11_proxy | v11_int6_xsaall | v11_banked | v11_gptq (11L INT6 + XSA-all + LZMA)" echo "Phase 9: v9_13l_int4attn (13L + INT4 MLP + INT4 Attn + VE, novel depth bet)" exit 1 ;; diff --git a/train_gpt_v2.py b/train_gpt_v2.py index 182da0d77d..3bd52b188c 100644 --- a/train_gpt_v2.py +++ b/train_gpt_v2.py @@ -9,15 +9,18 @@ import subprocess import sys import time +import lzma import uuid import zlib from pathlib import Path try: import zstandard - _COMPRESSOR = "zstd" + _COMPRESSOR_DEFAULT = "zstd" except ImportError: - _COMPRESSOR = "zlib" + _COMPRESSOR_DEFAULT = "zlib" + +_COMPRESSOR = os.environ.get("COMPRESS", _COMPRESSOR_DEFAULT) try: import wandb @@ -387,7 +390,91 @@ def quantize_intN_per_row(t: Tensor, clip_range: int = 31) -> tuple[Tensor, Tens return q, scale -def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15, attn_clip: int = 31): +def gptq_quantize_weight(W: Tensor, H: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + """Full Hessian GPTQ: column-wise quantization with Cholesky error propagation. + W: [out, in] float32 weight. H: [in, in] Hessian X^T X (CPU, float32). + Returns (q int8 [out, in], scale fp16 [out]) — same format as quantize_intN_per_row.""" + W = W.float().clone() + d_in = W.shape[1] + # Pre-compute per-row scale using GPTQ-lite best-percentile (same as existing code) + best_scale, best_err = None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 0.99999, 1.0]: + row_clip = torch.quantile(W.abs(), pct, dim=1) if pct < 1.0 else W.abs().amax(dim=1) + sc = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + sc = sc.clamp_min(torch.finfo(torch.float16).tiny) + recon = (W / sc.float().unsqueeze(1)).round().clamp(-clip_range, clip_range) * sc.float().unsqueeze(1) + err = (W - recon).pow(2).mean().item() + if err < best_err: + best_scale, best_err = sc, err + # Prepare inverse Hessian via Cholesky + H = H.float() + damp = 0.01 * H.diagonal().mean().clamp_min(1e-6) + H = H + damp * torch.eye(d_in, dtype=H.dtype) + try: + Hinv = torch.cholesky_inverse(torch.linalg.cholesky(H)) + except Exception: + return quantize_intN_per_row(W.half(), clip_range) # fallback + # Column-wise quantization with error propagation + scale_f = best_scale.float() # [out] + Q = torch.zeros_like(W) + for j in range(d_in): + w_j = W[:, j] + q_j = (w_j / scale_f).round().clamp(-clip_range, clip_range) + Q[:, j] = q_j * scale_f + err_j = w_j - Q[:, j] + if j + 1 < d_in: + W[:, j + 1:] -= (err_j / Hinv[j, j].clamp_min(1e-12)).unsqueeze(1) * Hinv[j, j + 1:].unsqueeze(0) + q_int8 = (Q / scale_f.unsqueeze(1)).round().clamp(-(clip_range + 1), clip_range).to(torch.int8) + return q_int8, best_scale + + +def collect_gptq_hessians(base_model: "GPT", device: torch.device, vocab_size: int, + num_seqs: int = 64, seq_len: int = 512, seed: int = 314) -> "dict[str, Tensor]": + """Collect GPTQ Hessians (X^T X) for all CastedLinear weights using random calibration data. + Random (not AR) for simplicity/speed. Difference vs AR self-gen: ~0.001 BPB. + Returns dict[weight_param_name -> H tensor (CPU float32)].""" + torch.manual_seed(seed) + hessians: dict[str, Tensor] = {} + counts: dict[str, int] = {} + hooks = [] + + def make_hook(pname: str): + def fn(mod, inp, out): + X = inp[0].detach().float().reshape(-1, inp[0].shape[-1]) # [N, in] + H = X.T @ X + if pname not in hessians: + hessians[pname] = H.cpu() + counts[pname] = X.shape[0] + else: + hessians[pname].add_(H.cpu()) + counts[pname] += X.shape[0] + return fn + + for name, mod in base_model.named_modules(): + if isinstance(mod, CastedLinear) and mod.weight.ndim == 2: + hooks.append(mod.register_forward_hook(make_hook(name + ".weight"))) + + base_model.eval() + batch = 8 + with torch.inference_mode(), torch.amp.autocast("cuda", dtype=torch.bfloat16): + for i in range(0, num_seqs, batch): + bs = min(batch, num_seqs - i) + x = torch.randint(0, vocab_size, (bs, seq_len), device=device) + base_model.forward_logits(x) + + for h in hooks: + h.remove() + base_model.train() + torch.cuda.empty_cache() + + for pname in hessians: + if counts[pname] > 0: + hessians[pname].div_(counts[pname]) + return hessians + + +def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15, attn_clip: int = 31, + hessians: "dict[str, Tensor] | None" = None): result: dict[str, Tensor] = {} meta: dict[str, object] = {} for name, tensor in state_dict.items(): @@ -417,7 +504,12 @@ def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_ clip = mlp_clip # INT4 bigram/trigram when MLP is INT4 else: clip = 31 # INT6 for bigram/trigram in INT5 mode - q, s = quantize_intN_per_row(t, clip_range=clip) + # Use full Hessian GPTQ when hessian available for this weight, else GPTQ-lite + H = hessians.get(name) if (hessians is not None and t.ndim == 2 and cat in ("mlp", "attn")) else None + if H is not None: + q, s = gptq_quantize_weight(t, H, clip_range=clip) + else: + q, s = quantize_intN_per_row(t, clip_range=clip) result[name + ".q"] = q result[name + ".scale"] = s bits = clip.bit_length() + 1 # clip=31→int6, clip=15→int5, clip=7→int4 @@ -1667,13 +1759,33 @@ def lr_mul(step: int, elapsed_ms: float) -> float: int6_cats = {"mlp", "attn", "bigram"} if base_model.trigram is not None: int6_cats.add("trigram") + + # Full Hessian GPTQ: collect activation statistics from random calibration data + _gptq_hessians = None + _gptq_enabled = int(os.environ.get("GPTQ_ENABLED", "0")) + if _gptq_enabled and master_process: + log0("gptq:collecting hessians (random calibration, 64 seqs × 512 tokens, seed=314)") + t_gptq0 = time.perf_counter() + _gptq_hessians = collect_gptq_hessians( + base_model, device, args.vocab_size, + num_seqs=64, seq_len=512, seed=314, + ) + log0(f"gptq:hessians collected ({len(_gptq_hessians)} layers, {time.perf_counter()-t_gptq0:.1f}s)") + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} - quant_result, quant_meta = mixed_quantize_int6(sd_cpu, int6_cats, mlp_clip=mlp_clip, attn_clip=attn_clip) + quant_result, quant_meta = mixed_quantize_int6( + sd_cpu, int6_cats, mlp_clip=mlp_clip, attn_clip=attn_clip, hessians=_gptq_hessians + ) + if _gptq_enabled: + gptq_count = sum(1 for k in _gptq_hessians) if _gptq_hessians else 0 + log0(f"gptq:applied to {gptq_count} weight matrices") quant_buf = io.BytesIO() torch.save({"w": quant_result, "m": quant_meta}, quant_buf) quant_raw = quant_buf.getvalue() if _COMPRESSOR == "zstd": quant_blob = zstandard.ZstdCompressor(level=22).compress(quant_raw) + elif _COMPRESSOR == "lzma": + quant_blob = lzma.compress(quant_raw, preset=9) else: quant_blob = zlib.compress(quant_raw, 9) if master_process: @@ -1692,6 +1804,8 @@ def lr_mul(step: int, elapsed_ms: float) -> float: quant_blob_disk = f.read() if _COMPRESSOR == "zstd": decompressed = zstandard.ZstdDecompressor().decompress(quant_blob_disk) + elif _COMPRESSOR == "lzma": + decompressed = lzma.decompress(quant_blob_disk) else: decompressed = zlib.decompress(quant_blob_disk) quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") diff --git a/train_gpt_v3.py b/train_gpt_v3.py index 589ee84e75..698c0b6d25 100644 --- a/train_gpt_v3.py +++ b/train_gpt_v3.py @@ -731,9 +731,11 @@ def forward(self, x: Tensor, q_w: Tensor, k_w: Tensor, v_w: Tensor, out_w: Tenso q, k, v, attn_mask=None, is_causal=True, enable_gqa=(self.num_kv_heads != self.num_heads), ) - y = y.transpose(1, 2).contiguous() + # Permute BHSD→BTHD in one op; if XSA is needed use contiguous for in-place ops if self.use_xsa: - y = self._xsa_efficient(y, v_bthd) + y = self._xsa_efficient(y.permute(0, 2, 1, 3).contiguous(), v_bthd) + else: + y = y.permute(0, 2, 1, 3) y = y.reshape(bsz, seqlen, dim) return F.linear(y, out_w.to(x.dtype)) @@ -1693,10 +1695,14 @@ def lr_mul(step: int, elapsed_ms: float) -> float: warmup_loss = model(x, y) (warmup_loss * grad_scale).backward() # Without DDP: manually all-reduce all grads for warmup (simple, only 20 steps) + # Launch async to let NCCL pipeline multiple small ops. if distributed: + _wup_handles = [] for p in base_model.parameters(): if p.grad is not None: - dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + _wup_handles.append(dist.all_reduce(p.grad, op=dist.ReduceOp.AVG, async_op=True)) + for _h in _wup_handles: + _h.wait() for opt in optimizers: opt.step() zero_grad_all() @@ -1786,13 +1792,21 @@ def lr_mul(step: int, elapsed_ms: float) -> float: # Phase 1: Launch async reduce-scatter for banks (biggest first) optimizer_muon.launch_reduce_scatters() # Phase 2: All-reduce non-bank grads + step Adam (while bank RS is in-flight) + # Launch ALL all-reduces async simultaneously so NCCL can pipeline them. if distributed: + _ar_handles = [] for p in replicated_params: if p.grad is not None: - dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) - for opt in optimizers: - if opt is not optimizer_muon: - opt.step() + _ar_handles.append(dist.all_reduce(p.grad, op=dist.ReduceOp.AVG, async_op=True)) + for opt in optimizers: + if opt is not optimizer_muon: + opt.step() + for _h in _ar_handles: + _h.wait() + else: + for opt in optimizers: + if opt is not optimizer_muon: + opt.step() # Phase 3: Wait for RS, local NS5, all-gather (banks processed last) optimizer_muon.step() zero_grad_all() From aae1ad26ae3c53d2f107d5d13fd001fb25f5ef41 Mon Sep 17 00:00:00 2001 From: Harsh Soni Date: Wed, 1 Apr 2026 07:09:48 +0000 Subject: [PATCH 7/9] =?UTF-8?q?Add=20MFU=20logging=20to=20training=20step?= =?UTF-8?q?=20output=20(zero=20overhead=20=E2=80=94=20pure=20Python=20math?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- train_gpt_v2.py | 24 ++++++++++++++++++++++-- train_gpt_v3.py | 20 ++++++++++++++++++-- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/train_gpt_v2.py b/train_gpt_v2.py index 3bd52b188c..9388a112d3 100644 --- a/train_gpt_v2.py +++ b/train_gpt_v2.py @@ -1580,6 +1580,22 @@ def lr_mul(step: int, elapsed_ms: float) -> float: zero_grad_all() train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + # Pre-compute model FLOPs for MFU logging (zero runtime overhead — pure Python math). + # Formula: 3× forward FLOPs (fwd + bwd ≈ 3×fwd). Forward FLOPs per token per layer: + # attn projections: 2*D*(D + kv_dim + kv_dim + D) + # attn matrix (QK + AV, GQA-aware): 4 * seq_len * num_heads * head_dim + # MLP (up + down): 4 * D * mlp_dim + _head_dim = args.model_dim // args.num_heads + _kv_dim = args.num_kv_heads * _head_dim + _mlp_dim = int(args.mlp_mult * args.model_dim) + _attn_proj = 2 * args.model_dim * (args.model_dim + _kv_dim + _kv_dim + args.model_dim) + _attn_mat = 4 * args.train_seq_len * args.num_heads * _head_dim + _mlp = 4 * args.model_dim * _mlp_dim + _fwd_flops_per_token = args.num_layers * (_attn_proj + _attn_mat + _mlp) + _flops_per_step = 3 * _fwd_flops_per_token * args.train_batch_tokens # fwd+bwd + _H100_PEAK_FLOPS = 989e12 # H100 SXM BF16 tensor core theoretical peak per GPU + log0(f"mfu_ref: fwd_flops_per_token={_fwd_flops_per_token/1e6:.1f}M flops_per_step={_flops_per_step/1e12:.2f}T") + # MAIN TRAINING LOOP training_time_ms = 0.0 stop_after_step: int | None = None @@ -1687,15 +1703,19 @@ def lr_mul(step: int, elapsed_ms: float) -> float: and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) ) if should_log_train: + _step_ms = approx_training_time_ms / step + _mfu = _flops_per_step / world_size / (_step_ms / 1000.0) / _H100_PEAK_FLOPS log0( f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " - f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{_step_ms:.2f}ms " + f"mfu:{_mfu:.1%}" ) if wandb_enabled: wandb.log({ "train/loss": train_loss.item(), "train/lr_scale": scale, - "train/step_ms": approx_training_time_ms / step, + "train/step_ms": _step_ms, + "train/mfu": _mfu, }, step=step) reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms diff --git a/train_gpt_v3.py b/train_gpt_v3.py index 698c0b6d25..c71539a3cf 100644 --- a/train_gpt_v3.py +++ b/train_gpt_v3.py @@ -1714,6 +1714,18 @@ def lr_mul(step: int, elapsed_ms: float) -> float: zero_grad_all() train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + # Pre-compute model FLOPs for MFU logging (zero runtime overhead — pure Python math). + _head_dim = args.model_dim // args.num_heads + _kv_dim = args.num_kv_heads * _head_dim + _mlp_dim = int(args.mlp_mult * args.model_dim) + _attn_proj = 2 * args.model_dim * (args.model_dim + _kv_dim + _kv_dim + args.model_dim) + _attn_mat = 4 * args.train_seq_len * args.num_heads * _head_dim + _mlp = 4 * args.model_dim * _mlp_dim + _fwd_flops_per_token = args.num_layers * (_attn_proj + _attn_mat + _mlp) + _flops_per_step = 3 * _fwd_flops_per_token * args.train_batch_tokens + _H100_PEAK_FLOPS = 989e12 + log0(f"mfu_ref: fwd_flops_per_token={_fwd_flops_per_token/1e6:.1f}M flops_per_step={_flops_per_step/1e12:.2f}T") + # MAIN TRAINING LOOP training_time_ms = 0.0 stop_after_step: int | None = None @@ -1839,15 +1851,19 @@ def lr_mul(step: int, elapsed_ms: float) -> float: and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) ) if should_log_train: + _step_ms = approx_training_time_ms / step + _mfu = _flops_per_step / world_size / (_step_ms / 1000.0) / _H100_PEAK_FLOPS log0( f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " - f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{_step_ms:.2f}ms " + f"mfu:{_mfu:.1%}" ) if wandb_enabled: wandb.log({ "train/loss": train_loss.item(), "train/lr_scale": scale, - "train/step_ms": approx_training_time_ms / step, + "train/step_ms": _step_ms, + "train/mfu": _mfu, }, step=step) reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms From f12538f0f59aa610ec89c03bc7dd5d57affaad5c Mon Sep 17 00:00:00 2001 From: SoHarshH Date: Wed, 1 Apr 2026 09:37:12 +0000 Subject: [PATCH 8/9] 11L INT6 XSA-all seed1: ttt_bpb=1.1487 (quality record, 19MB unsubmittable) --- .../2026-04-01_11L_INT6_XSA_all/README.md | 46 + .../submission.json | 9 + .../2026-04-01_11L_INT6_XSA_all/train_gpt.py | 1887 +++++++++++++++++ 3 files changed, 1942 insertions(+) create mode 100644 records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/README.md create mode 100644 records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/submission.json create mode 100644 records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/train_gpt.py diff --git a/records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/README.md b/records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/README.md new file mode 100644 index 0000000000..f3faad16ff --- /dev/null +++ b/records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/README.md @@ -0,0 +1,46 @@ +# 11L INT6 XSA-all + EMA + Value Embeddings + +**val_bpb: 1.1487** (quality record, unsubmittable) | **19.03 MB** (over 16MB limit) | 8×H100 SXM + +## Results + +| Seed | step_avg | steps | Post-quant bpb | Post-TTT bpb | Artifact | +|------|----------|-------|----------------|--------------|----------| +| 1 | 133ms (pre-QAT) / 163ms (post-QAT) | 3758 | 1.14971 | **1.14870** | 19,030,284 | + +## Architecture + +| Component | Setting | +|-----------|---------| +| Layers | 11 (512d, 8H, 4KV) | +| MLP | 3× with LeakyReLU(0.5)² | +| BigramHash | 3072 buckets × 112 dim | +| XSA | All 11 layers | +| RoPE | Partial (16/64 dims) | +| LN Scale | 1/√(layer+1) | +| Weight avg | EMA(0.997) with QAT-activation reset | +| Quantization | INT6 MLP + INT6 attn + INT6 bigram + LZMA preset=9 | +| QAT trigger | Wallclock fraction (65% of budget) | +| Value Embeddings | ve_dim=128, last 2 layers | +| TTT | Legal score-first, lr=0.002, 3 epochs | + +## Why Unsubmittable + +INT6 for all weight categories (MLP+attn+bigram) stores values in the range −32..+31 (64 distinct values), vs INT4's 16 distinct values. LZMA compression is proportionally weaker: ~5.5× ratio vs ~6.5× for INT4. Result: 19MB vs the 16MB budget. + +Fix: GPTQ (Run 2) forces quantized weights toward smaller values → more clustering → better LZMA compression. Expected to bring artifact below 16MB. + +## Comparison + +| Run | ms/step | Steps | ttt_bpb | Size | +|-----|---------|-------|---------|------| +| v10_banked seed 1 | 138ms | 4358 | 1.15711 | 16.47MB | +| **v11_int6_xsaall seed 1** | **133ms** | **3758** | **1.14870** | **19.03MB ❌** | + +## QAT Overhead Note + +QAT enabled at step ~2900 (65% of wallclock). After enabling INT6 QAT on all 3 categories simultaneously, step time jumped from 133ms → 163ms (MFU 22% → 18%). This cost ~900 steps vs expectation. Future runs: QAT on attn+bigram only (MLP clip is less expensive) or accept the overhead. + +## Training File + +`train_gpt_v2.py` diff --git a/records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/submission.json b/records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/submission.json new file mode 100644 index 0000000000..fcd46d4608 --- /dev/null +++ b/records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/submission.json @@ -0,0 +1,9 @@ +{ + "name": "11L INT6 XSA-all + EMA + VE — ttt_bpb 1.1487 (unsubmittable: 19MB)", + "val_bpb": 1.1487, + "bytes_total": 19030284, + "blurb": "11-layer INT6 QAT (mlp+attn+bigram) with XSA on all 11 layers, EMA(0.997), Value Embeddings (ve_dim=128, last 2 layers), Partial RoPE (16/64 dims), LN Scale 1/sqrt(layer+1), LZMA preset=9. ttt_bpb=1.1487, new quality best. Artifact is 19.03MB — over 16MB budget due to INT6 entropy being less compressible than INT4 under LZMA. GPTQ needed to compress below 16MB.", + "author": "Harsh Soni", + "github_id": "SoHarshH", + "date": "2026-04-01" +} diff --git a/records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/train_gpt.py b/records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/train_gpt.py new file mode 100644 index 0000000000..9388a112d3 --- /dev/null +++ b/records/track_10min_16mb/2026-04-01_11L_INT6_XSA_all/train_gpt.py @@ -0,0 +1,1887 @@ +from __future__ import annotations + +import copy +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import lzma +import uuid +import zlib +from pathlib import Path + +try: + import zstandard + _COMPRESSOR_DEFAULT = "zstd" +except ImportError: + _COMPRESSOR_DEFAULT = "zlib" + +_COMPRESSOR = os.environ.get("COMPRESS", _COMPRESSOR_DEFAULT) + +try: + import wandb + _WANDB_AVAILABLE = True +except ImportError: + _WANDB_AVAILABLE = False + +import numpy as np +import sentencepiece as spm +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import Tensor, nn +from torch.nn.parallel import DistributedDataParallel as DDP + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- + +class Hyperparameters: + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024") + train_files = os.path.join(data_path, "fineweb_train_*.bin") + val_files = os.path.join(data_path, "fineweb_val_*.bin") + tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 42)) + + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 500)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 100)) + + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3000)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 786_432)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2048)) + max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + + vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) + num_layers = int(os.environ.get("NUM_LAYERS", 10)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 4)) + model_dim = int(os.environ.get("MODEL_DIM", 512)) + num_heads = int(os.environ.get("NUM_HEADS", 8)) + mlp_mult = float(os.environ.get("MLP_MULT", 3.0)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.008)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.03)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.02)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.02)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.3)) + weight_decay = float(os.environ.get("WEIGHT_DECAY", 0.04)) + + eval_stride = int(os.environ.get("EVAL_STRIDE", 64)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 32)) + + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + trigram_vocab_size = int(os.environ.get("TRIGRAM_VOCAB_SIZE", 0)) # 0 = disabled + trigram_dim = int(os.environ.get("TRIGRAM_DIM", 64)) + + swa_enabled = bool(int(os.environ.get("SWA_ENABLED", "1"))) + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.4)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + + # EMA: exponential moving average of weights (replaces SWA when enabled) + ema_enabled = bool(int(os.environ.get("EMA_ENABLED", "0"))) + ema_decay = float(os.environ.get("EMA_DECAY", "0.997")) + + # QAT: fake-quantize weights during training to match PTQ targets + # MLP precision: INT4 (clip=7) or INT5 (clip=15, default); ATTN default INT6 (clip=31) + qat_enabled = bool(int(os.environ.get("QAT_ENABLED", "1"))) + mlp_quant_bits = int(os.environ.get("MLP_QUANT_BITS", "5")) # 4 or 5 + attn_quant_bits = int(os.environ.get("ATTN_QAT_BITS", "6")) # 6=INT6(default), 4=INT4 + + # XSA: Cross-Sequence Attention on last N layers (subtracts self-value projection) + xsa_last_n = int(os.environ.get("XSA_LAST_N", 0)) + + # Partial RoPE: apply RoPE to only first rope_dims dims of head_dim (0 = full) + rope_dims = int(os.environ.get("ROPE_DIMS", 0)) + + # LN Scale: scale norm input by 1/sqrt(layer_idx+1) for depth stability + ln_scale = bool(int(os.environ.get("LN_SCALE", "0"))) + + # Late QAT: delay fake-quantize until LR scale drops below threshold (0 = from start) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", "0")) + + # ValueEmbedding: reinject token identity into V at last N layers (0 = disabled) + value_embed_layers = int(os.environ.get("VALUE_EMBED_LAYERS", "0")) + value_embed_dim = int(os.environ.get("VALUE_EMBED_DIM", "64")) + + # TTT: Legal score-first test-time training at final eval + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "0"))) + ttt_lr = float(os.environ.get("TTT_LR", "0.002")) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", "3")) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", "32768")) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", "0")) + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", "0.9")) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", "32")) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", "1.0")) + +# ----------------------------- +# MUON OPTIMIZER — Parallel Muon (async reduce-scatter → sharded NS5 → all-gather) +# ----------------------------- + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 5, eps: float = 1e-7) -> Tensor: + """Batched Newton-Schulz orthogonalization. Accepts (B,M,N) or (M,N).""" + a, b, c = (3.4445, -4.7750, 2.0315) + was_2d = G.ndim == 2 + if was_2d: + G = G.unsqueeze(0) + X = G.bfloat16() + transposed = X.size(-2) > X.size(-1) + if transposed: + X = X.mT + X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps) + for _ in range(steps): + A = X @ X.mT + B = b * A + c * (A @ A) + X = a * X + B @ X + if transposed: + X = X.mT + if was_2d: + X = X.squeeze(0) + return X + + +class Muon(torch.optim.Optimizer): + """Muon — MomentUm Orthogonalized by Newton-schulz. + + Works with DDP: DDP handles gradient averaging during backward. + NS5 runs sequentially on the already-averaged gradients. + launch_reduce_scatters() is a no-op stub (DDP handles sync). + + Falls back identically on single-GPU proxy runs. + """ + def __init__(self, params, lr: float, momentum: float, backend_steps: int, + nesterov: bool = True, weight_decay: float = 0.0): + super().__init__( + params, + dict(lr=lr, momentum=momentum, backend_steps=backend_steps, + nesterov=nesterov, weight_decay=weight_decay), + ) + + def launch_reduce_scatters(self) -> None: + pass # No-op: DDP handles gradient sync during backward + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + for group in self.param_groups: + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + wd = group.get("weight_decay", 0.0) + for p in group["params"]: + if p.grad is None: + continue + g = p.grad.bfloat16() + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(g) + update = g.add(buf, alpha=momentum) if nesterov else buf.clone() + update = zeropower_via_newtonschulz5(update, steps=backend_steps) + if wd > 0.0: + p.data.mul_(1.0 - lr * wd) + scale = max(1, p.shape[-2] / p.shape[-1]) ** 0.5 + p.add_(update.to(dtype=p.dtype), alpha=-lr * scale) + return loss + + +def _apply_vbank_update(vb: dict, lr: float, wd: float) -> None: + pass # unused stub kept for import compatibility + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION +# ----------------------------- + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("\u2581"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return ( + torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device), + ) + + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError( + "VAL_BATCH_SIZE must provide at least one sequence per rank; " + f"got VAL_BATCH_SIZE={args.val_batch_size}, WORLD_SIZE={world_size}, " + f"GRAD_ACCUM_STEPS={grad_accum_steps}, TRAIN_SEQ_LEN={args.train_seq_len}" + ) + local_batch_seqs = local_batch_tokens // args.train_seq_len + total_seqs = (val_tokens.numel() - 1) // args.train_seq_len + seq_start = (total_seqs * rank) // world_size + seq_end = (total_seqs * (rank + 1)) // world_size + val_loss_sum = torch.zeros((), device=device, dtype=torch.float64) + val_token_count = torch.zeros((), device=device, dtype=torch.float64) + val_byte_count = torch.zeros((), device=device, dtype=torch.float64) + model.eval() + with torch.inference_mode(): + for batch_seq_start in range(seq_start, seq_end, local_batch_seqs): + batch_seq_end = min(batch_seq_start + local_batch_seqs, seq_end) + raw_start = batch_seq_start * args.train_seq_len + raw_end = batch_seq_end * args.train_seq_len + 1 + local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True) + x = local[:-1].reshape(-1, args.train_seq_len) + y = local[1:].reshape(-1, args.train_seq_len) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + batch_loss = model(x, y).detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +# ----------------------------- +# QUANTIZATION (INT5 MLP / INT6 ATTN mixed PTQ) +# ----------------------------- + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights,smear,bigram.scale,trigram.scale,ve_layer_scales,ve_shared.scale", + ).split(",") + if pattern +) +FP16_KEEP_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get("FP16_KEEP_NAME_PATTERNS", "tok_emb,blocks.8.attn.c_k").split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 + +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + INT8_CLIP_Q = 99.99984 / 100.0 + t32 = t.float() + if t32.ndim == 2: + clip_abs = ( + torch.quantile(t32.abs(), INT8_CLIP_Q, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + clipped = torch.maximum(torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None]) + scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) + q = torch.clamp(torch.round(clipped / scale[:, None]), -127, 127).to(torch.int8).contiguous() + return q, scale.to(dtype=torch.float16).contiguous() + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127).to(torch.int8).contiguous() + return q, scale + + +def _classify_param(name: str) -> str: + if "tok_emb" in name or "lm_head" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if "bigram" in name: + return "bigram" + if "trigram" in name: + return "trigram" + if ".attn." in name or (".proj." in name and ".mlp." not in name): + return "attn" + return "other" + + +def quantize_intN_per_row(t: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + """Quantize with GPTQ-lite: search 5 clip percentiles, pick best MSE.""" + t32 = t.float() + if t32.ndim == 2: + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 0.99999, 1.0]: + if pct < 1.0: + row_clip = torch.quantile(t32.abs(), pct, dim=1) + else: + row_clip = t32.abs().amax(dim=1) + scale = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + scale = scale.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(t32 / scale.float()[:, None]), -(clip_range + 1), clip_range).to(torch.int8) + err = (t32 - q.float() * scale.float()[:, None]).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, scale, err + return best_q, best_s + amax = t32.abs().max().item() + scale = torch.tensor(max(amax / clip_range, 1e-12), dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -(clip_range + 1), clip_range).to(torch.int8) + return q, scale + + +def gptq_quantize_weight(W: Tensor, H: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + """Full Hessian GPTQ: column-wise quantization with Cholesky error propagation. + W: [out, in] float32 weight. H: [in, in] Hessian X^T X (CPU, float32). + Returns (q int8 [out, in], scale fp16 [out]) — same format as quantize_intN_per_row.""" + W = W.float().clone() + d_in = W.shape[1] + # Pre-compute per-row scale using GPTQ-lite best-percentile (same as existing code) + best_scale, best_err = None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 0.99999, 1.0]: + row_clip = torch.quantile(W.abs(), pct, dim=1) if pct < 1.0 else W.abs().amax(dim=1) + sc = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + sc = sc.clamp_min(torch.finfo(torch.float16).tiny) + recon = (W / sc.float().unsqueeze(1)).round().clamp(-clip_range, clip_range) * sc.float().unsqueeze(1) + err = (W - recon).pow(2).mean().item() + if err < best_err: + best_scale, best_err = sc, err + # Prepare inverse Hessian via Cholesky + H = H.float() + damp = 0.01 * H.diagonal().mean().clamp_min(1e-6) + H = H + damp * torch.eye(d_in, dtype=H.dtype) + try: + Hinv = torch.cholesky_inverse(torch.linalg.cholesky(H)) + except Exception: + return quantize_intN_per_row(W.half(), clip_range) # fallback + # Column-wise quantization with error propagation + scale_f = best_scale.float() # [out] + Q = torch.zeros_like(W) + for j in range(d_in): + w_j = W[:, j] + q_j = (w_j / scale_f).round().clamp(-clip_range, clip_range) + Q[:, j] = q_j * scale_f + err_j = w_j - Q[:, j] + if j + 1 < d_in: + W[:, j + 1:] -= (err_j / Hinv[j, j].clamp_min(1e-12)).unsqueeze(1) * Hinv[j, j + 1:].unsqueeze(0) + q_int8 = (Q / scale_f.unsqueeze(1)).round().clamp(-(clip_range + 1), clip_range).to(torch.int8) + return q_int8, best_scale + + +def collect_gptq_hessians(base_model: "GPT", device: torch.device, vocab_size: int, + num_seqs: int = 64, seq_len: int = 512, seed: int = 314) -> "dict[str, Tensor]": + """Collect GPTQ Hessians (X^T X) for all CastedLinear weights using random calibration data. + Random (not AR) for simplicity/speed. Difference vs AR self-gen: ~0.001 BPB. + Returns dict[weight_param_name -> H tensor (CPU float32)].""" + torch.manual_seed(seed) + hessians: dict[str, Tensor] = {} + counts: dict[str, int] = {} + hooks = [] + + def make_hook(pname: str): + def fn(mod, inp, out): + X = inp[0].detach().float().reshape(-1, inp[0].shape[-1]) # [N, in] + H = X.T @ X + if pname not in hessians: + hessians[pname] = H.cpu() + counts[pname] = X.shape[0] + else: + hessians[pname].add_(H.cpu()) + counts[pname] += X.shape[0] + return fn + + for name, mod in base_model.named_modules(): + if isinstance(mod, CastedLinear) and mod.weight.ndim == 2: + hooks.append(mod.register_forward_hook(make_hook(name + ".weight"))) + + base_model.eval() + batch = 8 + with torch.inference_mode(), torch.amp.autocast("cuda", dtype=torch.bfloat16): + for i in range(0, num_seqs, batch): + bs = min(batch, num_seqs - i) + x = torch.randint(0, vocab_size, (bs, seq_len), device=device) + base_model.forward_logits(x) + + for h in hooks: + h.remove() + base_model.train() + torch.cuda.empty_cache() + + for pname in hessians: + if counts[pname] > 0: + hessians[pname].div_(counts[pname]) + return hessians + + +def mixed_quantize_int6(state_dict: dict[str, Tensor], int6_cats: set[str], mlp_clip: int = 15, attn_clip: int = 31, + hessians: "dict[str, Tensor] | None" = None): + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param(name) + if not t.is_floating_point() or t.numel() <= 8192: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + if any(pattern in name for pattern in FP16_KEEP_NAME_PATTERNS): + result[name] = t.to(dtype=torch.float16).contiguous() + meta[name] = "passthrough_fp16" + continue + if cat in int6_cats and t.ndim >= 1: + # MLP: always uses mlp_clip (INT4 or INT5) + # attn: uses attn_clip (INT6 default, INT4 when ATTN_QAT_BITS=4) + # bigram/trigram: follow mlp_clip when INT4 (saves ~0.25MB), else INT6 + if cat == "mlp": + clip = mlp_clip + elif cat == "attn": + clip = attn_clip + elif cat in ("bigram", "trigram") and mlp_clip <= 7: + clip = mlp_clip # INT4 bigram/trigram when MLP is INT4 + else: + clip = 31 # INT6 for bigram/trigram in INT5 mode + # Use full Hessian GPTQ when hessian available for this weight, else GPTQ-lite + H = hessians.get(name) if (hessians is not None and t.ndim == 2 and cat in ("mlp", "attn")) else None + if H is not None: + q, s = gptq_quantize_weight(t, H, clip_range=clip) + else: + q, s = quantize_intN_per_row(t, clip_range=clip) + result[name + ".q"] = q + result[name + ".scale"] = s + bits = clip.bit_length() + 1 # clip=31→int6, clip=15→int5, clip=7→int4 + meta[name] = {"type": f"int{bits}"} + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return result, meta + + +def dequantize_mixed_int6(result: dict[str, Tensor], meta: dict[str, object], + template_sd: dict[str, Tensor]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + for name, orig in template_sd.items(): + info = meta[name] + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl", "passthrough_fp16"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + + +# ----------------------------- +# DATA LOADING +# ----------------------------- + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = rank + self.world_size = world_size + self.device = device + self.stream = TokenStream(pattern) + + def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> tuple[Tensor, Tensor]: + local_tokens = global_tokens // (self.world_size * grad_accum_steps) + per_rank_span = local_tokens + 1 + chunk = self.stream.take(per_rank_span * self.world_size) + start = self.rank * per_rank_span + local = chunk[start : start + per_rank_span].to(dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + return x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) + + +# ----------------------------- +# TRANSFORMER MODULES +# ----------------------------- + +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + + +class CastedLinear(nn.Linear): + # _qat_clip_range: 127=off/INT8, 31=INT6, 15=INT5 + _qat_clip_range: int = 127 + + def forward(self, x: Tensor) -> Tensor: + w = self.weight + if self.training and self._qat_clip_range < 127 and w.ndim == 2: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w.to(x.dtype), bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int = 0): + super().__init__() + self.rope_dims = rope_dims if rope_dims > 0 else dim + rd = self.rope_dims + inv_freq = 1.0 / (base ** (torch.arange(0, rd, 2, dtype=torch.float32) / rd)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + rd = cos.size(-1) * 2 + if rd < x.size(-1): # partial RoPE: rotate first rd dims, pass rest unchanged + x_rope, x_pass = x[..., :rd], x[..., rd:] + half = rd // 2 + x1, x2 = x_rope[..., :half], x_rope[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + + +class CausalSelfAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, rope_base: float, qk_gain_init: float, rope_dims: int = 0): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base, rope_dims=rope_dims) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + """XSA: subtract self-value projection, forcing heads to attend to OTHER tokens.""" + B, T, H, D = y.shape + Hkv = v.size(2) # v is [B, T, Hkv, D] + group = H // Hkv + y_g = y.reshape(B, T, Hkv, group, D) + vn = F.normalize(v, dim=-1).unsqueeze(3) # [B, T, Hkv, 1, D] + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v_raw = self.c_v(x) + if v_embed is not None: + v_raw = v_raw + v_embed + v_bthd = v_raw.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + v = v_bthd.transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention( + q, k, v, attn_mask=None, is_causal=True, + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + y = y.transpose(1, 2).contiguous() # [B, T, H, D] + if self.use_xsa: + y = self._xsa_efficient(y, v_bthd) + y = y.reshape(bsz, seqlen, dim) + return self.proj(y) + + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: float): + super().__init__() + hidden = int(mlp_mult * dim) + self.fc = CastedLinear(dim, hidden, bias=False) + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + + def forward(self, x: Tensor) -> Tensor: + x = F.leaky_relu(self.fc(x), negative_slope=0.5) + return self.proj(x.square()) + + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate.to(dtype=x.dtype))[None, None, :] + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1 - g) * x + g * x_prev + + +class BigramHashEmbedding(nn.Module): + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, bigram_vocab_size: int, bigram_dim: int, model_dim: int): + super().__init__() + self.bigram_vocab_size = bigram_vocab_size + self.embed = nn.Embedding(bigram_vocab_size, bigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(bigram_dim, model_dim, bias=False) if bigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.05, dtype=torch.float32)) + + def bigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.bigram_vocab_size - 1 + out = torch.empty_like(t) + out[..., 0] = mod + out[..., 1:] = torch.bitwise_xor(36313 * t[..., 1:], 27191 * t[..., :-1]) % mod + return out.long() + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.bigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class TrigramHashEmbedding(nn.Module): + """3-gram context embedding: (prev2, prev1, curr) → hashed bucket → learned embedding.""" + # _qat_clip_range: 127=off, 31=INT6, 15=INT5, 7=INT4 — mirrors CastedLinear convention + _qat_clip_range: int = 127 + + def __init__(self, trigram_vocab_size: int, trigram_dim: int, model_dim: int): + super().__init__() + self.trigram_vocab_size = trigram_vocab_size + self.embed = nn.Embedding(trigram_vocab_size, trigram_dim) + nn.init.zeros_(self.embed.weight) + self.proj = CastedLinear(trigram_dim, model_dim, bias=False) if trigram_dim != model_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.02, dtype=torch.float32)) + + def trigram_hash(self, tokens: Tensor) -> Tensor: + t = tokens.to(torch.int32) + mod = self.trigram_vocab_size - 1 + out = torch.full_like(t, mod, dtype=torch.long) # sentinel for positions without full context + out[..., 2:] = ( + torch.bitwise_xor( + torch.bitwise_xor(17291 * t[..., 2:], 36313 * t[..., 1:-1]), + 27191 * t[..., :-2], + ) % mod + ) + return out + + def forward(self, token_ids: Tensor) -> Tensor: + w = self.embed.weight + if self.training and self._qat_clip_range < 127: + w_f = w.float() + clip = float(self._qat_clip_range) + amax = w_f.abs().amax(dim=-1, keepdim=True).clamp_min(1e-12) + scale = amax / clip + q = (w_f / scale).round().clamp(-(clip + 1), clip) + w_q = q * scale + w = w + (w_q - w_f).detach() # STE: straight-through estimator + h = F.embedding(self.trigram_hash(token_ids), w.to(self.embed.weight.dtype)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class ValueEmbedding(nn.Module): + """Reinject token identity into attention values at specific layers. + Shared embedding table + per-layer learned scale. Applied at last N layers.""" + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int): + super().__init__() + self.embed = nn.Embedding(vocab_size, ve_dim) + nn.init.normal_(self.embed.weight, std=0.01) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) if ve_dim != kv_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.1, dtype=torch.float32)) + + def forward(self, token_ids: Tensor) -> Tensor: + h = self.embed(token_ids) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class Block(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, mlp_mult: float, rope_base: float, qk_gain_init: float, rope_dims: int = 0, ln_scale: bool = False, layer_idx: int = 0): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, rope_dims=rope_dims) + self.mlp = MLP(dim, mlp_mult) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + + def forward(self, x: Tensor, x0: Tensor, v_embed: "Tensor | None" = None) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + s = self.ln_scale_factor + attn_out = self.attn(self.attn_norm(x) * s, v_embed=v_embed) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * s) + return x + + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_layers: int, + model_dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: float, + tie_embeddings: bool, + tied_embed_init_std: float, + logit_softcap: float, + rope_base: float, + qk_gain_init: float, + bigram_vocab_size: int = 0, + bigram_dim: int = 128, + trigram_vocab_size: int = 0, + trigram_dim: int = 64, + rope_dims: int = 0, + ln_scale: bool = False, + xsa_last_n: int = 0, + value_embed_layers: int = 0, + value_embed_dim: int = 64, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.bigram = BigramHashEmbedding(bigram_vocab_size, bigram_dim, model_dim) if bigram_vocab_size > 0 else None + self.trigram = TrigramHashEmbedding(trigram_vocab_size, trigram_dim, model_dim) if trigram_vocab_size > 0 else None + self.num_encoder_layers = num_layers // 2 + self.num_decoder_layers = num_layers - self.num_encoder_layers + self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers) + self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32)) + self.smear = SmearGate(model_dim) + self.blocks = nn.ModuleList( + [ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init, + rope_dims=rope_dims, ln_scale=ln_scale, layer_idx=i) + for i in range(num_layers) + ] + ) + if xsa_last_n > 0: + for i in range(max(0, num_layers - xsa_last_n), num_layers): + self.blocks[i].attn.use_xsa = True + # ValueEmbedding: shared table + per-layer scales for last N layers + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve_layer_indices = list(range(max(0, num_layers - value_embed_layers), num_layers)) if value_embed_layers > 0 else [] + if self.ve_layer_indices: + self.ve_shared = ValueEmbedding(vocab_size, value_embed_dim, kv_dim) + self.ve_layer_scales = nn.ParameterList( + [nn.Parameter(torch.ones(1, dtype=torch.float32)) for _ in self.ve_layer_indices] + ) + else: + self.ve_shared = None + self.ve_layer_scales = nn.ParameterList() + self.final_norm = RMSNorm() + self.lm_head = None if tie_embeddings else CastedLinear(model_dim, vocab_size, bias=False) + if self.lm_head is not None: + self.lm_head._zero_init = True + self._init_weights() + + def _init_weights(self) -> None: + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) + num_layers = len(self.blocks) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and module.weight.shape[0] >= 64 and module.weight.shape[1] >= 64: + nn.init.orthogonal_(module.weight, gain=1.0) + if ".proj." in name or name.endswith(".proj"): + with torch.no_grad(): + module.weight.mul_(1.0 / math.sqrt(2 * num_layers)) + + def _get_ve(self, layer_idx: int, ve_base: "Tensor | None") -> "Tensor | None": + if ve_base is None or layer_idx not in self.ve_layer_indices: + return None + idx = self.ve_layer_indices.index(layer_idx) + return ve_base * self.ve_layer_scales[idx].to(dtype=ve_base.dtype) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x = self.blocks[self.num_encoder_layers + i](x, x0, v_embed=self._get_ve(self.num_encoder_layers + i, ve_base)) + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + if self.trigram is not None: + x = x + self.trigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + ve_base = self.ve_shared(input_ids) if self.ve_shared is not None else None + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, ve_base)) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x = self.blocks[self.num_encoder_layers + i](x, x0, v_embed=self._get_ve(self.num_encoder_layers + i, ve_base)) + x = self.final_norm(x) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + logits_proj = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + + +def eval_val_sliding( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, + stride: int, + batch_seqs: int = 32, +) -> tuple[float, float]: + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + total_windows = len(window_starts) + my_s = (total_windows * rank) // world_size + my_e = (total_windows * (rank + 1)) // world_size + my_windows = window_starts[my_s:my_e] + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk[:-1] + y_batch[i, :wlen] = chunk[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt = y_batch[i, s:wlen] + prev = x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + running_bpb = 0.0 + if token_count.item() > 0: + rl = (loss_sum / token_count).item() + running_bpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) + print(f" sliding_eval [{pct:5.1f}%] {done}/{len(my_windows)} windows running_bpb={running_bpb:.6f}", flush=True) + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + bits_per_token = val_loss / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + base_model.train() + return val_loss, bits_per_token * tokens_per_byte + + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: nn.Module, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + """Legal score-first TTT: score each chunk with sliding windows, then train on it. + Every token is scored BEFORE any update that could use it (PR #461 recipe).""" + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + ttt_chunk = args.ttt_chunk_tokens + + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + + num_chunks = (total_tokens + ttt_chunk - 1) // ttt_chunk + chunk_windows: list[list[int]] = [[] for _ in range(num_chunks)] + for ws in window_starts: + end = min(ws + seq_len, total_tokens) + wlen = end - ws + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_start = ws + s + ci = min(scored_start // ttt_chunk, num_chunks - 1) + chunk_windows[ci].append(ws) + + log0(f"ttt_sliding:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"total_windows={len(window_starts)} stride={stride} " + f"ttt_lr={args.ttt_lr} ttt_epochs={args.ttt_epochs} " + f"freeze_blocks={args.ttt_freeze_blocks}") + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + log0(f"ttt_sliding:params unfrozen={sum(p.numel() for p in ttt_params)} " + f"frozen={sum(p.numel() for p in base_model.parameters() if not p.requires_grad)}") + + optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) + t0 = time.perf_counter() + + for ci in range(num_chunks): + windows = chunk_windows[ci] + if not windows: + continue + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + my_s = (len(windows) * rank) // world_size + my_e = (len(windows) * (rank + 1)) // world_size + my_windows = windows[my_s:my_e] + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk_tok = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk_tok[:-1] + y_batch[i, :wlen] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt, prev = y_batch[i, s:wlen], x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + my_seq_s = (chunk_seqs * rank) // world_size + my_seq_e = (chunk_seqs * (rank + 1)) // world_size + my_chunk_seqs = my_seq_e - my_seq_s + for _ep in range(args.ttt_epochs): + for bs in range(0, my_chunk_seqs, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_chunk_seqs) + actual_bs = my_seq_s + bs + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + (my_seq_s + be) * seq_len + 1 + if end_tok > val_tokens.numel(): + continue + local = val_tokens[start_tok:end_tok].to(device=device, dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + optimizer.zero_grad(set_to_none=True) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + loss = base_model(x, y) + loss.backward() + if world_size > 1: + for p in ttt_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) if token_count.item() > 0 else 0.0 + log0(f" ttt_chunk [{ci+1}/{num_chunks}] bpb={rbpb:.6f} time={elapsed:.1f}s") + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + val_bpb = val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.eval() + + log0(f"ttt_sliding:done val_loss={val_loss:.6f} val_bpb={val_bpb:.6f} " + f"elapsed={time.perf_counter() - t0:.1f}s") + return val_loss, val_bpb + + +# ----------------------------- +# TRAINING +# ----------------------------- + +def main() -> None: + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + # Parallel Muon uses batched bmm — do NOT torch.compile NS5 (bmm is already efficient) + + distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size <= 0: + raise ValueError(f"WORLD_SIZE must be positive, got {world_size}") + if 8 % world_size != 0: + raise ValueError(f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral") + grad_accum_steps = 8 // world_size + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + + logfile = None + wandb_enabled = False + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + if _WANDB_AVAILABLE and bool(int(os.environ.get("WANDB_ENABLED", "1"))): + wandb.init( + project=os.environ.get("WANDB_PROJECT", "parameter-golf"), + name=args.run_id, + config={ + "num_layers": args.num_layers, + "model_dim": args.model_dim, + "mlp_mult": args.mlp_mult, + "num_heads": args.num_heads, + "num_kv_heads": args.num_kv_heads, + "mlp_quant_bits": args.mlp_quant_bits, + "iterations": args.iterations, + "train_batch_tokens": args.train_batch_tokens, + "train_seq_len": args.train_seq_len, + "xsa_last_n": args.xsa_last_n, + "ema_enabled": args.ema_enabled, + "rope_dims": args.rope_dims, + "ln_scale": args.ln_scale, + "late_qat_threshold": args.late_qat_threshold, + "ttt_enabled": args.ttt_enabled, + "bigram_vocab_size": args.bigram_vocab_size, + "value_embed_layers": args.value_embed_layers, + "value_embed_dim": args.value_embed_dim, + "seed": args.seed, + }, + resume="allow", + ) + wandb_enabled = True + + def log0(msg: str, console: bool = True) -> None: + if not master_process: + return + if console: + print(msg) + if logfile is not None: + with open(logfile, "a", encoding="utf-8") as f: + print(msg, file=f) + + log0(code, console=False) + log0("=" * 100, console=False) + log0(f"Running Python {sys.version}", console=False) + log0(f"Running PyTorch {torch.__version__}", console=False) + log0( + subprocess.run(["nvidia-smi"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout, + console=False, + ) + log0("=" * 100, console=False) + + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + + if not args.tokenizer_path.endswith(".model"): + raise ValueError(f"Script only setup for SentencePiece .model file: {args.tokenizer_path}") + sp = spm.SentencePieceProcessor(model_file=args.tokenizer_path) + if int(sp.vocab_size()) != args.vocab_size: + raise ValueError( + f"VOCAB_SIZE={args.vocab_size} does not match tokenizer vocab_size={int(sp.vocab_size())}" + ) + dataset_dir = Path(args.data_path).resolve() + actual_train_files = len(list(dataset_dir.glob("fineweb_train_*.bin"))) + val_tokens = load_validation_tokens(args.val_files, args.train_seq_len) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = build_sentencepiece_luts( + sp, args.vocab_size, device + ) + log0(f"val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path={args.tokenizer_path}") + log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}") + log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}") + + # MODEL SETUP + base_model = GPT( + vocab_size=args.vocab_size, + num_layers=args.num_layers, + model_dim=args.model_dim, + num_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + mlp_mult=args.mlp_mult, + tie_embeddings=args.tie_embeddings, + tied_embed_init_std=args.tied_embed_init_std, + logit_softcap=args.logit_softcap, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + bigram_vocab_size=args.bigram_vocab_size, + bigram_dim=args.bigram_dim, + trigram_vocab_size=args.trigram_vocab_size, + trigram_dim=args.trigram_dim, + rope_dims=args.rope_dims, + ln_scale=args.ln_scale, + xsa_last_n=args.xsa_last_n, + value_embed_layers=args.value_embed_layers, + value_embed_dim=args.value_embed_dim, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + + # QAT: set per-layer fake-quantization targets + # MLP precision controlled by MLP_QUANT_BITS (4=INT4 clip=7, 5=INT5 clip=15) + mlp_clip = (1 << (args.mlp_quant_bits - 1)) - 1 # 5→15, 4→7 + attn_clip = (1 << (args.attn_quant_bits - 1)) - 1 # 6→31, 4→7 + ngram_clip = mlp_clip if args.mlp_quant_bits <= 4 else 31 # INT4 bigram/trigram when MLP is INT4 + _qat_active = False # tracks whether fake-quant has been activated + + def _enable_qat() -> None: + nonlocal _qat_active, ema_state + if _qat_active: + return + _qat_active = True + # Reset EMA so it only accumulates QAT-adapted weights (prevents pre-QAT contamination) + if args.ema_enabled and ema_state is not None: + ema_state = None + log0("qat:ema_reset (EMA will restart from current QAT weights)") + for name, module in base_model.named_modules(): + if isinstance(module, CastedLinear): + if ".mlp." in name: + module._qat_clip_range = mlp_clip + elif ".attn." in name: + module._qat_clip_range = attn_clip + elif "bigram" in name or "trigram" in name: + module._qat_clip_range = ngram_clip + else: + module._qat_clip_range = attn_clip + if base_model.bigram is not None: + base_model.bigram._qat_clip_range = ngram_clip + if base_model.trigram is not None: + base_model.trigram._qat_clip_range = ngram_clip + ngram_bits = '4' if ngram_clip <= 7 else '6' + trig_str = f" trigram=INT{ngram_bits}(clip={ngram_clip})" if base_model.trigram is not None else "" + log0(f"qat:enabled mlp=INT{args.mlp_quant_bits}(clip={mlp_clip}) attn=INT{args.attn_quant_bits}(clip={attn_clip}) bigram=INT{ngram_bits}(clip={ngram_clip}){trig_str}") + + if args.qat_enabled: + if args.late_qat_threshold > 0: + log0(f"qat:late_qat threshold={args.late_qat_threshold} (activates when lr_scale < threshold)") + else: + _enable_qat() + else: + log0("qat:disabled") + + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + if distributed: + model: nn.Module = DDP(compiled_model, device_ids=[device.index], static_graph=True) + else: + model = compiled_model + + # OPTIMIZER SETUP + block_named_params = list(base_model.blocks.named_parameters()) + matrix_params = [ + p for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + scalar_params.append(base_model.smear.gate) + if base_model.bigram is not None: + scalar_params.append(base_model.bigram.scale) + if base_model.trigram is not None: + scalar_params.append(base_model.trigram.scale) + + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + tok_params = [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}] + if base_model.bigram is not None: + tok_params.append({"params": [base_model.bigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.bigram.proj is not None: + matrix_params.append(base_model.bigram.proj.weight) + if base_model.trigram is not None: + tok_params.append({"params": [base_model.trigram.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.trigram.proj is not None: + matrix_params.append(base_model.trigram.proj.weight) + if base_model.ve_shared is not None: + tok_params.append({"params": [base_model.ve_shared.embed.weight], "lr": token_lr, "base_lr": token_lr}) + if base_model.ve_shared.proj is not None: + matrix_params.append(base_model.ve_shared.proj.weight) + scalar_params.append(base_model.ve_shared.scale) + for s in base_model.ve_layer_scales: + scalar_params.append(s) + + optimizer_tok = torch.optim.AdamW( + tok_params, + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=0.04, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params}") + if base_model.ve_shared is not None: + log0(f"value_embed:layers={base_model.ve_layer_indices} ve_dim={args.value_embed_dim} kv_dim={base_model.ve_shared.proj.out_features if base_model.ve_shared.proj else args.value_embed_dim}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0(f"sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + # DATA LOADER & WARMUP + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + + max_wallclock_ms = 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0 + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 + + if args.warmup_steps > 0: + initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()} + initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers] + model.train() + for warmup_step in range(args.warmup_steps): + zero_grad_all() + for micro_step in range(grad_accum_steps): + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + warmup_loss = model(x, y) + (warmup_loss * grad_scale).backward() + # Without DDP: manually all-reduce all grads for warmup (simple, only 20 steps) + if distributed: + for p in base_model.parameters(): + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + for opt in optimizers: + opt.step() + zero_grad_all() + if args.warmup_steps <= 20 or (warmup_step + 1) % 10 == 0 or warmup_step + 1 == args.warmup_steps: + log0(f"warmup_step:{warmup_step + 1}/{args.warmup_steps}") + base_model.load_state_dict(initial_model_state, strict=True) + for opt, state in zip(optimizers, initial_optimizer_states, strict=True): + opt.load_state_dict(state) + zero_grad_all() + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + # Pre-compute model FLOPs for MFU logging (zero runtime overhead — pure Python math). + # Formula: 3× forward FLOPs (fwd + bwd ≈ 3×fwd). Forward FLOPs per token per layer: + # attn projections: 2*D*(D + kv_dim + kv_dim + D) + # attn matrix (QK + AV, GQA-aware): 4 * seq_len * num_heads * head_dim + # MLP (up + down): 4 * D * mlp_dim + _head_dim = args.model_dim // args.num_heads + _kv_dim = args.num_kv_heads * _head_dim + _mlp_dim = int(args.mlp_mult * args.model_dim) + _attn_proj = 2 * args.model_dim * (args.model_dim + _kv_dim + _kv_dim + args.model_dim) + _attn_mat = 4 * args.train_seq_len * args.num_heads * _head_dim + _mlp = 4 * args.model_dim * _mlp_dim + _fwd_flops_per_token = args.num_layers * (_attn_proj + _attn_mat + _mlp) + _flops_per_step = 3 * _fwd_flops_per_token * args.train_batch_tokens # fwd+bwd + _H100_PEAK_FLOPS = 989e12 # H100 SXM BF16 tensor core theoretical peak per GPU + log0(f"mfu_ref: fwd_flops_per_token={_fwd_flops_per_token/1e6:.1f}M flops_per_step={_flops_per_step/1e12:.2f}T") + + # MAIN TRAINING LOOP + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + # EMA state: kept on GPU for efficiency, initialized on first step + ema_state: dict[str, Tensor] | None = None + # QAT timing: use wallclock fraction for deterministic triggering (immune to step_ms estimate noise) + # LATE_QAT_FRAC=0.65 fires QAT at 65% of budget (~390s), giving ~1400 QAT steps. + # Falls back to LR-scale method if LATE_QAT_FRAC is unset or 0. + _late_qat_frac = float(os.environ.get("LATE_QAT_FRAC", "0.0")) + _late_qat_trigger_ms = (_late_qat_frac * max_wallclock_ms) if (max_wallclock_ms and _late_qat_frac > 0) else None + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + if wandb_enabled: + wandb.log({"val/loss": val_loss, "val/bpb": val_bpb}, step=step) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_active: + if _late_qat_trigger_ms is not None: + if elapsed_ms >= _late_qat_trigger_ms: + _enable_qat() + elif args.late_qat_threshold > 0 and scale < args.late_qat_threshold: + _enable_qat() + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + + # EMA: update running average of weights (GPU, no extra transfer) + if args.ema_enabled: + if ema_state is None: + ema_state = {name: t.detach().clone() for name, t in base_model.state_dict().items()} + else: + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(args.ema_decay).add_(t.detach(), alpha=1.0 - args.ema_decay) + + # SWA: collect checkpoints during warmdown + if args.swa_enabled and scale < args.swa_start_frac and step % args.swa_every == 0: + if swa_state is None: + swa_state = {name: t.detach().cpu().clone() for name, t in base_model.state_dict().items()} + swa_count = 1 + log0(f"swa:start step:{step}") + else: + for name, t in base_model.state_dict().items(): + swa_state[name] += t.detach().cpu() + swa_count += 1 + + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + _step_ms = approx_training_time_ms / step + _mfu = _flops_per_step / world_size / (_step_ms / 1000.0) / _H100_PEAK_FLOPS + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{_step_ms:.2f}ms " + f"mfu:{_mfu:.1%}" + ) + if wandb_enabled: + wandb.log({ + "train/loss": train_loss.item(), + "train/lr_scale": scale, + "train/step_ms": _step_ms, + "train/mfu": _mfu, + }, step=step) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + # Apply SWA if collected + if args.swa_enabled and swa_state is not None and swa_count > 1: + log0(f"swa:applying averaged {swa_count} checkpoints") + current_state = base_model.state_dict() + avg_state = { + name: (tensor / swa_count).to(dtype=current_state[name].dtype) + for name, tensor in swa_state.items() + } + base_model.load_state_dict(avg_state, strict=True) + + # Apply EMA: use smooth running average as final weights (overrides SWA if both enabled) + if args.ema_enabled and ema_state is not None: + log0(f"ema:applying (decay={args.ema_decay})") + current_state = base_model.state_dict() + ema_cpu = {name: t.cpu().to(dtype=current_state[name].dtype) for name, t in ema_state.items()} + base_model.load_state_dict(ema_cpu, strict=True) + + # SERIALIZATION + QUANTIZATION + if master_process: + torch.save(base_model.state_dict(), f"final_model_{args.run_id}.pt") + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total uncompressed: {model_bytes + code_bytes} bytes") + + # Magnitude pruning: zero smallest 3% of large weight matrices to aid compression + with torch.no_grad(): + for name, param in base_model.named_parameters(): + if param.ndim == 2 and param.numel() > 65536: + threshold = torch.quantile(param.abs().float().flatten(), 0.03) + mask = param.abs() < threshold + param.masked_fill_(mask, 0.0) + + # Dynamically set FP16_KEEP to keep last attention layer's c_k in FP16 (reduces late-layer quant penalty) + # Default "blocks.8.attn.c_k" is correct for 9L; override here for other depths + global FP16_KEEP_NAME_PATTERNS + last_layer_ck = f"blocks.{args.num_layers - 1}.attn.c_k" + FP16_KEEP_NAME_PATTERNS = tuple( + p for p in set(list(FP16_KEEP_NAME_PATTERNS) + [last_layer_ck]) + if p and not p.startswith("blocks.") or p == last_layer_ck + ) + + # INT5/INT4 MLP + INT6/INT4 Attn/Bigram/Trigram mixed quantization + zstd-22 / zlib-9 export + int6_cats = {"mlp", "attn", "bigram"} + if base_model.trigram is not None: + int6_cats.add("trigram") + + # Full Hessian GPTQ: collect activation statistics from random calibration data + _gptq_hessians = None + _gptq_enabled = int(os.environ.get("GPTQ_ENABLED", "0")) + if _gptq_enabled and master_process: + log0("gptq:collecting hessians (random calibration, 64 seqs × 512 tokens, seed=314)") + t_gptq0 = time.perf_counter() + _gptq_hessians = collect_gptq_hessians( + base_model, device, args.vocab_size, + num_seqs=64, seq_len=512, seed=314, + ) + log0(f"gptq:hessians collected ({len(_gptq_hessians)} layers, {time.perf_counter()-t_gptq0:.1f}s)") + + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + quant_result, quant_meta = mixed_quantize_int6( + sd_cpu, int6_cats, mlp_clip=mlp_clip, attn_clip=attn_clip, hessians=_gptq_hessians + ) + if _gptq_enabled: + gptq_count = sum(1 for k in _gptq_hessians) if _gptq_hessians else 0 + log0(f"gptq:applied to {gptq_count} weight matrices") + quant_buf = io.BytesIO() + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + quant_raw = quant_buf.getvalue() + if _COMPRESSOR == "zstd": + quant_blob = zstandard.ZstdCompressor(level=22).compress(quant_raw) + elif _COMPRESSOR == "lzma": + quant_blob = lzma.compress(quant_raw, preset=9) + else: + quant_blob = zlib.compress(quant_raw, 9) + if master_process: + with open(f"final_model_{args.run_id}.int8.ptz", "wb") as f: + f.write(quant_blob) + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int5mlp+int6attn+{_COMPRESSOR}: {quant_file_bytes} bytes") + log0(f"Total submission size: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + if _COMPRESSOR == "zstd": + decompressed = zstandard.ZstdDecompressor().decompress(quant_blob_disk) + elif _COMPRESSOR == "lzma": + decompressed = lzma.decompress(quant_blob_disk) + else: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + deq_state = dequantize_mixed_int6(quant_state["w"], quant_state["m"], sd_cpu) + base_model.load_state_dict(deq_state, strict=True) + + # Final eval on roundtripped weights with sliding window + torch.cuda.synchronize() + t_qeval = time.perf_counter() + if args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window stride:{args.eval_stride} batch_seqs:{args.eval_batch_seqs}") + q_val_loss, q_val_bpb = eval_val_sliding( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, + ) + else: + log0("final_eval_mode:standard") + q_val_loss, q_val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + if wandb_enabled: + wandb.log({ + "final/post_quant_bpb": q_val_bpb, + "final/post_quant_loss": q_val_loss, + "final/artifact_mb": quant_file_bytes / 1e6, + }) + + if args.ttt_enabled: + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, log0=log0, + ) + torch.cuda.synchronize() + log0(f"legal_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms") + log0(f"legal_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + if wandb_enabled: + wandb.log({"final/ttt_bpb": ttt_bpb, "final/ttt_loss": ttt_loss}) + + if wandb_enabled: + wandb.finish() + + if distributed: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() From 3da1210277138786caa79e8258cf10699d6cd019 Mon Sep 17 00:00:00 2001 From: SoHarshH Date: Wed, 1 Apr 2026 09:53:33 +0000 Subject: [PATCH 9/9] Remove PLAN.md from tracking (private planning file) --- .gitignore | 2 +- PLAN.md | 252 ----------------------------------------------------- 2 files changed, 1 insertion(+), 253 deletions(-) delete mode 100644 PLAN.md diff --git a/.gitignore b/.gitignore index 3423c416a7..2870784fc2 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,4 @@ data/manifest.json data/docs_selected.jsonl .mypy_cache/ .venv -logs/ \ No newline at end of file +logs/PLAN.md diff --git a/PLAN.md b/PLAN.md deleted file mode 100644 index 67597b47e8..0000000000 --- a/PLAN.md +++ /dev/null @@ -1,252 +0,0 @@ -# Parameter Golf — Working Plan & Progress Tracker - -## Environment Setup (run at start of every new instance) -```bash -bash /vol/paraG/parameter-golf/setup.sh -export PATH="$HOME/.local/bin:$PATH" -source /vol/paraG/parameter-golf/.venv/bin/activate -cd /vol/paraG/parameter-golf -``` - ---- - -## ⚡ NEXT CLAUDE — START HERE (updated Mar 28 — v3 banking done) - -**Current best:** v7_ve seed 2, ttt_bpb=**1.15738** (PR: submission/12L-INT4-bQAT-VE) -**Model banking rewrite:** COMPLETE — `train_gpt_v3.py` ready, `v10_banked` config in `run.sh` - -### IMMEDIATE: Run v10_banked proxy smoke test (single GPU, 300 steps) -```bash -bash run.sh v10_banked_proxy -# Expected: step_avg ~110ms (no DDP), train loss ~3.1-3.3 at step 300 -# If it crashes → check logs. If slow → investigate. -``` - -### Then run v10_banked on 8×H100: -```bash -SEED=1 bash run.sh v10_banked -# Expected: ~90-100ms/step → ~6000-6700 steps → projected ~1.132-1.139 BPB -# Step avg at step 100 is the key signal: -# ~90ms → on track for 6700 steps -# ~100ms → on track for 6000 steps -# >110ms → Parallel Muon not working, investigate -``` - -### What changed in train_gpt_v3.py vs v2: -1. **Model Banking**: 4 contiguous 3D bank params replace per-layer CastedLinear - - `qo_bank[24,512,512]`, `kv_bank[24,256,512]`, `mlp_up_bank[12,1536,512]`, `mlp_down_bank[12,512,1536]` -2. **Parallel Muon**: async reduce-scatter → sharded NS5 → all-gather (no DDP) -3. **Bank QAT**: `GPT._fq(w, clip)` applies STE to bank slices during QAT -4. **Serialization**: `_unbank_state_dict()` + `_rebank_state_dict()` for quantization roundtrip - -### After run completes: -```bash -mkdir -p records/track_10min_16mb/2026-03-28_12L_banked_parallel_muon/ -cp train_gpt_v3.py records/track_10min_16mb/2026-03-28_12L_banked_parallel_muon/train_gpt.py -# write submission.json + README.md -git add records/track_10min_16mb/2026-03-28_12L_banked_parallel_muon/ train_gpt_v3.py run.sh -git commit -m "12L banked + Parallel Muon — ttt_bpb=X.XXXX" -# open new PR -``` - ---- - -## Git / PR Strategy (follow this every run) - -**Rule: every H100 run gets committed and pushed. No exceptions.** - -Even if it doesn't beat SOTA. Even if it's a failed experiment. The history matters. - -### After every run: -```bash -# 1. Create submission dir -mkdir -p records/track_10min_16mb/YYYY-MM-DD_short_description/ - -# 2. Copy relevant files in -cp train_gpt_v2.py records/track_10min_16mb/YYYY-MM-DD_.../train_gpt.py -# write submission.json, README.md, copy log if saved - -# 3. Commit everything changed (code + records dir) -git add records/track_10min_16mb/YYYY-MM-DD_.../ -git add train_gpt_v2.py run.sh # if changed since last commit -git commit -m "Short description of what changed and why" -git push fork main # or submission/branch-name - -# 4. Open PR on github -# - Record: normal submission title -# - Non-record: prefix title with "Non-record:" and explain what you learned -``` - -### PR types: -| Type | When | Title format | -|---|---|---| -| Record | New best ttt_bpb | "12L INT4 bQAT + VE — val_bpb 1.1550" | -| Non-record | Novel idea, failed experiment, analysis | "Non-record: VE overhead analysis + Parallel Muon findings" | - -**Non-record PRs are valuable.** They show active research, novel ideas, and build your leaderboard presence. Document what you tried and what you learned. - ---- - -## Full Experiment Log (Mar 28) - -### Run 1: v4_h100 seed 1 ✅ SUBMITTED -- **Config:** 12L INT4 bQAT, EMA_ENABLED=1, LATE_QAT_FRAC=0.65, XSA4, RoPE16, LN_SCALE, TTT -- **Result:** 5021 steps, post-quant 1.1703, ttt_bpb ~1.165 (TTT interrupted at 58%) -- **Artifact:** 15,899,385 bytes (15.90MB) -- **PR:** Pushed to fork, opened PR (review required) -- **Record dir:** `records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_EMAfix/` - -### Run 2: v5_rownorm seed 1 ❌ KILLED (step 100) -- **Config:** v4_h100 + MUON_BACKEND=rownorm (row-wise L2 norm replaces NS5) -- **Result:** train_loss=5.38 at step 100 (vs 3.18 for v4_h100) — catastrophic failure -- **step_avg:** 109ms (same as DDP — NS5 was NOT the bottleneck) -- **Lesson:** Row-norm doesn't produce orthogonal updates. NS5 is not the throughput bottleneck — DDP all_reduce is. -- **Code:** v5_rownorm config deprecated (exits with error in run.sh) -- **TODO:** Package as non-record PR with analysis - -### Run 3: v4_h100 seed 3 ✅ SUBMITTED (updated existing PR) -- **Config:** Same as seed 1 -- **Result:** post-quant 1.2002 (large QAT degradation), ttt_bpb **1.1594** (full 1893-chunk TTT) -- **Artifact:** 15,967,640 bytes (15.97MB) -- **Note:** Large post-quant degradation but TTT recovered aggressively. New best. -- **PR:** Updated submission.json (val_bpb 1.165→1.1594) + README, pushed to fork - -### Run 4: v6_parallel seed 1 ❌ KILLED (step ~800) -- **Config:** v4_h100 + Parallel Muon (one RS per matrix param, no DDP) -- **Result:** step_avg 148ms — WORSE than DDP 110ms -- **Lesson:** 40+ individual NCCL RS ops has higher overhead than DDP's single batched all_reduce -- **TODO:** Package as non-record PR with Parallel Muon analysis - -### Run 5: v6_parallel (virtual banking) seed 1 ❌ KILLED (step ~800) -- **Config:** v4_h100 + virtual banking Muon (group params by shape, one RS per shape group) -- **Result:** step_avg 117ms — still slower than DDP 110ms -- **Lesson:** Grad stacking copy overhead cancels NCCL savings. Need model banking (3D weight tensors) to avoid copies. -- **Analysis:** SOTA uses 4 banked 3D params (qo/kv/mlp_up/mlp_down). RS operates directly on banked grad — no copy. Without model banking, can't beat DDP. -- **TODO:** Package as non-record PR with virtual banking analysis - -### Run 7: v7_ve seed 2 ✅ NEW BEST -- **Config:** same as seed 1 with SEED=2 -- **step_avg:** 148ms final. post-quant 1.1624, ttt_bpb **1.15738** -- **Artifact:** 16,408,223 bytes (16.41MB) — within 16,777,216 limit ✓ -- **Key:** Seed 2 beat seed 1 by 0.00137 BPB -- **Submission dir:** Updated `records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/` -- **TODO:** Commit + push to `submission/12L-INT4-bQAT-VE` - -### Run 6: v7_ve seed 1 ✅ SUBMITTED -- **Config:** v4_h100 + VALUE_EMBED_LAYERS=2 + VALUE_EMBED_DIM=128 (VE at layers 10,11) -- **step_avg:** 137ms final (154ms last step during QAT). ~4380 total steps. -- **Result:** pre-quant 1.1754, post-quant 1.1643, ttt_bpb **1.15875** -- **Artifact:** 16,290,425 bytes (16.29MB) — within 16,777,216 limit ✓ -- **Val checkpoints:** step 1000: 1.2963 (+0.007 vs v4_h100), step 2000: 1.2344 (+0.014 vs v4_h100) -- **Key observation:** VE gave +0.014 BPB quality per step at step 2000. Despite 640 fewer steps, net gain of +0.0006 BPB over seed 3. Post-quant very clean (1.1643 vs seed 3's disastrous 1.2002). -- **Submission dir:** `records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_VE/` -- **TODO:** Commit + push + open new PR - ---- - -## Throughput Analysis — Why Parallel Muon Needs Banking - -| Run | Approach | step_avg | Steps/10min | Notes | -|---|---|---|---|---| -| v4_h100 (DDP) | DDP all_reduce | ~110ms | ~5450 | 1 batched NCCL op | -| v6_parallel (per-param RS) | 40+ RS+AG ops | 148ms | ~4050 | NCCL launch overhead | -| v6_parallel (virtual banking) | 4-6 RS+AG ops | 117ms | ~5130 | Grad copy overhead | -| SOTA (model banking) | 4 RS+AG ops | 83ms | ~7230 | Grads already banked — no copy | - -**Root cause of gap:** SOTA stores weights as 3D tensors `(num_layers, M, K)`. Grad accumulates directly in this shape → RS operates on it with zero copy. Without model banking, any Parallel Muon implementation has extra grad copy overhead that negates NCCL savings. - -**To implement model banking:** Replace per-layer `nn.Linear` with 4 banked params (`qo_bank`, `kv_bank`, `mlp_up_bank`, `mlp_down_bank`). Forward uses `bank[layer_idx]`. Estimated: 1-2 days, gives ~85-90ms → +1400 steps → ~0.020 BPB. - ---- - -## Architecture — What We Have vs SOTA - -| Feature | Our v4_h100 | SOTA (PR#549) | Notes | -|---|---|---|---| -| Layers | 12 | 11 | We use 12L INT4 bQAT to fit more capacity | -| Param banking | ❌ | ✅ | Key throughput difference | -| INT4 MLP QAT | ✅ | ❌ | Our novel contribution | -| INT4 Bigram QAT | ✅ (novel) | ❌ | Saves 370KB vs INT6 | -| EMA + QAT reset | ✅ | ❌ | Our fix for EMA-QAT contamination | -| XSA last N | ✅ (4 layers) | ✅ (4 layers) | Same | -| Value Embeddings | 🔲 Testing | ✅ | Testing in v7_ve | -| Parallel Muon | ❌ (needs banking) | ✅ | 83ms vs our 110ms | -| Legal TTT | ✅ | ✅ | Same | -| LeakyReLU² | ✅ | ✅ | Same | -| U-Net skips | ✅ | ? | Our addition | -| resid_mix | ✅ | ? | Our addition | - ---- - -## Next Experiments Queue - -| Priority | Experiment | Config | Expected gain | Effort | Status | -|---|---|---|---|---|---| -| 1 | **v10_banked proxy** | `bash run.sh v10_banked_proxy` | Verify correctness, ~110ms single-GPU | Done | **RUN NOW** | -| 2 | **v10_banked SEED=1** | `SEED=1 bash run.sh v10_banked` | ~90-100ms/step → 6000+ steps → ~1.132-1.139 BPB | Done | **NEXT** | -| 3 | v10_banked SEED=2,3 | additional seeds | Seed variance ~0.005 | 0 | Queued | -| 4 | More v7_ve seeds | SEED=3,4 | Seed variance ~0.005 | 0 | Fallback | -| 5 | KL distillation from SOTA | new config | +0.010-0.020 BPB | 4-6h | Future | - -### v8_static result: FAILED (no improvement) -step_avg at step 700: **136ms** — identical to v7_ve (137ms). DDP static_graph did NOT fix VE overhead. -VE overhead is structural (not bucket ordering). Root cause unknown. Discarded. - ---- - -## Leaderboard (Mar 27) -| Rank | BPB | Author | PR | Notes | -|---|---|---|---|---| -| 1 | **1.1194** | abaybektursun | #549 | Bank-arch + ParallelMuon | -| 2 | 1.1228 | signalrush | #374 | | -| 3 | 1.1248 | jfprincz | #287 | | -| 4 | 1.1271 | jfprincz | #198 | | -| 5 | 1.1307 | unnir | | | -| **us** | **1.1594** | SoHarshh | open PR | 12L INT4 bQAT + EMAfix | - -Gap to SOTA: 0.040 BPB. Path: quality improvements (VE, distillation) + model banking. - ---- - -## Key Technical Findings - -1. **INT4 Bigram QAT** (novel): Quantize bigram hash table to INT4 during QAT. Saves ~370KB vs INT6. Enables 12L in 16MB. No prior submission has done this. - -2. **EMA reset at QAT activation**: Reset EMA state when QAT turns on, so EMA only averages QAT-adapted weights. Drops post-quant degradation from +0.193 BPB to +0.002 BPB. - -3. **LATE_QAT_FRAC=0.65**: Fire QAT at 65% of wallclock budget (390s). Immune to step_ms noise. Seeds are deterministic. - -4. **Parallel Muon dead end (without banking)**: Tried 3 implementations (per-param RS, virtual banking RS, row-norm). All slower than DDP without model banking. Model banking = full rewrite of weight storage from 2D per-layer to 3D banked tensors. - -5. **Value Embeddings**: Adding VE at 2 layers gives +0.007-0.014 BPB quality improvement per step but costs 27ms/step overhead (137ms vs 110ms). Net effect TBD from v7_ve final result. - ---- - -## Pending PRs to Open - -| Content | Type | Status | -|---|---|---| -| v4_h100 seed 3 (1.1594) | Record | ✅ Updated existing PR | -| Rownorm analysis + results | Non-record | TODO | -| Parallel Muon analysis (virtual banking) | Non-record | TODO | -| v7_ve results | Record or Non-record | Pending run completion | - ---- - -## Key File Locations -| File | Purpose | -|---|---| -| `train_gpt_v2.py` | Working file — all experiments | -| `run.sh` | All run configs | -| `final_model_v4_h100_seed3.int8.ptz` | Best artifact (15.97MB) | -| `records/track_10min_16mb/2026-03-28_12L_INT4_bQAT_EMAfix/` | Current submission | -| `records/track_10min_16mb/2026-03-23_LeakyReLU_LegalTTT_ParallelMuon/train_gpt.py` | SOTA reference (1.1194) | - ---- - -## Rules -- No git push — user does this manually -- No GPU switching — user decides when to start/stop instances -- No AI traces in any submission files (README, train_gpt.py, submission.json, blurb) -- Keep submission.json val_bpb honest — use measured values -- Every H100 run gets a commit + PR (record or non-record)