diff --git a/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/README.md b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/README.md new file mode 100644 index 0000000000..c1daccb7c4 --- /dev/null +++ b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/README.md @@ -0,0 +1,89 @@ +# 11L Int6 + SmearGate + SWA + AdamW WD + +**val_bpb: 1.1400** (3-seed mean, sliding window stride=64) | **15.7 MB** artifact | 8xH100 SXM, 600s + +## Key Finding: Batch Size vs Step Count + +The dominant factor in 10-minute training is not batch quality but total optimization steps. Reducing batch from 786K to 524K tokens: +- Drops step time from 91ms to 67ms (26% faster) +- Increases total steps from ~7,300 to ~8,900 (22% more) +- Despite seeing 12% fewer total tokens, the extra gradient updates improve convergence + +This finding applies to any fixed-time training budget and suggests the optimal batch size is smaller than commonly assumed. + +## Technique Stack + +| Component | Choice | Rationale | +|-----------|--------|-----------| +| Layers | 11 | Extra depth funded by int6 + zstd compression headroom | +| MLP | 3x (1536) | Full width; int8 tok_emb + no Late-K saves space | +| Quantization | Int6 per-row (attention + MLP), int8 (tok_emb) | Int8 tok_emb preserves output projection quality | +| SmearGate | Per-dim, 512 params | Blends adjacent token embeddings | +| BigramHash | 2048 buckets, dim=128 | Consecutive token pair features | +| Weight decay | 0.04 (Muon + AdamW) | Dual WD shrinks weights for better quantization + compression | +| SWA | ~7 checkpoints, every 200 steps | Late-training weight averaging | +| OrthoInit | gain=1.0, proj scaled 1/sqrt(2L) | Standard orthogonal initialization | +| FlashAttention | v2.8.3 | ~3% throughput improvement over PyTorch SDPA | +| Compression | zstd level 22 | 35% better than zlib for int6-in-int8 data | +| Eval | Sliding window, stride=64, batch=32 | Batched windows make stride=64 feasible in 172s | + +## Metrics + +| Metric | Value | +|--------|-------| +| Sliding BPB (stride=64, 3-seed mean) | **1.1400** | +| Best single seed (1338) | **1.1381** | +| Artifact size | 15.7 MB | +| Steps (600s cap) | ~8,930 | +| Step time | 67ms | +| Model params | ~26.5M | + +## Reproducibility (3 seeds) + +| Seed | Sliding BPB | Artifact | +|------|-------------|----------| +| 1337 | 1.1411 | 15.95 MB | +| 1338 | 1.1381 | 15.63 MB | +| 1339 | 1.1408 | 15.66 MB | +| Mean | **1.1400** | 15.7 MB | +| Std | 0.0016 | — | + +## Run Command + +```bash +pip install zstandard flash-attn --no-build-isolation +SEED=1338 NUM_LAYERS=11 TRAIN_SEQ_LEN=2048 TRAIN_BATCH_TOKENS=524288 \ +MLP_HIDDEN=1536 BIGRAM_VOCAB_SIZE=2048 BIGRAM_DIM=128 \ +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 WARMDOWN_ITERS=3000 GRAD_CLIP_NORM=0.3 \ +EVAL_SEQ_LEN=2048 EVAL_STRIDE=64 EVAL_BATCH_SEQS=32 \ +MUON_WD=0.04 ADAM_WD=0.04 SWA_FRAC=0.5 SWA_EVERY=200 \ +torchrun --standalone --nproc_per_node=8 train_gpt.py +``` + +## Ablation Path (90+ experiments) + +| Change | BPB | Delta | +|--------|-----|-------| +| Baseline (stock 9L) | 1.2244 | — | +| + int6 + MLP 3x + train@2048 + clip=0.3 (PR #114) | 1.1574 | -0.067 | +| + OrthoInit + MuonWD=0.02 | 1.1536 | -0.004 | +| + SmearGate + BigramHash + 10L | 1.1465 | -0.007 | +| + batch=524K (from 786K) | 1.1465 | +0.000 (same but more steps) | +| + 11L/1408, WD=0.039, FA | 1.1423 | -0.004 | +| + MLP=1536, LR=0.025, AdamW WD=0.04, int8 tok_emb | **1.1400** | **-0.002** | + +## Dead Ends (selected from 90+ experiments) + +- **QAT (int6 STE)**: 115ms/step overhead (vs 67ms baseline). Better quant quality but 25% fewer steps. Net loss. +- **Int5 for MLP**: Saves artifact space but 0.020 BPB quality penalty. Int6-all with tighter compression is better. +- **Batch=786K**: More tokens/step but fewer steps. 524K is optimal. +- **NorMuon**: 110ms/step. Throughput death. +- **MTP**: 86ms/step. Aux head too expensive. + +## Previous Submissions + +- PR #61: 1.2154 (warmdown-quantization discovery) +- PR #96: 1.1764 (sliding window + long-context training) +- PR #114: 1.1574 (int6 + MLP 3x + selective precision) diff --git a/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/submission.json b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/submission.json new file mode 100644 index 0000000000..de3ac9bf35 --- /dev/null +++ b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/submission.json @@ -0,0 +1,10 @@ +{ + "name": "11L Int6 + SmearGate + SWA + AdamW WD (val_bpb=1.1400)", + "val_loss": 1.9267, + "val_bpb": 1.1400, + "bytes_total": 15951384, + "blurb": "11 layers with 3x MLP (1536), int6 per-row for attention+MLP, int8 for tied embedding. SmearGate + BigramHash(2048). Orthogonal init, Muon+AdamW WD=0.04, SWA ~7 checkpoint average. FlashAttention 2.8.3. Sliding window eval stride=64 with batched windows. Key finding: smaller batch (524K vs 786K) gives 40% more optimization steps at lower per-step cost, beating larger batches for total convergence.", + "author": "Sam Larson", + "github_id": "saml212", + "date": "2026-03-20" +} diff --git a/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train.log b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train.log new file mode 100644 index 0000000000..ac80aec1ba --- /dev/null +++ b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train.log @@ -0,0 +1,110 @@ +W0321 03:52:08.055000 411024 torch/distributed/run.py:803] +W0321 03:52:08.055000 411024 torch/distributed/run.py:803] ***************************************** +W0321 03:52:08.055000 411024 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0321 03:52:08.055000 411024 torch/distributed/run.py:803] ***************************************** +logs/2f87675d-0c37-4a2b-b135-ef2f522b65b8.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +model_params:26829913 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:8 num_kv_heads:4 +tie_embeddings:True embed_lr:0.035 head_lr:0.0 matrix_lr:0.025 scalar_lr:0.025 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:20 max_wallclock_seconds:600.000 +seed:1338 +warmup_step:1/20 +warmup_step:2/20 +warmup_step:3/20 +warmup_step:4/20 +warmup_step:5/20 +warmup_step:6/20 +warmup_step:7/20 +warmup_step:8/20 +warmup_step:9/20 +warmup_step:10/20 +warmup_step:11/20 +warmup_step:12/20 +warmup_step:13/20 +warmup_step:14/20 +warmup_step:15/20 +warmup_step:16/20 +warmup_step:17/20 +warmup_step:18/20 +warmup_step:19/20 +warmup_step:20/20 +step:0/20000 val_loss:6.9292 val_bpb:4.1038 train_time:0ms step_avg:0.01ms +step:1/20000 train_loss:6.9299 train_time:129ms step_avg:128.97ms +step:2/20000 train_loss:8.5876 train_time:199ms step_avg:99.40ms +step:3/20000 train_loss:7.7827 train_time:272ms step_avg:90.83ms +step:4/20000 train_loss:7.3472 train_time:346ms step_avg:86.55ms +step:5/20000 train_loss:6.8994 train_time:420ms step_avg:84.00ms +step:6/20000 train_loss:7.7853 train_time:494ms step_avg:82.40ms +step:7/20000 train_loss:6.9407 train_time:569ms step_avg:81.30ms +step:8/20000 train_loss:6.7671 train_time:643ms step_avg:80.37ms +step:9/20000 train_loss:6.5937 train_time:717ms step_avg:79.68ms +step:10/20000 train_loss:6.3448 train_time:791ms step_avg:79.13ms +step:200/20000 train_loss:2.7481 train_time:13826ms step_avg:69.13ms +step:400/20000 train_loss:2.2446 train_time:27583ms step_avg:68.96ms +step:600/20000 train_loss:2.4573 train_time:41385ms step_avg:68.97ms +step:800/20000 train_loss:2.2084 train_time:55206ms step_avg:69.01ms +step:1000/20000 train_loss:2.3072 train_time:69015ms step_avg:69.02ms +step:1000/20000 val_loss:2.2599 val_bpb:1.3384 train_time:69027ms step_avg:69.03ms +step:1200/20000 train_loss:2.3312 train_time:82818ms step_avg:69.01ms +step:1400/20000 train_loss:2.3683 train_time:96606ms step_avg:69.00ms +step:1600/20000 train_loss:2.0413 train_time:110400ms step_avg:69.00ms +step:1800/20000 train_loss:2.1449 train_time:124217ms step_avg:69.01ms +step:2000/20000 train_loss:2.1806 train_time:138066ms step_avg:69.03ms +step:2000/20000 val_loss:2.1652 val_bpb:1.2824 train_time:138078ms step_avg:69.04ms +step:2200/20000 train_loss:2.0035 train_time:151914ms step_avg:69.05ms +step:2400/20000 train_loss:2.1274 train_time:165770ms step_avg:69.07ms +step:2600/20000 train_loss:2.3560 train_time:179592ms step_avg:69.07ms +step:2800/20000 train_loss:2.1698 train_time:193422ms step_avg:69.08ms +step:3000/20000 train_loss:2.1621 train_time:207255ms step_avg:69.08ms +step:3000/20000 val_loss:2.1243 val_bpb:1.2581 train_time:207269ms step_avg:69.09ms +step:3200/20000 train_loss:2.1217 train_time:221087ms step_avg:69.09ms +step:3400/20000 train_loss:2.0934 train_time:234902ms step_avg:69.09ms +step:3600/20000 train_loss:2.0443 train_time:248726ms step_avg:69.09ms +step:3800/20000 train_loss:2.1490 train_time:262539ms step_avg:69.09ms +step:4000/20000 train_loss:2.1164 train_time:276368ms step_avg:69.09ms +step:4000/20000 val_loss:2.1071 val_bpb:1.2480 train_time:276381ms step_avg:69.10ms +step:4200/20000 train_loss:2.1073 train_time:290293ms step_avg:69.12ms +step:4400/20000 train_loss:2.0482 train_time:304096ms step_avg:69.11ms +step:4600/20000 train_loss:1.9118 train_time:317919ms step_avg:69.11ms +step:4800/20000 train_loss:2.2034 train_time:331744ms step_avg:69.11ms +step:5000/20000 train_loss:1.9566 train_time:345555ms step_avg:69.11ms +step:5000/20000 val_loss:2.0983 val_bpb:1.2427 train_time:345569ms step_avg:69.11ms +step:5200/20000 train_loss:2.1202 train_time:359369ms step_avg:69.11ms +step:5400/20000 train_loss:2.1386 train_time:373187ms step_avg:69.11ms +step:5600/20000 train_loss:2.1310 train_time:387000ms step_avg:69.11ms +step:5800/20000 train_loss:2.0856 train_time:400813ms step_avg:69.11ms +step:6000/20000 train_loss:2.1621 train_time:414616ms step_avg:69.10ms +step:6000/20000 val_loss:2.0853 val_bpb:1.2350 train_time:414629ms step_avg:69.10ms +step:6200/20000 train_loss:2.0259 train_time:428424ms step_avg:69.10ms +step:6400/20000 train_loss:2.0991 train_time:442210ms step_avg:69.10ms +step:6600/20000 train_loss:2.0433 train_time:455989ms step_avg:69.09ms +step:6800/20000 train_loss:2.0991 train_time:469773ms step_avg:69.08ms +step:7000/20000 train_loss:2.1395 train_time:483567ms step_avg:69.08ms +step:7000/20000 val_loss:2.0390 val_bpb:1.2076 train_time:483579ms step_avg:69.08ms +step:7200/20000 train_loss:2.0985 train_time:497364ms step_avg:69.08ms +step:7400/20000 train_loss:2.0154 train_time:511170ms step_avg:69.08ms +step:7600/20000 train_loss:1.8793 train_time:524979ms step_avg:69.08ms +step:7800/20000 train_loss:2.0212 train_time:538794ms step_avg:69.08ms +step:8000/20000 train_loss:1.9796 train_time:552599ms step_avg:69.07ms +step:8000/20000 val_loss:1.9822 val_bpb:1.1740 train_time:552612ms step_avg:69.08ms +step:8200/20000 train_loss:2.0431 train_time:566395ms step_avg:69.07ms +step:8400/20000 train_loss:1.9720 train_time:580294ms step_avg:69.08ms +step:8600/20000 train_loss:1.9745 train_time:594104ms step_avg:69.08ms +step:8685/20000 val_loss:1.9422 val_bpb:1.1503 train_time:599941ms step_avg:69.08ms +stopping_early: wallclock_cap train_time:599941ms step:8685/20000 +peak memory allocated: 14328 MiB reserved: 14392 MiB +ema: loading EMA weights (decay=0.997) +Serialized model: 105789375 bytes +Code size: 61617 bytes +Total submission size: 105850992 bytes +Serialized model int8+zlib: 15399540 bytes (payload:27057508 raw_torch:27113999 payload_ratio:3.91x) +Total submission size int8+zlib: 15461157 bytes +final_int8_zlib_roundtrip val_loss:1.9517 val_bpb:1.1559 eval_time:2147ms eval_seq_len:2048 +final_int8_zlib_roundtrip_exact val_loss:1.95166039 val_bpb:1.15588321 +final_sliding_window val_loss:1.9145 val_bpb:1.1339 eval_time:201285ms stride:64 seq_len:2048 +final_sliding_window_exact val_loss:1.91451721 val_bpb:1.13388793 diff --git a/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_gpt.py b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_gpt.py new file mode 100644 index 0000000000..c01043c13a --- /dev/null +++ b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_gpt.py @@ -0,0 +1,1435 @@ +""" +The `train_gpt.py` and `train_gpt_mlx.py` scripts are intended as good launching-off points for new participants, not SOTA configs. We'll accept PRs that tune, improve, or simplify these scripts without significantly increasing complexity, but competitive submissions should stay in the `/records` folder. + +Hard stop: `train_gpt.py` and `train_gpt_mlx.py` must never be longer than 1500 lines. +""" + +from __future__ import annotations + +import copy +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import uuid +import zlib +from pathlib import Path + +try: + import zstandard + _COMPRESSOR = "zstd" +except ImportError: + _COMPRESSOR = "zlib" + +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: + from flash_attn import flash_attn_func + _HAS_FLASH_ATTN = True +except ImportError: + _HAS_FLASH_ATTN = False + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- +# Default Simple Baseline run: +# - 9 transformer blocks at width 512 +# - 8 attention heads with 4 KV heads (GQA) and 2x MLP expansion +# - vocab size 1024, sequence length 1024, tied embeddings +# - 524,288 train tokens per step for 20,000 iterations with a ~10 minute cap + +class Hyperparameters: + # Data paths are shard globs produced by the existing preprocessing pipeline. + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024") + train_files = os.path.join(data_path, "fineweb_train_*.bin") + val_files = os.path.join(data_path, "fineweb_val_*.bin") + tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 1337)) + + # Validation cadence and batch size. Validation always uses the full fineweb_val split. + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200)) + + # Training length. + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 1200)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 524_288)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 1024)) + eval_seq_len = int(os.environ.get("EVAL_SEQ_LEN", 2048)) + eval_stride = int(os.environ.get("EVAL_STRIDE", 0)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 32)) + max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + + # Model shape. + vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) + num_layers = int(os.environ.get("NUM_LAYERS", 9)) + 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 = int(os.environ.get("MLP_MULT", 2)) + mlp_hidden = int(os.environ.get("MLP_HIDDEN", 0)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + bigram_vocab_size = int(os.environ.get("BIGRAM_VOCAB_SIZE", 4096)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + + # Optimizer hyperparameters. + 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.05)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.04)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.04)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.95)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.85)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 500)) + 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)) + muon_weight_decay = float(os.environ.get("MUON_WD", 0.04)) + adam_weight_decay = float(os.environ.get("ADAM_WD", 0.0)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.0)) + + # XSA (Exclusive Self Attention) and EMA + xsa_last_n = int(os.environ.get("XSA_LAST_N", 0)) # Apply XSA to last N layers (0=disabled) + ema_enabled = bool(int(os.environ.get("EMA_ENABLED", 0))) + ema_decay = float(os.environ.get("EMA_DECAY", 0.997)) + swa_enabled = bool(int(os.environ.get("SWA_ENABLED", 1))) + +# ----------------------------- +# MUON OPTIMIZER +# ----------------------------- +# +# As borrowed from modded-nanogpt +# Background on Muon: https://kellerjordan.github.io/posts/muon/ + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 10, eps: float = 1e-7) -> Tensor: + # Orthogonalize a 2D update matrix with a fast Newton-Schulz iteration. + # Muon uses this to normalize matrix-shaped gradients before applying them. + 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) + # Scale correction from Muon reference implementations. + 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) + p.add_(g, alpha=-lr) + if wd > 0: + p.data.mul_(1.0 - lr * wd) + curr += p.numel() + + return loss + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION SETUP +# ----------------------------- +# +# It's common for small models have a large fraction of their parameters be embeddings, since the 2 * d_model * d_vocab vectors can be gigantic. +# Instead of locking the tokenizer, we let you bring your own and calculate our validation metrics on the average compression of the validation set. +# We calculate BPB (bits-per-byte) instead of validation loss, so we need methods to count the number of bits per token in the tokenizer. +# Note: Submissions that edit the tokenizer will be examined more carefully, since screwing this up might unjustly improve your score. + +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}") + # The export pipeline writes the fixed first-50k-doc validation set to fineweb_val_*. + 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, + eval_seq_len: int | None = None, +) -> tuple[float, float]: + # Validation computes two metrics: + # - val_loss: token cross-entropy (natural log) + # - val_bpb: tokenizer-agnostic compression metric used by the challenge + seq_len = eval_seq_len or args.train_seq_len + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < seq_len: + raise ValueError( + "VAL_BATCH_SIZE must provide at least one sequence per rank; " + f"got VAL_BATCH_SIZE={args.val_batch_size}, WORLD_SIZE={world_size}, " + f"GRAD_ACCUM_STEPS={grad_accum_steps}, seq_len={seq_len}" + ) + local_batch_seqs = local_batch_tokens // seq_len + total_seqs = (val_tokens.numel() - 1) // 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 * seq_len + raw_end = batch_seq_end * seq_len + 1 + local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, 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) + +# ----------------------------- +# POST-TRAINING QUANTIZATION +# ----------------------------- +# +# It's silly to export our model, which is trained in bf16 and fp32, at that same precision. +# Instead, we get approximately the same model (with a small hit) by quantizing the model to int8 & zlib compressing. +# We can then decompress the model and run in higher precision for evaluation, after closing in under the size limit. + +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 +) +INT8_KEEP_FLOAT_FP32_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "INT8_KEEP_FLOAT_FP32_NAME_PATTERNS", + ",".join(CONTROL_TENSOR_NAME_PATTERNS), + ).split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 +INT8_KEEP_FLOAT_STORE_DTYPE = torch.float16 +INT8_PER_ROW_SCALE_DTYPE = torch.float16 +INT8_CLIP_PERCENTILE = 99.99984 +INT8_CLIP_Q = INT8_CLIP_PERCENTILE / 100.0 + +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def keep_float_tensor(name: str, t: Tensor, passthrough_orig_dtypes: dict[str, str]) -> Tensor: + if any(pattern in name for pattern in INT8_KEEP_FLOAT_FP32_NAME_PATTERNS): + return t.float().contiguous() + if t.dtype in {torch.float32, torch.bfloat16}: + passthrough_orig_dtypes[name] = str(t.dtype).removeprefix("torch.") + return t.to(dtype=INT8_KEEP_FLOAT_STORE_DTYPE).contiguous() + return t + +def quantize_float_tensor(t: Tensor, bits: int = 8) -> tuple[Tensor, Tensor]: + max_val = 127 if bits == 8 else (2 ** (bits - 1)) - 1 # int6: 31, int8: 127 + 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 / float(max_val)).clamp_min(1.0 / float(max_val)) + q = torch.clamp(torch.round(clipped / scale[:, None]), -max_val, max_val).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 / float(max_val) if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -max_val, max_val).to(torch.int8).contiguous() + return q, scale + +def quantize_state_dict_int8(state_dict: dict[str, Tensor]): + # Single supported clean-script export format: + # - per-row int8 for 2D float tensors + # - per-tensor int8 for other float tensors + # - exact passthrough for non-floats + # - passthrough for small float tensors, stored as fp16 to save bytes + quantized: dict[str, Tensor] = {} + scales: dict[str, Tensor] = {} + dtypes: dict[str, str] = {} + passthrough: dict[str, Tensor] = {} + passthrough_orig_dtypes: dict[str, str] = {} + qmeta: dict[str, dict[str, object]] = {} + stats = dict.fromkeys( + ("param_count", "num_tensors", "num_float_tensors", "num_nonfloat_tensors", "baseline_tensor_bytes", "int8_payload_bytes"), + 0, + ) + + for name, tensor in state_dict.items(): + t = tensor.detach().to("cpu").contiguous() + stats["param_count"] += int(t.numel()) + stats["num_tensors"] += 1 + stats["baseline_tensor_bytes"] += tensor_nbytes(t) + + if not t.is_floating_point(): + stats["num_nonfloat_tensors"] += 1 + passthrough[name] = t + stats["int8_payload_bytes"] += tensor_nbytes(t) + continue + + # Int8 for tok_emb (better quality than int6, smaller than fp16) + if name == "tok_emb.weight": + q, s = quantize_float_tensor(t, bits=8) + if s.ndim > 0: + qmeta[name] = {"scheme": "per_row", "axis": 0} + quantized[name] = q + scales[name] = s + dtypes[name] = str(t.dtype).removeprefix("torch.") + stats["num_float_tensors"] += 1 + stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + continue + + # Small float tensors are cheap enough to keep directly. + if t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + kept = keep_float_tensor(name, t, passthrough_orig_dtypes) + passthrough[name] = kept + stats["int8_payload_bytes"] += tensor_nbytes(kept) + continue + + # Int6 for all weight matrices + stats["num_float_tensors"] += 1 + bits = 6 + q, s = quantize_float_tensor(t, bits=bits) + if s.ndim > 0: + qmeta[name] = {"scheme": "per_row", "axis": 0} + quantized[name] = q + scales[name] = s + dtypes[name] = str(t.dtype).removeprefix("torch.") + stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + obj: dict[str, object] = { + "__quant_format__": "int8_clean_per_row_v1", + "quantized": quantized, + "scales": scales, + "dtypes": dtypes, + "passthrough": passthrough, + } + if qmeta: + obj["qmeta"] = qmeta + if passthrough_orig_dtypes: + obj["passthrough_orig_dtypes"] = passthrough_orig_dtypes + return obj, stats + +def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + qmeta = obj.get("qmeta", {}) + passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {}) + for name, q in obj["quantized"].items(): + dtype = getattr(torch, obj["dtypes"][name]) + s = obj["scales"][name] + if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: + s = s.to(dtype=torch.float32) + # Broadcast the saved row scale back across trailing dimensions. + out[name] = (q.float() * s.view(q.shape[0], *([1] * (q.ndim - 1)))).to(dtype=dtype).contiguous() + else: + scale = float(s.item()) + out[name] = (q.float() * scale).to(dtype=dtype).contiguous() + for name, t in obj["passthrough"].items(): + # Restore small tensors, undoing the temporary fp16 storage cast if needed. + out_t = t.detach().to("cpu").contiguous() + orig_dtype = passthrough_orig_dtypes.get(name) + if isinstance(orig_dtype, str): + out_t = out_t.to(dtype=getattr(torch, orig_dtype)).contiguous() + out[name] = out_t + 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: + # Each call consumes a contiguous chunk from the shared token stream, then slices out + # one disjoint span per rank. The extra "+1" token lets us build (x, y) by shifting. + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = rank + self.world_size = world_size + self.device = device + self.stream = TokenStream(pattern) + + def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> tuple[Tensor, Tensor]: + local_tokens = global_tokens // (self.world_size * grad_accum_steps) + per_rank_span = local_tokens + 1 + chunk = self.stream.take(per_rank_span * self.world_size) + start = self.rank * per_rank_span + local = chunk[start : start + per_rank_span].to(dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + return x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) + +# ----------------------------- +# TRANSFORMER MODULES +# ----------------------------- + +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + + +class CastedLinear(nn.Linear): + # Keep weights in fp32 for optimizer/state quality, cast at matmul time for bf16 compute. + def forward(self, x: Tensor) -> Tensor: + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, self.weight.to(x.dtype), bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + # Keep small/control parameters in fp32 even when the model body runs in bf16. + 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): + # Caches cos/sin tables per sequence length on the current device. + # NTK-aware RoPE scaling for sequence length extrapolation at eval time. + def __init__(self, dim: int, base: float = 10000.0, train_seq_len: int = 1024): + super().__init__() + self.dim = dim + self.base = base + self.train_seq_len = train_seq_len + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + if seq_len > self.train_seq_len: + scale = seq_len / self.train_seq_len + new_base = self.base * (scale ** (self.dim / (self.dim - 2))) + inv_freq = 1.0 / (new_base ** (torch.arange(0, self.dim, 2, dtype=torch.float32, device=device) / self.dim)) + else: + inv_freq = self.inv_freq.to(device) + t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) + freqs = torch.outer(t, inv_freq) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + + +class CausalSelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int, + rope_base: float, + qk_gain_init: float, + ): + 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, train_seq_len=1024) + self.use_xsa = False # Set externally by GPT.__init__ + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + """Subtract self-value projection via GQA-aware reshape (no repeat_interleave).""" + B, T, H, D = y.shape + Hkv = v.size(-2) + group = H // Hkv + y_g = y.reshape(B, T, Hkv, group, 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, T, H, D) + + def forward(self, x: Tensor) -> Tensor: + bsz, seqlen, dim = x.shape + # All shapes: (B, H, S, D) for rotary + q_gain, then transpose for flash_attn + q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = self.c_v(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + if _HAS_FLASH_ATTN: + # flash_attn needs (B, S, H, D) + q_fa = q.transpose(1, 2) + k_fa = k.transpose(1, 2) + v_fa = v.transpose(1, 2) + y = flash_attn_func(q_fa, k_fa, v_fa, causal=True) # (B, S, H, D) + else: + y = F.scaled_dot_product_attention( + q, k, v, + attn_mask=None, + is_causal=True, + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + y = y.transpose(1, 2) # (B, H, S, D) -> (B, S, H, D) + if self.use_xsa: + v_bshd = v.transpose(1, 2) # XSA needs (B, S, Hkv, D) + y = self._xsa_efficient(y, v_bshd) + y = y.reshape(bsz, seqlen, dim) + return self.proj(y) + + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: int, mlp_hidden: int = 0): + super().__init__() + hidden = mlp_hidden if mlp_hidden > 0 else 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): + """Blend each token's embedding with the previous token's embedding.""" + 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): + """Hash consecutive token pairs into a learned embedding table.""" + 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: int, + rope_base: float, + qk_gain_init: float, + mlp_hidden: int = 0, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init) + self.mlp = MLP(dim, mlp_mult, mlp_hidden) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + + def forward(self, x: Tensor, x0: Tensor) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + attn_out = self.attn(self.attn_norm(x)) + 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)) + return x + + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_layers: int, + model_dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: int, + mlp_hidden: int, + 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, + xsa_last_n: 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.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.smear = SmearGate(model_dim) + 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, + mlp_hidden=mlp_hidden, + ) + for i in range(num_layers) + ] + ) + # Enable XSA on last N layers + if xsa_last_n > 0: + for i in range(max(0, num_layers - xsa_last_n), num_layers): + self.blocks[i].attn.use_xsa = True + 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(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + skips: list[Tensor] = [] + + # First half stores skips; second half reuses them in reverse order. + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0) + 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) + + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") + + @torch.no_grad() + def get_logits(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram is not None: + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear(x) + x0 = x + skips: list[Tensor] = [] + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0) + 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) + x = self.final_norm(x) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + logits_proj = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + + +def eval_val_sliding( + args, 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, eval_seq_len: int, eval_stride: int, + batch_seqs: int = 32, +) -> tuple[float, float]: + total_tokens = val_tokens.numel() - 1 + all_starts = [s for s in range(0, total_tokens - eval_stride + 1, eval_stride) + if min(s + eval_seq_len, total_tokens) - s >= eval_stride] + # Distribute windows across ranks + n = len(all_starts) + my_s = (n * rank) // world_size + my_e = (n * (rank + 1)) // world_size + my_starts = all_starts[my_s:my_e] + + 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) + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_starts), batch_seqs): + batch_ws = my_starts[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, eval_seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, eval_seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + + for i, ws in enumerate(batch_ws): + end = min(ws + eval_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.get_logits(x_batch) + + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, eval_seq_len) + + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + score_from = max(wlen - eval_stride, 0) if ws > 0 else 0 + losses = nll[i, score_from:wlen] + val_loss_sum += losses.to(torch.float64).sum() + val_token_count += losses.numel() + prev_ids = x_batch[i, score_from:wlen] + tgt_ids = y_batch[i, score_from:wlen] + 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() + base_model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +# ----------------------------- +# TRAINING +# ----------------------------- + +def main() -> None: + global zeropower_via_newtonschulz5 + + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + zeropower_via_newtonschulz5 = torch.compile(zeropower_via_newtonschulz5) + + # ----------------------------- + # DISTRIBUTED + CUDA SETUP + # ----------------------------- + + distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size <= 0: + raise ValueError(f"WORLD_SIZE must be positive, got {world_size}") + if 8 % world_size != 0: + raise ValueError(f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral") + grad_accum_steps = 8 // world_size + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + + # Fast math knobs + 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("=" * 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) + + # ----------------------------- + # TOKENIZER + VALIDATION METRIC SETUP + # ----------------------------- + + 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"))) + effective_eval_seq_len = args.eval_seq_len if args.eval_seq_len > 0 else args.train_seq_len + val_seq_len = max(args.train_seq_len, effective_eval_seq_len) + val_tokens = load_validation_tokens(args.val_files, val_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 SETUP + # ----------------------------- + + base_model = GPT( + vocab_size=args.vocab_size, + num_layers=args.num_layers, + model_dim=args.model_dim, + num_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + mlp_mult=args.mlp_mult, + mlp_hidden=args.mlp_hidden, + 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, + xsa_last_n=args.xsa_last_n, + ).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=True) + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if distributed else compiled_model + + # Optimizer split: + # - token embedding (Adam) uses EMBED_LR + # - untied lm_head (Adam) uses HEAD_LR + # - matrix params in transformer blocks use MATRIX_LR via Muon + # - vectors/scalars use SCALAR_LR via Adam + 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) + # SmearGate and BigramHash params go through Adam at scalar_lr + scalar_params.append(base_model.smear.gate) + if base_model.bigram is not None: + for p in base_model.bigram.parameters(): + scalar_params.append(p) + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + adam_cls = torch.optim.AdamW if args.adam_weight_decay > 0 else torch.optim.Adam + adam_wd = args.adam_weight_decay + optimizer_tok = adam_cls( + [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=adam_wd, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.muon_weight_decay, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = adam_cls( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=adam_wd, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + # ----------------------------- + # DATA LOADER & MODEL WARMUP + # ----------------------------- + + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + + max_wallclock_ms = 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) if warmdown_start <= step < args.iterations else 1.0 + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 + + # Warmup primes the compiled forward/backward/optimizer paths, then we restore the + # initial weights/optimizer state so measured training starts from the true init. + 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) + + # ----------------------------- + # MAIN TRAINING LOOP + # ----------------------------- + + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + + # EMA state + ema_state: dict[str, Tensor] | None = None + if args.ema_enabled: + ema_state = {name: t.detach().float().clone() for name, t in base_model.state_dict().items()} + 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) + 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() + + # EMA update + if ema_state is not None: + d = args.ema_decay + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(d).add_(t.detach().float(), alpha=1.0 - d) + + # SWA: collect checkpoints during warmdown tail + swa_frac = float(os.environ.get("SWA_FRAC", 0.5)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + if args.swa_enabled and not args.ema_enabled and scale < swa_frac and step % swa_every == 0: + if swa_state is None: + swa_state = {name: t.detach().cpu().clone() for name, t in base_model.state_dict().items()} + swa_count = 1 + else: + for name, t in base_model.state_dict().items(): + swa_state[name] += t.detach().cpu() + swa_count += 1 + + 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" + ) + + # Needed to sync whether we've reached the wallclock cap. + 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 or SWA + if ema_state is not None: + log0(f"ema: loading EMA weights (decay={args.ema_decay})") + ema_loaded = {name: t.to(dtype=base_model.state_dict()[name].dtype) for name, t in ema_state.items()} + base_model.load_state_dict(ema_loaded, strict=True) + del ema_state + elif swa_state is not None and swa_count > 1: + log0(f"swa: averaging {swa_count} checkpoints") + avg_state = {name: (tensor / swa_count).to(dtype=base_model.state_dict()[name].dtype) + for name, tensor in swa_state.items()} + base_model.load_state_dict(avg_state, strict=True) + del swa_state + elif swa_count <= 1 and ema_state is None: + log0("swa/ema: no weight averaging applied") + + # ----------------------------- + # SERIALIZATION + ROUNDTRIP VALIDATION + # ----------------------------- + # Save the raw state (useful for debugging/loading in PyTorch directly), then always produce + # the compressed int8+zlib artifact and validate the round-tripped weights. + + 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"Code size: {code_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + quant_obj, quant_stats = quantize_state_dict_int8(base_model.state_dict()) + quant_buf = io.BytesIO() + torch.save(quant_obj, quant_buf) + quant_raw = quant_buf.getvalue() + if _COMPRESSOR == "zstd": + cctx = zstandard.ZstdCompressor(level=22) + quant_blob = cctx.compress(quant_raw) + else: + quant_blob = zlib.compress(quant_raw, level=9) + quant_raw_bytes = len(quant_raw) + 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")) + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int8_payload_bytes"], 1) + log0( + f"Serialized model int8+zlib: {quant_file_bytes} bytes " + f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" + ) + log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + if _COMPRESSOR == "zstd": + dctx = zstandard.ZstdDecompressor() + quant_decompressed = dctx.decompress(quant_blob_disk, max_output_size=len(quant_raw) * 2) + else: + quant_decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(quant_decompressed), map_location="cpu") + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), 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, + eval_seq_len=effective_eval_seq_len, + ) + 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 " + f"eval_seq_len:{effective_eval_seq_len}" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + if args.eval_stride > 0: + torch.cuda.synchronize() + t_slide = time.perf_counter() + s_val_loss, s_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, + eval_seq_len=effective_eval_seq_len, eval_stride=args.eval_stride, + batch_seqs=args.eval_batch_seqs, + ) + torch.cuda.synchronize() + log0( + f"final_sliding_window val_loss:{s_val_loss:.4f} val_bpb:{s_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_slide):.0f}ms " + f"stride:{args.eval_stride} seq_len:{effective_eval_seq_len}" + ) + log0(f"final_sliding_window_exact val_loss:{s_val_loss:.8f} val_bpb:{s_val_bpb:.8f}") + + if distributed: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_seed1337.log b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_seed1337.log new file mode 100644 index 0000000000..bfa76f7bfb --- /dev/null +++ b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_seed1337.log @@ -0,0 +1,111 @@ +W0320 16:25:08.539000 310265 torch/distributed/run.py:803] +W0320 16:25:08.539000 310265 torch/distributed/run.py:803] ***************************************** +W0320 16:25:08.539000 310265 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0320 16:25:08.539000 310265 torch/distributed/run.py:803] ***************************************** +logs/68de8bd0-a23f-4af4-813c-6372a7c834ce.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +model_params:26829913 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:8 num_kv_heads:4 +tie_embeddings:True embed_lr:0.035 head_lr:0.0 matrix_lr:0.025 scalar_lr:0.025 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:20 max_wallclock_seconds:600.000 +seed:1337 +warmup_step:1/20 +warmup_step:2/20 +warmup_step:3/20 +warmup_step:4/20 +warmup_step:5/20 +warmup_step:6/20 +warmup_step:7/20 +warmup_step:8/20 +warmup_step:9/20 +warmup_step:10/20 +warmup_step:11/20 +warmup_step:12/20 +warmup_step:13/20 +warmup_step:14/20 +warmup_step:15/20 +warmup_step:16/20 +warmup_step:17/20 +warmup_step:18/20 +warmup_step:19/20 +warmup_step:20/20 +step:0/20000 val_loss:6.9303 val_bpb:4.1045 train_time:0ms step_avg:0.02ms +step:1/20000 train_loss:6.9315 train_time:125ms step_avg:124.77ms +step:2/20000 train_loss:8.6361 train_time:202ms step_avg:101.13ms +step:3/20000 train_loss:7.8457 train_time:274ms step_avg:91.24ms +step:4/20000 train_loss:7.3984 train_time:346ms step_avg:86.48ms +step:5/20000 train_loss:7.0356 train_time:419ms step_avg:83.76ms +step:6/20000 train_loss:7.9153 train_time:490ms step_avg:81.69ms +step:7/20000 train_loss:6.9205 train_time:562ms step_avg:80.28ms +step:8/20000 train_loss:6.7478 train_time:634ms step_avg:79.25ms +step:9/20000 train_loss:6.4237 train_time:705ms step_avg:78.38ms +step:10/20000 train_loss:6.2284 train_time:777ms step_avg:77.71ms +step:200/20000 train_loss:2.7744 train_time:13509ms step_avg:67.55ms +step:400/20000 train_loss:2.2593 train_time:26923ms step_avg:67.31ms +step:600/20000 train_loss:2.4686 train_time:40360ms step_avg:67.27ms +step:800/20000 train_loss:2.2227 train_time:53825ms step_avg:67.28ms +step:1000/20000 train_loss:2.3183 train_time:67286ms step_avg:67.29ms +step:1000/20000 val_loss:2.2723 val_bpb:1.3458 train_time:67309ms step_avg:67.31ms +step:1200/20000 train_loss:2.3386 train_time:80754ms step_avg:67.29ms +step:1400/20000 train_loss:2.3774 train_time:94205ms step_avg:67.29ms +step:1600/20000 train_loss:2.0465 train_time:107637ms step_avg:67.27ms +step:1800/20000 train_loss:2.1484 train_time:121074ms step_avg:67.26ms +step:2000/20000 train_loss:2.1904 train_time:134512ms step_avg:67.26ms +step:2000/20000 val_loss:2.1740 val_bpb:1.2876 train_time:134533ms step_avg:67.27ms +step:2200/20000 train_loss:2.0124 train_time:147960ms step_avg:67.25ms +step:2400/20000 train_loss:2.1299 train_time:161396ms step_avg:67.25ms +step:2600/20000 train_loss:2.3670 train_time:174825ms step_avg:67.24ms +step:2800/20000 train_loss:2.1794 train_time:188246ms step_avg:67.23ms +step:3000/20000 train_loss:2.1652 train_time:201689ms step_avg:67.23ms +step:3000/20000 val_loss:2.1318 val_bpb:1.2626 train_time:201711ms step_avg:67.24ms +step:3200/20000 train_loss:2.1264 train_time:215118ms step_avg:67.22ms +step:3400/20000 train_loss:2.1027 train_time:228506ms step_avg:67.21ms +step:3600/20000 train_loss:2.0452 train_time:241918ms step_avg:67.20ms +step:3800/20000 train_loss:2.1495 train_time:255349ms step_avg:67.20ms +step:4000/20000 train_loss:2.1262 train_time:268776ms step_avg:67.19ms +step:4000/20000 val_loss:2.1136 val_bpb:1.2518 train_time:268799ms step_avg:67.20ms +step:4200/20000 train_loss:2.1144 train_time:282321ms step_avg:67.22ms +step:4400/20000 train_loss:2.0568 train_time:295775ms step_avg:67.22ms +step:4600/20000 train_loss:1.9175 train_time:309213ms step_avg:67.22ms +step:4800/20000 train_loss:2.2072 train_time:322645ms step_avg:67.22ms +step:5000/20000 train_loss:1.9636 train_time:336071ms step_avg:67.21ms +step:5000/20000 val_loss:2.1035 val_bpb:1.2458 train_time:336094ms step_avg:67.22ms +step:5200/20000 train_loss:2.1267 train_time:349490ms step_avg:67.21ms +step:5400/20000 train_loss:2.1430 train_time:362900ms step_avg:67.20ms +step:5600/20000 train_loss:2.1343 train_time:376321ms step_avg:67.20ms +step:5800/20000 train_loss:2.0895 train_time:389739ms step_avg:67.20ms +step:6000/20000 train_loss:2.1736 train_time:403168ms step_avg:67.19ms +step:6000/20000 val_loss:2.0984 val_bpb:1.2428 train_time:403189ms step_avg:67.20ms +step:6200/20000 train_loss:2.0409 train_time:416593ms step_avg:67.19ms +step:6400/20000 train_loss:2.1123 train_time:430016ms step_avg:67.19ms +step:6600/20000 train_loss:2.0571 train_time:443460ms step_avg:67.19ms +step:6800/20000 train_loss:2.1131 train_time:456904ms step_avg:67.19ms +step:7000/20000 train_loss:2.1500 train_time:470346ms step_avg:67.19ms +step:7000/20000 val_loss:2.0537 val_bpb:1.2163 train_time:470369ms step_avg:67.20ms +step:7200/20000 train_loss:2.1180 train_time:483784ms step_avg:67.19ms +step:7400/20000 train_loss:2.0319 train_time:497185ms step_avg:67.19ms +step:7600/20000 train_loss:1.8970 train_time:510570ms step_avg:67.18ms +step:7800/20000 train_loss:2.0393 train_time:524072ms step_avg:67.19ms +step:8000/20000 train_loss:1.9990 train_time:537555ms step_avg:67.19ms +step:8000/20000 val_loss:2.0007 val_bpb:1.1849 train_time:537577ms step_avg:67.20ms +step:8200/20000 train_loss:2.0623 train_time:550978ms step_avg:67.19ms +step:8400/20000 train_loss:1.9959 train_time:564537ms step_avg:67.21ms +step:8600/20000 train_loss:1.9891 train_time:577968ms step_avg:67.21ms +step:8800/20000 train_loss:1.9409 train_time:591401ms step_avg:67.20ms +step:8927/20000 val_loss:1.9462 val_bpb:1.1527 train_time:599951ms step_avg:67.21ms +stopping_early: wallclock_cap train_time:599951ms step:8927/20000 +peak memory allocated: 13958 MiB reserved: 14100 MiB +swa: averaging 7 checkpoints +Serialized model: 105789375 bytes +Code size: 59624 bytes +Total submission size: 105848999 bytes +Serialized model int8+zlib: 15891760 bytes (payload:27057508 raw_torch:27113999 payload_ratio:3.91x) +Total submission size int8+zlib: 15951384 bytes +final_int8_zlib_roundtrip val_loss:1.9643 val_bpb:1.1634 eval_time:2129ms eval_seq_len:2048 +final_int8_zlib_roundtrip_exact val_loss:1.96427613 val_bpb:1.16335497 +final_sliding_window val_loss:1.9267 val_bpb:1.1411 eval_time:186208ms stride:64 seq_len:2048 +final_sliding_window_exact val_loss:1.92674889 val_bpb:1.14113224 diff --git a/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_seed1338.log b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_seed1338.log new file mode 100644 index 0000000000..68bf89c731 --- /dev/null +++ b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_seed1338.log @@ -0,0 +1,111 @@ +W0320 16:41:21.833000 315996 torch/distributed/run.py:803] +W0320 16:41:21.833000 315996 torch/distributed/run.py:803] ***************************************** +W0320 16:41:21.833000 315996 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0320 16:41:21.833000 315996 torch/distributed/run.py:803] ***************************************** +logs/8cd8fac5-fb82-45c9-8951-1a2fee8e8dd9.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +model_params:26829913 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:8 num_kv_heads:4 +tie_embeddings:True embed_lr:0.035 head_lr:0.0 matrix_lr:0.025 scalar_lr:0.025 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:20 max_wallclock_seconds:600.000 +seed:1338 +warmup_step:1/20 +warmup_step:2/20 +warmup_step:3/20 +warmup_step:4/20 +warmup_step:5/20 +warmup_step:6/20 +warmup_step:7/20 +warmup_step:8/20 +warmup_step:9/20 +warmup_step:10/20 +warmup_step:11/20 +warmup_step:12/20 +warmup_step:13/20 +warmup_step:14/20 +warmup_step:15/20 +warmup_step:16/20 +warmup_step:17/20 +warmup_step:18/20 +warmup_step:19/20 +warmup_step:20/20 +step:0/20000 val_loss:6.9292 val_bpb:4.1038 train_time:0ms step_avg:0.02ms +step:1/20000 train_loss:6.9299 train_time:123ms step_avg:122.67ms +step:2/20000 train_loss:8.5826 train_time:203ms step_avg:101.69ms +step:3/20000 train_loss:7.7831 train_time:275ms step_avg:91.74ms +step:4/20000 train_loss:7.3583 train_time:347ms step_avg:86.84ms +step:5/20000 train_loss:6.9090 train_time:420ms step_avg:83.95ms +step:6/20000 train_loss:7.8032 train_time:492ms step_avg:81.99ms +step:7/20000 train_loss:6.9658 train_time:564ms step_avg:80.53ms +step:8/20000 train_loss:6.8001 train_time:636ms step_avg:79.46ms +step:9/20000 train_loss:6.6282 train_time:707ms step_avg:78.55ms +step:10/20000 train_loss:6.3678 train_time:779ms step_avg:77.85ms +step:200/20000 train_loss:2.7654 train_time:13454ms step_avg:67.27ms +step:400/20000 train_loss:2.2629 train_time:26816ms step_avg:67.04ms +step:600/20000 train_loss:2.4628 train_time:40212ms step_avg:67.02ms +step:800/20000 train_loss:2.2141 train_time:53668ms step_avg:67.09ms +step:1000/20000 train_loss:2.3173 train_time:67102ms step_avg:67.10ms +step:1000/20000 val_loss:2.2678 val_bpb:1.3431 train_time:67127ms step_avg:67.13ms +step:1200/20000 train_loss:2.3389 train_time:80517ms step_avg:67.10ms +step:1400/20000 train_loss:2.3723 train_time:93957ms step_avg:67.11ms +step:1600/20000 train_loss:2.0388 train_time:107403ms step_avg:67.13ms +step:1800/20000 train_loss:2.1487 train_time:120860ms step_avg:67.14ms +step:2000/20000 train_loss:2.1887 train_time:134306ms step_avg:67.15ms +step:2000/20000 val_loss:2.1699 val_bpb:1.2852 train_time:134328ms step_avg:67.16ms +step:2200/20000 train_loss:2.0047 train_time:147743ms step_avg:67.16ms +step:2400/20000 train_loss:2.1303 train_time:161182ms step_avg:67.16ms +step:2600/20000 train_loss:2.3638 train_time:174598ms step_avg:67.15ms +step:2800/20000 train_loss:2.1743 train_time:188018ms step_avg:67.15ms +step:3000/20000 train_loss:2.1620 train_time:201407ms step_avg:67.14ms +step:3000/20000 val_loss:2.1273 val_bpb:1.2599 train_time:201430ms step_avg:67.14ms +step:3200/20000 train_loss:2.1245 train_time:214812ms step_avg:67.13ms +step:3400/20000 train_loss:2.0989 train_time:228239ms step_avg:67.13ms +step:3600/20000 train_loss:2.0380 train_time:241654ms step_avg:67.13ms +step:3800/20000 train_loss:2.1448 train_time:255080ms step_avg:67.13ms +step:4000/20000 train_loss:2.1221 train_time:268513ms step_avg:67.13ms +step:4000/20000 val_loss:2.1085 val_bpb:1.2488 train_time:268536ms step_avg:67.13ms +step:4200/20000 train_loss:2.1140 train_time:282029ms step_avg:67.15ms +step:4400/20000 train_loss:2.0538 train_time:295415ms step_avg:67.14ms +step:4600/20000 train_loss:1.9144 train_time:308804ms step_avg:67.13ms +step:4800/20000 train_loss:2.2051 train_time:322210ms step_avg:67.13ms +step:5000/20000 train_loss:1.9640 train_time:335599ms step_avg:67.12ms +step:5000/20000 val_loss:2.0994 val_bpb:1.2434 train_time:335621ms step_avg:67.12ms +step:5200/20000 train_loss:2.1219 train_time:348985ms step_avg:67.11ms +step:5400/20000 train_loss:2.1394 train_time:362362ms step_avg:67.10ms +step:5600/20000 train_loss:2.1296 train_time:375727ms step_avg:67.09ms +step:5800/20000 train_loss:2.0905 train_time:389090ms step_avg:67.08ms +step:6000/20000 train_loss:2.1720 train_time:402482ms step_avg:67.08ms +step:6000/20000 val_loss:2.0937 val_bpb:1.2400 train_time:402504ms step_avg:67.08ms +step:6200/20000 train_loss:2.0358 train_time:415881ms step_avg:67.08ms +step:6400/20000 train_loss:2.1041 train_time:429274ms step_avg:67.07ms +step:6600/20000 train_loss:2.0534 train_time:442686ms step_avg:67.07ms +step:6800/20000 train_loss:2.1084 train_time:456091ms step_avg:67.07ms +step:7000/20000 train_loss:2.1466 train_time:469498ms step_avg:67.07ms +step:7000/20000 val_loss:2.0497 val_bpb:1.2140 train_time:469521ms step_avg:67.07ms +step:7200/20000 train_loss:2.1115 train_time:482929ms step_avg:67.07ms +step:7400/20000 train_loss:2.0270 train_time:496369ms step_avg:67.08ms +step:7600/20000 train_loss:1.8936 train_time:509800ms step_avg:67.08ms +step:7800/20000 train_loss:2.0372 train_time:523354ms step_avg:67.10ms +step:8000/20000 train_loss:1.9993 train_time:536807ms step_avg:67.10ms +step:8000/20000 val_loss:1.9975 val_bpb:1.1830 train_time:536830ms step_avg:67.10ms +step:8200/20000 train_loss:2.0587 train_time:550290ms step_avg:67.11ms +step:8400/20000 train_loss:1.9859 train_time:563857ms step_avg:67.13ms +step:8600/20000 train_loss:1.9922 train_time:577323ms step_avg:67.13ms +step:8800/20000 train_loss:1.9376 train_time:590790ms step_avg:67.14ms +step:8936/20000 val_loss:1.9418 val_bpb:1.1500 train_time:599944ms step_avg:67.14ms +stopping_early: wallclock_cap train_time:599944ms step:8936/20000 +peak memory allocated: 13958 MiB reserved: 14100 MiB +swa: averaging 7 checkpoints +Serialized model: 105789375 bytes +Code size: 59624 bytes +Total submission size: 105848999 bytes +Serialized model int8+zlib: 15570073 bytes (payload:27057508 raw_torch:27113999 payload_ratio:3.91x) +Total submission size int8+zlib: 15629697 bytes +final_int8_zlib_roundtrip val_loss:1.9593 val_bpb:1.1604 eval_time:2101ms eval_seq_len:2048 +final_int8_zlib_roundtrip_exact val_loss:1.95933252 val_bpb:1.16042708 +final_sliding_window val_loss:1.9217 val_bpb:1.1381 eval_time:186019ms stride:64 seq_len:2048 +final_sliding_window_exact val_loss:1.92165906 val_bpb:1.13811775 diff --git a/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_seed1339.log b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_seed1339.log new file mode 100644 index 0000000000..4b33d3cae0 --- /dev/null +++ b/records/track_10min_16mb/2026-03-20_11L_Int6_SmearGate_SWA/train_seed1339.log @@ -0,0 +1,111 @@ +W0320 16:57:06.400000 321592 torch/distributed/run.py:803] +W0320 16:57:06.400000 321592 torch/distributed/run.py:803] ***************************************** +W0320 16:57:06.400000 321592 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0320 16:57:06.400000 321592 torch/distributed/run.py:803] ***************************************** +logs/601ecb38-48e6-461f-b2fd-72b4782cdbeb.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +model_params:26829913 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:8 num_kv_heads:4 +tie_embeddings:True embed_lr:0.035 head_lr:0.0 matrix_lr:0.025 scalar_lr:0.025 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:20 max_wallclock_seconds:600.000 +seed:1339 +warmup_step:1/20 +warmup_step:2/20 +warmup_step:3/20 +warmup_step:4/20 +warmup_step:5/20 +warmup_step:6/20 +warmup_step:7/20 +warmup_step:8/20 +warmup_step:9/20 +warmup_step:10/20 +warmup_step:11/20 +warmup_step:12/20 +warmup_step:13/20 +warmup_step:14/20 +warmup_step:15/20 +warmup_step:16/20 +warmup_step:17/20 +warmup_step:18/20 +warmup_step:19/20 +warmup_step:20/20 +step:0/20000 val_loss:6.9303 val_bpb:4.1045 train_time:0ms step_avg:0.04ms +step:1/20000 train_loss:6.9314 train_time:123ms step_avg:122.93ms +step:2/20000 train_loss:8.5096 train_time:181ms step_avg:90.31ms +step:3/20000 train_loss:7.7008 train_time:252ms step_avg:83.96ms +step:4/20000 train_loss:7.3859 train_time:323ms step_avg:80.66ms +step:5/20000 train_loss:6.9947 train_time:394ms step_avg:78.86ms +step:6/20000 train_loss:7.8822 train_time:465ms step_avg:77.52ms +step:7/20000 train_loss:6.9587 train_time:537ms step_avg:76.65ms +step:8/20000 train_loss:6.7813 train_time:608ms step_avg:75.94ms +step:9/20000 train_loss:6.5388 train_time:678ms step_avg:75.35ms +step:10/20000 train_loss:6.3639 train_time:750ms step_avg:74.95ms +step:200/20000 train_loss:2.7601 train_time:13396ms step_avg:66.98ms +step:400/20000 train_loss:2.2546 train_time:26747ms step_avg:66.87ms +step:600/20000 train_loss:2.4617 train_time:40120ms step_avg:66.87ms +step:800/20000 train_loss:2.2114 train_time:53528ms step_avg:66.91ms +step:1000/20000 train_loss:2.3188 train_time:66921ms step_avg:66.92ms +step:1000/20000 val_loss:2.2676 val_bpb:1.3430 train_time:66943ms step_avg:66.94ms +step:1200/20000 train_loss:2.3377 train_time:80326ms step_avg:66.94ms +step:1400/20000 train_loss:2.3783 train_time:93695ms step_avg:66.93ms +step:1600/20000 train_loss:2.0439 train_time:107060ms step_avg:66.91ms +step:1800/20000 train_loss:2.1498 train_time:120459ms step_avg:66.92ms +step:2000/20000 train_loss:2.1841 train_time:133850ms step_avg:66.93ms +step:2000/20000 val_loss:2.1722 val_bpb:1.2865 train_time:133873ms step_avg:66.94ms +step:2200/20000 train_loss:2.0120 train_time:147247ms step_avg:66.93ms +step:2400/20000 train_loss:2.1356 train_time:160651ms step_avg:66.94ms +step:2600/20000 train_loss:2.3662 train_time:174038ms step_avg:66.94ms +step:2800/20000 train_loss:2.1757 train_time:187432ms step_avg:66.94ms +step:3000/20000 train_loss:2.1638 train_time:200847ms step_avg:66.95ms +step:3000/20000 val_loss:2.1312 val_bpb:1.2622 train_time:200870ms step_avg:66.96ms +step:3200/20000 train_loss:2.1280 train_time:214241ms step_avg:66.95ms +step:3400/20000 train_loss:2.1056 train_time:227640ms step_avg:66.95ms +step:3600/20000 train_loss:2.0434 train_time:241043ms step_avg:66.96ms +step:3800/20000 train_loss:2.1540 train_time:254436ms step_avg:66.96ms +step:4000/20000 train_loss:2.1183 train_time:267839ms step_avg:66.96ms +step:4000/20000 val_loss:2.1126 val_bpb:1.2512 train_time:267861ms step_avg:66.97ms +step:4200/20000 train_loss:2.1188 train_time:281342ms step_avg:66.99ms +step:4400/20000 train_loss:2.0507 train_time:294750ms step_avg:66.99ms +step:4600/20000 train_loss:1.9192 train_time:308130ms step_avg:66.98ms +step:4800/20000 train_loss:2.2089 train_time:321514ms step_avg:66.98ms +step:5000/20000 train_loss:1.9656 train_time:334891ms step_avg:66.98ms +step:5000/20000 val_loss:2.1035 val_bpb:1.2458 train_time:334915ms step_avg:66.98ms +step:5200/20000 train_loss:2.1265 train_time:348262ms step_avg:66.97ms +step:5400/20000 train_loss:2.1402 train_time:361647ms step_avg:66.97ms +step:5600/20000 train_loss:2.1362 train_time:375025ms step_avg:66.97ms +step:5800/20000 train_loss:2.0891 train_time:388392ms step_avg:66.96ms +step:6000/20000 train_loss:2.1711 train_time:401751ms step_avg:66.96ms +step:6000/20000 val_loss:2.0988 val_bpb:1.2430 train_time:401774ms step_avg:66.96ms +step:6200/20000 train_loss:2.0379 train_time:415136ms step_avg:66.96ms +step:6400/20000 train_loss:2.1119 train_time:428515ms step_avg:66.96ms +step:6600/20000 train_loss:2.0622 train_time:441903ms step_avg:66.96ms +step:6800/20000 train_loss:2.1118 train_time:455297ms step_avg:66.96ms +step:7000/20000 train_loss:2.1522 train_time:468688ms step_avg:66.96ms +step:7000/20000 val_loss:2.0552 val_bpb:1.2172 train_time:468711ms step_avg:66.96ms +step:7200/20000 train_loss:2.1190 train_time:482082ms step_avg:66.96ms +step:7400/20000 train_loss:2.0337 train_time:495474ms step_avg:66.96ms +step:7600/20000 train_loss:1.8954 train_time:508841ms step_avg:66.95ms +step:7800/20000 train_loss:2.0388 train_time:522372ms step_avg:66.97ms +step:8000/20000 train_loss:1.9991 train_time:535839ms step_avg:66.98ms +step:8000/20000 val_loss:2.0023 val_bpb:1.1859 train_time:535861ms step_avg:66.98ms +step:8200/20000 train_loss:2.0620 train_time:549304ms step_avg:66.99ms +step:8400/20000 train_loss:1.9895 train_time:562862ms step_avg:67.01ms +step:8600/20000 train_loss:1.9935 train_time:576288ms step_avg:67.01ms +step:8800/20000 train_loss:1.9409 train_time:589723ms step_avg:67.01ms +step:8954/20000 val_loss:1.9454 val_bpb:1.1522 train_time:600009ms step_avg:67.01ms +stopping_early: wallclock_cap train_time:600009ms step:8954/20000 +peak memory allocated: 13958 MiB reserved: 14100 MiB +swa: averaging 7 checkpoints +Serialized model: 105789375 bytes +Code size: 59624 bytes +Total submission size: 105848999 bytes +Serialized model int8+zlib: 15603038 bytes (payload:27057508 raw_torch:27113999 payload_ratio:3.91x) +Total submission size int8+zlib: 15662662 bytes +final_int8_zlib_roundtrip val_loss:1.9634 val_bpb:1.1628 eval_time:2106ms eval_seq_len:2048 +final_int8_zlib_roundtrip_exact val_loss:1.96338179 val_bpb:1.16282529 +final_sliding_window val_loss:1.9262 val_bpb:1.1408 eval_time:186134ms stride:64 seq_len:2048 +final_sliding_window_exact val_loss:1.92618948 val_bpb:1.14080093