diff --git a/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/README.md b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/README.md new file mode 100644 index 000000000..5671100b2 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/README.md @@ -0,0 +1,81 @@ +# 11L GEPA 30k Steps Pure Int6 Legal TTT + +## Result: 1.09197 BPB (non-record track) + +### Architecture +- 11 transformer layers, 512-dim, 8 heads (4 KV), MLP=1536 +- Value Embedding (VE_DIM=128) on layers 9,10 +- BigramHash(2048, dim=128), Partial RoPE (16 dims) +- ReLU² MLP, U-Net skip connections, SmearGate +- 27M parameters + +### Training +- **30000 steps** on 4×A100-40GB (~4.17 hours) +- 786K tokens/step = 23.59B tokens total +- Muon optimizer: LR=0.025 (matrix), 0.035 (tied embed), decoder 2× mult +- Muon momentum: 0.92→0.99 warmup over 1500 steps +- Weight decay: 0.04, Gradient clip: 0.3 +- EMA decay 0.997 +- **Warmdown: 18000 steps (60%)** — key insight: longer warmdown reduces quant gap +- Warmup: 20 steps + +### Quantization +- Pure int6 per-row + zstd-22 compression +- GPTQ-lite with 15-percentile clip search +- QUANT_EMBED=1 (int6 per-row for embeddings) +- **Artifact: 14,057,451 bytes (13.40 MB)** +- **Quant gap: 0.0224** (float 1.1043 → quant 1.1267) + +### Test-Time Training (Legal) +- SGD with momentum=0.9, lr=0.002, 10 epochs per chunk +- 32768 tokens/chunk, freeze first 2 blocks +- Gradient clip: 1.0 +- Cosine LR decay across chunks with 50-chunk warmup +- **TTT gain: -0.035** (quant 1.1267 → TTT 1.0920) + +### Training Trajectory +| Step | val_bpb | Phase | +|------|---------|-------| +| 500 | 1.3944 | Warmup | +| 5000 | 1.2315 | Peak LR | +| 10000 | 1.2177 | Peak LR plateau | +| 12000 | 1.2178 | Warmdown start | +| 15000 | 1.2021 | Early warmdown | +| 20000 | 1.1828 | Mid warmdown | +| 25000 | 1.1561 | Deep warmdown | +| 27000 | 1.1397 | Acceleration | +| 29000 | 1.1167 | Rapid convergence | +| 30000 | **1.1043** | **Final** | + +### Key Insights +1. **60% warmdown ratio** reduces quantization gap from 0.027 → 0.022 (5 mBPB) +2. **Peak-LR plateau** at ~1.217 reached by step ~9000 — longer peak LR has diminishing returns +3. **Final 5000 steps** of warmdown produce largest BPP decline (−0.052 from step 25k→30k) +4. **SGD TTT** more stable than AdamW TTT for this architecture +5. Scaling from 25k→30k steps: -0.0024 BPP improvement + +### Scaling Law (observed) +| Steps | Float base | TTT final | Δ from prev | +|-------|-----------|-----------|-------------| +| 9000 | 1.1353 | 1.1157 | — | +| 12000 | 1.1268 | 1.1079 | -0.008 | +| 15000 | 1.1217 | 1.1035 | -0.004 | +| 20000 | 1.1153 | 1.0983 | -0.005 | +| 25000 | 1.1088 | 1.0944 | -0.004 | +| **30000** | **1.1043** | **1.0920** | **−0.002** | + +--- + +## Acknowledgments + +This submission builds on techniques introduced by many contributors to the parameter-golf community: + +- **signalrush** (PR #414): GPTQ-lite clip search and EMA — the quantization backbone of this submission +- **jfprincz** (PR #315): Partial RoPE (16/64 dims) and layerwise LN scale +- **jfprincz** (PR #287): XSA on last 4 layers, EMA replacing SWA, MLP 3× expansion +- **unnir** (PR #265): Efficient Partial XSA concept +- **raahilshah** (PR #162): SmearGate, BigramHash embeddings, OrthoInit, Muon weight decay +- **aruniyer** (PR #86): Int6 quantization with STE QAT +- **samacqua**: LoRA-based test-time training concept +- **abaybektursun** (PR #549): LeakyReLU² activation exploration +- **OpenAI**: Baseline architecture, Muon optimizer, and competition infrastructure diff --git a/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/final_model.int6.ptz b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/final_model.int6.ptz new file mode 100644 index 000000000..6efb96e9d Binary files /dev/null and b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/final_model.int6.ptz differ diff --git a/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/submission.json b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/submission.json new file mode 100644 index 000000000..db745d605 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/submission.json @@ -0,0 +1,16 @@ +{ + "track": "non_record_16mb", + "val_bpb": 1.09197267, + "model_file": "final_model.int6.ptz", + "model_bytes": 14057451, + "total_submission_bytes": 14136140, + "training_tokens_billions": 23.59, + "training_script": "train_gpt.py", + "hardware": "4×A100-40GB", + "training_time_hours": 4.17, + "quantization": "int6+zstd-22", + "ttt_optimizer": "sgd", + "ttt_epochs": 10, + "ttt_lr": 0.002, + "date": "2026-03-24" +} diff --git a/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/train.log b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/train.log new file mode 100644 index 000000000..23187cebd --- /dev/null +++ b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/train.log @@ -0,0 +1,2071 @@ +logs/exp_30k_wd18_55245372.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=/hpfs/scratch/gpfs/mcclec07/code/parameter_golf/repo/data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=/hpfs/scratch/gpfs/mcclec07/code/parameter_golf/repo/data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +model_params:27030107 +world_size:4 grad_accum_steps:2 +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 decoder_lr_mult:2.0 +train_batch_tokens:786432 train_seq_len:2048 iterations:30000 warmup_steps:20 max_wallclock_seconds:0.000 +rope_dims:16 rope_train_seq_len:2048 ln_scale:True +muon_wd:0.04 adam_wd:0.04 ema_enabled:True late_qat:False +bigram_buckets:2048 bigram_embed_dim:128 seed:42 +ttt:enabled optimizer:sgd lr:0.002 epochs:10 freeze_blocks:2 chunk_tokens:32768 +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 +ema:init decay=0.997 +step:0/30000 val_loss:6.9300 val_bpb:4.1043 train_time:0ms step_avg:0.01ms +step:1/30000 train_loss:6.9314 train_time:546ms step_avg:545.60ms +step:2/30000 train_loss:8.5481 train_time:1026ms step_avg:512.82ms +step:3/30000 train_loss:7.3850 train_time:1534ms step_avg:511.45ms +step:4/30000 train_loss:7.5582 train_time:2033ms step_avg:508.27ms +step:5/30000 train_loss:7.5099 train_time:2529ms step_avg:505.86ms +step:6/30000 train_loss:7.2042 train_time:3032ms step_avg:505.26ms +step:7/30000 train_loss:6.9774 train_time:3531ms step_avg:504.39ms +step:8/30000 train_loss:6.7045 train_time:4034ms step_avg:504.29ms +step:9/30000 train_loss:6.4178 train_time:4538ms step_avg:504.23ms +step:10/30000 train_loss:6.0545 train_time:5040ms step_avg:504.00ms +step:200/30000 train_loss:2.4991 train_time:100586ms step_avg:502.93ms +step:400/30000 train_loss:2.4016 train_time:201238ms step_avg:503.09ms +step:500/30000 val_loss:2.3544 val_bpb:1.3944 train_time:251247ms step_avg:502.49ms +step:600/30000 train_loss:2.3529 train_time:301166ms step_avg:501.94ms +step:800/30000 train_loss:2.2454 train_time:401146ms step_avg:501.43ms +step:1000/30000 train_loss:2.2826 train_time:501164ms step_avg:501.16ms +step:1000/30000 val_loss:2.2328 val_bpb:1.3224 train_time:501172ms step_avg:501.17ms +step:1200/30000 train_loss:2.2797 train_time:601372ms step_avg:501.14ms +step:1400/30000 train_loss:2.2434 train_time:701432ms step_avg:501.02ms +step:1500/30000 val_loss:2.1898 val_bpb:1.2969 train_time:751450ms step_avg:500.97ms +step:1600/30000 train_loss:2.1355 train_time:801509ms step_avg:500.94ms +step:1800/30000 train_loss:2.1406 train_time:901887ms step_avg:501.05ms +step:2000/30000 train_loss:2.0338 train_time:1002034ms step_avg:501.02ms +step:2000/30000 val_loss:2.1366 val_bpb:1.2654 train_time:1002043ms step_avg:501.02ms +step:2200/30000 train_loss:2.1482 train_time:1102201ms step_avg:501.00ms +step:2400/30000 train_loss:2.0886 train_time:1202166ms step_avg:500.90ms +step:2500/30000 val_loss:2.1161 val_bpb:1.2533 train_time:1252164ms step_avg:500.87ms +step:2600/30000 train_loss:2.1544 train_time:1302340ms step_avg:500.90ms +step:2800/30000 train_loss:2.1919 train_time:1402561ms step_avg:500.91ms +step:3000/30000 train_loss:2.1185 train_time:1502572ms step_avg:500.86ms +step:3000/30000 val_loss:2.1042 val_bpb:1.2463 train_time:1502581ms step_avg:500.86ms +step:3200/30000 train_loss:2.1521 train_time:1602688ms step_avg:500.84ms +step:3400/30000 train_loss:2.1084 train_time:1702959ms step_avg:500.87ms +step:3500/30000 val_loss:2.0994 val_bpb:1.2434 train_time:1753105ms step_avg:500.89ms +step:3600/30000 train_loss:2.1061 train_time:1803280ms step_avg:500.91ms +step:3800/30000 train_loss:2.0990 train_time:1903312ms step_avg:500.87ms +step:4000/30000 train_loss:2.1643 train_time:2003214ms step_avg:500.80ms +step:4000/30000 val_loss:2.0957 val_bpb:1.2412 train_time:2003223ms step_avg:500.81ms +step:4200/30000 train_loss:2.1060 train_time:2103360ms step_avg:500.80ms +step:4400/30000 train_loss:2.0328 train_time:2203369ms step_avg:500.77ms +step:4500/30000 val_loss:2.0837 val_bpb:1.2341 train_time:2253541ms step_avg:500.79ms +step:4600/30000 train_loss:1.9880 train_time:2303446ms step_avg:500.75ms +step:4800/30000 train_loss:2.2877 train_time:2403445ms step_avg:500.72ms +step:5000/30000 train_loss:2.0968 train_time:2503743ms step_avg:500.75ms +step:5000/30000 val_loss:2.0793 val_bpb:1.2315 train_time:2503752ms step_avg:500.75ms +step:5200/30000 train_loss:2.1061 train_time:2603884ms step_avg:500.75ms +step:5400/30000 train_loss:2.0465 train_time:2703992ms step_avg:500.74ms +step:5500/30000 val_loss:2.0744 val_bpb:1.2286 train_time:2754030ms step_avg:500.73ms +step:5600/30000 train_loss:2.0674 train_time:2803995ms step_avg:500.71ms +step:5800/30000 train_loss:2.0491 train_time:2903970ms step_avg:500.68ms +step:6000/30000 train_loss:2.0347 train_time:3004253ms step_avg:500.71ms +step:6000/30000 val_loss:2.0755 val_bpb:1.2292 train_time:3004261ms step_avg:500.71ms +step:6200/30000 train_loss:2.1313 train_time:3104267ms step_avg:500.69ms +step:6400/30000 train_loss:2.0912 train_time:3204261ms step_avg:500.67ms +step:6500/30000 val_loss:2.0675 val_bpb:1.2245 train_time:3254204ms step_avg:500.65ms +step:6600/30000 train_loss:2.0028 train_time:3304142ms step_avg:500.63ms +step:6800/30000 train_loss:2.1588 train_time:3404444ms step_avg:500.65ms +step:7000/30000 train_loss:1.9374 train_time:3504696ms step_avg:500.67ms +step:7000/30000 val_loss:2.0686 val_bpb:1.2251 train_time:3504704ms step_avg:500.67ms +step:7200/30000 train_loss:2.0828 train_time:3604530ms step_avg:500.63ms +step:7400/30000 train_loss:2.0681 train_time:3704693ms step_avg:500.63ms +step:7500/30000 val_loss:2.0670 val_bpb:1.2242 train_time:3754695ms step_avg:500.63ms +step:7600/30000 train_loss:2.0143 train_time:3804846ms step_avg:500.64ms +step:7800/30000 train_loss:2.0304 train_time:3905040ms step_avg:500.65ms +step:8000/30000 train_loss:2.0140 train_time:4004829ms step_avg:500.60ms +step:8000/30000 val_loss:2.0622 val_bpb:1.2213 train_time:4004837ms step_avg:500.60ms +step:8200/30000 train_loss:2.0625 train_time:4104779ms step_avg:500.58ms +step:8400/30000 train_loss:2.0754 train_time:4204972ms step_avg:500.59ms +step:8500/30000 val_loss:2.0630 val_bpb:1.2218 train_time:4254913ms step_avg:500.58ms +step:8600/30000 train_loss:2.1466 train_time:4305002ms step_avg:500.58ms +step:8800/30000 train_loss:2.0648 train_time:4404960ms step_avg:500.56ms +step:9000/30000 train_loss:2.1183 train_time:4505014ms step_avg:500.56ms +step:9000/30000 val_loss:2.0600 val_bpb:1.2200 train_time:4505023ms step_avg:500.56ms +step:9200/30000 train_loss:2.0344 train_time:4605134ms step_avg:500.56ms +step:9400/30000 train_loss:2.1019 train_time:4705289ms step_avg:500.56ms +step:9500/30000 val_loss:2.0585 val_bpb:1.2192 train_time:4755350ms step_avg:500.56ms +step:9600/30000 train_loss:2.0706 train_time:4805279ms step_avg:500.55ms +step:9800/30000 train_loss:2.1013 train_time:4905163ms step_avg:500.53ms +step:10000/30000 train_loss:2.0922 train_time:5005214ms step_avg:500.52ms +step:10000/30000 val_loss:2.0560 val_bpb:1.2177 train_time:5005223ms step_avg:500.52ms +step:10200/30000 train_loss:2.0143 train_time:5105485ms step_avg:500.54ms +step:10400/30000 train_loss:2.0549 train_time:5205469ms step_avg:500.53ms +step:10500/30000 val_loss:2.0571 val_bpb:1.2183 train_time:5255466ms step_avg:500.52ms +step:10600/30000 train_loss:2.0377 train_time:5305364ms step_avg:500.51ms +step:10800/30000 train_loss:2.0364 train_time:5405491ms step_avg:500.51ms +step:11000/30000 train_loss:2.0159 train_time:5505707ms step_avg:500.52ms +step:11000/30000 val_loss:2.0543 val_bpb:1.2167 train_time:5505716ms step_avg:500.52ms +step:11200/30000 train_loss:2.0763 train_time:5605621ms step_avg:500.50ms +step:11400/30000 train_loss:2.0671 train_time:5705543ms step_avg:500.49ms +step:11500/30000 val_loss:2.0529 val_bpb:1.2158 train_time:5755598ms step_avg:500.49ms +step:11600/30000 train_loss:2.0398 train_time:5805690ms step_avg:500.49ms +step:11800/30000 train_loss:2.0627 train_time:5905811ms step_avg:500.49ms +step:12000/30000 train_loss:1.9935 train_time:6005889ms step_avg:500.49ms +step:12000/30000 val_loss:2.0562 val_bpb:1.2178 train_time:6005898ms step_avg:500.49ms +step:12200/30000 train_loss:2.1148 train_time:6105865ms step_avg:500.48ms +step:12400/30000 train_loss:2.2111 train_time:6205913ms step_avg:500.48ms +step:12500/30000 val_loss:2.0494 val_bpb:1.2138 train_time:6256014ms step_avg:500.48ms +step:12600/30000 train_loss:2.1433 train_time:6306127ms step_avg:500.49ms +step:12800/30000 train_loss:2.6056 train_time:6405968ms step_avg:500.47ms +step:13000/30000 train_loss:2.0102 train_time:6505795ms step_avg:500.45ms +step:13000/30000 val_loss:2.0422 val_bpb:1.2095 train_time:6505804ms step_avg:500.45ms +step:13200/30000 train_loss:1.9565 train_time:6605524ms step_avg:500.42ms +step:13400/30000 train_loss:1.9784 train_time:6705721ms step_avg:500.43ms +step:13500/30000 val_loss:2.0417 val_bpb:1.2092 train_time:6755812ms step_avg:500.43ms +step:13600/30000 train_loss:2.0012 train_time:6805749ms step_avg:500.42ms +step:13800/30000 train_loss:2.0028 train_time:6905670ms step_avg:500.41ms +step:14000/30000 train_loss:1.9311 train_time:7005748ms step_avg:500.41ms +step:14000/30000 val_loss:2.0378 val_bpb:1.2069 train_time:7005757ms step_avg:500.41ms +step:14200/30000 train_loss:2.1196 train_time:7105708ms step_avg:500.40ms +step:14400/30000 train_loss:2.0805 train_time:7205813ms step_avg:500.40ms +step:14500/30000 val_loss:2.0390 val_bpb:1.2076 train_time:7255726ms step_avg:500.39ms +step:14600/30000 train_loss:2.0142 train_time:7305707ms step_avg:500.39ms +step:14800/30000 train_loss:2.0834 train_time:7405717ms step_avg:500.39ms +step:15000/30000 train_loss:2.0554 train_time:7505740ms step_avg:500.38ms +step:15000/30000 val_loss:2.0298 val_bpb:1.2021 train_time:7505748ms step_avg:500.38ms +step:15200/30000 train_loss:1.9792 train_time:7605871ms step_avg:500.39ms +step:15400/30000 train_loss:2.1544 train_time:7705640ms step_avg:500.37ms +step:15500/30000 val_loss:2.0291 val_bpb:1.2017 train_time:7755479ms step_avg:500.35ms +step:15600/30000 train_loss:2.0694 train_time:7805388ms step_avg:500.35ms +step:15800/30000 train_loss:2.0544 train_time:7905682ms step_avg:500.36ms +step:16000/30000 train_loss:2.1075 train_time:8005762ms step_avg:500.36ms +step:16000/30000 val_loss:2.0256 val_bpb:1.1997 train_time:8005770ms step_avg:500.36ms +step:16200/30000 train_loss:1.9772 train_time:8105677ms step_avg:500.35ms +step:16400/30000 train_loss:1.9736 train_time:8205540ms step_avg:500.34ms +step:16500/30000 val_loss:2.0261 val_bpb:1.2000 train_time:8255585ms step_avg:500.34ms +step:16600/30000 train_loss:2.0822 train_time:8305669ms step_avg:500.34ms +step:16800/30000 train_loss:2.0487 train_time:8405837ms step_avg:500.35ms +step:17000/30000 train_loss:2.0848 train_time:8505621ms step_avg:500.33ms +step:17000/30000 val_loss:2.0189 val_bpb:1.1957 train_time:8505629ms step_avg:500.33ms +step:17200/30000 train_loss:2.0493 train_time:8605383ms step_avg:500.31ms +step:17400/30000 train_loss:1.9419 train_time:8705424ms step_avg:500.31ms +step:17500/30000 val_loss:2.0144 val_bpb:1.1931 train_time:8755544ms step_avg:500.32ms +step:17600/30000 train_loss:2.0639 train_time:8805645ms step_avg:500.32ms +step:17800/30000 train_loss:2.0593 train_time:8905422ms step_avg:500.30ms +step:18000/30000 train_loss:1.9512 train_time:9005173ms step_avg:500.29ms +step:18000/30000 val_loss:2.0108 val_bpb:1.1909 train_time:9005182ms step_avg:500.29ms +step:18200/30000 train_loss:1.9921 train_time:9105373ms step_avg:500.30ms +step:18400/30000 train_loss:1.8727 train_time:9205259ms step_avg:500.29ms +step:18500/30000 val_loss:2.0110 val_bpb:1.1910 train_time:9255177ms step_avg:500.28ms +step:18600/30000 train_loss:1.9433 train_time:9305094ms step_avg:500.27ms +step:18800/30000 train_loss:2.0571 train_time:9405042ms step_avg:500.27ms +step:19000/30000 train_loss:1.8993 train_time:9505118ms step_avg:500.27ms +step:19000/30000 val_loss:2.0070 val_bpb:1.1887 train_time:9505126ms step_avg:500.27ms +step:19200/30000 train_loss:2.0513 train_time:9604958ms step_avg:500.26ms +step:19400/30000 train_loss:1.9864 train_time:9704875ms step_avg:500.25ms +step:19500/30000 val_loss:2.0046 val_bpb:1.1872 train_time:9754861ms step_avg:500.25ms +step:19600/30000 train_loss:2.0123 train_time:9804830ms step_avg:500.25ms +step:19800/30000 train_loss:2.0956 train_time:9904885ms step_avg:500.25ms +step:20000/30000 train_loss:2.0031 train_time:10005089ms step_avg:500.25ms +step:20000/30000 val_loss:1.9970 val_bpb:1.1828 train_time:10005097ms step_avg:500.25ms +step:20200/30000 train_loss:2.0028 train_time:10104822ms step_avg:500.24ms +step:20400/30000 train_loss:1.9961 train_time:10204416ms step_avg:500.22ms +step:20500/30000 val_loss:1.9921 val_bpb:1.1798 train_time:10254410ms step_avg:500.22ms +step:20600/30000 train_loss:2.0058 train_time:10304412ms step_avg:500.21ms +step:20800/30000 train_loss:2.0867 train_time:10404313ms step_avg:500.21ms +step:21000/30000 train_loss:1.9591 train_time:10504183ms step_avg:500.20ms +step:21000/30000 val_loss:1.9904 val_bpb:1.1788 train_time:10504191ms step_avg:500.20ms +step:21200/30000 train_loss:1.9145 train_time:10604005ms step_avg:500.19ms +step:21400/30000 train_loss:1.8732 train_time:10703916ms step_avg:500.18ms +step:21500/30000 val_loss:1.9850 val_bpb:1.1756 train_time:10754028ms step_avg:500.19ms +step:21600/30000 train_loss:1.9156 train_time:10803813ms step_avg:500.18ms +step:21800/30000 train_loss:1.9684 train_time:10903755ms step_avg:500.17ms +step:22000/30000 train_loss:1.9974 train_time:11003433ms step_avg:500.16ms +step:22000/30000 val_loss:1.9812 val_bpb:1.1734 train_time:11003442ms step_avg:500.16ms +step:22200/30000 train_loss:1.9005 train_time:11103329ms step_avg:500.15ms +step:22400/30000 train_loss:1.9658 train_time:11203460ms step_avg:500.15ms +step:22500/30000 val_loss:1.9771 val_bpb:1.1710 train_time:11253320ms step_avg:500.15ms +step:22600/30000 train_loss:2.0321 train_time:11303298ms step_avg:500.15ms +step:22800/30000 train_loss:1.8939 train_time:11403073ms step_avg:500.13ms +step:23000/30000 train_loss:1.9373 train_time:11502893ms step_avg:500.13ms +step:23000/30000 val_loss:1.9718 val_bpb:1.1678 train_time:11502901ms step_avg:500.13ms +step:23200/30000 train_loss:2.0103 train_time:11602872ms step_avg:500.12ms +step:23400/30000 train_loss:1.9853 train_time:11702818ms step_avg:500.12ms +step:23500/30000 val_loss:1.9679 val_bpb:1.1655 train_time:11752727ms step_avg:500.12ms +step:23600/30000 train_loss:1.9675 train_time:11802656ms step_avg:500.11ms +step:23800/30000 train_loss:1.9904 train_time:11902737ms step_avg:500.12ms +step:24000/30000 train_loss:1.9170 train_time:12002855ms step_avg:500.12ms +step:24000/30000 val_loss:1.9646 val_bpb:1.1635 train_time:12002863ms step_avg:500.12ms +step:24200/30000 train_loss:2.0116 train_time:12102918ms step_avg:500.12ms +step:24400/30000 train_loss:1.9096 train_time:12202600ms step_avg:500.11ms +step:24500/30000 val_loss:1.9570 val_bpb:1.1591 train_time:12252463ms step_avg:500.10ms +step:24600/30000 train_loss:2.0602 train_time:12302337ms step_avg:500.10ms +step:24800/30000 train_loss:1.9444 train_time:12402464ms step_avg:500.10ms +step:25000/30000 train_loss:1.9634 train_time:12502450ms step_avg:500.10ms +step:25000/30000 val_loss:1.9520 val_bpb:1.1561 train_time:12502458ms step_avg:500.10ms +step:25200/30000 train_loss:1.9027 train_time:12602150ms step_avg:500.09ms +step:25400/30000 train_loss:2.0850 train_time:12701929ms step_avg:500.08ms +step:25500/30000 val_loss:1.9443 val_bpb:1.1515 train_time:12751892ms step_avg:500.07ms +step:25600/30000 train_loss:1.9483 train_time:12801985ms step_avg:500.08ms +step:25800/30000 train_loss:1.9880 train_time:12901764ms step_avg:500.07ms +step:26000/30000 train_loss:2.0057 train_time:13001484ms step_avg:500.06ms +step:26000/30000 val_loss:1.9381 val_bpb:1.1479 train_time:13001492ms step_avg:500.06ms +step:26200/30000 train_loss:1.9545 train_time:13101168ms step_avg:500.04ms +step:26400/30000 train_loss:1.9307 train_time:13201127ms step_avg:500.04ms +step:26500/30000 val_loss:1.9317 val_bpb:1.1441 train_time:13251332ms step_avg:500.05ms +step:26600/30000 train_loss:1.8534 train_time:13301371ms step_avg:500.05ms +step:26800/30000 train_loss:1.9410 train_time:13401029ms step_avg:500.04ms +step:27000/30000 train_loss:1.9123 train_time:13500885ms step_avg:500.03ms +step:27000/30000 val_loss:1.9244 val_bpb:1.1397 train_time:13500894ms step_avg:500.03ms +step:27200/30000 train_loss:2.0025 train_time:13600801ms step_avg:500.03ms +step:27400/30000 train_loss:2.0013 train_time:13700943ms step_avg:500.03ms +step:27500/30000 val_loss:1.9159 val_bpb:1.1347 train_time:13750832ms step_avg:500.03ms +step:27600/30000 train_loss:1.9193 train_time:13800722ms step_avg:500.03ms +step:27800/30000 train_loss:1.8969 train_time:13900379ms step_avg:500.01ms +step:28000/30000 train_loss:1.7392 train_time:14000286ms step_avg:500.01ms +step:28000/30000 val_loss:1.9070 val_bpb:1.1295 train_time:14000295ms step_avg:500.01ms +step:28200/30000 train_loss:1.8931 train_time:14100167ms step_avg:500.01ms +step:28400/30000 train_loss:1.8706 train_time:14200007ms step_avg:500.00ms +step:28500/30000 val_loss:1.8955 val_bpb:1.1226 train_time:14249922ms step_avg:500.00ms +step:28600/30000 train_loss:1.9868 train_time:14299717ms step_avg:499.99ms +step:28800/30000 train_loss:1.9378 train_time:14399533ms step_avg:499.98ms +step:29000/30000 train_loss:1.9117 train_time:14499515ms step_avg:499.98ms +step:29000/30000 val_loss:1.8854 val_bpb:1.1167 train_time:14499523ms step_avg:499.98ms +step:29200/30000 train_loss:1.9355 train_time:14599105ms step_avg:499.97ms +step:29400/30000 train_loss:1.9370 train_time:14698635ms step_avg:499.95ms +step:29500/30000 val_loss:1.8736 val_bpb:1.1097 train_time:14748462ms step_avg:499.95ms +step:29600/30000 train_loss:1.8760 train_time:14798307ms step_avg:499.94ms +step:29800/30000 train_loss:1.7713 train_time:14898217ms step_avg:499.94ms +step:30000/30000 train_loss:1.8458 train_time:14997969ms step_avg:499.93ms +step:30000/30000 val_loss:1.8646 val_bpb:1.1043 train_time:14997977ms step_avg:499.93ms +peak memory allocated: 21231 MiB reserved: 21414 MiB +ema:applying EMA weights +Serialized model: 107123189 bytes +Code size: 78689 bytes +Total submission size: 107201878 bytes +Serialized model int6+zstd-22: 14057451 bytes (payload:27530604 raw_torch:27595991 payload_ratio:3.89x) +Total submission size int6+zstd-22: 14136140 bytes +pre_ttt_quant_eval val_loss:1.902436 val_bpb:1.126730 elapsed:27.8s +final_eval_mode:sliding_window_ttt stride:64 chunk_tokens:32768 optimizer:sgd +ttt_sliding:start chunks=1893 chunk_tokens=32768 total_windows=969088 stride=64 ttt_lr=0.002 ttt_epochs=10 ttt_optimizer=sgd freeze_blocks=2 +ttt_sliding:params unfrozen=22301259 frozen=4728848 + ttt_chunk [1/1893] bpb=1.144238 time=1.1s + ttt_chunk [11/1893] bpb=1.106734 time=11.9s + ttt_chunk [21/1893] bpb=1.110751 time=22.8s + ttt_chunk [31/1893] bpb=1.114003 time=33.7s + ttt_chunk [41/1893] bpb=1.102340 time=44.6s + ttt_chunk [51/1893] bpb=1.098278 time=55.5s + ttt_chunk [61/1893] bpb=1.102372 time=66.4s + ttt_chunk [71/1893] bpb=1.099190 time=77.3s + ttt_chunk [81/1893] bpb=1.099001 time=88.3s + ttt_chunk [91/1893] bpb=1.097374 time=99.2s + ttt_chunk [101/1893] bpb=1.100026 time=110.1s + ttt_chunk [111/1893] bpb=1.101028 time=121.0s + ttt_chunk [121/1893] bpb=1.097556 time=132.0s + ttt_chunk [131/1893] bpb=1.097331 time=142.9s + ttt_chunk [141/1893] bpb=1.096855 time=153.8s + ttt_chunk [151/1893] bpb=1.099890 time=164.7s + ttt_chunk [161/1893] bpb=1.101477 time=175.7s + ttt_chunk [171/1893] bpb=1.102018 time=186.6s + ttt_chunk [181/1893] bpb=1.101935 time=197.5s + ttt_chunk [191/1893] bpb=1.105097 time=208.4s + ttt_chunk [201/1893] bpb=1.105417 time=219.3s + ttt_chunk [211/1893] bpb=1.102946 time=230.2s + ttt_chunk [221/1893] bpb=1.104959 time=241.2s + ttt_chunk [231/1893] bpb=1.104326 time=252.1s + ttt_chunk [241/1893] bpb=1.104048 time=263.0s + ttt_chunk [251/1893] bpb=1.102481 time=273.9s + ttt_chunk [261/1893] bpb=1.100760 time=284.8s + ttt_chunk [271/1893] bpb=1.099409 time=295.7s + ttt_chunk [281/1893] bpb=1.101660 time=306.6s + ttt_chunk [291/1893] bpb=1.102369 time=317.6s + ttt_chunk [301/1893] bpb=1.102909 time=328.5s + ttt_chunk [311/1893] bpb=1.104429 time=339.4s + ttt_chunk [321/1893] bpb=1.105875 time=350.3s + ttt_chunk [331/1893] bpb=1.105674 time=361.2s + ttt_chunk [341/1893] bpb=1.105922 time=372.1s + ttt_chunk [351/1893] bpb=1.107170 time=383.0s + ttt_chunk [361/1893] bpb=1.108321 time=393.9s + ttt_chunk [371/1893] bpb=1.107851 time=404.8s + ttt_chunk [381/1893] bpb=1.107781 time=415.8s + ttt_chunk [391/1893] bpb=1.107369 time=426.7s + ttt_chunk [401/1893] bpb=1.105965 time=437.6s + ttt_chunk [411/1893] bpb=1.104863 time=448.5s + ttt_chunk [421/1893] bpb=1.104320 time=459.4s + ttt_chunk [431/1893] bpb=1.104986 time=470.3s + ttt_chunk [441/1893] bpb=1.104798 time=481.2s + ttt_chunk [451/1893] bpb=1.104455 time=492.1s + ttt_chunk [461/1893] bpb=1.103683 time=503.0s + ttt_chunk [471/1893] bpb=1.103263 time=514.0s + ttt_chunk [481/1893] bpb=1.102955 time=524.9s + ttt_chunk [491/1893] bpb=1.102649 time=535.8s + ttt_chunk [501/1893] bpb=1.102090 time=546.7s + ttt_chunk [511/1893] bpb=1.101452 time=557.6s + ttt_chunk [521/1893] bpb=1.100370 time=568.5s + ttt_chunk [531/1893] bpb=1.100435 time=579.4s + ttt_chunk [541/1893] bpb=1.100395 time=590.3s + ttt_chunk [551/1893] bpb=1.099223 time=601.3s + ttt_chunk [561/1893] bpb=1.099746 time=612.2s + ttt_chunk [571/1893] bpb=1.099015 time=623.1s + ttt_chunk [581/1893] bpb=1.098438 time=634.0s + ttt_chunk [591/1893] bpb=1.097752 time=644.9s + ttt_chunk [601/1893] bpb=1.098435 time=655.8s + ttt_chunk [611/1893] bpb=1.097969 time=666.7s + ttt_chunk [621/1893] bpb=1.097872 time=677.7s + ttt_chunk [631/1893] bpb=1.098257 time=688.6s + ttt_chunk [641/1893] bpb=1.098033 time=699.5s + ttt_chunk [651/1893] bpb=1.098012 time=710.4s + ttt_chunk [661/1893] bpb=1.097925 time=721.4s + ttt_chunk [671/1893] bpb=1.097564 time=732.3s + ttt_chunk [681/1893] bpb=1.097841 time=743.2s + ttt_chunk [691/1893] bpb=1.098505 time=754.1s + ttt_chunk [701/1893] bpb=1.097710 time=765.0s + ttt_chunk [711/1893] bpb=1.098286 time=775.9s + ttt_chunk [721/1893] bpb=1.097890 time=786.8s + ttt_chunk [731/1893] bpb=1.098321 time=797.7s + ttt_chunk [741/1893] bpb=1.098280 time=808.6s + ttt_chunk [751/1893] bpb=1.097917 time=819.6s + ttt_chunk [761/1893] bpb=1.097752 time=830.5s + ttt_chunk [771/1893] bpb=1.097531 time=841.4s + ttt_chunk [781/1893] bpb=1.098051 time=852.3s + ttt_chunk [791/1893] bpb=1.097692 time=863.2s + ttt_chunk [801/1893] bpb=1.097774 time=874.1s + ttt_chunk [811/1893] bpb=1.097280 time=885.0s + ttt_chunk [821/1893] bpb=1.097090 time=895.9s + ttt_chunk [831/1893] bpb=1.096646 time=906.8s + ttt_chunk [841/1893] bpb=1.096059 time=917.7s + ttt_chunk [851/1893] bpb=1.095935 time=928.6s + ttt_chunk [861/1893] bpb=1.096071 time=939.6s + ttt_chunk [871/1893] bpb=1.096090 time=950.5s + ttt_chunk [881/1893] bpb=1.096085 time=961.4s + ttt_chunk [891/1893] bpb=1.095899 time=972.3s + ttt_chunk [901/1893] bpb=1.095873 time=983.2s + ttt_chunk [911/1893] bpb=1.095865 time=994.1s + ttt_chunk [921/1893] bpb=1.096213 time=1005.0s + ttt_chunk [931/1893] bpb=1.096049 time=1015.9s + ttt_chunk [941/1893] bpb=1.095947 time=1026.8s + ttt_chunk [951/1893] bpb=1.095952 time=1037.7s + ttt_chunk [961/1893] bpb=1.095702 time=1048.6s + ttt_chunk [971/1893] bpb=1.096410 time=1059.5s + ttt_chunk [981/1893] bpb=1.096564 time=1070.4s + ttt_chunk [991/1893] bpb=1.096465 time=1081.3s + ttt_chunk [1001/1893] bpb=1.096600 time=1092.2s + ttt_chunk [1011/1893] bpb=1.096849 time=1103.1s + ttt_chunk [1021/1893] bpb=1.096995 time=1114.0s + ttt_chunk [1031/1893] bpb=1.097540 time=1124.9s + ttt_chunk [1041/1893] bpb=1.097195 time=1135.8s + ttt_chunk [1051/1893] bpb=1.096931 time=1146.7s + ttt_chunk [1061/1893] bpb=1.097171 time=1157.6s + ttt_chunk [1071/1893] bpb=1.097623 time=1168.5s + ttt_chunk [1081/1893] bpb=1.097641 time=1179.4s + ttt_chunk [1091/1893] bpb=1.098038 time=1190.4s + ttt_chunk [1101/1893] bpb=1.098168 time=1201.3s + ttt_chunk [1111/1893] bpb=1.097948 time=1212.2s + ttt_chunk [1121/1893] bpb=1.097865 time=1223.1s + ttt_chunk [1131/1893] bpb=1.097777 time=1234.0s + ttt_chunk [1141/1893] bpb=1.097631 time=1244.9s + ttt_chunk [1151/1893] bpb=1.097673 time=1255.8s + ttt_chunk [1161/1893] bpb=1.096980 time=1266.7s + ttt_chunk [1171/1893] bpb=1.097561 time=1277.6s + ttt_chunk [1181/1893] bpb=1.097045 time=1288.5s + ttt_chunk [1191/1893] bpb=1.096742 time=1299.4s + ttt_chunk [1201/1893] bpb=1.097314 time=1310.3s + ttt_chunk [1211/1893] bpb=1.096736 time=1321.2s + ttt_chunk [1221/1893] bpb=1.096434 time=1332.2s + ttt_chunk [1231/1893] bpb=1.096362 time=1343.1s + ttt_chunk [1241/1893] bpb=1.096176 time=1354.0s + ttt_chunk [1251/1893] bpb=1.095931 time=1364.9s + ttt_chunk [1261/1893] bpb=1.095864 time=1375.8s + ttt_chunk [1271/1893] bpb=1.095656 time=1386.7s + ttt_chunk [1281/1893] bpb=1.095457 time=1397.6s + ttt_chunk [1291/1893] bpb=1.095263 time=1408.6s + ttt_chunk [1301/1893] bpb=1.094875 time=1419.5s + ttt_chunk [1311/1893] bpb=1.094556 time=1430.4s + ttt_chunk [1321/1893] bpb=1.094368 time=1441.3s + ttt_chunk [1331/1893] bpb=1.094276 time=1452.2s + ttt_chunk [1341/1893] bpb=1.094154 time=1463.1s + ttt_chunk [1351/1893] bpb=1.094097 time=1474.0s + ttt_chunk [1361/1893] bpb=1.094305 time=1484.9s + ttt_chunk [1371/1893] bpb=1.094142 time=1495.8s + ttt_chunk [1381/1893] bpb=1.094051 time=1506.8s + ttt_chunk [1391/1893] bpb=1.093534 time=1517.7s + ttt_chunk [1401/1893] bpb=1.093535 time=1528.6s + ttt_chunk [1411/1893] bpb=1.093563 time=1539.5s + ttt_chunk [1421/1893] bpb=1.093801 time=1550.4s + ttt_chunk [1431/1893] bpb=1.093653 time=1561.3s + ttt_chunk [1441/1893] bpb=1.094314 time=1572.2s + ttt_chunk [1451/1893] bpb=1.094417 time=1583.1s + ttt_chunk [1461/1893] bpb=1.094159 time=1594.0s + ttt_chunk [1471/1893] bpb=1.095064 time=1604.9s + ttt_chunk [1481/1893] bpb=1.094872 time=1615.8s + ttt_chunk [1491/1893] bpb=1.094874 time=1626.7s + ttt_chunk [1501/1893] bpb=1.095028 time=1637.6s + ttt_chunk [1511/1893] bpb=1.095090 time=1648.5s + ttt_chunk [1521/1893] bpb=1.095110 time=1659.4s + ttt_chunk [1531/1893] bpb=1.094932 time=1670.3s + ttt_chunk [1541/1893] bpb=1.094910 time=1681.2s + ttt_chunk [1551/1893] bpb=1.095253 time=1692.1s + ttt_chunk [1561/1893] bpb=1.095391 time=1703.0s + ttt_chunk [1571/1893] bpb=1.095518 time=1713.9s + ttt_chunk [1581/1893] bpb=1.095631 time=1724.8s + ttt_chunk [1591/1893] bpb=1.095580 time=1735.7s + ttt_chunk [1601/1893] bpb=1.095759 time=1746.6s + ttt_chunk [1611/1893] bpb=1.095828 time=1757.5s + ttt_chunk [1621/1893] bpb=1.095692 time=1768.4s + ttt_chunk [1631/1893] bpb=1.095861 time=1779.3s + ttt_chunk [1641/1893] bpb=1.095750 time=1790.2s + ttt_chunk [1651/1893] bpb=1.095660 time=1801.1s + ttt_chunk [1661/1893] bpb=1.095550 time=1812.0s + ttt_chunk [1671/1893] bpb=1.095906 time=1822.9s + ttt_chunk [1681/1893] bpb=1.096158 time=1833.8s + ttt_chunk [1691/1893] bpb=1.096122 time=1844.7s + ttt_chunk [1701/1893] bpb=1.096115 time=1855.6s + ttt_chunk [1711/1893] bpb=1.095947 time=1866.5s + ttt_chunk [1721/1893] bpb=1.095795 time=1877.4s + ttt_chunk [1731/1893] bpb=1.095752 time=1888.2s + ttt_chunk [1741/1893] bpb=1.095526 time=1899.2s + ttt_chunk [1751/1893] bpb=1.095379 time=1910.1s + ttt_chunk [1761/1893] bpb=1.095468 time=1920.9s + ttt_chunk [1771/1893] bpb=1.095400 time=1931.8s + ttt_chunk [1781/1893] bpb=1.095342 time=1942.7s + ttt_chunk [1791/1893] bpb=1.094947 time=1953.7s + ttt_chunk [1801/1893] bpb=1.094944 time=1964.6s + ttt_chunk [1811/1893] bpb=1.094777 time=1975.4s + ttt_chunk [1821/1893] bpb=1.094808 time=1986.3s + ttt_chunk [1831/1893] bpb=1.094411 time=1997.2s + ttt_chunk [1841/1893] bpb=1.094394 time=2008.2s + ttt_chunk [1851/1893] bpb=1.094164 time=2019.0s + ttt_chunk [1861/1893] bpb=1.093702 time=2030.0s + ttt_chunk [1871/1893] bpb=1.093549 time=2040.8s + ttt_chunk [1881/1893] bpb=1.093167 time=2051.7s + ttt_chunk [1891/1893] bpb=1.093004 time=2062.6s + ttt_chunk [1893/1893] bpb=1.093024 time=2064.1s +ttt_sliding:done val_loss=1.843745 val_bpb=1.091973 elapsed=2064.2s +final_int6_zstd-22_roundtrip val_loss:1.8437 val_bpb:1.0920 eval:2064650ms +final_int6_zstd-22_roundtrip_exact val_bpb:1.09197267 +to(torch.int8) + recon = q.float() * scale[:, None] + err = (t32 - recon).pow(2).mean().item() + if err < best_err: + best_q = q.contiguous() + best_s = scale.to(dtype=INT6_PER_ROW_SCALE_DTYPE).contiguous() + best_err = err + return best_q, best_s + + clip_abs = float(torch.quantile(t32.abs().flatten(), INT6_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / float(qmax) if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), qmin, qmax).to(torch.int8).contiguous() + return q, scale + +def quantize_state_dict_int6(state_dict: dict[str, Tensor]): + 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", "int6_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["int6_payload_bytes"] += tensor_nbytes(t) + continue + + # Keep small float tensors (and tok_emb.weight unless QUANT_EMBED=1) in fp16 + quant_embed = int(os.environ.get("QUANT_EMBED", "0")) + if t.numel() <= INT6_KEEP_FLOAT_MAX_NUMEL or (name == "tok_emb.weight" and not quant_embed): + kept = keep_float_tensor(name, t, passthrough_orig_dtypes) + passthrough[name] = kept + stats["int6_payload_bytes"] += tensor_nbytes(kept) + continue + + stats["num_float_tensors"] += 1 + # Mixed quantization: int6 per-row for MLP+attn, int8 per-tensor for rest + cat = _classify_param(name) + if MIXED_QUANT and cat not in ("mlp", "attn"): + q, s = quantize_float_tensor_int8_scalar(t) + qmeta[name] = {"scheme": "per_tensor", "quant_type": "int8"} + else: + q, s = quantize_float_tensor_int6(t) + 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["int6_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + quant_label = "mixed" if MIXED_QUANT else ("int8" if INT8_STORAGE else "int6") + obj: dict[str, object] = { + "__quant_format__": f"{quant_label}_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_int6(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) + 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(): + 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: + 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): + # Class-level flag: set True during late-QAT phase to enable fake int6 STE + _qat_enabled: bool = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if CastedLinear._qat_enabled and self.training and w.ndim == 2: + # Fake int6 quantization via straight-through estimator + with torch.no_grad(): + w32 = self.weight.float() + row_max = w32.abs().amax(dim=1) + scale = (row_max / 31.0).clamp_min(1.0 / 31.0) + w_q = (torch.clamp(torch.round(w32 / scale[:, None]), -32, 31) * scale[:, None]).to(x.dtype) + w = w + (w_q - w).detach() + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + """RoPE with optional partial application and YARN scaling.""" + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int = 0, train_seq_len: int = 1024): + super().__init__() + # rope_dims=0 means full head_dim; otherwise rotate only first rope_dims dims + rope_d = rope_dims if rope_dims > 0 else dim + self.rope_d = rope_d + self.base = base + self.train_seq_len = train_seq_len + inv_freq = 1.0 / (base ** (torch.arange(0, rope_d, 2, dtype=torch.float32) / rope_d)) + 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 + ): + rd = self.rope_d + if seq_len > self.train_seq_len: + scale = seq_len / self.train_seq_len + new_base = self.base * (scale ** (rd / (rd - 2))) + inv_freq = 1.0 / (new_base ** (torch.arange(0, rd, 2, dtype=torch.float32, device=device) / rd)) + 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: + """Apply RoPE; if cos covers fewer dims than x, rotate only those dims.""" + rd = cos.size(-1) * 2 + if rd < x.size(-1): + x_rope = x[..., :rd] + x_pass = x[..., rd:] + half = rd // 2 + x1 = x_rope[..., :half] + x2 = x_rope[..., half:] + x_rot = torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + return torch.cat((x_rot, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + + +class CausalSelfAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, rope_base: float, qk_gain_init: float, rope_dims: int = 0, rope_train_seq_len: int = 1024): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base, rope_dims=rope_dims, train_seq_len=rope_train_seq_len) + self.use_xsa = False + + 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, v_embed: Tensor | None = None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = self.c_v(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + # Add value embeddings to v before attention if provided + if v_embed is not None: + ve_reshaped = v_embed.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = v + ve_reshaped + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, is_causal=True, enable_gqa=(self.num_kv_heads != self.num_heads)) + if self.use_xsa: + y_xsa = y.transpose(1, 2) + v_xsa = v.transpose(1, 2) + y_xsa = self._xsa_efficient(y_xsa, v_xsa) + y = y_xsa.reshape(bsz, seqlen, dim) + else: + y = y.transpose(1, 2).contiguous().reshape(bsz, seqlen, dim) + return self.proj(y) + + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: int, mlp_hidden: int = 0): + super().__init__() + # Star-ReLU implementation. mlp_mult is unused. + hidden = mlp_hidden if mlp_hidden > 0 else int(dim * 3) + self.up_proj = CastedLinear(dim, hidden, bias=False) + self.down_proj = CastedLinear(hidden, dim, bias=False) + self.down_proj._zero_init = True + self.scale = nn.Parameter(torch.ones(hidden, dtype=torch.float32)) + self.bias = nn.Parameter(torch.zeros(hidden, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + x_up = self.up_proj(x) + activated = F.relu(x_up).pow(2) + activated = activated * self.scale.to(dtype=activated.dtype) + self.bias.to(dtype=activated.dtype) + return self.down_proj(activated) + + +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, + rope_dims: int = 0, + layer_idx: int = 0, + ln_scale: bool = False, + rope_train_seq_len: int = 1024, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, rope_dims=rope_dims, rope_train_seq_len=rope_train_seq_len) + self.mlp = MLP(dim, mlp_mult, mlp_hidden=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()) + # LN Scale: dampen norm inputs by 1/sqrt(layer_idx+1) for deeper layers + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + + def forward(self, x: Tensor, x0: Tensor, v_embed: Tensor | None = None) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + s = self.ln_scale_factor + attn_out = self.attn(self.attn_norm(x) * s, v_embed=v_embed) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * s) + return x + + +# ----------------------------- +# BIGRAM HASH EMBEDDING +# ----------------------------- + +class BigramHashEmbedding(nn.Module): + """Hash-based bigram embedding with optional XOR hash and learned scale.""" + def __init__(self, num_buckets: int, embed_dim: int, model_dim: int, use_xor_hash: bool = True): + super().__init__() + self.num_buckets = num_buckets + self.use_xor_hash = use_xor_hash + self.embed = nn.Embedding(num_buckets, embed_dim) + self.proj = CastedLinear(embed_dim, model_dim, bias=False) + if use_xor_hash: + nn.init.zeros_(self.embed.weight) # Zero init with learned scale + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.05, dtype=torch.float32)) + else: + nn.init.normal_(self.embed.weight, std=0.01) + nn.init.zeros_(self.proj.weight) + self.scale = None + + def bigram_hash(self, tokens: Tensor) -> Tensor: + """XOR-based bigram hash with large primes for uniform distribution.""" + t = tokens.to(torch.int32) + mod = self.num_buckets - 1 + out = torch.empty_like(t) + out[..., 0] = mod # Special bucket for first position + out[..., 1:] = torch.bitwise_xor(36313 * t[..., 1:], 27191 * t[..., :-1]) % mod + return out.long() + + def forward(self, input_ids: Tensor) -> Tensor: + if self.use_xor_hash: + h = self.embed(self.bigram_hash(input_ids)) + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + else: + bsz, seq_len = input_ids.shape + prev_ids = F.pad(input_ids[:, :-1], (1, 0), value=0) + bigram_hash = (prev_ids * 1009 + input_ids) % self.num_buckets + bigram_emb = self.embed(bigram_hash) + return self.proj(bigram_emb) + + +# ----------------------------- +# SMEAR GATE +# ----------------------------- + +class SmearGate(nn.Module): + """Learned blending of current position with previous position.""" + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + # x: (bsz, seq_len, dim) + gate = torch.sigmoid(self.gate.to(dtype=x.dtype)) + # Shift x to get previous position, pad with zeros + x_prev = F.pad(x[:, :-1], (0, 0, 1, 0)) + return (1 - gate) * x + gate * x_prev + + +class ValueEmbedding(nn.Module): + """Reinject token identity into attention values at specific layers.""" + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int): + super().__init__() + self.embed = nn.Embedding(vocab_size, ve_dim) + nn.init.normal_(self.embed.weight, std=0.01) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) if ve_dim != kv_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.1, dtype=torch.float32)) + + def forward(self, token_ids: Tensor) -> Tensor: + h = self.embed(token_ids) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class 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, + tie_embeddings: bool, + tied_embed_init_std: float, + logit_softcap: float, + rope_base: float, + qk_gain_init: float, + mlp_hidden: int = 0, + bigram_buckets: int = 4096, + bigram_embed_dim: int = 128, + bigram_xor_hash: bool = True, + rope_dims: int = 0, + ln_scale: bool = False, + xsa_last_n: int = 0, + ve_enabled: bool = False, + ve_dim: int = 128, + ve_layers: str = "9,10", + rope_train_seq_len: int = 1024, + ortho_init: bool = True, + ): + 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.ortho_init = ortho_init + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.bigram_emb = BigramHashEmbedding(bigram_buckets, bigram_embed_dim, model_dim, use_xor_hash=bigram_xor_hash) if bigram_buckets > 0 else None + self.smear_gate = 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.skip_gates = nn.Parameter(torch.zeros(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, rope_dims=rope_dims, layer_idx=i, ln_scale=ln_scale, + rope_train_seq_len=rope_train_seq_len, + ) + for i in range(num_layers) + ]) + if xsa_last_n > 0: + for i in range(max(0, num_layers - xsa_last_n), num_layers): + self.blocks[i].attn.use_xsa = True + # Value Embeddings: reinject token identity into values at deep layers + kv_dim = model_dim // num_heads * num_kv_heads + self.ve_layer_indices = [int(x) for x in ve_layers.split(",") if x.strip()] if ve_enabled else [] + if self.ve_layer_indices: + self.ve_shared = ValueEmbedding(vocab_size, ve_dim, kv_dim) + self.ve_layer_scales = nn.ParameterList( + [nn.Parameter(torch.ones(1, dtype=torch.float32)) for _ in self.ve_layer_indices] + ) + else: + self.ve_shared = None + self.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 self.ortho_init and module.weight.ndim == 2 and module.weight.shape[0] >= 64 and module.weight.shape[1] >= 64: + nn.init.orthogonal_(module.weight, gain=1.0) + if ".proj." in name or name.endswith(".proj"): + with torch.no_grad(): + module.weight.mul_(1.0 / math.sqrt(2 * num_layers)) + + def _get_ve(self, layer_idx: int, input_ids: Tensor, ve_cache: dict) -> Tensor | None: + if self.ve_shared is None or layer_idx not in self.ve_layer_indices: + return None + if 've' not in ve_cache: + ve_cache['ve'] = self.ve_shared(input_ids) + ve_base = ve_cache['ve'] + ve_idx = self.ve_layer_indices.index(layer_idx) + return ve_base * self.ve_layer_scales[ve_idx].to(dtype=ve_base.dtype) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram_emb is not None: + x = x + self.bigram_emb(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear_gate(x) + x0 = x + skips: list[Tensor] = [] + ve_cache: dict = {} + + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, input_ids, ve_cache)) + skips.append(x) + for i in range(self.num_decoder_layers): + bi = self.num_encoder_layers + i + if skips: + skip = skips.pop() + gate = torch.sigmoid(self.skip_gates[i].to(dtype=x.dtype)) + scaled_skip = self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skip + x = gate[None, None, :] * x + (1.0 - gate[None, None, :]) * scaled_skip + x = self.blocks[bi](x, x0, v_embed=self._get_ve(bi, input_ids, ve_cache)) + + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + """Return logits (bsz, seq_len, vocab) without computing loss.""" + x = self.tok_emb(input_ids) + if self.bigram_emb is not None: + x = x + self.bigram_emb(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear_gate(x) + x0 = x + skips: list[Tensor] = [] + ve_cache: dict = {} + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, input_ids, ve_cache)) + skips.append(x) + for i in range(self.num_decoder_layers): + bi = self.num_encoder_layers + i + if skips: + skip = skips.pop() + gate = torch.sigmoid(self.skip_gates[i].to(dtype=x.dtype)) + scaled_skip = self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skip + x = gate[None, None, :] * x + (1.0 - gate[None, None, :]) * scaled_skip + x = self.blocks[bi](x, x0, v_embed=self._get_ve(bi, input_ids, ve_cache)) + 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) + + + +# ----------------------------- +# 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 + + 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"))) + 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 SETUP + # ----------------------------- + + CastedLinear._qat_enabled = False # start with QAT off; late_qat enables it mid-run + + 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, + mlp_hidden=args.mlp_hidden, + bigram_buckets=args.bigram_buckets, + bigram_embed_dim=args.bigram_embed_dim, + bigram_xor_hash=args.bigram_xor_hash, + rope_dims=args.rope_dims, + ln_scale=args.ln_scale, + xsa_last_n=args.xsa_layers, + ve_enabled=args.ve_enabled, + ve_dim=args.ve_dim, + ve_layers=args.ve_layers, + rope_train_seq_len=args.rope_train_seq_len, + ortho_init=args.ortho_init, + ).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 + + # Differential LR setup + matrix_params_enc, scalar_params_enc = [], [] + matrix_params_dec, scalar_params_dec = [], [] + num_encoder_layers = base_model.num_encoder_layers + for i, block in enumerate(base_model.blocks): + is_decoder = i >= num_encoder_layers + for name, p in block.named_parameters(): + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS): + (matrix_params_dec if is_decoder else matrix_params_enc).append(p) + else: + (scalar_params_dec if is_decoder else scalar_params_enc).append(p) + + # Non-block scalar parameters + other_scalar_params = [base_model.smear_gate.gate] + if base_model.bigram_emb is not None: + other_scalar_params.append(base_model.bigram_emb.embed.weight) + if base_model.skip_weights.numel() > 0: + other_scalar_params.append(base_model.skip_weights) + if hasattr(base_model, 'skip_gates') and base_model.skip_gates.numel() > 0: + other_scalar_params.append(base_model.skip_gates) + # Value Embedding parameters + if base_model.ve_shared is not None: + other_scalar_params.extend(list(base_model.ve_shared.parameters())) + other_scalar_params.extend(list(base_model.ve_layer_scales.parameters())) + + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + optimizer_tok = torch.optim.AdamW( + [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.adam_wd, + fused=True, + ) + + matrix_lr_dec = args.matrix_lr * args.decoder_lr_mult + optimizer_muon = Muon( + [ + {'params': matrix_params_enc, 'lr': args.matrix_lr, 'base_lr': args.matrix_lr}, + {'params': matrix_params_dec, 'lr': matrix_lr_dec, 'base_lr': matrix_lr_dec}, + ], + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.muon_wd, + ) + + scalar_lr_dec = args.scalar_lr * args.decoder_lr_mult + optimizer_scalar = torch.optim.AdamW( + [ + {'params': scalar_params_enc, 'lr': args.scalar_lr, 'base_lr': args.scalar_lr}, + {'params': scalar_params_dec, 'lr': scalar_lr_dec, 'base_lr': scalar_lr_dec}, + {'params': other_scalar_params, 'lr': args.scalar_lr, 'base_lr': args.scalar_lr}, + ], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.adam_wd, + fused=True, + ) + + optimizer_bigram_proj = Muon( + [base_model.bigram_emb.proj.weight], + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.muon_wd, + ) + for group in optimizer_bigram_proj.param_groups: + group["base_lr"] = args.matrix_lr + + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar, optimizer_bigram_proj] + if base_model.lm_head is not None: + optimizer_head = torch.optim.AdamW( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.adam_wd, + 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} head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr} decoder_lr_mult:{args.decoder_lr_mult}") + log0(f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} iterations:{args.iterations} warmup_steps:{args.warmup_steps} max_wallclock_seconds:{args.max_wallclock_seconds:.3f}") + log0(f"rope_dims:{args.rope_dims} rope_train_seq_len:{args.rope_train_seq_len} ln_scale:{args.ln_scale}") + log0(f"muon_wd:{args.muon_wd} adam_wd:{args.adam_wd} ema_enabled:{args.ema_enabled} late_qat:{args.late_qat}") + log0(f"bigram_buckets:{args.bigram_buckets} bigram_embed_dim:{args.bigram_embed_dim} seed:{args.seed}") + if args.ttt_enabled: + log0(f"ttt:enabled optimizer:{args.ttt_optimizer} lr:{args.ttt_lr} epochs:{args.ttt_epochs} " + f"freeze_blocks:{args.ttt_freeze_blocks} chunk_tokens:{args.ttt_chunk_tokens}") + + # ----------------------------- + # 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 + + 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) + + # ----------------------------- + # EMA / SWA STATE + # ----------------------------- + + # EMA takes priority; SWA is fallback (mutually exclusive) + 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()} + log0(f"ema:init decay={args.ema_decay}") + + swa_state: dict[str, Tensor] = {} + swa_count = 0 + + def update_swa(): + nonlocal swa_count + with torch.no_grad(): + for name, param in base_model.state_dict().items(): + if name not in swa_state: + swa_state[name] = param.detach().cpu().clone().float() + else: + swa_state[name].add_(param.detach().cpu().float()) + swa_count += 1 + + def get_swa_state() -> dict[str, Tensor]: + return {name: (t / swa_count).to(dtype=base_model.state_dict()[name].dtype) for name, t in swa_state.items()} + + # ----------------------------- + # MAIN TRAINING LOOP + # ----------------------------- + + training_time_ms = 0.0 + stop_after_step: int | None = None + torch.cuda.synchronize() + t0 = time.perf_counter() + + # Estimate total steps for SWA start + estimated_total_steps = args.iterations + if max_wallclock_ms is not None: + estimated_total_steps = min(args.iterations, int(max_wallclock_ms / 30)) # rough estimate + + 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} 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) + + # Late QAT: enable fake int6 quantization once LR scale drops below threshold + # NOTE: torch.compile constant-folds _qat_enabled at first trace, so we must + # reset dynamo caches to force recompilation with QAT branch active. + if args.late_qat and not CastedLinear._qat_enabled and scale < args.qat_threshold: + CastedLinear._qat_enabled = True + torch._dynamo.reset() # force recompile with QAT enabled + log0(f"late_qat:enabled step:{step} scale:{scale:.4f} (dynamo reset for recompile)") + + 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 group in optimizer_bigram_proj.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + step += 1 + + # EMA update every step (takes priority over SWA) + if ema_state is not None: + d = args.ema_decay + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(d).add_(t.detach().float(), alpha=1.0 - d) + + # SWA update (only when EMA disabled) + swa_start_step = int(estimated_total_steps * args.swa_start_frac) + if ema_state is None and step >= swa_start_step and step % args.swa_every == 0: + update_swa() + + 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} 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 + + # Final SWA update (only if EMA disabled and no SWA yet) + if ema_state is None and swa_count == 0: + update_swa() + + log0(f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB") + + # Apply EMA or SWA weights (EMA takes priority) + if ema_state is not None: + log0("ema:applying EMA weights") + avg_state = {name: t.to(dtype=base_model.state_dict()[name].dtype) for name, t in ema_state.items()} + del ema_state + base_model.load_state_dict(avg_state, strict=True) + del avg_state + elif swa_count > 0: + log0(f"swa:applying averaged {swa_count} checkpoints") + base_model.load_state_dict(get_swa_state(), strict=True) + else: + log0("weight_avg:skipped (no EMA or SWA state)") + + # ----------------------------- + # TTT: fine-tune on val data AFTER EMA/SWA, BEFORE quantization + # ----------------------------- + + # ----------------------------- + # SERIALIZATION + ROUNDTRIP VALIDATION + # ----------------------------- + + 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_int6(base_model.state_dict()) + quant_buf = io.BytesIO() + torch.save(quant_obj, quant_buf) + quant_raw = quant_buf.getvalue() + + # Use zstd-22 for compression (or zlib fallback) + if USE_ZSTD: + cctx = zstd.ZstdCompressor(level=22) + quant_blob = cctx.compress(quant_raw) + compression_method = "zstd-22" + else: + import zlib + quant_blob = zlib.compress(quant_raw, level=9) + compression_method = "zlib-9" + + quant_raw_bytes = len(quant_raw) + if master_process: + with open("final_model.int6.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int6.ptz") + code_bytes = len(code.encode("utf-8")) + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int6_payload_bytes"], 1) + q_label = "mixed" if MIXED_QUANT else ("int8" if INT8_STORAGE else "int6") + log0(f"Serialized model {q_label}+{compression_method}: {quant_file_bytes} bytes (payload:{quant_stats['int6_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)") + log0(f"Total submission size {q_label}+{compression_method}: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int6.ptz", "rb") as f: + quant_blob_disk = f.read() + + # Decompress + if USE_ZSTD: + dctx = zstd.ZstdDecompressor() + quant_raw_disk = dctx.decompress(quant_blob_disk) + else: + import zlib + quant_raw_disk = zlib.decompress(quant_blob_disk) + + quant_state = torch.load(io.BytesIO(quant_raw_disk), map_location="cpu") + base_model.load_state_dict(dequantize_state_dict_int6(quant_state), strict=True) + torch.cuda.synchronize() + + # Quick pre-TTT eval to measure quantization gap + t_pre = time.perf_counter() + pre_val_loss, pre_val_bpb = eval_val( + args, base_model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + log0(f"pre_ttt_quant_eval val_loss:{pre_val_loss:.6f} val_bpb:{pre_val_bpb:.6f} elapsed:{time.perf_counter()-t_pre:.1f}s") + + t_qeval = time.perf_counter() + if args.ttt_enabled and args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window_ttt stride:{args.eval_stride} " + f"chunk_tokens:{args.ttt_chunk_tokens} optimizer:{args.ttt_optimizer}") + q_val_loss, q_val_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, log0=log0) + elif args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window stride:{args.eval_stride}") + q_val_loss, q_val_bpb = eval_val_sliding( + args, base_model, rank, world_size, device, val_tokens, + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, + ) + else: + log0("final_eval_mode:standard") + q_val_loss, q_val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + torch.cuda.synchronize() + log0(f"final_int6_{compression_method}_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} eval:{1000.0*(time.perf_counter()-t_qeval):.0f}ms") + log0(f"final_int6_{compression_method}_roundtrip_exact val_bpb:{q_val_bpb:.8f}") + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main() +==================================================================================================== +Running Python 3.12.7 | packaged by conda-forge | (main, Oct 4 2024, 16:05:46) [GCC 13.3.0] +Running PyTorch 2.10.0+cu128 +Tue Mar 24 15:57:53 2026 ++-----------------------------------------------------------------------------------------+ +| NVIDIA-SMI 570.172.08 Driver Version: 570.172.08 CUDA Version: 12.8 | +|-----------------------------------------+------------------------+----------------------+ +| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC | +| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. | +| | | MIG M. | +|=========================================+========================+======================| +| 0 NVIDIA A100-PCIE-40GB On | 00000000:17:00.0 Off | 0 | +| N/A 42C P0 49W / 250W | 667MiB / 40960MiB | 12% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 1 NVIDIA A100-PCIE-40GB On | 00000000:65:00.0 Off | 0 | +| N/A 43C P0 52W / 250W | 667MiB / 40960MiB | 8% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 2 NVIDIA A100-PCIE-40GB On | 00000000:CA:00.0 Off | 0 | +| N/A 42C P0 50W / 250W | 667MiB / 40960MiB | 3% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 3 NVIDIA A100-PCIE-40GB On | 00000000:E3:00.0 Off | 0 | +| N/A 43C P0 52W / 250W | 667MiB / 40960MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ + ++-----------------------------------------------------------------------------------------+ +| Processes: | +| GPU GI CI PID Type Process name GPU Memory | +| ID ID Usage | +|=========================================================================================| +| 0 N/A N/A 381226 C ...ameter_golf/.venv/bin/python3 658MiB | +| 1 N/A N/A 381227 C ...ameter_golf/.venv/bin/python3 658MiB | +| 2 N/A N/A 381228 C ...ameter_golf/.venv/bin/python3 658MiB | +| 3 N/A N/A 381230 C ...ameter_golf/.venv/bin/python3 658MiB | ++-----------------------------------------------------------------------------------------+ + +==================================================================================================== +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=/hpfs/scratch/gpfs/mcclec07/code/parameter_golf/repo/data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=/hpfs/scratch/gpfs/mcclec07/code/parameter_golf/repo/data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +model_params:27030107 +world_size:4 grad_accum_steps:2 +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 decoder_lr_mult:2.0 +train_batch_tokens:786432 train_seq_len:2048 iterations:30000 warmup_steps:20 max_wallclock_seconds:0.000 +rope_dims:16 rope_train_seq_len:2048 ln_scale:True +muon_wd:0.04 adam_wd:0.04 ema_enabled:True late_qat:False +bigram_buckets:2048 bigram_embed_dim:128 seed:42 +ttt:enabled optimizer:sgd lr:0.002 epochs:10 freeze_blocks:2 chunk_tokens:32768 +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 +ema:init decay=0.997 +step:0/30000 val_loss:6.9300 val_bpb:4.1043 train_time:0ms step_avg:0.01ms +step:1/30000 train_loss:6.9314 train_time:546ms step_avg:545.60ms +step:2/30000 train_loss:8.5481 train_time:1026ms step_avg:512.82ms +step:3/30000 train_loss:7.3850 train_time:1534ms step_avg:511.45ms +step:4/30000 train_loss:7.5582 train_time:2033ms step_avg:508.27ms +step:5/30000 train_loss:7.5099 train_time:2529ms step_avg:505.86ms +step:6/30000 train_loss:7.2042 train_time:3032ms step_avg:505.26ms +step:7/30000 train_loss:6.9774 train_time:3531ms step_avg:504.39ms +step:8/30000 train_loss:6.7045 train_time:4034ms step_avg:504.29ms +step:9/30000 train_loss:6.4178 train_time:4538ms step_avg:504.23ms +step:10/30000 train_loss:6.0545 train_time:5040ms step_avg:504.00ms +step:200/30000 train_loss:2.4991 train_time:100586ms step_avg:502.93ms +step:400/30000 train_loss:2.4016 train_time:201238ms step_avg:503.09ms +step:500/30000 val_loss:2.3544 val_bpb:1.3944 train_time:251247ms step_avg:502.49ms +step:600/30000 train_loss:2.3529 train_time:301166ms step_avg:501.94ms +step:800/30000 train_loss:2.2454 train_time:401146ms step_avg:501.43ms +step:1000/30000 train_loss:2.2826 train_time:501164ms step_avg:501.16ms +step:1000/30000 val_loss:2.2328 val_bpb:1.3224 train_time:501172ms step_avg:501.17ms +step:1200/30000 train_loss:2.2797 train_time:601372ms step_avg:501.14ms +step:1400/30000 train_loss:2.2434 train_time:701432ms step_avg:501.02ms +step:1500/30000 val_loss:2.1898 val_bpb:1.2969 train_time:751450ms step_avg:500.97ms +step:1600/30000 train_loss:2.1355 train_time:801509ms step_avg:500.94ms +step:1800/30000 train_loss:2.1406 train_time:901887ms step_avg:501.05ms +step:2000/30000 train_loss:2.0338 train_time:1002034ms step_avg:501.02ms +step:2000/30000 val_loss:2.1366 val_bpb:1.2654 train_time:1002043ms step_avg:501.02ms +step:2200/30000 train_loss:2.1482 train_time:1102201ms step_avg:501.00ms +step:2400/30000 train_loss:2.0886 train_time:1202166ms step_avg:500.90ms +step:2500/30000 val_loss:2.1161 val_bpb:1.2533 train_time:1252164ms step_avg:500.87ms +step:2600/30000 train_loss:2.1544 train_time:1302340ms step_avg:500.90ms +step:2800/30000 train_loss:2.1919 train_time:1402561ms step_avg:500.91ms +step:3000/30000 train_loss:2.1185 train_time:1502572ms step_avg:500.86ms +step:3000/30000 val_loss:2.1042 val_bpb:1.2463 train_time:1502581ms step_avg:500.86ms +step:3200/30000 train_loss:2.1521 train_time:1602688ms step_avg:500.84ms +step:3400/30000 train_loss:2.1084 train_time:1702959ms step_avg:500.87ms +step:3500/30000 val_loss:2.0994 val_bpb:1.2434 train_time:1753105ms step_avg:500.89ms +step:3600/30000 train_loss:2.1061 train_time:1803280ms step_avg:500.91ms +step:3800/30000 train_loss:2.0990 train_time:1903312ms step_avg:500.87ms +step:4000/30000 train_loss:2.1643 train_time:2003214ms step_avg:500.80ms +step:4000/30000 val_loss:2.0957 val_bpb:1.2412 train_time:2003223ms step_avg:500.81ms +step:4200/30000 train_loss:2.1060 train_time:2103360ms step_avg:500.80ms +step:4400/30000 train_loss:2.0328 train_time:2203369ms step_avg:500.77ms +step:4500/30000 val_loss:2.0837 val_bpb:1.2341 train_time:2253541ms step_avg:500.79ms +step:4600/30000 train_loss:1.9880 train_time:2303446ms step_avg:500.75ms +step:4800/30000 train_loss:2.2877 train_time:2403445ms step_avg:500.72ms +step:5000/30000 train_loss:2.0968 train_time:2503743ms step_avg:500.75ms +step:5000/30000 val_loss:2.0793 val_bpb:1.2315 train_time:2503752ms step_avg:500.75ms +step:5200/30000 train_loss:2.1061 train_time:2603884ms step_avg:500.75ms +step:5400/30000 train_loss:2.0465 train_time:2703992ms step_avg:500.74ms +step:5500/30000 val_loss:2.0744 val_bpb:1.2286 train_time:2754030ms step_avg:500.73ms +step:5600/30000 train_loss:2.0674 train_time:2803995ms step_avg:500.71ms +step:5800/30000 train_loss:2.0491 train_time:2903970ms step_avg:500.68ms +step:6000/30000 train_loss:2.0347 train_time:3004253ms step_avg:500.71ms +step:6000/30000 val_loss:2.0755 val_bpb:1.2292 train_time:3004261ms step_avg:500.71ms +step:6200/30000 train_loss:2.1313 train_time:3104267ms step_avg:500.69ms +step:6400/30000 train_loss:2.0912 train_time:3204261ms step_avg:500.67ms +step:6500/30000 val_loss:2.0675 val_bpb:1.2245 train_time:3254204ms step_avg:500.65ms +step:6600/30000 train_loss:2.0028 train_time:3304142ms step_avg:500.63ms +step:6800/30000 train_loss:2.1588 train_time:3404444ms step_avg:500.65ms +step:7000/30000 train_loss:1.9374 train_time:3504696ms step_avg:500.67ms +step:7000/30000 val_loss:2.0686 val_bpb:1.2251 train_time:3504704ms step_avg:500.67ms +step:7200/30000 train_loss:2.0828 train_time:3604530ms step_avg:500.63ms +step:7400/30000 train_loss:2.0681 train_time:3704693ms step_avg:500.63ms +step:7500/30000 val_loss:2.0670 val_bpb:1.2242 train_time:3754695ms step_avg:500.63ms +step:7600/30000 train_loss:2.0143 train_time:3804846ms step_avg:500.64ms +step:7800/30000 train_loss:2.0304 train_time:3905040ms step_avg:500.65ms +step:8000/30000 train_loss:2.0140 train_time:4004829ms step_avg:500.60ms +step:8000/30000 val_loss:2.0622 val_bpb:1.2213 train_time:4004837ms step_avg:500.60ms +step:8200/30000 train_loss:2.0625 train_time:4104779ms step_avg:500.58ms +step:8400/30000 train_loss:2.0754 train_time:4204972ms step_avg:500.59ms +step:8500/30000 val_loss:2.0630 val_bpb:1.2218 train_time:4254913ms step_avg:500.58ms +step:8600/30000 train_loss:2.1466 train_time:4305002ms step_avg:500.58ms +step:8800/30000 train_loss:2.0648 train_time:4404960ms step_avg:500.56ms +step:9000/30000 train_loss:2.1183 train_time:4505014ms step_avg:500.56ms +step:9000/30000 val_loss:2.0600 val_bpb:1.2200 train_time:4505023ms step_avg:500.56ms +step:9200/30000 train_loss:2.0344 train_time:4605134ms step_avg:500.56ms +step:9400/30000 train_loss:2.1019 train_time:4705289ms step_avg:500.56ms +step:9500/30000 val_loss:2.0585 val_bpb:1.2192 train_time:4755350ms step_avg:500.56ms +step:9600/30000 train_loss:2.0706 train_time:4805279ms step_avg:500.55ms +step:9800/30000 train_loss:2.1013 train_time:4905163ms step_avg:500.53ms +step:10000/30000 train_loss:2.0922 train_time:5005214ms step_avg:500.52ms +step:10000/30000 val_loss:2.0560 val_bpb:1.2177 train_time:5005223ms step_avg:500.52ms +step:10200/30000 train_loss:2.0143 train_time:5105485ms step_avg:500.54ms +step:10400/30000 train_loss:2.0549 train_time:5205469ms step_avg:500.53ms +step:10500/30000 val_loss:2.0571 val_bpb:1.2183 train_time:5255466ms step_avg:500.52ms +step:10600/30000 train_loss:2.0377 train_time:5305364ms step_avg:500.51ms +step:10800/30000 train_loss:2.0364 train_time:5405491ms step_avg:500.51ms +step:11000/30000 train_loss:2.0159 train_time:5505707ms step_avg:500.52ms +step:11000/30000 val_loss:2.0543 val_bpb:1.2167 train_time:5505716ms step_avg:500.52ms +step:11200/30000 train_loss:2.0763 train_time:5605621ms step_avg:500.50ms +step:11400/30000 train_loss:2.0671 train_time:5705543ms step_avg:500.49ms +step:11500/30000 val_loss:2.0529 val_bpb:1.2158 train_time:5755598ms step_avg:500.49ms +step:11600/30000 train_loss:2.0398 train_time:5805690ms step_avg:500.49ms +step:11800/30000 train_loss:2.0627 train_time:5905811ms step_avg:500.49ms +step:12000/30000 train_loss:1.9935 train_time:6005889ms step_avg:500.49ms +step:12000/30000 val_loss:2.0562 val_bpb:1.2178 train_time:6005898ms step_avg:500.49ms +step:12200/30000 train_loss:2.1148 train_time:6105865ms step_avg:500.48ms +step:12400/30000 train_loss:2.2111 train_time:6205913ms step_avg:500.48ms +step:12500/30000 val_loss:2.0494 val_bpb:1.2138 train_time:6256014ms step_avg:500.48ms +step:12600/30000 train_loss:2.1433 train_time:6306127ms step_avg:500.49ms +step:12800/30000 train_loss:2.6056 train_time:6405968ms step_avg:500.47ms +step:13000/30000 train_loss:2.0102 train_time:6505795ms step_avg:500.45ms +step:13000/30000 val_loss:2.0422 val_bpb:1.2095 train_time:6505804ms step_avg:500.45ms +step:13200/30000 train_loss:1.9565 train_time:6605524ms step_avg:500.42ms +step:13400/30000 train_loss:1.9784 train_time:6705721ms step_avg:500.43ms +step:13500/30000 val_loss:2.0417 val_bpb:1.2092 train_time:6755812ms step_avg:500.43ms +step:13600/30000 train_loss:2.0012 train_time:6805749ms step_avg:500.42ms +step:13800/30000 train_loss:2.0028 train_time:6905670ms step_avg:500.41ms +step:14000/30000 train_loss:1.9311 train_time:7005748ms step_avg:500.41ms +step:14000/30000 val_loss:2.0378 val_bpb:1.2069 train_time:7005757ms step_avg:500.41ms +step:14200/30000 train_loss:2.1196 train_time:7105708ms step_avg:500.40ms +step:14400/30000 train_loss:2.0805 train_time:7205813ms step_avg:500.40ms +step:14500/30000 val_loss:2.0390 val_bpb:1.2076 train_time:7255726ms step_avg:500.39ms +step:14600/30000 train_loss:2.0142 train_time:7305707ms step_avg:500.39ms +step:14800/30000 train_loss:2.0834 train_time:7405717ms step_avg:500.39ms +step:15000/30000 train_loss:2.0554 train_time:7505740ms step_avg:500.38ms +step:15000/30000 val_loss:2.0298 val_bpb:1.2021 train_time:7505748ms step_avg:500.38ms +step:15200/30000 train_loss:1.9792 train_time:7605871ms step_avg:500.39ms +step:15400/30000 train_loss:2.1544 train_time:7705640ms step_avg:500.37ms +step:15500/30000 val_loss:2.0291 val_bpb:1.2017 train_time:7755479ms step_avg:500.35ms +step:15600/30000 train_loss:2.0694 train_time:7805388ms step_avg:500.35ms +step:15800/30000 train_loss:2.0544 train_time:7905682ms step_avg:500.36ms +step:16000/30000 train_loss:2.1075 train_time:8005762ms step_avg:500.36ms +step:16000/30000 val_loss:2.0256 val_bpb:1.1997 train_time:8005770ms step_avg:500.36ms +step:16200/30000 train_loss:1.9772 train_time:8105677ms step_avg:500.35ms +step:16400/30000 train_loss:1.9736 train_time:8205540ms step_avg:500.34ms +step:16500/30000 val_loss:2.0261 val_bpb:1.2000 train_time:8255585ms step_avg:500.34ms +step:16600/30000 train_loss:2.0822 train_time:8305669ms step_avg:500.34ms +step:16800/30000 train_loss:2.0487 train_time:8405837ms step_avg:500.35ms +step:17000/30000 train_loss:2.0848 train_time:8505621ms step_avg:500.33ms +step:17000/30000 val_loss:2.0189 val_bpb:1.1957 train_time:8505629ms step_avg:500.33ms +step:17200/30000 train_loss:2.0493 train_time:8605383ms step_avg:500.31ms +step:17400/30000 train_loss:1.9419 train_time:8705424ms step_avg:500.31ms +step:17500/30000 val_loss:2.0144 val_bpb:1.1931 train_time:8755544ms step_avg:500.32ms +step:17600/30000 train_loss:2.0639 train_time:8805645ms step_avg:500.32ms +step:17800/30000 train_loss:2.0593 train_time:8905422ms step_avg:500.30ms +step:18000/30000 train_loss:1.9512 train_time:9005173ms step_avg:500.29ms +step:18000/30000 val_loss:2.0108 val_bpb:1.1909 train_time:9005182ms step_avg:500.29ms +step:18200/30000 train_loss:1.9921 train_time:9105373ms step_avg:500.30ms +step:18400/30000 train_loss:1.8727 train_time:9205259ms step_avg:500.29ms +step:18500/30000 val_loss:2.0110 val_bpb:1.1910 train_time:9255177ms step_avg:500.28ms +step:18600/30000 train_loss:1.9433 train_time:9305094ms step_avg:500.27ms +step:18800/30000 train_loss:2.0571 train_time:9405042ms step_avg:500.27ms +step:19000/30000 train_loss:1.8993 train_time:9505118ms step_avg:500.27ms +step:19000/30000 val_loss:2.0070 val_bpb:1.1887 train_time:9505126ms step_avg:500.27ms +step:19200/30000 train_loss:2.0513 train_time:9604958ms step_avg:500.26ms +step:19400/30000 train_loss:1.9864 train_time:9704875ms step_avg:500.25ms +step:19500/30000 val_loss:2.0046 val_bpb:1.1872 train_time:9754861ms step_avg:500.25ms +step:19600/30000 train_loss:2.0123 train_time:9804830ms step_avg:500.25ms +step:19800/30000 train_loss:2.0956 train_time:9904885ms step_avg:500.25ms +step:20000/30000 train_loss:2.0031 train_time:10005089ms step_avg:500.25ms +step:20000/30000 val_loss:1.9970 val_bpb:1.1828 train_time:10005097ms step_avg:500.25ms +step:20200/30000 train_loss:2.0028 train_time:10104822ms step_avg:500.24ms +step:20400/30000 train_loss:1.9961 train_time:10204416ms step_avg:500.22ms +step:20500/30000 val_loss:1.9921 val_bpb:1.1798 train_time:10254410ms step_avg:500.22ms +step:20600/30000 train_loss:2.0058 train_time:10304412ms step_avg:500.21ms +step:20800/30000 train_loss:2.0867 train_time:10404313ms step_avg:500.21ms +step:21000/30000 train_loss:1.9591 train_time:10504183ms step_avg:500.20ms +step:21000/30000 val_loss:1.9904 val_bpb:1.1788 train_time:10504191ms step_avg:500.20ms +step:21200/30000 train_loss:1.9145 train_time:10604005ms step_avg:500.19ms +step:21400/30000 train_loss:1.8732 train_time:10703916ms step_avg:500.18ms +step:21500/30000 val_loss:1.9850 val_bpb:1.1756 train_time:10754028ms step_avg:500.19ms +step:21600/30000 train_loss:1.9156 train_time:10803813ms step_avg:500.18ms +step:21800/30000 train_loss:1.9684 train_time:10903755ms step_avg:500.17ms +step:22000/30000 train_loss:1.9974 train_time:11003433ms step_avg:500.16ms +step:22000/30000 val_loss:1.9812 val_bpb:1.1734 train_time:11003442ms step_avg:500.16ms +step:22200/30000 train_loss:1.9005 train_time:11103329ms step_avg:500.15ms +step:22400/30000 train_loss:1.9658 train_time:11203460ms step_avg:500.15ms +step:22500/30000 val_loss:1.9771 val_bpb:1.1710 train_time:11253320ms step_avg:500.15ms +step:22600/30000 train_loss:2.0321 train_time:11303298ms step_avg:500.15ms +step:22800/30000 train_loss:1.8939 train_time:11403073ms step_avg:500.13ms +step:23000/30000 train_loss:1.9373 train_time:11502893ms step_avg:500.13ms +step:23000/30000 val_loss:1.9718 val_bpb:1.1678 train_time:11502901ms step_avg:500.13ms +step:23200/30000 train_loss:2.0103 train_time:11602872ms step_avg:500.12ms +step:23400/30000 train_loss:1.9853 train_time:11702818ms step_avg:500.12ms +step:23500/30000 val_loss:1.9679 val_bpb:1.1655 train_time:11752727ms step_avg:500.12ms +step:23600/30000 train_loss:1.9675 train_time:11802656ms step_avg:500.11ms +step:23800/30000 train_loss:1.9904 train_time:11902737ms step_avg:500.12ms +step:24000/30000 train_loss:1.9170 train_time:12002855ms step_avg:500.12ms +step:24000/30000 val_loss:1.9646 val_bpb:1.1635 train_time:12002863ms step_avg:500.12ms +step:24200/30000 train_loss:2.0116 train_time:12102918ms step_avg:500.12ms +step:24400/30000 train_loss:1.9096 train_time:12202600ms step_avg:500.11ms +step:24500/30000 val_loss:1.9570 val_bpb:1.1591 train_time:12252463ms step_avg:500.10ms +step:24600/30000 train_loss:2.0602 train_time:12302337ms step_avg:500.10ms +step:24800/30000 train_loss:1.9444 train_time:12402464ms step_avg:500.10ms +step:25000/30000 train_loss:1.9634 train_time:12502450ms step_avg:500.10ms +step:25000/30000 val_loss:1.9520 val_bpb:1.1561 train_time:12502458ms step_avg:500.10ms +step:25200/30000 train_loss:1.9027 train_time:12602150ms step_avg:500.09ms +step:25400/30000 train_loss:2.0850 train_time:12701929ms step_avg:500.08ms +step:25500/30000 val_loss:1.9443 val_bpb:1.1515 train_time:12751892ms step_avg:500.07ms +step:25600/30000 train_loss:1.9483 train_time:12801985ms step_avg:500.08ms +step:25800/30000 train_loss:1.9880 train_time:12901764ms step_avg:500.07ms +step:26000/30000 train_loss:2.0057 train_time:13001484ms step_avg:500.06ms +step:26000/30000 val_loss:1.9381 val_bpb:1.1479 train_time:13001492ms step_avg:500.06ms +step:26200/30000 train_loss:1.9545 train_time:13101168ms step_avg:500.04ms +step:26400/30000 train_loss:1.9307 train_time:13201127ms step_avg:500.04ms +step:26500/30000 val_loss:1.9317 val_bpb:1.1441 train_time:13251332ms step_avg:500.05ms +step:26600/30000 train_loss:1.8534 train_time:13301371ms step_avg:500.05ms +step:26800/30000 train_loss:1.9410 train_time:13401029ms step_avg:500.04ms +step:27000/30000 train_loss:1.9123 train_time:13500885ms step_avg:500.03ms +step:27000/30000 val_loss:1.9244 val_bpb:1.1397 train_time:13500894ms step_avg:500.03ms +step:27200/30000 train_loss:2.0025 train_time:13600801ms step_avg:500.03ms +step:27400/30000 train_loss:2.0013 train_time:13700943ms step_avg:500.03ms +step:27500/30000 val_loss:1.9159 val_bpb:1.1347 train_time:13750832ms step_avg:500.03ms +step:27600/30000 train_loss:1.9193 train_time:13800722ms step_avg:500.03ms +step:27800/30000 train_loss:1.8969 train_time:13900379ms step_avg:500.01ms +step:28000/30000 train_loss:1.7392 train_time:14000286ms step_avg:500.01ms +step:28000/30000 val_loss:1.9070 val_bpb:1.1295 train_time:14000295ms step_avg:500.01ms +step:28200/30000 train_loss:1.8931 train_time:14100167ms step_avg:500.01ms +step:28400/30000 train_loss:1.8706 train_time:14200007ms step_avg:500.00ms +step:28500/30000 val_loss:1.8955 val_bpb:1.1226 train_time:14249922ms step_avg:500.00ms +step:28600/30000 train_loss:1.9868 train_time:14299717ms step_avg:499.99ms +step:28800/30000 train_loss:1.9378 train_time:14399533ms step_avg:499.98ms +step:29000/30000 train_loss:1.9117 train_time:14499515ms step_avg:499.98ms +step:29000/30000 val_loss:1.8854 val_bpb:1.1167 train_time:14499523ms step_avg:499.98ms +step:29200/30000 train_loss:1.9355 train_time:14599105ms step_avg:499.97ms +step:29400/30000 train_loss:1.9370 train_time:14698635ms step_avg:499.95ms +step:29500/30000 val_loss:1.8736 val_bpb:1.1097 train_time:14748462ms step_avg:499.95ms +step:29600/30000 train_loss:1.8760 train_time:14798307ms step_avg:499.94ms +step:29800/30000 train_loss:1.7713 train_time:14898217ms step_avg:499.94ms +step:30000/30000 train_loss:1.8458 train_time:14997969ms step_avg:499.93ms +step:30000/30000 val_loss:1.8646 val_bpb:1.1043 train_time:14997977ms step_avg:499.93ms +peak memory allocated: 21231 MiB reserved: 21414 MiB +ema:applying EMA weights +Serialized model: 107123189 bytes +Code size: 78689 bytes +Total submission size: 107201878 bytes +Serialized model int6+zstd-22: 14057451 bytes (payload:27530604 raw_torch:27595991 payload_ratio:3.89x) +Total submission size int6+zstd-22: 14136140 bytes +pre_ttt_quant_eval val_loss:1.902436 val_bpb:1.126730 elapsed:27.8s +final_eval_mode:sliding_window_ttt stride:64 chunk_tokens:32768 optimizer:sgd +ttt_sliding:start chunks=1893 chunk_tokens=32768 total_windows=969088 stride=64 ttt_lr=0.002 ttt_epochs=10 ttt_optimizer=sgd freeze_blocks=2 +ttt_sliding:params unfrozen=22301259 frozen=4728848 + ttt_chunk [1/1893] bpb=1.144238 time=1.1s + ttt_chunk [11/1893] bpb=1.106734 time=11.9s + ttt_chunk [21/1893] bpb=1.110751 time=22.8s + ttt_chunk [31/1893] bpb=1.114003 time=33.7s + ttt_chunk [41/1893] bpb=1.102340 time=44.6s + ttt_chunk [51/1893] bpb=1.098278 time=55.5s + ttt_chunk [61/1893] bpb=1.102372 time=66.4s + ttt_chunk [71/1893] bpb=1.099190 time=77.3s + ttt_chunk [81/1893] bpb=1.099001 time=88.3s + ttt_chunk [91/1893] bpb=1.097374 time=99.2s + ttt_chunk [101/1893] bpb=1.100026 time=110.1s + ttt_chunk [111/1893] bpb=1.101028 time=121.0s + ttt_chunk [121/1893] bpb=1.097556 time=132.0s + ttt_chunk [131/1893] bpb=1.097331 time=142.9s + ttt_chunk [141/1893] bpb=1.096855 time=153.8s + ttt_chunk [151/1893] bpb=1.099890 time=164.7s + ttt_chunk [161/1893] bpb=1.101477 time=175.7s + ttt_chunk [171/1893] bpb=1.102018 time=186.6s + ttt_chunk [181/1893] bpb=1.101935 time=197.5s + ttt_chunk [191/1893] bpb=1.105097 time=208.4s + ttt_chunk [201/1893] bpb=1.105417 time=219.3s + ttt_chunk [211/1893] bpb=1.102946 time=230.2s + ttt_chunk [221/1893] bpb=1.104959 time=241.2s + ttt_chunk [231/1893] bpb=1.104326 time=252.1s + ttt_chunk [241/1893] bpb=1.104048 time=263.0s + ttt_chunk [251/1893] bpb=1.102481 time=273.9s + ttt_chunk [261/1893] bpb=1.100760 time=284.8s + ttt_chunk [271/1893] bpb=1.099409 time=295.7s + ttt_chunk [281/1893] bpb=1.101660 time=306.6s + ttt_chunk [291/1893] bpb=1.102369 time=317.6s + ttt_chunk [301/1893] bpb=1.102909 time=328.5s + ttt_chunk [311/1893] bpb=1.104429 time=339.4s + ttt_chunk [321/1893] bpb=1.105875 time=350.3s + ttt_chunk [331/1893] bpb=1.105674 time=361.2s + ttt_chunk [341/1893] bpb=1.105922 time=372.1s + ttt_chunk [351/1893] bpb=1.107170 time=383.0s + ttt_chunk [361/1893] bpb=1.108321 time=393.9s + ttt_chunk [371/1893] bpb=1.107851 time=404.8s + ttt_chunk [381/1893] bpb=1.107781 time=415.8s + ttt_chunk [391/1893] bpb=1.107369 time=426.7s + ttt_chunk [401/1893] bpb=1.105965 time=437.6s + ttt_chunk [411/1893] bpb=1.104863 time=448.5s + ttt_chunk [421/1893] bpb=1.104320 time=459.4s + ttt_chunk [431/1893] bpb=1.104986 time=470.3s + ttt_chunk [441/1893] bpb=1.104798 time=481.2s + ttt_chunk [451/1893] bpb=1.104455 time=492.1s + ttt_chunk [461/1893] bpb=1.103683 time=503.0s + ttt_chunk [471/1893] bpb=1.103263 time=514.0s + ttt_chunk [481/1893] bpb=1.102955 time=524.9s + ttt_chunk [491/1893] bpb=1.102649 time=535.8s + ttt_chunk [501/1893] bpb=1.102090 time=546.7s + ttt_chunk [511/1893] bpb=1.101452 time=557.6s + ttt_chunk [521/1893] bpb=1.100370 time=568.5s + ttt_chunk [531/1893] bpb=1.100435 time=579.4s + ttt_chunk [541/1893] bpb=1.100395 time=590.3s + ttt_chunk [551/1893] bpb=1.099223 time=601.3s + ttt_chunk [561/1893] bpb=1.099746 time=612.2s + ttt_chunk [571/1893] bpb=1.099015 time=623.1s + ttt_chunk [581/1893] bpb=1.098438 time=634.0s + ttt_chunk [591/1893] bpb=1.097752 time=644.9s + ttt_chunk [601/1893] bpb=1.098435 time=655.8s + ttt_chunk [611/1893] bpb=1.097969 time=666.7s + ttt_chunk [621/1893] bpb=1.097872 time=677.7s + ttt_chunk [631/1893] bpb=1.098257 time=688.6s + ttt_chunk [641/1893] bpb=1.098033 time=699.5s + ttt_chunk [651/1893] bpb=1.098012 time=710.4s + ttt_chunk [661/1893] bpb=1.097925 time=721.4s + ttt_chunk [671/1893] bpb=1.097564 time=732.3s + ttt_chunk [681/1893] bpb=1.097841 time=743.2s + ttt_chunk [691/1893] bpb=1.098505 time=754.1s + ttt_chunk [701/1893] bpb=1.097710 time=765.0s + ttt_chunk [711/1893] bpb=1.098286 time=775.9s + ttt_chunk [721/1893] bpb=1.097890 time=786.8s + ttt_chunk [731/1893] bpb=1.098321 time=797.7s + ttt_chunk [741/1893] bpb=1.098280 time=808.6s + ttt_chunk [751/1893] bpb=1.097917 time=819.6s + ttt_chunk [761/1893] bpb=1.097752 time=830.5s + ttt_chunk [771/1893] bpb=1.097531 time=841.4s + ttt_chunk [781/1893] bpb=1.098051 time=852.3s + ttt_chunk [791/1893] bpb=1.097692 time=863.2s + ttt_chunk [801/1893] bpb=1.097774 time=874.1s + ttt_chunk [811/1893] bpb=1.097280 time=885.0s + ttt_chunk [821/1893] bpb=1.097090 time=895.9s + ttt_chunk [831/1893] bpb=1.096646 time=906.8s + ttt_chunk [841/1893] bpb=1.096059 time=917.7s + ttt_chunk [851/1893] bpb=1.095935 time=928.6s + ttt_chunk [861/1893] bpb=1.096071 time=939.6s + ttt_chunk [871/1893] bpb=1.096090 time=950.5s + ttt_chunk [881/1893] bpb=1.096085 time=961.4s + ttt_chunk [891/1893] bpb=1.095899 time=972.3s + ttt_chunk [901/1893] bpb=1.095873 time=983.2s + ttt_chunk [911/1893] bpb=1.095865 time=994.1s + ttt_chunk [921/1893] bpb=1.096213 time=1005.0s + ttt_chunk [931/1893] bpb=1.096049 time=1015.9s + ttt_chunk [941/1893] bpb=1.095947 time=1026.8s + ttt_chunk [951/1893] bpb=1.095952 time=1037.7s + ttt_chunk [961/1893] bpb=1.095702 time=1048.6s + ttt_chunk [971/1893] bpb=1.096410 time=1059.5s + ttt_chunk [981/1893] bpb=1.096564 time=1070.4s + ttt_chunk [991/1893] bpb=1.096465 time=1081.3s + ttt_chunk [1001/1893] bpb=1.096600 time=1092.2s + ttt_chunk [1011/1893] bpb=1.096849 time=1103.1s + ttt_chunk [1021/1893] bpb=1.096995 time=1114.0s + ttt_chunk [1031/1893] bpb=1.097540 time=1124.9s + ttt_chunk [1041/1893] bpb=1.097195 time=1135.8s + ttt_chunk [1051/1893] bpb=1.096931 time=1146.7s + ttt_chunk [1061/1893] bpb=1.097171 time=1157.6s + ttt_chunk [1071/1893] bpb=1.097623 time=1168.5s + ttt_chunk [1081/1893] bpb=1.097641 time=1179.4s + ttt_chunk [1091/1893] bpb=1.098038 time=1190.4s + ttt_chunk [1101/1893] bpb=1.098168 time=1201.3s + ttt_chunk [1111/1893] bpb=1.097948 time=1212.2s + ttt_chunk [1121/1893] bpb=1.097865 time=1223.1s + ttt_chunk [1131/1893] bpb=1.097777 time=1234.0s + ttt_chunk [1141/1893] bpb=1.097631 time=1244.9s + ttt_chunk [1151/1893] bpb=1.097673 time=1255.8s + ttt_chunk [1161/1893] bpb=1.096980 time=1266.7s + ttt_chunk [1171/1893] bpb=1.097561 time=1277.6s + ttt_chunk [1181/1893] bpb=1.097045 time=1288.5s + ttt_chunk [1191/1893] bpb=1.096742 time=1299.4s + ttt_chunk [1201/1893] bpb=1.097314 time=1310.3s + ttt_chunk [1211/1893] bpb=1.096736 time=1321.2s + ttt_chunk [1221/1893] bpb=1.096434 time=1332.2s + ttt_chunk [1231/1893] bpb=1.096362 time=1343.1s + ttt_chunk [1241/1893] bpb=1.096176 time=1354.0s + ttt_chunk [1251/1893] bpb=1.095931 time=1364.9s + ttt_chunk [1261/1893] bpb=1.095864 time=1375.8s + ttt_chunk [1271/1893] bpb=1.095656 time=1386.7s + ttt_chunk [1281/1893] bpb=1.095457 time=1397.6s + ttt_chunk [1291/1893] bpb=1.095263 time=1408.6s + ttt_chunk [1301/1893] bpb=1.094875 time=1419.5s + ttt_chunk [1311/1893] bpb=1.094556 time=1430.4s + ttt_chunk [1321/1893] bpb=1.094368 time=1441.3s + ttt_chunk [1331/1893] bpb=1.094276 time=1452.2s + ttt_chunk [1341/1893] bpb=1.094154 time=1463.1s + ttt_chunk [1351/1893] bpb=1.094097 time=1474.0s + ttt_chunk [1361/1893] bpb=1.094305 time=1484.9s + ttt_chunk [1371/1893] bpb=1.094142 time=1495.8s + ttt_chunk [1381/1893] bpb=1.094051 time=1506.8s + ttt_chunk [1391/1893] bpb=1.093534 time=1517.7s + ttt_chunk [1401/1893] bpb=1.093535 time=1528.6s + ttt_chunk [1411/1893] bpb=1.093563 time=1539.5s + ttt_chunk [1421/1893] bpb=1.093801 time=1550.4s + ttt_chunk [1431/1893] bpb=1.093653 time=1561.3s + ttt_chunk [1441/1893] bpb=1.094314 time=1572.2s + ttt_chunk [1451/1893] bpb=1.094417 time=1583.1s + ttt_chunk [1461/1893] bpb=1.094159 time=1594.0s + ttt_chunk [1471/1893] bpb=1.095064 time=1604.9s + ttt_chunk [1481/1893] bpb=1.094872 time=1615.8s + ttt_chunk [1491/1893] bpb=1.094874 time=1626.7s + ttt_chunk [1501/1893] bpb=1.095028 time=1637.6s + ttt_chunk [1511/1893] bpb=1.095090 time=1648.5s + ttt_chunk [1521/1893] bpb=1.095110 time=1659.4s + ttt_chunk [1531/1893] bpb=1.094932 time=1670.3s + ttt_chunk [1541/1893] bpb=1.094910 time=1681.2s + ttt_chunk [1551/1893] bpb=1.095253 time=1692.1s + ttt_chunk [1561/1893] bpb=1.095391 time=1703.0s + ttt_chunk [1571/1893] bpb=1.095518 time=1713.9s + ttt_chunk [1581/1893] bpb=1.095631 time=1724.8s + ttt_chunk [1591/1893] bpb=1.095580 time=1735.7s + ttt_chunk [1601/1893] bpb=1.095759 time=1746.6s + ttt_chunk [1611/1893] bpb=1.095828 time=1757.5s + ttt_chunk [1621/1893] bpb=1.095692 time=1768.4s + ttt_chunk [1631/1893] bpb=1.095861 time=1779.3s + ttt_chunk [1641/1893] bpb=1.095750 time=1790.2s + ttt_chunk [1651/1893] bpb=1.095660 time=1801.1s + ttt_chunk [1661/1893] bpb=1.095550 time=1812.0s + ttt_chunk [1671/1893] bpb=1.095906 time=1822.9s + ttt_chunk [1681/1893] bpb=1.096158 time=1833.8s + ttt_chunk [1691/1893] bpb=1.096122 time=1844.7s + ttt_chunk [1701/1893] bpb=1.096115 time=1855.6s + ttt_chunk [1711/1893] bpb=1.095947 time=1866.5s + ttt_chunk [1721/1893] bpb=1.095795 time=1877.4s + ttt_chunk [1731/1893] bpb=1.095752 time=1888.2s + ttt_chunk [1741/1893] bpb=1.095526 time=1899.2s + ttt_chunk [1751/1893] bpb=1.095379 time=1910.1s + ttt_chunk [1761/1893] bpb=1.095468 time=1920.9s + ttt_chunk [1771/1893] bpb=1.095400 time=1931.8s + ttt_chunk [1781/1893] bpb=1.095342 time=1942.7s + ttt_chunk [1791/1893] bpb=1.094947 time=1953.7s + ttt_chunk [1801/1893] bpb=1.094944 time=1964.6s + ttt_chunk [1811/1893] bpb=1.094777 time=1975.4s + ttt_chunk [1821/1893] bpb=1.094808 time=1986.3s + ttt_chunk [1831/1893] bpb=1.094411 time=1997.2s + ttt_chunk [1841/1893] bpb=1.094394 time=2008.2s + ttt_chunk [1851/1893] bpb=1.094164 time=2019.0s + ttt_chunk [1861/1893] bpb=1.093702 time=2030.0s + ttt_chunk [1871/1893] bpb=1.093549 time=2040.8s + ttt_chunk [1881/1893] bpb=1.093167 time=2051.7s + ttt_chunk [1891/1893] bpb=1.093004 time=2062.6s + ttt_chunk [1893/1893] bpb=1.093024 time=2064.1s +ttt_sliding:done val_loss=1.843745 val_bpb=1.091973 elapsed=2064.2s +final_int6_zstd-22_roundtrip val_loss:1.8437 val_bpb:1.0920 eval:2064650ms +final_int6_zstd-22_roundtrip_exact val_bpb:1.09197267 diff --git a/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/train_gpt.py b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/train_gpt.py new file mode 100644 index 000000000..09e425b1b --- /dev/null +++ b/records/track_non_record_16mb/2026-03-24_11L_GEPA_30kSteps_PureInt6_LegalTTT/train_gpt.py @@ -0,0 +1,1762 @@ +"""train_gpt.py — GEPA (SwiGLU + U-Net + BigramHash + EMA + XSA4 + GPTQ-lite) + Legal TTT.""" + +from __future__ import annotations + +import copy +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import uuid +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 + +# zstd-22 compression with zlib fallback +try: + import zstandard as zstd + USE_ZSTD = True +except ImportError: + import zlib + USE_ZSTD = False + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- + +class Hyperparameters: + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024") + train_files = os.path.join(data_path, "fineweb_train_*.bin") + val_files = os.path.join(data_path, "fineweb_val_*.bin") + tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 42)) + + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200)) + + 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)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + + vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) + num_layers = int(os.environ.get("NUM_LAYERS", "11")) # Up from 9 + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", "8")) + 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", 3)) # Unused by Star-ReLU + mlp_hidden = int(os.environ.get("MLP_HIDDEN", "1792")) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + eval_stride = int(os.environ.get("EVAL_STRIDE", 64)) + eval_batch_seqs = int(os.environ.get("EVAL_BATCH_SEQS", 32)) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + + # BigramHash config + bigram_buckets = int(os.environ.get("BIGRAM_BUCKETS", "8192")) + bigram_embed_dim = int(os.environ.get("BIGRAM_EMBED_DIM", 128)) + + # Partial RoPE: apply rotary to only first ROPE_DIMS of head_dim (0 = full) + rope_dims = int(os.environ.get("ROPE_DIMS", 16)) + + # YARN RoPE: train_seq_len for YARN scaling (default 1024 enables YARN at seq_len=2048) + rope_train_seq_len = int(os.environ.get("ROPE_TRAIN_SEQ_LEN", "1024")) + + # LN Scale: scale norm input by 1/sqrt(layer_idx+1) per block + ln_scale = bool(int(os.environ.get("LN_SCALE", "1"))) + + # Optimizer hyperparameters (updated to match #1 team) + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.008)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.035)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.025)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.025)) + decoder_lr_mult = float(os.environ.get("DECODER_LR_MULT", 2.0)) + 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)) + muon_wd = float(os.environ.get("MUON_WD", 0.04)) + adam_wd = float(os.environ.get("ADAM_WD", 0.04)) + 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.0)) + + # V2 improvements (each controllable via env var) + ortho_init = bool(int(os.environ.get("ORTHO_INIT", "1"))) + bigram_xor_hash = bool(int(os.environ.get("BIGRAM_XOR_HASH", "1"))) + + # EMA: exponential moving average, updates every step (priority over SWA) + ema_enabled = bool(int(os.environ.get("EMA_ENABLED", "1"))) + ema_decay = float(os.environ.get("EMA_DECAY", "0.997")) + + # SWA config (fallback when EMA disabled) + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.5)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + + # Late QAT: enable fake int6 quantization when LR scale < qat_threshold + late_qat = bool(int(os.environ.get("LATE_QAT", "1"))) + qat_threshold = float(os.environ.get("QAT_THRESHOLD", "0.15")) + + # Value Embeddings: reinject token identity into attention values at deep layers + ve_enabled = bool(int(os.environ.get("VE_ENABLED", "1"))) + ve_dim = int(os.environ.get("VE_DIM", 128)) + ve_layers = os.environ.get("VE_LAYERS", "9,10") + + # TTT: legal score-first fine-tune on val data after training + xsa_layers = int(os.environ.get("XSA_LAYERS", "4")) + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "1"))) + ttt_lr = float(os.environ.get("TTT_LR", 0.003)) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", 3)) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 2)) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", 1.0)) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", 32)) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) + ttt_optimizer = os.environ.get("TTT_OPTIMIZER", "adamw") # "sgd" or "adamw" + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", 0.9)) # for SGD + ttt_adam_wd = float(os.environ.get("TTT_ADAM_WD", 0.01)) # for AdamW + + +# ----------------------------- +# MUON OPTIMIZER WITH WEIGHT DECAY +# ----------------------------- + +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.02): + 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"] + wd = group["weight_decay"] + + total_params = sum(int(p.numel()) for p in params) + updates_flat = torch.zeros(total_params, device=params[0].device, dtype=torch.bfloat16) + + curr = 0 + for i, p in enumerate(params): + if i % world_size == rank and p.grad is not None: + g = p.grad + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(g) + if nesterov: + g = g.add(buf, alpha=momentum) + g = zeropower_via_newtonschulz5(g, steps=backend_steps) + g *= max(1, g.size(0) / g.size(1)) ** 0.5 + updates_flat[curr : curr + p.numel()] = g.reshape(-1) + curr += p.numel() + + if distributed: + dist.all_reduce(updates_flat, op=dist.ReduceOp.SUM) + + curr = 0 + for p in params: + # Apply weight decay BEFORE update (standard decoupled WD) + if wd > 0: + p.data.mul_(1.0 - lr * wd) + g = updates_flat[curr : curr + p.numel()].view_as(p).to(dtype=p.dtype) + p.add_(g, alpha=-lr) + curr += p.numel() + + return loss + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION SETUP +# ----------------------------- + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("\u2581"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return ( + torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device), + ) + + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError( + "VAL_BATCH_SIZE must provide at least one sequence per rank; " + f"got VAL_BATCH_SIZE={args.val_batch_size}, WORLD_SIZE={world_size}, " + f"GRAD_ACCUM_STEPS={grad_accum_steps}, TRAIN_SEQ_LEN={args.train_seq_len}" + ) + local_batch_seqs = local_batch_tokens // args.train_seq_len + total_seqs = (val_tokens.numel() - 1) // args.train_seq_len + seq_start = (total_seqs * rank) // world_size + seq_end = (total_seqs * (rank + 1)) // world_size + val_loss_sum = torch.zeros((), device=device, dtype=torch.float64) + val_token_count = torch.zeros((), device=device, dtype=torch.float64) + val_byte_count = torch.zeros((), device=device, dtype=torch.float64) + + model.eval() + with torch.inference_mode(): + for batch_seq_start in range(seq_start, seq_end, local_batch_seqs): + batch_seq_end = min(batch_seq_start + local_batch_seqs, seq_end) + raw_start = batch_seq_start * args.train_seq_len + raw_end = batch_seq_end * args.train_seq_len + 1 + local = val_tokens[raw_start:raw_end].to(device=device, dtype=torch.int64, non_blocking=True) + x = local[:-1].reshape(-1, args.train_seq_len) + y = local[1:].reshape(-1, args.train_seq_len) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + batch_loss = model(x, y).detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += (has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids]).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +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]: + """Sliding window evaluation: each token scored with maximum context.""" + 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] + total_windows = len(window_starts) + + my_s = (total_windows * rank) // world_size + my_e = (total_windows * (rank + 1)) // world_size + my_windows = window_starts[my_s:my_e] + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk[:-1] + y_batch[i, :wlen] = chunk[1:] + + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else wlen - stride + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + + scored_prev = x_batch[i, s:wlen] + scored_tgt = y_batch[i, s:wlen] + tb = base_bytes_lut[scored_tgt].to(torch.int16) + tb += (has_leading_space_lut[scored_tgt] & ~is_boundary_token_lut[scored_prev]).to(torch.int16) + byte_count += tb.to(torch.float64).sum() + token_count += float(wlen - s) + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = loss_sum / token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + base_model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: nn.Module, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + """Legal score-first TTT: score each chunk with sliding windows, then train on it.""" + seq_len = args.train_seq_len + total_tokens = val_tokens.numel() - 1 + ttt_chunk = args.ttt_chunk_tokens + + window_starts = [ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= stride or ws == 0] + + num_chunks = (total_tokens + ttt_chunk - 1) // ttt_chunk + chunk_windows: list[list[int]] = [[] for _ in range(num_chunks)] + for ws in window_starts: + end = min(ws + seq_len, total_tokens) + wlen = end - ws + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_start = ws + s + ci = min(scored_start // ttt_chunk, num_chunks - 1) + chunk_windows[ci].append(ws) + + log0(f"ttt_sliding:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"total_windows={len(window_starts)} stride={stride} " + f"ttt_lr={args.ttt_lr} ttt_epochs={args.ttt_epochs} " + f"ttt_optimizer={args.ttt_optimizer} freeze_blocks={args.ttt_freeze_blocks}") + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + # Freeze first N blocks (GEPA has no depth recurrence, freeze by block index) + n_blocks = len(base_model.blocks) + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, n_blocks))) + + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = False + for bi in frozen_block_ids: + if f"blocks.{bi}." in name: + freeze = True + break + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + log0(f"ttt_sliding:params unfrozen={sum(p.numel() for p in ttt_params)} " + f"frozen={sum(p.numel() for p in base_model.parameters() if not p.requires_grad)}") + + if args.ttt_optimizer == "adamw": + optimizer = torch.optim.AdamW(ttt_params, lr=args.ttt_lr, weight_decay=args.ttt_adam_wd) + else: + optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) + + t0 = time.perf_counter() + + for ci in range(num_chunks): + windows = chunk_windows[ci] + if not windows: + continue + + # --- Phase 1: SCORE this chunk's windows --- + my_s = (len(windows) * rank) // world_size + my_e = (len(windows) * (rank + 1)) // world_size + my_windows = windows[my_s:my_e] + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi:bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + wlens: list[int] = [] + for i, ws in enumerate(batch_ws): + end = min(ws + seq_len, total_tokens) + wlen = end - ws + wlens.append(wlen) + chunk_tok = val_tokens[ws:end + 1].to(dtype=torch.int64, device=device) + x_batch[i, :wlen] = chunk_tok[:-1] + y_batch[i, :wlen] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch) + nll = F.cross_entropy( + logits.reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + wlen = wlens[i] + s = 0 if ws == 0 else max(wlen - stride, 0) + scored_nll = nll[i, s:wlen].to(torch.float64) + loss_sum += scored_nll.sum() + token_count += float(wlen - s) + tgt, prev = y_batch[i, s:wlen], x_batch[i, s:wlen] + tb = base_bytes_lut[tgt].to(torch.float64) + tb += (has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev]).to(torch.float64) + byte_count += tb.sum() + + # --- Phase 2: TRAIN on this chunk's tokens (already scored = legal) --- + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + # TTT LR schedule: linear warmup over first 5% of chunks, then cosine decay + warmup_chunks = max(num_chunks // 20, 1) + if ci < warmup_chunks: + lr_scale = (ci + 1) / warmup_chunks + else: + progress = (ci - warmup_chunks) / max(num_chunks - 1 - warmup_chunks, 1) + lr_scale = 0.5 * (1.0 + math.cos(math.pi * progress)) + cos_lr = args.ttt_lr * lr_scale + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + + my_seq_s = (chunk_seqs * rank) // world_size + my_seq_e = (chunk_seqs * (rank + 1)) // world_size + my_chunk_seqs = my_seq_e - my_seq_s + + for _ep in range(args.ttt_epochs): + for bs in range(0, my_chunk_seqs, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_chunk_seqs) + actual_bs = my_seq_s + bs + actual_be = my_seq_s + be + start_tok = chunk_start + actual_bs * seq_len + end_tok = chunk_start + actual_be * seq_len + 1 + if end_tok > val_tokens.numel(): + continue + local = val_tokens[start_tok:end_tok].to(device=device, dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + optimizer.zero_grad(set_to_none=True) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + loss = base_model(x, y) + loss.backward() + if world_size > 1: + for p in ttt_params: + if p.grad is not None: + dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) + if args.ttt_grad_clip > 0: + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) if token_count.item() > 0 else 0.0 + log0(f" ttt_chunk [{ci+1}/{num_chunks}] bpb={rbpb:.6f} time={elapsed:.1f}s") + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = (loss_sum / token_count).item() + val_bpb = val_loss / math.log(2.0) * (token_count.item() / byte_count.item()) + + for p in base_model.parameters(): + p.requires_grad_(True) + base_model.eval() + + log0(f"ttt_sliding:done val_loss={val_loss:.6f} val_bpb={val_bpb:.6f} " + f"elapsed={time.perf_counter() - t0:.1f}s") + return val_loss, val_bpb + + +# ----------------------------- +# POST-TRAINING INT6 QUANTIZATION +# ----------------------------- + +INT6_MIN = -32 +INT6_MAX = 31 +INT6_CLIP_PERCENTILE = 99.99984 +INT6_CLIP_Q = INT6_CLIP_PERCENTILE / 100.0 + +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_gate,bigram,skip_gates,ve_shared,ve_layer_scales", + ).split(",") + if pattern +) +INT6_KEEP_FLOAT_FP32_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "INT6_KEEP_FLOAT_FP32_NAME_PATTERNS", + ",".join(CONTROL_TENSOR_NAME_PATTERNS), + ).split(",") + if pattern +) +INT6_KEEP_FLOAT_MAX_NUMEL = 65_536 +INT6_KEEP_FLOAT_STORE_DTYPE = torch.float16 +INT6_PER_ROW_SCALE_DTYPE = torch.float16 + +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 INT6_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=INT6_KEEP_FLOAT_STORE_DTYPE).contiguous() + return t + +# Storage format: INT8_STORAGE=1 uses [-127,127] for better accuracy (larger artifact) +# Default (int6): uses [-32,31] for smaller artifacts but more quantization noise +# MIXED_QUANT=1: int6 per-row for MLP+attn (QAT-trained), int8 per-tensor for rest +INT8_STORAGE = int(os.environ.get("INT8_STORAGE", "0")) +MIXED_QUANT = int(os.environ.get("MIXED_QUANT", "0")) +QUANT_MIN = -127 if INT8_STORAGE else INT6_MIN +QUANT_MAX = 127 if INT8_STORAGE else INT6_MAX + +def _classify_param(name: str) -> str: + """Classify parameter by category for mixed quantization.""" + if "tok_emb" in name or "lm_head" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if ".attn." in name or (".proj." in name and ".mlp." not in name): + return "attn" + return "other" + +def quantize_float_tensor_int8_scalar(t: Tensor) -> tuple[Tensor, Tensor]: + """Quantize to int8 [-127,127] range with per-tensor scalar scale.""" + t32 = t.float() + amax = t32.abs().max().item() + scale = torch.tensor(amax / 127.0 if amax > 0 else 1.0, dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -127, 127).to(torch.int8) + return q.contiguous(), scale + +def quantize_float_tensor_int6(t: Tensor) -> tuple[Tensor, Tensor]: + """Quantize to int6 [-32,31] or int8 [-127,127] range, stored as int8. + Uses GPTQ-lite: per-row optimal clip percentile search (15 candidates) + to minimize reconstruction MSE. Free improvement over fixed percentile.""" + t32 = t.float() + qmin, qmax = QUANT_MIN, QUANT_MAX + if t32.ndim == 2 and t32.numel() > 0: + # GPTQ-lite: per-row optimal clip percentile search (20 candidates) + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.990, 0.993, 0.995, 0.997, 0.998, 0.999, 0.9993, 0.9995, + 0.9997, 0.9999, 0.99993, 0.99995, 0.99997, 0.99999, 1.0]: + if pct < 1.0: + row_clip = torch.quantile(t32.abs(), pct, dim=1) + else: + row_clip = t32.abs().amax(dim=1) + scale = (row_clip / float(qmax)).clamp_min(1.0 / float(qmax)) + q = torch.clamp(torch.round(t32 / scale[:, None]), qmin, qmax).to(torch.int8) + recon = q.float() * scale[:, None] + err = (t32 - recon).pow(2).mean().item() + if err < best_err: + best_q = q.contiguous() + best_s = scale.to(dtype=INT6_PER_ROW_SCALE_DTYPE).contiguous() + best_err = err + return best_q, best_s + + clip_abs = float(torch.quantile(t32.abs().flatten(), INT6_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / float(qmax) if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), qmin, qmax).to(torch.int8).contiguous() + return q, scale + +def quantize_state_dict_int6(state_dict: dict[str, Tensor]): + 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", "int6_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["int6_payload_bytes"] += tensor_nbytes(t) + continue + + # Keep small float tensors (and tok_emb.weight unless QUANT_EMBED=1) in fp16 + quant_embed = int(os.environ.get("QUANT_EMBED", "0")) + if t.numel() <= INT6_KEEP_FLOAT_MAX_NUMEL or (name == "tok_emb.weight" and not quant_embed): + kept = keep_float_tensor(name, t, passthrough_orig_dtypes) + passthrough[name] = kept + stats["int6_payload_bytes"] += tensor_nbytes(kept) + continue + + stats["num_float_tensors"] += 1 + # Mixed quantization: int6 per-row for MLP+attn, int8 per-tensor for rest + cat = _classify_param(name) + if MIXED_QUANT and cat not in ("mlp", "attn"): + q, s = quantize_float_tensor_int8_scalar(t) + qmeta[name] = {"scheme": "per_tensor", "quant_type": "int8"} + else: + q, s = quantize_float_tensor_int6(t) + 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["int6_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + quant_label = "mixed" if MIXED_QUANT else ("int8" if INT8_STORAGE else "int6") + obj: dict[str, object] = { + "__quant_format__": f"{quant_label}_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_int6(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) + 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(): + 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: + 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): + # Class-level flag: set True during late-QAT phase to enable fake int6 STE + _qat_enabled: bool = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if CastedLinear._qat_enabled and self.training and w.ndim == 2: + # Fake int6 quantization via straight-through estimator + with torch.no_grad(): + w32 = self.weight.float() + row_max = w32.abs().amax(dim=1) + scale = (row_max / 31.0).clamp_min(1.0 / 31.0) + w_q = (torch.clamp(torch.round(w32 / scale[:, None]), -32, 31) * scale[:, None]).to(x.dtype) + w = w + (w_q - w).detach() + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + """RoPE with optional partial application and YARN scaling.""" + def __init__(self, dim: int, base: float = 10000.0, rope_dims: int = 0, train_seq_len: int = 1024): + super().__init__() + # rope_dims=0 means full head_dim; otherwise rotate only first rope_dims dims + rope_d = rope_dims if rope_dims > 0 else dim + self.rope_d = rope_d + self.base = base + self.train_seq_len = train_seq_len + inv_freq = 1.0 / (base ** (torch.arange(0, rope_d, 2, dtype=torch.float32) / rope_d)) + 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 + ): + rd = self.rope_d + if seq_len > self.train_seq_len: + scale = seq_len / self.train_seq_len + new_base = self.base * (scale ** (rd / (rd - 2))) + inv_freq = 1.0 / (new_base ** (torch.arange(0, rd, 2, dtype=torch.float32, device=device) / rd)) + 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: + """Apply RoPE; if cos covers fewer dims than x, rotate only those dims.""" + rd = cos.size(-1) * 2 + if rd < x.size(-1): + x_rope = x[..., :rd] + x_pass = x[..., rd:] + half = rd // 2 + x1 = x_rope[..., :half] + x2 = x_rope[..., half:] + x_rot = torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + return torch.cat((x_rot, x_pass), dim=-1) + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + + +class CausalSelfAttention(nn.Module): + def __init__(self, dim: int, num_heads: int, num_kv_heads: int, rope_base: float, qk_gain_init: float, rope_dims: int = 0, rope_train_seq_len: int = 1024): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base, rope_dims=rope_dims, train_seq_len=rope_train_seq_len) + self.use_xsa = False + + 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, v_embed: Tensor | None = None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = self.c_v(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + # Add value embeddings to v before attention if provided + if v_embed is not None: + ve_reshaped = v_embed.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = v + ve_reshaped + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, is_causal=True, enable_gqa=(self.num_kv_heads != self.num_heads)) + if self.use_xsa: + y_xsa = y.transpose(1, 2) + v_xsa = v.transpose(1, 2) + y_xsa = self._xsa_efficient(y_xsa, v_xsa) + y = y_xsa.reshape(bsz, seqlen, dim) + else: + y = y.transpose(1, 2).contiguous().reshape(bsz, seqlen, dim) + return self.proj(y) + + +class MLP(nn.Module): + def __init__(self, dim: int, mlp_mult: int, mlp_hidden: int = 0): + super().__init__() + # Star-ReLU implementation. mlp_mult is unused. + hidden = mlp_hidden if mlp_hidden > 0 else int(dim * 3) + self.up_proj = CastedLinear(dim, hidden, bias=False) + self.down_proj = CastedLinear(hidden, dim, bias=False) + self.down_proj._zero_init = True + self.scale = nn.Parameter(torch.ones(hidden, dtype=torch.float32)) + self.bias = nn.Parameter(torch.zeros(hidden, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + x_up = self.up_proj(x) + activated = F.relu(x_up).pow(2) + activated = activated * self.scale.to(dtype=activated.dtype) + self.bias.to(dtype=activated.dtype) + return self.down_proj(activated) + + +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, + rope_dims: int = 0, + layer_idx: int = 0, + ln_scale: bool = False, + rope_train_seq_len: int = 1024, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init, rope_dims=rope_dims, rope_train_seq_len=rope_train_seq_len) + self.mlp = MLP(dim, mlp_mult, mlp_hidden=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()) + # LN Scale: dampen norm inputs by 1/sqrt(layer_idx+1) for deeper layers + self.ln_scale_factor = 1.0 / math.sqrt(layer_idx + 1) if ln_scale else 1.0 + + def forward(self, x: Tensor, x0: Tensor, v_embed: Tensor | None = None) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + s = self.ln_scale_factor + attn_out = self.attn(self.attn_norm(x) * s, v_embed=v_embed) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x) * s) + return x + + +# ----------------------------- +# BIGRAM HASH EMBEDDING +# ----------------------------- + +class BigramHashEmbedding(nn.Module): + """Hash-based bigram embedding with optional XOR hash and learned scale.""" + def __init__(self, num_buckets: int, embed_dim: int, model_dim: int, use_xor_hash: bool = True): + super().__init__() + self.num_buckets = num_buckets + self.use_xor_hash = use_xor_hash + self.embed = nn.Embedding(num_buckets, embed_dim) + self.proj = CastedLinear(embed_dim, model_dim, bias=False) + if use_xor_hash: + nn.init.zeros_(self.embed.weight) # Zero init with learned scale + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.05, dtype=torch.float32)) + else: + nn.init.normal_(self.embed.weight, std=0.01) + nn.init.zeros_(self.proj.weight) + self.scale = None + + def bigram_hash(self, tokens: Tensor) -> Tensor: + """XOR-based bigram hash with large primes for uniform distribution.""" + t = tokens.to(torch.int32) + mod = self.num_buckets - 1 + out = torch.empty_like(t) + out[..., 0] = mod # Special bucket for first position + out[..., 1:] = torch.bitwise_xor(36313 * t[..., 1:], 27191 * t[..., :-1]) % mod + return out.long() + + def forward(self, input_ids: Tensor) -> Tensor: + if self.use_xor_hash: + h = self.embed(self.bigram_hash(input_ids)) + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + else: + bsz, seq_len = input_ids.shape + prev_ids = F.pad(input_ids[:, :-1], (1, 0), value=0) + bigram_hash = (prev_ids * 1009 + input_ids) % self.num_buckets + bigram_emb = self.embed(bigram_hash) + return self.proj(bigram_emb) + + +# ----------------------------- +# SMEAR GATE +# ----------------------------- + +class SmearGate(nn.Module): + """Learned blending of current position with previous position.""" + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + # x: (bsz, seq_len, dim) + gate = torch.sigmoid(self.gate.to(dtype=x.dtype)) + # Shift x to get previous position, pad with zeros + x_prev = F.pad(x[:, :-1], (0, 0, 1, 0)) + return (1 - gate) * x + gate * x_prev + + +class ValueEmbedding(nn.Module): + """Reinject token identity into attention values at specific layers.""" + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int): + super().__init__() + self.embed = nn.Embedding(vocab_size, ve_dim) + nn.init.normal_(self.embed.weight, std=0.01) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) if ve_dim != kv_dim else None + if self.proj is not None: + nn.init.zeros_(self.proj.weight) + self.scale = nn.Parameter(torch.tensor(0.1, dtype=torch.float32)) + + def forward(self, token_ids: Tensor) -> Tensor: + h = self.embed(token_ids) + if self.proj is not None: + h = self.proj(h) + return h * self.scale.to(dtype=h.dtype) + + +class 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, + tie_embeddings: bool, + tied_embed_init_std: float, + logit_softcap: float, + rope_base: float, + qk_gain_init: float, + mlp_hidden: int = 0, + bigram_buckets: int = 4096, + bigram_embed_dim: int = 128, + bigram_xor_hash: bool = True, + rope_dims: int = 0, + ln_scale: bool = False, + xsa_last_n: int = 0, + ve_enabled: bool = False, + ve_dim: int = 128, + ve_layers: str = "9,10", + rope_train_seq_len: int = 1024, + ortho_init: bool = True, + ): + 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.ortho_init = ortho_init + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.bigram_emb = BigramHashEmbedding(bigram_buckets, bigram_embed_dim, model_dim, use_xor_hash=bigram_xor_hash) if bigram_buckets > 0 else None + self.smear_gate = 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.skip_gates = nn.Parameter(torch.zeros(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, rope_dims=rope_dims, layer_idx=i, ln_scale=ln_scale, + rope_train_seq_len=rope_train_seq_len, + ) + for i in range(num_layers) + ]) + if xsa_last_n > 0: + for i in range(max(0, num_layers - xsa_last_n), num_layers): + self.blocks[i].attn.use_xsa = True + # Value Embeddings: reinject token identity into values at deep layers + kv_dim = model_dim // num_heads * num_kv_heads + self.ve_layer_indices = [int(x) for x in ve_layers.split(",") if x.strip()] if ve_enabled else [] + if self.ve_layer_indices: + self.ve_shared = ValueEmbedding(vocab_size, ve_dim, kv_dim) + self.ve_layer_scales = nn.ParameterList( + [nn.Parameter(torch.ones(1, dtype=torch.float32)) for _ in self.ve_layer_indices] + ) + else: + self.ve_shared = None + self.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 self.ortho_init and module.weight.ndim == 2 and module.weight.shape[0] >= 64 and module.weight.shape[1] >= 64: + nn.init.orthogonal_(module.weight, gain=1.0) + if ".proj." in name or name.endswith(".proj"): + with torch.no_grad(): + module.weight.mul_(1.0 / math.sqrt(2 * num_layers)) + + def _get_ve(self, layer_idx: int, input_ids: Tensor, ve_cache: dict) -> Tensor | None: + if self.ve_shared is None or layer_idx not in self.ve_layer_indices: + return None + if 've' not in ve_cache: + ve_cache['ve'] = self.ve_shared(input_ids) + ve_base = ve_cache['ve'] + ve_idx = self.ve_layer_indices.index(layer_idx) + return ve_base * self.ve_layer_scales[ve_idx].to(dtype=ve_base.dtype) + + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.bigram_emb is not None: + x = x + self.bigram_emb(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear_gate(x) + x0 = x + skips: list[Tensor] = [] + ve_cache: dict = {} + + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, input_ids, ve_cache)) + skips.append(x) + for i in range(self.num_decoder_layers): + bi = self.num_encoder_layers + i + if skips: + skip = skips.pop() + gate = torch.sigmoid(self.skip_gates[i].to(dtype=x.dtype)) + scaled_skip = self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skip + x = gate[None, None, :] * x + (1.0 - gate[None, None, :]) * scaled_skip + x = self.blocks[bi](x, x0, v_embed=self._get_ve(bi, input_ids, ve_cache)) + + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + """Return logits (bsz, seq_len, vocab) without computing loss.""" + x = self.tok_emb(input_ids) + if self.bigram_emb is not None: + x = x + self.bigram_emb(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + x = self.smear_gate(x) + x0 = x + skips: list[Tensor] = [] + ve_cache: dict = {} + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0, v_embed=self._get_ve(i, input_ids, ve_cache)) + skips.append(x) + for i in range(self.num_decoder_layers): + bi = self.num_encoder_layers + i + if skips: + skip = skips.pop() + gate = torch.sigmoid(self.skip_gates[i].to(dtype=x.dtype)) + scaled_skip = self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skip + x = gate[None, None, :] * x + (1.0 - gate[None, None, :]) * scaled_skip + x = self.blocks[bi](x, x0, v_embed=self._get_ve(bi, input_ids, ve_cache)) + 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) + + + +# ----------------------------- +# 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 + + 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"))) + 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 SETUP + # ----------------------------- + + CastedLinear._qat_enabled = False # start with QAT off; late_qat enables it mid-run + + 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, + mlp_hidden=args.mlp_hidden, + bigram_buckets=args.bigram_buckets, + bigram_embed_dim=args.bigram_embed_dim, + bigram_xor_hash=args.bigram_xor_hash, + rope_dims=args.rope_dims, + ln_scale=args.ln_scale, + xsa_last_n=args.xsa_layers, + ve_enabled=args.ve_enabled, + ve_dim=args.ve_dim, + ve_layers=args.ve_layers, + rope_train_seq_len=args.rope_train_seq_len, + ortho_init=args.ortho_init, + ).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 + + # Differential LR setup + matrix_params_enc, scalar_params_enc = [], [] + matrix_params_dec, scalar_params_dec = [], [] + num_encoder_layers = base_model.num_encoder_layers + for i, block in enumerate(base_model.blocks): + is_decoder = i >= num_encoder_layers + for name, p in block.named_parameters(): + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS): + (matrix_params_dec if is_decoder else matrix_params_enc).append(p) + else: + (scalar_params_dec if is_decoder else scalar_params_enc).append(p) + + # Non-block scalar parameters + other_scalar_params = [base_model.smear_gate.gate] + if base_model.bigram_emb is not None: + other_scalar_params.append(base_model.bigram_emb.embed.weight) + if base_model.skip_weights.numel() > 0: + other_scalar_params.append(base_model.skip_weights) + if hasattr(base_model, 'skip_gates') and base_model.skip_gates.numel() > 0: + other_scalar_params.append(base_model.skip_gates) + # Value Embedding parameters + if base_model.ve_shared is not None: + other_scalar_params.extend(list(base_model.ve_shared.parameters())) + other_scalar_params.extend(list(base_model.ve_layer_scales.parameters())) + + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + optimizer_tok = torch.optim.AdamW( + [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.adam_wd, + fused=True, + ) + + matrix_lr_dec = args.matrix_lr * args.decoder_lr_mult + optimizer_muon = Muon( + [ + {'params': matrix_params_enc, 'lr': args.matrix_lr, 'base_lr': args.matrix_lr}, + {'params': matrix_params_dec, 'lr': matrix_lr_dec, 'base_lr': matrix_lr_dec}, + ], + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.muon_wd, + ) + + scalar_lr_dec = args.scalar_lr * args.decoder_lr_mult + optimizer_scalar = torch.optim.AdamW( + [ + {'params': scalar_params_enc, 'lr': args.scalar_lr, 'base_lr': args.scalar_lr}, + {'params': scalar_params_dec, 'lr': scalar_lr_dec, 'base_lr': scalar_lr_dec}, + {'params': other_scalar_params, 'lr': args.scalar_lr, 'base_lr': args.scalar_lr}, + ], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.adam_wd, + fused=True, + ) + + optimizer_bigram_proj = Muon( + [base_model.bigram_emb.proj.weight], + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.muon_wd, + ) + for group in optimizer_bigram_proj.param_groups: + group["base_lr"] = args.matrix_lr + + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar, optimizer_bigram_proj] + if base_model.lm_head is not None: + optimizer_head = torch.optim.AdamW( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.adam_wd, + 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} head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr} decoder_lr_mult:{args.decoder_lr_mult}") + log0(f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} iterations:{args.iterations} warmup_steps:{args.warmup_steps} max_wallclock_seconds:{args.max_wallclock_seconds:.3f}") + log0(f"rope_dims:{args.rope_dims} rope_train_seq_len:{args.rope_train_seq_len} ln_scale:{args.ln_scale}") + log0(f"muon_wd:{args.muon_wd} adam_wd:{args.adam_wd} ema_enabled:{args.ema_enabled} late_qat:{args.late_qat}") + log0(f"bigram_buckets:{args.bigram_buckets} bigram_embed_dim:{args.bigram_embed_dim} seed:{args.seed}") + if args.ttt_enabled: + log0(f"ttt:enabled optimizer:{args.ttt_optimizer} lr:{args.ttt_lr} epochs:{args.ttt_epochs} " + f"freeze_blocks:{args.ttt_freeze_blocks} chunk_tokens:{args.ttt_chunk_tokens}") + + # ----------------------------- + # 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 + + 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) + + # ----------------------------- + # EMA / SWA STATE + # ----------------------------- + + # EMA takes priority; SWA is fallback (mutually exclusive) + 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()} + log0(f"ema:init decay={args.ema_decay}") + + swa_state: dict[str, Tensor] = {} + swa_count = 0 + + def update_swa(): + nonlocal swa_count + with torch.no_grad(): + for name, param in base_model.state_dict().items(): + if name not in swa_state: + swa_state[name] = param.detach().cpu().clone().float() + else: + swa_state[name].add_(param.detach().cpu().float()) + swa_count += 1 + + def get_swa_state() -> dict[str, Tensor]: + return {name: (t / swa_count).to(dtype=base_model.state_dict()[name].dtype) for name, t in swa_state.items()} + + # ----------------------------- + # MAIN TRAINING LOOP + # ----------------------------- + + training_time_ms = 0.0 + stop_after_step: int | None = None + torch.cuda.synchronize() + t0 = time.perf_counter() + + # Estimate total steps for SWA start + estimated_total_steps = args.iterations + if max_wallclock_ms is not None: + estimated_total_steps = min(args.iterations, int(max_wallclock_ms / 30)) # rough estimate + + 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} 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) + + # Late QAT: enable fake int6 quantization once LR scale drops below threshold + # NOTE: torch.compile constant-folds _qat_enabled at first trace, so we must + # reset dynamo caches to force recompilation with QAT branch active. + if args.late_qat and not CastedLinear._qat_enabled and scale < args.qat_threshold: + CastedLinear._qat_enabled = True + torch._dynamo.reset() # force recompile with QAT enabled + log0(f"late_qat:enabled step:{step} scale:{scale:.4f} (dynamo reset for recompile)") + + 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 group in optimizer_bigram_proj.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + step += 1 + + # EMA update every step (takes priority over SWA) + if ema_state is not None: + d = args.ema_decay + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(d).add_(t.detach().float(), alpha=1.0 - d) + + # SWA update (only when EMA disabled) + swa_start_step = int(estimated_total_steps * args.swa_start_frac) + if ema_state is None and step >= swa_start_step and step % args.swa_every == 0: + update_swa() + + 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} 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 + + # Final SWA update (only if EMA disabled and no SWA yet) + if ema_state is None and swa_count == 0: + update_swa() + + log0(f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB") + + # Apply EMA or SWA weights (EMA takes priority) + if ema_state is not None: + log0("ema:applying EMA weights") + avg_state = {name: t.to(dtype=base_model.state_dict()[name].dtype) for name, t in ema_state.items()} + del ema_state + base_model.load_state_dict(avg_state, strict=True) + del avg_state + elif swa_count > 0: + log0(f"swa:applying averaged {swa_count} checkpoints") + base_model.load_state_dict(get_swa_state(), strict=True) + else: + log0("weight_avg:skipped (no EMA or SWA state)") + + # ----------------------------- + # TTT: fine-tune on val data AFTER EMA/SWA, BEFORE quantization + # ----------------------------- + + # ----------------------------- + # SERIALIZATION + ROUNDTRIP VALIDATION + # ----------------------------- + + 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_int6(base_model.state_dict()) + quant_buf = io.BytesIO() + torch.save(quant_obj, quant_buf) + quant_raw = quant_buf.getvalue() + + # Use zstd-22 for compression (or zlib fallback) + if USE_ZSTD: + cctx = zstd.ZstdCompressor(level=22) + quant_blob = cctx.compress(quant_raw) + compression_method = "zstd-22" + else: + import zlib + quant_blob = zlib.compress(quant_raw, level=9) + compression_method = "zlib-9" + + quant_raw_bytes = len(quant_raw) + if master_process: + with open("final_model.int6.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int6.ptz") + code_bytes = len(code.encode("utf-8")) + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int6_payload_bytes"], 1) + q_label = "mixed" if MIXED_QUANT else ("int8" if INT8_STORAGE else "int6") + log0(f"Serialized model {q_label}+{compression_method}: {quant_file_bytes} bytes (payload:{quant_stats['int6_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)") + log0(f"Total submission size {q_label}+{compression_method}: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int6.ptz", "rb") as f: + quant_blob_disk = f.read() + + # Decompress + if USE_ZSTD: + dctx = zstd.ZstdDecompressor() + quant_raw_disk = dctx.decompress(quant_blob_disk) + else: + import zlib + quant_raw_disk = zlib.decompress(quant_blob_disk) + + quant_state = torch.load(io.BytesIO(quant_raw_disk), map_location="cpu") + base_model.load_state_dict(dequantize_state_dict_int6(quant_state), strict=True) + torch.cuda.synchronize() + + # Quick pre-TTT eval to measure quantization gap + t_pre = time.perf_counter() + pre_val_loss, pre_val_bpb = eval_val( + args, base_model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + log0(f"pre_ttt_quant_eval val_loss:{pre_val_loss:.6f} val_bpb:{pre_val_bpb:.6f} elapsed:{time.perf_counter()-t_pre:.1f}s") + + t_qeval = time.perf_counter() + if args.ttt_enabled and args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window_ttt stride:{args.eval_stride} " + f"chunk_tokens:{args.ttt_chunk_tokens} optimizer:{args.ttt_optimizer}") + q_val_loss, q_val_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, log0=log0) + elif args.eval_stride > 0 and args.eval_stride < args.train_seq_len: + log0(f"final_eval_mode:sliding_window stride:{args.eval_stride}") + q_val_loss, q_val_bpb = eval_val_sliding( + args, base_model, rank, world_size, device, val_tokens, + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.eval_stride, batch_seqs=args.eval_batch_seqs, + ) + else: + log0("final_eval_mode:standard") + q_val_loss, q_val_bpb = eval_val( + args, model, rank, world_size, device, grad_accum_steps, + val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut) + torch.cuda.synchronize() + log0(f"final_int6_{compression_method}_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} eval:{1000.0*(time.perf_counter()-t_qeval):.0f}ms") + log0(f"final_int6_{compression_method}_roundtrip_exact val_bpb:{q_val_bpb:.8f}") + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main() \ No newline at end of file