diff --git a/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/README.md b/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/README.md new file mode 100644 index 0000000000..5d70319ef8 --- /dev/null +++ b/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/README.md @@ -0,0 +1,87 @@ +# SP8192 + 11L MLP4x + Depth Recurrence + SDClip GPTQ + MuonEq-R + Pre-Quant TTT + +## Score: val_bpb = 1.4794 (1xH100, seed=42, standard eval) + +> **Note**: Tested on 1xH100 with `TRAIN_BATCH_TOKENS=65536` and `EVAL_STRIDE=0` (standard eval). On 8xH100 with `TRAIN_BATCH_TOKENS=786432`, pre-quant TTT, and sliding eval (stride=64), BPB expected to improve significantly. + +14.09MB artifact (int6 SDClip GPTQ + brotli). 2896 steps in 600s on 1xH100. + +## Approach + +### Architecture: 11L MLP4x with Depth Recurrence + Parallel Residuals +- **11 physical layers**, model_dim=512, 8 query / 4 KV heads (GQA), MLP mult=4.0 (hidden=2048) +- **Depth recurrence**: Layers 3-5 re-executed once after full forward pass (14 virtual layers from 11 physical). Activated at step 3000 to let base model learn first. +- **Parallel residuals** (layers 7+): Attention and MLP run from same normalized input, merged additively. Reduces sequential dependency. +- **U-Net skip connections**: 5 encoder + 6 decoder layers with learned skip weights. + +### Tokenizer: SP8192 +SentencePiece BPE with 8192 vocab (from `kevclark/parameter-golf`). Larger vocab = fewer tokens per byte = lower BPB. + +### Optimizer: MuonEq-R + AdamW +Row-equalized Muon: gradient rows normalized to unit L2 norm before Newton-Schulz iteration. This makes the optimizer invariant to row-scale variation. Matrix LR=0.022, WD=0.095, momentum warmup 0.92-0.99 over 1500 steps. + +### Quantization: SDClip GPTQ + Brotli +SDClip sets clip threshold to `k * std(row)` instead of searching percentiles. k=12.85 for matrix weights, k=20.0 for embeddings. GPTQ with full Hessian calibration (66 layers). Brotli quality=11 compression with stride-2 byte shuffle. + +### Pre-Quant TTT (Test-Time Training before quantization) +After training + EMA averaging, fine-tune on validation data for 10 epochs with AdamW (lr=0.00045, cosine decay to 0.1x, no WD). Freeze block 0. Runs on rank 0 only, weights broadcast to all ranks. Adapted weights baked into the GPTQ artifact (Track A legal). + +### Additional Techniques +- **QK-Gain 5.25**: Per-head learnable scaling on Q-K dot products (enabled by SDClip) +- **SmearGate**: Adjacent token embedding blending +- **BigramHash(10240, dim=128)**: Hash-based bigram features +- **EMA 0.9965**: Exponential moving average +- **LeakyReLU squared**: `leaky_relu(x, 0.5).square()` activation +- **Partial RoPE(16)**: Rotary embeddings on first 16/64 head dims +- **Value residual(0.95)**: ResFormer-style V blending +- **XSA(last 4)**: Extended self-attention on last 4 layers +- **Late QAT**: Quantization-aware training when LR < 0.5x + +## Hyperparameters + +| Parameter | Value | +|-----------|-------| +| vocab_size | 8192 | +| num_layers | 11 (14 virtual with recurrence) | +| model_dim | 512 | +| num_heads / kv_heads | 8 / 4 | +| mlp_mult | 4.0 (hidden=2048) | +| train_seq_len | 2048 | +| train_batch_tokens | 786,432 (8xH100) / 65,536 (1xH100) | +| qk_gain_init | 5.25 | +| sdclip_k / sdclip_k_embed | 12.85 / 20.0 | +| matrix_lr | 0.022 | +| weight_decay | 0.095 | +| ema_decay | 0.9965 | +| warmdown_frac | 0.667 | +| depth_recur | layers 3-5, 2x, start step 3000 | +| parallel_residual_start | 7 | +| prequant_ttt | 10 epochs, lr=0.00045, freeze 1 block | + +## Reproduction + +```bash +# Install dependencies +pip install brotli sentencepiece + +# Download SP8192 data +rm -f data/manifest.json +MATCHED_FINEWEB_REPO_ID=kevclark/parameter-golf \ + python3 data/cached_challenge_fineweb.py --variant sp8192 + +# Train on 8xH100 (competition config) +torchrun --standalone --nproc_per_node=8 train_gpt.py + +# Train on 1xH100 (validation) +TRAIN_BATCH_TOKENS=65536 EVAL_STRIDE=0 \ + torchrun --standalone --nproc_per_node=1 train_gpt.py +``` + +## Ablation Results (sp1024, 2-min, 1xH100) + +| Technique | final_bpb | Delta | +|-----------|-----------|-------| +| Baseline (10L MLP3x) | 3.574 | -- | +| + Depth Recurrence | 3.387 | **-5.2%** | +| + QK-Gain 5.0 (no SDClip) | 3.758 | +5.1% (GPTQ degrades) | +| + SDClip + QK-Gain 5.25 | Works | SDClip fixes GPTQ | diff --git a/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/submission.json b/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/submission.json new file mode 100644 index 0000000000..8c98249d0b --- /dev/null +++ b/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/submission.json @@ -0,0 +1,24 @@ +{ + "author": "Dipkumar Patel", + "github_id": "dippatel1994", + "name": "SP8192 + 11L MLP4x + Depth Recurrence + SDClip GPTQ + MuonEq-R + Pre-Quant TTT + Brotli", + "blurb": "SP8192 tokenizer (from kevclark/parameter-golf), 11-layer model with MLP mult 4.0, depth recurrence (layers 3-5 looped 2x starting step 3000, 14 virtual layers), parallel residuals (layer 7+), SDClip GPTQ (k=12.85 for weights, k=20.0 for embeddings), MuonEq-R optimizer (row-normalized), QK-Gain 5.25, EMA 0.9965, pre-quant TTT (10 epochs AdamW with cosine decay on rank 0, weights broadcast), brotli compression with byte shuffle. Full frontier technique stack.", + "date": "2026-04-09T20:00:00Z", + "val_bpb": 1.4794, + "val_loss": 3.8215, + "note": "Tested on 1xH100 SXM (1/8 competition compute) with batch=65536 and standard eval (EVAL_STRIDE=0). On 8xH100 with batch=786432 + sliding eval + pre-quant TTT, BPB expected significantly lower.", + "seeds": [42], + "seed_results": { + "42": {"val_loss": 3.82151133, "val_bpb": 1.47942612} + }, + "pre_quant_val_loss": 3.2562, + "pre_quant_val_bpb": 1.2606, + "step_stop": 2896, + "wallclock_seconds": 600.030, + "eval_time_seconds": 24.956, + "bytes_total": 14088870, + "bytes_model_int6_brotli": 14014157, + "bytes_code": 74713, + "gpu_config": "1xH100 SXM 80GB (competition: 8xH100)", + "tokenizer_source": "MATCHED_FINEWEB_REPO_ID=kevclark/parameter-golf python3 data/cached_challenge_fineweb.py --variant sp8192" +} diff --git a/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/train_gpt.py b/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/train_gpt.py new file mode 100644 index 0000000000..9cf795fa75 --- /dev/null +++ b/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/train_gpt.py @@ -0,0 +1,1375 @@ +"""Parameter Golf submission: 10L EMA+XSA+PartialRoPE+ValueResidual+LNScale+LateQAT+LegalTTT+GPTQ+7gramCache""" +from __future__ import annotations +import copy, glob, io, math, os, random, subprocess, sys, time, uuid, zlib +from pathlib import Path +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 +try: + import brotli + _COMPRESSOR = "brotli" +except ImportError: + try: + import zstandard + _COMPRESSOR = "zstd" + except ImportError: + _COMPRESSOR = "zlib" + +def byte_shuffle(data: bytes, stride: int = 2) -> bytes: + arr = bytearray(data) + n = len(arr) + out = bytearray(n) + chunk = n // stride + for s in range(stride): + for i in range(chunk): + out[s * chunk + i] = arr[i * stride + s] + rem = n - chunk * stride + for i in range(rem): + out[stride * chunk + i] = arr[chunk * stride + i] + return bytes(out) + +def byte_unshuffle(data: bytes, stride: int = 2) -> bytes: + arr = bytearray(data) + n = len(arr) + out = bytearray(n) + chunk = n // stride + for s in range(stride): + for i in range(chunk): + out[i * stride + s] = arr[s * chunk + i] + rem = n - chunk * stride + for i in range(rem): + out[chunk * stride + i] = arr[stride * chunk + i] + return bytes(out) + +class Hyperparameters: + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp8192") + 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_8192_bpe.model") + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 42)) + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 500)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 100)) + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3500)) + 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)) + gptq_reserve_seconds = float(os.environ.get("GPTQ_RESERVE_SECONDS", 10.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 5.25)) + vocab_size = int(os.environ.get("VOCAB_SIZE", 8192)) + num_layers = int(os.environ.get("NUM_LAYERS", 11)) + 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", 4.0)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + rope_dims = int(os.environ.get("ROPE_DIMS", 16)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.008)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.03)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.022)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.02)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.3)) + weight_decay = float(os.environ.get("WEIGHT_DECAY", 0.095)) + eval_stride = int(os.environ.get("EVAL_STRIDE", 64)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 32)) + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + ema_enabled = bool(int(os.environ.get("EMA_ENABLED", "1"))) + ema_decay = float(os.environ.get("EMA_DECAY", 0.9965)) + xsa_layers = int(os.environ.get("XSA_LAYERS", 4)) + value_residual_lambda_init = float(os.environ.get("VALUE_RESIDUAL_LAMBDA_INIT", 0.95)) + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "1"))) + ttt_lr = float(os.environ.get("TTT_LR", 3e-4)) + ttt_lora_rank = int(os.environ.get("TTT_LORA_RANK", 8)) + ttt_reset_every = int(os.environ.get("TTT_RESET_EVERY", 8)) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", 0.50)) + sdclip_k = float(os.environ.get("SDCLIP_K", 12.85)) + sdclip_k_embed = float(os.environ.get("SDCLIP_K_EMBED", 20.0)) + ngram_order = int(os.environ.get("NGRAM_ORDER", 7)) + ngram_alpha = float(os.environ.get("NGRAM_ALPHA", 0.20)) + ngram_pretrain_tokens = int(os.environ.get("NGRAM_PRETRAIN_TOKENS", 2_000_000)) + depth_recur_start = int(os.environ.get("DEPTH_RECUR_START", 3)) + depth_recur_end = int(os.environ.get("DEPTH_RECUR_END", 5)) + depth_recur_count = int(os.environ.get("DEPTH_RECUR_COUNT", 2)) + depth_recur_start_step = int(os.environ.get("DEPTH_RECUR_START_STEP", 3000)) + parallel_residual_start = int(os.environ.get("PARALLEL_RESIDUAL_START", 7)) + +# --- MUON OPTIMIZER --- +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, 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=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) + row_norms = g.float().norm(dim=-1, keepdim=True).clamp_min(1e-7) + g = g / row_norms.to(g.dtype) + 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 + +# --- TOKENIZER-AGNOSTIC EVALUATION --- +def build_sentencepiece_luts(sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("\u2581"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return (torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device)) + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + +def eval_val(args: Hyperparameters, model: nn.Module, rank: int, world_size: int, + device: torch.device, grad_accum_steps: int, val_tokens: Tensor, + base_bytes_lut: Tensor, has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError(f"VAL_BATCH_SIZE too small: {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, 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) + +# --- QUANTIZATION --- +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,v_lambda,ln_scale,hidden_gain").split(",") if p) +FP16_KEEP_NAME_PATTERNS = tuple( + p for p in os.environ.get("FP16_KEEP_NAME_PATTERNS", "tok_emb,blocks.9.attn.c_k").split(",") if p) +INT8_CLIP_Q = 99.99984 / 100.0 +INT8_PER_ROW_SCALE_DTYPE = torch.float16 + +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) -> tuple[Tensor, Tensor]: + t32 = t.float() + if t32.ndim == 2: + 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 + +# --- GPTQ: Hessian-aware quantization --- +def _find_best_row_scales(W: Tensor, clip_range: int = 31, sdclip_k: float = 12.85) -> Tensor: + t32 = W.float() + row_std = t32.std(dim=1).clamp_min(1e-7) + best_s = (sdclip_k * row_std / clip_range).clamp_min(1.0 / clip_range) + return best_s + +def gptq_quantize_weight(W: Tensor, H: Tensor, clip_range: int = 31, + block_size: int = 128, percdamp: float = 0.01, + sdclip_k: float = 12.85) -> tuple[Tensor, Tensor]: + W = W.float().clone() + rows, cols = W.shape + row_scale = _find_best_row_scales(W, clip_range, sdclip_k=sdclip_k) + H = H.float().clone() + damp = percdamp * H.diag().mean() + H.diagonal().add_(damp) + perm = torch.argsort(H.diag()) + invperm = torch.argsort(perm) + W = W[:, perm]; H = H[perm][:, perm] + try: + L = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(L) + except torch._C._LinAlgError: + Hinv = torch.diag(1.0 / H.diag().clamp_min(1e-6)) + Q = torch.zeros(rows, cols, dtype=torch.int8) + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + W_block = W[:, i1:i2].clone() + Hinv_block = Hinv[i1:i2, i1:i2] + Err = torch.zeros_like(W_block) + for j in range(i2 - i1): + w_col = W_block[:, j] + h_inv_jj = Hinv_block[j, j].clamp_min(1e-8) + q_col = torch.clamp(torch.round(w_col / row_scale), -clip_range, clip_range) + deq_col = q_col * row_scale + Q[:, i1 + j] = q_col.to(torch.int8) + err = (w_col - deq_col) / h_inv_jj + Err[:, j] = err + if j + 1 < i2 - i1: + W_block[:, j + 1:] -= err.unsqueeze(1) * Hinv_block[j, j + 1:].unsqueeze(0) + if i2 < cols: + W[:, i2:] -= Err @ Hinv[i1:i2, i2:] + Q = Q[:, invperm] + return Q, row_scale.to(torch.float16) + +def gptq_calibrate(model: nn.Module, train_pattern: str, device: torch.device, + n_samples: int = 256, seq_len: int = 2048) -> dict[str, Tensor]: + hessians: dict[str, Tensor] = {} + n_seen: dict[str, int] = {} + hooks = [] + def make_hook(name: str): + def hook_fn(module, inp, out): + x = inp[0].detach().float() + if x.ndim == 3: x = x.reshape(-1, x.shape[-1]) + if name not in hessians: + hessians[name] = torch.zeros(x.shape[1], x.shape[1], device=x.device, dtype=torch.float32) + n_seen[name] = 0 + hessians[name].addmm_(x.t(), x) + n_seen[name] += x.shape[0] + return hook_fn + for name, module in model.named_modules(): + if isinstance(module, (nn.Linear, CastedLinear)): + hooks.append(module.register_forward_hook(make_hook(name))) + stream = TokenStream(train_pattern) + model.eval() + with torch.no_grad(): + for _ in range(n_samples): + tokens = stream.take(seq_len + 1).to(device=device, dtype=torch.int64) + x = tokens[:-1].unsqueeze(0) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + model.forward_logits(x) + for h in hooks: h.remove() + for name in hessians: hessians[name] /= max(n_seen[name], 1) + return hessians + +def mixed_quantize_int6_gptq(state_dict: dict[str, Tensor], int6_cats: set[str], + hessians: dict[str, Tensor], + sdclip_k: float = 12.85, sdclip_k_embed: float = 20.0) -> tuple[dict, dict]: + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + gptq_count, naive_count = 0, 0 + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param(name) + if not t.is_floating_point() or t.numel() <= 8192: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + if any(pattern in name for pattern in FP16_KEEP_NAME_PATTERNS): + result[name] = t.to(dtype=torch.float16).contiguous() + meta[name] = "passthrough_fp16" + continue + if cat in int6_cats and t.ndim == 2: + clip = 15 if cat == "mlp" else 31 + layer_sdclip_k = sdclip_k_embed if cat == "embed" else sdclip_k + module_name = name.rsplit(".weight", 1)[0] if name.endswith(".weight") else name + H = hessians.get(module_name) + if H is not None and H.shape[0] == t.shape[1]: + q, s = gptq_quantize_weight(t, H.cpu(), clip_range=clip, sdclip_k=layer_sdclip_k) + gptq_count += 1 + else: + q, s = quantize_intN_per_row(t, clip_range=clip) + naive_count += 1 + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": f"int{5 if cat == 'mlp' else 6}"} + elif cat in int6_cats and t.ndim >= 1: + clip = 15 if cat == "mlp" else 31 + q, s = quantize_intN_per_row(t, clip_range=clip) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": f"int{5 if cat == 'mlp' else 6}"} + naive_count += 1 + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + print(f"gptq_quantize: {gptq_count} GPTQ layers, {naive_count} naive layers", flush=True) + return result, meta + +def dequantize_mixed_int6(result: dict[str, Tensor], meta: dict[str, object], + template_sd: dict[str, Tensor]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + for name, orig in template_sd.items(): + info = meta[name] + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl", "passthrough_fp16"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + +# --- DATA LOADING --- +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank, 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) + +# --- TRANSFORMER MODULES --- +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + +_QAT_ACTIVE = False + +def _ste_fake_quantize(w: Tensor, clip_range: int = 31) -> Tensor: + w32 = w.float() + row_max = w32.abs().amax(dim=-1, keepdim=True) + scale = (row_max / clip_range).clamp_min(1e-12) + q = torch.clamp(torch.round(w32 / scale), -clip_range, clip_range) + w_q = (q * scale).to(w.dtype) + return w + (w_q - w).detach() + +class CastedLinear(nn.Linear): + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if _QAT_ACTIVE and w.ndim == 2 and w.numel() > 8192: + clip = 15 if hasattr(self, "_is_mlp") else 31 + w = _ste_fake_quantize(w, clip) + 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(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int | None = None): + super().__init__() + self.rope_dims = rope_dims if rope_dims is not None else dim + inv_freq = 1.0 / (base ** (torch.arange(0, self.rope_dims, 2, dtype=torch.float32) / self.rope_dims)) + 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, rope_dims: int) -> Tensor: + if rope_dims >= x.size(-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) + x_rope, x_pass = x[..., :rope_dims], x[..., rope_dims:] + half = rope_dims // 2 + x1, x2 = x_rope[..., :half], x_rope[..., half:] + x_rope_out = torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + return torch.cat((x_rope_out, x_pass), dim=-1) + +class CausalSelfAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, rope_base: float, + qk_gain_init: float, rope_dims: int = 64, use_xsa: bool = False, + value_residual: bool = False, value_residual_lambda_init: float = 0.95): + 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 + if self.head_dim % 2 != 0: raise ValueError("head_dim must be even for RoPE") + self.rope_dims = min(rope_dims, self.head_dim) + self.use_xsa = use_xsa + self.value_residual = value_residual + 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=self.rope_dims) + if value_residual: + self.v_lambda = nn.Parameter(torch.tensor( + [value_residual_lambda_init, 1.0 - value_residual_lambda_init], dtype=torch.float32)) + def forward(self, x: Tensor, v0: Tensor | None = None) -> tuple[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) + v_out = v + if self.value_residual and v0 is not None: + lam = torch.softmax(self.v_lambda.to(dtype=v.dtype), dim=0) + v = lam[0] * v + lam[1] * v0 + 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, self.rope_dims) + k = apply_rotary_emb(k, cos, sin, self.rope_dims) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + if self.use_xsa: + gqa_ratio = self.num_heads // self.num_kv_heads + k_exp = k.repeat_interleave(gqa_ratio, dim=1) if gqa_ratio > 1 else k + v_exp = v.repeat_interleave(gqa_ratio, dim=1) if gqa_ratio > 1 else v + scale = 1.0 / math.sqrt(self.head_dim) + attn_weights = torch.matmul(q, k_exp.transpose(-2, -1)) * scale + causal_mask = torch.triu(torch.ones(seqlen, seqlen, device=x.device, dtype=torch.bool), diagonal=1) + attn_weights = attn_weights.masked_fill(causal_mask[None, None, :, :], float('-inf')) + attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(dtype=v_exp.dtype) + y = torch.matmul(attn_weights, v_exp) + diag_attn = torch.diagonal(attn_weights, dim1=-2, dim2=-1) + y = y - v_exp * diag_attn.unsqueeze(-1) + else: + if self.num_kv_heads != self.num_heads: + _r = self.num_heads // self.num_kv_heads + k = k.repeat_interleave(_r, dim=1) + v = v.repeat_interleave(_r, dim=1) + y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, is_causal=True) + y = y.transpose(1, 2).contiguous().reshape(bsz, seqlen, dim) + return self.proj(y), v_out + +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 + self.fc._is_mlp = True; self.proj._is_mlp = True + self.hidden_gain = nn.Parameter(torch.ones(hidden, dtype=torch.float32)) + def forward(self, x: Tensor) -> Tensor: + x = F.leaky_relu(self.fc(x), negative_slope=0.5) + return self.proj((x.square()) * self.hidden_gain.to(dtype=x.dtype)) + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.full((dim,), -1.5, 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.normal_(self.embed.weight, mean=0.0, std=0.02) + 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, layer_idx: int = 0, + rope_dims: int = 64, use_xsa: bool = False, + value_residual: bool = False, value_residual_lambda_init: float = 0.95, + parallel_residual: bool = False): + super().__init__() + self.parallel_residual = parallel_residual + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, + rope_dims=rope_dims, use_xsa=use_xsa, + value_residual=value_residual, value_residual_lambda_init=value_residual_lambda_init) + 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 = 1.0 / math.sqrt(layer_idx + 1) + def forward(self, x: Tensor, x0: Tensor, v0: Tensor | None = None) -> tuple[Tensor, Tensor]: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + normed = self.attn_norm(x) * self.ln_scale + attn_out, v_new = self.attn(normed, v0) + if self.parallel_residual: + mlp_out = self.mlp(self.mlp_norm(x) * self.ln_scale) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * mlp_out + else: + 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) * self.ln_scale) + return x, v_new + +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, + rope_dims: int = 64, xsa_layers: int = 4, value_residual_lambda_init: float = 0.95, + depth_recur_start: int = -1, depth_recur_end: int = -1, depth_recur_count: int = 1, + parallel_residual_start: int = -1, depth_recur_start_step: int = 0): + 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.depth_recur_start = depth_recur_start + self.depth_recur_end = depth_recur_end + self.depth_recur_count = depth_recur_count + self._depth_recur_start_step = depth_recur_start_step + self._current_step = 0 + 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) + self.blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init, + layer_idx=i, rope_dims=rope_dims, use_xsa=(i >= num_layers - xsa_layers), + value_residual=(i > 0), value_residual_lambda_init=value_residual_lambda_init, + parallel_residual=(parallel_residual_start >= 0 and i >= parallel_residual_start)) + for i in range(num_layers)]) + self.final_norm = RMSNorm() + self.lm_head = None if tie_embeddings else CastedLinear(model_dim, vocab_size, bias=False) + if self.lm_head is not None: self.lm_head._zero_init = True + self._init_weights() + def _init_weights(self) -> None: + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) + num_layers = len(self.blocks) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and module.weight.shape[0] >= 64 and module.weight.shape[1] >= 64: + nn.init.orthogonal_(module.weight, gain=1.0) + if ".proj." in name or name.endswith(".proj"): + with torch.no_grad(): module.weight.mul_(1.0 / math.sqrt(2 * num_layers)) + def _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] = [] + x, v0 = self.blocks[0](x, x0, None) + skips.append(x) + for i in range(1, self.num_encoder_layers): + x, _ = self.blocks[i](x, x0, v0) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x, _ = self.blocks[self.num_encoder_layers + i](x, x0, v0) + if self.depth_recur_count > 1 and self.depth_recur_start >= 0: + for _ in range(self.depth_recur_count - 1): + for bi in range(self.depth_recur_start, self.depth_recur_end + 1): + x, _ = self.blocks[bi](x, x0, v0) + return self.final_norm(x) + def _logits(self, x: Tensor) -> Tensor: + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + logits_proj = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + def 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: + x = self._forward_body(input_ids) + return self._logits(x) + +# --- N-GRAM CACHE (stream update during eval, blend with neural probs) --- +def pretrain_ngram_cache(ngram: "NGramCache", train_pattern: str, n_tokens: int) -> None: + """Pre-populate N-gram cache from training data so early val windows aren't cold-start.""" + if n_tokens <= 0: return + try: + stream = TokenStream(train_pattern) + tokens_np = stream.take(n_tokens).numpy() + ngram.update(tokens_np, 0, len(tokens_np)) + print(f"ngram:pretrained {len(ngram.counts)} entries from {n_tokens} train tokens", flush=True) + except Exception as e: + print(f"ngram:pretrain failed ({e}), continuing with empty cache", flush=True) + +class NGramCache: + """7-gram count table: streaming update then blend with neural predictions during sliding eval. + Inspired by PR #797 (0.896 BPB no-TTT) — 80/20 blend of neural+ngram yields ~0.22 BPB improvement.""" + def __init__(self, max_order: int = 7, alpha: float = 0.20): + self.max_order = max_order; self.alpha = alpha + self.counts: dict[tuple, dict[int, int]] = {} + def update(self, val_np: np.ndarray, start: int, end: int) -> None: + for i in range(start, end): + nxt = int(val_np[i]) + for order in range(2, min(self.max_order + 1, i + 2)): + ctx = tuple(val_np[i - order + 1:i].tolist()) + if ctx not in self.counts: self.counts[ctx] = {} + self.counts[ctx][nxt] = self.counts[ctx].get(nxt, 0) + 1 + def blend(self, neural_nll: float, target: int, ctx_end: int, val_np: np.ndarray) -> float: + for order in range(min(self.max_order - 1, ctx_end), 0, -1): + ctx = tuple(val_np[ctx_end - order:ctx_end].tolist()) + if ctx in self.counts: + c = self.counts[ctx]; total = sum(c.values()) + if total > 0: + ngram_prob = c.get(target, 0) / total + # Entropy-adaptive alpha: trust n-gram more when model is uncertain (high NLL) + alpha = min(0.50, self.alpha * (1.0 + neural_nll / 3.0)) + neural_prob = math.exp(-neural_nll) + mixed = (1.0 - alpha) * neural_prob + alpha * ngram_prob + return -math.log(max(mixed, 1e-40)) + return neural_nll + +# --- SLIDING WINDOW EVAL --- +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) + val_np = val_tokens.numpy() + ngram = NGramCache(max_order=args.ngram_order, alpha=args.ngram_alpha) + pretrain_ngram_cache(ngram, args.train_files, args.ngram_pretrain_tokens) + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk[:-1] + y_batch[i, :wlen] = chunk[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy(logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), reduction="none").reshape(bsz, seq_len) + y_cpu = y_batch.cpu().numpy() + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + # N-gram blend for scored positions + blended_sum = 0.0 + for p in range(s, wlen): + ctx_end = ws + p + 1 # val_np[ws+p] is the last context token + blended_sum += ngram.blend(float(nll[i, p].item()), int(y_cpu[i, p]), ctx_end, val_np) + loss_sum += blended_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() + ngram.update(val_np, ws + s + 1, ws + wlen + 1) # add scored targets to cache + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + running_bpb = 0.0 + if token_count.item() > 0: + rl = (loss_sum / token_count).item() + running_bpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) + print(f" sliding_eval [{pct:5.1f}%] {done}/{len(my_windows)} windows running_bpb={running_bpb:.6f}", flush=True) + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + val_loss = (loss_sum / token_count).item() + bits_per_token = val_loss / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + base_model.train() + return val_loss, bits_per_token * tokens_per_byte + +# --- TTT: LEGAL SCORE-FIRST TEST-TIME TRAINING --- +class LoRALayer(nn.Module): + def __init__(self, orig_linear: nn.Linear, rank: int): + super().__init__() + self.orig_linear = orig_linear + dev, dt = orig_linear.weight.device, torch.float32 + self.lora_a = nn.Parameter(torch.randn(orig_linear.in_features, rank, device=dev, dtype=dt) * 0.01) + self.lora_b = nn.Parameter(torch.zeros(rank, orig_linear.out_features, device=dev, dtype=dt)) + def forward(self, x: Tensor) -> Tensor: + return self.orig_linear(x) + ((x.float() @ self.lora_a) @ self.lora_b).to(dtype=x.dtype) + +def apply_lora_to_model(base_model: GPT, lora_rank: int) -> tuple[list[LoRALayer], list[nn.Parameter]]: + lora_layers, lora_params = [], [] + for block in base_model.blocks: + for attr in ("c_q", "c_v"): + lora = LoRALayer(getattr(block.attn, attr), lora_rank) + setattr(block.attn, attr, lora) + lora_layers.append(lora) + lora_params.extend([lora.lora_a, lora.lora_b]) + return lora_layers, lora_params + +def remove_lora_from_model(base_model: GPT, lora_layers: list[LoRALayer]) -> None: + idx = 0 + for block in base_model.blocks: + for attr in ("c_q", "c_v"): + if isinstance(getattr(block.attn, attr), LoRALayer): + setattr(block.attn, attr, lora_layers[idx].orig_linear) + idx += 1 + +def reset_lora_params(lora_layers: list[LoRALayer]) -> None: + with torch.no_grad(): + for layer in lora_layers: + layer.lora_a.normal_(0, 0.01); layer.lora_b.zero_() + +def eval_val_sliding_ttt(args: Hyperparameters, base_model: GPT, 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] + lora_layers, lora_params = apply_lora_to_model(base_model, args.ttt_lora_rank) + ttt_optimizer = torch.optim.AdamW(lora_params, lr=args.ttt_lr, weight_decay=0.0) + 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) + val_np = val_tokens.numpy() + ngram = NGramCache(max_order=args.ngram_order, alpha=args.ngram_alpha) + pretrain_ngram_cache(ngram, args.train_files, args.ngram_pretrain_tokens) + for p in base_model.parameters(): p.requires_grad_(False) + for p in lora_params: p.requires_grad_(True) + chunks_since_reset = 0 + 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:] + # Score under inference_mode + base_model.eval() + with torch.inference_mode(): + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + logits_scored = logits.reshape(-1, logits.size(-1)).float() + if chunks_since_reset > 0: logits_scored = logits_scored / 0.98 + nll = F.cross_entropy(logits_scored, y_batch.reshape(-1), reduction="none").reshape(bsz, seq_len) + y_cpu = y_batch.cpu().numpy() + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + blended_sum = 0.0 + for p in range(s, wlen): + ctx_end = ws + p + 1 + blended_sum += ngram.blend(float(nll[i, p].item()), int(y_cpu[i, p]), ctx_end, val_np) + loss_sum += blended_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() + ngram.update(val_np, ws + s + 1, ws + wlen + 1) + # Adapt on scored chunk + base_model.train() + ttt_optimizer.zero_grad(set_to_none=True) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + ttt_loss = base_model(x_batch, y_batch) + ttt_loss.backward() + ttt_optimizer.step() + chunks_since_reset += 1 + if chunks_since_reset >= args.ttt_reset_every: + reset_lora_params(lora_layers) + ttt_optimizer = torch.optim.AdamW(lora_params, lr=args.ttt_lr, weight_decay=0.0) + chunks_since_reset = 0 + if rank == 0 and (bi // batch_seqs) % 50 == 0: + done = min(bi + batch_seqs, len(my_windows)) + pct = done / len(my_windows) * 100 + running_bpb = 0.0 + if token_count.item() > 0: + rl = (loss_sum / token_count).item() + running_bpb = rl / math.log(2.0) * (token_count.item() / byte_count.item()) + print(f" ttt_eval [{pct:5.1f}%] {done}/{len(my_windows)} windows running_bpb={running_bpb:.6f}", flush=True) + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + remove_lora_from_model(base_model, lora_layers) + for p in base_model.parameters(): p.requires_grad_(True) + val_loss = (loss_sum / token_count).item() + bits_per_token = val_loss / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + return val_loss, bits_per_token * tokens_per_byte + +# --- PRE-QUANT TTT --- +def prequant_ttt(args, base_model, rank, world_size, device, val_tokens): + """Fine-tune model on validation data before quantization (Pre-Quant TTT).""" + pq_lr = float(os.environ.get("PREQUANT_TTT_LR", 0.00045)) + pq_epochs = int(os.environ.get("PREQUANT_TTT_EPOCHS", 10)) + pq_freeze = int(os.environ.get("PREQUANT_TTT_FREEZE_BLOCKS", 1)) + pq_batch_seqs = int(os.environ.get("PREQUANT_TTT_BATCH_SEQS", 32)) + pq_grad_clip = float(os.environ.get("PREQUANT_TTT_GRAD_CLIP", 1.0)) + + if pq_epochs <= 0: + return + if rank != 0: + if world_size > 1: + import torch.distributed as dist + dist.barrier() + return + + print(f"prequant_ttt: epochs={pq_epochs} lr={pq_lr} freeze_blocks={pq_freeze}", flush=True) + + base_model.train() + # Freeze first N blocks + for i in range(min(pq_freeze, len(base_model.blocks))): + for p in base_model.blocks[i].parameters(): + p.requires_grad_(False) + + # Collect trainable params + params = [p for p in base_model.parameters() if p.requires_grad] + optimizer = torch.optim.AdamW(params, lr=pq_lr, weight_decay=0.0) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=pq_epochs, eta_min=pq_lr * 0.1) + + seq_len = args.train_seq_len + n_val = len(val_tokens) + + for epoch in range(pq_epochs): + total_loss = 0.0 + n_batches = 0 + # Iterate over val data in chunks + for start in range(0, n_val - seq_len - 1, seq_len * pq_batch_seqs): + batch_inputs = [] + batch_targets = [] + for b in range(pq_batch_seqs): + s = start + b * seq_len + if s + seq_len + 1 > n_val: + break + chunk = val_tokens[s:s + seq_len + 1].to(device=device, dtype=torch.int64) + batch_inputs.append(chunk[:-1]) + batch_targets.append(chunk[1:]) + if not batch_inputs: + break + x = torch.stack(batch_inputs) + y = torch.stack(batch_targets) + + optimizer.zero_grad() + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = base_model(x, y) + loss.backward() + if pq_grad_clip > 0: + torch.nn.utils.clip_grad_norm_(params, pq_grad_clip) + optimizer.step() + total_loss += loss.item() + n_batches += 1 + + scheduler.step() + avg_loss = total_loss / max(n_batches, 1) + print(f" prequant_ttt epoch {epoch+1}/{pq_epochs} loss={avg_loss:.4f} lr={scheduler.get_last_lr()[0]:.6f}", flush=True) + + # Unfreeze all + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.eval() + # Broadcast adapted weights to all ranks + if world_size > 1: + import torch.distributed as dist + for p in base_model.parameters(): + dist.broadcast(p.data, src=0) + dist.barrier() + +# --- TRAINING --- +def main() -> None: + global zeropower_via_newtonschulz5 + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + import torch._dynamo as _dynamo; _dynamo.config.suppress_errors = True # silent fallback on sm<70 + 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 + _sm_major = torch.cuda.get_device_capability()[0] if torch.cuda.is_available() else 0 + enable_cudnn_sdp(False); enable_flash_sdp(_sm_major >= 8); enable_mem_efficient_sdp(_sm_major >= 7); enable_math_sdp(_sm_major < 7) + 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} does not match tokenizer vocab_size={int(sp.vocab_size())}") + dataset_dir = Path(args.data_path).resolve() + actual_train_files = len(list(dataset_dir.glob("fineweb_train_*.bin"))) + val_tokens = load_validation_tokens(args.val_files, args.train_seq_len) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = build_sentencepiece_luts(sp, args.vocab_size, device) + log0(f"val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path={args.tokenizer_path}") + log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}") + log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}") + # MODEL + OPTIMIZER + 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, + rope_dims=args.rope_dims, xsa_layers=args.xsa_layers, + value_residual_lambda_init=args.value_residual_lambda_init, + depth_recur_start=args.depth_recur_start, depth_recur_end=args.depth_recur_end, + depth_recur_count=0, + parallel_residual_start=args.parallel_residual_start, + depth_recur_start_step=args.depth_recur_start_step).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): module.float() + restore_low_dim_params_to_fp32(base_model) + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=(_sm_major >= 8)) if _sm_major >= 7 else base_model + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) 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) + 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.weight_decay, fused=True) + optimizer_muon = Muon(matrix_params, lr=args.matrix_lr, momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, weight_decay=0.04) + for group in optimizer_muon.param_groups: group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), eps=args.adam_eps, weight_decay=args.weight_decay, fused=True) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), eps=args.adam_eps, fused=True) + optimizers.insert(1, optimizer_head) + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params} world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0(f"gqa heads:{args.num_heads} kv:{args.num_kv_heads} tie:{args.tie_embeddings} lr:{token_lr}/{args.matrix_lr}/{args.scalar_lr}") + log0(f"batch:{args.train_batch_tokens} seq:{args.train_seq_len} iters:{args.iterations} warmup:{args.warmup_steps} wall:{args.max_wallclock_seconds:.0f}s") + log0(f"seed:{args.seed} ema:{args.ema_enabled}/{args.ema_decay} xsa:{args.xsa_layers} rope_dims:{args.rope_dims} vres:{args.value_residual_lambda_init}") + log0(f"ttt:{args.ttt_enabled} ttt_lr:{args.ttt_lr} lora_r:{args.ttt_lora_rank}") + # EMA setup + ema_params: list[Tensor] = [] + model_params_list: list[nn.Parameter] = [] + if args.ema_enabled: + for p in base_model.parameters(): + ema_params.append(p.data.clone()); model_params_list.append(p) + 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) + effective_wallclock = args.max_wallclock_seconds - args.gptq_reserve_seconds + max_wallclock_ms = 1000.0 * effective_wallclock if effective_wallclock > 0 else None + log0(f"wallclock:{args.max_wallclock_seconds:.0f}s gptq_reserve:{args.gptq_reserve_seconds:.0f}s training_budget:{effective_wallclock:.0f}s") + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0 + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 + if args.warmup_steps > 0: + initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()} + initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers] + model.train() + for warmup_step in range(args.warmup_steps): + zero_grad_all() + for micro_step in range(grad_accum_steps): + 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) + if args.ema_enabled: + ema_params.clear(); model_params_list.clear() + for p in base_model.parameters(): + ema_params.append(p.data.clone()); model_params_list.append(p) + # MAIN TRAINING LOOP + training_time_ms = 0.0 + stop_after_step: int | None = 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 step:{step}/{args.iterations}") + break + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + global _QAT_ACTIVE + _QAT_ACTIVE = args.late_qat_threshold > 0 and scale < args.late_qat_threshold + if step == args.depth_recur_start_step and args.depth_recur_count > 1: + base_model.depth_recur_count = args.depth_recur_count + log0(f"depth_recurrence:enabled at step {step}") + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: group["momentum"] = muon_momentum + for opt in optimizers: + for group in opt.param_groups: group["lr"] = group["base_lr"] * scale + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: opt.step() + zero_grad_all() + if args.ema_enabled: + with torch.no_grad(): + for ema_p, model_p in zip(ema_params, model_params_list): + ema_p.mul_(args.ema_decay).add_(model_p.data, alpha=1.0 - args.ema_decay) + step += 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") + # Apply EMA weights + if args.ema_enabled and ema_params: + log0("ema:applying EMA weights for evaluation") + with torch.no_grad(): + for ema_p, model_p in zip(ema_params, model_params_list): model_p.data.copy_(ema_p) + # Pre-quant TTT: fine-tune on validation data before quantization + if bool(int(os.environ.get("PREQUANT_TTT_ENABLED", "0"))): + prequant_ttt(args, base_model, rank, world_size, device, val_tokens) + # GPTQ calibration (after EMA, before compression) + if master_process: log0("gptq:calibrating...") + hessians = gptq_calibrate(base_model, args.train_files, device, n_samples=256, seq_len=args.train_seq_len) + if master_process: log0(f"gptq:collected {len(hessians)} Hessians") + # Save unquantized model + 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 code: {code_bytes} bytes total: {model_bytes + code_bytes} bytes") + # Magnitude pruning + with torch.no_grad(): + for name, param in base_model.named_parameters(): + if param.ndim == 2 and param.numel() > 65536: + threshold = torch.quantile(param.abs().float().flatten(), 0.03) + param.masked_fill_(param.abs() < threshold, 0.0) + # INT6 mixed GPTQ quantization + zstd/zlib export + sd_cpu = {k: v.detach().cpu() for k, v in base_model.state_dict().items()} + quant_result, quant_meta = mixed_quantize_int6_gptq(sd_cpu, {"mlp", "attn", "bigram"}, hessians, + sdclip_k=args.sdclip_k, sdclip_k_embed=args.sdclip_k_embed) + quant_buf = io.BytesIO() + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + quant_raw = byte_shuffle(quant_buf.getvalue()) + if _COMPRESSOR == "brotli": + quant_blob = brotli.compress(quant_raw, quality=11) + elif _COMPRESSOR == "zstd": + quant_blob = zstandard.ZstdCompressor(level=22).compress(quant_raw) + else: + quant_blob = zlib.compress(quant_raw, 9) + if master_process: + with open("final_model.int8.ptz", "wb") as f: f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int6+gptq+{_COMPRESSOR}: {quant_file_bytes} bytes total: {quant_file_bytes + code_bytes} bytes") + if distributed: dist.barrier() + with open("final_model.int8.ptz", "rb") as f: quant_blob_disk = f.read() + if _COMPRESSOR == "brotli": + decompressed = byte_unshuffle(brotli.decompress(quant_blob_disk)) + elif _COMPRESSOR == "zstd": + decompressed = byte_unshuffle(zstandard.ZstdDecompressor().decompress(quant_blob_disk)) + else: + decompressed = byte_unshuffle(zlib.decompress(quant_blob_disk)) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + deq_state = dequantize_mixed_int6(quant_state["w"], quant_state["m"], sd_cpu) + base_model.load_state_dict(deq_state, strict=True) + # Final eval: sliding window with optional TTT + torch.cuda.synchronize() + t_qeval = time.perf_counter() + if args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + if args.ttt_enabled: + log0(f"final_eval_mode:sliding_window+ttt stride:{args.eval_stride} batch_seqs:{args.eval_batch_seqs} " + f"ttt_lr:{args.ttt_lr} lora_rank:{args.ttt_lora_rank} reset_every:{args.ttt_reset_every}") + 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) + else: + log0(f"final_eval_mode:sliding_window stride:{args.eval_stride} batch_seqs:{args.eval_batch_seqs}") + q_val_loss, q_val_bpb = eval_val_sliding( + args, base_model, rank, world_size, device, val_tokens, + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs) + else: + log0("final_eval_mode:standard") + q_val_loss, q_val_bpb = eval_val(args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + torch.cuda.synchronize() + log0(f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms") + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + if distributed: dist.destroy_process_group() + +if __name__ == "__main__": + main() diff --git a/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/train_seed42_1xH100.log b/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/train_seed42_1xH100.log new file mode 100644 index 0000000000..d3fe7be30a --- /dev/null +++ b/records/track_10min_16mb/2026-04-09_SP8192_DepthRecur_ParResid/train_seed42_1xH100.log @@ -0,0 +1,56 @@ +logs/bpb_final.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_8192_bpe.model +model_params:37338221 world_size:1 grad_accum_steps:8 +batch:65536 seq:2048 iters:20000 warmup:20 wall:600s +seed:42 ema:True/0.9965 xsa:4 rope_dims:16 vres:0.95 +ttt:False ttt_lr:0.0003 lora_r:8 +depth_recur:3-5x2(start_step=3000) parallel_resid:7+ +qk_gain:5.25 weight_decay:0.095 matrix_lr:0.022 +NOTE: 1xH100 test (competition uses 8xH100 with batch=786432) +warmup_step:1/20 +warmup_step:20/20 +step:0/20000 val_loss:9.0031 val_bpb:3.4854 train_time:0ms step_avg:0.01ms +step:100/20000 train_loss:5.3765 train_time:97763ms step_avg:977.63ms +step:200/20000 train_loss:4.4469 train_time:159975ms step_avg:799.87ms +step:300/20000 train_loss:4.1166 train_time:222432ms step_avg:741.44ms +step:400/20000 train_loss:3.7673 train_time:284713ms step_avg:711.78ms +step:500/20000 train_loss:3.5366 train_time:346937ms step_avg:693.87ms +step:500/20000 val_loss:3.6091 val_bpb:1.3972 train_time:346950ms step_avg:693.90ms +step:600/20000 train_loss:3.5930 train_time:406716ms step_avg:677.86ms +step:700/20000 train_loss:3.3799 train_time:467576ms step_avg:667.97ms +step:800/20000 train_loss:3.8154 train_time:236512ms step_avg:295.64ms +step:900/20000 train_loss:3.7081 train_time:261603ms step_avg:290.67ms +step:1000/20000 train_loss:3.7845 train_time:286712ms step_avg:286.71ms +step:1100/20000 train_loss:3.6247 train_time:311784ms step_avg:283.44ms +step:1200/20000 train_loss:3.7066 train_time:336743ms step_avg:280.62ms +step:1300/20000 train_loss:3.3809 train_time:361869ms step_avg:278.36ms +step:1400/20000 train_loss:3.5744 train_time:386913ms step_avg:276.37ms +step:1500/20000 train_loss:3.3874 train_time:411454ms step_avg:274.30ms +step:1600/20000 train_loss:3.5373 train_time:436123ms step_avg:272.58ms +step:1700/20000 train_loss:3.4030 train_time:461302ms step_avg:271.35ms +step:1800/20000 train_loss:3.4635 train_time:486699ms step_avg:270.39ms +step:1900/20000 train_loss:3.4736 train_time:402939ms step_avg:212.07ms +step:2000/20000 train_loss:3.5042 train_time:421860ms step_avg:210.93ms +step:2000/20000 val_loss:3.4379 val_bpb:1.3309 train_time:421861ms step_avg:210.93ms +step:2100/20000 train_loss:3.4285 train_time:440795ms step_avg:209.90ms +step:2200/20000 train_loss:3.4960 train_time:459666ms step_avg:208.94ms +step:2300/20000 train_loss:3.5436 train_time:478566ms step_avg:208.07ms +step:2400/20000 train_loss:3.3287 train_time:497516ms step_avg:207.30ms +step:2500/20000 train_loss:3.3352 train_time:516484ms step_avg:206.59ms +step:2500/20000 val_loss:3.3281 val_bpb:1.2884 train_time:516485ms step_avg:206.59ms +step:2600/20000 train_loss:3.3527 train_time:536560ms step_avg:206.37ms +step:2700/20000 train_loss:3.3067 train_time:556834ms step_avg:206.23ms +step:2800/20000 train_loss:3.4435 train_time:576470ms step_avg:205.88ms +step:2900/20000 train_loss:3.3247 train_time:596199ms step_avg:205.59ms +step:2896/20000 val_loss:3.2562 val_bpb:1.2606 train_time:600030ms step_avg:207.19ms +stopping_early: wallclock_cap train_time:600030ms step:2896/20000 +peak memory allocated: 5476 MiB reserved: 8058 MiB +ema:applying EMA weights for evaluation +gptq:calibrating... +gptq:collected 66 Hessians +Serialized model: 149353232 bytes code: 74713 bytes total: 149427945 bytes +gptq_quantize: 66 GPTQ layers, 1 naive layers +Serialized model int6+gptq+brotli: 14014157 bytes total: 14088870 bytes +final_eval_mode:standard +final_int8_zlib_roundtrip val_loss:3.8215 val_bpb:1.4794 eval_time:24956ms +final_int8_zlib_roundtrip_exact val_loss:3.82151133 val_bpb:1.47942612