diff --git a/records/track_non_record_16mb/2026-03-24_LateQAT_VR_GA_FullGPTQ_anantdgoel/README.md b/records/track_non_record_16mb/2026-03-24_LateQAT_VR_GA_FullGPTQ_anantdgoel/README.md new file mode 100644 index 000000000..9b0c1a553 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-24_LateQAT_VR_GA_FullGPTQ_anantdgoel/README.md @@ -0,0 +1,89 @@ +**val_bpb: 1.1418** | **15.7 MB** | 1x NVIDIA RTX A6000, ~14 hours + +## Summary + +11-layer GPT with community meta-stack plus novel techniques: **Value Residual (VR)** and **Gated Attention (GA)**, combined with **Late QAT** during training and **Full GPTQ + Int5 MLP** post-training quantization pipeline. Achieves 1.1418 BPB at stride=128 in a 15.7 MB artifact. + +## Novel Contributions + +### Value Residual (VR) +Inspired by [arXiv:2410.17897](https://arxiv.org/abs/2410.17897). Each attention layer receives a shortcut from layer-0's V projection (`v0`), blended with the current layer's V via learned mixing. This prevents deep attention layers from losing signal, providing a consistent -0.015 BPB improvement across configurations. + +### Gated Attention (GA) +Inspired by [arXiv:2505.06708](https://arxiv.org/abs/2505.06708). A per-head learned sigmoid gate applied after scaled dot-product attention, allowing each head to learn when to suppress or amplify its contribution. Provides -0.003 BPB on top of VR. + +### Late QAT (Quantization-Aware Training) +STE fake-quantize applied to all linear layers when the learning rate scale drops below a threshold (0.15), activating during the final ~5% of training. Helps the model adapt its weight distribution to the target int6 quantization format during training. + +### Full GPTQ Post-Training Quantization +Hessian-aware column-wise quantization with Cholesky error compensation, applied post-training. Uses 100 calibration batches to collect per-layer Hessian information, then quantizes each column optimally to minimize reconstruction error. Combined with adaptive clip percentile search (GPTQ-lite). + +### Int5 MLP Re-quantization +Post-training re-quantization of MLP weights from int6 to int5. Surprisingly acts as regularization, improving BPB by ~0.028 while reducing artifact size. + +## Architecture + +- 11 layers, dim=512, 8 heads (4 KV), MLP mult=3 +- Vocab 1024 (SentencePiece BPE), BigramHash with 1024 buckets +- XSA (first 4 layers), partial RoPE (16 dims), logit softcap=30 +- EMA (decay=0.997), SmearGate, orthogonal init, LN scale + +## Training Configuration + +- 9500 steps, batch size 524K tokens, warmdown 3500 steps +- Muon optimizer: matrix_lr=0.025, momentum=0.99 (warmup from 0.92 over 1500 steps) +- Adam for scalars/embeddings: lr=0.025/0.035 +- Weight decay: 0.04 (both Muon and Adam) +- Late QAT threshold: 0.15 (activated at step ~8976) + +## Post-Training Pipeline + +1. Full GPTQ quantization (100 calibration batches) +2. Int5 MLP re-quantization +3. GPTQ-lite adaptive clip search +4. Int6+zstd serialization → 16,442,824 bytes (15.7 MB) + +## Ablation Results (stride=128) + +| Configuration | BPB | Delta | +|--------------|-----|-------| +| Base (int6+zstd, no post-training) | 1.1696 | — | +| + Full GPTQ + Int5 + GPTQ-lite | **1.1418** | **-0.028** | +| + VR_V0_FP16 (asymmetric quant) | 1.1418 | +0.000 | +| + SGD TTT (legal, cosine, per-layer) | 1.1721 | +0.030 (worse) | + +Key finding: TTT hurts on GPTQ-quantized models — the quantized weight space is incompatible with gradient-based test-time adaptation. + +## Reproducibility + +```bash +# Training (requires ~14 hours on A6000) +TORCHDYNAMO_DISABLE=1 \ +VOCAB_SIZE=1024 NUM_LAYERS=11 MODEL_DIM=512 NUM_HEADS=8 NUM_KV_HEADS=4 MLP_MULT=3 \ +TRAIN_SEQ_LEN=1024 TRAIN_BATCH_TOKENS=524288 \ +ITERATIONS=9500 WARMDOWN_ITERS=3500 WARMUP_STEPS=20 \ +MATRIX_LR=0.025 SCALAR_LR=0.025 TIED_EMBED_LR=0.035 \ +MUON_MOMENTUM=0.99 MUON_MOMENTUM_WARMUP_START=0.92 MUON_MOMENTUM_WARMUP_STEPS=1500 \ +MUON_BACKEND_STEPS=5 GRAD_CLIP_NORM=0.3 \ +WEIGHT_DECAY_MUON=0.04 WEIGHT_DECAY_ADAM=0.04 \ +SMEAR_GATE=1 BIGRAM_HASH=1 BIGRAM_BUCKETS=1024 BIGRAM_DIM=128 ORTHO_INIT=1 \ +XSA_LAYERS=4 EMA_ENABLED=1 EMA_DECAY=0.997 SWA_ENABLED=0 \ +PARTIAL_ROPE_DIMS=16 LN_SCALE=1 LOGIT_SOFTCAP=30.0 \ +GATED_ATTENTION=1 VALUE_RESIDUAL=1 \ +LATE_QAT=1 LATE_QAT_THRESHOLD=0.15 \ +QUANT_BITS=6 EVAL_SEQ_LEN=1024 EVAL_STRIDE=128 \ +DATA_PATH=./data/datasets/fineweb10B_sp1024 \ +TOKENIZER_PATH=./data/tokenizers/fineweb_1024_bpe.model \ +torchrun --standalone --nproc_per_node=1 train_gpt.py + +# Eval with post-training pipeline (loads trained model) +LOAD_ARTIFACT=model.ptz FULL_GPTQ=1 INT5_MLP=1 GPTQ_LITE=1 \ +ITERATIONS=0 EVAL_STRIDE=128 \ +torchrun --standalone --nproc_per_node=1 train_gpt.py +``` + +## Files + +- `train_gpt.py` — Training script with all techniques +- `submission.json` — Metadata +- `README.md` — This file diff --git a/records/track_non_record_16mb/2026-03-24_LateQAT_VR_GA_FullGPTQ_anantdgoel/submission.json b/records/track_non_record_16mb/2026-03-24_LateQAT_VR_GA_FullGPTQ_anantdgoel/submission.json new file mode 100644 index 000000000..b231452ad --- /dev/null +++ b/records/track_non_record_16mb/2026-03-24_LateQAT_VR_GA_FullGPTQ_anantdgoel/submission.json @@ -0,0 +1,14 @@ +{ + "track": "non-record-16mb", + "val_bpb": 1.1418, + "artifact_size_bytes": 16442824, + "hardware": "1x NVIDIA RTX A6000 (48GB)", + "training_time_hours": 14, + "novel_contributions": [ + "Value Residual (VR): Layer-0 V vector shortcut that improves deep attention signal flow", + "Gated Attention (GA): Per-head learned sigmoid gate after SDPA for adaptive attention filtering", + "Late QAT: LR-threshold-based quantization-aware training during final training phase", + "Full GPTQ post-training: Hessian-aware column-wise quantization with Cholesky error compensation", + "Int5 MLP: Post-training re-quantization of MLP weights to int5, acts as regularization" + ] +} diff --git a/records/track_non_record_16mb/2026-03-24_LateQAT_VR_GA_FullGPTQ_anantdgoel/train_gpt.py b/records/track_non_record_16mb/2026-03-24_LateQAT_VR_GA_FullGPTQ_anantdgoel/train_gpt.py new file mode 100644 index 000000000..d1e84d4d4 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-24_LateQAT_VR_GA_FullGPTQ_anantdgoel/train_gpt.py @@ -0,0 +1,1723 @@ +"""train_gpt.py — Hard stop: must never be longer than 1500 lines.""" + +from __future__ import annotations + +import copy +import glob +import io +import json +import math +import os +import random +import subprocess +import sys +import time +import uuid +from pathlib import Path + +try: + import zstandard +except ImportError: + zstandard = None + +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 + +def _ei(k, d): return int(os.environ.get(k, str(d))) +def _ef(k, d): return float(os.environ.get(k, str(d))) +def _eb(k, d="0"): return bool(int(os.environ.get(k, d))) +def _es(k, d=""): return os.environ.get(k, d) + +class Hyperparameters: + data_path = _es("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 = _es("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") + run_id = _es("RUN_ID", str(uuid.uuid4())); seed = _ei("SEED", 1337) + val_batch_size = _ei("VAL_BATCH_SIZE", 524288); val_loss_every = _ei("VAL_LOSS_EVERY", 1000) + train_log_every = _ei("TRAIN_LOG_EVERY", 200); iterations = _ei("ITERATIONS", 20000) + warmdown_iters = _ei("WARMDOWN_ITERS", 3000); warmup_steps = _ei("WARMUP_STEPS", 20) + train_batch_tokens = _ei("TRAIN_BATCH_TOKENS", 524288); train_seq_len = _ei("TRAIN_SEQ_LEN", 2048) + max_wallclock_seconds = _ef("MAX_WALLCLOCK_SECONDS", 600.0); qk_gain_init = _ef("QK_GAIN_INIT", 1.5) + vocab_size = _ei("VOCAB_SIZE", 1024); num_layers = _ei("NUM_LAYERS", 9) + num_kv_heads = _ei("NUM_KV_HEADS", 4); model_dim = _ei("MODEL_DIM", 512) + num_heads = _ei("NUM_HEADS", 8); mlp_mult = _ef("MLP_MULT", 2) + tie_embeddings = _eb("TIE_EMBEDDINGS", "1"); rope_base = _ef("ROPE_BASE", 10000.0) + logit_softcap = _ef("LOGIT_SOFTCAP", 30.0); embed_lr = _ef("EMBED_LR", 0.6) + head_lr = _ef("HEAD_LR", 0.008); tied_embed_lr = _ef("TIED_EMBED_LR", 0.05) + tied_embed_init_std = _ef("TIED_EMBED_INIT_STD", 0.005) + matrix_lr = _ef("MATRIX_LR", 0.02); scalar_lr = _ef("SCALAR_LR", 0.02) + muon_momentum = _ef("MUON_MOMENTUM", 0.99); muon_backend_steps = _ei("MUON_BACKEND_STEPS", 5) + muon_momentum_warmup_start = _ef("MUON_MOMENTUM_WARMUP_START", 0.92) + muon_momentum_warmup_steps = _ei("MUON_MOMENTUM_WARMUP_STEPS", 1500) + beta1 = _ef("BETA1", 0.9); beta2 = _ef("BETA2", 0.95); adam_eps = _ef("ADAM_EPS", 1e-8) + grad_clip_norm = _ef("GRAD_CLIP_NORM", 0.3) + weight_decay_muon = _ef("WEIGHT_DECAY_MUON", 0.02); weight_decay_adam = _ef("WEIGHT_DECAY_ADAM", 0.01) + eval_seq_len = _ei("EVAL_SEQ_LEN", 0); eval_stride = _ei("EVAL_STRIDE", 0) + kv_cache_len = _ei("KV_CACHE_LEN", 0) + sgd_ttt = _eb("SGD_TTT"); sgd_ttt_lr = _ef("SGD_TTT_LR", 0.002) + sgd_ttt_momentum = _ef("SGD_TTT_MOMENTUM", 0.9); sgd_ttt_epochs = _ei("SGD_TTT_EPOCHS", 2) + sgd_ttt_seq_len = _ei("SGD_TTT_SEQ_LEN", 1024); sgd_ttt_param_set = _es("SGD_TTT_PARAM_SET", "control") + ttt_optimizer = _es("TTT_OPTIMIZER", "sgd"); ttt_legal = _eb("TTT_LEGAL") + ttt_freeze_blocks = _ei("TTT_FREEZE_BLOCKS", 0) + ttt_cosine_lr = _eb("TTT_COSINE_LR"); ttt_perlayer_lr = _eb("TTT_PERLAYER_LR") + cache_mixture = _eb("CACHE_MIXTURE"); cache_lambda = _ef("CACHE_LAMBDA", 0.02) + cache_decay = _ef("CACHE_DECAY", 0.995); ogd_bias = _eb("OGD_BIAS"); ogd_lr = _ef("OGD_LR", 0.1) + smear_gate = _eb("SMEAR_GATE"); bigram_hash = _eb("BIGRAM_HASH") + bigram_buckets = _ei("BIGRAM_BUCKETS", 4096); bigram_dim = _ei("BIGRAM_DIM", 128) + ortho_init = _eb("ORTHO_INIT"); gated_attention = _eb("GATED_ATTENTION") + value_residual = _eb("VALUE_RESIDUAL"); xsa_layers = _ei("XSA_LAYERS", 0) + ema_enabled = _eb("EMA_ENABLED"); ema_decay = _ef("EMA_DECAY", 0.997) + partial_rope_dims = _ei("PARTIAL_ROPE_DIMS", 0); ln_scale = _eb("LN_SCALE") + swa_enabled = _eb("SWA_ENABLED"); swa_start_frac = _ef("SWA_START_FRAC", 0.2) + swa_every = _ei("SWA_EVERY", 50); late_qat = _eb("LATE_QAT") + late_qat_threshold = _ef("LATE_QAT_THRESHOLD", 0.15) + gptq_lite = _eb("GPTQ_LITE_SEARCH"); gptq_lite_grid = _ei("GPTQ_LITE_GRID", 20) + full_gptq = _eb("FULL_GPTQ"); gptq_calib_batches = _ei("GPTQ_CALIB_BATCHES", 100) + train_only = _eb("TRAIN_ONLY"); artifact_filename = _es("ARTIFACT_FILENAME") + load_artifact = _es("LOAD_ARTIFACT") + hyper_connections = _eb("HYPER_CONNECTIONS"); adaptive_vr = _eb("ADAPTIVE_VR") + vr_v0_fp16 = _eb("VR_V0_FP16"); ttt_ga_guided = _eb("TTT_GA_GUIDED") + +def get_artifact_compressor() -> str: + compressor = os.environ.get("ARTIFACT_COMPRESSOR", "zstd" if zstandard is not None else "zlib") + if compressor not in ("zlib", "zstd"): + raise ValueError(f"ARTIFACT_COMPRESSOR must be zlib or zstd, got {compressor}") + if compressor == "zstd" and zstandard is None: + raise RuntimeError("ARTIFACT_COMPRESSOR=zstd requires zstandard to be installed") + return compressor + +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.bfloat16() + 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 = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + total_params = sum(int(p.numel()) for p in params) + updates_flat = torch.zeros(total_params, device=params[0].device, dtype=torch.bfloat16) + 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 + row_norms = g.norm(dim=-1, keepdim=True).clamp_min(1e-7) + g = g / row_norms + 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("▁"): + 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(f"VAL_BATCH_SIZE too small for rank: {args.val_batch_size}") + local_batch_seqs = local_batch_tokens // args.train_seq_len + total_seqs = (val_tokens.numel() - 1) // args.train_seq_len + seq_start = (total_seqs * rank) // world_size + seq_end = (total_seqs * (rank + 1)) // world_size + val_loss_sum = torch.zeros((), device=device, dtype=torch.float64) + val_token_count = torch.zeros((), device=device, dtype=torch.float64) + val_byte_count = torch.zeros((), device=device, dtype=torch.float64) + model.eval() + with torch.inference_mode(): + for batch_seq_start in range(seq_start, seq_end, local_batch_seqs): + batch_seq_end = min(batch_seq_start + local_batch_seqs, seq_end) + raw_start = batch_seq_start * args.train_seq_len + raw_end = batch_seq_end * args.train_seq_len + 1 + local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True) + x = local[:-1].reshape(-1, args.train_seq_len) + y = local[1:].reshape(-1, args.train_seq_len) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + batch_loss = model(x, y).detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + +def _count_token_bytes( + prev_ids: Tensor, tgt_ids: Tensor, + base_bytes_lut: Tensor, has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, +) -> float: + tb = base_bytes_lut[tgt_ids].to(torch.int16) + ( + has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids] + ).to(torch.int16) + return tb.to(torch.float64).sum().item() + +BOS_ID = 1 + +def _build_sliding_windows(val_tokens: Tensor, seq_len: int, stride: int, doc_isolated: bool): + N = val_tokens.numel() - 1 + if not doc_isolated: + return list(range(0, N - seq_len + 1, stride)) + bos_positions = (val_tokens[:N] == BOS_ID).nonzero(as_tuple=True)[0].tolist() + if not bos_positions or bos_positions[0] != 0: + bos_positions = [0] + bos_positions + bos_positions.append(N) + starts: list[int] = [] + for di in range(len(bos_positions) - 1): + doc_start, doc_end = bos_positions[di], bos_positions[di + 1] + doc_len = doc_end - doc_start + if doc_len < 2: + continue + pos = doc_start + while pos + 1 <= doc_end: + starts.append(pos) + pos += stride + if pos + seq_len > doc_end: + if doc_end - seq_len > starts[-1]: + starts.append(max(doc_start, doc_end - seq_len)) + break + return starts + +def eval_val_sliding( + args: Hyperparameters, model: nn.Module, device: torch.device, + val_tokens: Tensor, base_bytes_lut: Tensor, has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float, int, float]: + seq_len = args.eval_seq_len or args.train_seq_len + stride = args.eval_stride or seq_len + cache_len = args.kv_cache_len + N = val_tokens.numel() - 1 + use_cache = cache_len > 0 + if use_cache and cache_len > seq_len: + raise ValueError(f"KV_CACHE_LEN ({cache_len}) must be <= EVAL_SEQ_LEN ({seq_len})") + batch_seqs = 1 if use_cache else max(1, min(args.val_batch_size // seq_len, 64)) + starts = _build_sliding_windows(val_tokens, seq_len, stride, False) + loss_sum, tok_count, byte_count = 0.0, 0, 0.0 + num_layers = len([b for b in model.modules() if isinstance(b, Block)]) + model.eval() + with torch.inference_mode(): + kv_caches: list | None = None + for bi in range(0, len(starts), batch_seqs): + bs = starts[bi : bi + batch_seqs] + bsz = len(bs) + x = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(bs): + end = min(ws + seq_len, N) + wlen = end - ws + wlens.append(wlen) + chunk = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x[i, :wlen] = chunk[:-1] + y[i, :wlen] = chunk[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + if use_cache: + if kv_caches is None or val_tokens[bs[0]].item() == BOS_ID: + kv_caches = [None] * num_layers + logits, new_caches = model.get_logits(x, kv_caches=kv_caches) + kv_caches = [ + (nc[0][:, :, -cache_len:, :].detach(), nc[1][:, :, -cache_len:, :].detach()) + if nc is not None else None + for nc in new_caches + ] + else: + logits = model.get_logits(x) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), y.reshape(-1), reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(bs): + 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().item() + tok_count += wlen - s + byte_count += _count_token_bytes( + x[i, s:wlen], y[i, s:wlen], + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + model.train() + val_loss = loss_sum / tok_count + return val_loss, val_loss / math.log(2.0) * tok_count / byte_count, tok_count, byte_count + +def _make_ttt_optimizer(args, named_ttt_params): + lr = args.sgd_ttt_lr + if args.ttt_perlayer_lr: + proj_params = [p for n, p in named_ttt_params if ".mlp.proj." in n or n.endswith(".mlp.proj.weight")] + fc_params = [p for n, p in named_ttt_params if ".mlp.fc." in n or n.endswith(".mlp.fc.weight")] + other_params = [p for n, p in named_ttt_params if not any(k in n for k in [".mlp.proj.", ".mlp.fc."]) and not n.endswith((".mlp.proj.weight", ".mlp.fc.weight"))] + groups = [] + if proj_params: groups.append({"params": proj_params, "lr": lr * 3.0}) + if fc_params: groups.append({"params": fc_params, "lr": lr * 0.5}) + if other_params: groups.append({"params": other_params, "lr": lr}) + else: + ttt_params = [p for _, p in named_ttt_params] + groups = [{"params": ttt_params, "lr": lr}] + opt_type = args.ttt_optimizer + if args.ttt_legal and opt_type == "sgd": + return torch.optim.SGD(groups, lr=lr, momentum=args.sgd_ttt_momentum) + elif opt_type == "adamw": + return torch.optim.AdamW(groups, lr=lr, weight_decay=0.0) + return torch.optim.SGD(groups, lr=lr, momentum=args.sgd_ttt_momentum) + +def _ttt_adapt_chunk(model, opt, x, y, ttt_ga_guided=False): + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + logits = model.get_logits(x) + loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)).float(), y.reshape(-1), reduction="mean") + opt.zero_grad() + loss.backward() + if ttt_ga_guided and hasattr(model, 'blocks'): + for block in model.blocks: + if hasattr(block.attn, 'attn_gate') and block.attn.attn_gate.bias is not None: + bias = block.attn.attn_gate.bias.detach() + uncertainty = 4 * torch.sigmoid(bias) * (1 - torch.sigmoid(bias)) + for name, param in block.attn.named_parameters(): + if param.grad is not None and 'attn_gate' not in name and param.ndim >= 1: + head_dim = param.shape[0] // len(uncertainty) + if head_dim > 0 and head_dim * len(uncertainty) == param.shape[0]: + scale = uncertainty.repeat_interleave(head_dim) + param.grad.mul_(scale.view(-1, *([1] * (param.grad.ndim - 1)))) + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + +def eval_val_sgd_ttt( + args: Hyperparameters, model: nn.Module, device: torch.device, + val_tokens: Tensor, base_bytes_lut: Tensor, has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float, int, float]: + seq_len = args.sgd_ttt_seq_len or args.train_seq_len + stride = args.eval_stride or seq_len + N = val_tokens.numel() - 1 + vocab_size = model.tok_emb.num_embeddings if hasattr(model, "tok_emb") else args.vocab_size + named_ttt_params = _named_ttt_params(model, args.sgd_ttt_param_set) + if args.ttt_freeze_blocks > 0: + freeze_prefix = tuple(f"blocks.{i}." for i in range(args.ttt_freeze_blocks)) + named_ttt_params = [(n, p) for n, p in named_ttt_params if not n.startswith(freeze_prefix)] + if not named_ttt_params: + raise ValueError(f"No parameters matched SGD_TTT_PARAM_SET={args.sgd_ttt_param_set}") + ttt_params = [param for _, param in named_ttt_params] + saved = {name: param.data.clone() for name, param in named_ttt_params} + for param in model.parameters(): + param.requires_grad_(False) + for param in ttt_params: + param.requires_grad_(True) + opt = _make_ttt_optimizer(args, named_ttt_params) + _reset_rotary_caches(model) + model.eval() + if args.ttt_legal: + return _eval_val_legal_ttt(args, model, device, val_tokens, base_bytes_lut, + has_leading_space_lut, is_boundary_token_lut, named_ttt_params, saved, opt, + seq_len, stride, N, vocab_size) + adapt_starts = list(range(0, N - seq_len + 1, seq_len)) + for epoch in range(args.sgd_ttt_epochs): + for s in adapt_starts: + chunk = val_tokens[s : s + seq_len + 1].to(device=device, dtype=torch.int64) + _ttt_adapt_chunk(model, opt, chunk[:-1].unsqueeze(0), chunk[1:].unsqueeze(0), ttt_ga_guided=args.ttt_ga_guided) + for p in model.parameters(): + p.requires_grad_(False) + use_cache, use_ogd = args.cache_mixture, args.ogd_bias + ogd_b = torch.zeros(vocab_size, device=device) if use_ogd else None + cache_counts = torch.zeros(vocab_size, device=device, dtype=torch.float64) if use_cache else None + cache_sum = 0.0 + batch_seqs = max(1, min(args.val_batch_size // seq_len, 64)) + starts = list(range(0, N - seq_len + 1, stride)) + loss_sum, tok_count, byte_count = 0.0, 0, 0.0 + with torch.inference_mode(): + for bi in range(0, len(starts), batch_seqs): + bs = starts[bi : bi + batch_seqs] + bsz = len(bs) + x = torch.stack([val_tokens[s : s + seq_len] for s in bs]).to(device=device, dtype=torch.int64) + y = torch.stack([val_tokens[s + 1 : s + seq_len + 1] for s in bs]).to(device=device, dtype=torch.int64) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + logits = model.get_logits(x) + for i, s in enumerate(bs): + sc = seq_len - stride if s > 0 else 0 + sl, st = logits[i, sc:, :].float(), y[i, sc:] + if use_ogd: sl = sl + ogd_b + if use_cache and cache_sum > 0: + log_pm = F.log_softmax(sl, dim=-1) + target_log_pm = log_pm.gather(1, st.unsqueeze(1)).squeeze(1).to(torch.float64) + la = target_log_pm + math.log(1 - args.cache_lambda) + lb = torch.log(args.cache_lambda * cache_counts[st] / cache_sum + 1e-30) + loss_sum += (-torch.logaddexp(la, lb)).sum().item() + else: + loss_sum += F.cross_entropy(sl, st, reduction="sum").item() + tok_count += st.numel() + byte_count += _count_token_bytes(x[i, sc:], st, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + if use_cache: + decay_factor = args.cache_decay ** st.numel() + cache_counts *= decay_factor + cache_sum = cache_sum * decay_factor + st.numel() + cache_counts.scatter_add_(0, st.long(), torch.ones_like(st, dtype=torch.float64)) + if use_ogd: + probs = F.softmax(sl.detach(), dim=-1).mean(0) + one_hot_mean = torch.zeros(vocab_size, device=device) + one_hot_mean.scatter_add_(0, st.long(), torch.ones(st.numel(), device=device) / st.numel()) + ogd_b.sub_(args.ogd_lr * (probs - one_hot_mean)) + with torch.no_grad(): + for name, param in named_ttt_params: + param.data.copy_(saved[name]) + model.train() + val_loss = loss_sum / tok_count + return val_loss, val_loss / math.log(2.0) * tok_count / byte_count, tok_count, byte_count + +def _eval_val_legal_ttt( + args, model, device, val_tokens, base_bytes_lut, has_leading_space_lut, + is_boundary_token_lut, named_ttt_params, saved, opt, + seq_len, stride, N, vocab_size, +) -> tuple[float, float, int, float]: + """Legal score-first TTT (PR #473 protocol): split val into non-overlapping chunks, + score each chunk with sliding window under inference_mode, then adapt on scored chunk. + Chunk N is scored by model adapted only on chunks 0..N-1. Last chunk scored but not trained.""" + chunk_size = int(os.environ.get("TTT_CHUNK_SIZE", 32768)) + chunk_starts = list(range(0, N, chunk_size)) + loss_sum, tok_count, byte_count = 0.0, 0, 0.0 + for ci, cs in enumerate(chunk_starts): + ce = min(cs + chunk_size, N) + chunk_tokens = val_tokens[cs : ce + 1].to(device=device, dtype=torch.int64) + chunk_N = ce - cs + sw_starts = list(range(0, chunk_N - seq_len + 1, stride)) + if not sw_starts: + sw_starts = [0] if chunk_N >= 2 else [] + with torch.inference_mode(): + for s in sw_starts: + end = min(s + seq_len, chunk_N) + wlen = end - s + x = chunk_tokens[s : s + wlen].unsqueeze(0) + y = chunk_tokens[s + 1 : s + wlen + 1].unsqueeze(0) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + logits = model.get_logits(x) + sc = max(wlen - stride, 0) if s > 0 else 0 + sl, st = logits[0, sc:wlen, :].float(), y[0, sc:wlen] + loss_sum += F.cross_entropy(sl, st, reduction="sum").item() + tok_count += st.numel() + byte_count += _count_token_bytes(x[0, sc:wlen], st, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + if ci < len(chunk_starts) - 1: + for m in model.modules(): + if isinstance(m, Rotary): + m._cos_cached = m._sin_cached = None + m._seq_len_cached = 0 + adapt_x = chunk_tokens[:chunk_N].unsqueeze(0) + adapt_y = chunk_tokens[1:chunk_N + 1].unsqueeze(0) + n_windows = max(1, (chunk_N - seq_len) // seq_len + 1) + total_steps = args.sgd_ttt_epochs * n_windows + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=total_steps) if args.ttt_cosine_lr else None + for _ in range(args.sgd_ttt_epochs): + for as_ in range(0, chunk_N - seq_len + 1, seq_len): + _ttt_adapt_chunk(model, opt, adapt_x[:, as_:as_+seq_len], adapt_y[:, as_:as_+seq_len], ttt_ga_guided=args.ttt_ga_guided) + if sched: sched.step() + if sched: + for g in opt.param_groups: g["lr"] = g.get("initial_lr", args.sgd_ttt_lr) + for p in model.parameters(): + p.requires_grad_(False) + with torch.no_grad(): + for name, param in named_ttt_params: + param.data.copy_(saved[name]) + model.train() + val_loss = loss_sum / tok_count + return val_loss, val_loss / math.log(2.0) * tok_count / byte_count, tok_count, byte_count + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights,smear,bigram.scale", + ).split(",") + if pattern +) +FP16_KEEP_NAME_PATTERNS = tuple( + p for p in os.environ.get("FP16_KEEP_NAME_PATTERNS", "tok_emb").split(",") if p +) +INT8_PER_ROW_SCALE_DTYPE = torch.float16 +INT8_CLIP_Q = 0.9999984 + +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: + percentiles = [0.999, 0.9995, 0.9999, 0.99999, 1.0] + best_q = None + best_scale = None + best_mse = torch.full((t32.shape[0],), float('inf'), device=t32.device) + for pct in percentiles: + if pct >= 1.0: + clip_abs = t32.abs().amax(dim=1) + else: + clip_abs = torch.quantile(t32.abs(), pct, dim=1) + clip_abs = clip_abs.clamp_min(1e-12) + clipped = torch.clamp(t32, -clip_abs[:, None], clip_abs[:, None]) + s = (clip_abs / clip_range).clamp_min(1e-12).to(torch.float16) + s = s.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(clipped / s.float()[:, None]), -(clip_range + 1), clip_range).to(torch.int8) + recon = q.float() * s.float()[:, None] + mse = ((t32 - recon) ** 2).mean(dim=1) + improved = mse < best_mse + if best_q is None: + best_q = q + best_scale = s + best_mse = mse + else: + best_q[improved] = q[improved] + best_scale[improved] = s[improved] + best_mse[improved] = mse[improved] + 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 quantize_int8_per_row(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 fake_quantize_int6(w: Tensor) -> Tensor: + if w.ndim != 2: + return w + with torch.no_grad(): + row_max = w.abs().amax(dim=1).clamp_min(1e-12) + scale = (row_max / 31.0).to(torch.float16).float() + q = torch.clamp(torch.round(w / scale[:, None]), -32, 31) + return q * scale[:, None] + +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 ".attn." in name or (".proj." in name and ".mlp." not in name): + return "attn" + return "other" + +def _quant_passthrough(name: str, t: Tensor, fp16_patterns: list[str], + result: dict, meta: dict) -> bool: + if not t.is_floating_point() or t.numel() <= 65536: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + return True + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + return True + if any(p in name for p in fp16_patterns): + result[name] = t.to(dtype=torch.float16).contiguous() + meta[name] = "passthrough_fp16" + return True + return False + +def _quant_fp16_patterns(num_layers: int) -> list[str]: + pats = list(FP16_KEEP_NAME_PATTERNS) + for li in range(max(0, num_layers - 2), num_layers): + pats.append(f"blocks.{li}.attn.c_k") + if int(os.environ.get("VR_V0_FP16", "0")) == 1: + pats.append("blocks.0.attn.c_v") + return pats + +def gptq_lite_search(state_dict: dict[str, Tensor], num_layers: int, quant_bits: int = 6, + grid_size: int = 20) -> dict: + attn_clip = 31 if quant_bits == 6 else 127 + int5_mlp = int(os.environ.get("INT5_MLP", "0")) == 1 + mlp_clip = 15 if int5_mlp else attn_clip + fp16_patterns = _quant_fp16_patterns(num_layers) + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + if _quant_passthrough(name, t, fp16_patterns, result, meta): + continue + cat = _classify_param(name) + if cat in ("mlp", "attn") and t.ndim == 2: + cr = mlp_clip if cat == "mlp" else attn_clip + bits_label = 5 if (cat == "mlp" and int5_mlp) else quant_bits + t32 = t.float() + best_mse = float("inf") + best_q, best_s = None, None + for gi in range(grid_size): + pct = 99.0 + gi * (1.0 / max(grid_size - 1, 1)) + clip_abs = torch.quantile(t32.abs(), pct / 100.0, dim=1) + clipped = torch.clamp(t32, -clip_abs[:, None], clip_abs[:, None]) + s = (clip_abs / cr).clamp_min(1e-12).to(torch.float16) + s = s.clamp_min(torch.finfo(torch.float16).tiny) + q = torch.clamp(torch.round(clipped / s.float()[:, None]), -(cr + 1), cr).to(torch.int8) + recon = q.float() * s.float()[:, None] + mse = (t32 - recon).pow(2).mean().item() + if mse < best_mse: + best_mse, best_q, best_s = mse, q, s + result[name + ".q"] = best_q + result[name + ".scale"] = best_s + meta[name] = {"type": f"int{bits_label}"} + else: + q, s = quantize_int8_per_row(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return {"w": result, "m": meta} + +def mixed_quantize(state_dict: dict[str, Tensor], num_layers: int, quant_bits: int = 6): + gptq_lite = int(os.environ.get("GPTQ_LITE", "0")) == 1 + int5_mlp = int(os.environ.get("INT5_MLP", "0")) == 1 + attn_clip = (1 << (quant_bits - 1)) - 1 if quant_bits == 6 else 127 + mlp_clip = 15 if int5_mlp else attn_clip + fp16_patterns = _quant_fp16_patterns(num_layers) + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + if _quant_passthrough(name, t, fp16_patterns, result, meta): + continue + cat = _classify_param(name) + if cat in ("mlp", "attn") and t.ndim >= 1: + clip = mlp_clip if cat == "mlp" else attn_clip + if quant_bits == 6 or int5_mlp: + q, s = quantize_intN_per_row(t, clip_range=clip, gptq_lite=gptq_lite) + bits_label = 5 if (cat == "mlp" and int5_mlp) else quant_bits + else: + q, s = quantize_int8_per_row(t) + bits_label = 8 + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": f"int{bits_label}"} + else: + q, s = quantize_int8_per_row(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return {"w": result, "m": meta} + +def _gptq_quantize_matrix(W: Tensor, H: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + """Full GPTQ: column-wise quantization with Hessian error compensation. + W: [out_features, in_features] float weight matrix + H: [in_features, in_features] Hessian proxy (X^T @ X from calibration) + Returns (q, scale) in standard per-row int format.""" + W = W.float().clone() + nrows, ncols = W.shape + damp = 0.01 * torch.diag(H).mean() + H_damp = H + damp * torch.eye(ncols, device=H.device) + try: + H_inv = torch.cholesky_inverse(torch.linalg.cholesky(H_damp)) + except Exception: + row_max = W.abs().amax(dim=1).clamp_min(1e-12) + 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(W / scale.float()[:, None]), -(clip_range + 1), clip_range).to(torch.int8) + return q, scale + diag_inv = torch.diag(H_inv).clamp_min(1e-12) + for j in range(ncols): + col = W[:, j] + row_max_col = col.abs().clamp_min(1e-12) + s_col = row_max_col / clip_range + q_col = torch.clamp(torch.round(col / s_col), -(clip_range + 1), clip_range) + err = col - q_col * s_col + W[:, j] = q_col * s_col + if j < ncols - 1: + W[:, j + 1:] -= err.unsqueeze(1) * (H_inv[j, j + 1:] / diag_inv[j]).unsqueeze(0) + row_max = W.abs().amax(dim=1).clamp_min(1e-12) + 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(W / scale.float()[:, None]), -(clip_range + 1), clip_range).to(torch.int8) + return q, scale + +def _collect_hessians(model: nn.Module, data_loader, device: torch.device, seq_len: int, + num_batches: int, batch_tokens: int) -> dict[str, Tensor]: + """Run calibration batches and collect H = X^T @ X for each Linear layer with numel > 65536.""" + hooks, hessians, nsamples = [], {}, {} + target_linears: dict[str, nn.Linear] = {} + for name, module in model.named_modules(): + if isinstance(module, nn.Linear) and module.weight.numel() > 65536: + target_linears[name] = module + def make_hook(layer_name: str, in_features: int): + def hook_fn(module, inp, out): + x = inp[0].detach().float() + if x.ndim == 3: + x = x.reshape(-1, x.shape[-1]) + if layer_name not in hessians: + hessians[layer_name] = torch.zeros(in_features, in_features, device=x.device) + nsamples[layer_name] = 0 + hessians[layer_name].add_(x.T @ x) + nsamples[layer_name] += x.shape[0] + return hook_fn + for name, module in target_linears.items(): + hooks.append(module.register_forward_hook(make_hook(name, module.in_features))) + model.eval() + with torch.inference_mode(): + for _ in range(num_batches): + x, y = data_loader.next_batch(batch_tokens, seq_len, 1) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + model(x, y) + for h in hooks: + h.remove() + model.train() + return {name: (hessians[name] / max(nsamples[name], 1)).cpu() for name in hessians} + +def gptq_full_quantize(state_dict: dict[str, Tensor], num_layers: int, + hessians: dict[str, Tensor], quant_bits: int = 6) -> dict: + """Like mixed_quantize but uses Hessian-aware GPTQ for layers with Hessian data.""" + int5_mlp = int(os.environ.get("INT5_MLP", "0")) == 1 + attn_clip = (1 << (quant_bits - 1)) - 1 if quant_bits == 6 else 127 + mlp_clip = 15 if int5_mlp else attn_clip + fp16_patterns = _quant_fp16_patterns(num_layers) + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + gptq_count, naive_count = 0, 0 + param_to_layer = {ln + ".weight": ln for ln in hessians} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + if _quant_passthrough(name, t, fp16_patterns, result, meta): + continue + cat = _classify_param(name) + if cat in ("mlp", "attn") and t.ndim >= 1: + clip = mlp_clip if cat == "mlp" else attn_clip + bits_label = 5 if (cat == "mlp" and int5_mlp) else quant_bits + if name in param_to_layer and t.ndim == 2: + H = hessians[param_to_layer[name]] + q, s = _gptq_quantize_matrix(t, H, clip_range=clip) + gptq_count += 1 + elif quant_bits == 6 or int5_mlp: + q, s = quantize_intN_per_row(t, clip_range=clip) + naive_count += 1 + else: + q, s = quantize_int8_per_row(t) + naive_count += 1 + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": f"int{bits_label}"} + else: + q, s = quantize_int8_per_row(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return {"w": result, "m": meta, "_gptq_stats": {"gptq": gptq_count, "naive": naive_count}} + +def dequantize_mixed(obj: dict[str, object], template_sd: dict[str, Tensor]) -> dict[str, Tensor]: + if obj.get("__quant_format__") == "int8_clean_per_row_v1": # legacy format + out, qm, po = {}, obj.get("qmeta", {}), obj.get("passthrough_orig_dtypes", {}) + for n, q in obj["quantized"].items(): + dt, s = getattr(torch, obj["dtypes"][n]), obj["scales"][n] + out[n] = (q.float() * s.float().view(q.shape[0], *([1]*(q.ndim-1)))).to(dt) if (qm.get(n,{}).get("scheme")=="per_row" or s.ndim>0) else (q.float()*float(s.item())).to(dt) + for n, t in obj["passthrough"].items(): + out[n] = t.to(dtype=getattr(torch, po[n])) if po.get(n) else t.detach().cpu() + return out + result, meta, out = obj["w"], obj["m"], {} + for name, orig in template_sd.items(): + info = meta[name] + if info in ("passthrough", "passthrough_ctrl", "passthrough_fp16"): + t = result[name] + out[name] = t.to(orig.dtype) if (t.dtype == torch.float16 and orig.dtype in (torch.float32, torch.bfloat16)) else t + continue + q, s = result[name + ".q"], result[name + ".scale"] + out[name] = (q.float() * s.float().view(q.shape[0], *([1]*(q.ndim-1)))).to(orig.dtype) if s.ndim > 0 else (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 = rank; self.world_size = world_size; self.device = device + self.stream = TokenStream(pattern) + self.data_stream = torch.cuda.Stream(device=device) + self._prefetched: tuple[Tensor, Tensor] | None = None + def _prepare(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, y = local[:-1].reshape(-1, seq_len), local[1:].reshape(-1, seq_len) + with torch.cuda.stream(self.data_stream): + x, y = x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) + return x, y + def prefetch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> None: + self._prefetched = self._prepare(global_tokens, seq_len, grad_accum_steps) + def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> tuple[Tensor, Tensor]: + if self._prefetched is not None: + x, y = self._prefetched; self._prefetched = None + torch.cuda.current_stream().wait_stream(self.data_stream) + return x, y + x, y = self._prepare(global_tokens, seq_len, grad_accum_steps) + torch.cuda.current_stream().wait_stream(self.data_stream) + return x, y + +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): + def forward(self, x: Tensor) -> Tensor: + return F.linear(x, self.weight.to(x.dtype), self.bias.to(x.dtype) if self.bias is not None else None) + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + +def _reset_rotary_caches(module: nn.Module) -> None: + for submodule in module.modules(): + if hasattr(submodule, "_seq_len_cached"): + submodule._seq_len_cached = 0 + +def _named_ttt_params(model: nn.Module, param_set: str) -> list[tuple[str, nn.Parameter]]: + named_params = list(model.named_parameters()) + if param_set == "all": + return named_params + if param_set not in ("control", "control_qk"): + raise ValueError(f"Unsupported TTT param set: {param_set}") + qk_names = { + f"blocks.{li}.attn.c_k.weight" + for li in range(max(0, len(model.blocks) - 2), len(model.blocks)) + } + selected: list[tuple[str, nn.Parameter]] = [] + for name, param in named_params: + is_control = any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + if is_control or (param_set == "control_qk" and name in qk_names): + selected.append((name, param)) + return selected + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int = 0): + super().__init__() + self.rope_dims = rope_dims if rope_dims > 0 else dim + rd = self.rope_dims + inv_freq = 1.0 / (base ** (torch.arange(0, rd, 2, dtype=torch.float32) / rd)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + rd = cos.size(-1) * 2 + if rd < x.size(-1): + x_rope, x_pass = x[..., :rd], x[..., rd:] + half = rd // 2 + x1, x2 = x_rope[..., :half], x_rope[..., half:] + x_rot = torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + return torch.cat((x_rot, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + +class CausalSelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int, + rope_base: float, + qk_gain_init: float, + gated_attention: bool = False, + value_residual: bool = False, + partial_rope_dims: int = 0, + adaptive_vr: 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 = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base, rope_dims=partial_rope_dims) + self.use_xsa = False + self.gated_attention = gated_attention + if gated_attention: + self.attn_gate = nn.Linear(dim, num_heads, bias=True) + nn.init.zeros_(self.attn_gate.weight) + nn.init.constant_(self.attn_gate.bias, 4.0) + self.value_residual = value_residual + if value_residual: + self.vr_lambda = nn.Parameter(torch.tensor([0.5, 0.5], dtype=torch.float32)) + self.vr_router = nn.Linear(dim, 1, bias=True) if (value_residual and adaptive_vr) else None + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + B, H, T, D = y.shape + Hkv = v.size(1) + group = H // Hkv + y_g = y.reshape(B, Hkv, group, T, D) + vn = F.normalize(v, dim=-1).unsqueeze(2) + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, H, T, D) + def forward( + self, x: Tensor, v0: Tensor | None = None, + kv_cache: tuple[Tensor, Tensor] | None = None, return_cache: bool = False, + ) -> tuple[Tensor, Tensor | None, tuple[Tensor, Tensor] | None]: + 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) + raw_v = v if self.value_residual else None + if self.value_residual and v0 is not None: + if self.vr_router is not None: + alpha = torch.sigmoid(self.vr_router(x.mean(dim=1, keepdim=True))).unsqueeze(-1) + v = alpha * v0 + (1 - alpha) * v + else: + lam = self.vr_lambda.to(dtype=v.dtype) + v = lam[0] * v0 + lam[1] * v + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + k_for_cache = k + v_for_cache = v + has_cache = kv_cache is not None and kv_cache[0] is not None + if has_cache: + cached_k, cached_v = kv_cache + k = torch.cat([cached_k, k], dim=2) + v = torch.cat([cached_v, v], dim=2) + total_len = k.size(2) + cos, sin = self.rotary(total_len, x.device, q.dtype) + cache_len = total_len - seqlen + q = apply_rotary_emb(q, cos[:, :, cache_len:, :], sin[:, :, cache_len:, :]) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + if has_cache: + causal_current = torch.tril(torch.ones(seqlen, seqlen, device=x.device, dtype=torch.bool)) + cached_visible = torch.ones(seqlen, cache_len, device=x.device, dtype=torch.bool) + mask = torch.cat([cached_visible, causal_current], dim=1)[None, None, :, :] + else: + mask = None + y = F.scaled_dot_product_attention( + q, + k, + v, + attn_mask=mask, + is_causal=(not has_cache), + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + if self.use_xsa: + v_current = v[:, :, cache_len:, :] if has_cache else v + y = self._xsa_efficient(y, v_current) + if self.gated_attention: + gate = torch.sigmoid(self.attn_gate(x)) + y = y * gate.unsqueeze(-1).transpose(1, 2) + y = y.transpose(1, 2).contiguous().reshape(bsz, seqlen, dim) + new_cache = (k_for_cache, v_for_cache) if (kv_cache is not None or return_cache) else None + return self.proj(y), raw_v, new_cache + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: float): + super().__init__() + hidden = int(mlp_mult * dim) + self.fc = CastedLinear(dim, hidden, bias=False) + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + def forward(self, x: Tensor) -> Tensor: + x = 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 Block(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: float, + rope_base: float, + qk_gain_init: float, + gated_attention: bool = False, + value_residual: bool = False, + partial_rope_dims: int = 0, + layer_idx: int = 0, + ln_scale: bool = False, + adaptive_vr: bool = False, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, + gated_attention=gated_attention, value_residual=value_residual, + partial_rope_dims=partial_rope_dims, adaptive_vr=adaptive_vr) + self.mlp = MLP(dim, mlp_mult) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + def forward( + self, x: Tensor, x0: Tensor, v0: Tensor | None = None, + kv_cache: tuple[Tensor, Tensor] | None = None, return_cache: bool = False, + ) -> tuple[Tensor, Tensor | None, tuple[Tensor, Tensor] | None]: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + s = self.ln_scale_factor + attn_out, raw_v, new_cache = self.attn(self.attn_norm(x) * s, v0=v0, kv_cache=kv_cache, return_cache=return_cache) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * s) + return x, raw_v, new_cache + +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, + smear_gate: bool = False, + bigram_buckets: int = 0, + bigram_dim: int = 128, + ortho_init: bool = False, + gated_attention: bool = False, + value_residual: bool = False, + xsa_layers: int = 0, + partial_rope_dims: int = 0, + ln_scale: bool = False, + hyper_connections: bool = False, + adaptive_vr: bool = False, + ): + 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.value_residual = value_residual + self.hyper_connections = hyper_connections + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.smear = SmearGate(model_dim) if smear_gate else None + self.bigram = BigramHashEmbedding(bigram_buckets, bigram_dim, model_dim) if bigram_buckets > 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.blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init, + gated_attention=gated_attention, value_residual=value_residual, + partial_rope_dims=partial_rope_dims, layer_idx=i, ln_scale=ln_scale, + adaptive_vr=adaptive_vr) + for i in range(num_layers) + ]) + if hyper_connections: + self.hc_alpha = nn.ParameterList([nn.Parameter(torch.eye(2)) for _ in range(num_layers)]) + if xsa_layers > 0: + for i in range(max(0, num_layers - xsa_layers), num_layers): + self.blocks[i].attn.use_xsa = True + 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._ortho_init = ortho_init + self._init_weights() + def _init_weights(self) -> None: + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) + num_layers = len(self.blocks) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif self._ortho_init and 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 _encode(self, input_ids: Tensor, kv_caches: list | None = None) -> tuple[Tensor, list | None]: + 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),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + v0 = None + skips: list[Tensor] = [] + want_cache = kv_caches is not None + new_caches: list | None = [] if want_cache else None + x_fast = torch.zeros_like(x) if self.hyper_connections else None + for i, block in enumerate(self.blocks): + layer_cache = kv_caches[i] if want_cache else None + if self.hyper_connections: + a = self.hc_alpha[i].to(dtype=x.dtype) + block_in = a[0, 0] * x + a[0, 1] * x_fast + else: + block_in = x + if i < self.num_encoder_layers: + out, raw_v, nc = block(block_in, x0, v0=v0, kv_cache=layer_cache, return_cache=want_cache) + if v0 is None and raw_v is not None: + v0 = raw_v + if self.hyper_connections: + x = a[1, 0] * x + a[1, 1] * out + x_fast = out + else: + x = out + skips.append(x) + else: + dec_idx = i - self.num_encoder_layers + if dec_idx < self.num_skip_weights and skips: + block_in = block_in + self.skip_weights[dec_idx].to(dtype=block_in.dtype)[None, None, :] * skips.pop() + out, _, nc = block(block_in, x0, v0=v0, kv_cache=layer_cache, return_cache=want_cache) + if self.hyper_connections: + x = a[1, 0] * x + a[1, 1] * out + x_fast = out + else: + x = out + if new_caches is not None: + new_caches.append(nc) + return self.final_norm(x), new_caches + def _project_to_logits(self, hidden: Tensor) -> Tensor: + logits_proj = F.linear(hidden, self.tok_emb.weight) if self.tie_embeddings else self.lm_head(hidden) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + def get_logits(self, input_ids: Tensor, kv_caches: list | None = None) -> Tensor | tuple[Tensor, list]: + hidden, new_caches = self._encode(input_ids, kv_caches) + logits = self._project_to_logits(hidden) + if kv_caches is not None: + return logits, new_caches + return logits + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + hidden, _ = self._encode(input_ids) + logits = self._project_to_logits(hidden.reshape(-1, hidden.size(-1))) + return F.cross_entropy(logits.float(), target_ids.reshape(-1), reduction="mean") + +def main() -> None: + global zeropower_via_newtonschulz5 + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + artifact_compressor = get_artifact_compressor() + 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}") + default_accum = 8 // world_size if 8 % world_size == 0 else 1 + grad_accum_steps = int(os.environ.get("GRAD_ACCUM_STEPS", str(default_accum))) + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + logfile = None + 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(f"Python {sys.version} PyTorch {torch.__version__}", console=False) + log0(subprocess.run(["nvidia-smi"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout, console=False) + random.seed(args.seed); np.random.seed(args.seed); torch.manual_seed(args.seed); torch.cuda.manual_seed_all(args.seed) + assert args.tokenizer_path.endswith(".model"), f"Need SentencePiece .model file: {args.tokenizer_path}" + sp = spm.SentencePieceProcessor(model_file=args.tokenizer_path) + assert int(sp.vocab_size()) == args.vocab_size, f"VOCAB_SIZE={args.vocab_size} != tokenizer {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"tokenizer:{args.tokenizer_path} dataset:{dataset_dir.name} shards:{actual_train_files} val_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, + smear_gate=args.smear_gate, bigram_buckets=args.bigram_buckets if args.bigram_hash else 0, + bigram_dim=args.bigram_dim, ortho_init=args.ortho_init, gated_attention=args.gated_attention, + value_residual=args.value_residual, xsa_layers=args.xsa_layers, + partial_rope_dims=args.partial_rope_dims, ln_scale=args.ln_scale, + hyper_connections=args.hyper_connections, adaptive_vr=args.adaptive_vr, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + late_qat_linears: list[nn.Linear] = [] + late_qat_activated = False + if args.late_qat: + for m in base_model.modules(): + if isinstance(m, nn.Linear) and m.weight.numel() > 65536: + late_qat_linears.append(m) + log0(f"late_qat:enabled threshold:{args.late_qat_threshold} linear_layers:{len(late_qat_linears)}") + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True, mode=os.environ.get("COMPILE_MODE", "default")) + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False, find_unused_parameters=(args.gated_attention or args.value_residual)) if distributed else compiled_model + block_named_params = list(base_model.blocks.named_parameters()) + matrix_params = [ + p + for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p + for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + if base_model.skip_weights.numel() > 0: scalar_params.append(base_model.skip_weights) + if base_model.smear is not None: scalar_params.append(base_model.smear.gate) + if base_model.bigram is not None: scalar_params.append(base_model.bigram.scale) + if hasattr(base_model, 'hc_alpha'): + for p in base_model.hc_alpha: scalar_params.append(p) + 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) + adam_kw = dict(betas=(args.beta1, args.beta2), eps=args.adam_eps, weight_decay=args.weight_decay_adam, fused=True) + optimizer_tok = torch.optim.AdamW(tok_params, **adam_kw) + optimizer_muon = Muon(matrix_params, lr=args.matrix_lr, momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, weight_decay=args.weight_decay_muon) + 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}], **adam_kw) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizers.insert(1, torch.optim.AdamW([{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], **adam_kw)) + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params} layers:{len(base_model.blocks)} world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0(f"embed_lr:{token_lr} matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr} seed:{args.seed}") + log0(f"train_batch_tokens:{args.train_batch_tokens} seq_len:{args.train_seq_len} iterations:{args.iterations} warmdown:{args.warmdown_iters}") + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + max_wallclock_ms = 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0 + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 + if args.load_artifact: + log0(f"load_artifact: loading from {args.load_artifact}") + la_blob = Path(args.load_artifact).read_bytes() + la_raw = zstandard.ZstdDecompressor().decompress(la_blob) if artifact_compressor == "zstd" else __import__("zlib").decompress(la_blob) + la_state = torch.load(io.BytesIO(la_raw), map_location="cpu") + la_template = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + la_sd = dequantize_mixed(la_state, la_template) + requant = int(os.environ.get("GPTQ_LITE", "0")) == 1 or int(os.environ.get("INT5_MLP", "0")) == 1 or args.gptq_lite or args.full_gptq + if requant: + rq_bits = int(os.environ.get("QUANT_BITS", "6")) + if args.full_gptq: + base_model.load_state_dict(la_sd, strict=True) + log0(f"load_artifact: full_gptq calibrating with {args.gptq_calib_batches} batches") + calib_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + la_hessians = _collect_hessians(base_model, calib_loader, device, args.train_seq_len, args.gptq_calib_batches, args.train_batch_tokens) + la_sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + rq_obj = gptq_full_quantize(la_sd_cpu, args.num_layers, la_hessians, quant_bits=rq_bits) + rq_obj.pop("_gptq_stats", None) + elif args.gptq_lite: + rq_obj = gptq_lite_search(la_sd, args.num_layers, quant_bits=rq_bits, grid_size=args.gptq_lite_grid) + else: + rq_obj = mixed_quantize(la_sd, args.num_layers, quant_bits=rq_bits) + la_sd = dequantize_mixed(rq_obj, la_template) + rq_buf = io.BytesIO(); torch.save(rq_obj, rq_buf) + rq_blob = zstandard.ZstdCompressor(level=22).compress(rq_buf.getvalue()) if artifact_compressor == "zstd" else __import__("zlib").compress(rq_buf.getvalue(), level=9) + rq_fname = f"requantized_model.int6+{artifact_compressor}.ptz" + with open(rq_fname, "wb") as rqf: rqf.write(rq_blob) + log0(f"load_artifact: re-quantized to {rq_fname} ({len(rq_blob)} bytes)") + base_model.load_state_dict(la_sd, strict=True) + log0("load_artifact: model loaded, skipping training, proceeding to eval") + quant_filename = args.load_artifact + sd_cpu = la_template + lut_args = (base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + if args.eval_stride > 0: + sw_loss, sw_bpb, sw_tokens, sw_bytes = eval_val_sliding(args, base_model, device, val_tokens, *lut_args) + log0(f"sliding_window stride:{args.eval_stride} val_loss:{sw_loss:.4f} val_bpb:{sw_bpb:.4f} tokens:{sw_tokens}") + log0(f"sliding_window_exact val_loss:{sw_loss:.8f} val_bpb:{sw_bpb:.8f}") + if args.sgd_ttt: + for m in base_model.modules(): + if isinstance(m, Rotary): + m._cos_cached = None + m._sin_cached = None + m._seq_len_cached = 0 + original_param_set = args.sgd_ttt_param_set + original_ttt_opt = args.ttt_optimizer + eval_modes = [("ttt", original_param_set, original_ttt_opt)] + if original_ttt_opt == "adamw": + eval_modes.append(("ttt_sgd", original_param_set, "sgd")) + elif original_ttt_opt == "sgd": + eval_modes.append(("ttt_adamw", original_param_set, "adamw")) + for label, param_set, ttt_opt in eval_modes: + args.sgd_ttt_param_set = param_set + args.ttt_optimizer = ttt_opt + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb, ttt_tokens, ttt_bytes = eval_val_sgd_ttt( + args, base_model, device, val_tokens, *lut_args) + torch.cuda.synchronize() + log0( + f"{label} opt:{ttt_opt} param_set:{param_set} lr:{args.sgd_ttt_lr} legal:{args.ttt_legal} " + f"val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} tokens:{ttt_tokens} time:{1000*(time.perf_counter()-t_ttt):.0f}ms" + ) + log0(f"{label}_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + args.sgd_ttt_param_set = original_param_set + args.ttt_optimizer = original_ttt_opt + if distributed: dist.destroy_process_group() + return + 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=torch.bfloat16, 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) + swa_state, swa_count = None, 0 + ema_state = {name: t.detach().float().clone() for name, t in base_model.state_dict().items()} if args.ema_enabled else None + training_time_ms, stop_after_step = 0.0, None + torch.cuda.synchronize() + t0 = time.perf_counter() + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + torch.cuda.synchronize() + t0 = time.perf_counter() + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + zero_grad_all() + train_loss = torch.zeros((), device=device) + qat_active = args.late_qat and scale < args.late_qat_threshold + if qat_active and not late_qat_activated: + late_qat_activated = True + log0(f"late_qat:activated step:{step} scale:{scale:.4f} threshold:{args.late_qat_threshold}") + qat_saved: dict[int, Tensor] = {} + if qat_active: + for lin in late_qat_linears: + qat_saved[id(lin)] = lin.weight.data.clone() + lin.weight.data = fake_quantize_int6(lin.weight) + train_loader.prefetch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + 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) + if micro_step < grad_accum_steps - 1: + train_loader.prefetch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + if qat_active: + for lin in late_qat_linears: + lin.weight.data = qat_saved[id(lin)] + 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 + + if ema_state is not None: + with torch.no_grad(): + ema_vals = list(ema_state.values()) + model_vals = [t.detach().float() for t in base_model.state_dict().values()] + torch._foreach_mul_(ema_vals, args.ema_decay) + torch._foreach_add_(ema_vals, model_vals, alpha=1.0 - args.ema_decay) + + if args.swa_enabled and not args.ema_enabled and scale < args.swa_start_frac and step % args.swa_every == 0: + if swa_state is None: + swa_state = {name: t.detach().cpu().float() 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().float() + swa_count += 1 + + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + 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 ema_state is not None: + log0("ema:applying EMA weights") + avg_sd = {name: t.to(dtype=base_model.state_dict()[name].dtype) for name, t in ema_state.items()} + del ema_state + base_model.load_state_dict(avg_sd, strict=True) + + if args.swa_enabled and not args.ema_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_sd = { + name: (tensor / swa_count).to(dtype=current_state[name].dtype) + for name, tensor in swa_state.items() + } + base_model.load_state_dict(avg_sd, strict=True) + + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + if master_process: + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + quant_bits = int(os.environ.get("QUANT_BITS", "6")) + quant_label = f"int{quant_bits}+{artifact_compressor}" + if args.full_gptq: + log0(f"full_gptq:collecting hessians from {args.gptq_calib_batches} calibration batches") + calib_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + hessians = _collect_hessians(base_model, calib_loader, device, args.train_seq_len, + args.gptq_calib_batches, args.train_batch_tokens) + log0(f"full_gptq:collected hessians for {len(hessians)} layers, quantizing") + quant_obj = gptq_full_quantize(sd_cpu, args.num_layers, hessians, quant_bits=quant_bits) + gstats = quant_obj.pop("_gptq_stats", {}) + log0(f"full_gptq:done gptq_layers:{gstats.get('gptq',0)} naive_layers:{gstats.get('naive',0)}") + elif args.gptq_lite: + log0(f"gptq_lite:searching grid_size:{args.gptq_lite_grid}") + quant_obj = gptq_lite_search(sd_cpu, args.num_layers, quant_bits=quant_bits, grid_size=args.gptq_lite_grid) + else: + quant_obj = mixed_quantize(sd_cpu, args.num_layers, quant_bits=quant_bits) + quant_buf = io.BytesIO(); torch.save(quant_obj, quant_buf); quant_raw = quant_buf.getvalue() + quant_blob = zstandard.ZstdCompressor(level=22).compress(quant_raw) if artifact_compressor == "zstd" else __import__("zlib").compress(quant_raw, level=9) + quant_filename = args.artifact_filename or f"final_model.{quant_label}.ptz" + if master_process: + Path(quant_filename).write_bytes(quant_blob) + Path("artifact_info.json").write_text(json.dumps({"artifact_filename": quant_filename, "artifact_compressor": artifact_compressor, "quant_bits": quant_bits, "tokenizer_path": args.tokenizer_path, "data_path": args.data_path}, indent=2)) + quant_file_bytes = os.path.getsize(quant_filename) + log0(f"Serialized model {quant_label}: {quant_file_bytes} bytes, total: {quant_file_bytes + len(code.encode('utf-8'))} bytes") + + if args.train_only: + log0("train_only: skipping eval, model saved.") + if distributed: dist.destroy_process_group() + return + + if distributed: + dist.barrier() + quant_blob_disk = Path(quant_filename).read_bytes() + quant_raw_disk = zstandard.ZstdDecompressor().decompress(quant_blob_disk) if artifact_compressor == "zstd" else __import__("zlib").decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(quant_raw_disk), map_location="cpu") + base_model.load_state_dict(dequantize_mixed(quant_state, sd_cpu), strict=True) + torch.cuda.synchronize() + t_qeval = time.perf_counter() + 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_{quant_label}_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_quant_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + lut_args = (base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + if args.eval_stride > 0: + sw_loss, sw_bpb, sw_tokens, sw_bytes = eval_val_sliding(args, base_model, device, val_tokens, *lut_args) + log0(f"sliding_window stride:{args.eval_stride} val_loss:{sw_loss:.4f} val_bpb:{sw_bpb:.4f} tokens:{sw_tokens} bytes:{sw_bytes:.0f}") + log0(f"sliding_window_exact val_loss:{sw_loss:.8f} val_bpb:{sw_bpb:.8f}") + if args.sgd_ttt: + original_param_set = args.sgd_ttt_param_set + original_ttt_opt = args.ttt_optimizer + eval_modes = [("ttt", original_param_set, original_ttt_opt)] + if original_ttt_opt == "adamw": + eval_modes.append(("ttt_sgd", original_param_set, "sgd")) + elif original_ttt_opt == "sgd": + eval_modes.append(("ttt_adamw", original_param_set, "adamw")) + for label, param_set, ttt_opt in eval_modes: + args.sgd_ttt_param_set = param_set + args.ttt_optimizer = ttt_opt + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb, ttt_tokens, ttt_bytes = eval_val_sgd_ttt( + args, base_model, device, val_tokens, *lut_args) + torch.cuda.synchronize() + log0( + f"{label} opt:{ttt_opt} param_set:{param_set} lr:{args.sgd_ttt_lr} legal:{args.ttt_legal} " + f"val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} tokens:{ttt_tokens} time:{1000*(time.perf_counter()-t_ttt):.0f}ms" + ) + log0(f"{label}_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + args.sgd_ttt_param_set = original_param_set + args.ttt_optimizer = original_ttt_opt + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main()