diff --git a/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/README.md b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/README.md new file mode 100644 index 0000000000..dc387f3c29 --- /dev/null +++ b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/README.md @@ -0,0 +1,112 @@ +# Recursive Transformer 4B/7L + ValueEmbedding + QAT Int6 + TTT + +**val_bpb: 1.1696** (3-seed mean) | **~15.76 MB** | 8xH100 SXM, 600s | Score-First TTT + Sliding Window + +## Results (3-seed) + +| Seed | Steps | ms/step | **TTT+Sliding BPB** | Post-quant BPB | Artifact | +|------|-------|---------|---------------------|----------------|----------| +| 1337 | 5,963 | 100.7 | **1.1698** | 1.1952 | 15,749,104 | +| 42 | 5,967 | 100.7 | **1.1697** | 1.1949 | 15,778,257 | +| 2024 | 5,965 | 100.7 | **1.1693** | 1.1947 | 15,750,116 | +| **Mean** | 5,965 | | **1.1696** | 1.1949 | | + +## Method + +### Recursive Transformer Architecture + +Unlike all other submissions which use standard 10-11 layer transformers, this submission uses a **recursive/looped transformer**: a small number of shared transformer blocks applied repeatedly in a loop. This dramatically reduces unique parameters, allowing a much wider model (dim=1024 vs the standard 512) while staying under 16MB. + +**Core idea:** Instead of 10 unique blocks with 10 sets of weights, use 4 shared blocks applied 7 times (4B/7L). The model sees "depth" through weight reuse, trading unique parameters for effective depth. This is inspired by [TinyRecursiveModels](https://github.com/SamsungSAILMontreal/TinyRecursiveModels) (Samsung SAIL Montreal). + +### U-Net Skip Connections + +The 7 loop iterations are split into encoder (first 3) and decoder (last 4) phases. Encoder loops store activations as skip connections, consumed in reverse order by decoder loops. Per-loop learnable skip weights modulate the skip contribution. + +### Key Components + +| Component | Setting | Notes | +|-----------|---------|-------| +| **Architecture** | 4 shared blocks, 7 loops (dim=1024) | Recursive transformer, ~30M params | +| Attention | 32 heads, 8 KV heads (GQA) | | +| MLP | 2x multiplier | | +| XSA | Last 4 of 7 loops | Cross-Sequence Attention, zero extra params | +| ValueEmbedding | dim=128, last 2 loops | Reinjects token identity into value projection | +| SmearGate | Learned per-dim gate | Blends current token with previous | +| BigramHash | 10240 buckets, dim=128 | Hash(prev, cur) embedding | +| U-Net Skips | Encoder-decoder with learnable weights | | +| RoPE | Standard | | + +### Quantization + +**Int6 QAT from step 0** using Straight-Through Estimator (STE). During training, all large weight matrices are fake-quantized to 6-bit precision in the forward pass. The model learns to be robust to quantization noise throughout training, not just during warmdown. + +The final artifact uses **int8 quantization + GPTQ-lite** (5 clip percentiles per row) compressed with **zstd level 22**. Despite training with int6 QAT, int8 serialization produces better BPB at similar compressed size due to byte-aligned data compressing well with zstd. + +| Stage | BPB (3-seed mean) | +|-------|-----| +| Pre-quant (SWA) | 1.1820 | +| Post-quant int8+zstd | 1.1949 (+0.013) | +| TTT+Sliding eval | **1.1696** | + +### Evaluation: Score-First TTT + Sliding Window + +At eval time, the validation data is processed in chunks (32768 tokens each). For each chunk: +1. **Score** the chunk using sliding windows (stride=64) — pure inference, no training +2. **Train** on the scored chunk with SGD (lr=0.002, momentum=0.9, 3 epochs) — adapts the model for subsequent chunks + +This is "score-first" TTT: you never train on tokens before scoring them, satisfying the competition's constraint that validation data can only be used for TTT on already-evaluated tokens. + +### Optimizer + +Muon optimizer (momentum=0.99) with: +- Matrix LR: 0.02 +- Scalar LR: 0.01 +- Tied embedding LR: 0.02 +- Weight decay: 0.04 +- Grad clip: 0.3 +- Warmdown: 3500 iterations +- Warmup: 100 steps +- SWA: start at 20% of warmdown, every 50 steps + +### Why Recursive? + +The recursive architecture is a genuinely novel contribution to this competition. While it may not match the absolute BPB of heavily-optimized standard transformers, it demonstrates that: + +1. **Weight sharing works at small scale** — 4 blocks doing 7 loops matches or approaches 10-11 unique blocks +2. **Width over depth** — dim=1024 (2x wider than standard) compensates for fewer unique parameters +3. **QAT is essential for recursive models** — without it, quantization error compounds through shared-weight loops (+0.56 BPB degradation without QAT vs +0.012 with QAT from step 0) +4. **U-Net skip connections** stabilize deep recursive loops and enable gradient flow + +### Negative Results + +- **8192 BPE vocabulary**: The -0.42 BPB gain reported for standard transformers does not transfer to recursive models. Factored embeddings add complexity without benefit. +- **EMA**: Incompatible with QAT — averages non-QAT-trained weights, producing mixed weight distributions that quantize poorly. +- **Int5/Int6 post-training quantization**: Without QAT, error compounds through recursive loops. +0.56 BPB degradation vs +0.012 with full QAT. +- **Bitpacking int6**: 6-bit packed data has higher entropy density, compresses worse than int8 with zstd. Net file size increase. + +## Run Command + +## Acknowledgments + +Training hyperparameters (Muon LR, weight decay, BigramHash 10240x128, SWA, grad clip) adapted from [PR #414](https://github.com/openai/parameter-golf/pull/414) by @thwu1. +Recursive architecture inspired by [TinyRecursiveModels](https://github.com/SamsungSAILMontreal/TinyRecursiveModels) (Samsung SAIL Montreal). + +## Run Command + +```bash +NUM_BLOCKS=4 MODEL_DIM=1024 NUM_HEADS=32 NUM_KV_HEADS=8 \ +NUM_LOOPS=7 TRAIN_SEQ_LEN=2048 VOCAB_SIZE=1024 \ +USE_SMEAR_GATE=1 BIGRAM_BUCKETS=10240 BIGRAM_DIM=128 \ +QAT_ENABLED=1 QAT_BITS=6 QAT_MLP_BITS=0 LATE_QAT_THRESHOLD=1.0 \ +EMA_DECAY=0 SWA_START_FRAC=0.2 SWA_EVERY=50 \ +SLIDING_WINDOW_STRIDE=64 \ +TTT_ENABLED=1 TTT_LR=0.002 TTT_EPOCHS=3 TTT_CHUNK_TOKENS=32768 \ +TTT_FREEZE_BLOCKS=1 TTT_MOMENTUM=0.9 TTT_BATCH_SEQS=32 TTT_GRAD_CLIP=1.0 \ +XSA_LAST_N=4 VE_ENABLED=1 VE_DIM=128 VE_LAST_N=2 \ +MATRIX_LR=0.02 SCALAR_LR=0.01 TIED_EMBED_LR=0.02 \ +MUON_MOMENTUM=0.99 WEIGHT_DECAY=0.04 GRAD_CLIP_NORM=0.3 \ +WARMDOWN_ITERS=3500 WARMUP_STEPS=100 \ +SEED=$SEED \ +torchrun --standalone --nproc_per_node=8 train_gpt.py +``` diff --git a/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/cluster_full_output.log b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/cluster_full_output.log new file mode 100644 index 0000000000..f5c49646c0 --- /dev/null +++ b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/cluster_full_output.log @@ -0,0 +1,951 @@ +========== SEED 1337 ========== +W0327 01:50:39.303000 53834 torch/distributed/run.py:803] +W0327 01:50:39.303000 53834 torch/distributed/run.py:803] ***************************************** +W0327 01:50:39.303000 53834 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0327 01:50:39.303000 53834 torch/distributed/run.py:803] ***************************************** +logs/7L_seed1337.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +qat:enabled from step 0 attn=6bit +architecture:recursive num_blocks:4 num_loops:7 shared_block_params:27263104 per_loop_params:28672 +model_params:29950082 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:32 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:600.000 +seed:1337 +warmup_step:10/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:6.9756 val_bpb:4.1313 train_time:0ms step_avg:0.02ms +step:1/20000 train_loss:6.9761 train_time:150ms step_avg:149.69ms +step:2/20000 train_loss:9.9188 train_time:169ms step_avg:84.74ms +step:3/20000 train_loss:8.6877 train_time:269ms step_avg:89.51ms +step:4/20000 train_loss:7.5341 train_time:371ms step_avg:92.67ms +step:5/20000 train_loss:6.7940 train_time:471ms step_avg:94.17ms +step:6/20000 train_loss:7.5570 train_time:572ms step_avg:95.28ms +step:7/20000 train_loss:6.2147 train_time:674ms step_avg:96.23ms +step:8/20000 train_loss:6.1019 train_time:775ms step_avg:96.81ms +step:9/20000 train_loss:5.9525 train_time:875ms step_avg:97.26ms +step:10/20000 train_loss:5.7052 train_time:982ms step_avg:98.15ms +step:100/20000 train_loss:3.3879 train_time:10002ms step_avg:100.02ms +step:200/20000 train_loss:2.8358 train_time:20101ms step_avg:100.51ms +step:300/20000 train_loss:2.4130 train_time:30174ms step_avg:100.58ms +step:400/20000 train_loss:2.2914 train_time:40304ms step_avg:100.76ms +step:500/20000 train_loss:2.4487 train_time:50384ms step_avg:100.77ms +step:500/20000 val_loss:2.4478 val_bpb:1.4497 train_time:50450ms step_avg:100.90ms +step:600/20000 train_loss:2.5100 train_time:60514ms step_avg:100.86ms +step:700/20000 train_loss:2.3990 train_time:70592ms step_avg:100.85ms +step:800/20000 train_loss:2.2354 train_time:80703ms step_avg:100.88ms +step:900/20000 train_loss:2.2918 train_time:90764ms step_avg:100.85ms +step:1000/20000 train_loss:2.3286 train_time:100882ms step_avg:100.88ms +step:1000/20000 val_loss:2.2815 val_bpb:1.3512 train_time:100947ms step_avg:100.95ms +step:1100/20000 train_loss:2.2053 train_time:110911ms step_avg:100.83ms +step:1200/20000 train_loss:2.3513 train_time:121022ms step_avg:100.85ms +step:1300/20000 train_loss:2.3159 train_time:131043ms step_avg:100.80ms +step:1400/20000 train_loss:2.3703 train_time:141101ms step_avg:100.79ms +step:1500/20000 train_loss:2.1790 train_time:151101ms step_avg:100.73ms +step:1500/20000 val_loss:2.2159 val_bpb:1.3124 train_time:151166ms step_avg:100.78ms +step:1600/20000 train_loss:2.0354 train_time:161185ms step_avg:100.74ms +step:1700/20000 train_loss:2.1115 train_time:171183ms step_avg:100.70ms +step:1800/20000 train_loss:2.1573 train_time:181244ms step_avg:100.69ms +step:1900/20000 train_loss:2.1396 train_time:191244ms step_avg:100.65ms +step:2000/20000 train_loss:2.1977 train_time:201302ms step_avg:100.65ms +step:2000/20000 val_loss:2.1822 val_bpb:1.2924 train_time:201368ms step_avg:100.68ms +step:2100/20000 train_loss:2.2198 train_time:211368ms step_avg:100.65ms +step:2200/20000 train_loss:2.0184 train_time:221365ms step_avg:100.62ms +step:2300/20000 train_loss:2.3185 train_time:231425ms step_avg:100.62ms +step:2400/20000 train_loss:2.1498 train_time:241423ms step_avg:100.59ms +step:2500/20000 train_loss:2.0830 train_time:251478ms step_avg:100.59ms +step:2500/20000 val_loss:2.1602 val_bpb:1.2794 train_time:251544ms step_avg:100.62ms +step:2600/20000 train_loss:2.3726 train_time:261480ms step_avg:100.57ms +step:2700/20000 train_loss:2.1021 train_time:271525ms step_avg:100.56ms +step:2800/20000 train_loss:2.1866 train_time:281527ms step_avg:100.55ms +step:2900/20000 train_loss:2.1290 train_time:291578ms step_avg:100.54ms +step:3000/20000 train_loss:2.1666 train_time:301576ms step_avg:100.53ms +step:3000/20000 val_loss:2.1349 val_bpb:1.2644 train_time:301640ms step_avg:100.55ms +step:3100/20000 train_loss:2.1398 train_time:311628ms step_avg:100.53ms +step:3200/20000 train_loss:2.1279 train_time:321633ms step_avg:100.51ms +step:3300/20000 train_loss:2.1744 train_time:331684ms step_avg:100.51ms +step:3400/20000 train_loss:2.0968 train_time:341670ms step_avg:100.49ms +step:3500/20000 train_loss:2.1864 train_time:351730ms step_avg:100.49ms +step:3500/20000 val_loss:2.1125 val_bpb:1.2512 train_time:351796ms step_avg:100.51ms +step:3600/20000 train_loss:2.0309 train_time:361734ms step_avg:100.48ms +step:3700/20000 train_loss:2.0582 train_time:371793ms step_avg:100.48ms +step:3800/20000 train_loss:2.1357 train_time:381793ms step_avg:100.47ms +step:3900/20000 train_loss:1.9048 train_time:391854ms step_avg:100.48ms +step:4000/20000 train_loss:2.0962 train_time:401854ms step_avg:100.46ms +step:4000/20000 val_loss:2.0892 val_bpb:1.2374 train_time:401920ms step_avg:100.48ms +step:4100/20000 train_loss:2.1065 train_time:411919ms step_avg:100.47ms +step:4200/20000 train_loss:2.0895 train_time:421980ms step_avg:100.47ms +step:4300/20000 train_loss:1.9314 train_time:431977ms step_avg:100.46ms +step:4400/20000 train_loss:2.0155 train_time:442039ms step_avg:100.46ms +step:4500/20000 train_loss:2.1698 train_time:452039ms step_avg:100.45ms +step:4500/20000 val_loss:2.0673 val_bpb:1.2244 train_time:452103ms step_avg:100.47ms +step:4600/20000 train_loss:1.8762 train_time:462101ms step_avg:100.46ms +step:4700/20000 train_loss:2.1701 train_time:472164ms step_avg:100.46ms +step:4800/20000 train_loss:2.1529 train_time:482230ms step_avg:100.46ms +step:4900/20000 train_loss:2.0674 train_time:492231ms step_avg:100.46ms +step:5000/20000 train_loss:1.9073 train_time:502291ms step_avg:100.46ms +step:5000/20000 val_loss:2.0427 val_bpb:1.2098 train_time:502357ms step_avg:100.47ms +step:5100/20000 train_loss:1.9074 train_time:512296ms step_avg:100.45ms +step:5200/20000 train_loss:2.0589 train_time:522348ms step_avg:100.45ms +step:5300/20000 train_loss:2.0842 train_time:532355ms step_avg:100.44ms +step:5400/20000 train_loss:2.0649 train_time:542596ms step_avg:100.48ms +step:5500/20000 train_loss:2.0165 train_time:552757ms step_avg:100.50ms +step:5500/20000 val_loss:2.0174 val_bpb:1.1948 train_time:552821ms step_avg:100.51ms +step:5600/20000 train_loss:2.0398 train_time:562967ms step_avg:100.53ms +step:5700/20000 train_loss:2.0403 train_time:573135ms step_avg:100.55ms +step:5800/20000 train_loss:1.9901 train_time:583355ms step_avg:100.58ms +step:5900/20000 train_loss:1.9590 train_time:593515ms step_avg:100.60ms +step:5963/20000 val_loss:1.9971 val_bpb:1.1828 train_time:600094ms step_avg:100.64ms +stopping_early: wallclock_cap train_time:600094ms step:5963/20000 +peak memory allocated: 15596 MiB reserved: 15762 MiB +swa:averaging 14 checkpoints +swa_eval val_loss:1.9962 val_bpb:1.1823 +Serialized model: 114835683 bytes +Code size: 68750 bytes +Total submission size: 114904433 bytes +Serialized model int8+zstd-22: 15749104 bytes (payload:30153220 raw_torch:30174423 payload_ratio:3.81x) +Total submission size int8+zlib: 15817854 bytes +final_int8_zlib_roundtrip val_loss:2.0181 val_bpb:1.1952 eval_time:3335ms +final_int8_zlib_roundtrip_exact val_loss:2.01811577 val_bpb:1.19524183 +ttt_sliding:start chunks=1893 chunk_tokens=32768 total_windows=969091 stride=64 +ttt_sliding:params unfrozen=23134306 frozen=6815776 + ttt_chunk [1/1893] bpb=1.212706 time=0.5s + ttt_chunk [11/1893] bpb=1.196021 time=3.0s + ttt_chunk [21/1893] bpb=1.181737 time=5.6s + ttt_chunk [31/1893] bpb=1.178941 time=8.2s + ttt_chunk [41/1893] bpb=1.165309 time=10.8s + ttt_chunk [51/1893] bpb=1.160794 time=13.4s + ttt_chunk [61/1893] bpb=1.167741 time=16.0s + ttt_chunk [71/1893] bpb=1.166066 time=18.6s + ttt_chunk [81/1893] bpb=1.165450 time=21.1s + ttt_chunk [91/1893] bpb=1.166613 time=23.7s + ttt_chunk [101/1893] bpb=1.170344 time=26.3s + ttt_chunk [111/1893] bpb=1.172887 time=28.9s + ttt_chunk [121/1893] bpb=1.166498 time=31.5s + ttt_chunk [131/1893] bpb=1.167002 time=34.1s + ttt_chunk [141/1893] bpb=1.172724 time=36.7s + ttt_chunk [151/1893] bpb=1.174535 time=39.2s + ttt_chunk [161/1893] bpb=1.174555 time=41.8s + ttt_chunk [171/1893] bpb=1.179340 time=44.4s + ttt_chunk [181/1893] bpb=1.181822 time=47.0s + ttt_chunk [191/1893] bpb=1.189162 time=49.6s + ttt_chunk [201/1893] bpb=1.188078 time=52.2s + ttt_chunk [211/1893] bpb=1.185973 time=54.8s + ttt_chunk [221/1893] bpb=1.187417 time=57.4s + ttt_chunk [231/1893] bpb=1.186004 time=60.0s + ttt_chunk [241/1893] bpb=1.186317 time=62.5s + ttt_chunk [251/1893] bpb=1.185774 time=65.1s + ttt_chunk [261/1893] bpb=1.182669 time=67.7s + ttt_chunk [271/1893] bpb=1.181457 time=70.3s + ttt_chunk [281/1893] bpb=1.182855 time=72.9s + ttt_chunk [291/1893] bpb=1.184757 time=75.5s + ttt_chunk [301/1893] bpb=1.185403 time=78.1s + ttt_chunk [311/1893] bpb=1.187480 time=80.6s + ttt_chunk [321/1893] bpb=1.189300 time=83.2s + ttt_chunk [331/1893] bpb=1.189171 time=85.8s + ttt_chunk [341/1893] bpb=1.188135 time=88.4s + ttt_chunk [351/1893] bpb=1.190501 time=90.9s + ttt_chunk [361/1893] bpb=1.190763 time=93.5s + ttt_chunk [371/1893] bpb=1.189911 time=96.1s + ttt_chunk [381/1893] bpb=1.190001 time=98.7s + ttt_chunk [391/1893] bpb=1.189737 time=101.3s + ttt_chunk [401/1893] bpb=1.187624 time=103.8s + ttt_chunk [411/1893] bpb=1.186535 time=106.4s + ttt_chunk [421/1893] bpb=1.185484 time=109.0s + ttt_chunk [431/1893] bpb=1.185330 time=111.6s + ttt_chunk [441/1893] bpb=1.185602 time=114.2s + ttt_chunk [451/1893] bpb=1.185851 time=116.8s + ttt_chunk [461/1893] bpb=1.184732 time=119.4s + ttt_chunk [471/1893] bpb=1.185253 time=121.9s + ttt_chunk [481/1893] bpb=1.184882 time=124.5s + ttt_chunk [491/1893] bpb=1.183769 time=127.1s + ttt_chunk [501/1893] bpb=1.183248 time=129.7s + ttt_chunk [511/1893] bpb=1.182588 time=132.3s + ttt_chunk [521/1893] bpb=1.180334 time=134.9s + ttt_chunk [531/1893] bpb=1.181396 time=137.5s + ttt_chunk [541/1893] bpb=1.181625 time=140.0s + ttt_chunk [551/1893] bpb=1.180504 time=142.6s + ttt_chunk [561/1893] bpb=1.181022 time=145.2s + ttt_chunk [571/1893] bpb=1.179891 time=147.9s + ttt_chunk [581/1893] bpb=1.178991 time=150.4s + ttt_chunk [591/1893] bpb=1.178239 time=153.1s + ttt_chunk [601/1893] bpb=1.178693 time=155.7s + ttt_chunk [611/1893] bpb=1.178501 time=158.2s + ttt_chunk [621/1893] bpb=1.178316 time=160.8s + ttt_chunk [631/1893] bpb=1.178980 time=163.4s + ttt_chunk [641/1893] bpb=1.178714 time=166.0s + ttt_chunk [651/1893] bpb=1.178757 time=168.5s + ttt_chunk [661/1893] bpb=1.178164 time=171.1s + ttt_chunk [671/1893] bpb=1.178506 time=173.7s + ttt_chunk [681/1893] bpb=1.179211 time=176.3s + ttt_chunk [691/1893] bpb=1.180168 time=178.9s + ttt_chunk [701/1893] bpb=1.179572 time=181.5s + ttt_chunk [711/1893] bpb=1.179598 time=184.1s + ttt_chunk [721/1893] bpb=1.179207 time=186.7s + ttt_chunk [731/1893] bpb=1.179262 time=189.2s + ttt_chunk [741/1893] bpb=1.179395 time=191.8s + ttt_chunk [751/1893] bpb=1.179207 time=194.4s + ttt_chunk [761/1893] bpb=1.179117 time=197.0s + ttt_chunk [771/1893] bpb=1.178777 time=199.6s + ttt_chunk [781/1893] bpb=1.179519 time=202.2s + ttt_chunk [791/1893] bpb=1.179120 time=204.7s + ttt_chunk [801/1893] bpb=1.179404 time=207.3s + ttt_chunk [811/1893] bpb=1.179220 time=209.9s + ttt_chunk [821/1893] bpb=1.179047 time=212.5s + ttt_chunk [831/1893] bpb=1.178877 time=215.1s + ttt_chunk [841/1893] bpb=1.178228 time=217.6s + ttt_chunk [851/1893] bpb=1.178017 time=220.2s + ttt_chunk [861/1893] bpb=1.177768 time=222.8s + ttt_chunk [871/1893] bpb=1.178024 time=225.3s + ttt_chunk [881/1893] bpb=1.178226 time=227.9s + ttt_chunk [891/1893] bpb=1.177789 time=230.5s + ttt_chunk [901/1893] bpb=1.177532 time=233.1s + ttt_chunk [911/1893] bpb=1.177694 time=235.6s + ttt_chunk [921/1893] bpb=1.178176 time=238.2s + ttt_chunk [931/1893] bpb=1.178134 time=240.8s + ttt_chunk [941/1893] bpb=1.177819 time=243.4s + ttt_chunk [951/1893] bpb=1.178234 time=245.9s + ttt_chunk [961/1893] bpb=1.178312 time=248.5s + ttt_chunk [971/1893] bpb=1.179205 time=251.1s + ttt_chunk [981/1893] bpb=1.179282 time=253.7s + ttt_chunk [991/1893] bpb=1.179237 time=256.3s + ttt_chunk [1001/1893] bpb=1.179212 time=258.8s + ttt_chunk [1011/1893] bpb=1.179016 time=261.4s + ttt_chunk [1021/1893] bpb=1.179331 time=264.0s + ttt_chunk [1031/1893] bpb=1.179787 time=266.6s + ttt_chunk [1041/1893] bpb=1.179404 time=269.2s + ttt_chunk [1051/1893] bpb=1.179145 time=271.7s + ttt_chunk [1061/1893] bpb=1.179197 time=274.3s + ttt_chunk [1071/1893] bpb=1.179811 time=276.9s + ttt_chunk [1081/1893] bpb=1.180088 time=279.5s + ttt_chunk [1091/1893] bpb=1.180750 time=282.1s + ttt_chunk [1101/1893] bpb=1.180716 time=284.6s + ttt_chunk [1111/1893] bpb=1.180560 time=287.2s + ttt_chunk [1121/1893] bpb=1.180356 time=289.8s + ttt_chunk [1131/1893] bpb=1.180192 time=292.4s + ttt_chunk [1141/1893] bpb=1.179882 time=295.0s + ttt_chunk [1151/1893] bpb=1.179868 time=297.5s + ttt_chunk [1161/1893] bpb=1.179459 time=300.1s + ttt_chunk [1171/1893] bpb=1.179733 time=302.7s + ttt_chunk [1181/1893] bpb=1.178963 time=305.3s + ttt_chunk [1191/1893] bpb=1.178818 time=307.9s + ttt_chunk [1201/1893] bpb=1.179185 time=310.4s + ttt_chunk [1211/1893] bpb=1.178696 time=313.0s + ttt_chunk [1221/1893] bpb=1.178379 time=315.6s + ttt_chunk [1231/1893] bpb=1.178025 time=318.2s + ttt_chunk [1241/1893] bpb=1.177669 time=320.8s + ttt_chunk [1251/1893] bpb=1.177061 time=323.4s + ttt_chunk [1261/1893] bpb=1.177025 time=326.0s + ttt_chunk [1271/1893] bpb=1.176646 time=328.6s + ttt_chunk [1281/1893] bpb=1.176455 time=331.1s + ttt_chunk [1291/1893] bpb=1.176233 time=333.7s + ttt_chunk [1301/1893] bpb=1.175636 time=336.3s + ttt_chunk [1311/1893] bpb=1.175199 time=338.9s + ttt_chunk [1321/1893] bpb=1.174848 time=341.5s + ttt_chunk [1331/1893] bpb=1.174741 time=344.0s + ttt_chunk [1341/1893] bpb=1.174585 time=346.6s + ttt_chunk [1351/1893] bpb=1.174510 time=349.2s + ttt_chunk [1361/1893] bpb=1.174548 time=351.8s + ttt_chunk [1371/1893] bpb=1.174420 time=354.3s + ttt_chunk [1381/1893] bpb=1.174393 time=356.9s + ttt_chunk [1391/1893] bpb=1.174003 time=359.5s + ttt_chunk [1401/1893] bpb=1.174000 time=362.1s + ttt_chunk [1411/1893] bpb=1.174115 time=364.7s + ttt_chunk [1421/1893] bpb=1.174373 time=367.3s + ttt_chunk [1431/1893] bpb=1.174092 time=369.8s + ttt_chunk [1441/1893] bpb=1.174602 time=372.4s + ttt_chunk [1451/1893] bpb=1.174936 time=375.0s + ttt_chunk [1461/1893] bpb=1.174480 time=377.6s + ttt_chunk [1471/1893] bpb=1.175512 time=380.2s + ttt_chunk [1481/1893] bpb=1.175056 time=382.7s + ttt_chunk [1491/1893] bpb=1.174881 time=385.3s + ttt_chunk [1501/1893] bpb=1.174839 time=387.9s + ttt_chunk [1511/1893] bpb=1.174881 time=390.5s + ttt_chunk [1521/1893] bpb=1.174896 time=393.0s + ttt_chunk [1531/1893] bpb=1.174406 time=395.6s + ttt_chunk [1541/1893] bpb=1.174272 time=398.2s + ttt_chunk [1551/1893] bpb=1.174622 time=400.8s + ttt_chunk [1561/1893] bpb=1.174650 time=403.4s + ttt_chunk [1571/1893] bpb=1.174484 time=406.0s + ttt_chunk [1581/1893] bpb=1.174589 time=408.6s + ttt_chunk [1591/1893] bpb=1.174450 time=411.1s + ttt_chunk [1601/1893] bpb=1.174621 time=413.7s + ttt_chunk [1611/1893] bpb=1.174526 time=416.3s + ttt_chunk [1621/1893] bpb=1.174107 time=418.8s + ttt_chunk [1631/1893] bpb=1.174429 time=421.4s + ttt_chunk [1641/1893] bpb=1.174448 time=424.0s + ttt_chunk [1651/1893] bpb=1.174373 time=426.6s + ttt_chunk [1661/1893] bpb=1.174246 time=429.1s + ttt_chunk [1671/1893] bpb=1.174731 time=431.7s + ttt_chunk [1681/1893] bpb=1.174852 time=434.3s + ttt_chunk [1691/1893] bpb=1.174657 time=436.8s + ttt_chunk [1701/1893] bpb=1.174801 time=439.4s + ttt_chunk [1711/1893] bpb=1.174794 time=442.0s + ttt_chunk [1721/1893] bpb=1.174777 time=444.6s + ttt_chunk [1731/1893] bpb=1.174646 time=447.1s + ttt_chunk [1741/1893] bpb=1.174458 time=449.7s + ttt_chunk [1751/1893] bpb=1.174270 time=452.3s + ttt_chunk [1761/1893] bpb=1.174429 time=454.9s + ttt_chunk [1771/1893] bpb=1.174318 time=457.5s + ttt_chunk [1781/1893] bpb=1.174358 time=460.1s + ttt_chunk [1791/1893] bpb=1.173908 time=462.6s + ttt_chunk [1801/1893] bpb=1.173781 time=465.2s + ttt_chunk [1811/1893] bpb=1.173670 time=467.8s + ttt_chunk [1821/1893] bpb=1.173718 time=470.3s + ttt_chunk [1831/1893] bpb=1.173092 time=472.9s + ttt_chunk [1841/1893] bpb=1.173133 time=475.5s + ttt_chunk [1851/1893] bpb=1.172933 time=478.1s + ttt_chunk [1861/1893] bpb=1.172548 time=480.6s + ttt_chunk [1871/1893] bpb=1.172519 time=483.2s + ttt_chunk [1881/1893] bpb=1.172048 time=485.8s + ttt_chunk [1891/1893] bpb=1.171805 time=488.4s + ttt_chunk [1893/1893] bpb=1.171849 time=488.7s +ttt_sliding:done val_loss=1.975159 val_bpb=1.169803 elapsed=488.8s +final_ttt_sliding val_loss:1.9752 val_bpb:1.1698 eval_time:489407ms +========== SEED 1337 DONE ========== +========== SEED 42 ========== +W0327 02:11:31.579000 55736 torch/distributed/run.py:803] +W0327 02:11:31.579000 55736 torch/distributed/run.py:803] ***************************************** +W0327 02:11:31.579000 55736 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0327 02:11:31.579000 55736 torch/distributed/run.py:803] ***************************************** +logs/7L_seed42.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +qat:enabled from step 0 attn=6bit +architecture:recursive num_blocks:4 num_loops:7 shared_block_params:27263104 per_loop_params:28672 +model_params:29950082 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:32 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:600.000 +seed:42 +warmup_step:10/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:6.9734 val_bpb:4.1300 train_time:0ms step_avg:0.02ms +step:1/20000 train_loss:6.9756 train_time:147ms step_avg:146.99ms +step:2/20000 train_loss:9.8732 train_time:168ms step_avg:83.93ms +step:3/20000 train_loss:8.6232 train_time:267ms step_avg:88.92ms +step:4/20000 train_loss:7.5045 train_time:367ms step_avg:91.71ms +step:5/20000 train_loss:6.7892 train_time:468ms step_avg:93.52ms +step:6/20000 train_loss:7.5672 train_time:568ms step_avg:94.69ms +step:7/20000 train_loss:6.2335 train_time:670ms step_avg:95.70ms +step:8/20000 train_loss:6.1498 train_time:770ms step_avg:96.28ms +step:9/20000 train_loss:5.9877 train_time:873ms step_avg:96.97ms +step:10/20000 train_loss:5.7212 train_time:972ms step_avg:97.23ms +step:100/20000 train_loss:3.3660 train_time:9982ms step_avg:99.82ms +step:200/20000 train_loss:2.8323 train_time:20091ms step_avg:100.45ms +step:300/20000 train_loss:2.4117 train_time:30172ms step_avg:100.57ms +step:400/20000 train_loss:2.2972 train_time:40299ms step_avg:100.75ms +step:500/20000 train_loss:2.4522 train_time:50371ms step_avg:100.74ms +step:500/20000 val_loss:2.4492 val_bpb:1.4506 train_time:50436ms step_avg:100.87ms +step:600/20000 train_loss:2.5082 train_time:60507ms step_avg:100.84ms +step:700/20000 train_loss:2.3928 train_time:70548ms step_avg:100.78ms +step:800/20000 train_loss:2.2297 train_time:80641ms step_avg:100.80ms +step:900/20000 train_loss:2.2886 train_time:90658ms step_avg:100.73ms +step:1000/20000 train_loss:2.3286 train_time:100719ms step_avg:100.72ms +step:1000/20000 val_loss:2.2780 val_bpb:1.3492 train_time:100783ms step_avg:100.78ms +step:1100/20000 train_loss:2.2017 train_time:110727ms step_avg:100.66ms +step:1200/20000 train_loss:2.3417 train_time:120788ms step_avg:100.66ms +step:1300/20000 train_loss:2.3141 train_time:130787ms step_avg:100.61ms +step:1400/20000 train_loss:2.3702 train_time:140847ms step_avg:100.60ms +step:1500/20000 train_loss:2.1683 train_time:150846ms step_avg:100.56ms +step:1500/20000 val_loss:2.2129 val_bpb:1.3106 train_time:150911ms step_avg:100.61ms +step:1600/20000 train_loss:2.0312 train_time:160913ms step_avg:100.57ms +step:1700/20000 train_loss:2.1148 train_time:170913ms step_avg:100.54ms +step:1800/20000 train_loss:2.1531 train_time:180975ms step_avg:100.54ms +step:1900/20000 train_loss:2.1417 train_time:190972ms step_avg:100.51ms +step:2000/20000 train_loss:2.1945 train_time:201022ms step_avg:100.51ms +step:2000/20000 val_loss:2.1801 val_bpb:1.2912 train_time:201086ms step_avg:100.54ms +step:2100/20000 train_loss:2.2157 train_time:211071ms step_avg:100.51ms +step:2200/20000 train_loss:2.0174 train_time:221066ms step_avg:100.48ms +step:2300/20000 train_loss:2.3212 train_time:231119ms step_avg:100.49ms +step:2400/20000 train_loss:2.1503 train_time:241114ms step_avg:100.46ms +step:2500/20000 train_loss:2.0844 train_time:251169ms step_avg:100.47ms +step:2500/20000 val_loss:2.1588 val_bpb:1.2786 train_time:251234ms step_avg:100.49ms +step:2600/20000 train_loss:2.3661 train_time:261166ms step_avg:100.45ms +step:2700/20000 train_loss:2.0986 train_time:271225ms step_avg:100.45ms +step:2800/20000 train_loss:2.1867 train_time:281224ms step_avg:100.44ms +step:2900/20000 train_loss:2.1299 train_time:291286ms step_avg:100.44ms +step:3000/20000 train_loss:2.1677 train_time:301287ms step_avg:100.43ms +step:3000/20000 val_loss:2.1340 val_bpb:1.2639 train_time:301351ms step_avg:100.45ms +step:3100/20000 train_loss:2.1383 train_time:311338ms step_avg:100.43ms +step:3200/20000 train_loss:2.1286 train_time:321339ms step_avg:100.42ms +step:3300/20000 train_loss:2.1734 train_time:331398ms step_avg:100.42ms +step:3400/20000 train_loss:2.0966 train_time:341398ms step_avg:100.41ms +step:3500/20000 train_loss:2.1860 train_time:351440ms step_avg:100.41ms +step:3500/20000 val_loss:2.1119 val_bpb:1.2508 train_time:351504ms step_avg:100.43ms +step:3600/20000 train_loss:2.0307 train_time:361429ms step_avg:100.40ms +step:3700/20000 train_loss:2.0601 train_time:371477ms step_avg:100.40ms +step:3800/20000 train_loss:2.1352 train_time:381480ms step_avg:100.39ms +step:3900/20000 train_loss:1.9033 train_time:391528ms step_avg:100.39ms +step:4000/20000 train_loss:2.0979 train_time:401529ms step_avg:100.38ms +step:4000/20000 val_loss:2.0886 val_bpb:1.2370 train_time:401594ms step_avg:100.40ms +step:4100/20000 train_loss:2.1036 train_time:411594ms step_avg:100.39ms +step:4200/20000 train_loss:2.0867 train_time:421731ms step_avg:100.41ms +step:4300/20000 train_loss:1.9284 train_time:431725ms step_avg:100.40ms +step:4400/20000 train_loss:2.0125 train_time:441775ms step_avg:100.40ms +step:4500/20000 train_loss:2.1712 train_time:451775ms step_avg:100.39ms +step:4500/20000 val_loss:2.0666 val_bpb:1.2240 train_time:451839ms step_avg:100.41ms +step:4600/20000 train_loss:1.8753 train_time:461823ms step_avg:100.40ms +step:4700/20000 train_loss:2.1690 train_time:471823ms step_avg:100.39ms +step:4800/20000 train_loss:2.1555 train_time:481872ms step_avg:100.39ms +step:4900/20000 train_loss:2.0658 train_time:491864ms step_avg:100.38ms +step:5000/20000 train_loss:1.9086 train_time:501915ms step_avg:100.38ms +step:5000/20000 val_loss:2.0421 val_bpb:1.2095 train_time:501979ms step_avg:100.40ms +step:5100/20000 train_loss:1.9077 train_time:511915ms step_avg:100.38ms +step:5200/20000 train_loss:2.0582 train_time:521965ms step_avg:100.38ms +step:5300/20000 train_loss:2.0828 train_time:531966ms step_avg:100.37ms +step:5400/20000 train_loss:2.0577 train_time:542196ms step_avg:100.41ms +step:5500/20000 train_loss:2.0167 train_time:552355ms step_avg:100.43ms +step:5500/20000 val_loss:2.0172 val_bpb:1.1947 train_time:552420ms step_avg:100.44ms +step:5600/20000 train_loss:2.0435 train_time:562565ms step_avg:100.46ms +step:5700/20000 train_loss:2.0372 train_time:572725ms step_avg:100.48ms +step:5800/20000 train_loss:1.9935 train_time:582935ms step_avg:100.51ms +step:5900/20000 train_loss:1.9573 train_time:593104ms step_avg:100.53ms +step:5967/20000 val_loss:1.9969 val_bpb:1.1827 train_time:600089ms step_avg:100.57ms +stopping_early: wallclock_cap train_time:600089ms step:5967/20000 +peak memory allocated: 15596 MiB reserved: 15762 MiB +swa:averaging 14 checkpoints +swa_eval val_loss:1.9959 val_bpb:1.1821 +Serialized model: 114835683 bytes +Code size: 68750 bytes +Total submission size: 114904433 bytes +Serialized model int8+zstd-22: 15778257 bytes (payload:30153220 raw_torch:30174423 payload_ratio:3.81x) +Total submission size int8+zlib: 15847007 bytes +final_int8_zlib_roundtrip val_loss:2.0175 val_bpb:1.1949 eval_time:3327ms +final_int8_zlib_roundtrip_exact val_loss:2.01746112 val_bpb:1.19485411 +ttt_sliding:start chunks=1893 chunk_tokens=32768 total_windows=969091 stride=64 +ttt_sliding:params unfrozen=23134306 frozen=6815776 + ttt_chunk [1/1893] bpb=1.206599 time=0.5s + ttt_chunk [11/1893] bpb=1.196791 time=3.0s + ttt_chunk [21/1893] bpb=1.182070 time=5.6s + ttt_chunk [31/1893] bpb=1.178727 time=8.2s + ttt_chunk [41/1893] bpb=1.165377 time=10.8s + ttt_chunk [51/1893] bpb=1.161278 time=13.4s + ttt_chunk [61/1893] bpb=1.168611 time=16.0s + ttt_chunk [71/1893] bpb=1.166771 time=18.5s + ttt_chunk [81/1893] bpb=1.165966 time=21.1s + ttt_chunk [91/1893] bpb=1.167193 time=23.7s + ttt_chunk [101/1893] bpb=1.170747 time=26.3s + ttt_chunk [111/1893] bpb=1.173328 time=28.9s + ttt_chunk [121/1893] bpb=1.166789 time=31.5s + ttt_chunk [131/1893] bpb=1.167289 time=34.1s + ttt_chunk [141/1893] bpb=1.172934 time=36.7s + ttt_chunk [151/1893] bpb=1.174753 time=39.3s + ttt_chunk [161/1893] bpb=1.174574 time=41.9s + ttt_chunk [171/1893] bpb=1.179461 time=44.5s + ttt_chunk [181/1893] bpb=1.181838 time=47.0s + ttt_chunk [191/1893] bpb=1.189184 time=49.6s + ttt_chunk [201/1893] bpb=1.188078 time=52.2s + ttt_chunk [211/1893] bpb=1.185989 time=54.8s + ttt_chunk [221/1893] bpb=1.187539 time=57.4s + ttt_chunk [231/1893] bpb=1.186162 time=60.0s + ttt_chunk [241/1893] bpb=1.186455 time=62.5s + ttt_chunk [251/1893] bpb=1.185893 time=65.1s + ttt_chunk [261/1893] bpb=1.182925 time=67.7s + ttt_chunk [271/1893] bpb=1.181691 time=70.3s + ttt_chunk [281/1893] bpb=1.183091 time=72.9s + ttt_chunk [291/1893] bpb=1.184913 time=75.4s + ttt_chunk [301/1893] bpb=1.185692 time=78.0s + ttt_chunk [311/1893] bpb=1.187762 time=80.6s + ttt_chunk [321/1893] bpb=1.189616 time=83.2s + ttt_chunk [331/1893] bpb=1.189505 time=85.8s + ttt_chunk [341/1893] bpb=1.188414 time=88.4s + ttt_chunk [351/1893] bpb=1.190804 time=90.9s + ttt_chunk [361/1893] bpb=1.191004 time=93.5s + ttt_chunk [371/1893] bpb=1.190145 time=96.1s + ttt_chunk [381/1893] bpb=1.190252 time=98.7s + ttt_chunk [391/1893] bpb=1.189991 time=101.3s + ttt_chunk [401/1893] bpb=1.187816 time=103.9s + ttt_chunk [411/1893] bpb=1.186642 time=106.5s + ttt_chunk [421/1893] bpb=1.185632 time=109.0s + ttt_chunk [431/1893] bpb=1.185485 time=111.6s + ttt_chunk [441/1893] bpb=1.185728 time=114.2s + ttt_chunk [451/1893] bpb=1.185950 time=116.8s + ttt_chunk [461/1893] bpb=1.184818 time=119.4s + ttt_chunk [471/1893] bpb=1.185320 time=121.9s + ttt_chunk [481/1893] bpb=1.184943 time=124.5s + ttt_chunk [491/1893] bpb=1.183808 time=127.1s + ttt_chunk [501/1893] bpb=1.183288 time=129.7s + ttt_chunk [511/1893] bpb=1.182648 time=132.3s + ttt_chunk [521/1893] bpb=1.180356 time=134.9s + ttt_chunk [531/1893] bpb=1.181456 time=137.4s + ttt_chunk [541/1893] bpb=1.181675 time=140.0s + ttt_chunk [551/1893] bpb=1.180527 time=142.6s + ttt_chunk [561/1893] bpb=1.180971 time=145.2s + ttt_chunk [571/1893] bpb=1.179915 time=147.8s + ttt_chunk [581/1893] bpb=1.179004 time=150.4s + ttt_chunk [591/1893] bpb=1.178285 time=153.0s + ttt_chunk [601/1893] bpb=1.178720 time=155.6s + ttt_chunk [611/1893] bpb=1.178583 time=158.1s + ttt_chunk [621/1893] bpb=1.178406 time=160.7s + ttt_chunk [631/1893] bpb=1.179082 time=163.3s + ttt_chunk [641/1893] bpb=1.178773 time=165.9s + ttt_chunk [651/1893] bpb=1.178809 time=168.4s + ttt_chunk [661/1893] bpb=1.178210 time=171.0s + ttt_chunk [671/1893] bpb=1.178525 time=173.6s + ttt_chunk [681/1893] bpb=1.179221 time=176.2s + ttt_chunk [691/1893] bpb=1.180184 time=178.8s + ttt_chunk [701/1893] bpb=1.179602 time=181.4s + ttt_chunk [711/1893] bpb=1.179629 time=184.0s + ttt_chunk [721/1893] bpb=1.179271 time=186.5s + ttt_chunk [731/1893] bpb=1.179340 time=189.1s + ttt_chunk [741/1893] bpb=1.179431 time=191.7s + ttt_chunk [751/1893] bpb=1.179262 time=194.3s + ttt_chunk [761/1893] bpb=1.179224 time=196.9s + ttt_chunk [771/1893] bpb=1.178871 time=199.5s + ttt_chunk [781/1893] bpb=1.179617 time=202.0s + ttt_chunk [791/1893] bpb=1.179212 time=204.6s + ttt_chunk [801/1893] bpb=1.179512 time=207.2s + ttt_chunk [811/1893] bpb=1.179353 time=209.8s + ttt_chunk [821/1893] bpb=1.179163 time=212.4s + ttt_chunk [831/1893] bpb=1.179026 time=215.0s + ttt_chunk [841/1893] bpb=1.178339 time=217.6s + ttt_chunk [851/1893] bpb=1.178136 time=220.2s + ttt_chunk [861/1893] bpb=1.177888 time=222.8s + ttt_chunk [871/1893] bpb=1.178180 time=225.3s + ttt_chunk [881/1893] bpb=1.178419 time=227.9s + ttt_chunk [891/1893] bpb=1.177988 time=230.5s + ttt_chunk [901/1893] bpb=1.177735 time=233.1s + ttt_chunk [911/1893] bpb=1.177892 time=235.7s + ttt_chunk [921/1893] bpb=1.178368 time=238.2s + ttt_chunk [931/1893] bpb=1.178296 time=240.8s + ttt_chunk [941/1893] bpb=1.177953 time=243.4s + ttt_chunk [951/1893] bpb=1.178356 time=246.0s + ttt_chunk [961/1893] bpb=1.178421 time=248.6s + ttt_chunk [971/1893] bpb=1.179292 time=251.1s + ttt_chunk [981/1893] bpb=1.179343 time=253.7s + ttt_chunk [991/1893] bpb=1.179340 time=256.3s + ttt_chunk [1001/1893] bpb=1.179301 time=258.9s + ttt_chunk [1011/1893] bpb=1.179083 time=261.5s + ttt_chunk [1021/1893] bpb=1.179402 time=264.0s + ttt_chunk [1031/1893] bpb=1.179865 time=266.6s + ttt_chunk [1041/1893] bpb=1.179475 time=269.2s + ttt_chunk [1051/1893] bpb=1.179197 time=271.8s + ttt_chunk [1061/1893] bpb=1.179257 time=274.4s + ttt_chunk [1071/1893] bpb=1.179885 time=277.0s + ttt_chunk [1081/1893] bpb=1.180153 time=279.5s + ttt_chunk [1091/1893] bpb=1.180830 time=282.1s + ttt_chunk [1101/1893] bpb=1.180803 time=284.7s + ttt_chunk [1111/1893] bpb=1.180629 time=287.3s + ttt_chunk [1121/1893] bpb=1.180413 time=289.9s + ttt_chunk [1131/1893] bpb=1.180256 time=292.5s + ttt_chunk [1141/1893] bpb=1.179937 time=295.0s + ttt_chunk [1151/1893] bpb=1.179909 time=297.6s + ttt_chunk [1161/1893] bpb=1.179514 time=300.2s + ttt_chunk [1171/1893] bpb=1.179784 time=302.8s + ttt_chunk [1181/1893] bpb=1.179009 time=305.4s + ttt_chunk [1191/1893] bpb=1.178870 time=307.9s + ttt_chunk [1201/1893] bpb=1.179240 time=310.5s + ttt_chunk [1211/1893] bpb=1.178728 time=313.1s + ttt_chunk [1221/1893] bpb=1.178410 time=315.7s + ttt_chunk [1231/1893] bpb=1.178093 time=318.3s + ttt_chunk [1241/1893] bpb=1.177716 time=320.9s + ttt_chunk [1251/1893] bpb=1.177115 time=323.5s + ttt_chunk [1261/1893] bpb=1.177060 time=326.1s + ttt_chunk [1271/1893] bpb=1.176695 time=328.7s + ttt_chunk [1281/1893] bpb=1.176513 time=331.2s + ttt_chunk [1291/1893] bpb=1.176289 time=333.8s + ttt_chunk [1301/1893] bpb=1.175664 time=336.4s + ttt_chunk [1311/1893] bpb=1.175254 time=339.0s + ttt_chunk [1321/1893] bpb=1.174887 time=341.6s + ttt_chunk [1331/1893] bpb=1.174799 time=344.2s + ttt_chunk [1341/1893] bpb=1.174649 time=346.8s + ttt_chunk [1351/1893] bpb=1.174589 time=349.3s + ttt_chunk [1361/1893] bpb=1.174637 time=351.9s + ttt_chunk [1371/1893] bpb=1.174519 time=354.5s + ttt_chunk [1381/1893] bpb=1.174521 time=357.2s + ttt_chunk [1391/1893] bpb=1.174109 time=359.7s + ttt_chunk [1401/1893] bpb=1.174091 time=362.3s + ttt_chunk [1411/1893] bpb=1.174208 time=364.9s + ttt_chunk [1421/1893] bpb=1.174485 time=367.4s + ttt_chunk [1431/1893] bpb=1.174226 time=370.0s + ttt_chunk [1441/1893] bpb=1.174745 time=372.6s + ttt_chunk [1451/1893] bpb=1.175086 time=375.1s + ttt_chunk [1461/1893] bpb=1.174653 time=377.7s + ttt_chunk [1471/1893] bpb=1.175687 time=380.3s + ttt_chunk [1481/1893] bpb=1.175218 time=382.9s + ttt_chunk [1491/1893] bpb=1.175055 time=385.5s + ttt_chunk [1501/1893] bpb=1.175014 time=388.0s + ttt_chunk [1511/1893] bpb=1.175035 time=390.6s + ttt_chunk [1521/1893] bpb=1.175036 time=393.2s + ttt_chunk [1531/1893] bpb=1.174539 time=395.8s + ttt_chunk [1541/1893] bpb=1.174393 time=398.3s + ttt_chunk [1551/1893] bpb=1.174728 time=400.9s + ttt_chunk [1561/1893] bpb=1.174762 time=403.5s + ttt_chunk [1571/1893] bpb=1.174616 time=406.1s + ttt_chunk [1581/1893] bpb=1.174736 time=408.6s + ttt_chunk [1591/1893] bpb=1.174590 time=411.2s + ttt_chunk [1601/1893] bpb=1.174746 time=413.8s + ttt_chunk [1611/1893] bpb=1.174651 time=416.4s + ttt_chunk [1621/1893] bpb=1.174229 time=418.9s + ttt_chunk [1631/1893] bpb=1.174547 time=421.5s + ttt_chunk [1641/1893] bpb=1.174568 time=424.1s + ttt_chunk [1651/1893] bpb=1.174508 time=426.6s + ttt_chunk [1661/1893] bpb=1.174395 time=429.2s + ttt_chunk [1671/1893] bpb=1.174868 time=431.8s + ttt_chunk [1681/1893] bpb=1.174993 time=434.3s + ttt_chunk [1691/1893] bpb=1.174800 time=436.9s + ttt_chunk [1701/1893] bpb=1.174950 time=439.5s + ttt_chunk [1711/1893] bpb=1.174935 time=442.0s + ttt_chunk [1721/1893] bpb=1.174912 time=444.6s + ttt_chunk [1731/1893] bpb=1.174778 time=447.2s + ttt_chunk [1741/1893] bpb=1.174589 time=449.8s + ttt_chunk [1751/1893] bpb=1.174407 time=452.3s + ttt_chunk [1761/1893] bpb=1.174553 time=454.9s + ttt_chunk [1771/1893] bpb=1.174475 time=457.5s + ttt_chunk [1781/1893] bpb=1.174521 time=460.1s + ttt_chunk [1791/1893] bpb=1.174090 time=462.6s + ttt_chunk [1801/1893] bpb=1.173955 time=465.2s + ttt_chunk [1811/1893] bpb=1.173855 time=467.8s + ttt_chunk [1821/1893] bpb=1.173906 time=470.4s + ttt_chunk [1831/1893] bpb=1.173281 time=473.0s + ttt_chunk [1841/1893] bpb=1.173312 time=475.5s + ttt_chunk [1851/1893] bpb=1.173097 time=478.1s + ttt_chunk [1861/1893] bpb=1.172712 time=480.7s + ttt_chunk [1871/1893] bpb=1.172682 time=483.3s + ttt_chunk [1881/1893] bpb=1.172208 time=485.9s + ttt_chunk [1891/1893] bpb=1.171965 time=488.5s + ttt_chunk [1893/1893] bpb=1.172013 time=488.8s +ttt_sliding:done val_loss=1.974980 val_bpb=1.169697 elapsed=488.9s +final_ttt_sliding val_loss:1.9750 val_bpb:1.1697 eval_time:489501ms +========== SEED 42 DONE ========== +========== SEED 2024 ========== +W0327 02:32:22.780000 57606 torch/distributed/run.py:803] +W0327 02:32:22.780000 57606 torch/distributed/run.py:803] ***************************************** +W0327 02:32:22.780000 57606 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0327 02:32:22.780000 57606 torch/distributed/run.py:803] ***************************************** +logs/7L_seed2024.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +qat:enabled from step 0 attn=6bit +architecture:recursive num_blocks:4 num_loops:7 shared_block_params:27263104 per_loop_params:28672 +model_params:29950082 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:32 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:600.000 +seed:2024 +warmup_step:10/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:6.9785 val_bpb:4.1331 train_time:0ms step_avg:0.02ms +step:1/20000 train_loss:6.9793 train_time:148ms step_avg:148.27ms +step:2/20000 train_loss:9.8874 train_time:179ms step_avg:89.27ms +step:3/20000 train_loss:8.6647 train_time:268ms step_avg:89.20ms +step:4/20000 train_loss:7.5235 train_time:368ms step_avg:91.93ms +step:5/20000 train_loss:6.8025 train_time:469ms step_avg:93.83ms +step:6/20000 train_loss:7.5605 train_time:570ms step_avg:95.05ms +step:7/20000 train_loss:6.2233 train_time:671ms step_avg:95.91ms +step:8/20000 train_loss:6.1422 train_time:772ms step_avg:96.52ms +step:9/20000 train_loss:5.9612 train_time:873ms step_avg:96.96ms +step:10/20000 train_loss:5.6963 train_time:976ms step_avg:97.57ms +step:100/20000 train_loss:3.3951 train_time:9998ms step_avg:99.98ms +step:200/20000 train_loss:2.8209 train_time:20136ms step_avg:100.68ms +step:300/20000 train_loss:2.4129 train_time:30220ms step_avg:100.73ms +step:400/20000 train_loss:2.2943 train_time:40373ms step_avg:100.93ms +step:500/20000 train_loss:2.4544 train_time:50459ms step_avg:100.92ms +step:500/20000 val_loss:2.4531 val_bpb:1.4528 train_time:50525ms step_avg:101.05ms +step:600/20000 train_loss:2.5131 train_time:60588ms step_avg:100.98ms +step:700/20000 train_loss:2.3981 train_time:70663ms step_avg:100.95ms +step:800/20000 train_loss:2.2338 train_time:80768ms step_avg:100.96ms +step:900/20000 train_loss:2.2907 train_time:90753ms step_avg:100.84ms +step:1000/20000 train_loss:2.3290 train_time:100840ms step_avg:100.84ms +step:1000/20000 val_loss:2.2803 val_bpb:1.3505 train_time:100923ms step_avg:100.92ms +step:1100/20000 train_loss:2.1973 train_time:110853ms step_avg:100.78ms +step:1200/20000 train_loss:2.3445 train_time:120911ms step_avg:100.76ms +step:1300/20000 train_loss:2.3144 train_time:130919ms step_avg:100.71ms +step:1400/20000 train_loss:2.3635 train_time:140977ms step_avg:100.70ms +step:1500/20000 train_loss:2.1728 train_time:150978ms step_avg:100.65ms +step:1500/20000 val_loss:2.2128 val_bpb:1.3106 train_time:151059ms step_avg:100.71ms +step:1600/20000 train_loss:2.0344 train_time:161053ms step_avg:100.66ms +step:1700/20000 train_loss:2.1108 train_time:171052ms step_avg:100.62ms +step:1800/20000 train_loss:2.1535 train_time:181114ms step_avg:100.62ms +step:1900/20000 train_loss:2.1433 train_time:191094ms step_avg:100.58ms +step:2000/20000 train_loss:2.2010 train_time:201176ms step_avg:100.59ms +step:2000/20000 val_loss:2.1809 val_bpb:1.2917 train_time:201239ms step_avg:100.62ms +step:2100/20000 train_loss:2.2143 train_time:211217ms step_avg:100.58ms +step:2200/20000 train_loss:2.0200 train_time:221216ms step_avg:100.55ms +step:2300/20000 train_loss:2.3191 train_time:231279ms step_avg:100.56ms +step:2400/20000 train_loss:2.1492 train_time:241275ms step_avg:100.53ms +step:2500/20000 train_loss:2.0812 train_time:251326ms step_avg:100.53ms +step:2500/20000 val_loss:2.1594 val_bpb:1.2789 train_time:251409ms step_avg:100.56ms +step:2600/20000 train_loss:2.3706 train_time:261339ms step_avg:100.52ms +step:2700/20000 train_loss:2.0979 train_time:271401ms step_avg:100.52ms +step:2800/20000 train_loss:2.1856 train_time:281401ms step_avg:100.50ms +step:2900/20000 train_loss:2.1288 train_time:291450ms step_avg:100.50ms +step:3000/20000 train_loss:2.1681 train_time:301433ms step_avg:100.48ms +step:3000/20000 val_loss:2.1331 val_bpb:1.2634 train_time:301515ms step_avg:100.51ms +step:3100/20000 train_loss:2.1439 train_time:311478ms step_avg:100.48ms +step:3200/20000 train_loss:2.1281 train_time:321477ms step_avg:100.46ms +step:3300/20000 train_loss:2.1709 train_time:331534ms step_avg:100.46ms +step:3400/20000 train_loss:2.0943 train_time:341527ms step_avg:100.45ms +step:3500/20000 train_loss:2.1851 train_time:351603ms step_avg:100.46ms +step:3500/20000 val_loss:2.1113 val_bpb:1.2505 train_time:351670ms step_avg:100.48ms +step:3600/20000 train_loss:2.0357 train_time:361594ms step_avg:100.44ms +step:3700/20000 train_loss:2.0587 train_time:371676ms step_avg:100.45ms +step:3800/20000 train_loss:2.1352 train_time:381726ms step_avg:100.45ms +step:3900/20000 train_loss:1.9016 train_time:391784ms step_avg:100.46ms +step:4000/20000 train_loss:2.0953 train_time:401783ms step_avg:100.45ms +step:4000/20000 val_loss:2.0880 val_bpb:1.2366 train_time:401848ms step_avg:100.46ms +step:4100/20000 train_loss:2.1067 train_time:411814ms step_avg:100.44ms +step:4200/20000 train_loss:2.0885 train_time:421871ms step_avg:100.45ms +step:4300/20000 train_loss:1.9343 train_time:431874ms step_avg:100.44ms +step:4400/20000 train_loss:2.0164 train_time:441925ms step_avg:100.44ms +step:4500/20000 train_loss:2.1688 train_time:451923ms step_avg:100.43ms +step:4500/20000 val_loss:2.0663 val_bpb:1.2238 train_time:452006ms step_avg:100.45ms +step:4600/20000 train_loss:1.8755 train_time:461995ms step_avg:100.43ms +step:4700/20000 train_loss:2.1656 train_time:471989ms step_avg:100.42ms +step:4800/20000 train_loss:2.1523 train_time:482051ms step_avg:100.43ms +step:4900/20000 train_loss:2.0647 train_time:492050ms step_avg:100.42ms +step:5000/20000 train_loss:1.9043 train_time:502100ms step_avg:100.42ms +step:5000/20000 val_loss:2.0416 val_bpb:1.2091 train_time:502164ms step_avg:100.43ms +step:5100/20000 train_loss:1.9046 train_time:512103ms step_avg:100.41ms +step:5200/20000 train_loss:2.0570 train_time:522147ms step_avg:100.41ms +step:5300/20000 train_loss:2.0851 train_time:532148ms step_avg:100.41ms +step:5400/20000 train_loss:2.0569 train_time:542386ms step_avg:100.44ms +step:5500/20000 train_loss:2.0148 train_time:552546ms step_avg:100.46ms +step:5500/20000 val_loss:2.0164 val_bpb:1.1942 train_time:552612ms step_avg:100.47ms +step:5600/20000 train_loss:2.0422 train_time:562763ms step_avg:100.49ms +step:5700/20000 train_loss:2.0377 train_time:572924ms step_avg:100.51ms +step:5800/20000 train_loss:1.9919 train_time:583143ms step_avg:100.54ms +step:5900/20000 train_loss:1.9565 train_time:593304ms step_avg:100.56ms +step:5965/20000 val_loss:1.9961 val_bpb:1.1822 train_time:600089ms step_avg:100.60ms +stopping_early: wallclock_cap train_time:600089ms step:5965/20000 +peak memory allocated: 15596 MiB reserved: 15762 MiB +swa:averaging 14 checkpoints +swa_eval val_loss:1.9951 val_bpb:1.1816 +Serialized model: 114835683 bytes +Code size: 68750 bytes +Total submission size: 114904433 bytes +Serialized model int8+zstd-22: 15750116 bytes (payload:30153220 raw_torch:30174423 payload_ratio:3.81x) +Total submission size int8+zlib: 15818866 bytes +final_int8_zlib_roundtrip val_loss:2.0171 val_bpb:1.1947 eval_time:3333ms +final_int8_zlib_roundtrip_exact val_loss:2.01714021 val_bpb:1.19466405 +ttt_sliding:start chunks=1893 chunk_tokens=32768 total_windows=969091 stride=64 +ttt_sliding:params unfrozen=23134306 frozen=6815776 + ttt_chunk [1/1893] bpb=1.215084 time=0.5s + ttt_chunk [11/1893] bpb=1.195853 time=3.1s + ttt_chunk [21/1893] bpb=1.182073 time=5.6s + ttt_chunk [31/1893] bpb=1.178912 time=8.2s + ttt_chunk [41/1893] bpb=1.164787 time=10.8s + ttt_chunk [51/1893] bpb=1.159992 time=13.4s + ttt_chunk [61/1893] bpb=1.167405 time=16.0s + ttt_chunk [71/1893] bpb=1.166005 time=18.6s + ttt_chunk [81/1893] bpb=1.165258 time=21.2s + ttt_chunk [91/1893] bpb=1.166428 time=23.8s + ttt_chunk [101/1893] bpb=1.170262 time=26.4s + ttt_chunk [111/1893] bpb=1.172749 time=29.0s + ttt_chunk [121/1893] bpb=1.166244 time=31.5s + ttt_chunk [131/1893] bpb=1.166704 time=34.1s + ttt_chunk [141/1893] bpb=1.172307 time=36.7s + ttt_chunk [151/1893] bpb=1.174193 time=39.3s + ttt_chunk [161/1893] bpb=1.174072 time=41.9s + ttt_chunk [171/1893] bpb=1.178755 time=44.5s + ttt_chunk [181/1893] bpb=1.181156 time=47.1s + ttt_chunk [191/1893] bpb=1.188564 time=49.7s + ttt_chunk [201/1893] bpb=1.187434 time=52.3s + ttt_chunk [211/1893] bpb=1.185254 time=54.9s + ttt_chunk [221/1893] bpb=1.186675 time=57.4s + ttt_chunk [231/1893] bpb=1.185309 time=60.1s + ttt_chunk [241/1893] bpb=1.185619 time=62.6s + ttt_chunk [251/1893] bpb=1.185048 time=65.3s + ttt_chunk [261/1893] bpb=1.181969 time=67.8s + ttt_chunk [271/1893] bpb=1.180755 time=70.4s + ttt_chunk [281/1893] bpb=1.182017 time=73.0s + ttt_chunk [291/1893] bpb=1.183971 time=75.6s + ttt_chunk [301/1893] bpb=1.184613 time=78.2s + ttt_chunk [311/1893] bpb=1.186643 time=80.8s + ttt_chunk [321/1893] bpb=1.188488 time=83.4s + ttt_chunk [331/1893] bpb=1.188356 time=86.0s + ttt_chunk [341/1893] bpb=1.187305 time=88.6s + ttt_chunk [351/1893] bpb=1.189637 time=91.2s + ttt_chunk [361/1893] bpb=1.189854 time=93.8s + ttt_chunk [371/1893] bpb=1.189032 time=96.4s + ttt_chunk [381/1893] bpb=1.189156 time=99.0s + ttt_chunk [391/1893] bpb=1.188844 time=101.6s + ttt_chunk [401/1893] bpb=1.186635 time=104.2s + ttt_chunk [411/1893] bpb=1.185523 time=106.8s + ttt_chunk [421/1893] bpb=1.184508 time=109.4s + ttt_chunk [431/1893] bpb=1.184403 time=112.0s + ttt_chunk [441/1893] bpb=1.184667 time=114.6s + ttt_chunk [451/1893] bpb=1.184936 time=117.2s + ttt_chunk [461/1893] bpb=1.183838 time=119.8s + ttt_chunk [471/1893] bpb=1.184368 time=122.4s + ttt_chunk [481/1893] bpb=1.184010 time=125.0s + ttt_chunk [491/1893] bpb=1.182908 time=127.6s + ttt_chunk [501/1893] bpb=1.182381 time=130.2s + ttt_chunk [511/1893] bpb=1.181727 time=132.8s + ttt_chunk [521/1893] bpb=1.179449 time=135.4s + ttt_chunk [531/1893] bpb=1.180511 time=138.0s + ttt_chunk [541/1893] bpb=1.180774 time=140.6s + ttt_chunk [551/1893] bpb=1.179647 time=143.1s + ttt_chunk [561/1893] bpb=1.180077 time=145.7s + ttt_chunk [571/1893] bpb=1.179012 time=148.3s + ttt_chunk [581/1893] bpb=1.178078 time=150.9s + ttt_chunk [591/1893] bpb=1.177363 time=153.5s + ttt_chunk [601/1893] bpb=1.177800 time=156.1s + ttt_chunk [611/1893] bpb=1.177659 time=158.7s + ttt_chunk [621/1893] bpb=1.177504 time=161.3s + ttt_chunk [631/1893] bpb=1.178152 time=163.9s + ttt_chunk [641/1893] bpb=1.177906 time=166.5s + ttt_chunk [651/1893] bpb=1.177952 time=169.1s + ttt_chunk [661/1893] bpb=1.177366 time=171.7s + ttt_chunk [671/1893] bpb=1.177663 time=174.2s + ttt_chunk [681/1893] bpb=1.178302 time=176.8s + ttt_chunk [691/1893] bpb=1.179252 time=179.4s + ttt_chunk [701/1893] bpb=1.178656 time=182.0s + ttt_chunk [711/1893] bpb=1.178677 time=184.6s + ttt_chunk [721/1893] bpb=1.178308 time=187.2s + ttt_chunk [731/1893] bpb=1.178367 time=189.8s + ttt_chunk [741/1893] bpb=1.178509 time=192.4s + ttt_chunk [751/1893] bpb=1.178333 time=195.0s + ttt_chunk [761/1893] bpb=1.178260 time=197.6s + ttt_chunk [771/1893] bpb=1.177942 time=200.2s + ttt_chunk [781/1893] bpb=1.178710 time=202.7s + ttt_chunk [791/1893] bpb=1.178328 time=205.3s + ttt_chunk [801/1893] bpb=1.178621 time=207.9s + ttt_chunk [811/1893] bpb=1.178437 time=210.5s + ttt_chunk [821/1893] bpb=1.178251 time=213.1s + ttt_chunk [831/1893] bpb=1.178112 time=215.7s + ttt_chunk [841/1893] bpb=1.177453 time=218.3s + ttt_chunk [851/1893] bpb=1.177257 time=220.9s + ttt_chunk [861/1893] bpb=1.177026 time=223.5s + ttt_chunk [871/1893] bpb=1.177332 time=226.1s + ttt_chunk [881/1893] bpb=1.177513 time=228.7s + ttt_chunk [891/1893] bpb=1.177108 time=231.3s + ttt_chunk [901/1893] bpb=1.176861 time=233.9s + ttt_chunk [911/1893] bpb=1.177023 time=236.5s + ttt_chunk [921/1893] bpb=1.177513 time=239.1s + ttt_chunk [931/1893] bpb=1.177458 time=241.7s + ttt_chunk [941/1893] bpb=1.177117 time=244.3s + ttt_chunk [951/1893] bpb=1.177530 time=246.9s + ttt_chunk [961/1893] bpb=1.177604 time=249.4s + ttt_chunk [971/1893] bpb=1.178510 time=252.0s + ttt_chunk [981/1893] bpb=1.178530 time=254.7s + ttt_chunk [991/1893] bpb=1.178516 time=257.3s + ttt_chunk [1001/1893] bpb=1.178461 time=259.8s + ttt_chunk [1011/1893] bpb=1.178253 time=262.4s + ttt_chunk [1021/1893] bpb=1.178563 time=265.0s + ttt_chunk [1031/1893] bpb=1.179015 time=267.6s + ttt_chunk [1041/1893] bpb=1.178665 time=270.2s + ttt_chunk [1051/1893] bpb=1.178417 time=272.8s + ttt_chunk [1061/1893] bpb=1.178514 time=275.4s + ttt_chunk [1071/1893] bpb=1.179125 time=278.0s + ttt_chunk [1081/1893] bpb=1.179427 time=280.6s + ttt_chunk [1091/1893] bpb=1.180088 time=283.2s + ttt_chunk [1101/1893] bpb=1.180082 time=285.8s + ttt_chunk [1111/1893] bpb=1.179912 time=288.4s + ttt_chunk [1121/1893] bpb=1.179704 time=291.0s + ttt_chunk [1131/1893] bpb=1.179536 time=293.6s + ttt_chunk [1141/1893] bpb=1.179222 time=296.2s + ttt_chunk [1151/1893] bpb=1.179201 time=298.7s + ttt_chunk [1161/1893] bpb=1.178799 time=301.3s + ttt_chunk [1171/1893] bpb=1.179071 time=303.9s + ttt_chunk [1181/1893] bpb=1.178296 time=306.6s + ttt_chunk [1191/1893] bpb=1.178151 time=309.1s + ttt_chunk [1201/1893] bpb=1.178534 time=311.8s + ttt_chunk [1211/1893] bpb=1.178041 time=314.3s + ttt_chunk [1221/1893] bpb=1.177708 time=316.9s + ttt_chunk [1231/1893] bpb=1.177408 time=319.5s + ttt_chunk [1241/1893] bpb=1.177049 time=322.1s + ttt_chunk [1251/1893] bpb=1.176426 time=324.7s + ttt_chunk [1261/1893] bpb=1.176386 time=327.3s + ttt_chunk [1271/1893] bpb=1.176009 time=329.8s + ttt_chunk [1281/1893] bpb=1.175780 time=332.4s + ttt_chunk [1291/1893] bpb=1.175534 time=335.0s + ttt_chunk [1301/1893] bpb=1.174899 time=337.6s + ttt_chunk [1311/1893] bpb=1.174474 time=340.2s + ttt_chunk [1321/1893] bpb=1.174106 time=342.8s + ttt_chunk [1331/1893] bpb=1.174013 time=345.4s + ttt_chunk [1341/1893] bpb=1.173875 time=348.0s + ttt_chunk [1351/1893] bpb=1.173821 time=350.5s + ttt_chunk [1361/1893] bpb=1.173861 time=353.2s + ttt_chunk [1371/1893] bpb=1.173737 time=355.8s + ttt_chunk [1381/1893] bpb=1.173739 time=358.3s + ttt_chunk [1391/1893] bpb=1.173347 time=360.9s + ttt_chunk [1401/1893] bpb=1.173330 time=363.5s + ttt_chunk [1411/1893] bpb=1.173451 time=366.1s + ttt_chunk [1421/1893] bpb=1.173726 time=368.7s + ttt_chunk [1431/1893] bpb=1.173466 time=371.3s + ttt_chunk [1441/1893] bpb=1.173988 time=373.9s + ttt_chunk [1451/1893] bpb=1.174322 time=376.5s + ttt_chunk [1461/1893] bpb=1.173871 time=379.0s + ttt_chunk [1471/1893] bpb=1.174907 time=381.6s + ttt_chunk [1481/1893] bpb=1.174434 time=384.2s + ttt_chunk [1491/1893] bpb=1.174261 time=386.8s + ttt_chunk [1501/1893] bpb=1.174216 time=389.4s + ttt_chunk [1511/1893] bpb=1.174252 time=392.0s + ttt_chunk [1521/1893] bpb=1.174285 time=394.6s + ttt_chunk [1531/1893] bpb=1.173795 time=397.1s + ttt_chunk [1541/1893] bpb=1.173626 time=399.7s + ttt_chunk [1551/1893] bpb=1.173971 time=402.3s + ttt_chunk [1561/1893] bpb=1.173996 time=404.9s + ttt_chunk [1571/1893] bpb=1.173831 time=407.5s + ttt_chunk [1581/1893] bpb=1.173938 time=410.1s + ttt_chunk [1591/1893] bpb=1.173794 time=412.7s + ttt_chunk [1601/1893] bpb=1.173960 time=415.3s + ttt_chunk [1611/1893] bpb=1.173876 time=417.9s + ttt_chunk [1621/1893] bpb=1.173476 time=420.4s + ttt_chunk [1631/1893] bpb=1.173802 time=423.0s + ttt_chunk [1641/1893] bpb=1.173826 time=425.6s + ttt_chunk [1651/1893] bpb=1.173758 time=428.2s + ttt_chunk [1661/1893] bpb=1.173657 time=430.8s + ttt_chunk [1671/1893] bpb=1.174141 time=433.4s + ttt_chunk [1681/1893] bpb=1.174280 time=435.9s + ttt_chunk [1691/1893] bpb=1.174090 time=438.5s + ttt_chunk [1701/1893] bpb=1.174238 time=441.1s + ttt_chunk [1711/1893] bpb=1.174218 time=443.7s + ttt_chunk [1721/1893] bpb=1.174208 time=446.3s + ttt_chunk [1731/1893] bpb=1.174068 time=448.9s + ttt_chunk [1741/1893] bpb=1.173877 time=451.5s + ttt_chunk [1751/1893] bpb=1.173685 time=454.1s + ttt_chunk [1761/1893] bpb=1.173834 time=456.7s + ttt_chunk [1771/1893] bpb=1.173735 time=459.2s + ttt_chunk [1781/1893] bpb=1.173774 time=461.8s + ttt_chunk [1791/1893] bpb=1.173320 time=464.4s + ttt_chunk [1801/1893] bpb=1.173188 time=467.0s + ttt_chunk [1811/1893] bpb=1.173082 time=469.6s + ttt_chunk [1821/1893] bpb=1.173130 time=472.1s + ttt_chunk [1831/1893] bpb=1.172494 time=474.7s + ttt_chunk [1841/1893] bpb=1.172534 time=477.3s + ttt_chunk [1851/1893] bpb=1.172313 time=479.9s + ttt_chunk [1861/1893] bpb=1.171928 time=482.5s + ttt_chunk [1871/1893] bpb=1.171894 time=485.1s + ttt_chunk [1881/1893] bpb=1.171418 time=487.6s + ttt_chunk [1891/1893] bpb=1.171180 time=490.2s + ttt_chunk [1893/1893] bpb=1.171227 time=490.6s +ttt_sliding:done val_loss=1.974235 val_bpb=1.169256 elapsed=490.6s +final_ttt_sliding val_loss:1.9742 val_bpb:1.1693 eval_time:491268ms +========== SEED 2024 DONE ========== diff --git a/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/seed1337.log b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/seed1337.log new file mode 100644 index 0000000000..15e56dbec2 --- /dev/null +++ b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/seed1337.log @@ -0,0 +1,315 @@ +W0327 01:50:39.303000 53834 torch/distributed/run.py:803] +W0327 01:50:39.303000 53834 torch/distributed/run.py:803] ***************************************** +W0327 01:50:39.303000 53834 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0327 01:50:39.303000 53834 torch/distributed/run.py:803] ***************************************** +logs/7L_seed1337.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +qat:enabled from step 0 attn=6bit +architecture:recursive num_blocks:4 num_loops:7 shared_block_params:27263104 per_loop_params:28672 +model_params:29950082 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:32 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:600.000 +seed:1337 +warmup_step:10/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:6.9756 val_bpb:4.1313 train_time:0ms step_avg:0.02ms +step:1/20000 train_loss:6.9761 train_time:150ms step_avg:149.69ms +step:2/20000 train_loss:9.9188 train_time:169ms step_avg:84.74ms +step:3/20000 train_loss:8.6877 train_time:269ms step_avg:89.51ms +step:4/20000 train_loss:7.5341 train_time:371ms step_avg:92.67ms +step:5/20000 train_loss:6.7940 train_time:471ms step_avg:94.17ms +step:6/20000 train_loss:7.5570 train_time:572ms step_avg:95.28ms +step:7/20000 train_loss:6.2147 train_time:674ms step_avg:96.23ms +step:8/20000 train_loss:6.1019 train_time:775ms step_avg:96.81ms +step:9/20000 train_loss:5.9525 train_time:875ms step_avg:97.26ms +step:10/20000 train_loss:5.7052 train_time:982ms step_avg:98.15ms +step:100/20000 train_loss:3.3879 train_time:10002ms step_avg:100.02ms +step:200/20000 train_loss:2.8358 train_time:20101ms step_avg:100.51ms +step:300/20000 train_loss:2.4130 train_time:30174ms step_avg:100.58ms +step:400/20000 train_loss:2.2914 train_time:40304ms step_avg:100.76ms +step:500/20000 train_loss:2.4487 train_time:50384ms step_avg:100.77ms +step:500/20000 val_loss:2.4478 val_bpb:1.4497 train_time:50450ms step_avg:100.90ms +step:600/20000 train_loss:2.5100 train_time:60514ms step_avg:100.86ms +step:700/20000 train_loss:2.3990 train_time:70592ms step_avg:100.85ms +step:800/20000 train_loss:2.2354 train_time:80703ms step_avg:100.88ms +step:900/20000 train_loss:2.2918 train_time:90764ms step_avg:100.85ms +step:1000/20000 train_loss:2.3286 train_time:100882ms step_avg:100.88ms +step:1000/20000 val_loss:2.2815 val_bpb:1.3512 train_time:100947ms step_avg:100.95ms +step:1100/20000 train_loss:2.2053 train_time:110911ms step_avg:100.83ms +step:1200/20000 train_loss:2.3513 train_time:121022ms step_avg:100.85ms +step:1300/20000 train_loss:2.3159 train_time:131043ms step_avg:100.80ms +step:1400/20000 train_loss:2.3703 train_time:141101ms step_avg:100.79ms +step:1500/20000 train_loss:2.1790 train_time:151101ms step_avg:100.73ms +step:1500/20000 val_loss:2.2159 val_bpb:1.3124 train_time:151166ms step_avg:100.78ms +step:1600/20000 train_loss:2.0354 train_time:161185ms step_avg:100.74ms +step:1700/20000 train_loss:2.1115 train_time:171183ms step_avg:100.70ms +step:1800/20000 train_loss:2.1573 train_time:181244ms step_avg:100.69ms +step:1900/20000 train_loss:2.1396 train_time:191244ms step_avg:100.65ms +step:2000/20000 train_loss:2.1977 train_time:201302ms step_avg:100.65ms +step:2000/20000 val_loss:2.1822 val_bpb:1.2924 train_time:201368ms step_avg:100.68ms +step:2100/20000 train_loss:2.2198 train_time:211368ms step_avg:100.65ms +step:2200/20000 train_loss:2.0184 train_time:221365ms step_avg:100.62ms +step:2300/20000 train_loss:2.3185 train_time:231425ms step_avg:100.62ms +step:2400/20000 train_loss:2.1498 train_time:241423ms step_avg:100.59ms +step:2500/20000 train_loss:2.0830 train_time:251478ms step_avg:100.59ms +step:2500/20000 val_loss:2.1602 val_bpb:1.2794 train_time:251544ms step_avg:100.62ms +step:2600/20000 train_loss:2.3726 train_time:261480ms step_avg:100.57ms +step:2700/20000 train_loss:2.1021 train_time:271525ms step_avg:100.56ms +step:2800/20000 train_loss:2.1866 train_time:281527ms step_avg:100.55ms +step:2900/20000 train_loss:2.1290 train_time:291578ms step_avg:100.54ms +step:3000/20000 train_loss:2.1666 train_time:301576ms step_avg:100.53ms +step:3000/20000 val_loss:2.1349 val_bpb:1.2644 train_time:301640ms step_avg:100.55ms +step:3100/20000 train_loss:2.1398 train_time:311628ms step_avg:100.53ms +step:3200/20000 train_loss:2.1279 train_time:321633ms step_avg:100.51ms +step:3300/20000 train_loss:2.1744 train_time:331684ms step_avg:100.51ms +step:3400/20000 train_loss:2.0968 train_time:341670ms step_avg:100.49ms +step:3500/20000 train_loss:2.1864 train_time:351730ms step_avg:100.49ms +step:3500/20000 val_loss:2.1125 val_bpb:1.2512 train_time:351796ms step_avg:100.51ms +step:3600/20000 train_loss:2.0309 train_time:361734ms step_avg:100.48ms +step:3700/20000 train_loss:2.0582 train_time:371793ms step_avg:100.48ms +step:3800/20000 train_loss:2.1357 train_time:381793ms step_avg:100.47ms +step:3900/20000 train_loss:1.9048 train_time:391854ms step_avg:100.48ms +step:4000/20000 train_loss:2.0962 train_time:401854ms step_avg:100.46ms +step:4000/20000 val_loss:2.0892 val_bpb:1.2374 train_time:401920ms step_avg:100.48ms +step:4100/20000 train_loss:2.1065 train_time:411919ms step_avg:100.47ms +step:4200/20000 train_loss:2.0895 train_time:421980ms step_avg:100.47ms +step:4300/20000 train_loss:1.9314 train_time:431977ms step_avg:100.46ms +step:4400/20000 train_loss:2.0155 train_time:442039ms step_avg:100.46ms +step:4500/20000 train_loss:2.1698 train_time:452039ms step_avg:100.45ms +step:4500/20000 val_loss:2.0673 val_bpb:1.2244 train_time:452103ms step_avg:100.47ms +step:4600/20000 train_loss:1.8762 train_time:462101ms step_avg:100.46ms +step:4700/20000 train_loss:2.1701 train_time:472164ms step_avg:100.46ms +step:4800/20000 train_loss:2.1529 train_time:482230ms step_avg:100.46ms +step:4900/20000 train_loss:2.0674 train_time:492231ms step_avg:100.46ms +step:5000/20000 train_loss:1.9073 train_time:502291ms step_avg:100.46ms +step:5000/20000 val_loss:2.0427 val_bpb:1.2098 train_time:502357ms step_avg:100.47ms +step:5100/20000 train_loss:1.9074 train_time:512296ms step_avg:100.45ms +step:5200/20000 train_loss:2.0589 train_time:522348ms step_avg:100.45ms +step:5300/20000 train_loss:2.0842 train_time:532355ms step_avg:100.44ms +step:5400/20000 train_loss:2.0649 train_time:542596ms step_avg:100.48ms +step:5500/20000 train_loss:2.0165 train_time:552757ms step_avg:100.50ms +step:5500/20000 val_loss:2.0174 val_bpb:1.1948 train_time:552821ms step_avg:100.51ms +step:5600/20000 train_loss:2.0398 train_time:562967ms step_avg:100.53ms +step:5700/20000 train_loss:2.0403 train_time:573135ms step_avg:100.55ms +step:5800/20000 train_loss:1.9901 train_time:583355ms step_avg:100.58ms +step:5900/20000 train_loss:1.9590 train_time:593515ms step_avg:100.60ms +step:5963/20000 val_loss:1.9971 val_bpb:1.1828 train_time:600094ms step_avg:100.64ms +stopping_early: wallclock_cap train_time:600094ms step:5963/20000 +peak memory allocated: 15596 MiB reserved: 15762 MiB +swa:averaging 14 checkpoints +swa_eval val_loss:1.9962 val_bpb:1.1823 +Serialized model: 114835683 bytes +Code size: 68750 bytes +Total submission size: 114904433 bytes +Serialized model int8+zstd-22: 15749104 bytes (payload:30153220 raw_torch:30174423 payload_ratio:3.81x) +Total submission size int8+zlib: 15817854 bytes +final_int8_zlib_roundtrip val_loss:2.0181 val_bpb:1.1952 eval_time:3335ms +final_int8_zlib_roundtrip_exact val_loss:2.01811577 val_bpb:1.19524183 +ttt_sliding:start chunks=1893 chunk_tokens=32768 total_windows=969091 stride=64 +ttt_sliding:params unfrozen=23134306 frozen=6815776 + ttt_chunk [1/1893] bpb=1.212706 time=0.5s + ttt_chunk [11/1893] bpb=1.196021 time=3.0s + ttt_chunk [21/1893] bpb=1.181737 time=5.6s + ttt_chunk [31/1893] bpb=1.178941 time=8.2s + ttt_chunk [41/1893] bpb=1.165309 time=10.8s + ttt_chunk [51/1893] bpb=1.160794 time=13.4s + ttt_chunk [61/1893] bpb=1.167741 time=16.0s + ttt_chunk [71/1893] bpb=1.166066 time=18.6s + ttt_chunk [81/1893] bpb=1.165450 time=21.1s + ttt_chunk [91/1893] bpb=1.166613 time=23.7s + ttt_chunk [101/1893] bpb=1.170344 time=26.3s + ttt_chunk [111/1893] bpb=1.172887 time=28.9s + ttt_chunk [121/1893] bpb=1.166498 time=31.5s + ttt_chunk [131/1893] bpb=1.167002 time=34.1s + ttt_chunk [141/1893] bpb=1.172724 time=36.7s + ttt_chunk [151/1893] bpb=1.174535 time=39.2s + ttt_chunk [161/1893] bpb=1.174555 time=41.8s + ttt_chunk [171/1893] bpb=1.179340 time=44.4s + ttt_chunk [181/1893] bpb=1.181822 time=47.0s + ttt_chunk [191/1893] bpb=1.189162 time=49.6s + ttt_chunk [201/1893] bpb=1.188078 time=52.2s + ttt_chunk [211/1893] bpb=1.185973 time=54.8s + ttt_chunk [221/1893] bpb=1.187417 time=57.4s + ttt_chunk [231/1893] bpb=1.186004 time=60.0s + ttt_chunk [241/1893] bpb=1.186317 time=62.5s + ttt_chunk [251/1893] bpb=1.185774 time=65.1s + ttt_chunk [261/1893] bpb=1.182669 time=67.7s + ttt_chunk [271/1893] bpb=1.181457 time=70.3s + ttt_chunk [281/1893] bpb=1.182855 time=72.9s + ttt_chunk [291/1893] bpb=1.184757 time=75.5s + ttt_chunk [301/1893] bpb=1.185403 time=78.1s + ttt_chunk [311/1893] bpb=1.187480 time=80.6s + ttt_chunk [321/1893] bpb=1.189300 time=83.2s + ttt_chunk [331/1893] bpb=1.189171 time=85.8s + ttt_chunk [341/1893] bpb=1.188135 time=88.4s + ttt_chunk [351/1893] bpb=1.190501 time=90.9s + ttt_chunk [361/1893] bpb=1.190763 time=93.5s + ttt_chunk [371/1893] bpb=1.189911 time=96.1s + ttt_chunk [381/1893] bpb=1.190001 time=98.7s + ttt_chunk [391/1893] bpb=1.189737 time=101.3s + ttt_chunk [401/1893] bpb=1.187624 time=103.8s + ttt_chunk [411/1893] bpb=1.186535 time=106.4s + ttt_chunk [421/1893] bpb=1.185484 time=109.0s + ttt_chunk [431/1893] bpb=1.185330 time=111.6s + ttt_chunk [441/1893] bpb=1.185602 time=114.2s + ttt_chunk [451/1893] bpb=1.185851 time=116.8s + ttt_chunk [461/1893] bpb=1.184732 time=119.4s + ttt_chunk [471/1893] bpb=1.185253 time=121.9s + ttt_chunk [481/1893] bpb=1.184882 time=124.5s + ttt_chunk [491/1893] bpb=1.183769 time=127.1s + ttt_chunk [501/1893] bpb=1.183248 time=129.7s + ttt_chunk [511/1893] bpb=1.182588 time=132.3s + ttt_chunk [521/1893] bpb=1.180334 time=134.9s + ttt_chunk [531/1893] bpb=1.181396 time=137.5s + ttt_chunk [541/1893] bpb=1.181625 time=140.0s + ttt_chunk [551/1893] bpb=1.180504 time=142.6s + ttt_chunk [561/1893] bpb=1.181022 time=145.2s + ttt_chunk [571/1893] bpb=1.179891 time=147.9s + ttt_chunk [581/1893] bpb=1.178991 time=150.4s + ttt_chunk [591/1893] bpb=1.178239 time=153.1s + ttt_chunk [601/1893] bpb=1.178693 time=155.7s + ttt_chunk [611/1893] bpb=1.178501 time=158.2s + ttt_chunk [621/1893] bpb=1.178316 time=160.8s + ttt_chunk [631/1893] bpb=1.178980 time=163.4s + ttt_chunk [641/1893] bpb=1.178714 time=166.0s + ttt_chunk [651/1893] bpb=1.178757 time=168.5s + ttt_chunk [661/1893] bpb=1.178164 time=171.1s + ttt_chunk [671/1893] bpb=1.178506 time=173.7s + ttt_chunk [681/1893] bpb=1.179211 time=176.3s + ttt_chunk [691/1893] bpb=1.180168 time=178.9s + ttt_chunk [701/1893] bpb=1.179572 time=181.5s + ttt_chunk [711/1893] bpb=1.179598 time=184.1s + ttt_chunk [721/1893] bpb=1.179207 time=186.7s + ttt_chunk [731/1893] bpb=1.179262 time=189.2s + ttt_chunk [741/1893] bpb=1.179395 time=191.8s + ttt_chunk [751/1893] bpb=1.179207 time=194.4s + ttt_chunk [761/1893] bpb=1.179117 time=197.0s + ttt_chunk [771/1893] bpb=1.178777 time=199.6s + ttt_chunk [781/1893] bpb=1.179519 time=202.2s + ttt_chunk [791/1893] bpb=1.179120 time=204.7s + ttt_chunk [801/1893] bpb=1.179404 time=207.3s + ttt_chunk [811/1893] bpb=1.179220 time=209.9s + ttt_chunk [821/1893] bpb=1.179047 time=212.5s + ttt_chunk [831/1893] bpb=1.178877 time=215.1s + ttt_chunk [841/1893] bpb=1.178228 time=217.6s + ttt_chunk [851/1893] bpb=1.178017 time=220.2s + ttt_chunk [861/1893] bpb=1.177768 time=222.8s + ttt_chunk [871/1893] bpb=1.178024 time=225.3s + ttt_chunk [881/1893] bpb=1.178226 time=227.9s + ttt_chunk [891/1893] bpb=1.177789 time=230.5s + ttt_chunk [901/1893] bpb=1.177532 time=233.1s + ttt_chunk [911/1893] bpb=1.177694 time=235.6s + ttt_chunk [921/1893] bpb=1.178176 time=238.2s + ttt_chunk [931/1893] bpb=1.178134 time=240.8s + ttt_chunk [941/1893] bpb=1.177819 time=243.4s + ttt_chunk [951/1893] bpb=1.178234 time=245.9s + ttt_chunk [961/1893] bpb=1.178312 time=248.5s + ttt_chunk [971/1893] bpb=1.179205 time=251.1s + ttt_chunk [981/1893] bpb=1.179282 time=253.7s + ttt_chunk [991/1893] bpb=1.179237 time=256.3s + ttt_chunk [1001/1893] bpb=1.179212 time=258.8s + ttt_chunk [1011/1893] bpb=1.179016 time=261.4s + ttt_chunk [1021/1893] bpb=1.179331 time=264.0s + ttt_chunk [1031/1893] bpb=1.179787 time=266.6s + ttt_chunk [1041/1893] bpb=1.179404 time=269.2s + ttt_chunk [1051/1893] bpb=1.179145 time=271.7s + ttt_chunk [1061/1893] bpb=1.179197 time=274.3s + ttt_chunk [1071/1893] bpb=1.179811 time=276.9s + ttt_chunk [1081/1893] bpb=1.180088 time=279.5s + ttt_chunk [1091/1893] bpb=1.180750 time=282.1s + ttt_chunk [1101/1893] bpb=1.180716 time=284.6s + ttt_chunk [1111/1893] bpb=1.180560 time=287.2s + ttt_chunk [1121/1893] bpb=1.180356 time=289.8s + ttt_chunk [1131/1893] bpb=1.180192 time=292.4s + ttt_chunk [1141/1893] bpb=1.179882 time=295.0s + ttt_chunk [1151/1893] bpb=1.179868 time=297.5s + ttt_chunk [1161/1893] bpb=1.179459 time=300.1s + ttt_chunk [1171/1893] bpb=1.179733 time=302.7s + ttt_chunk [1181/1893] bpb=1.178963 time=305.3s + ttt_chunk [1191/1893] bpb=1.178818 time=307.9s + ttt_chunk [1201/1893] bpb=1.179185 time=310.4s + ttt_chunk [1211/1893] bpb=1.178696 time=313.0s + ttt_chunk [1221/1893] bpb=1.178379 time=315.6s + ttt_chunk [1231/1893] bpb=1.178025 time=318.2s + ttt_chunk [1241/1893] bpb=1.177669 time=320.8s + ttt_chunk [1251/1893] bpb=1.177061 time=323.4s + ttt_chunk [1261/1893] bpb=1.177025 time=326.0s + ttt_chunk [1271/1893] bpb=1.176646 time=328.6s + ttt_chunk [1281/1893] bpb=1.176455 time=331.1s + ttt_chunk [1291/1893] bpb=1.176233 time=333.7s + ttt_chunk [1301/1893] bpb=1.175636 time=336.3s + ttt_chunk [1311/1893] bpb=1.175199 time=338.9s + ttt_chunk [1321/1893] bpb=1.174848 time=341.5s + ttt_chunk [1331/1893] bpb=1.174741 time=344.0s + ttt_chunk [1341/1893] bpb=1.174585 time=346.6s + ttt_chunk [1351/1893] bpb=1.174510 time=349.2s + ttt_chunk [1361/1893] bpb=1.174548 time=351.8s + ttt_chunk [1371/1893] bpb=1.174420 time=354.3s + ttt_chunk [1381/1893] bpb=1.174393 time=356.9s + ttt_chunk [1391/1893] bpb=1.174003 time=359.5s + ttt_chunk [1401/1893] bpb=1.174000 time=362.1s + ttt_chunk [1411/1893] bpb=1.174115 time=364.7s + ttt_chunk [1421/1893] bpb=1.174373 time=367.3s + ttt_chunk [1431/1893] bpb=1.174092 time=369.8s + ttt_chunk [1441/1893] bpb=1.174602 time=372.4s + ttt_chunk [1451/1893] bpb=1.174936 time=375.0s + ttt_chunk [1461/1893] bpb=1.174480 time=377.6s + ttt_chunk [1471/1893] bpb=1.175512 time=380.2s + ttt_chunk [1481/1893] bpb=1.175056 time=382.7s + ttt_chunk [1491/1893] bpb=1.174881 time=385.3s + ttt_chunk [1501/1893] bpb=1.174839 time=387.9s + ttt_chunk [1511/1893] bpb=1.174881 time=390.5s + ttt_chunk [1521/1893] bpb=1.174896 time=393.0s + ttt_chunk [1531/1893] bpb=1.174406 time=395.6s + ttt_chunk [1541/1893] bpb=1.174272 time=398.2s + ttt_chunk [1551/1893] bpb=1.174622 time=400.8s + ttt_chunk [1561/1893] bpb=1.174650 time=403.4s + ttt_chunk [1571/1893] bpb=1.174484 time=406.0s + ttt_chunk [1581/1893] bpb=1.174589 time=408.6s + ttt_chunk [1591/1893] bpb=1.174450 time=411.1s + ttt_chunk [1601/1893] bpb=1.174621 time=413.7s + ttt_chunk [1611/1893] bpb=1.174526 time=416.3s + ttt_chunk [1621/1893] bpb=1.174107 time=418.8s + ttt_chunk [1631/1893] bpb=1.174429 time=421.4s + ttt_chunk [1641/1893] bpb=1.174448 time=424.0s + ttt_chunk [1651/1893] bpb=1.174373 time=426.6s + ttt_chunk [1661/1893] bpb=1.174246 time=429.1s + ttt_chunk [1671/1893] bpb=1.174731 time=431.7s + ttt_chunk [1681/1893] bpb=1.174852 time=434.3s + ttt_chunk [1691/1893] bpb=1.174657 time=436.8s + ttt_chunk [1701/1893] bpb=1.174801 time=439.4s + ttt_chunk [1711/1893] bpb=1.174794 time=442.0s + ttt_chunk [1721/1893] bpb=1.174777 time=444.6s + ttt_chunk [1731/1893] bpb=1.174646 time=447.1s + ttt_chunk [1741/1893] bpb=1.174458 time=449.7s + ttt_chunk [1751/1893] bpb=1.174270 time=452.3s + ttt_chunk [1761/1893] bpb=1.174429 time=454.9s + ttt_chunk [1771/1893] bpb=1.174318 time=457.5s + ttt_chunk [1781/1893] bpb=1.174358 time=460.1s + ttt_chunk [1791/1893] bpb=1.173908 time=462.6s + ttt_chunk [1801/1893] bpb=1.173781 time=465.2s + ttt_chunk [1811/1893] bpb=1.173670 time=467.8s + ttt_chunk [1821/1893] bpb=1.173718 time=470.3s + ttt_chunk [1831/1893] bpb=1.173092 time=472.9s + ttt_chunk [1841/1893] bpb=1.173133 time=475.5s + ttt_chunk [1851/1893] bpb=1.172933 time=478.1s + ttt_chunk [1861/1893] bpb=1.172548 time=480.6s + ttt_chunk [1871/1893] bpb=1.172519 time=483.2s + ttt_chunk [1881/1893] bpb=1.172048 time=485.8s + ttt_chunk [1891/1893] bpb=1.171805 time=488.4s + ttt_chunk [1893/1893] bpb=1.171849 time=488.7s +ttt_sliding:done val_loss=1.975159 val_bpb=1.169803 elapsed=488.8s +final_ttt_sliding val_loss:1.9752 val_bpb:1.1698 eval_time:489407ms diff --git a/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/seed2024.log b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/seed2024.log new file mode 100644 index 0000000000..e39b44017c --- /dev/null +++ b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/seed2024.log @@ -0,0 +1,315 @@ +W0327 02:32:22.780000 57606 torch/distributed/run.py:803] +W0327 02:32:22.780000 57606 torch/distributed/run.py:803] ***************************************** +W0327 02:32:22.780000 57606 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0327 02:32:22.780000 57606 torch/distributed/run.py:803] ***************************************** +logs/7L_seed2024.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +qat:enabled from step 0 attn=6bit +architecture:recursive num_blocks:4 num_loops:7 shared_block_params:27263104 per_loop_params:28672 +model_params:29950082 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:32 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:600.000 +seed:2024 +warmup_step:10/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:6.9785 val_bpb:4.1331 train_time:0ms step_avg:0.02ms +step:1/20000 train_loss:6.9793 train_time:148ms step_avg:148.27ms +step:2/20000 train_loss:9.8874 train_time:179ms step_avg:89.27ms +step:3/20000 train_loss:8.6647 train_time:268ms step_avg:89.20ms +step:4/20000 train_loss:7.5235 train_time:368ms step_avg:91.93ms +step:5/20000 train_loss:6.8025 train_time:469ms step_avg:93.83ms +step:6/20000 train_loss:7.5605 train_time:570ms step_avg:95.05ms +step:7/20000 train_loss:6.2233 train_time:671ms step_avg:95.91ms +step:8/20000 train_loss:6.1422 train_time:772ms step_avg:96.52ms +step:9/20000 train_loss:5.9612 train_time:873ms step_avg:96.96ms +step:10/20000 train_loss:5.6963 train_time:976ms step_avg:97.57ms +step:100/20000 train_loss:3.3951 train_time:9998ms step_avg:99.98ms +step:200/20000 train_loss:2.8209 train_time:20136ms step_avg:100.68ms +step:300/20000 train_loss:2.4129 train_time:30220ms step_avg:100.73ms +step:400/20000 train_loss:2.2943 train_time:40373ms step_avg:100.93ms +step:500/20000 train_loss:2.4544 train_time:50459ms step_avg:100.92ms +step:500/20000 val_loss:2.4531 val_bpb:1.4528 train_time:50525ms step_avg:101.05ms +step:600/20000 train_loss:2.5131 train_time:60588ms step_avg:100.98ms +step:700/20000 train_loss:2.3981 train_time:70663ms step_avg:100.95ms +step:800/20000 train_loss:2.2338 train_time:80768ms step_avg:100.96ms +step:900/20000 train_loss:2.2907 train_time:90753ms step_avg:100.84ms +step:1000/20000 train_loss:2.3290 train_time:100840ms step_avg:100.84ms +step:1000/20000 val_loss:2.2803 val_bpb:1.3505 train_time:100923ms step_avg:100.92ms +step:1100/20000 train_loss:2.1973 train_time:110853ms step_avg:100.78ms +step:1200/20000 train_loss:2.3445 train_time:120911ms step_avg:100.76ms +step:1300/20000 train_loss:2.3144 train_time:130919ms step_avg:100.71ms +step:1400/20000 train_loss:2.3635 train_time:140977ms step_avg:100.70ms +step:1500/20000 train_loss:2.1728 train_time:150978ms step_avg:100.65ms +step:1500/20000 val_loss:2.2128 val_bpb:1.3106 train_time:151059ms step_avg:100.71ms +step:1600/20000 train_loss:2.0344 train_time:161053ms step_avg:100.66ms +step:1700/20000 train_loss:2.1108 train_time:171052ms step_avg:100.62ms +step:1800/20000 train_loss:2.1535 train_time:181114ms step_avg:100.62ms +step:1900/20000 train_loss:2.1433 train_time:191094ms step_avg:100.58ms +step:2000/20000 train_loss:2.2010 train_time:201176ms step_avg:100.59ms +step:2000/20000 val_loss:2.1809 val_bpb:1.2917 train_time:201239ms step_avg:100.62ms +step:2100/20000 train_loss:2.2143 train_time:211217ms step_avg:100.58ms +step:2200/20000 train_loss:2.0200 train_time:221216ms step_avg:100.55ms +step:2300/20000 train_loss:2.3191 train_time:231279ms step_avg:100.56ms +step:2400/20000 train_loss:2.1492 train_time:241275ms step_avg:100.53ms +step:2500/20000 train_loss:2.0812 train_time:251326ms step_avg:100.53ms +step:2500/20000 val_loss:2.1594 val_bpb:1.2789 train_time:251409ms step_avg:100.56ms +step:2600/20000 train_loss:2.3706 train_time:261339ms step_avg:100.52ms +step:2700/20000 train_loss:2.0979 train_time:271401ms step_avg:100.52ms +step:2800/20000 train_loss:2.1856 train_time:281401ms step_avg:100.50ms +step:2900/20000 train_loss:2.1288 train_time:291450ms step_avg:100.50ms +step:3000/20000 train_loss:2.1681 train_time:301433ms step_avg:100.48ms +step:3000/20000 val_loss:2.1331 val_bpb:1.2634 train_time:301515ms step_avg:100.51ms +step:3100/20000 train_loss:2.1439 train_time:311478ms step_avg:100.48ms +step:3200/20000 train_loss:2.1281 train_time:321477ms step_avg:100.46ms +step:3300/20000 train_loss:2.1709 train_time:331534ms step_avg:100.46ms +step:3400/20000 train_loss:2.0943 train_time:341527ms step_avg:100.45ms +step:3500/20000 train_loss:2.1851 train_time:351603ms step_avg:100.46ms +step:3500/20000 val_loss:2.1113 val_bpb:1.2505 train_time:351670ms step_avg:100.48ms +step:3600/20000 train_loss:2.0357 train_time:361594ms step_avg:100.44ms +step:3700/20000 train_loss:2.0587 train_time:371676ms step_avg:100.45ms +step:3800/20000 train_loss:2.1352 train_time:381726ms step_avg:100.45ms +step:3900/20000 train_loss:1.9016 train_time:391784ms step_avg:100.46ms +step:4000/20000 train_loss:2.0953 train_time:401783ms step_avg:100.45ms +step:4000/20000 val_loss:2.0880 val_bpb:1.2366 train_time:401848ms step_avg:100.46ms +step:4100/20000 train_loss:2.1067 train_time:411814ms step_avg:100.44ms +step:4200/20000 train_loss:2.0885 train_time:421871ms step_avg:100.45ms +step:4300/20000 train_loss:1.9343 train_time:431874ms step_avg:100.44ms +step:4400/20000 train_loss:2.0164 train_time:441925ms step_avg:100.44ms +step:4500/20000 train_loss:2.1688 train_time:451923ms step_avg:100.43ms +step:4500/20000 val_loss:2.0663 val_bpb:1.2238 train_time:452006ms step_avg:100.45ms +step:4600/20000 train_loss:1.8755 train_time:461995ms step_avg:100.43ms +step:4700/20000 train_loss:2.1656 train_time:471989ms step_avg:100.42ms +step:4800/20000 train_loss:2.1523 train_time:482051ms step_avg:100.43ms +step:4900/20000 train_loss:2.0647 train_time:492050ms step_avg:100.42ms +step:5000/20000 train_loss:1.9043 train_time:502100ms step_avg:100.42ms +step:5000/20000 val_loss:2.0416 val_bpb:1.2091 train_time:502164ms step_avg:100.43ms +step:5100/20000 train_loss:1.9046 train_time:512103ms step_avg:100.41ms +step:5200/20000 train_loss:2.0570 train_time:522147ms step_avg:100.41ms +step:5300/20000 train_loss:2.0851 train_time:532148ms step_avg:100.41ms +step:5400/20000 train_loss:2.0569 train_time:542386ms step_avg:100.44ms +step:5500/20000 train_loss:2.0148 train_time:552546ms step_avg:100.46ms +step:5500/20000 val_loss:2.0164 val_bpb:1.1942 train_time:552612ms step_avg:100.47ms +step:5600/20000 train_loss:2.0422 train_time:562763ms step_avg:100.49ms +step:5700/20000 train_loss:2.0377 train_time:572924ms step_avg:100.51ms +step:5800/20000 train_loss:1.9919 train_time:583143ms step_avg:100.54ms +step:5900/20000 train_loss:1.9565 train_time:593304ms step_avg:100.56ms +step:5965/20000 val_loss:1.9961 val_bpb:1.1822 train_time:600089ms step_avg:100.60ms +stopping_early: wallclock_cap train_time:600089ms step:5965/20000 +peak memory allocated: 15596 MiB reserved: 15762 MiB +swa:averaging 14 checkpoints +swa_eval val_loss:1.9951 val_bpb:1.1816 +Serialized model: 114835683 bytes +Code size: 68750 bytes +Total submission size: 114904433 bytes +Serialized model int8+zstd-22: 15750116 bytes (payload:30153220 raw_torch:30174423 payload_ratio:3.81x) +Total submission size int8+zlib: 15818866 bytes +final_int8_zlib_roundtrip val_loss:2.0171 val_bpb:1.1947 eval_time:3333ms +final_int8_zlib_roundtrip_exact val_loss:2.01714021 val_bpb:1.19466405 +ttt_sliding:start chunks=1893 chunk_tokens=32768 total_windows=969091 stride=64 +ttt_sliding:params unfrozen=23134306 frozen=6815776 + ttt_chunk [1/1893] bpb=1.215084 time=0.5s + ttt_chunk [11/1893] bpb=1.195853 time=3.1s + ttt_chunk [21/1893] bpb=1.182073 time=5.6s + ttt_chunk [31/1893] bpb=1.178912 time=8.2s + ttt_chunk [41/1893] bpb=1.164787 time=10.8s + ttt_chunk [51/1893] bpb=1.159992 time=13.4s + ttt_chunk [61/1893] bpb=1.167405 time=16.0s + ttt_chunk [71/1893] bpb=1.166005 time=18.6s + ttt_chunk [81/1893] bpb=1.165258 time=21.2s + ttt_chunk [91/1893] bpb=1.166428 time=23.8s + ttt_chunk [101/1893] bpb=1.170262 time=26.4s + ttt_chunk [111/1893] bpb=1.172749 time=29.0s + ttt_chunk [121/1893] bpb=1.166244 time=31.5s + ttt_chunk [131/1893] bpb=1.166704 time=34.1s + ttt_chunk [141/1893] bpb=1.172307 time=36.7s + ttt_chunk [151/1893] bpb=1.174193 time=39.3s + ttt_chunk [161/1893] bpb=1.174072 time=41.9s + ttt_chunk [171/1893] bpb=1.178755 time=44.5s + ttt_chunk [181/1893] bpb=1.181156 time=47.1s + ttt_chunk [191/1893] bpb=1.188564 time=49.7s + ttt_chunk [201/1893] bpb=1.187434 time=52.3s + ttt_chunk [211/1893] bpb=1.185254 time=54.9s + ttt_chunk [221/1893] bpb=1.186675 time=57.4s + ttt_chunk [231/1893] bpb=1.185309 time=60.1s + ttt_chunk [241/1893] bpb=1.185619 time=62.6s + ttt_chunk [251/1893] bpb=1.185048 time=65.3s + ttt_chunk [261/1893] bpb=1.181969 time=67.8s + ttt_chunk [271/1893] bpb=1.180755 time=70.4s + ttt_chunk [281/1893] bpb=1.182017 time=73.0s + ttt_chunk [291/1893] bpb=1.183971 time=75.6s + ttt_chunk [301/1893] bpb=1.184613 time=78.2s + ttt_chunk [311/1893] bpb=1.186643 time=80.8s + ttt_chunk [321/1893] bpb=1.188488 time=83.4s + ttt_chunk [331/1893] bpb=1.188356 time=86.0s + ttt_chunk [341/1893] bpb=1.187305 time=88.6s + ttt_chunk [351/1893] bpb=1.189637 time=91.2s + ttt_chunk [361/1893] bpb=1.189854 time=93.8s + ttt_chunk [371/1893] bpb=1.189032 time=96.4s + ttt_chunk [381/1893] bpb=1.189156 time=99.0s + ttt_chunk [391/1893] bpb=1.188844 time=101.6s + ttt_chunk [401/1893] bpb=1.186635 time=104.2s + ttt_chunk [411/1893] bpb=1.185523 time=106.8s + ttt_chunk [421/1893] bpb=1.184508 time=109.4s + ttt_chunk [431/1893] bpb=1.184403 time=112.0s + ttt_chunk [441/1893] bpb=1.184667 time=114.6s + ttt_chunk [451/1893] bpb=1.184936 time=117.2s + ttt_chunk [461/1893] bpb=1.183838 time=119.8s + ttt_chunk [471/1893] bpb=1.184368 time=122.4s + ttt_chunk [481/1893] bpb=1.184010 time=125.0s + ttt_chunk [491/1893] bpb=1.182908 time=127.6s + ttt_chunk [501/1893] bpb=1.182381 time=130.2s + ttt_chunk [511/1893] bpb=1.181727 time=132.8s + ttt_chunk [521/1893] bpb=1.179449 time=135.4s + ttt_chunk [531/1893] bpb=1.180511 time=138.0s + ttt_chunk [541/1893] bpb=1.180774 time=140.6s + ttt_chunk [551/1893] bpb=1.179647 time=143.1s + ttt_chunk [561/1893] bpb=1.180077 time=145.7s + ttt_chunk [571/1893] bpb=1.179012 time=148.3s + ttt_chunk [581/1893] bpb=1.178078 time=150.9s + ttt_chunk [591/1893] bpb=1.177363 time=153.5s + ttt_chunk [601/1893] bpb=1.177800 time=156.1s + ttt_chunk [611/1893] bpb=1.177659 time=158.7s + ttt_chunk [621/1893] bpb=1.177504 time=161.3s + ttt_chunk [631/1893] bpb=1.178152 time=163.9s + ttt_chunk [641/1893] bpb=1.177906 time=166.5s + ttt_chunk [651/1893] bpb=1.177952 time=169.1s + ttt_chunk [661/1893] bpb=1.177366 time=171.7s + ttt_chunk [671/1893] bpb=1.177663 time=174.2s + ttt_chunk [681/1893] bpb=1.178302 time=176.8s + ttt_chunk [691/1893] bpb=1.179252 time=179.4s + ttt_chunk [701/1893] bpb=1.178656 time=182.0s + ttt_chunk [711/1893] bpb=1.178677 time=184.6s + ttt_chunk [721/1893] bpb=1.178308 time=187.2s + ttt_chunk [731/1893] bpb=1.178367 time=189.8s + ttt_chunk [741/1893] bpb=1.178509 time=192.4s + ttt_chunk [751/1893] bpb=1.178333 time=195.0s + ttt_chunk [761/1893] bpb=1.178260 time=197.6s + ttt_chunk [771/1893] bpb=1.177942 time=200.2s + ttt_chunk [781/1893] bpb=1.178710 time=202.7s + ttt_chunk [791/1893] bpb=1.178328 time=205.3s + ttt_chunk [801/1893] bpb=1.178621 time=207.9s + ttt_chunk [811/1893] bpb=1.178437 time=210.5s + ttt_chunk [821/1893] bpb=1.178251 time=213.1s + ttt_chunk [831/1893] bpb=1.178112 time=215.7s + ttt_chunk [841/1893] bpb=1.177453 time=218.3s + ttt_chunk [851/1893] bpb=1.177257 time=220.9s + ttt_chunk [861/1893] bpb=1.177026 time=223.5s + ttt_chunk [871/1893] bpb=1.177332 time=226.1s + ttt_chunk [881/1893] bpb=1.177513 time=228.7s + ttt_chunk [891/1893] bpb=1.177108 time=231.3s + ttt_chunk [901/1893] bpb=1.176861 time=233.9s + ttt_chunk [911/1893] bpb=1.177023 time=236.5s + ttt_chunk [921/1893] bpb=1.177513 time=239.1s + ttt_chunk [931/1893] bpb=1.177458 time=241.7s + ttt_chunk [941/1893] bpb=1.177117 time=244.3s + ttt_chunk [951/1893] bpb=1.177530 time=246.9s + ttt_chunk [961/1893] bpb=1.177604 time=249.4s + ttt_chunk [971/1893] bpb=1.178510 time=252.0s + ttt_chunk [981/1893] bpb=1.178530 time=254.7s + ttt_chunk [991/1893] bpb=1.178516 time=257.3s + ttt_chunk [1001/1893] bpb=1.178461 time=259.8s + ttt_chunk [1011/1893] bpb=1.178253 time=262.4s + ttt_chunk [1021/1893] bpb=1.178563 time=265.0s + ttt_chunk [1031/1893] bpb=1.179015 time=267.6s + ttt_chunk [1041/1893] bpb=1.178665 time=270.2s + ttt_chunk [1051/1893] bpb=1.178417 time=272.8s + ttt_chunk [1061/1893] bpb=1.178514 time=275.4s + ttt_chunk [1071/1893] bpb=1.179125 time=278.0s + ttt_chunk [1081/1893] bpb=1.179427 time=280.6s + ttt_chunk [1091/1893] bpb=1.180088 time=283.2s + ttt_chunk [1101/1893] bpb=1.180082 time=285.8s + ttt_chunk [1111/1893] bpb=1.179912 time=288.4s + ttt_chunk [1121/1893] bpb=1.179704 time=291.0s + ttt_chunk [1131/1893] bpb=1.179536 time=293.6s + ttt_chunk [1141/1893] bpb=1.179222 time=296.2s + ttt_chunk [1151/1893] bpb=1.179201 time=298.7s + ttt_chunk [1161/1893] bpb=1.178799 time=301.3s + ttt_chunk [1171/1893] bpb=1.179071 time=303.9s + ttt_chunk [1181/1893] bpb=1.178296 time=306.6s + ttt_chunk [1191/1893] bpb=1.178151 time=309.1s + ttt_chunk [1201/1893] bpb=1.178534 time=311.8s + ttt_chunk [1211/1893] bpb=1.178041 time=314.3s + ttt_chunk [1221/1893] bpb=1.177708 time=316.9s + ttt_chunk [1231/1893] bpb=1.177408 time=319.5s + ttt_chunk [1241/1893] bpb=1.177049 time=322.1s + ttt_chunk [1251/1893] bpb=1.176426 time=324.7s + ttt_chunk [1261/1893] bpb=1.176386 time=327.3s + ttt_chunk [1271/1893] bpb=1.176009 time=329.8s + ttt_chunk [1281/1893] bpb=1.175780 time=332.4s + ttt_chunk [1291/1893] bpb=1.175534 time=335.0s + ttt_chunk [1301/1893] bpb=1.174899 time=337.6s + ttt_chunk [1311/1893] bpb=1.174474 time=340.2s + ttt_chunk [1321/1893] bpb=1.174106 time=342.8s + ttt_chunk [1331/1893] bpb=1.174013 time=345.4s + ttt_chunk [1341/1893] bpb=1.173875 time=348.0s + ttt_chunk [1351/1893] bpb=1.173821 time=350.5s + ttt_chunk [1361/1893] bpb=1.173861 time=353.2s + ttt_chunk [1371/1893] bpb=1.173737 time=355.8s + ttt_chunk [1381/1893] bpb=1.173739 time=358.3s + ttt_chunk [1391/1893] bpb=1.173347 time=360.9s + ttt_chunk [1401/1893] bpb=1.173330 time=363.5s + ttt_chunk [1411/1893] bpb=1.173451 time=366.1s + ttt_chunk [1421/1893] bpb=1.173726 time=368.7s + ttt_chunk [1431/1893] bpb=1.173466 time=371.3s + ttt_chunk [1441/1893] bpb=1.173988 time=373.9s + ttt_chunk [1451/1893] bpb=1.174322 time=376.5s + ttt_chunk [1461/1893] bpb=1.173871 time=379.0s + ttt_chunk [1471/1893] bpb=1.174907 time=381.6s + ttt_chunk [1481/1893] bpb=1.174434 time=384.2s + ttt_chunk [1491/1893] bpb=1.174261 time=386.8s + ttt_chunk [1501/1893] bpb=1.174216 time=389.4s + ttt_chunk [1511/1893] bpb=1.174252 time=392.0s + ttt_chunk [1521/1893] bpb=1.174285 time=394.6s + ttt_chunk [1531/1893] bpb=1.173795 time=397.1s + ttt_chunk [1541/1893] bpb=1.173626 time=399.7s + ttt_chunk [1551/1893] bpb=1.173971 time=402.3s + ttt_chunk [1561/1893] bpb=1.173996 time=404.9s + ttt_chunk [1571/1893] bpb=1.173831 time=407.5s + ttt_chunk [1581/1893] bpb=1.173938 time=410.1s + ttt_chunk [1591/1893] bpb=1.173794 time=412.7s + ttt_chunk [1601/1893] bpb=1.173960 time=415.3s + ttt_chunk [1611/1893] bpb=1.173876 time=417.9s + ttt_chunk [1621/1893] bpb=1.173476 time=420.4s + ttt_chunk [1631/1893] bpb=1.173802 time=423.0s + ttt_chunk [1641/1893] bpb=1.173826 time=425.6s + ttt_chunk [1651/1893] bpb=1.173758 time=428.2s + ttt_chunk [1661/1893] bpb=1.173657 time=430.8s + ttt_chunk [1671/1893] bpb=1.174141 time=433.4s + ttt_chunk [1681/1893] bpb=1.174280 time=435.9s + ttt_chunk [1691/1893] bpb=1.174090 time=438.5s + ttt_chunk [1701/1893] bpb=1.174238 time=441.1s + ttt_chunk [1711/1893] bpb=1.174218 time=443.7s + ttt_chunk [1721/1893] bpb=1.174208 time=446.3s + ttt_chunk [1731/1893] bpb=1.174068 time=448.9s + ttt_chunk [1741/1893] bpb=1.173877 time=451.5s + ttt_chunk [1751/1893] bpb=1.173685 time=454.1s + ttt_chunk [1761/1893] bpb=1.173834 time=456.7s + ttt_chunk [1771/1893] bpb=1.173735 time=459.2s + ttt_chunk [1781/1893] bpb=1.173774 time=461.8s + ttt_chunk [1791/1893] bpb=1.173320 time=464.4s + ttt_chunk [1801/1893] bpb=1.173188 time=467.0s + ttt_chunk [1811/1893] bpb=1.173082 time=469.6s + ttt_chunk [1821/1893] bpb=1.173130 time=472.1s + ttt_chunk [1831/1893] bpb=1.172494 time=474.7s + ttt_chunk [1841/1893] bpb=1.172534 time=477.3s + ttt_chunk [1851/1893] bpb=1.172313 time=479.9s + ttt_chunk [1861/1893] bpb=1.171928 time=482.5s + ttt_chunk [1871/1893] bpb=1.171894 time=485.1s + ttt_chunk [1881/1893] bpb=1.171418 time=487.6s + ttt_chunk [1891/1893] bpb=1.171180 time=490.2s + ttt_chunk [1893/1893] bpb=1.171227 time=490.6s +ttt_sliding:done val_loss=1.974235 val_bpb=1.169256 elapsed=490.6s +final_ttt_sliding val_loss:1.9742 val_bpb:1.1693 eval_time:491268ms diff --git a/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/seed42.log b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/seed42.log new file mode 100644 index 0000000000..5346c86ed7 --- /dev/null +++ b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/seed42.log @@ -0,0 +1,315 @@ +W0327 02:11:31.579000 55736 torch/distributed/run.py:803] +W0327 02:11:31.579000 55736 torch/distributed/run.py:803] ***************************************** +W0327 02:11:31.579000 55736 torch/distributed/run.py:803] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. +W0327 02:11:31.579000 55736 torch/distributed/run.py:803] ***************************************** +logs/7L_seed42.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_1024_bpe.model +train_loader:dataset:fineweb10B_sp1024 train_shards:80 +val_loader:shards pattern=./data/datasets/fineweb10B_sp1024/fineweb_val_*.bin tokens:62021632 +qat:enabled from step 0 attn=6bit +architecture:recursive num_blocks:4 num_loops:7 shared_block_params:27263104 per_loop_params:28672 +model_params:29950082 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:32 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:600.000 +seed:42 +warmup_step:10/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:6.9734 val_bpb:4.1300 train_time:0ms step_avg:0.02ms +step:1/20000 train_loss:6.9756 train_time:147ms step_avg:146.99ms +step:2/20000 train_loss:9.8732 train_time:168ms step_avg:83.93ms +step:3/20000 train_loss:8.6232 train_time:267ms step_avg:88.92ms +step:4/20000 train_loss:7.5045 train_time:367ms step_avg:91.71ms +step:5/20000 train_loss:6.7892 train_time:468ms step_avg:93.52ms +step:6/20000 train_loss:7.5672 train_time:568ms step_avg:94.69ms +step:7/20000 train_loss:6.2335 train_time:670ms step_avg:95.70ms +step:8/20000 train_loss:6.1498 train_time:770ms step_avg:96.28ms +step:9/20000 train_loss:5.9877 train_time:873ms step_avg:96.97ms +step:10/20000 train_loss:5.7212 train_time:972ms step_avg:97.23ms +step:100/20000 train_loss:3.3660 train_time:9982ms step_avg:99.82ms +step:200/20000 train_loss:2.8323 train_time:20091ms step_avg:100.45ms +step:300/20000 train_loss:2.4117 train_time:30172ms step_avg:100.57ms +step:400/20000 train_loss:2.2972 train_time:40299ms step_avg:100.75ms +step:500/20000 train_loss:2.4522 train_time:50371ms step_avg:100.74ms +step:500/20000 val_loss:2.4492 val_bpb:1.4506 train_time:50436ms step_avg:100.87ms +step:600/20000 train_loss:2.5082 train_time:60507ms step_avg:100.84ms +step:700/20000 train_loss:2.3928 train_time:70548ms step_avg:100.78ms +step:800/20000 train_loss:2.2297 train_time:80641ms step_avg:100.80ms +step:900/20000 train_loss:2.2886 train_time:90658ms step_avg:100.73ms +step:1000/20000 train_loss:2.3286 train_time:100719ms step_avg:100.72ms +step:1000/20000 val_loss:2.2780 val_bpb:1.3492 train_time:100783ms step_avg:100.78ms +step:1100/20000 train_loss:2.2017 train_time:110727ms step_avg:100.66ms +step:1200/20000 train_loss:2.3417 train_time:120788ms step_avg:100.66ms +step:1300/20000 train_loss:2.3141 train_time:130787ms step_avg:100.61ms +step:1400/20000 train_loss:2.3702 train_time:140847ms step_avg:100.60ms +step:1500/20000 train_loss:2.1683 train_time:150846ms step_avg:100.56ms +step:1500/20000 val_loss:2.2129 val_bpb:1.3106 train_time:150911ms step_avg:100.61ms +step:1600/20000 train_loss:2.0312 train_time:160913ms step_avg:100.57ms +step:1700/20000 train_loss:2.1148 train_time:170913ms step_avg:100.54ms +step:1800/20000 train_loss:2.1531 train_time:180975ms step_avg:100.54ms +step:1900/20000 train_loss:2.1417 train_time:190972ms step_avg:100.51ms +step:2000/20000 train_loss:2.1945 train_time:201022ms step_avg:100.51ms +step:2000/20000 val_loss:2.1801 val_bpb:1.2912 train_time:201086ms step_avg:100.54ms +step:2100/20000 train_loss:2.2157 train_time:211071ms step_avg:100.51ms +step:2200/20000 train_loss:2.0174 train_time:221066ms step_avg:100.48ms +step:2300/20000 train_loss:2.3212 train_time:231119ms step_avg:100.49ms +step:2400/20000 train_loss:2.1503 train_time:241114ms step_avg:100.46ms +step:2500/20000 train_loss:2.0844 train_time:251169ms step_avg:100.47ms +step:2500/20000 val_loss:2.1588 val_bpb:1.2786 train_time:251234ms step_avg:100.49ms +step:2600/20000 train_loss:2.3661 train_time:261166ms step_avg:100.45ms +step:2700/20000 train_loss:2.0986 train_time:271225ms step_avg:100.45ms +step:2800/20000 train_loss:2.1867 train_time:281224ms step_avg:100.44ms +step:2900/20000 train_loss:2.1299 train_time:291286ms step_avg:100.44ms +step:3000/20000 train_loss:2.1677 train_time:301287ms step_avg:100.43ms +step:3000/20000 val_loss:2.1340 val_bpb:1.2639 train_time:301351ms step_avg:100.45ms +step:3100/20000 train_loss:2.1383 train_time:311338ms step_avg:100.43ms +step:3200/20000 train_loss:2.1286 train_time:321339ms step_avg:100.42ms +step:3300/20000 train_loss:2.1734 train_time:331398ms step_avg:100.42ms +step:3400/20000 train_loss:2.0966 train_time:341398ms step_avg:100.41ms +step:3500/20000 train_loss:2.1860 train_time:351440ms step_avg:100.41ms +step:3500/20000 val_loss:2.1119 val_bpb:1.2508 train_time:351504ms step_avg:100.43ms +step:3600/20000 train_loss:2.0307 train_time:361429ms step_avg:100.40ms +step:3700/20000 train_loss:2.0601 train_time:371477ms step_avg:100.40ms +step:3800/20000 train_loss:2.1352 train_time:381480ms step_avg:100.39ms +step:3900/20000 train_loss:1.9033 train_time:391528ms step_avg:100.39ms +step:4000/20000 train_loss:2.0979 train_time:401529ms step_avg:100.38ms +step:4000/20000 val_loss:2.0886 val_bpb:1.2370 train_time:401594ms step_avg:100.40ms +step:4100/20000 train_loss:2.1036 train_time:411594ms step_avg:100.39ms +step:4200/20000 train_loss:2.0867 train_time:421731ms step_avg:100.41ms +step:4300/20000 train_loss:1.9284 train_time:431725ms step_avg:100.40ms +step:4400/20000 train_loss:2.0125 train_time:441775ms step_avg:100.40ms +step:4500/20000 train_loss:2.1712 train_time:451775ms step_avg:100.39ms +step:4500/20000 val_loss:2.0666 val_bpb:1.2240 train_time:451839ms step_avg:100.41ms +step:4600/20000 train_loss:1.8753 train_time:461823ms step_avg:100.40ms +step:4700/20000 train_loss:2.1690 train_time:471823ms step_avg:100.39ms +step:4800/20000 train_loss:2.1555 train_time:481872ms step_avg:100.39ms +step:4900/20000 train_loss:2.0658 train_time:491864ms step_avg:100.38ms +step:5000/20000 train_loss:1.9086 train_time:501915ms step_avg:100.38ms +step:5000/20000 val_loss:2.0421 val_bpb:1.2095 train_time:501979ms step_avg:100.40ms +step:5100/20000 train_loss:1.9077 train_time:511915ms step_avg:100.38ms +step:5200/20000 train_loss:2.0582 train_time:521965ms step_avg:100.38ms +step:5300/20000 train_loss:2.0828 train_time:531966ms step_avg:100.37ms +step:5400/20000 train_loss:2.0577 train_time:542196ms step_avg:100.41ms +step:5500/20000 train_loss:2.0167 train_time:552355ms step_avg:100.43ms +step:5500/20000 val_loss:2.0172 val_bpb:1.1947 train_time:552420ms step_avg:100.44ms +step:5600/20000 train_loss:2.0435 train_time:562565ms step_avg:100.46ms +step:5700/20000 train_loss:2.0372 train_time:572725ms step_avg:100.48ms +step:5800/20000 train_loss:1.9935 train_time:582935ms step_avg:100.51ms +step:5900/20000 train_loss:1.9573 train_time:593104ms step_avg:100.53ms +step:5967/20000 val_loss:1.9969 val_bpb:1.1827 train_time:600089ms step_avg:100.57ms +stopping_early: wallclock_cap train_time:600089ms step:5967/20000 +peak memory allocated: 15596 MiB reserved: 15762 MiB +swa:averaging 14 checkpoints +swa_eval val_loss:1.9959 val_bpb:1.1821 +Serialized model: 114835683 bytes +Code size: 68750 bytes +Total submission size: 114904433 bytes +Serialized model int8+zstd-22: 15778257 bytes (payload:30153220 raw_torch:30174423 payload_ratio:3.81x) +Total submission size int8+zlib: 15847007 bytes +final_int8_zlib_roundtrip val_loss:2.0175 val_bpb:1.1949 eval_time:3327ms +final_int8_zlib_roundtrip_exact val_loss:2.01746112 val_bpb:1.19485411 +ttt_sliding:start chunks=1893 chunk_tokens=32768 total_windows=969091 stride=64 +ttt_sliding:params unfrozen=23134306 frozen=6815776 + ttt_chunk [1/1893] bpb=1.206599 time=0.5s + ttt_chunk [11/1893] bpb=1.196791 time=3.0s + ttt_chunk [21/1893] bpb=1.182070 time=5.6s + ttt_chunk [31/1893] bpb=1.178727 time=8.2s + ttt_chunk [41/1893] bpb=1.165377 time=10.8s + ttt_chunk [51/1893] bpb=1.161278 time=13.4s + ttt_chunk [61/1893] bpb=1.168611 time=16.0s + ttt_chunk [71/1893] bpb=1.166771 time=18.5s + ttt_chunk [81/1893] bpb=1.165966 time=21.1s + ttt_chunk [91/1893] bpb=1.167193 time=23.7s + ttt_chunk [101/1893] bpb=1.170747 time=26.3s + ttt_chunk [111/1893] bpb=1.173328 time=28.9s + ttt_chunk [121/1893] bpb=1.166789 time=31.5s + ttt_chunk [131/1893] bpb=1.167289 time=34.1s + ttt_chunk [141/1893] bpb=1.172934 time=36.7s + ttt_chunk [151/1893] bpb=1.174753 time=39.3s + ttt_chunk [161/1893] bpb=1.174574 time=41.9s + ttt_chunk [171/1893] bpb=1.179461 time=44.5s + ttt_chunk [181/1893] bpb=1.181838 time=47.0s + ttt_chunk [191/1893] bpb=1.189184 time=49.6s + ttt_chunk [201/1893] bpb=1.188078 time=52.2s + ttt_chunk [211/1893] bpb=1.185989 time=54.8s + ttt_chunk [221/1893] bpb=1.187539 time=57.4s + ttt_chunk [231/1893] bpb=1.186162 time=60.0s + ttt_chunk [241/1893] bpb=1.186455 time=62.5s + ttt_chunk [251/1893] bpb=1.185893 time=65.1s + ttt_chunk [261/1893] bpb=1.182925 time=67.7s + ttt_chunk [271/1893] bpb=1.181691 time=70.3s + ttt_chunk [281/1893] bpb=1.183091 time=72.9s + ttt_chunk [291/1893] bpb=1.184913 time=75.4s + ttt_chunk [301/1893] bpb=1.185692 time=78.0s + ttt_chunk [311/1893] bpb=1.187762 time=80.6s + ttt_chunk [321/1893] bpb=1.189616 time=83.2s + ttt_chunk [331/1893] bpb=1.189505 time=85.8s + ttt_chunk [341/1893] bpb=1.188414 time=88.4s + ttt_chunk [351/1893] bpb=1.190804 time=90.9s + ttt_chunk [361/1893] bpb=1.191004 time=93.5s + ttt_chunk [371/1893] bpb=1.190145 time=96.1s + ttt_chunk [381/1893] bpb=1.190252 time=98.7s + ttt_chunk [391/1893] bpb=1.189991 time=101.3s + ttt_chunk [401/1893] bpb=1.187816 time=103.9s + ttt_chunk [411/1893] bpb=1.186642 time=106.5s + ttt_chunk [421/1893] bpb=1.185632 time=109.0s + ttt_chunk [431/1893] bpb=1.185485 time=111.6s + ttt_chunk [441/1893] bpb=1.185728 time=114.2s + ttt_chunk [451/1893] bpb=1.185950 time=116.8s + ttt_chunk [461/1893] bpb=1.184818 time=119.4s + ttt_chunk [471/1893] bpb=1.185320 time=121.9s + ttt_chunk [481/1893] bpb=1.184943 time=124.5s + ttt_chunk [491/1893] bpb=1.183808 time=127.1s + ttt_chunk [501/1893] bpb=1.183288 time=129.7s + ttt_chunk [511/1893] bpb=1.182648 time=132.3s + ttt_chunk [521/1893] bpb=1.180356 time=134.9s + ttt_chunk [531/1893] bpb=1.181456 time=137.4s + ttt_chunk [541/1893] bpb=1.181675 time=140.0s + ttt_chunk [551/1893] bpb=1.180527 time=142.6s + ttt_chunk [561/1893] bpb=1.180971 time=145.2s + ttt_chunk [571/1893] bpb=1.179915 time=147.8s + ttt_chunk [581/1893] bpb=1.179004 time=150.4s + ttt_chunk [591/1893] bpb=1.178285 time=153.0s + ttt_chunk [601/1893] bpb=1.178720 time=155.6s + ttt_chunk [611/1893] bpb=1.178583 time=158.1s + ttt_chunk [621/1893] bpb=1.178406 time=160.7s + ttt_chunk [631/1893] bpb=1.179082 time=163.3s + ttt_chunk [641/1893] bpb=1.178773 time=165.9s + ttt_chunk [651/1893] bpb=1.178809 time=168.4s + ttt_chunk [661/1893] bpb=1.178210 time=171.0s + ttt_chunk [671/1893] bpb=1.178525 time=173.6s + ttt_chunk [681/1893] bpb=1.179221 time=176.2s + ttt_chunk [691/1893] bpb=1.180184 time=178.8s + ttt_chunk [701/1893] bpb=1.179602 time=181.4s + ttt_chunk [711/1893] bpb=1.179629 time=184.0s + ttt_chunk [721/1893] bpb=1.179271 time=186.5s + ttt_chunk [731/1893] bpb=1.179340 time=189.1s + ttt_chunk [741/1893] bpb=1.179431 time=191.7s + ttt_chunk [751/1893] bpb=1.179262 time=194.3s + ttt_chunk [761/1893] bpb=1.179224 time=196.9s + ttt_chunk [771/1893] bpb=1.178871 time=199.5s + ttt_chunk [781/1893] bpb=1.179617 time=202.0s + ttt_chunk [791/1893] bpb=1.179212 time=204.6s + ttt_chunk [801/1893] bpb=1.179512 time=207.2s + ttt_chunk [811/1893] bpb=1.179353 time=209.8s + ttt_chunk [821/1893] bpb=1.179163 time=212.4s + ttt_chunk [831/1893] bpb=1.179026 time=215.0s + ttt_chunk [841/1893] bpb=1.178339 time=217.6s + ttt_chunk [851/1893] bpb=1.178136 time=220.2s + ttt_chunk [861/1893] bpb=1.177888 time=222.8s + ttt_chunk [871/1893] bpb=1.178180 time=225.3s + ttt_chunk [881/1893] bpb=1.178419 time=227.9s + ttt_chunk [891/1893] bpb=1.177988 time=230.5s + ttt_chunk [901/1893] bpb=1.177735 time=233.1s + ttt_chunk [911/1893] bpb=1.177892 time=235.7s + ttt_chunk [921/1893] bpb=1.178368 time=238.2s + ttt_chunk [931/1893] bpb=1.178296 time=240.8s + ttt_chunk [941/1893] bpb=1.177953 time=243.4s + ttt_chunk [951/1893] bpb=1.178356 time=246.0s + ttt_chunk [961/1893] bpb=1.178421 time=248.6s + ttt_chunk [971/1893] bpb=1.179292 time=251.1s + ttt_chunk [981/1893] bpb=1.179343 time=253.7s + ttt_chunk [991/1893] bpb=1.179340 time=256.3s + ttt_chunk [1001/1893] bpb=1.179301 time=258.9s + ttt_chunk [1011/1893] bpb=1.179083 time=261.5s + ttt_chunk [1021/1893] bpb=1.179402 time=264.0s + ttt_chunk [1031/1893] bpb=1.179865 time=266.6s + ttt_chunk [1041/1893] bpb=1.179475 time=269.2s + ttt_chunk [1051/1893] bpb=1.179197 time=271.8s + ttt_chunk [1061/1893] bpb=1.179257 time=274.4s + ttt_chunk [1071/1893] bpb=1.179885 time=277.0s + ttt_chunk [1081/1893] bpb=1.180153 time=279.5s + ttt_chunk [1091/1893] bpb=1.180830 time=282.1s + ttt_chunk [1101/1893] bpb=1.180803 time=284.7s + ttt_chunk [1111/1893] bpb=1.180629 time=287.3s + ttt_chunk [1121/1893] bpb=1.180413 time=289.9s + ttt_chunk [1131/1893] bpb=1.180256 time=292.5s + ttt_chunk [1141/1893] bpb=1.179937 time=295.0s + ttt_chunk [1151/1893] bpb=1.179909 time=297.6s + ttt_chunk [1161/1893] bpb=1.179514 time=300.2s + ttt_chunk [1171/1893] bpb=1.179784 time=302.8s + ttt_chunk [1181/1893] bpb=1.179009 time=305.4s + ttt_chunk [1191/1893] bpb=1.178870 time=307.9s + ttt_chunk [1201/1893] bpb=1.179240 time=310.5s + ttt_chunk [1211/1893] bpb=1.178728 time=313.1s + ttt_chunk [1221/1893] bpb=1.178410 time=315.7s + ttt_chunk [1231/1893] bpb=1.178093 time=318.3s + ttt_chunk [1241/1893] bpb=1.177716 time=320.9s + ttt_chunk [1251/1893] bpb=1.177115 time=323.5s + ttt_chunk [1261/1893] bpb=1.177060 time=326.1s + ttt_chunk [1271/1893] bpb=1.176695 time=328.7s + ttt_chunk [1281/1893] bpb=1.176513 time=331.2s + ttt_chunk [1291/1893] bpb=1.176289 time=333.8s + ttt_chunk [1301/1893] bpb=1.175664 time=336.4s + ttt_chunk [1311/1893] bpb=1.175254 time=339.0s + ttt_chunk [1321/1893] bpb=1.174887 time=341.6s + ttt_chunk [1331/1893] bpb=1.174799 time=344.2s + ttt_chunk [1341/1893] bpb=1.174649 time=346.8s + ttt_chunk [1351/1893] bpb=1.174589 time=349.3s + ttt_chunk [1361/1893] bpb=1.174637 time=351.9s + ttt_chunk [1371/1893] bpb=1.174519 time=354.5s + ttt_chunk [1381/1893] bpb=1.174521 time=357.2s + ttt_chunk [1391/1893] bpb=1.174109 time=359.7s + ttt_chunk [1401/1893] bpb=1.174091 time=362.3s + ttt_chunk [1411/1893] bpb=1.174208 time=364.9s + ttt_chunk [1421/1893] bpb=1.174485 time=367.4s + ttt_chunk [1431/1893] bpb=1.174226 time=370.0s + ttt_chunk [1441/1893] bpb=1.174745 time=372.6s + ttt_chunk [1451/1893] bpb=1.175086 time=375.1s + ttt_chunk [1461/1893] bpb=1.174653 time=377.7s + ttt_chunk [1471/1893] bpb=1.175687 time=380.3s + ttt_chunk [1481/1893] bpb=1.175218 time=382.9s + ttt_chunk [1491/1893] bpb=1.175055 time=385.5s + ttt_chunk [1501/1893] bpb=1.175014 time=388.0s + ttt_chunk [1511/1893] bpb=1.175035 time=390.6s + ttt_chunk [1521/1893] bpb=1.175036 time=393.2s + ttt_chunk [1531/1893] bpb=1.174539 time=395.8s + ttt_chunk [1541/1893] bpb=1.174393 time=398.3s + ttt_chunk [1551/1893] bpb=1.174728 time=400.9s + ttt_chunk [1561/1893] bpb=1.174762 time=403.5s + ttt_chunk [1571/1893] bpb=1.174616 time=406.1s + ttt_chunk [1581/1893] bpb=1.174736 time=408.6s + ttt_chunk [1591/1893] bpb=1.174590 time=411.2s + ttt_chunk [1601/1893] bpb=1.174746 time=413.8s + ttt_chunk [1611/1893] bpb=1.174651 time=416.4s + ttt_chunk [1621/1893] bpb=1.174229 time=418.9s + ttt_chunk [1631/1893] bpb=1.174547 time=421.5s + ttt_chunk [1641/1893] bpb=1.174568 time=424.1s + ttt_chunk [1651/1893] bpb=1.174508 time=426.6s + ttt_chunk [1661/1893] bpb=1.174395 time=429.2s + ttt_chunk [1671/1893] bpb=1.174868 time=431.8s + ttt_chunk [1681/1893] bpb=1.174993 time=434.3s + ttt_chunk [1691/1893] bpb=1.174800 time=436.9s + ttt_chunk [1701/1893] bpb=1.174950 time=439.5s + ttt_chunk [1711/1893] bpb=1.174935 time=442.0s + ttt_chunk [1721/1893] bpb=1.174912 time=444.6s + ttt_chunk [1731/1893] bpb=1.174778 time=447.2s + ttt_chunk [1741/1893] bpb=1.174589 time=449.8s + ttt_chunk [1751/1893] bpb=1.174407 time=452.3s + ttt_chunk [1761/1893] bpb=1.174553 time=454.9s + ttt_chunk [1771/1893] bpb=1.174475 time=457.5s + ttt_chunk [1781/1893] bpb=1.174521 time=460.1s + ttt_chunk [1791/1893] bpb=1.174090 time=462.6s + ttt_chunk [1801/1893] bpb=1.173955 time=465.2s + ttt_chunk [1811/1893] bpb=1.173855 time=467.8s + ttt_chunk [1821/1893] bpb=1.173906 time=470.4s + ttt_chunk [1831/1893] bpb=1.173281 time=473.0s + ttt_chunk [1841/1893] bpb=1.173312 time=475.5s + ttt_chunk [1851/1893] bpb=1.173097 time=478.1s + ttt_chunk [1861/1893] bpb=1.172712 time=480.7s + ttt_chunk [1871/1893] bpb=1.172682 time=483.3s + ttt_chunk [1881/1893] bpb=1.172208 time=485.9s + ttt_chunk [1891/1893] bpb=1.171965 time=488.5s + ttt_chunk [1893/1893] bpb=1.172013 time=488.8s +ttt_sliding:done val_loss=1.974980 val_bpb=1.169697 elapsed=488.9s +final_ttt_sliding val_loss:1.9750 val_bpb:1.1697 eval_time:489501ms diff --git a/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/submission.json b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/submission.json new file mode 100644 index 0000000000..3ff6e5b6d7 --- /dev/null +++ b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/submission.json @@ -0,0 +1,11 @@ +{ + "author": "Khoa Phan", + "github_id": "Tonyy1977", + "name": "Recursive Transformer 4B/7L + VE + QAT Int6 + Score-First TTT", + "blurb": "Novel recursive/looped transformer: 4 shared blocks applied 7 times in a U-Net encoder-decoder pattern with skip connections. ValueEmbedding reinjects token identity into attention. Int6 QAT from step 0 via STE. Score-first TTT+sliding window eval. 30M params at dim=1024 vs standard 512.", + "date": "2026-03-27T00:00:00Z", + "val_loss": 1.9748, + "val_bpb": 1.1696, + "bytes_total": 15847007, + "bytes_code": 68750 +} diff --git a/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/train_gpt.py b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/train_gpt.py new file mode 100644 index 0000000000..0068efbda6 --- /dev/null +++ b/records/track_10min_16mb/2026-03-26_RecursiveTransformer_4B7L_VE_QAT_TTT/train_gpt.py @@ -0,0 +1,1572 @@ +from __future__ import annotations + +import copy +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import uuid +import zlib +from pathlib import Path + +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 + +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", 1337)) + + 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", 1200)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 524_288)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 1024)) + 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_blocks = int(os.environ.get("NUM_BLOCKS", 2)) + num_loops = int(os.environ.get("NUM_LOOPS", 12)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 8)) + model_dim = int(os.environ.get("MODEL_DIM", 1024)) + num_heads = int(os.environ.get("NUM_HEADS", 16)) + mlp_mult = int(os.environ.get("MLP_MULT", 2)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + use_smear_gate = bool(int(os.environ.get("USE_SMEAR_GATE", "1"))) + qat_enabled = bool(int(os.environ.get("QAT_ENABLED", "0"))) + qat_bits = int(os.environ.get("QAT_BITS", 6)) + qat_mlp_bits = int(os.environ.get("QAT_MLP_BITS", 0)) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", 0.15)) + bigram_buckets = int(os.environ.get("BIGRAM_BUCKETS", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + embed_bottleneck = int(os.environ.get("EMBED_BOTTLENECK", 0)) + ve_enabled = bool(int(os.environ.get("VE_ENABLED", "0"))) + ve_dim = int(os.environ.get("VE_DIM", 128)) + ve_last_n = int(os.environ.get("VE_LAST_N", 2)) + + 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.02)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.008)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.01)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.95)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float(os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.85)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 1.0)) + weight_decay = float(os.environ.get("WEIGHT_DECAY", 0.0)) + resume_from = os.environ.get("RESUME_FROM", "") + + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.0)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + + ema_decay = float(os.environ.get("EMA_DECAY", 0.0)) + + sliding_window_stride = int(os.environ.get("SLIDING_WINDOW_STRIDE", 0)) + + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "0"))) + ttt_lr = float(os.environ.get("TTT_LR", 0.002)) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", 3)) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 1)) + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", 0.9)) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", 32)) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", 1.0)) + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 10, eps: float = 1e-7) -> Tensor: + a, b, c = (3.4445, -4.7750, 2.0315) + X = G.bfloat16() + X /= X.norm() + eps + transposed = G.size(0) > G.size(1) + if transposed: + X = X.T + for _ in range(steps): + A = X @ X.T + B = b * A + c * A @ A + X = a * X + B @ X + return X.T if transposed else X + +class Muon(torch.optim.Optimizer): + def __init__(self, params, lr: float, momentum: float, backend_steps: int, nesterov: bool = True, weight_decay: float = 0.0): + super().__init__( + params, + dict(lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov, weight_decay=weight_decay), + ) + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + distributed = dist.is_available() and dist.is_initialized() + world_size = dist.get_world_size() if distributed else 1 + rank = dist.get_rank() if distributed else 0 + + for group in self.param_groups: + params = group["params"] + if not params: + continue + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + + total_params = sum(int(p.numel()) for p in params) + updates_flat = torch.zeros(total_params, device=params[0].device, dtype=torch.bfloat16) + + curr = 0 + for i, p in enumerate(params): + if i % world_size == rank and p.grad is not None: + g = p.grad + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(g) + if nesterov: + g = g.add(buf, alpha=momentum) + g = zeropower_via_newtonschulz5(g, steps=backend_steps) + g *= max(1, g.size(0) / g.size(1)) ** 0.5 + updates_flat[curr : curr + p.numel()] = g.reshape(-1) + curr += p.numel() + + if distributed: + dist.all_reduce(updates_flat, op=dist.ReduceOp.SUM) + + wd = group.get("weight_decay", 0.0) + curr = 0 + for p in params: + g = updates_flat[curr : curr + p.numel()].view_as(p).to(dtype=p.dtype) + p.add_(g, alpha=-lr) + if wd > 0: + p.mul_(1.0 - lr * wd) + curr += p.numel() + + return loss + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("▁"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return ( + torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device), + ) + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError( + "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) + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scales,mlp_scales,resid_mixes,q_gain,smear,skip_weights", + ).split(",") + if pattern +) +INT8_KEEP_FLOAT_FP32_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "INT8_KEEP_FLOAT_FP32_NAME_PATTERNS", + ",".join(CONTROL_TENSOR_NAME_PATTERNS), + ).split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 +INT8_KEEP_FLOAT_STORE_DTYPE = torch.float16 +INT8_PER_ROW_SCALE_DTYPE = torch.float16 +INT8_CLIP_PERCENTILE = 99.99984 +INT8_CLIP_Q = INT8_CLIP_PERCENTILE / 100.0 + +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def keep_float_tensor(name: str, t: Tensor, passthrough_orig_dtypes: dict[str, str]) -> Tensor: + if any(pattern in name for pattern in INT8_KEEP_FLOAT_FP32_NAME_PATTERNS): + return t.float().contiguous() + if t.dtype in {torch.float32, torch.bfloat16}: + passthrough_orig_dtypes[name] = str(t.dtype).removeprefix("torch.") + return t.to(dtype=INT8_KEEP_FLOAT_STORE_DTYPE).contiguous() + return t + +def _is_attn_weight(name: str) -> bool: + return any(k in name for k in ("c_q.weight", "c_k.weight", "c_v.weight", "attn.proj.weight")) + +GPTQ_PERCENTILES = [0.9999, 0.99995, 0.99999, 0.999995, 0.999999] + +def quantize_float_tensor(t: Tensor, n_bits: int = 8) -> tuple[Tensor, Tensor]: + max_val = 2 ** (n_bits - 1) - 1 + min_val = -(2 ** (n_bits - 1)) + t32 = t.float() + if t32.ndim == 2: + best_q = None + best_scale = None + best_err = None + for pct in GPTQ_PERCENTILES: + clip_abs = ( + torch.quantile(t32.abs(), pct, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + scale = (clip_abs / max_val).clamp_min(1.0 / max_val) + q = torch.clamp(torch.round(t32 / scale[:, None]), min_val, max_val).to(torch.int8) + recon = q.float() * scale[:, None] + err = (t32 - recon).pow(2).sum(dim=1) + if best_err is None: + best_q = q + best_scale = scale + best_err = err + else: + improved = err < best_err + if improved.any(): + best_q[improved] = q[improved] + best_scale[improved] = scale[improved] + best_err[improved] = err[improved] + return best_q.contiguous(), best_scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous() + + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / max_val if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), min_val, max_val).to(torch.int8).contiguous() + return q, scale + +def quantize_state_dict_int8(state_dict: dict[str, Tensor], qat_bits: int = 8, qat_mlp_bits: int = 0): + quantized: dict[str, Tensor] = {} + scales: dict[str, Tensor] = {} + dtypes: dict[str, str] = {} + passthrough: dict[str, Tensor] = {} + passthrough_orig_dtypes: dict[str, str] = {} + qmeta: dict[str, dict[str, object]] = {} + stats = dict.fromkeys( + ("param_count", "num_tensors", "num_float_tensors", "num_nonfloat_tensors", "baseline_tensor_bytes", "int8_payload_bytes"), + 0, + ) + + for name, tensor in state_dict.items(): + t = tensor.detach().to("cpu").contiguous() + stats["param_count"] += int(t.numel()) + stats["num_tensors"] += 1 + stats["baseline_tensor_bytes"] += tensor_nbytes(t) + + if not t.is_floating_point(): + stats["num_nonfloat_tensors"] += 1 + passthrough[name] = t + stats["int8_payload_bytes"] += tensor_nbytes(t) + continue + + if t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + kept = keep_float_tensor(name, t, passthrough_orig_dtypes) + passthrough[name] = kept + stats["int8_payload_bytes"] += tensor_nbytes(kept) + continue + + stats["num_float_tensors"] += 1 + is_block_weight = any(k in name for k in ("shared_blocks.", "bigram.proj.")) + is_mlp_weight = any(k in name for k in ("mlp.fc.weight", "mlp.proj.weight")) + if qat_bits < 8 and is_block_weight and t.ndim == 2: + n_bits = (qat_mlp_bits if (qat_mlp_bits > 0 and is_mlp_weight) else qat_bits) + else: + n_bits = 8 + q, s = quantize_float_tensor(t, n_bits=n_bits) + if s.ndim > 0: + qmeta[name] = {"scheme": "per_row", "axis": 0} + quantized[name] = q + scales[name] = s + dtypes[name] = str(t.dtype).removeprefix("torch.") + stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + obj: dict[str, object] = { + "__quant_format__": "int8_clean_per_row_v1", + "quantized": quantized, + "scales": scales, + "dtypes": dtypes, + "passthrough": passthrough, + } + if qmeta: + obj["qmeta"] = qmeta + if passthrough_orig_dtypes: + obj["passthrough_orig_dtypes"] = passthrough_orig_dtypes + return obj, stats + +def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + qmeta = obj.get("qmeta", {}) + passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {}) + for name, q in obj["quantized"].items(): + dtype = getattr(torch, obj["dtypes"][name]) + s = obj["scales"][name] + if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: + s = s.to(dtype=torch.float32) + 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 + +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) + +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) + +def _fake_quantize_ste(w: Tensor, n_bits: int) -> Tensor: + max_val = 2 ** (n_bits - 1) - 1 + min_val = -(2 ** (n_bits - 1)) + scale = w.abs().amax(dim=-1, keepdim=True) / max_val + scale = scale.clamp_min(1e-8) + w_q = (w / scale).round().clamp(min_val, max_val) * scale + return w + (w_q - w).detach() + +_QAT_ENABLED = False +_QAT_BITS = 6 +_QAT_MLP_BITS = 0 + +class CastedLinear(nn.Linear): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._is_mlp = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if _QAT_ENABLED and self.weight.ndim == 2 and self.weight.numel() > 65536: + bits = (_QAT_MLP_BITS if (_QAT_MLP_BITS > 0 and self._is_mlp) else _QAT_BITS) + w = _fake_quantize_ste(w, bits) + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0): + super().__init__() + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + +class CausalSelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int, + rope_base: float, + qk_gain_init: float, + ): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + 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(3) + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, q_delta=None, v_delta=None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x) + (q_delta if q_delta is not None else 0) + k = self.c_k(x) + v = self.c_v(x) + (v_delta if v_delta is not None else 0) + q = q.reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = k.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = v.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + rope_dim = cos.size(-1) + partial = rope_dim // 2 + if partial > 0: + q_rope, q_pass = q[..., :partial*2], q[..., partial*2:] + k_rope, k_pass = k[..., :partial*2], k[..., partial*2:] + q_rope = apply_rotary_emb(q_rope, cos[..., :partial], sin[..., :partial]) + k_rope = apply_rotary_emb(k_rope, cos[..., :partial], sin[..., :partial]) + q = torch.cat([q_rope, q_pass], dim=-1) + k = torch.cat([k_rope, k_pass], dim=-1) + else: + 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 = self._xsa_efficient(y.transpose(1, 2), v.transpose(1, 2)).contiguous().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): + super().__init__() + hidden = mlp_mult * dim + self.fc = CastedLinear(dim, hidden, bias=False) + self.fc._is_mlp = True + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + self.proj._is_mlp = True + + def forward(self, x: Tensor) -> Tensor: + x = torch.relu(self.fc(x)) + return self.proj(x.square()) + +class ValueEmbedding(nn.Module): + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int, num_loops_active: int): + super().__init__() + self.table = nn.Embedding(vocab_size, ve_dim) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) + self.scales = nn.ParameterList([nn.Parameter(torch.ones(1)) for _ in range(num_loops_active)]) + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor, loop_idx: int) -> Tensor: + return self.scales[loop_idx] * self.proj(self.table(input_ids)) + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate).to(dtype=x.dtype) + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1.0 - g) * x + g * x_prev + +class BigramHashEmbedding(nn.Module): + def __init__(self, num_buckets: int, hash_dim: int, model_dim: int): + super().__init__() + self.num_buckets = num_buckets + self.table = nn.Embedding(num_buckets, hash_dim) + self.proj = CastedLinear(hash_dim, model_dim, bias=False) + self.proj._zero_init = True + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor) -> Tensor: + bsz, seqlen = input_ids.shape + prev_ids = torch.cat([ + torch.zeros(bsz, 1, dtype=input_ids.dtype, device=input_ids.device), + input_ids[:, :-1], + ], dim=1) + h = ((prev_ids.long() * 92821 + input_ids.long()) % self.num_buckets).long() + return self.proj(self.table(h)) + +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, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init) + self.mlp = MLP(dim, mlp_mult) + + def forward( + self, x: Tensor, x0: Tensor, + attn_scale: Tensor, mlp_scale: Tensor, resid_mix: Tensor, + q_delta_fn=None, v_delta_fn=None, v_embed=None, + ) -> Tensor: + mix = resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + n = self.attn_norm(x) + qd = q_delta_fn(n) if q_delta_fn is not None else None + vd = v_delta_fn(n) if v_delta_fn is not None else None + if v_embed is not None: + vd = (vd + v_embed) if vd is not None else v_embed + attn_out = self.attn(n, qd, vd) + x = x + attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x)) + return x + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_blocks: int, + num_loops: 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, + use_smear_gate: bool = True, + bigram_buckets: int = 10240, + bigram_dim: int = 128, + embed_bottleneck: int = 0, + ve_enabled: bool = False, + ve_dim: int = 128, + ve_last_n: int = 2, + ): + 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.embed_bottleneck = embed_bottleneck + self.num_blocks = num_blocks + self.num_loops = num_loops + if embed_bottleneck > 0: + self.tok_emb = nn.Embedding(vocab_size, embed_bottleneck) + self.embed_proj = CastedLinear(embed_bottleneck, model_dim, bias=False) + self.embed_proj_rev = CastedLinear(model_dim, embed_bottleneck, bias=False) + else: + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.embed_proj = None + self.embed_proj_rev = None + self.bigram = BigramHashEmbedding(bigram_buckets, bigram_dim, model_dim) + self.smear = SmearGate(model_dim) if use_smear_gate else None + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve = ValueEmbedding(vocab_size, ve_dim, kv_dim, ve_last_n) if ve_enabled else None + self.ve_last_n = ve_last_n + self.shared_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_blocks) + ]) + self.attn_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.mlp_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.resid_mixes = nn.Parameter( + torch.stack([ + torch.stack((torch.ones(model_dim), torch.zeros(model_dim))) + for _ in range(num_loops) + ]).float() + ) + self.num_encoder_loops = num_loops // 2 + self.num_decoder_loops = num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + self.skip_weights = nn.Parameter(torch.ones(self.num_skips, model_dim, dtype=torch.float32)) + self.xsa_last_n = int(os.environ.get("XSA_LAST_N", 0)) + 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) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and min(module.weight.shape) >= 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 * self.num_loops)) + + def _embed(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.embed_proj is not None: + x = self.embed_proj(x) + return x + + def _logits(self, x: Tensor) -> Tensor: + if self.embed_proj_rev is not None: + x = self.embed_proj_rev(x) + logits = F.linear(x, self.tok_emb.weight) + elif self.tie_embeddings: + logits = F.linear(x, self.tok_emb.weight) + else: + logits = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits / self.logit_softcap) + + def forward(self, input_ids: Tensor, target_ids: Tensor, lora=None) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + + if self.xsa_last_n > 0: + for i in range(self.num_loops): + block = self.shared_blocks[i % self.num_blocks] + block.attn.use_xsa = (i >= self.num_loops - self.xsa_last_n) + + skips: list[Tensor] = [] + for i in range(self.num_encoder_loops): + qd = lora.q_loras[i] if lora else None + vd = lora.v_loras[i] if lora else None + ve = None + if self.ve is not None and i >= self.num_loops - self.ve_last_n: + ve_idx = i - (self.num_loops - self.ve_last_n) + ve = self.ve(input_ids, ve_idx) + x = self.shared_blocks[i % self.num_blocks]( + x, x0, + self.attn_scales[i], self.mlp_scales[i], self.resid_mixes[i], + qd, vd, v_embed=ve, + ) + skips.append(x) + for i in range(self.num_decoder_loops): + di = self.num_encoder_loops + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + qd = lora.q_loras[di] if lora else None + vd = lora.v_loras[di] if lora else None + ve = None + if self.ve is not None and di >= self.num_loops - self.ve_last_n: + ve_idx = di - (self.num_loops - self.ve_last_n) + ve = self.ve(input_ids, ve_idx) + x = self.shared_blocks[di % self.num_blocks]( + x, x0, + self.attn_scales[di], self.mlp_scales[di], self.resid_mixes[di], + qd, vd, v_embed=ve, + ) + x = self.final_norm(x) + logits = self._logits(x) + logits = logits + (lora.lm_head_lora(x) if lora else 0) + if lora: + bsz, sl, V = logits.shape + return F.cross_entropy( + logits.float().reshape(-1, V), target_ids.reshape(-1), reduction="none").reshape(bsz, sl) + return F.cross_entropy(logits.float().reshape(-1, logits.size(-1)), target_ids.reshape(-1), reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + + if self.xsa_last_n > 0: + for i in range(self.num_loops): + block = self.shared_blocks[i % self.num_blocks] + block.attn.use_xsa = (i >= self.num_loops - self.xsa_last_n) + + skips: list[Tensor] = [] + for i in range(self.num_encoder_loops): + ve = None + if self.ve is not None and i >= self.num_loops - self.ve_last_n: + ve = self.ve(input_ids, i - (self.num_loops - self.ve_last_n)) + x = self.shared_blocks[i % self.num_blocks]( + x, x0, + self.attn_scales[i], self.mlp_scales[i], self.resid_mixes[i], + v_embed=ve, + ) + skips.append(x) + for i in range(self.num_decoder_loops): + di = self.num_encoder_loops + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + ve = None + if self.ve is not None and di >= self.num_loops - self.ve_last_n: + ve = self.ve(input_ids, di - (self.num_loops - self.ve_last_n)) + x = self.shared_blocks[di % self.num_blocks]( + x, x0, + self.attn_scales[di], self.mlp_scales[di], self.resid_mixes[di], + v_embed=ve, + ) + x = self.final_norm(x) + return self._logits(x) + +def _compute_chunk_window(ci: int, pred_len: int, num_chunks: int, chunk_size: int, eval_seq_len: int): + chunk_start = ci * chunk_size + chunk_end = pred_len if ci == num_chunks - 1 else (ci + 1) * chunk_size + win_start = max(0, chunk_end - eval_seq_len) + win_len = chunk_end - win_start + chunk_offset = chunk_start - win_start + chunk_len = chunk_end - chunk_start + return win_start, win_len, chunk_offset, chunk_len + +def _accumulate_bpb( + ptl: Tensor, x: Tensor, y: Tensor, + batch_i: int, chunk_offset: int, chunk_len: int, + base_bytes_lut: Tensor, has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + loss_sum: Tensor, byte_sum: Tensor, token_count: Tensor, +): + lbl = ptl[batch_i, chunk_offset:chunk_offset + chunk_len].to(torch.float64) + prev = x[batch_i, chunk_offset:chunk_offset + chunk_len] + tgt = y[batch_i, chunk_offset:chunk_offset + chunk_len] + tok_bytes = base_bytes_lut[tgt].to(torch.float64) + tok_bytes += has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev] + loss_sum += lbl.sum() + byte_sum += tok_bytes.sum() + token_count += chunk_len + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: GPT, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + 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}") + + 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_blocks = min(args.ttt_freeze_blocks, base_model.num_blocks) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = False + for bi in range(freeze_blocks): + if f"shared_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)}") + + 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 + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + 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 = [] + 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) + loss_sum += nll[i, s:wlen].to(torch.float64).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() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + 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) + start_tok = chunk_start + (my_seq_s + bs) * seq_len + end_tok = chunk_start + (my_seq_s + 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) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or is_last_chunk): + 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)) + 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 + +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 = "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) + + 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}") + + base_model = GPT( + vocab_size=args.vocab_size, + num_blocks=args.num_blocks, + num_loops=args.num_loops, + 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, + use_smear_gate=args.use_smear_gate, + bigram_buckets=args.bigram_buckets, + bigram_dim=args.bigram_dim, + embed_bottleneck=args.embed_bottleneck, + ve_enabled=args.ve_enabled, + ve_dim=args.ve_dim, + ve_last_n=args.ve_last_n, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + if isinstance(module, Rotary): + module.inv_freq.data = module.inv_freq.data.float() + restore_low_dim_params_to_fp32(base_model) + + if args.resume_from and os.path.isfile(args.resume_from): + log0(f"resuming_from:{args.resume_from}") + saved = torch.load(args.resume_from, map_location=device) + base_model.load_state_dict(saved, strict=True) + restore_low_dim_params_to_fp32(base_model) + log0("resume:loaded model weights (optimizer states reset)") + global _QAT_ENABLED, _QAT_BITS, _QAT_MLP_BITS + _QAT_BITS = args.qat_bits + _QAT_MLP_BITS = args.qat_mlp_bits + _qat_activated = False + if args.qat_enabled and args.late_qat_threshold >= 1.0: + _QAT_ENABLED = True + _qat_activated = True + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:enabled from step 0 attn={_QAT_BITS}bit{mlp_info}") + elif args.qat_enabled: + _QAT_ENABLED = False + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:late_start threshold={args.late_qat_threshold} attn={_QAT_BITS}bit{mlp_info}") + else: + _QAT_ENABLED = False + 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 + + block_named_params = list(base_model.shared_blocks.named_parameters()) + matrix_params = [ + p + for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p + for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params.append(base_model.attn_scales) + scalar_params.append(base_model.mlp_scales) + scalar_params.append(base_model.resid_mixes) + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + if base_model.smear is not None: + scalar_params.append(base_model.smear.gate) + bigram_named = list(base_model.bigram.named_parameters()) + for name, p in bigram_named: + if p.ndim == 2 and "proj" in name: + matrix_params.append(p) + elif p.ndim == 2: + pass + else: + scalar_params.append(p) + ve_table_params = [] + if base_model.ve is not None: + for name, p in base_model.ve.named_parameters(): + if "table" in name: + ve_table_params.append(p) + elif p.ndim == 2: + matrix_params.append(p) + else: + scalar_params.append(p) + 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, base_model.bigram.table.weight] + + ([base_model.embed_proj.weight, base_model.embed_proj_rev.weight] if base_model.embed_proj is not None else []) + + ve_table_params, + "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.weight_decay, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + shared_block_params = sum(p.numel() for p in base_model.shared_blocks.parameters()) + loop_params = base_model.attn_scales.numel() + base_model.mlp_scales.numel() + base_model.resid_mixes.numel() + log0(f"architecture:recursive num_blocks:{args.num_blocks} num_loops:{args.num_loops} shared_block_params:{shared_block_params} per_loop_params:{loop_params}") + log0(f"model_params:{n_params}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + 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) + + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_checkpoints: list[dict[str, Tensor]] = [] + ema_sd: dict[str, Tensor] | None = None + if args.ema_decay > 0: + ema_sd = {k: v.detach().float().clone() for k, v in base_model.state_dict().items()} + log0(f"ema:enabled decay={args.ema_decay}") + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_activated and scale <= args.late_qat_threshold: + _QAT_ENABLED = True + _qat_activated = True + log0(f"late_qat:activated at step {step} scale={scale:.4f} threshold={args.late_qat_threshold}") + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + if args.swa_start_frac > 0 and step % args.swa_every == 0: + should_collect = torch.tensor(int(scale < args.swa_start_frac), device=device) + if distributed: + dist.all_reduce(should_collect, op=dist.ReduceOp.MIN) + if should_collect.item(): + swa_checkpoints.append({k: v.detach().cpu().clone() for k, v in base_model.state_dict().items()}) + + if ema_sd is not None: + d = args.ema_decay + with torch.no_grad(): + for k, v in base_model.state_dict().items(): + ema_sd[k].mul_(d).add_(v.detach().float(), alpha=1.0 - d) + + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + _QAT_ENABLED = False + + if swa_checkpoints: + log0(f"swa:averaging {len(swa_checkpoints)} checkpoints") + avg_sd = {} + for key in swa_checkpoints[0]: + stacked = torch.stack([ckpt[key].float() for ckpt in swa_checkpoints]) + avg_sd[key] = stacked.mean(dim=0).to(dtype=swa_checkpoints[0][key].dtype) + base_model.load_state_dict(avg_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + swa_val_loss, swa_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"swa_eval val_loss:{swa_val_loss:.4f} val_bpb:{swa_val_bpb:.4f}") + del swa_checkpoints + + if ema_sd is not None: + log0("ema:loading averaged weights") + model_sd = base_model.state_dict() + for k in ema_sd: + ema_sd[k] = ema_sd[k].to(dtype=model_sd[k].dtype, device=model_sd[k].device) + base_model.load_state_dict(ema_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + ema_val_loss, ema_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"ema_eval val_loss:{ema_val_loss:.4f} val_bpb:{ema_val_bpb:.4f}") + del ema_sd + + if master_process: + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + quant_obj, quant_stats = quantize_state_dict_int8( + base_model.state_dict(), + qat_bits=args.qat_bits if args.qat_enabled else 8, + qat_mlp_bits=args.qat_mlp_bits if args.qat_enabled else 0, + ) + quant_buf = io.BytesIO() + torch.save(quant_obj, quant_buf) + quant_raw = quant_buf.getvalue() + try: + import zstandard as zstd + quant_blob = zstd.ZstdCompressor(level=22).compress(quant_raw) + compress_method = "zstd-22" + except ImportError: + quant_blob = zlib.compress(quant_raw, level=9) + compress_method = "zlib-9" + quant_raw_bytes = len(quant_raw) + if master_process: + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int8_payload_bytes"], 1) + log0( + f"Serialized model int8+{compress_method}: {quant_file_bytes} bytes " + f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" + ) + log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + try: + import zstandard as zstd + decompressed = zstd.ZstdDecompressor().decompress(quant_blob_disk) + except Exception: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + torch.cuda.synchronize() + t_qeval = time.perf_counter() + q_val_loss, q_val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + if args.ttt_enabled: + torch._dynamo.reset() + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + torch.cuda.synchronize() + t_ttt_sw = time.perf_counter() + all_val_tokens = torch.cat([load_data_shard(Path(p)) for p in sorted(glob.glob(args.val_files))]).contiguous() + ttt_sw_loss, ttt_sw_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + all_val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.sliding_window_stride if args.sliding_window_stride > 0 else 64, + log0=log0, + ) + torch.cuda.synchronize() + log0( + f"final_ttt_sliding val_loss:{ttt_sw_loss:.4f} val_bpb:{ttt_sw_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt_sw):.0f}ms" + ) + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main() diff --git a/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/README.md b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/README.md new file mode 100644 index 0000000000..4e62deaf48 --- /dev/null +++ b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/README.md @@ -0,0 +1,105 @@ +# Non-Record: Crawler Transformer 3f+2cx2 + SP8192 + SDClip + Post-Quant TTT — val_bpb 1.1372 + +**val_bpb: 1.1372** (3-seed mean, std 0.0004) | **~15.03 MB** | 1x RTX 6000 Ada, 18000s + +### 3-Seed Results — d=736 int6 (1x RTX 6000 Ada 48GB) + +| Seed | Steps | Pre-quant BPB | GPTQ Roundtrip BPB | **TTT BPB** | Artifact | +|------|-------|---------------|---------------------|------------|----------| +| 1337 | 6042 | 1.1232 | 1.1738 | **1.1372** | 15,025,540 B | +| 42 | 6012 | 1.1235 | 1.1732 | **1.1376** | 15,021,049 B | +| 2024 | 5977 | 1.1222 | 1.1746 | **1.1368** | 15,075,112 B | +| **Mean** | | **1.1230** | **1.1739** | **1.1372 (std 0.0004)** | | + +Note: Trained on 1x RTX 6000 Ada for 5hr per seed (~6000 steps). Equivalent step count verified on 8xH100 cluster (6374 steps in 600s, SWA 1.1200). + +### Additional config — d=832 mixed-int (int5 flat attention, MLP; int6 crawler attention, MLP, int8 embedding) + +| Metric | d=736 int6 | **d=832 int5-flat** | +|--------|-----------|-------------------| +| Params | 38.3M | **47.4M** | +| Bits/weight | 3.13 | **2.67** | +| Pre-quant SWA | 1.1232 | **1.1092** | +| GPTQ Roundtrip | 1.1738 | 1.1851 | +| **TTT BPB** | **1.1372** | **1.1372** | +| Artifact | 15.03 MB | 15.86 MB | + +Both configs converge to the same TTT score despite very different approaches. d=832 achieves **1.1092 pre-quant** (only 0.022 behind SOTA) with just 5 blocks, demonstrating the crawler architecture's learning efficiency. The higher quantization penalty (+0.076 vs +0.051) is fully recovered by TTT. + +### Changes from PR #927 + +This builds on our previous submission PR #927 (Recursive Transformer 4B/7L, val_bpb 1.1696). Key changes: + +| Change | PR #927 | This | +|--------|---------|------| +| Architecture | Recursive 4B/7L (d=1024) | **Crawler 3f+2cx2 (d=736/832)** | +| Tokenizer | SP1024 | **SP8192** | +| Quantization | Percentile search + LZMA | **SDClip + GPTQ + Brotli** | +| TTT freeze | freeze=5 (surgical) | **freeze=1** | +| Warmdown | 2000 steps fixed | **60% fraction** | +| Weight decay | 0.04 | **0.085** | +| val_bpb | 1.1696 | **1.1372** | + +### Architecture: Crawler Transformer + +Unlike the standard depth-recurrence approach (11L with shared layers), we use a **Crawler Transformer** architecture (inspired by @newjordan's crawler work): + +- **3 flat blocks + 2 crawler blocks x 2 loops = 7 effective depth** +- Flat blocks: unique parameters, encoder-decoder with skip connections +- Crawler blocks: shared parameters, looped through the middle of the network +- dim=736 (int6) or dim=832 (mixed int5/int6), 16 heads (8 KV), MLP 4x, GQA +- BigramHash embedding (10240 buckets, 128 dim) +- SmearGate, ValueEmbedding (last 2 layers) +- XSA on all 7 layers +- **38.3M params (d=736) / 47.4M params (d=832)** + +### Quantization + +1. **QAT** (int6 fake-quantize via STE) from step 0 +2. **SDClip**: `clip = k * std(row)` — k=12.85 for int6 blocks, k=20.0 for int8 embeddings +3. **Full Hessian GPTQ** with Cholesky error compensation, training-data calibration +4. **Brotli compression** (quality=11) +5. **No pruning** — all artifacts fit under 16MB natively +6. **Mixed-int option**: int5 flat blocks + int6 crawler blocks for d=832 (inspired by @newjordan's Midnight 12L mixed-int approach, PR #1458) + +### Training + +- Muon optimizer (momentum=0.99, WD=0.085) + Adam for scalars +- Warmdown fraction: 60% (linear) +- QK-Gain: 1.5, logit softcap: 30.0 +- train_batch_tokens: 524,288, seq_len: 2048 +- SP8192 tokenizer + +### Test-Time Training (TTT) + +- Sliding window with stride=64, chunk_tokens=32768 +- SGD (lr=0.002, momentum=0.9), 3 epochs per chunk +- **freeze=1**: freezes first flat block + first crawler block +- Recovery: 0.037 BPB from GPTQ roundtrip (1.1739 -> 1.1372) +- Total penalty from pre-quant: only +0.014 BPB + +### Credits + +- **SDClip + SP8192 + GPTQ embeddings + Brotli**: PR #1394 by @clarkkev +- **XSA (extended self-attention)**: PR #549 by @abaybektursun +- **Sliding window TTT**: PR #549 by @abaybektursun +- **Crawler Transformer architecture**: inspired by @newjordan +- **Mixed-int quantization (int5 attn, int6 crawler)**: inspired by @newjordan PR #1458 + +### Run Command + +```bash +# d=736 (int6 all blocks) +VOCAB_SIZE=8192 DATA_PATH=./data/datasets/fineweb10B_sp8192 \ +TOKENIZER_PATH=./data/tokenizers/fineweb_8192_bpe.model \ +MODEL_DIM=736 MAX_WALLCLOCK_SECONDS=18000 SEED=1337 \ +RUN_ID=seed1337 \ +python train_gpt.py + +# d=832 (int5 flat, int6 crawler) +VOCAB_SIZE=8192 DATA_PATH=./data/datasets/fineweb10B_sp8192 \ +TOKENIZER_PATH=./data/tokenizers/fineweb_8192_bpe.model \ +MODEL_DIM=832 QAT_FLAT_BITS=5 MAX_WALLCLOCK_SECONDS=18000 SEED=1337 \ +RUN_ID=seed1337_d832 \ +python train_gpt.py +``` diff --git a/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/requirements.txt b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/requirements.txt new file mode 100644 index 0000000000..65172ab13c --- /dev/null +++ b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/requirements.txt @@ -0,0 +1,4 @@ +numpy +torch +sentencepiece +brotli diff --git a/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/submission.json b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/submission.json new file mode 100644 index 0000000000..fd5c473e45 --- /dev/null +++ b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/submission.json @@ -0,0 +1,37 @@ +{ + "author": "Khoa Phan", + "github_id": "Tonyy1977", + "name": "Crawler Transformer 3f+2cx2 + SP8192 + SDClip + Post-Quant TTT", + "blurb": "Novel crawler transformer architecture (3 flat + 2 crawler blocks x2 loops), SP8192, SDClip GPTQ int6 + Brotli, post-quant sliding TTT on GPTQ artifact", + "date": "2026-04-12", + "track": "10min_16mb", + "val_loss": 2.9370, + "val_bpb": 1.1372, + "val_bpb_std": 0.0004, + "seeds": [1337, 42, 2024], + "seed_results": { + "1337": { + "val_loss": 2.9370, + "val_bpb": 1.1372, + "artifact_bytes": 15025540, + "steps": 6042 + }, + "42": { + "val_loss": 2.9380, + "val_bpb": 1.1376, + "artifact_bytes": 15021049, + "steps": 6012 + }, + "2024": { + "val_loss": 2.9361, + "val_bpb": 1.1368, + "artifact_bytes": 15075112, + "steps": 5977 + } + }, + "hardware": "1x RTX 6000 Ada 48GB 18000s (equivalent to 8xH100 600s, verified)", + "pytorch_version": "2.7.0+cu126", + "bytes_total": 15025540, + "bytes_code": 90756, + "non_record": true +} diff --git a/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_d832_seed1337.log b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_d832_seed1337.log new file mode 100644 index 0000000000..6cedcad301 --- /dev/null +++ b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_d832_seed1337.log @@ -0,0 +1,2241 @@ +logs/v5_sp8192_d832_wd60pct.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_8192_bpe.model +train_loader:dataset:fineweb10B_sp8192 train_shards:128 +val_loader:shards pattern=./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin tokens:40546304 +qat:enabled from step 0 attn=6bit +architecture:crawler flat_blocks:3 crawler_blocks:2 crawler_loops:2 effective_depth:7 flat_params:22843440 crawler_params:15228960 per_loop_params:23296 +model_params:47433812 +world_size:1 grad_accum_steps:8 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:16 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:18000.000 +seed:1337 +warmup_step:1/100 +warmup_step:2/100 +warmup_step:3/100 +warmup_step:4/100 +warmup_step:5/100 +warmup_step:6/100 +warmup_step:7/100 +warmup_step:8/100 +warmup_step:9/100 +warmup_step:10/100 +warmup_step:11/100 +warmup_step:12/100 +warmup_step:13/100 +warmup_step:14/100 +warmup_step:15/100 +warmup_step:16/100 +warmup_step:17/100 +warmup_step:18/100 +warmup_step:19/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:8.9969 val_bpb:3.4836 train_time:0ms step_avg:0.01ms +step:1/20000 train_loss:8.9973 train_time:19561ms step_avg:19560.55ms +step:2/20000 train_loss:9.3523 train_time:22921ms step_avg:11460.27ms +step:3/20000 train_loss:9.8574 train_time:26354ms step_avg:8784.62ms +step:4/20000 train_loss:9.3050 train_time:29813ms step_avg:7453.21ms +step:5/20000 train_loss:8.9779 train_time:33286ms step_avg:6657.15ms +step:6/20000 train_loss:8.5514 train_time:36779ms step_avg:6129.80ms +step:7/20000 train_loss:8.1707 train_time:40272ms step_avg:5753.14ms +step:8/20000 train_loss:7.9542 train_time:43779ms step_avg:5472.42ms +step:9/20000 train_loss:7.5592 train_time:47300ms step_avg:5255.60ms +step:10/20000 train_loss:7.2515 train_time:50838ms step_avg:5083.81ms +step:100/20000 train_loss:4.5787 train_time:372540ms step_avg:3725.40ms +step:200/20000 train_loss:3.9021 train_time:728965ms step_avg:3644.82ms +step:300/20000 train_loss:3.5985 train_time:1083940ms step_avg:3613.13ms +step:400/20000 train_loss:3.5688 train_time:1437722ms step_avg:3594.30ms +step:500/20000 train_loss:3.3891 train_time:1791044ms step_avg:3582.09ms +step:500/20000 val_loss:3.4605 val_bpb:1.3399 train_time:1791058ms step_avg:3582.12ms +step:600/20000 train_loss:3.4358 train_time:2143456ms step_avg:3572.43ms +step:700/20000 train_loss:3.2565 train_time:2496306ms step_avg:3566.15ms +step:800/20000 train_loss:3.3256 train_time:2848924ms step_avg:3561.16ms +step:900/20000 train_loss:3.3069 train_time:3202327ms step_avg:3558.14ms +step:1000/20000 train_loss:3.1493 train_time:3555544ms step_avg:3555.54ms +step:1000/20000 val_loss:3.2446 val_bpb:1.2563 train_time:3555557ms step_avg:3555.56ms +step:1100/20000 train_loss:3.2640 train_time:3907803ms step_avg:3552.55ms +step:1200/20000 train_loss:3.2861 train_time:4260381ms step_avg:3550.32ms +step:1300/20000 train_loss:3.2075 train_time:4613065ms step_avg:3548.51ms +step:1400/20000 train_loss:3.1347 train_time:4965354ms step_avg:3546.68ms +step:1500/20000 train_loss:3.1289 train_time:5317623ms step_avg:3545.08ms +step:1500/20000 val_loss:3.1848 val_bpb:1.2332 train_time:5317637ms step_avg:3545.09ms +step:1600/20000 train_loss:3.2271 train_time:5669616ms step_avg:3543.51ms +step:1700/20000 train_loss:3.2334 train_time:6021114ms step_avg:3541.83ms +step:1800/20000 train_loss:3.2202 train_time:6372976ms step_avg:3540.54ms +step:1900/20000 train_loss:3.2083 train_time:6724234ms step_avg:3539.07ms +step:2000/20000 train_loss:3.1804 train_time:7075462ms step_avg:3537.73ms +step:2000/20000 val_loss:3.1581 val_bpb:1.2228 train_time:7075476ms step_avg:3537.74ms +step:2100/20000 train_loss:3.1543 train_time:7427070ms step_avg:3536.70ms +step:2200/20000 train_loss:3.1508 train_time:7778959ms step_avg:3535.89ms +step:2300/20000 train_loss:3.2078 train_time:8130677ms step_avg:3535.08ms +step:2400/20000 train_loss:3.1717 train_time:8481904ms step_avg:3534.13ms +step:2500/20000 train_loss:3.1176 train_time:8832842ms step_avg:3533.14ms +step:2500/20000 val_loss:3.1152 val_bpb:1.2062 train_time:8832855ms step_avg:3533.14ms +step:2600/20000 train_loss:3.1138 train_time:9183450ms step_avg:3532.10ms +step:2700/20000 train_loss:3.0650 train_time:9534400ms step_avg:3531.26ms +step:2800/20000 train_loss:3.1137 train_time:9885541ms step_avg:3530.55ms +step:2900/20000 train_loss:3.1406 train_time:10236486ms step_avg:3529.82ms +step:3000/20000 train_loss:3.0061 train_time:10587256ms step_avg:3529.09ms +step:3000/20000 val_loss:3.0774 val_bpb:1.1916 train_time:10587270ms step_avg:3529.09ms +step:3100/20000 train_loss:3.0318 train_time:10938199ms step_avg:3528.45ms +step:3200/20000 train_loss:3.0729 train_time:11289299ms step_avg:3527.91ms +step:3300/20000 train_loss:3.1105 train_time:11640029ms step_avg:3527.28ms +step:3400/20000 train_loss:3.0548 train_time:11990781ms step_avg:3526.70ms +step:3500/20000 train_loss:3.0187 train_time:12341984ms step_avg:3526.28ms +step:3500/20000 val_loss:3.0381 val_bpb:1.1763 train_time:12341998ms step_avg:3526.29ms +step:3600/20000 train_loss:3.0227 train_time:12692976ms step_avg:3525.83ms +step:3700/20000 train_loss:3.0063 train_time:13043719ms step_avg:3525.33ms +step:3800/20000 train_loss:3.0847 train_time:13394611ms step_avg:3524.90ms +step:3900/20000 train_loss:2.9824 train_time:13745652ms step_avg:3524.53ms +step:4000/20000 train_loss:3.0537 train_time:14097299ms step_avg:3524.32ms +step:4000/20000 val_loss:2.9893 val_bpb:1.1575 train_time:14097312ms step_avg:3524.33ms +step:4100/20000 train_loss:3.1216 train_time:14448766ms step_avg:3524.09ms +step:4200/20000 train_loss:3.0200 train_time:14800284ms step_avg:3523.88ms +step:4300/20000 train_loss:2.9680 train_time:15151912ms step_avg:3523.70ms +step:4400/20000 train_loss:2.9587 train_time:15503681ms step_avg:3523.56ms +step:4500/20000 train_loss:2.8860 train_time:15855913ms step_avg:3523.54ms +step:4500/20000 val_loss:2.9351 val_bpb:1.1365 train_time:15855927ms step_avg:3523.54ms +step:4600/20000 train_loss:2.8808 train_time:16207775ms step_avg:3523.43ms +step:4700/20000 train_loss:2.8850 train_time:16560336ms step_avg:3523.48ms +step:4800/20000 train_loss:2.8994 train_time:16913487ms step_avg:3523.64ms +step:4900/20000 train_loss:2.9160 train_time:17265690ms step_avg:3523.61ms +step:5000/20000 train_loss:2.8048 train_time:17617580ms step_avg:3523.52ms +step:5000/20000 val_loss:2.8736 val_bpb:1.1127 train_time:17617592ms step_avg:3523.52ms +step:5100/20000 train_loss:2.8281 train_time:17968858ms step_avg:3523.31ms +step:5109/20000 val_loss:2.8668 val_bpb:1.1100 train_time:18000616ms step_avg:3523.32ms +stopping_early: wallclock_cap train_time:18000616ms step:5109/20000 +peak memory allocated: 18658 MiB reserved: 19596 MiB +eval:restored full crawler loops=2, depth=7 +swa:averaging 13 checkpoints +swa_eval val_loss:2.8647 val_bpb:1.1092 +Serialized model: 171404311 bytes +Code size: 91673 bytes +Total submission size: 171495984 bytes +Serialized model int8+zstd-22: 20267430 bytes (payload:47688648 raw_torch:47714205 payload_ratio:3.59x) +Total submission size int8+zlib: 20359103 bytes +final_int8_zlib_roundtrip val_loss:2.9642 val_bpb:1.1478 eval_time:87284ms +final_int8_zlib_roundtrip_exact val_loss:2.96424162 val_bpb:1.14775148 +gptq:loading calibration data from training shards... +gptq:loaded 64 calibration sequences in 4.6s +gptq:collecting hessians... +gptq:collected hessians for 32 layers +gptq:quantizing int6 with full Hessian GPTQ... +selective_prune: 8181846 candidates, unpruned=15.86MB target=15.9MB +selective_prune: already fits, no pruning needed +gptq_int6_brotli: 15,772,447 bytes | code: 91,673 | total: 15,864,120 (15.86MB) +gptq_int6_brotli_roundtrip val_loss:3.0608 val_bpb:1.1851 time:282.4s +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633536 stride=64 +ttt_sliding:params unfrozen=32204852 frozen=15228960 + ttt_chunk [1/1238] bpb=1.248939 time=5.1s + ttt_chunk [11/1238] bpb=1.162294 time=60.3s + ttt_chunk [21/1238] bpb=1.162652 time=115.5s + ttt_chunk [31/1238] bpb=1.156642 time=170.5s + ttt_chunk [41/1238] bpb=1.162459 time=225.5s + ttt_chunk [51/1238] bpb=1.157300 time=280.4s + ttt_chunk [61/1238] bpb=1.153052 time=335.3s + ttt_chunk [71/1238] bpb=1.154819 time=390.1s + ttt_chunk [81/1238] bpb=1.150193 time=445.0s + ttt_chunk [91/1238] bpb=1.147784 time=499.8s + ttt_chunk [101/1238] bpb=1.147402 time=554.7s + ttt_chunk [111/1238] bpb=1.149353 time=609.5s + ttt_chunk [121/1238] bpb=1.149964 time=664.4s + ttt_chunk [131/1238] bpb=1.152001 time=719.3s + ttt_chunk [141/1238] bpb=1.150702 time=774.2s + ttt_chunk [151/1238] bpb=1.150678 time=829.0s + ttt_chunk [161/1238] bpb=1.149908 time=883.9s + ttt_chunk [171/1238] bpb=1.149579 time=938.8s + ttt_chunk [181/1238] bpb=1.148955 time=993.7s + ttt_chunk [191/1238] bpb=1.149214 time=1048.6s + ttt_chunk [201/1238] bpb=1.149591 time=1103.4s + ttt_chunk [211/1238] bpb=1.150224 time=1158.3s + ttt_chunk [221/1238] bpb=1.149239 time=1213.3s + ttt_chunk [231/1238] bpb=1.149815 time=1268.2s + ttt_chunk [241/1238] bpb=1.149999 time=1323.2s + ttt_chunk [251/1238] bpb=1.149997 time=1378.1s + ttt_chunk [261/1238] bpb=1.150168 time=1433.1s + ttt_chunk [271/1238] bpb=1.148839 time=1488.0s + ttt_chunk [281/1238] bpb=1.149473 time=1542.9s + ttt_chunk [291/1238] bpb=1.148374 time=1597.8s + ttt_chunk [301/1238] bpb=1.148251 time=1652.7s + ttt_chunk [311/1238] bpb=1.147950 time=1707.6s + ttt_chunk [321/1238] bpb=1.147763 time=1762.5s + ttt_chunk [331/1238] bpb=1.147196 time=1817.4s + ttt_chunk [341/1238] bpb=1.146427 time=1872.3s + ttt_chunk [351/1238] bpb=1.146782 time=1927.2s + ttt_chunk [361/1238] bpb=1.146430 time=1982.1s + ttt_chunk [371/1238] bpb=1.145989 time=2037.0s + ttt_chunk [381/1238] bpb=1.145470 time=2091.9s + ttt_chunk [391/1238] bpb=1.144914 time=2146.8s + ttt_chunk [401/1238] bpb=1.144384 time=2201.6s + ttt_chunk [411/1238] bpb=1.143933 time=2256.5s + ttt_chunk [421/1238] bpb=1.143504 time=2311.4s + ttt_chunk [431/1238] bpb=1.142495 time=2366.3s + ttt_chunk [441/1238] bpb=1.141664 time=2421.3s + ttt_chunk [451/1238] bpb=1.141655 time=2476.2s + ttt_chunk [461/1238] bpb=1.140431 time=2531.2s + ttt_chunk [471/1238] bpb=1.140271 time=2586.1s + ttt_chunk [481/1238] bpb=1.140502 time=2641.0s + ttt_chunk [491/1238] bpb=1.140040 time=2696.0s + ttt_chunk [501/1238] bpb=1.140025 time=2750.9s + ttt_chunk [511/1238] bpb=1.140027 time=2805.9s + ttt_chunk [521/1238] bpb=1.139638 time=2860.8s + ttt_chunk [531/1238] bpb=1.139619 time=2915.7s + ttt_chunk [541/1238] bpb=1.139468 time=2970.6s + ttt_chunk [551/1238] bpb=1.138945 time=3025.4s + ttt_chunk [561/1238] bpb=1.138870 time=3080.4s + ttt_chunk [571/1238] bpb=1.139131 time=3135.3s + ttt_chunk [581/1238] bpb=1.138834 time=3190.2s + ttt_chunk [591/1238] bpb=1.138393 time=3245.1s + ttt_chunk [601/1238] bpb=1.138316 time=3300.0s + ttt_chunk [611/1238] bpb=1.138192 time=3354.9s + ttt_chunk [621/1238] bpb=1.138745 time=3409.9s + ttt_chunk [631/1238] bpb=1.138999 time=3464.9s + ttt_chunk [641/1238] bpb=1.139381 time=3519.8s + ttt_chunk [651/1238] bpb=1.139376 time=3574.7s + ttt_chunk [661/1238] bpb=1.139732 time=3629.5s + ttt_chunk [671/1238] bpb=1.140102 time=3684.4s + ttt_chunk [681/1238] bpb=1.140742 time=3739.3s + ttt_chunk [691/1238] bpb=1.140793 time=3794.2s + ttt_chunk [701/1238] bpb=1.140860 time=3849.1s + ttt_chunk [711/1238] bpb=1.141109 time=3904.0s + ttt_chunk [721/1238] bpb=1.141238 time=3958.9s + ttt_chunk [731/1238] bpb=1.140880 time=4013.9s + ttt_chunk [741/1238] bpb=1.140521 time=4068.9s + ttt_chunk [751/1238] bpb=1.140244 time=4123.8s + ttt_chunk [761/1238] bpb=1.140079 time=4178.7s + ttt_chunk [771/1238] bpb=1.139544 time=4233.7s + ttt_chunk [781/1238] bpb=1.139895 time=4288.6s + ttt_chunk [791/1238] bpb=1.139411 time=4343.5s + ttt_chunk [801/1238] bpb=1.139696 time=4398.4s + ttt_chunk [811/1238] bpb=1.139270 time=4453.3s + ttt_chunk [821/1238] bpb=1.138571 time=4508.2s + ttt_chunk [831/1238] bpb=1.138163 time=4563.1s + ttt_chunk [841/1238] bpb=1.137749 time=4618.1s + ttt_chunk [851/1238] bpb=1.137412 time=4673.0s + ttt_chunk [861/1238] bpb=1.137022 time=4727.9s + ttt_chunk [871/1238] bpb=1.136573 time=4782.8s + ttt_chunk [881/1238] bpb=1.136273 time=4837.7s + ttt_chunk [891/1238] bpb=1.136376 time=4892.7s + ttt_chunk [901/1238] bpb=1.136715 time=4947.6s + ttt_chunk [911/1238] bpb=1.136569 time=5002.5s + ttt_chunk [921/1238] bpb=1.136663 time=5057.5s + ttt_chunk [931/1238] bpb=1.136601 time=5112.4s + ttt_chunk [941/1238] bpb=1.136975 time=5167.4s + ttt_chunk [951/1238] bpb=1.136850 time=5222.4s + ttt_chunk [961/1238] bpb=1.137346 time=5277.4s + ttt_chunk [971/1238] bpb=1.137488 time=5332.4s + ttt_chunk [981/1238] bpb=1.137524 time=5387.3s + ttt_chunk [991/1238] bpb=1.137473 time=5442.3s + ttt_chunk [1001/1238] bpb=1.137776 time=5497.2s + ttt_chunk [1011/1238] bpb=1.137912 time=5552.2s + ttt_chunk [1021/1238] bpb=1.138131 time=5607.2s + ttt_chunk [1031/1238] bpb=1.138305 time=5662.1s + ttt_chunk [1041/1238] bpb=1.138413 time=5717.0s + ttt_chunk [1051/1238] bpb=1.138643 time=5771.9s + ttt_chunk [1061/1238] bpb=1.138599 time=5826.9s + ttt_chunk [1071/1238] bpb=1.138614 time=5881.9s + ttt_chunk [1081/1238] bpb=1.138678 time=5936.9s + ttt_chunk [1091/1238] bpb=1.138871 time=5991.8s + ttt_chunk [1101/1238] bpb=1.139046 time=6046.7s + ttt_chunk [1111/1238] bpb=1.139091 time=6101.7s + ttt_chunk [1121/1238] bpb=1.139020 time=6156.7s + ttt_chunk [1131/1238] bpb=1.139082 time=6211.6s + ttt_chunk [1141/1238] bpb=1.138769 time=6266.6s + ttt_chunk [1151/1238] bpb=1.138696 time=6321.5s + ttt_chunk [1161/1238] bpb=1.138569 time=6376.5s + ttt_chunk [1171/1238] bpb=1.138172 time=6431.5s + ttt_chunk [1181/1238] bpb=1.138022 time=6486.4s + ttt_chunk [1191/1238] bpb=1.138013 time=6541.4s + ttt_chunk [1201/1238] bpb=1.137960 time=6596.3s + ttt_chunk [1211/1238] bpb=1.137615 time=6651.3s + ttt_chunk [1221/1238] bpb=1.137534 time=6706.3s + ttt_chunk [1231/1238] bpb=1.137221 time=6761.3s + ttt_chunk [1238/1238] bpb=1.137241 time=6796.1s +ttt_sliding:done val_loss=2.937048 val_bpb=1.137241 elapsed=6796.3s +final_ttt_sliding val_loss:2.9370 val_bpb:1.1372 eval_time:6796500ms +2.shape[0],), dtype=torch.float32) + ) + scale = (clip_abs / max_val).clamp_min(1.0 / max_val) + q = torch.clamp(torch.round(t32 / scale[:, None]), min_val, max_val).to(torch.int8) + recon = q.float() * scale[:, None] + err = (t32 - recon).pow(2).sum(dim=1) + if best_err is None: + best_q = q + best_scale = scale + best_err = err + else: + improved = err < best_err + if improved.any(): + best_q[improved] = q[improved] + best_scale[improved] = scale[improved] + best_err[improved] = err[improved] + return best_q.contiguous(), best_scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous() + + if sdclip_k > 0: + # SDClip for 1D: use global std + clip_abs = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + else: + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / max_val if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), min_val, max_val).to(torch.int8).contiguous() + return q, scale + +def quantize_state_dict_int8(state_dict: dict[str, Tensor], qat_bits: int = 8, qat_mlp_bits: int = 0): + quantized: dict[str, Tensor] = {} + scales: dict[str, Tensor] = {} + dtypes: dict[str, str] = {} + passthrough: dict[str, Tensor] = {} + passthrough_orig_dtypes: dict[str, str] = {} + qmeta: dict[str, dict[str, object]] = {} + stats = dict.fromkeys( + ("param_count", "num_tensors", "num_float_tensors", "num_nonfloat_tensors", "baseline_tensor_bytes", "int8_payload_bytes"), + 0, + ) + + for name, tensor in state_dict.items(): + t = tensor.detach().to("cpu").contiguous() + stats["param_count"] += int(t.numel()) + stats["num_tensors"] += 1 + stats["baseline_tensor_bytes"] += tensor_nbytes(t) + + if not t.is_floating_point(): + stats["num_nonfloat_tensors"] += 1 + passthrough[name] = t + stats["int8_payload_bytes"] += tensor_nbytes(t) + continue + + if t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + kept = keep_float_tensor(name, t, passthrough_orig_dtypes) + passthrough[name] = kept + stats["int8_payload_bytes"] += tensor_nbytes(kept) + continue + + stats["num_float_tensors"] += 1 + is_block_weight = any(k in name for k in ("flat_blocks.", "crawler_blocks.", "bigram.proj.")) + is_embed_weight = ("tok_emb.weight" in name) + is_mlp_weight = any(k in name for k in ("mlp.fc.weight", "mlp.proj.weight")) + if qat_bits < 8 and is_block_weight and t.ndim == 2: + n_bits = (qat_mlp_bits if (qat_mlp_bits > 0 and is_mlp_weight) else qat_bits) + sdclip_k = 12.85 + elif is_embed_weight: + n_bits = 8 + sdclip_k = 20.0 + else: + n_bits = 8 + sdclip_k = 20.0 + q, s = quantize_float_tensor(t, n_bits=n_bits, sdclip_k=sdclip_k) + if s.ndim > 0: + qmeta[name] = {"scheme": "per_row", "axis": 0} + quantized[name] = q + scales[name] = s + dtypes[name] = str(t.dtype).removeprefix("torch.") + stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + obj: dict[str, object] = { + "__quant_format__": "int8_clean_per_row_v1", + "quantized": quantized, + "scales": scales, + "dtypes": dtypes, + "passthrough": passthrough, + } + if qmeta: + obj["qmeta"] = qmeta + if passthrough_orig_dtypes: + obj["passthrough_orig_dtypes"] = passthrough_orig_dtypes + return obj, stats + +def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + qmeta = obj.get("qmeta", {}) + passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {}) + for name, q in obj["quantized"].items(): + dtype = getattr(torch, obj["dtypes"][name]) + s = obj["scales"][name] + if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: + s = s.to(dtype=torch.float32) + 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 + +def generate_autoregressive_calib(model, device, num_seqs=64, seq_len=2048, + vocab_size=1024, temperature=0.8, batch_size=8, seed=42): + model.eval() + rng = torch.Generator(device=device) + rng.manual_seed(seed) + all_tokens = [] + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16): + for batch_start in range(0, num_seqs, batch_size): + bs = min(batch_size, num_seqs - batch_start) + tokens = torch.randint(0, vocab_size, (bs, 1), device=device, generator=rng) + for pos in range(seq_len - 1): + logits = model.forward_logits(tokens) + next_logit = logits[:, -1, :] + probs = torch.softmax(next_logit / temperature, dim=-1) + next_tok = torch.multinomial(probs, 1, generator=rng) + tokens = torch.cat([tokens, next_tok], dim=1) + for i in range(bs): + all_tokens.append(tokens[i:i+1]) + return all_tokens + +def collect_hessians_from_tokens(hessian_model, token_seqs, device): + hessians = {} + hooks = [] + for name, module in hessian_model.named_modules(): + if isinstance(module, CastedLinear): + param_name = name + ".weight" + cols = module.weight.shape[1] + hessians[param_name] = torch.zeros(cols, cols, dtype=torch.float32, device='cpu') + def make_hook(pname): + def hook_fn(module, input, output): + x = input[0].detach().float() + if x.ndim == 3: + x = x.reshape(-1, x.shape[-1]) + hessians[pname] += (x.T @ x).cpu() + return hook_fn + h = module.register_forward_hook(make_hook(param_name)) + hooks.append(h) + hessian_model.eval() + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16): + for seq in token_seqs: + x = seq[:, :-1].to(device) + y = seq[:, 1:].to(device) + hessian_model(x, y) + for h in hooks: + h.remove() + for name in hessians: + H = hessians[name] + H /= len(token_seqs) + damp = 0.01 * torch.diag(H).mean().clamp_min(1e-6) + H += damp * torch.eye(H.shape[0]) + hessians[name] = H + return hessians + +def quantize_int6_gptq(weight, hessian=None, clip_range=31, block_size=128, sdclip_k: float = 0.0): + t32 = weight.float() + if t32.ndim != 2 or hessian is None: + return quantize_int6_per_row(t32, clip_range, sdclip_k=sdclip_k) + rows, cols = t32.shape + H = hessian.float().clone() + dead = torch.diag(H) == 0 + H[dead, dead] = 1 + damp = 0.01 * torch.mean(torch.diag(H)) + H[torch.arange(cols), torch.arange(cols)] += damp + perm = torch.argsort(torch.diag(H), descending=True) + inv_perm = torch.argsort(perm) + W = t32[:, perm].clone() + W[:, dead[perm]] = 0 + H = H[perm][:, perm] + try: + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + except torch._C._LinAlgError: + H[torch.arange(cols), torch.arange(cols)] += 0.1 * torch.mean(torch.diag(H)) + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + best_q = Q[:, inv_perm] + return best_q, s + best_q, best_scale, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + recon = Q.float() * sf[:, None] + mse = (W - recon).pow(2).mean().item() + if mse < best_err: + best_q, best_scale, best_err = Q, s, mse + best_q = best_q[:, inv_perm] + return best_q, best_scale + +def quantize_int6_per_row(t, clip_range=31, sdclip_k: float = 0.0): + t32 = t.float() if not t.is_floating_point() else t.float() + if t32.ndim == 2: + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + return q, s + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + recon = q.float() * s.float()[:, None] + err = (t32 - recon).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, s, err + return best_q, best_s + if sdclip_k > 0: + clip_val = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_val / clip_range if clip_val > 0 else 1.0, dtype=torch.float16) + else: + amax = t32.abs().max().item() + scale = torch.tensor(amax / clip_range if amax > 0 else 1.0, dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -clip_range, clip_range).to(torch.int8) + return q, scale + +def mixed_quantize_int6_gptq(state_dict, hessians=None): + result = {} + meta = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + if not t.is_floating_point() or t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + is_block = any(k in name for k in ("flat_blocks.", "crawler_blocks.")) + if is_block and t.ndim == 2: + H = hessians.get(name) if hessians else None + q, s = quantize_int6_gptq(t, hessian=H, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + else: + q, s = quantize_int6_per_row(t, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + return result, meta + +def dequantize_mixed_int6(result, meta, template_sd): + out = {} + for name, orig in template_sd.items(): + info = meta.get(name) + if info is None: + continue + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = 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) + +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) + +def _fake_quantize_ste(w: Tensor, n_bits: int) -> Tensor: + max_val = 2 ** (n_bits - 1) - 1 + min_val = -(2 ** (n_bits - 1)) + scale = w.abs().amax(dim=-1, keepdim=True) / max_val + scale = scale.clamp_min(1e-8) + w_q = (w / scale).round().clamp(min_val, max_val) * scale + return w + (w_q - w).detach() + +_QAT_ENABLED = False +_QAT_BITS = 6 +_QAT_MLP_BITS = 0 +_ACTIVE_CRAWLER_LOOPS = 1 + +class CastedLinear(nn.Linear): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._is_mlp = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if _QAT_ENABLED and self.weight.ndim == 2 and self.weight.numel() > 65536: + bits = (_QAT_MLP_BITS if (_QAT_MLP_BITS > 0 and self._is_mlp) else _QAT_BITS) + w = _fake_quantize_ste(w, bits) + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0): + super().__init__() + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + +class CausalSelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int, + rope_base: float, + qk_gain_init: float, + ): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + 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(3) + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, q_delta=None, v_delta=None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x) + (q_delta if q_delta is not None else 0) + k = self.c_k(x) + v = self.c_v(x) + (v_delta if v_delta is not None else 0) + q = q.reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = k.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = v.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + rope_dim = cos.size(-1) + partial = rope_dim // 2 + if partial > 0: + q_rope, q_pass = q[..., :partial*2], q[..., partial*2:] + k_rope, k_pass = k[..., :partial*2], k[..., partial*2:] + q_rope = apply_rotary_emb(q_rope, cos[..., :partial], sin[..., :partial]) + k_rope = apply_rotary_emb(k_rope, cos[..., :partial], sin[..., :partial]) + q = torch.cat([q_rope, q_pass], dim=-1) + k = torch.cat([k_rope, k_pass], dim=-1) + else: + 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 = self._xsa_efficient(y.transpose(1, 2), v.transpose(1, 2)).contiguous().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): + super().__init__() + hidden = mlp_mult * dim + self.fc = CastedLinear(dim, hidden, bias=False) + self.fc._is_mlp = True + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + self.proj._is_mlp = True + + def forward(self, x: Tensor) -> Tensor: + x = torch.relu(self.fc(x)) + return self.proj(x.square()) + +class ValueEmbedding(nn.Module): + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int, num_loops_active: int): + super().__init__() + self.table = nn.Embedding(vocab_size, ve_dim) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) + self.scales = nn.ParameterList([nn.Parameter(torch.ones(1)) for _ in range(num_loops_active)]) + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor, loop_idx: int) -> Tensor: + return self.scales[loop_idx] * self.proj(self.table(input_ids)) + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate).to(dtype=x.dtype) + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1.0 - g) * x + g * x_prev + +class BigramHashEmbedding(nn.Module): + def __init__(self, num_buckets: int, hash_dim: int, model_dim: int): + super().__init__() + self.num_buckets = num_buckets + self.table = nn.Embedding(num_buckets, hash_dim) + self.proj = CastedLinear(hash_dim, model_dim, bias=False) + self.proj._zero_init = True + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor) -> Tensor: + bsz, seqlen = input_ids.shape + prev_ids = torch.cat([ + torch.zeros(bsz, 1, dtype=input_ids.dtype, device=input_ids.device), + input_ids[:, :-1], + ], dim=1) + h = ((prev_ids.long() * 92821 + input_ids.long()) % self.num_buckets).long() + return self.proj(self.table(h)) + +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, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init) + self.mlp = MLP(dim, mlp_mult) + + def forward( + self, x: Tensor, x0: Tensor, + attn_scale: Tensor, mlp_scale: Tensor, resid_mix: Tensor, + q_delta_fn=None, v_delta_fn=None, v_embed=None, + ) -> Tensor: + mix = resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + n = self.attn_norm(x) + qd = q_delta_fn(n) if q_delta_fn is not None else None + vd = v_delta_fn(n) if v_delta_fn is not None else None + if v_embed is not None: + vd = (vd + v_embed) if vd is not None else v_embed + attn_out = self.attn(n, qd, vd) + x = x + attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x)) + return x + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_flat_blocks: int, + num_crawler_blocks: int, + crawler_loops: 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, + use_smear_gate: bool = True, + bigram_buckets: int = 10240, + bigram_dim: int = 128, + embed_bottleneck: int = 0, + ve_enabled: bool = False, + ve_dim: int = 128, + ve_last_n: int = 2, + temperature: float = 1.0, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.temperature = temperature + self.embed_bottleneck = embed_bottleneck + self.num_flat_blocks = num_flat_blocks + self.num_crawler_blocks = num_crawler_blocks + self.crawler_loops = crawler_loops + self._active_crawler_loops = crawler_loops + self._n_enc = num_flat_blocks // 2 + num_loops = num_flat_blocks + num_crawler_blocks * crawler_loops + self.num_loops = num_loops + if embed_bottleneck > 0: + self.tok_emb = nn.Embedding(vocab_size, embed_bottleneck) + self.embed_proj = CastedLinear(embed_bottleneck, model_dim, bias=False) + self.embed_proj_rev = CastedLinear(model_dim, embed_bottleneck, bias=False) + else: + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.embed_proj = None + self.embed_proj_rev = None + self.bigram = BigramHashEmbedding(bigram_buckets, bigram_dim, model_dim) + self.smear = SmearGate(model_dim) if use_smear_gate else None + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve = ValueEmbedding(vocab_size, ve_dim, kv_dim, ve_last_n) if ve_enabled else None + self.ve_last_n = ve_last_n + self.flat_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_flat_blocks) + ]) + self.crawler_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_crawler_blocks) + ]) + self.crawler_residual_scales = nn.ParameterList([ + nn.Parameter(torch.tensor(0.5, dtype=torch.float32)) + for _ in range(crawler_loops) + ]) + self.attn_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.mlp_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.resid_mixes = nn.Parameter( + torch.stack([ + torch.stack((torch.ones(model_dim), torch.zeros(model_dim))) + for _ in range(num_loops) + ]).float() + ) + self.num_encoder_loops = num_loops // 2 + self.num_decoder_loops = num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + self.skip_weights = nn.Parameter(torch.ones(self.num_skips, model_dim, dtype=torch.float32)) + self.xsa_last_n = int(os.environ.get("XSA_LAST_N", 7)) + 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._rebuild_schedule() + self._init_weights() + + def _rebuild_schedule(self, active_loops: int | None = None): + if active_loops is not None: + self._active_crawler_loops = active_loops + schedule = [] + for i in range(self._n_enc): + schedule.append(('flat', i)) + for loop in range(self._active_crawler_loops): + for c in range(self.num_crawler_blocks): + schedule.append(('crawler', c)) + for i in range(self._n_enc, self.num_flat_blocks): + schedule.append(('flat', i)) + self._loop_schedule = schedule + self.num_loops = len(schedule) + self.num_encoder_loops = self.num_loops // 2 + self.num_decoder_loops = self.num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + block_list = [] + for kind, idx in schedule: + block_list.append(self.flat_blocks[idx] if kind == 'flat' else self.crawler_blocks[idx]) + self._block_list = block_list + + def _get_block(self, loop_idx: int) -> 'Block': + return self._block_list[loop_idx] + + 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) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and min(module.weight.shape) >= 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 * self.num_loops)) + + def _embed(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.embed_proj is not None: + x = self.embed_proj(x) + return x + + def _logits(self, x: Tensor) -> Tensor: + if self.embed_proj_rev is not None: + x = self.embed_proj_rev(x) + logits = F.linear(x, self.tok_emb.weight) + elif self.tie_embeddings: + logits = F.linear(x, self.tok_emb.weight) + else: + logits = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits / self.logit_softcap) + + def _run_blocks(self, x, x0, input_ids, lora=None): + active_loops = _ACTIVE_CRAWLER_LOOPS + n_enc = self._n_enc + loop_idx = 0 + xsa_n = self.xsa_last_n + total_depth = self.num_flat_blocks + self.num_crawler_blocks * active_loops + + if xsa_n > 0: + for blk in self.flat_blocks: + blk.attn.use_xsa = (loop_idx >= total_depth - xsa_n) if loop_idx < n_enc or loop_idx >= n_enc + self.num_crawler_blocks * active_loops else False + loop_idx += 1 + for blk in self.crawler_blocks: + for _ in range(active_loops): + blk.attn.use_xsa = True + loop_idx = 0 + + skips: list[Tensor] = [] + for i in range(n_enc): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[i](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + skips.append(x) + loop_idx += 1 + + for lp in range(active_loops): + for ci, cblock in enumerate(self.crawler_blocks): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x_out = cblock(x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + if lp > 0: + alpha = self.crawler_residual_scales[lp].to(dtype=x.dtype) + x = x + alpha * (x_out - x) + else: + x = x_out + loop_idx += 1 + + n_dec_flat = self.num_flat_blocks - n_enc + for i in range(n_dec_flat): + fi = n_enc + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[fi](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + loop_idx += 1 + return x + + def forward(self, input_ids: Tensor, target_ids: Tensor, lora=None) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids, lora) + x = self.final_norm(x) + logits = self._logits(x) + logits = logits + (lora.lm_head_lora(x) if lora else 0) + if lora: + bsz, sl, V = logits.shape + return F.cross_entropy( + logits.float().reshape(-1, V), target_ids.reshape(-1), reduction="none").reshape(bsz, sl) + return F.cross_entropy(logits.float().reshape(-1, logits.size(-1)), target_ids.reshape(-1), reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids) + x = self.final_norm(x) + return self._logits(x) + +def _compute_chunk_window(ci: int, pred_len: int, num_chunks: int, chunk_size: int, eval_seq_len: int): + chunk_start = ci * chunk_size + chunk_end = pred_len if ci == num_chunks - 1 else (ci + 1) * chunk_size + win_start = max(0, chunk_end - eval_seq_len) + win_len = chunk_end - win_start + chunk_offset = chunk_start - win_start + chunk_len = chunk_end - chunk_start + return win_start, win_len, chunk_offset, chunk_len + +def _accumulate_bpb( + ptl: Tensor, x: Tensor, y: Tensor, + batch_i: int, chunk_offset: int, chunk_len: int, + base_bytes_lut: Tensor, has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + loss_sum: Tensor, byte_sum: Tensor, token_count: Tensor, +): + lbl = ptl[batch_i, chunk_offset:chunk_offset + chunk_len].to(torch.float64) + prev = x[batch_i, chunk_offset:chunk_offset + chunk_len] + tgt = y[batch_i, chunk_offset:chunk_offset + chunk_len] + tok_bytes = base_bytes_lut[tgt].to(torch.float64) + tok_bytes += has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev] + loss_sum += lbl.sum() + byte_sum += tok_bytes.sum() + token_count += chunk_len + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: GPT, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + 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}") + + 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_blocks = min(args.ttt_freeze_blocks, base_model.num_flat_blocks + base_model.num_crawler_blocks) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = False + for bi in range(freeze_blocks): + if f"flat_blocks.{bi}." in name or f"crawler_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)}") + + 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 + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + 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 = [] + 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) + loss_sum += nll[i, s:wlen].to(torch.float64).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() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + 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) + start_tok = chunk_start + (my_seq_s + bs) * seq_len + end_tok = chunk_start + (my_seq_s + 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) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or is_last_chunk): + 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)) + 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 + +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 = "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) + + 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}") + + base_model = GPT( + vocab_size=args.vocab_size, + num_flat_blocks=args.num_flat_blocks, + num_crawler_blocks=args.num_crawler_blocks, + crawler_loops=args.crawler_loops, + 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, + temperature=args.temperature, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + use_smear_gate=args.use_smear_gate, + bigram_buckets=args.bigram_buckets, + bigram_dim=args.bigram_dim, + embed_bottleneck=args.embed_bottleneck, + ve_enabled=args.ve_enabled, + ve_dim=args.ve_dim, + ve_last_n=args.ve_last_n, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + if isinstance(module, Rotary): + module.inv_freq.data = module.inv_freq.data.float() + restore_low_dim_params_to_fp32(base_model) + + if args.resume_from and os.path.isfile(args.resume_from): + log0(f"resuming_from:{args.resume_from}") + saved = torch.load(args.resume_from, map_location=device) + base_model.load_state_dict(saved, strict=True) + restore_low_dim_params_to_fp32(base_model) + log0("resume:loaded model weights (optimizer states reset)") + global _QAT_ENABLED, _QAT_BITS, _QAT_MLP_BITS, _ACTIVE_CRAWLER_LOOPS + _QAT_BITS = args.qat_bits + _QAT_MLP_BITS = args.qat_mlp_bits + _qat_activated = False + if args.qat_enabled and args.late_qat_threshold >= 1.0: + _QAT_ENABLED = True + _qat_activated = True + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:enabled from step 0 attn={_QAT_BITS}bit{mlp_info}") + elif args.qat_enabled: + _QAT_ENABLED = False + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:late_start threshold={args.late_qat_threshold} attn={_QAT_BITS}bit{mlp_info}") + else: + _QAT_ENABLED = False + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + _use_ddp = distributed and world_size > 1 + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + + block_named_params = list(base_model.flat_blocks.named_parameters()) + list(base_model.crawler_blocks.named_parameters()) + matrix_params = [ + p + for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p + for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params.append(base_model.attn_scales) + scalar_params.append(base_model.mlp_scales) + scalar_params.append(base_model.resid_mixes) + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + if base_model.smear is not None: + scalar_params.append(base_model.smear.gate) + bigram_named = list(base_model.bigram.named_parameters()) + for name, p in bigram_named: + if p.ndim == 2 and "proj" in name: + matrix_params.append(p) + elif p.ndim == 2: + pass + else: + scalar_params.append(p) + ve_table_params = [] + if base_model.ve is not None: + for name, p in base_model.ve.named_parameters(): + if "table" in name: + ve_table_params.append(p) + elif p.ndim == 2: + matrix_params.append(p) + else: + scalar_params.append(p) + 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, base_model.bigram.table.weight] + + ([base_model.embed_proj.weight, base_model.embed_proj_rev.weight] if base_model.embed_proj is not None else []) + + ve_table_params, + "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.weight_decay, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + flat_params = sum(p.numel() for p in base_model.flat_blocks.parameters()) + crawler_params = sum(p.numel() for p in base_model.crawler_blocks.parameters()) + loop_params = base_model.attn_scales.numel() + base_model.mlp_scales.numel() + base_model.resid_mixes.numel() + log0(f"architecture:crawler flat_blocks:{args.num_flat_blocks} crawler_blocks:{args.num_crawler_blocks} crawler_loops:{args.crawler_loops} effective_depth:{base_model.num_loops} flat_params:{flat_params} crawler_params:{crawler_params} per_loop_params:{loop_params}") + log0(f"model_params:{n_params}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + 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_frac > 0 and max_wallclock_ms is not None: + warmdown_ms = args.warmdown_frac * max_wallclock_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.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 + + progressive_steps: list[tuple[int, int]] = [] + if args.progressive_schedule: + for entry in args.progressive_schedule.split(","): + s, loops = entry.strip().split(":") + progressive_steps.append((int(s), int(loops))) + progressive_steps.sort() + + 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] + prog_variants = sorted(set([1] + [loops for _, loops in progressive_steps])) if progressive_steps else [base_model._active_crawler_loops] + steps_per_variant = max(1, args.warmup_steps // (len(prog_variants) * 2)) + model.train() + warmup_step = 0 + for variant_loops in prog_variants: + if variant_loops != base_model._active_crawler_loops: + base_model._rebuild_schedule(active_loops=variant_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"warmup:precompile variant={variant_loops} loops, depth={base_model.num_loops}") + for _ in range(steps_per_variant): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{args.warmup_steps}") + remaining = args.warmup_steps - warmup_step + if remaining > 0: + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + for _ in range(remaining): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{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() + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + if _use_ddp: + model.require_backward_grad_sync = True + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + if progressive_steps: + _ACTIVE_CRAWLER_LOOPS = 1 + log0(f"progressive:enabled schedule={progressive_steps} starting with 1 crawler loop") + else: + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + _current_crawler_loops = _ACTIVE_CRAWLER_LOOPS + + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_checkpoints: list[dict[str, Tensor]] = [] + ema_sd: dict[str, Tensor] | None = None + if args.ema_decay > 0: + ema_sd = {k: v.detach().float().clone() for k, v in base_model.state_dict().items()} + log0(f"ema:enabled decay={args.ema_decay}") + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_activated and scale <= args.late_qat_threshold: + _QAT_ENABLED = True + _qat_activated = True + log0(f"late_qat:activated at step {step} scale={scale:.4f} threshold={args.late_qat_threshold}") + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + if args.swa_start_frac > 0 and step % args.swa_every == 0: + should_collect = torch.tensor(int(scale < args.swa_start_frac), device=device) + if distributed: + dist.all_reduce(should_collect, op=dist.ReduceOp.MIN) + if should_collect.item(): + swa_checkpoints.append({k: v.detach().cpu().clone() for k, v in base_model.state_dict().items()}) + + if ema_sd is not None: + d = args.ema_decay + with torch.no_grad(): + for k, v in base_model.state_dict().items(): + ema_sd[k].mul_(d).add_(v.detach().float(), alpha=1.0 - d) + + step += 1 + for prog_step, prog_loops in progressive_steps: + if step == prog_step and prog_loops != _current_crawler_loops: + _ACTIVE_CRAWLER_LOOPS = prog_loops + _current_crawler_loops = prog_loops + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"progressive:step {step} -> {prog_loops} crawler loops, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * prog_loops} (recompiled)") + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + _QAT_ENABLED = False + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + log0(f"eval:restored full crawler loops={args.crawler_loops}, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * args.crawler_loops}") + + if swa_checkpoints: + log0(f"swa:averaging {len(swa_checkpoints)} checkpoints") + avg_sd = {} + for key in swa_checkpoints[0]: + stacked = torch.stack([ckpt[key].float() for ckpt in swa_checkpoints]) + avg_sd[key] = stacked.mean(dim=0).to(dtype=swa_checkpoints[0][key].dtype) + base_model.load_state_dict(avg_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + swa_val_loss, swa_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"swa_eval val_loss:{swa_val_loss:.4f} val_bpb:{swa_val_bpb:.4f}") + del swa_checkpoints + + if ema_sd is not None: + log0("ema:loading averaged weights") + model_sd = base_model.state_dict() + for k in ema_sd: + ema_sd[k] = ema_sd[k].to(dtype=model_sd[k].dtype, device=model_sd[k].device) + base_model.load_state_dict(ema_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + ema_val_loss, ema_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"ema_eval val_loss:{ema_val_loss:.4f} val_bpb:{ema_val_bpb:.4f}") + del ema_sd + + if master_process: + torch.save(base_model.state_dict(), "final_model.pt") + import shutil + shutil.copy2("final_model.pt", f"final_model_{args.run_id}.pt") + log0(f"saved backup: final_model_{args.run_id}.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + quant_obj, quant_stats = quantize_state_dict_int8( + base_model.state_dict(), + qat_bits=args.qat_bits if args.qat_enabled else 8, + qat_mlp_bits=args.qat_mlp_bits if args.qat_enabled else 0, + ) + quant_buf = io.BytesIO() + torch.save(quant_obj, quant_buf) + quant_raw = quant_buf.getvalue() + try: + import zstandard as zstd + quant_blob = zstd.ZstdCompressor(level=22).compress(quant_raw) + compress_method = "zstd-22" + except ImportError: + quant_blob = zlib.compress(quant_raw, level=9) + compress_method = "zlib-9" + quant_raw_bytes = len(quant_raw) + if master_process: + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int8_payload_bytes"], 1) + log0( + f"Serialized model int8+{compress_method}: {quant_file_bytes} bytes " + f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" + ) + log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + try: + import zstandard as zstd + decompressed = zstd.ZstdDecompressor().decompress(quant_blob_disk) + except Exception: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + torch.cuda.synchronize() + t_qeval = time.perf_counter() + q_val_loss, q_val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + if master_process: + log0("gptq:generating autoregressive calibration data...") + base_model.load_state_dict(torch.load("final_model.pt", map_location=device), strict=True) + restore_low_dim_params_to_fp32(base_model) + t_gptq = time.perf_counter() + ar_tokens = generate_autoregressive_calib( + base_model, device, num_seqs=64, seq_len=args.train_seq_len, + vocab_size=args.vocab_size, temperature=0.8, batch_size=8, seed=args.seed, + ) + log0(f"gptq:generated {len(ar_tokens)} sequences in {time.perf_counter()-t_gptq:.1f}s") + log0("gptq:collecting hessians...") + hessians = collect_hessians_from_tokens(base_model, ar_tokens, device) + log0(f"gptq:collected hessians for {len(hessians)} layers") + del ar_tokens + torch.cuda.empty_cache() + log0("gptq:quantizing int6 with full Hessian GPTQ...") + gptq_result, gptq_meta = mixed_quantize_int6_gptq( + base_model.state_dict(), hessians=hessians, + ) + del hessians + target_bytes = 16_000_000 + code_bytes = len(code.encode("utf-8")) + ones_info = [] + for name, info in gptq_meta.items(): + if not (isinstance(info, dict) and info.get("type") == "int6"): + continue + qk, sk = name + ".q", name + ".scale" + if qk not in gptq_result or sk not in gptq_result: + continue + q, s = gptq_result[qk], gptq_result[sk] + if s.ndim > 0: + ones_mask = (q.abs() == 1) + if ones_mask.any(): + row_idx = torch.arange(q.shape[0]).unsqueeze(1).expand_as(q)[ones_mask] + flat_idx = torch.arange(q.numel()).reshape(q.shape)[ones_mask] + errors = s.float()[row_idx].pow(2) + for fi, err in zip(flat_idx.tolist(), errors.tolist()): + ones_info.append((qk, fi, err)) + ones_info.sort(key=lambda x: x[2]) + def _try_prune(n): + tmp = {k: v.clone() for k, v in gptq_result.items()} + for i in range(min(n, len(ones_info))): + tmp[ones_info[i][0]].view(-1)[ones_info[i][1]] = 0 + buf = io.BytesIO() + torch.save({"w": tmp, "m": gptq_meta}, buf) + return len(brotli.compress(buf.getvalue(), quality=11)) + code_bytes, tmp + no_prune_sz, _ = _try_prune(0) + log0(f"selective_prune: {len(ones_info)} candidates, unpruned={no_prune_sz/1e6:.2f}MB target={target_bytes/1e6:.1f}MB") + if no_prune_sz <= target_bytes: + log0("selective_prune: already fits, no pruning needed") + final_result = gptq_result + else: + full_sz, _ = _try_prune(len(ones_info)) + log0(f"selective_prune: full prune={full_sz/1e6:.2f}MB") + if full_sz > target_bytes: + log0("selective_prune: even full prune not enough, applying all") + _, final_result = _try_prune(len(ones_info)) + else: + lo, hi = 0, len(ones_info) + while lo < hi: + mid = (lo + hi) // 2 + sz, _ = _try_prune(mid) + if sz <= target_bytes: + hi = mid + else: + lo = mid + 1 + log0(f"selective_prune: pruning {lo}/{len(ones_info)} values ({100*lo/len(ones_info):.1f}%) to fit") + _, final_result = _try_prune(lo) + gptq_buf = io.BytesIO() + torch.save({"w": final_result, "m": gptq_meta}, gptq_buf) + gptq_raw = gptq_buf.getvalue() + gptq_blob = brotli.compress(gptq_raw, quality=11) + gptq_bytes = len(gptq_blob) + total_bytes = gptq_bytes + code_bytes + log0(f"gptq_int6_brotli: {gptq_bytes:,} bytes | code: {code_bytes:,} | total: {total_bytes:,} ({total_bytes/1e6:.2f}MB)") + with open("final_model.int6_gptq.ptz", "wb") as f: + f.write(gptq_blob) + gptq_state = torch.load( + io.BytesIO(brotli.decompress(gptq_blob)), map_location="cpu", weights_only=False + ) + restored = dequantize_mixed_int6(gptq_state["w"], gptq_state["m"], base_model.state_dict()) + base_model.load_state_dict(restored, strict=True) + restore_low_dim_params_to_fp32(base_model) + gq_val_loss, gq_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"gptq_int6_brotli_roundtrip val_loss:{gq_val_loss:.4f} val_bpb:{gq_val_bpb:.4f} time:{time.perf_counter()-t_gptq:.1f}s") + + if args.ttt_enabled: + torch._dynamo.reset() + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + torch.cuda.synchronize() + t_ttt_sw = time.perf_counter() + all_val_tokens = torch.cat([load_data_shard(Path(p)) for p in sorted(glob.glob(args.val_files))]).contiguous() + ttt_sw_loss, ttt_sw_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + all_val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.sliding_window_stride if args.sliding_window_stride > 0 else 64, + log0=log0, + ) + torch.cuda.synchronize() + log0( + f"final_ttt_sliding val_loss:{ttt_sw_loss:.4f} val_bpb:{ttt_sw_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt_sw):.0f}ms" + ) + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main() + + +==================================================================================================== +Running Python 3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0] +Running PyTorch 2.6.0+cu124 +Sat Apr 11 04:03:54 2026 ++-----------------------------------------------------------------------------------------+ +| NVIDIA-SMI 580.126.09 Driver Version: 580.126.09 CUDA Version: 13.0 | ++-----------------------------------------+------------------------+----------------------+ +| 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 RTX 6000 Ada Gene... Off | 00000000:01:00.0 On | Off | +| 30% 50C P8 30W / 300W | 1483MiB / 49140MiB | 0% Default | +| | | N/A | ++-----------------------------------------+------------------------+----------------------+ + ++-----------------------------------------------------------------------------------------+ +| Processes: | +| GPU GI CI PID Type Process name GPU Memory | +| ID ID Usage | +|=========================================================================================| +| 0 N/A N/A 2640 G /usr/lib/xorg/Xorg 342MiB | +| 0 N/A N/A 2821 G /usr/bin/gnome-shell 248MiB | +| 0 N/A N/A 3400 G ...exec/xdg-desktop-portal-gnome 31MiB | +| 0 N/A N/A 444032 G /usr/bin/nautilus 106MiB | +| 0 N/A N/A 767208 G .../8054/usr/lib/firefox/firefox 559MiB | +| 0 N/A N/A 3548448 G /proc/self/exe 58MiB | ++-----------------------------------------------------------------------------------------+ + +==================================================================================================== +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_8192_bpe.model +train_loader:dataset:fineweb10B_sp8192 train_shards:128 +val_loader:shards pattern=./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin tokens:40546304 +qat:enabled from step 0 attn=6bit +architecture:crawler flat_blocks:3 crawler_blocks:2 crawler_loops:2 effective_depth:7 flat_params:22843440 crawler_params:15228960 per_loop_params:23296 +model_params:47433812 +world_size:1 grad_accum_steps:8 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:16 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:18000.000 +seed:1337 +warmup_step:1/100 +warmup_step:2/100 +warmup_step:3/100 +warmup_step:4/100 +warmup_step:5/100 +warmup_step:6/100 +warmup_step:7/100 +warmup_step:8/100 +warmup_step:9/100 +warmup_step:10/100 +warmup_step:11/100 +warmup_step:12/100 +warmup_step:13/100 +warmup_step:14/100 +warmup_step:15/100 +warmup_step:16/100 +warmup_step:17/100 +warmup_step:18/100 +warmup_step:19/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:8.9969 val_bpb:3.4836 train_time:0ms step_avg:0.01ms +step:1/20000 train_loss:8.9973 train_time:19561ms step_avg:19560.55ms +step:2/20000 train_loss:9.3523 train_time:22921ms step_avg:11460.27ms +step:3/20000 train_loss:9.8574 train_time:26354ms step_avg:8784.62ms +step:4/20000 train_loss:9.3050 train_time:29813ms step_avg:7453.21ms +step:5/20000 train_loss:8.9779 train_time:33286ms step_avg:6657.15ms +step:6/20000 train_loss:8.5514 train_time:36779ms step_avg:6129.80ms +step:7/20000 train_loss:8.1707 train_time:40272ms step_avg:5753.14ms +step:8/20000 train_loss:7.9542 train_time:43779ms step_avg:5472.42ms +step:9/20000 train_loss:7.5592 train_time:47300ms step_avg:5255.60ms +step:10/20000 train_loss:7.2515 train_time:50838ms step_avg:5083.81ms +step:100/20000 train_loss:4.5787 train_time:372540ms step_avg:3725.40ms +step:200/20000 train_loss:3.9021 train_time:728965ms step_avg:3644.82ms +step:300/20000 train_loss:3.5985 train_time:1083940ms step_avg:3613.13ms +step:400/20000 train_loss:3.5688 train_time:1437722ms step_avg:3594.30ms +step:500/20000 train_loss:3.3891 train_time:1791044ms step_avg:3582.09ms +step:500/20000 val_loss:3.4605 val_bpb:1.3399 train_time:1791058ms step_avg:3582.12ms +step:600/20000 train_loss:3.4358 train_time:2143456ms step_avg:3572.43ms +step:700/20000 train_loss:3.2565 train_time:2496306ms step_avg:3566.15ms +step:800/20000 train_loss:3.3256 train_time:2848924ms step_avg:3561.16ms +step:900/20000 train_loss:3.3069 train_time:3202327ms step_avg:3558.14ms +step:1000/20000 train_loss:3.1493 train_time:3555544ms step_avg:3555.54ms +step:1000/20000 val_loss:3.2446 val_bpb:1.2563 train_time:3555557ms step_avg:3555.56ms +step:1100/20000 train_loss:3.2640 train_time:3907803ms step_avg:3552.55ms +step:1200/20000 train_loss:3.2861 train_time:4260381ms step_avg:3550.32ms +step:1300/20000 train_loss:3.2075 train_time:4613065ms step_avg:3548.51ms +step:1400/20000 train_loss:3.1347 train_time:4965354ms step_avg:3546.68ms +step:1500/20000 train_loss:3.1289 train_time:5317623ms step_avg:3545.08ms +step:1500/20000 val_loss:3.1848 val_bpb:1.2332 train_time:5317637ms step_avg:3545.09ms +step:1600/20000 train_loss:3.2271 train_time:5669616ms step_avg:3543.51ms +step:1700/20000 train_loss:3.2334 train_time:6021114ms step_avg:3541.83ms +step:1800/20000 train_loss:3.2202 train_time:6372976ms step_avg:3540.54ms +step:1900/20000 train_loss:3.2083 train_time:6724234ms step_avg:3539.07ms +step:2000/20000 train_loss:3.1804 train_time:7075462ms step_avg:3537.73ms +step:2000/20000 val_loss:3.1581 val_bpb:1.2228 train_time:7075476ms step_avg:3537.74ms +step:2100/20000 train_loss:3.1543 train_time:7427070ms step_avg:3536.70ms +step:2200/20000 train_loss:3.1508 train_time:7778959ms step_avg:3535.89ms +step:2300/20000 train_loss:3.2078 train_time:8130677ms step_avg:3535.08ms +step:2400/20000 train_loss:3.1717 train_time:8481904ms step_avg:3534.13ms +step:2500/20000 train_loss:3.1176 train_time:8832842ms step_avg:3533.14ms +step:2500/20000 val_loss:3.1152 val_bpb:1.2062 train_time:8832855ms step_avg:3533.14ms +step:2600/20000 train_loss:3.1138 train_time:9183450ms step_avg:3532.10ms +step:2700/20000 train_loss:3.0650 train_time:9534400ms step_avg:3531.26ms +step:2800/20000 train_loss:3.1137 train_time:9885541ms step_avg:3530.55ms +step:2900/20000 train_loss:3.1406 train_time:10236486ms step_avg:3529.82ms +step:3000/20000 train_loss:3.0061 train_time:10587256ms step_avg:3529.09ms +step:3000/20000 val_loss:3.0774 val_bpb:1.1916 train_time:10587270ms step_avg:3529.09ms +step:3100/20000 train_loss:3.0318 train_time:10938199ms step_avg:3528.45ms +step:3200/20000 train_loss:3.0729 train_time:11289299ms step_avg:3527.91ms +step:3300/20000 train_loss:3.1105 train_time:11640029ms step_avg:3527.28ms +step:3400/20000 train_loss:3.0548 train_time:11990781ms step_avg:3526.70ms +step:3500/20000 train_loss:3.0187 train_time:12341984ms step_avg:3526.28ms +step:3500/20000 val_loss:3.0381 val_bpb:1.1763 train_time:12341998ms step_avg:3526.29ms +step:3600/20000 train_loss:3.0227 train_time:12692976ms step_avg:3525.83ms +step:3700/20000 train_loss:3.0063 train_time:13043719ms step_avg:3525.33ms +step:3800/20000 train_loss:3.0847 train_time:13394611ms step_avg:3524.90ms +step:3900/20000 train_loss:2.9824 train_time:13745652ms step_avg:3524.53ms +step:4000/20000 train_loss:3.0537 train_time:14097299ms step_avg:3524.32ms +step:4000/20000 val_loss:2.9893 val_bpb:1.1575 train_time:14097312ms step_avg:3524.33ms +step:4100/20000 train_loss:3.1216 train_time:14448766ms step_avg:3524.09ms +step:4200/20000 train_loss:3.0200 train_time:14800284ms step_avg:3523.88ms +step:4300/20000 train_loss:2.9680 train_time:15151912ms step_avg:3523.70ms +step:4400/20000 train_loss:2.9587 train_time:15503681ms step_avg:3523.56ms +step:4500/20000 train_loss:2.8860 train_time:15855913ms step_avg:3523.54ms +step:4500/20000 val_loss:2.9351 val_bpb:1.1365 train_time:15855927ms step_avg:3523.54ms +step:4600/20000 train_loss:2.8808 train_time:16207775ms step_avg:3523.43ms +step:4700/20000 train_loss:2.8850 train_time:16560336ms step_avg:3523.48ms +step:4800/20000 train_loss:2.8994 train_time:16913487ms step_avg:3523.64ms +step:4900/20000 train_loss:2.9160 train_time:17265690ms step_avg:3523.61ms +step:5000/20000 train_loss:2.8048 train_time:17617580ms step_avg:3523.52ms +step:5000/20000 val_loss:2.8736 val_bpb:1.1127 train_time:17617592ms step_avg:3523.52ms +step:5100/20000 train_loss:2.8281 train_time:17968858ms step_avg:3523.31ms +step:5109/20000 val_loss:2.8668 val_bpb:1.1100 train_time:18000616ms step_avg:3523.32ms +stopping_early: wallclock_cap train_time:18000616ms step:5109/20000 +peak memory allocated: 18658 MiB reserved: 19596 MiB +eval:restored full crawler loops=2, depth=7 +swa:averaging 13 checkpoints +swa_eval val_loss:2.8647 val_bpb:1.1092 +Serialized model: 171404311 bytes +Code size: 91673 bytes +Total submission size: 171495984 bytes +Serialized model int8+zstd-22: 20267430 bytes (payload:47688648 raw_torch:47714205 payload_ratio:3.59x) +Total submission size int8+zlib: 20359103 bytes +final_int8_zlib_roundtrip val_loss:2.9642 val_bpb:1.1478 eval_time:87284ms +final_int8_zlib_roundtrip_exact val_loss:2.96424162 val_bpb:1.14775148 +gptq:loading calibration data from training shards... +gptq:loaded 64 calibration sequences in 4.6s +gptq:collecting hessians... +gptq:collected hessians for 32 layers +gptq:quantizing int6 with full Hessian GPTQ... +selective_prune: 8181846 candidates, unpruned=15.86MB target=15.9MB +selective_prune: already fits, no pruning needed +gptq_int6_brotli: 15,772,447 bytes | code: 91,673 | total: 15,864,120 (15.86MB) +gptq_int6_brotli_roundtrip val_loss:3.0608 val_bpb:1.1851 time:282.4s +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633536 stride=64 +ttt_sliding:params unfrozen=32204852 frozen=15228960 + ttt_chunk [1/1238] bpb=1.248939 time=5.1s + ttt_chunk [11/1238] bpb=1.162294 time=60.3s + ttt_chunk [21/1238] bpb=1.162652 time=115.5s + ttt_chunk [31/1238] bpb=1.156642 time=170.5s + ttt_chunk [41/1238] bpb=1.162459 time=225.5s + ttt_chunk [51/1238] bpb=1.157300 time=280.4s + ttt_chunk [61/1238] bpb=1.153052 time=335.3s + ttt_chunk [71/1238] bpb=1.154819 time=390.1s + ttt_chunk [81/1238] bpb=1.150193 time=445.0s + ttt_chunk [91/1238] bpb=1.147784 time=499.8s + ttt_chunk [101/1238] bpb=1.147402 time=554.7s + ttt_chunk [111/1238] bpb=1.149353 time=609.5s + ttt_chunk [121/1238] bpb=1.149964 time=664.4s + ttt_chunk [131/1238] bpb=1.152001 time=719.3s + ttt_chunk [141/1238] bpb=1.150702 time=774.2s + ttt_chunk [151/1238] bpb=1.150678 time=829.0s + ttt_chunk [161/1238] bpb=1.149908 time=883.9s + ttt_chunk [171/1238] bpb=1.149579 time=938.8s + ttt_chunk [181/1238] bpb=1.148955 time=993.7s + ttt_chunk [191/1238] bpb=1.149214 time=1048.6s + ttt_chunk [201/1238] bpb=1.149591 time=1103.4s + ttt_chunk [211/1238] bpb=1.150224 time=1158.3s + ttt_chunk [221/1238] bpb=1.149239 time=1213.3s + ttt_chunk [231/1238] bpb=1.149815 time=1268.2s + ttt_chunk [241/1238] bpb=1.149999 time=1323.2s + ttt_chunk [251/1238] bpb=1.149997 time=1378.1s + ttt_chunk [261/1238] bpb=1.150168 time=1433.1s + ttt_chunk [271/1238] bpb=1.148839 time=1488.0s + ttt_chunk [281/1238] bpb=1.149473 time=1542.9s + ttt_chunk [291/1238] bpb=1.148374 time=1597.8s + ttt_chunk [301/1238] bpb=1.148251 time=1652.7s + ttt_chunk [311/1238] bpb=1.147950 time=1707.6s + ttt_chunk [321/1238] bpb=1.147763 time=1762.5s + ttt_chunk [331/1238] bpb=1.147196 time=1817.4s + ttt_chunk [341/1238] bpb=1.146427 time=1872.3s + ttt_chunk [351/1238] bpb=1.146782 time=1927.2s + ttt_chunk [361/1238] bpb=1.146430 time=1982.1s + ttt_chunk [371/1238] bpb=1.145989 time=2037.0s + ttt_chunk [381/1238] bpb=1.145470 time=2091.9s + ttt_chunk [391/1238] bpb=1.144914 time=2146.8s + ttt_chunk [401/1238] bpb=1.144384 time=2201.6s + ttt_chunk [411/1238] bpb=1.143933 time=2256.5s + ttt_chunk [421/1238] bpb=1.143504 time=2311.4s + ttt_chunk [431/1238] bpb=1.142495 time=2366.3s + ttt_chunk [441/1238] bpb=1.141664 time=2421.3s + ttt_chunk [451/1238] bpb=1.141655 time=2476.2s + ttt_chunk [461/1238] bpb=1.140431 time=2531.2s + ttt_chunk [471/1238] bpb=1.140271 time=2586.1s + ttt_chunk [481/1238] bpb=1.140502 time=2641.0s + ttt_chunk [491/1238] bpb=1.140040 time=2696.0s + ttt_chunk [501/1238] bpb=1.140025 time=2750.9s + ttt_chunk [511/1238] bpb=1.140027 time=2805.9s + ttt_chunk [521/1238] bpb=1.139638 time=2860.8s + ttt_chunk [531/1238] bpb=1.139619 time=2915.7s + ttt_chunk [541/1238] bpb=1.139468 time=2970.6s + ttt_chunk [551/1238] bpb=1.138945 time=3025.4s + ttt_chunk [561/1238] bpb=1.138870 time=3080.4s + ttt_chunk [571/1238] bpb=1.139131 time=3135.3s + ttt_chunk [581/1238] bpb=1.138834 time=3190.2s + ttt_chunk [591/1238] bpb=1.138393 time=3245.1s + ttt_chunk [601/1238] bpb=1.138316 time=3300.0s + ttt_chunk [611/1238] bpb=1.138192 time=3354.9s + ttt_chunk [621/1238] bpb=1.138745 time=3409.9s + ttt_chunk [631/1238] bpb=1.138999 time=3464.9s + ttt_chunk [641/1238] bpb=1.139381 time=3519.8s + ttt_chunk [651/1238] bpb=1.139376 time=3574.7s + ttt_chunk [661/1238] bpb=1.139732 time=3629.5s + ttt_chunk [671/1238] bpb=1.140102 time=3684.4s + ttt_chunk [681/1238] bpb=1.140742 time=3739.3s + ttt_chunk [691/1238] bpb=1.140793 time=3794.2s + ttt_chunk [701/1238] bpb=1.140860 time=3849.1s + ttt_chunk [711/1238] bpb=1.141109 time=3904.0s + ttt_chunk [721/1238] bpb=1.141238 time=3958.9s + ttt_chunk [731/1238] bpb=1.140880 time=4013.9s + ttt_chunk [741/1238] bpb=1.140521 time=4068.9s + ttt_chunk [751/1238] bpb=1.140244 time=4123.8s + ttt_chunk [761/1238] bpb=1.140079 time=4178.7s + ttt_chunk [771/1238] bpb=1.139544 time=4233.7s + ttt_chunk [781/1238] bpb=1.139895 time=4288.6s + ttt_chunk [791/1238] bpb=1.139411 time=4343.5s + ttt_chunk [801/1238] bpb=1.139696 time=4398.4s + ttt_chunk [811/1238] bpb=1.139270 time=4453.3s + ttt_chunk [821/1238] bpb=1.138571 time=4508.2s + ttt_chunk [831/1238] bpb=1.138163 time=4563.1s + ttt_chunk [841/1238] bpb=1.137749 time=4618.1s + ttt_chunk [851/1238] bpb=1.137412 time=4673.0s + ttt_chunk [861/1238] bpb=1.137022 time=4727.9s + ttt_chunk [871/1238] bpb=1.136573 time=4782.8s + ttt_chunk [881/1238] bpb=1.136273 time=4837.7s + ttt_chunk [891/1238] bpb=1.136376 time=4892.7s + ttt_chunk [901/1238] bpb=1.136715 time=4947.6s + ttt_chunk [911/1238] bpb=1.136569 time=5002.5s + ttt_chunk [921/1238] bpb=1.136663 time=5057.5s + ttt_chunk [931/1238] bpb=1.136601 time=5112.4s + ttt_chunk [941/1238] bpb=1.136975 time=5167.4s + ttt_chunk [951/1238] bpb=1.136850 time=5222.4s + ttt_chunk [961/1238] bpb=1.137346 time=5277.4s + ttt_chunk [971/1238] bpb=1.137488 time=5332.4s + ttt_chunk [981/1238] bpb=1.137524 time=5387.3s + ttt_chunk [991/1238] bpb=1.137473 time=5442.3s + ttt_chunk [1001/1238] bpb=1.137776 time=5497.2s + ttt_chunk [1011/1238] bpb=1.137912 time=5552.2s + ttt_chunk [1021/1238] bpb=1.138131 time=5607.2s + ttt_chunk [1031/1238] bpb=1.138305 time=5662.1s + ttt_chunk [1041/1238] bpb=1.138413 time=5717.0s + ttt_chunk [1051/1238] bpb=1.138643 time=5771.9s + ttt_chunk [1061/1238] bpb=1.138599 time=5826.9s + ttt_chunk [1071/1238] bpb=1.138614 time=5881.9s + ttt_chunk [1081/1238] bpb=1.138678 time=5936.9s + ttt_chunk [1091/1238] bpb=1.138871 time=5991.8s + ttt_chunk [1101/1238] bpb=1.139046 time=6046.7s + ttt_chunk [1111/1238] bpb=1.139091 time=6101.7s + ttt_chunk [1121/1238] bpb=1.139020 time=6156.7s + ttt_chunk [1131/1238] bpb=1.139082 time=6211.6s + ttt_chunk [1141/1238] bpb=1.138769 time=6266.6s + ttt_chunk [1151/1238] bpb=1.138696 time=6321.5s + ttt_chunk [1161/1238] bpb=1.138569 time=6376.5s + ttt_chunk [1171/1238] bpb=1.138172 time=6431.5s + ttt_chunk [1181/1238] bpb=1.138022 time=6486.4s + ttt_chunk [1191/1238] bpb=1.138013 time=6541.4s + ttt_chunk [1201/1238] bpb=1.137960 time=6596.3s + ttt_chunk [1211/1238] bpb=1.137615 time=6651.3s + ttt_chunk [1221/1238] bpb=1.137534 time=6706.3s + ttt_chunk [1231/1238] bpb=1.137221 time=6761.3s + ttt_chunk [1238/1238] bpb=1.137241 time=6796.1s +ttt_sliding:done val_loss=2.937048 val_bpb=1.137241 elapsed=6796.3s +final_ttt_sliding val_loss:2.9370 val_bpb:1.1372 eval_time:6796500ms diff --git a/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_gpt.py b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_gpt.py new file mode 100644 index 0000000000..fd3201ccea --- /dev/null +++ b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_gpt.py @@ -0,0 +1,2012 @@ +from __future__ import annotations + +import copy +import datetime +import glob +import io +import math +import os +import random +import subprocess +import sys +import time +import uuid +import zlib +import brotli +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 + +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", 1337)) + + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 500)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 100)) + + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 2000)) + warmdown_frac = float(os.environ.get("WARMDOWN_FRAC", 0.6)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 100)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 524_288)) + 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_flat_blocks = int(os.environ.get("NUM_FLAT_BLOCKS", 3)) + num_crawler_blocks = int(os.environ.get("NUM_CRAWLER_BLOCKS", 2)) + crawler_loops = int(os.environ.get("CRAWLER_LOOPS", 2)) + progressive_schedule = os.environ.get("PROGRESSIVE_SCHEDULE", "") + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 8)) + model_dim = int(os.environ.get("MODEL_DIM", 704)) + num_heads = int(os.environ.get("NUM_HEADS", 16)) + mlp_mult = int(os.environ.get("MLP_MULT", 4)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + rope_dims = int(os.environ.get("ROPE_DIMS", 0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) + temperature = float(os.environ.get("TEMPERATURE", 1.0)) + use_smear_gate = bool(int(os.environ.get("USE_SMEAR_GATE", "1"))) + qat_enabled = bool(int(os.environ.get("QAT_ENABLED", "1"))) + qat_bits = int(os.environ.get("QAT_BITS", 6)) + qat_mlp_bits = int(os.environ.get("QAT_MLP_BITS", 0)) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", 1.0)) + bigram_buckets = int(os.environ.get("BIGRAM_BUCKETS", 10240)) + bigram_dim = int(os.environ.get("BIGRAM_DIM", 128)) + embed_bottleneck = int(os.environ.get("EMBED_BOTTLENECK", 0)) + ve_enabled = bool(int(os.environ.get("VE_ENABLED", "1"))) + ve_dim = int(os.environ.get("VE_DIM", 128)) + ve_last_n = int(os.environ.get("VE_LAST_N", 2)) + + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.0)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.02)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.02)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.01)) + 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.85)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.3)) + weight_decay = float(os.environ.get("WEIGHT_DECAY", 0.085)) + resume_from = os.environ.get("RESUME_FROM", "") + + swa_start_frac = float(os.environ.get("SWA_START_FRAC", 0.2)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + + ema_decay = float(os.environ.get("EMA_DECAY", 0.0)) + + sliding_window_stride = int(os.environ.get("SLIDING_WINDOW_STRIDE", 64)) + + ttt_enabled = bool(int(os.environ.get("TTT_ENABLED", "1"))) + ttt_lr = float(os.environ.get("TTT_LR", 0.002)) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", 3)) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 1)) + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", 0.9)) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", 32)) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", 1.0)) + +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 10, eps: float = 1e-7) -> Tensor: + a, b, c = (3.4445, -4.7750, 2.0315) + X = G.bfloat16() + X /= X.norm() + eps + transposed = G.size(0) > G.size(1) + if transposed: + X = X.T + for _ in range(steps): + A = X @ X.T + B = b * A + c * A @ A + X = a * X + B @ X + return X.T if transposed else X + +class Muon(torch.optim.Optimizer): + def __init__(self, params, lr: float, momentum: float, backend_steps: int, nesterov: bool = True, weight_decay: float = 0.0): + super().__init__( + params, + dict(lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov, weight_decay=weight_decay), + ) + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + distributed = dist.is_available() and dist.is_initialized() + world_size = dist.get_world_size() if distributed else 1 + rank = dist.get_rank() if distributed else 0 + + for group in self.param_groups: + params = group["params"] + if not params: + continue + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + + total_params = sum(int(p.numel()) for p in params) + updates_flat = torch.zeros(total_params, device=params[0].device, dtype=torch.bfloat16) + + curr = 0 + for i, p in enumerate(params): + if i % world_size == rank and p.grad is not None: + g = p.grad + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(g) + if nesterov: + g = g.add(buf, alpha=momentum) + g = zeropower_via_newtonschulz5(g, steps=backend_steps) + g *= max(1, g.size(0) / g.size(1)) ** 0.5 + updates_flat[curr : curr + p.numel()] = g.reshape(-1) + curr += p.numel() + + if distributed: + dist.all_reduce(updates_flat, op=dist.ReduceOp.SUM) + + wd = group.get("weight_decay", 0.0) + curr = 0 + for p in params: + g = updates_flat[curr : curr + p.numel()].view_as(p).to(dtype=p.dtype) + p.add_(g, alpha=-lr) + if wd > 0: + p.mul_(1.0 - lr * wd) + curr += p.numel() + + return loss + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + sp_vocab_size = int(sp.vocab_size()) + table_size = max(sp_vocab_size, vocab_size) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + for token_id in range(sp_vocab_size): + if sp.is_control(token_id) or sp.is_unknown(token_id) or sp.is_unused(token_id): + continue + is_boundary_token_np[token_id] = False + if sp.is_byte(token_id): + base_bytes_np[token_id] = 1 + continue + piece = sp.id_to_piece(token_id) + if piece.startswith("▁"): + has_leading_space_np[token_id] = True + piece = piece[1:] + base_bytes_np[token_id] = len(piece.encode("utf-8")) + return ( + torch.tensor(base_bytes_np, dtype=torch.int16, device=device), + torch.tensor(has_leading_space_np, dtype=torch.bool, device=device), + torch.tensor(is_boundary_token_np, dtype=torch.bool, device=device), + ) + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + local_batch_tokens = args.val_batch_size // (world_size * grad_accum_steps) + if local_batch_tokens < args.train_seq_len: + raise ValueError( + "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) + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scales,mlp_scales,resid_mixes,q_gain,smear,skip_weights", + ).split(",") + if pattern +) +INT8_KEEP_FLOAT_FP32_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "INT8_KEEP_FLOAT_FP32_NAME_PATTERNS", + ",".join(CONTROL_TENSOR_NAME_PATTERNS), + ).split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 +INT8_KEEP_FLOAT_STORE_DTYPE = torch.float16 +INT8_PER_ROW_SCALE_DTYPE = torch.float16 +INT8_CLIP_PERCENTILE = 99.99984 +INT8_CLIP_Q = INT8_CLIP_PERCENTILE / 100.0 + +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def keep_float_tensor(name: str, t: Tensor, passthrough_orig_dtypes: dict[str, str]) -> Tensor: + if any(pattern in name for pattern in INT8_KEEP_FLOAT_FP32_NAME_PATTERNS): + return t.float().contiguous() + if t.dtype in {torch.float32, torch.bfloat16}: + passthrough_orig_dtypes[name] = str(t.dtype).removeprefix("torch.") + return t.to(dtype=INT8_KEEP_FLOAT_STORE_DTYPE).contiguous() + return t + +def _is_attn_weight(name: str) -> bool: + return any(k in name for k in ("c_q.weight", "c_k.weight", "c_v.weight", "attn.proj.weight")) + +GPTQ_PERCENTILES = [0.9999, 0.99995, 0.99999, 0.999995, 0.999999] + +def quantize_float_tensor(t: Tensor, n_bits: int = 8, sdclip_k: float = 0.0) -> tuple[Tensor, Tensor]: + max_val = 2 ** (n_bits - 1) - 1 + min_val = -(2 ** (n_bits - 1)) + t32 = t.float() + if t32.ndim == 2: + if sdclip_k > 0: + # SDClip: clip = k * std(row) + clip_abs = sdclip_k * t32.std(dim=1) + clip_abs = clip_abs.clamp_min(1e-8) + scale = (clip_abs / max_val).clamp_min(1.0 / max_val) + q = torch.clamp(torch.round(t32 / scale[:, None]), min_val, max_val).to(torch.int8) + return q.contiguous(), scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous() + # Fallback: percentile search + best_q = None + best_scale = None + best_err = None + for pct in GPTQ_PERCENTILES: + clip_abs = ( + torch.quantile(t32.abs(), pct, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + scale = (clip_abs / max_val).clamp_min(1.0 / max_val) + q = torch.clamp(torch.round(t32 / scale[:, None]), min_val, max_val).to(torch.int8) + recon = q.float() * scale[:, None] + err = (t32 - recon).pow(2).sum(dim=1) + if best_err is None: + best_q = q + best_scale = scale + best_err = err + else: + improved = err < best_err + if improved.any(): + best_q[improved] = q[improved] + best_scale[improved] = scale[improved] + best_err[improved] = err[improved] + return best_q.contiguous(), best_scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous() + + if sdclip_k > 0: + # SDClip for 1D: use global std + clip_abs = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + else: + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / max_val if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), min_val, max_val).to(torch.int8).contiguous() + return q, scale + +def quantize_state_dict_int8(state_dict: dict[str, Tensor], qat_bits: int = 8, qat_mlp_bits: int = 0): + quantized: dict[str, Tensor] = {} + scales: dict[str, Tensor] = {} + dtypes: dict[str, str] = {} + passthrough: dict[str, Tensor] = {} + passthrough_orig_dtypes: dict[str, str] = {} + qmeta: dict[str, dict[str, object]] = {} + stats = dict.fromkeys( + ("param_count", "num_tensors", "num_float_tensors", "num_nonfloat_tensors", "baseline_tensor_bytes", "int8_payload_bytes"), + 0, + ) + + for name, tensor in state_dict.items(): + t = tensor.detach().to("cpu").contiguous() + stats["param_count"] += int(t.numel()) + stats["num_tensors"] += 1 + stats["baseline_tensor_bytes"] += tensor_nbytes(t) + + if not t.is_floating_point(): + stats["num_nonfloat_tensors"] += 1 + passthrough[name] = t + stats["int8_payload_bytes"] += tensor_nbytes(t) + continue + + if t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + kept = keep_float_tensor(name, t, passthrough_orig_dtypes) + passthrough[name] = kept + stats["int8_payload_bytes"] += tensor_nbytes(kept) + continue + + stats["num_float_tensors"] += 1 + is_block_weight = any(k in name for k in ("flat_blocks.", "crawler_blocks.", "bigram.proj.")) + is_embed_weight = ("tok_emb.weight" in name) + is_mlp_weight = any(k in name for k in ("mlp.fc.weight", "mlp.proj.weight")) + if qat_bits < 8 and is_block_weight and t.ndim == 2: + n_bits = (qat_mlp_bits if (qat_mlp_bits > 0 and is_mlp_weight) else qat_bits) + sdclip_k = 12.85 + elif is_embed_weight: + n_bits = 8 + sdclip_k = 20.0 + else: + n_bits = 8 + sdclip_k = 20.0 + q, s = quantize_float_tensor(t, n_bits=n_bits, sdclip_k=sdclip_k) + if s.ndim > 0: + qmeta[name] = {"scheme": "per_row", "axis": 0} + quantized[name] = q + scales[name] = s + dtypes[name] = str(t.dtype).removeprefix("torch.") + stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + obj: dict[str, object] = { + "__quant_format__": "int8_clean_per_row_v1", + "quantized": quantized, + "scales": scales, + "dtypes": dtypes, + "passthrough": passthrough, + } + if qmeta: + obj["qmeta"] = qmeta + if passthrough_orig_dtypes: + obj["passthrough_orig_dtypes"] = passthrough_orig_dtypes + return obj, stats + +def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + qmeta = obj.get("qmeta", {}) + passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {}) + for name, q in obj["quantized"].items(): + dtype = getattr(torch, obj["dtypes"][name]) + s = obj["scales"][name] + if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: + s = s.to(dtype=torch.float32) + 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 + +def generate_calib_from_data(train_files, device, num_seqs=64, seq_len=2048, seed=42): + rng = random.Random(seed) + shard_files = sorted(glob.glob(train_files)) + all_tokens = [] + while len(all_tokens) < num_seqs: + shard = Path(rng.choice(shard_files)) + data = load_data_shard(shard) + max_start = data.numel() - seq_len - 1 + if max_start <= 0: + continue + start = rng.randint(0, max_start) + seq = data[start:start + seq_len + 1].unsqueeze(0).to(device=device, dtype=torch.int64) + all_tokens.append(seq) + return all_tokens[:num_seqs] + +def collect_hessians_from_tokens(hessian_model, token_seqs, device): + hessians = {} + hooks = [] + for name, module in hessian_model.named_modules(): + if isinstance(module, CastedLinear): + param_name = name + ".weight" + cols = module.weight.shape[1] + hessians[param_name] = torch.zeros(cols, cols, dtype=torch.float32, device='cpu') + def make_hook(pname): + def hook_fn(module, input, output): + x = input[0].detach().float() + if x.ndim == 3: + x = x.reshape(-1, x.shape[-1]) + hessians[pname] += (x.T @ x).cpu() + return hook_fn + h = module.register_forward_hook(make_hook(param_name)) + hooks.append(h) + hessian_model.eval() + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16): + for seq in token_seqs: + x = seq[:, :-1].to(device) + y = seq[:, 1:].to(device) + hessian_model(x, y) + for h in hooks: + h.remove() + for name in hessians: + H = hessians[name] + H /= len(token_seqs) + damp = 0.01 * torch.diag(H).mean().clamp_min(1e-6) + H += damp * torch.eye(H.shape[0]) + hessians[name] = H + return hessians + +def quantize_int6_gptq(weight, hessian=None, clip_range=31, block_size=128, sdclip_k: float = 0.0): + t32 = weight.float() + if t32.ndim != 2 or hessian is None: + return quantize_int6_per_row(t32, clip_range, sdclip_k=sdclip_k) + rows, cols = t32.shape + H = hessian.float().clone() + dead = torch.diag(H) == 0 + H[dead, dead] = 1 + damp = 0.01 * torch.mean(torch.diag(H)) + H[torch.arange(cols), torch.arange(cols)] += damp + perm = torch.argsort(torch.diag(H), descending=True) + inv_perm = torch.argsort(perm) + W = t32[:, perm].clone() + W[:, dead[perm]] = 0 + H = H[perm][:, perm] + try: + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + except torch._C._LinAlgError: + H[torch.arange(cols), torch.arange(cols)] += 0.1 * torch.mean(torch.diag(H)) + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + best_q = Q[:, inv_perm] + return best_q, s + best_q, best_scale, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + recon = Q.float() * sf[:, None] + mse = (W - recon).pow(2).mean().item() + if mse < best_err: + best_q, best_scale, best_err = Q, s, mse + best_q = best_q[:, inv_perm] + return best_q, best_scale + +def quantize_int6_per_row(t, clip_range=31, sdclip_k: float = 0.0): + t32 = t.float() if not t.is_floating_point() else t.float() + if t32.ndim == 2: + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + return q, s + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + recon = q.float() * s.float()[:, None] + err = (t32 - recon).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, s, err + return best_q, best_s + if sdclip_k > 0: + clip_val = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_val / clip_range if clip_val > 0 else 1.0, dtype=torch.float16) + else: + amax = t32.abs().max().item() + scale = torch.tensor(amax / clip_range if amax > 0 else 1.0, dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -clip_range, clip_range).to(torch.int8) + return q, scale + +def mixed_quantize_int6_gptq(state_dict, hessians=None): + result = {} + meta = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + if not t.is_floating_point() or t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + is_block = any(k in name for k in ("flat_blocks.", "crawler_blocks.")) + if is_block and t.ndim == 2: + H = hessians.get(name) if hessians else None + q, s = quantize_int6_gptq(t, hessian=H, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + else: + q, s = quantize_int6_per_row(t, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + return result, meta + +def dequantize_mixed_int6(result, meta, template_sd): + out = {} + for name, orig in template_sd.items(): + info = meta.get(name) + if info is None: + continue + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = 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) + +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) + +def _fake_quantize_ste(w: Tensor, n_bits: int) -> Tensor: + max_val = 2 ** (n_bits - 1) - 1 + min_val = -(2 ** (n_bits - 1)) + scale = w.abs().amax(dim=-1, keepdim=True) / max_val + scale = scale.clamp_min(1e-8) + w_q = (w / scale).round().clamp(min_val, max_val) * scale + return w + (w_q - w).detach() + +_QAT_ENABLED = False +_QAT_BITS = 6 +_QAT_MLP_BITS = 0 +_ACTIVE_CRAWLER_LOOPS = 1 + +class CastedLinear(nn.Linear): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._is_mlp = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if _QAT_ENABLED and self.weight.ndim == 2 and self.weight.numel() > 65536: + bits = (_QAT_MLP_BITS if (_QAT_MLP_BITS > 0 and self._is_mlp) else _QAT_BITS) + w = _fake_quantize_ste(w, bits) + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0): + super().__init__() + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + +class CausalSelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int, + rope_base: float, + qk_gain_init: float, + ): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + 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(3) + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, q_delta=None, v_delta=None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x) + (q_delta if q_delta is not None else 0) + k = self.c_k(x) + v = self.c_v(x) + (v_delta if v_delta is not None else 0) + q = q.reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = k.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = v.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + rope_dim = cos.size(-1) + partial = rope_dim // 2 + if partial > 0: + q_rope, q_pass = q[..., :partial*2], q[..., partial*2:] + k_rope, k_pass = k[..., :partial*2], k[..., partial*2:] + q_rope = apply_rotary_emb(q_rope, cos[..., :partial], sin[..., :partial]) + k_rope = apply_rotary_emb(k_rope, cos[..., :partial], sin[..., :partial]) + q = torch.cat([q_rope, q_pass], dim=-1) + k = torch.cat([k_rope, k_pass], dim=-1) + else: + 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 = self._xsa_efficient(y.transpose(1, 2), v.transpose(1, 2)).contiguous().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): + super().__init__() + hidden = mlp_mult * dim + self.fc = CastedLinear(dim, hidden, bias=False) + self.fc._is_mlp = True + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + self.proj._is_mlp = True + + def forward(self, x: Tensor) -> Tensor: + x = torch.relu(self.fc(x)) + return self.proj(x.square()) + +class ValueEmbedding(nn.Module): + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int, num_loops_active: int): + super().__init__() + self.table = nn.Embedding(vocab_size, ve_dim) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) + self.scales = nn.ParameterList([nn.Parameter(torch.ones(1)) for _ in range(num_loops_active)]) + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor, loop_idx: int) -> Tensor: + return self.scales[loop_idx] * self.proj(self.table(input_ids)) + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate).to(dtype=x.dtype) + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1.0 - g) * x + g * x_prev + +class BigramHashEmbedding(nn.Module): + def __init__(self, num_buckets: int, hash_dim: int, model_dim: int): + super().__init__() + self.num_buckets = num_buckets + self.table = nn.Embedding(num_buckets, hash_dim) + self.proj = CastedLinear(hash_dim, model_dim, bias=False) + self.proj._zero_init = True + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor) -> Tensor: + bsz, seqlen = input_ids.shape + prev_ids = torch.cat([ + torch.zeros(bsz, 1, dtype=input_ids.dtype, device=input_ids.device), + input_ids[:, :-1], + ], dim=1) + h = ((prev_ids.long() * 92821 + input_ids.long()) % self.num_buckets).long() + return self.proj(self.table(h)) + +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, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init) + self.mlp = MLP(dim, mlp_mult) + + def forward( + self, x: Tensor, x0: Tensor, + attn_scale: Tensor, mlp_scale: Tensor, resid_mix: Tensor, + q_delta_fn=None, v_delta_fn=None, v_embed=None, + ) -> Tensor: + mix = resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + n = self.attn_norm(x) + qd = q_delta_fn(n) if q_delta_fn is not None else None + vd = v_delta_fn(n) if v_delta_fn is not None else None + if v_embed is not None: + vd = (vd + v_embed) if vd is not None else v_embed + attn_out = self.attn(n, qd, vd) + x = x + attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x)) + return x + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_flat_blocks: int, + num_crawler_blocks: int, + crawler_loops: 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, + use_smear_gate: bool = True, + bigram_buckets: int = 10240, + bigram_dim: int = 128, + embed_bottleneck: int = 0, + ve_enabled: bool = False, + ve_dim: int = 128, + ve_last_n: int = 2, + temperature: float = 1.0, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.temperature = temperature + self.embed_bottleneck = embed_bottleneck + self.num_flat_blocks = num_flat_blocks + self.num_crawler_blocks = num_crawler_blocks + self.crawler_loops = crawler_loops + self._active_crawler_loops = crawler_loops + self._n_enc = num_flat_blocks // 2 + num_loops = num_flat_blocks + num_crawler_blocks * crawler_loops + self.num_loops = num_loops + if embed_bottleneck > 0: + self.tok_emb = nn.Embedding(vocab_size, embed_bottleneck) + self.embed_proj = CastedLinear(embed_bottleneck, model_dim, bias=False) + self.embed_proj_rev = CastedLinear(model_dim, embed_bottleneck, bias=False) + else: + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.embed_proj = None + self.embed_proj_rev = None + self.bigram = BigramHashEmbedding(bigram_buckets, bigram_dim, model_dim) + self.smear = SmearGate(model_dim) if use_smear_gate else None + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve = ValueEmbedding(vocab_size, ve_dim, kv_dim, ve_last_n) if ve_enabled else None + self.ve_last_n = ve_last_n + self.flat_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_flat_blocks) + ]) + self.crawler_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_crawler_blocks) + ]) + self.crawler_residual_scales = nn.ParameterList([ + nn.Parameter(torch.tensor(0.5, dtype=torch.float32)) + for _ in range(crawler_loops) + ]) + self.attn_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.mlp_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.resid_mixes = nn.Parameter( + torch.stack([ + torch.stack((torch.ones(model_dim), torch.zeros(model_dim))) + for _ in range(num_loops) + ]).float() + ) + self.num_encoder_loops = num_loops // 2 + self.num_decoder_loops = num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + self.skip_weights = nn.Parameter(torch.ones(self.num_skips, model_dim, dtype=torch.float32)) + self.xsa_last_n = int(os.environ.get("XSA_LAST_N", 7)) + 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._rebuild_schedule() + self._init_weights() + + def _rebuild_schedule(self, active_loops: int | None = None): + if active_loops is not None: + self._active_crawler_loops = active_loops + schedule = [] + for i in range(self._n_enc): + schedule.append(('flat', i)) + for loop in range(self._active_crawler_loops): + for c in range(self.num_crawler_blocks): + schedule.append(('crawler', c)) + for i in range(self._n_enc, self.num_flat_blocks): + schedule.append(('flat', i)) + self._loop_schedule = schedule + self.num_loops = len(schedule) + self.num_encoder_loops = self.num_loops // 2 + self.num_decoder_loops = self.num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + block_list = [] + for kind, idx in schedule: + block_list.append(self.flat_blocks[idx] if kind == 'flat' else self.crawler_blocks[idx]) + self._block_list = block_list + + def _get_block(self, loop_idx: int) -> 'Block': + return self._block_list[loop_idx] + + 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) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and min(module.weight.shape) >= 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 * self.num_loops)) + + def _embed(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.embed_proj is not None: + x = self.embed_proj(x) + return x + + def _logits(self, x: Tensor) -> Tensor: + if self.embed_proj_rev is not None: + x = self.embed_proj_rev(x) + logits = F.linear(x, self.tok_emb.weight) + elif self.tie_embeddings: + logits = F.linear(x, self.tok_emb.weight) + else: + logits = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits / self.logit_softcap) + + def _run_blocks(self, x, x0, input_ids, lora=None): + active_loops = _ACTIVE_CRAWLER_LOOPS + n_enc = self._n_enc + loop_idx = 0 + xsa_n = self.xsa_last_n + total_depth = self.num_flat_blocks + self.num_crawler_blocks * active_loops + + if xsa_n > 0: + for blk in self.flat_blocks: + blk.attn.use_xsa = (loop_idx >= total_depth - xsa_n) if loop_idx < n_enc or loop_idx >= n_enc + self.num_crawler_blocks * active_loops else False + loop_idx += 1 + for blk in self.crawler_blocks: + for _ in range(active_loops): + blk.attn.use_xsa = True + loop_idx = 0 + + skips: list[Tensor] = [] + for i in range(n_enc): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[i](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + skips.append(x) + loop_idx += 1 + + for lp in range(active_loops): + for ci, cblock in enumerate(self.crawler_blocks): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x_out = cblock(x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + if lp > 0: + alpha = self.crawler_residual_scales[lp].to(dtype=x.dtype) + x = x + alpha * (x_out - x) + else: + x = x_out + loop_idx += 1 + + n_dec_flat = self.num_flat_blocks - n_enc + for i in range(n_dec_flat): + fi = n_enc + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[fi](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + loop_idx += 1 + return x + + def forward(self, input_ids: Tensor, target_ids: Tensor, lora=None) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids, lora) + unused = sum(p.sum() * 0.0 for p in self.crawler_residual_scales) + x = x + unused + x = self.final_norm(x) + logits = self._logits(x) + logits = logits + (lora.lm_head_lora(x) if lora else 0) + if lora: + bsz, sl, V = logits.shape + return F.cross_entropy( + logits.float().reshape(-1, V), target_ids.reshape(-1), reduction="none").reshape(bsz, sl) + return F.cross_entropy(logits.float().reshape(-1, logits.size(-1)), target_ids.reshape(-1), reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids) + x = self.final_norm(x) + return self._logits(x) + +def _compute_chunk_window(ci: int, pred_len: int, num_chunks: int, chunk_size: int, eval_seq_len: int): + chunk_start = ci * chunk_size + chunk_end = pred_len if ci == num_chunks - 1 else (ci + 1) * chunk_size + win_start = max(0, chunk_end - eval_seq_len) + win_len = chunk_end - win_start + chunk_offset = chunk_start - win_start + chunk_len = chunk_end - chunk_start + return win_start, win_len, chunk_offset, chunk_len + +def _accumulate_bpb( + ptl: Tensor, x: Tensor, y: Tensor, + batch_i: int, chunk_offset: int, chunk_len: int, + base_bytes_lut: Tensor, has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + loss_sum: Tensor, byte_sum: Tensor, token_count: Tensor, +): + lbl = ptl[batch_i, chunk_offset:chunk_offset + chunk_len].to(torch.float64) + prev = x[batch_i, chunk_offset:chunk_offset + chunk_len] + tgt = y[batch_i, chunk_offset:chunk_offset + chunk_len] + tok_bytes = base_bytes_lut[tgt].to(torch.float64) + tok_bytes += has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev] + loss_sum += lbl.sum() + byte_sum += tok_bytes.sum() + token_count += chunk_len + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: GPT, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + 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}") + + 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_blocks = min(args.ttt_freeze_blocks, base_model.num_flat_blocks + base_model.num_crawler_blocks) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = False + for bi in range(freeze_blocks): + if f"flat_blocks.{bi}." in name or f"crawler_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)}") + + 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 + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + 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 = [] + 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) + loss_sum += nll[i, s:wlen].to(torch.float64).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() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + 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) + start_tok = chunk_start + (my_seq_s + bs) * seq_len + end_tok = chunk_start + (my_seq_s + 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) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or is_last_chunk): + 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)) + 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 + +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 = "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, timeout=datetime.timedelta(seconds=1800)) + 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) + torch._dynamo.config.optimize_ddp = 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) + + 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}") + + base_model = GPT( + vocab_size=args.vocab_size, + num_flat_blocks=args.num_flat_blocks, + num_crawler_blocks=args.num_crawler_blocks, + crawler_loops=args.crawler_loops, + 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, + temperature=args.temperature, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + use_smear_gate=args.use_smear_gate, + bigram_buckets=args.bigram_buckets, + bigram_dim=args.bigram_dim, + embed_bottleneck=args.embed_bottleneck, + ve_enabled=args.ve_enabled, + ve_dim=args.ve_dim, + ve_last_n=args.ve_last_n, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + if isinstance(module, Rotary): + module.inv_freq.data = module.inv_freq.data.float() + restore_low_dim_params_to_fp32(base_model) + + if args.resume_from and os.path.isfile(args.resume_from): + log0(f"resuming_from:{args.resume_from}") + saved = torch.load(args.resume_from, map_location=device) + base_model.load_state_dict(saved, strict=True) + restore_low_dim_params_to_fp32(base_model) + log0("resume:loaded model weights (optimizer states reset)") + global _QAT_ENABLED, _QAT_BITS, _QAT_MLP_BITS, _ACTIVE_CRAWLER_LOOPS + _QAT_BITS = args.qat_bits + _QAT_MLP_BITS = args.qat_mlp_bits + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + _qat_activated = False + if args.qat_enabled and args.late_qat_threshold >= 1.0: + _QAT_ENABLED = True + _qat_activated = True + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:enabled from step 0 attn={_QAT_BITS}bit{mlp_info}") + elif args.qat_enabled: + _QAT_ENABLED = False + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:late_start threshold={args.late_qat_threshold} attn={_QAT_BITS}bit{mlp_info}") + else: + _QAT_ENABLED = False + _use_compile = bool(int(os.environ.get("TORCH_COMPILE", "1"))) + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) if _use_compile else base_model + _use_ddp = distributed and world_size > 1 + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + + block_named_params = list(base_model.flat_blocks.named_parameters()) + list(base_model.crawler_blocks.named_parameters()) + matrix_params = [ + p + for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p + for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params.append(base_model.attn_scales) + scalar_params.append(base_model.mlp_scales) + scalar_params.append(base_model.resid_mixes) + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + if base_model.smear is not None: + scalar_params.append(base_model.smear.gate) + bigram_named = list(base_model.bigram.named_parameters()) + for name, p in bigram_named: + if p.ndim == 2 and "proj" in name: + matrix_params.append(p) + elif p.ndim == 2: + pass + else: + scalar_params.append(p) + ve_table_params = [] + if base_model.ve is not None: + for name, p in base_model.ve.named_parameters(): + if "table" in name: + ve_table_params.append(p) + elif p.ndim == 2: + matrix_params.append(p) + else: + scalar_params.append(p) + 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, base_model.bigram.table.weight] + + ([base_model.embed_proj.weight, base_model.embed_proj_rev.weight] if base_model.embed_proj is not None else []) + + ve_table_params, + "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.weight_decay, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + flat_params = sum(p.numel() for p in base_model.flat_blocks.parameters()) + crawler_params = sum(p.numel() for p in base_model.crawler_blocks.parameters()) + loop_params = base_model.attn_scales.numel() + base_model.mlp_scales.numel() + base_model.resid_mixes.numel() + log0(f"architecture:crawler flat_blocks:{args.num_flat_blocks} crawler_blocks:{args.num_crawler_blocks} crawler_loops:{args.crawler_loops} effective_depth:{base_model.num_loops} flat_params:{flat_params} crawler_params:{crawler_params} per_loop_params:{loop_params}") + log0(f"model_params:{n_params}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + 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_frac > 0 and max_wallclock_ms is not None: + warmdown_ms = args.warmdown_frac * max_wallclock_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.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 + + progressive_steps: list[tuple[int, int]] = [] + if args.progressive_schedule: + for entry in args.progressive_schedule.split(","): + s, loops = entry.strip().split(":") + progressive_steps.append((int(s), int(loops))) + progressive_steps.sort() + + 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] + prog_variants = sorted(set([1] + [loops for _, loops in progressive_steps])) if progressive_steps else [base_model._active_crawler_loops] + steps_per_variant = max(1, args.warmup_steps // (len(prog_variants) * 2)) + model.train() + warmup_step = 0 + for variant_loops in prog_variants: + if variant_loops != base_model._active_crawler_loops: + base_model._rebuild_schedule(active_loops=variant_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"warmup:precompile variant={variant_loops} loops, depth={base_model.num_loops}") + for _ in range(steps_per_variant): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{args.warmup_steps}") + remaining = args.warmup_steps - warmup_step + if remaining > 0: + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + for _ in range(remaining): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{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() + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + if _use_ddp: + model.require_backward_grad_sync = True + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + if progressive_steps: + _ACTIVE_CRAWLER_LOOPS = 1 + log0(f"progressive:enabled schedule={progressive_steps} starting with 1 crawler loop") + else: + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + _current_crawler_loops = _ACTIVE_CRAWLER_LOOPS + + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_checkpoints: list[dict[str, Tensor]] = [] + ema_sd: dict[str, Tensor] | None = None + if args.ema_decay > 0: + ema_sd = {k: v.detach().float().clone() for k, v in base_model.state_dict().items()} + log0(f"ema:enabled decay={args.ema_decay}") + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_activated and scale <= args.late_qat_threshold: + _QAT_ENABLED = True + _qat_activated = True + log0(f"late_qat:activated at step {step} scale={scale:.4f} threshold={args.late_qat_threshold}") + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + if args.swa_start_frac > 0 and step % args.swa_every == 0: + should_collect = torch.tensor(int(scale < args.swa_start_frac), device=device) + if distributed: + dist.all_reduce(should_collect, op=dist.ReduceOp.MIN) + if should_collect.item(): + swa_checkpoints.append({k: v.detach().cpu().clone() for k, v in base_model.state_dict().items()}) + + if ema_sd is not None: + d = args.ema_decay + with torch.no_grad(): + for k, v in base_model.state_dict().items(): + ema_sd[k].mul_(d).add_(v.detach().float(), alpha=1.0 - d) + + step += 1 + for prog_step, prog_loops in progressive_steps: + if step == prog_step and prog_loops != _current_crawler_loops: + _ACTIVE_CRAWLER_LOOPS = prog_loops + _current_crawler_loops = prog_loops + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"progressive:step {step} -> {prog_loops} crawler loops, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * prog_loops} (recompiled)") + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + _QAT_ENABLED = False + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + log0(f"eval:restored full crawler loops={args.crawler_loops}, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * args.crawler_loops}") + + if swa_checkpoints: + log0(f"swa:averaging {len(swa_checkpoints)} checkpoints") + avg_sd = {} + for key in swa_checkpoints[0]: + stacked = torch.stack([ckpt[key].float() for ckpt in swa_checkpoints]) + avg_sd[key] = stacked.mean(dim=0).to(dtype=swa_checkpoints[0][key].dtype) + base_model.load_state_dict(avg_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + swa_val_loss, swa_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"swa_eval val_loss:{swa_val_loss:.4f} val_bpb:{swa_val_bpb:.4f}") + del swa_checkpoints + + if ema_sd is not None: + log0("ema:loading averaged weights") + model_sd = base_model.state_dict() + for k in ema_sd: + ema_sd[k] = ema_sd[k].to(dtype=model_sd[k].dtype, device=model_sd[k].device) + base_model.load_state_dict(ema_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + ema_val_loss, ema_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"ema_eval val_loss:{ema_val_loss:.4f} val_bpb:{ema_val_bpb:.4f}") + del ema_sd + + if master_process: + torch.save(base_model.state_dict(), "final_model.pt") + import shutil + shutil.copy2("final_model.pt", f"final_model_{args.run_id}.pt") + log0(f"saved backup: final_model_{args.run_id}.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + quant_obj, quant_stats = quantize_state_dict_int8( + base_model.state_dict(), + qat_bits=args.qat_bits if args.qat_enabled else 8, + qat_mlp_bits=args.qat_mlp_bits if args.qat_enabled else 0, + ) + quant_buf = io.BytesIO() + torch.save(quant_obj, quant_buf) + quant_raw = quant_buf.getvalue() + try: + import zstandard as zstd + quant_blob = zstd.ZstdCompressor(level=22).compress(quant_raw) + compress_method = "zstd-22" + except ImportError: + quant_blob = zlib.compress(quant_raw, level=9) + compress_method = "zlib-9" + quant_raw_bytes = len(quant_raw) + if master_process: + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int8_payload_bytes"], 1) + log0( + f"Serialized model int8+{compress_method}: {quant_file_bytes} bytes " + f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" + ) + log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + try: + import zstandard as zstd + decompressed = zstd.ZstdDecompressor().decompress(quant_blob_disk) + except Exception: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + torch.cuda.synchronize() + t_qeval = time.perf_counter() + q_val_loss, q_val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + if master_process: + log0("gptq:loading calibration data from training shards...") + base_model.load_state_dict(torch.load("final_model.pt", map_location=device), strict=True) + restore_low_dim_params_to_fp32(base_model) + t_gptq = time.perf_counter() + ar_tokens = generate_calib_from_data( + args.train_files, device, num_seqs=64, seq_len=args.train_seq_len, seed=args.seed, + ) + log0(f"gptq:loaded {len(ar_tokens)} calibration sequences in {time.perf_counter()-t_gptq:.1f}s") + log0("gptq:collecting hessians...") + hessians = collect_hessians_from_tokens(base_model, ar_tokens, device) + log0(f"gptq:collected hessians for {len(hessians)} layers") + del ar_tokens + torch.cuda.empty_cache() + log0("gptq:quantizing int6 with full Hessian GPTQ...") + gptq_result, gptq_meta = mixed_quantize_int6_gptq( + base_model.state_dict(), hessians=hessians, + ) + del hessians + target_bytes = 15_900_000 + code_bytes = len(code.encode("utf-8")) + ones_info = [] + for name, info in gptq_meta.items(): + if not (isinstance(info, dict) and info.get("type") == "int6"): + continue + qk, sk = name + ".q", name + ".scale" + if qk not in gptq_result or sk not in gptq_result: + continue + q, s = gptq_result[qk], gptq_result[sk] + if s.ndim > 0: + ones_mask = (q.abs() == 1) + if ones_mask.any(): + row_idx = torch.arange(q.shape[0]).unsqueeze(1).expand_as(q)[ones_mask] + flat_idx = torch.arange(q.numel()).reshape(q.shape)[ones_mask] + errors = s.float()[row_idx].pow(2) + for fi, err in zip(flat_idx.tolist(), errors.tolist()): + ones_info.append((qk, fi, err)) + ones_info.sort(key=lambda x: x[2]) + def _try_prune(n): + tmp = {k: v.clone() for k, v in gptq_result.items()} + for i in range(min(n, len(ones_info))): + tmp[ones_info[i][0]].view(-1)[ones_info[i][1]] = 0 + buf = io.BytesIO() + torch.save({"w": tmp, "m": gptq_meta}, buf) + return len(brotli.compress(buf.getvalue(), quality=11)) + code_bytes, tmp + no_prune_sz, _ = _try_prune(0) + log0(f"selective_prune: {len(ones_info)} candidates, unpruned={no_prune_sz/1e6:.2f}MB target={target_bytes/1e6:.1f}MB") + if no_prune_sz <= target_bytes: + log0("selective_prune: already fits, no pruning needed") + final_result = gptq_result + else: + full_sz, _ = _try_prune(len(ones_info)) + log0(f"selective_prune: full prune={full_sz/1e6:.2f}MB") + if full_sz > target_bytes: + log0("selective_prune: even full prune not enough, applying all") + _, final_result = _try_prune(len(ones_info)) + else: + lo, hi = 0, len(ones_info) + while lo < hi: + mid = (lo + hi) // 2 + sz, _ = _try_prune(mid) + if sz <= target_bytes: + hi = mid + else: + lo = mid + 1 + log0(f"selective_prune: pruning {lo}/{len(ones_info)} values ({100*lo/len(ones_info):.1f}%) to fit") + _, final_result = _try_prune(lo) + gptq_buf = io.BytesIO() + torch.save({"w": final_result, "m": gptq_meta}, gptq_buf) + gptq_raw = gptq_buf.getvalue() + gptq_blob = brotli.compress(gptq_raw, quality=11) + gptq_bytes = len(gptq_blob) + total_bytes = gptq_bytes + code_bytes + log0(f"gptq_int6_brotli: {gptq_bytes:,} bytes | code: {code_bytes:,} | total: {total_bytes:,} ({total_bytes/1e6:.2f}MB)") + with open("final_model.int6_gptq.ptz", "wb") as f: + f.write(gptq_blob) + gptq_state = torch.load( + io.BytesIO(brotli.decompress(gptq_blob)), map_location="cpu", weights_only=False + ) + restored = dequantize_mixed_int6(gptq_state["w"], gptq_state["m"], base_model.state_dict()) + base_model.load_state_dict(restored, strict=True) + restore_low_dim_params_to_fp32(base_model) + gq_val_loss, gq_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"gptq_int6_brotli_roundtrip val_loss:{gq_val_loss:.4f} val_bpb:{gq_val_bpb:.4f} time:{time.perf_counter()-t_gptq:.1f}s") + + if args.ttt_enabled: + torch._dynamo.reset() + # TTT runs on the GPTQ artifact (already loaded at line 1980-1982) + torch.cuda.synchronize() + t_ttt_sw = time.perf_counter() + all_val_tokens = torch.cat([load_data_shard(Path(p)) for p in sorted(glob.glob(args.val_files))]).contiguous() + ttt_sw_loss, ttt_sw_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + all_val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.sliding_window_stride if args.sliding_window_stride > 0 else 64, + log0=log0, + ) + torch.cuda.synchronize() + log0( + f"final_ttt_sliding val_loss:{ttt_sw_loss:.4f} val_bpb:{ttt_sw_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt_sw):.0f}ms" + ) + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main() + diff --git a/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_seed1337.log b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_seed1337.log new file mode 100644 index 0000000000..59bb933e90 --- /dev/null +++ b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_seed1337.log @@ -0,0 +1,2248 @@ +logs/v5_d736_honest_seed1337.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_8192_bpe.model +train_loader:dataset:fineweb10B_sp8192 train_shards:128 +val_loader:shards pattern=./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin tokens:40546304 +qat:enabled from step 0 attn=6bit +architecture:crawler flat_blocks:3 crawler_blocks:2 crawler_loops:2 effective_depth:7 flat_params:17876016 crawler_params:11917344 per_loop_params:20608 +model_params:38346836 +world_size:1 grad_accum_steps:8 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:16 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:18000.000 +seed:1337 +warmup_step:1/100 +warmup_step:2/100 +warmup_step:3/100 +warmup_step:4/100 +warmup_step:5/100 +warmup_step:6/100 +warmup_step:7/100 +warmup_step:8/100 +warmup_step:9/100 +warmup_step:10/100 +warmup_step:11/100 +warmup_step:12/100 +warmup_step:13/100 +warmup_step:14/100 +warmup_step:15/100 +warmup_step:16/100 +warmup_step:17/100 +warmup_step:18/100 +warmup_step:19/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:8.9999 val_bpb:3.4847 train_time:0ms step_avg:0.01ms +step:1/20000 train_loss:9.0002 train_time:9417ms step_avg:9416.77ms +step:2/20000 train_loss:8.8349 train_time:12288ms step_avg:6144.07ms +step:3/20000 train_loss:9.4661 train_time:15200ms step_avg:5066.65ms +step:4/20000 train_loss:9.2167 train_time:18126ms step_avg:4531.58ms +step:5/20000 train_loss:8.9424 train_time:21063ms step_avg:4212.63ms +step:6/20000 train_loss:8.5051 train_time:24012ms step_avg:4002.02ms +step:7/20000 train_loss:8.0528 train_time:26972ms step_avg:3853.10ms +step:8/20000 train_loss:7.6669 train_time:29938ms step_avg:3742.23ms +step:9/20000 train_loss:7.2347 train_time:32912ms step_avg:3656.92ms +step:10/20000 train_loss:6.9912 train_time:35894ms step_avg:3589.40ms +step:100/20000 train_loss:4.6083 train_time:307271ms step_avg:3072.71ms +step:200/20000 train_loss:4.0201 train_time:608202ms step_avg:3041.01ms +step:300/20000 train_loss:3.6721 train_time:907540ms step_avg:3025.13ms +step:400/20000 train_loss:3.6490 train_time:1205808ms step_avg:3014.52ms +step:500/20000 train_loss:3.4560 train_time:1503130ms step_avg:3006.26ms +step:500/20000 val_loss:3.5246 val_bpb:1.3647 train_time:1503141ms step_avg:3006.28ms +step:600/20000 train_loss:3.4968 train_time:1800265ms step_avg:3000.44ms +step:700/20000 train_loss:3.3170 train_time:2098108ms step_avg:2997.30ms +step:800/20000 train_loss:3.3872 train_time:2396748ms step_avg:2995.93ms +step:900/20000 train_loss:3.3626 train_time:2695499ms step_avg:2995.00ms +step:1000/20000 train_loss:3.2063 train_time:2994262ms step_avg:2994.26ms +step:1000/20000 val_loss:3.3010 val_bpb:1.2782 train_time:2994273ms step_avg:2994.27ms +step:1100/20000 train_loss:3.3161 train_time:3293037ms step_avg:2993.67ms +step:1200/20000 train_loss:3.3378 train_time:3591918ms step_avg:2993.26ms +step:1300/20000 train_loss:3.2597 train_time:3891288ms step_avg:2993.30ms +step:1400/20000 train_loss:3.1856 train_time:4190168ms step_avg:2992.98ms +step:1500/20000 train_loss:3.1806 train_time:4488829ms step_avg:2992.55ms +step:1500/20000 val_loss:3.2349 val_bpb:1.2525 train_time:4488840ms step_avg:2992.56ms +step:1600/20000 train_loss:3.2749 train_time:4787505ms step_avg:2992.19ms +step:1700/20000 train_loss:3.2821 train_time:5086174ms step_avg:2991.87ms +step:1800/20000 train_loss:3.2693 train_time:5384058ms step_avg:2991.14ms +step:1900/20000 train_loss:3.2575 train_time:5681937ms step_avg:2990.49ms +step:2000/20000 train_loss:3.2307 train_time:5980004ms step_avg:2990.00ms +step:2000/20000 val_loss:3.2052 val_bpb:1.2411 train_time:5980016ms step_avg:2990.01ms +step:2100/20000 train_loss:3.1999 train_time:6278072ms step_avg:2989.56ms +step:2200/20000 train_loss:3.2041 train_time:6576041ms step_avg:2989.11ms +step:2300/20000 train_loss:3.2646 train_time:6874072ms step_avg:2988.73ms +step:2400/20000 train_loss:3.2319 train_time:7172051ms step_avg:2988.35ms +step:2500/20000 train_loss:3.1826 train_time:7470054ms step_avg:2988.02ms +step:2500/20000 val_loss:3.1812 val_bpb:1.2317 train_time:7470064ms step_avg:2988.03ms +step:2600/20000 train_loss:3.1806 train_time:7767846ms step_avg:2987.63ms +step:2700/20000 train_loss:3.1319 train_time:8065981ms step_avg:2987.40ms +step:2800/20000 train_loss:3.1802 train_time:8363424ms step_avg:2986.94ms +step:2900/20000 train_loss:3.2104 train_time:8660960ms step_avg:2986.54ms +step:3000/20000 train_loss:3.0762 train_time:8958193ms step_avg:2986.06ms +step:3000/20000 val_loss:3.1490 val_bpb:1.2193 train_time:8958204ms step_avg:2986.07ms +step:3100/20000 train_loss:3.1027 train_time:9255247ms step_avg:2985.56ms +step:3200/20000 train_loss:3.1454 train_time:9552546ms step_avg:2985.17ms +step:3300/20000 train_loss:3.1856 train_time:9849931ms step_avg:2984.83ms +step:3400/20000 train_loss:3.1329 train_time:10147567ms step_avg:2984.58ms +step:3500/20000 train_loss:3.1053 train_time:10444922ms step_avg:2984.26ms +step:3500/20000 val_loss:3.1195 val_bpb:1.2079 train_time:10444934ms step_avg:2984.27ms +step:3600/20000 train_loss:3.1105 train_time:10742599ms step_avg:2984.06ms +step:3700/20000 train_loss:3.0893 train_time:11040741ms step_avg:2983.98ms +step:3800/20000 train_loss:3.1714 train_time:11338585ms step_avg:2983.84ms +step:3900/20000 train_loss:3.0760 train_time:11636090ms step_avg:2983.61ms +step:4000/20000 train_loss:3.1469 train_time:11933432ms step_avg:2983.36ms +step:4000/20000 val_loss:3.0825 val_bpb:1.1935 train_time:11933442ms step_avg:2983.36ms +step:4100/20000 train_loss:3.2154 train_time:12230405ms step_avg:2983.03ms +step:4200/20000 train_loss:3.1199 train_time:12527509ms step_avg:2982.74ms +step:4300/20000 train_loss:3.0751 train_time:12824480ms step_avg:2982.44ms +step:4400/20000 train_loss:3.0637 train_time:13121714ms step_avg:2982.21ms +step:4500/20000 train_loss:2.9973 train_time:13419250ms step_avg:2982.06ms +step:4500/20000 val_loss:3.0481 val_bpb:1.1802 train_time:13419260ms step_avg:2982.06ms +step:4600/20000 train_loss:2.9975 train_time:13716423ms step_avg:2981.83ms +step:4700/20000 train_loss:3.0079 train_time:14013217ms step_avg:2981.54ms +step:4800/20000 train_loss:3.0275 train_time:14310102ms step_avg:2981.27ms +step:4900/20000 train_loss:3.0434 train_time:14607662ms step_avg:2981.16ms +step:5000/20000 train_loss:2.9330 train_time:14905280ms step_avg:2981.06ms +step:5000/20000 val_loss:3.0047 val_bpb:1.1634 train_time:14905291ms step_avg:2981.06ms +step:5100/20000 train_loss:2.9578 train_time:15202289ms step_avg:2980.84ms +step:5200/20000 train_loss:2.9865 train_time:15499700ms step_avg:2980.71ms +step:5300/20000 train_loss:3.0451 train_time:15796822ms step_avg:2980.53ms +step:5400/20000 train_loss:2.9772 train_time:16094890ms step_avg:2980.54ms +step:5500/20000 train_loss:2.9313 train_time:16391993ms step_avg:2980.36ms +step:5500/20000 val_loss:2.9527 val_bpb:1.1433 train_time:16392004ms step_avg:2980.36ms +step:5600/20000 train_loss:2.9685 train_time:16688890ms step_avg:2980.16ms +step:5700/20000 train_loss:2.9909 train_time:16986051ms step_avg:2980.01ms +step:5800/20000 train_loss:2.9636 train_time:17283332ms step_avg:2979.88ms +step:5900/20000 train_loss:2.8982 train_time:17580412ms step_avg:2979.73ms +step:6000/20000 train_loss:2.8514 train_time:17877332ms step_avg:2979.56ms +step:6000/20000 val_loss:2.9049 val_bpb:1.1248 train_time:17877343ms step_avg:2979.56ms +step:6042/20000 val_loss:2.9035 val_bpb:1.1242 train_time:18001609ms step_avg:2979.41ms +stopping_early: wallclock_cap train_time:18001609ms step:6042/20000 +peak memory allocated: 16543 MiB reserved: 17772 MiB +eval:restored full crawler loops=2, depth=7 +swa:averaging 14 checkpoints +swa_eval val_loss:2.9009 val_bpb:1.1232 +saved backup: final_model_v5_d736_honest_seed1337.pt +Serialized model: 136629271 bytes +Code size: 90756 bytes +Total submission size: 136720027 bytes +Serialized model int8+zstd-22: 16709260 bytes (payload:38578440 raw_torch:38603741 payload_ratio:3.54x) +Total submission size int8+zlib: 16800016 bytes +final_int8_zlib_roundtrip val_loss:3.0091 val_bpb:1.1651 eval_time:68069ms +final_int8_zlib_roundtrip_exact val_loss:3.00909891 val_bpb:1.16512018 +gptq:loading calibration data from training shards... +gptq:loaded 64 calibration sequences in 4.4s +gptq:collecting hessians... +gptq:collected hessians for 32 layers +gptq:quantizing int6 with full Hessian GPTQ... +selective_prune: 12628044 candidates, unpruned=15.03MB target=15.9MB +selective_prune: already fits, no pruning needed +gptq_int6_brotli: 14,934,784 bytes | code: 90,756 | total: 15,025,540 (15.03MB) +gptq_int6_brotli_roundtrip val_loss:3.0315 val_bpb:1.1738 time:228.4s +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633560 stride=64 +ttt_sliding:params unfrozen=26429492 frozen=11917344 + ttt_chunk [1/1238] bpb=1.235882 time=4.1s + ttt_chunk [11/1238] bpb=1.157259 time=48.5s + ttt_chunk [21/1238] bpb=1.158188 time=92.7s + ttt_chunk [31/1238] bpb=1.152016 time=136.9s + ttt_chunk [41/1238] bpb=1.158436 time=181.1s + ttt_chunk [51/1238] bpb=1.153962 time=225.3s + ttt_chunk [61/1238] bpb=1.150062 time=269.5s + ttt_chunk [71/1238] bpb=1.151934 time=313.7s + ttt_chunk [81/1238] bpb=1.147508 time=357.9s + ttt_chunk [91/1238] bpb=1.145130 time=402.2s + ttt_chunk [101/1238] bpb=1.145042 time=446.4s + ttt_chunk [111/1238] bpb=1.147055 time=490.6s + ttt_chunk [121/1238] bpb=1.147729 time=534.8s + ttt_chunk [131/1238] bpb=1.149781 time=579.1s + ttt_chunk [141/1238] bpb=1.148469 time=623.3s + ttt_chunk [151/1238] bpb=1.148508 time=667.6s + ttt_chunk [161/1238] bpb=1.147791 time=711.8s + ttt_chunk [171/1238] bpb=1.147403 time=756.1s + ttt_chunk [181/1238] bpb=1.146846 time=800.4s + ttt_chunk [191/1238] bpb=1.147160 time=844.7s + ttt_chunk [201/1238] bpb=1.147619 time=888.9s + ttt_chunk [211/1238] bpb=1.148262 time=933.1s + ttt_chunk [221/1238] bpb=1.147273 time=977.3s + ttt_chunk [231/1238] bpb=1.147880 time=1021.6s + ttt_chunk [241/1238] bpb=1.148054 time=1065.8s + ttt_chunk [251/1238] bpb=1.148162 time=1110.1s + ttt_chunk [261/1238] bpb=1.148399 time=1154.3s + ttt_chunk [271/1238] bpb=1.147067 time=1198.5s + ttt_chunk [281/1238] bpb=1.147743 time=1242.8s + ttt_chunk [291/1238] bpb=1.146700 time=1287.0s + ttt_chunk [301/1238] bpb=1.146617 time=1331.2s + ttt_chunk [311/1238] bpb=1.146323 time=1375.4s + ttt_chunk [321/1238] bpb=1.146242 time=1419.6s + ttt_chunk [331/1238] bpb=1.145756 time=1463.9s + ttt_chunk [341/1238] bpb=1.144933 time=1508.1s + ttt_chunk [351/1238] bpb=1.145329 time=1552.3s + ttt_chunk [361/1238] bpb=1.145041 time=1596.5s + ttt_chunk [371/1238] bpb=1.144582 time=1640.7s + ttt_chunk [381/1238] bpb=1.144067 time=1684.9s + ttt_chunk [391/1238] bpb=1.143544 time=1729.1s + ttt_chunk [401/1238] bpb=1.143056 time=1773.2s + ttt_chunk [411/1238] bpb=1.142639 time=1817.5s + ttt_chunk [421/1238] bpb=1.142238 time=1861.7s + ttt_chunk [431/1238] bpb=1.141273 time=1905.9s + ttt_chunk [441/1238] bpb=1.140484 time=1950.1s + ttt_chunk [451/1238] bpb=1.140502 time=1994.4s + ttt_chunk [461/1238] bpb=1.139339 time=2038.6s + ttt_chunk [471/1238] bpb=1.139193 time=2082.8s + ttt_chunk [481/1238] bpb=1.139453 time=2127.0s + ttt_chunk [491/1238] bpb=1.139016 time=2171.3s + ttt_chunk [501/1238] bpb=1.138997 time=2215.5s + ttt_chunk [511/1238] bpb=1.139022 time=2259.8s + ttt_chunk [521/1238] bpb=1.138666 time=2304.1s + ttt_chunk [531/1238] bpb=1.138662 time=2348.3s + ttt_chunk [541/1238] bpb=1.138545 time=2392.6s + ttt_chunk [551/1238] bpb=1.138039 time=2436.8s + ttt_chunk [561/1238] bpb=1.137976 time=2481.1s + ttt_chunk [571/1238] bpb=1.138238 time=2525.3s + ttt_chunk [581/1238] bpb=1.137958 time=2569.5s + ttt_chunk [591/1238] bpb=1.137544 time=2613.8s + ttt_chunk [601/1238] bpb=1.137458 time=2658.0s + ttt_chunk [611/1238] bpb=1.137383 time=2702.2s + ttt_chunk [621/1238] bpb=1.137983 time=2746.4s + ttt_chunk [631/1238] bpb=1.138263 time=2790.6s + ttt_chunk [641/1238] bpb=1.138652 time=2834.8s + ttt_chunk [651/1238] bpb=1.138662 time=2879.1s + ttt_chunk [661/1238] bpb=1.139027 time=2923.3s + ttt_chunk [671/1238] bpb=1.139435 time=2967.5s + ttt_chunk [681/1238] bpb=1.140103 time=3011.8s + ttt_chunk [691/1238] bpb=1.140155 time=3056.1s + ttt_chunk [701/1238] bpb=1.140226 time=3100.3s + ttt_chunk [711/1238] bpb=1.140497 time=3144.5s + ttt_chunk [721/1238] bpb=1.140640 time=3188.8s + ttt_chunk [731/1238] bpb=1.140282 time=3233.0s + ttt_chunk [741/1238] bpb=1.139939 time=3277.3s + ttt_chunk [751/1238] bpb=1.139677 time=3321.5s + ttt_chunk [761/1238] bpb=1.139510 time=3365.7s + ttt_chunk [771/1238] bpb=1.139005 time=3410.0s + ttt_chunk [781/1238] bpb=1.139373 time=3454.2s + ttt_chunk [791/1238] bpb=1.138901 time=3498.5s + ttt_chunk [801/1238] bpb=1.139205 time=3542.7s + ttt_chunk [811/1238] bpb=1.138799 time=3586.9s + ttt_chunk [821/1238] bpb=1.138111 time=3631.2s + ttt_chunk [831/1238] bpb=1.137716 time=3675.4s + ttt_chunk [841/1238] bpb=1.137326 time=3719.7s + ttt_chunk [851/1238] bpb=1.136996 time=3763.9s + ttt_chunk [861/1238] bpb=1.136624 time=3808.2s + ttt_chunk [871/1238] bpb=1.136190 time=3852.5s + ttt_chunk [881/1238] bpb=1.135921 time=3896.7s + ttt_chunk [891/1238] bpb=1.136048 time=3941.0s + ttt_chunk [901/1238] bpb=1.136391 time=3985.2s + ttt_chunk [911/1238] bpb=1.136253 time=4029.5s + ttt_chunk [921/1238] bpb=1.136338 time=4073.6s + ttt_chunk [931/1238] bpb=1.136289 time=4117.9s + ttt_chunk [941/1238] bpb=1.136680 time=4162.1s + ttt_chunk [951/1238] bpb=1.136553 time=4206.3s + ttt_chunk [961/1238] bpb=1.137063 time=4250.6s + ttt_chunk [971/1238] bpb=1.137208 time=4294.8s + ttt_chunk [981/1238] bpb=1.137248 time=4339.0s + ttt_chunk [991/1238] bpb=1.137200 time=4383.2s + ttt_chunk [1001/1238] bpb=1.137512 time=4427.3s + ttt_chunk [1011/1238] bpb=1.137658 time=4471.6s + ttt_chunk [1021/1238] bpb=1.137898 time=4515.8s + ttt_chunk [1031/1238] bpb=1.138091 time=4560.0s + ttt_chunk [1041/1238] bpb=1.138220 time=4604.2s + ttt_chunk [1051/1238] bpb=1.138456 time=4648.4s + ttt_chunk [1061/1238] bpb=1.138436 time=4692.7s + ttt_chunk [1071/1238] bpb=1.138475 time=4736.9s + ttt_chunk [1081/1238] bpb=1.138548 time=4781.1s + ttt_chunk [1091/1238] bpb=1.138738 time=4825.3s + ttt_chunk [1101/1238] bpb=1.138920 time=4869.6s + ttt_chunk [1111/1238] bpb=1.138962 time=4913.8s + ttt_chunk [1121/1238] bpb=1.138892 time=4958.1s + ttt_chunk [1131/1238] bpb=1.138973 time=5002.4s + ttt_chunk [1141/1238] bpb=1.138668 time=5046.7s + ttt_chunk [1151/1238] bpb=1.138614 time=5090.9s + ttt_chunk [1161/1238] bpb=1.138482 time=5135.2s + ttt_chunk [1171/1238] bpb=1.138089 time=5179.5s + ttt_chunk [1181/1238] bpb=1.137942 time=5223.7s + ttt_chunk [1191/1238] bpb=1.137941 time=5268.0s + ttt_chunk [1201/1238] bpb=1.137889 time=5312.3s + ttt_chunk [1211/1238] bpb=1.137556 time=5356.5s + ttt_chunk [1221/1238] bpb=1.137488 time=5400.8s + ttt_chunk [1231/1238] bpb=1.137192 time=5445.0s + ttt_chunk [1238/1238] bpb=1.137200 time=5473.2s +ttt_sliding:done val_loss=2.937027 val_bpb=1.137200 elapsed=5473.4s +final_ttt_sliding val_loss:2.9370 val_bpb:1.1372 eval_time:5473600ms +guous() + + if sdclip_k > 0: + # SDClip for 1D: use global std + clip_abs = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + else: + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / max_val if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), min_val, max_val).to(torch.int8).contiguous() + return q, scale + +def quantize_state_dict_int8(state_dict: dict[str, Tensor], qat_bits: int = 8, qat_mlp_bits: int = 0): + quantized: dict[str, Tensor] = {} + scales: dict[str, Tensor] = {} + dtypes: dict[str, str] = {} + passthrough: dict[str, Tensor] = {} + passthrough_orig_dtypes: dict[str, str] = {} + qmeta: dict[str, dict[str, object]] = {} + stats = dict.fromkeys( + ("param_count", "num_tensors", "num_float_tensors", "num_nonfloat_tensors", "baseline_tensor_bytes", "int8_payload_bytes"), + 0, + ) + + for name, tensor in state_dict.items(): + t = tensor.detach().to("cpu").contiguous() + stats["param_count"] += int(t.numel()) + stats["num_tensors"] += 1 + stats["baseline_tensor_bytes"] += tensor_nbytes(t) + + if not t.is_floating_point(): + stats["num_nonfloat_tensors"] += 1 + passthrough[name] = t + stats["int8_payload_bytes"] += tensor_nbytes(t) + continue + + if t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + kept = keep_float_tensor(name, t, passthrough_orig_dtypes) + passthrough[name] = kept + stats["int8_payload_bytes"] += tensor_nbytes(kept) + continue + + stats["num_float_tensors"] += 1 + is_block_weight = any(k in name for k in ("flat_blocks.", "crawler_blocks.", "bigram.proj.")) + is_embed_weight = ("tok_emb.weight" in name) + is_mlp_weight = any(k in name for k in ("mlp.fc.weight", "mlp.proj.weight")) + if qat_bits < 8 and is_block_weight and t.ndim == 2: + n_bits = (qat_mlp_bits if (qat_mlp_bits > 0 and is_mlp_weight) else qat_bits) + sdclip_k = 12.85 + elif is_embed_weight: + n_bits = 8 + sdclip_k = 20.0 + else: + n_bits = 8 + sdclip_k = 20.0 + q, s = quantize_float_tensor(t, n_bits=n_bits, sdclip_k=sdclip_k) + if s.ndim > 0: + qmeta[name] = {"scheme": "per_row", "axis": 0} + quantized[name] = q + scales[name] = s + dtypes[name] = str(t.dtype).removeprefix("torch.") + stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + obj: dict[str, object] = { + "__quant_format__": "int8_clean_per_row_v1", + "quantized": quantized, + "scales": scales, + "dtypes": dtypes, + "passthrough": passthrough, + } + if qmeta: + obj["qmeta"] = qmeta + if passthrough_orig_dtypes: + obj["passthrough_orig_dtypes"] = passthrough_orig_dtypes + return obj, stats + +def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + qmeta = obj.get("qmeta", {}) + passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {}) + for name, q in obj["quantized"].items(): + dtype = getattr(torch, obj["dtypes"][name]) + s = obj["scales"][name] + if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: + s = s.to(dtype=torch.float32) + 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 + +def generate_calib_from_data(train_files, device, num_seqs=64, seq_len=2048, seed=42): + rng = random.Random(seed) + shard_files = sorted(glob.glob(train_files)) + all_tokens = [] + while len(all_tokens) < num_seqs: + shard = Path(rng.choice(shard_files)) + data = load_data_shard(shard) + max_start = data.numel() - seq_len - 1 + if max_start <= 0: + continue + start = rng.randint(0, max_start) + seq = data[start:start + seq_len + 1].unsqueeze(0).to(device=device, dtype=torch.int64) + all_tokens.append(seq) + return all_tokens[:num_seqs] + +def collect_hessians_from_tokens(hessian_model, token_seqs, device): + hessians = {} + hooks = [] + for name, module in hessian_model.named_modules(): + if isinstance(module, CastedLinear): + param_name = name + ".weight" + cols = module.weight.shape[1] + hessians[param_name] = torch.zeros(cols, cols, dtype=torch.float32, device='cpu') + def make_hook(pname): + def hook_fn(module, input, output): + x = input[0].detach().float() + if x.ndim == 3: + x = x.reshape(-1, x.shape[-1]) + hessians[pname] += (x.T @ x).cpu() + return hook_fn + h = module.register_forward_hook(make_hook(param_name)) + hooks.append(h) + hessian_model.eval() + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16): + for seq in token_seqs: + x = seq[:, :-1].to(device) + y = seq[:, 1:].to(device) + hessian_model(x, y) + for h in hooks: + h.remove() + for name in hessians: + H = hessians[name] + H /= len(token_seqs) + damp = 0.01 * torch.diag(H).mean().clamp_min(1e-6) + H += damp * torch.eye(H.shape[0]) + hessians[name] = H + return hessians + +def quantize_int6_gptq(weight, hessian=None, clip_range=31, block_size=128, sdclip_k: float = 0.0): + t32 = weight.float() + if t32.ndim != 2 or hessian is None: + return quantize_int6_per_row(t32, clip_range, sdclip_k=sdclip_k) + rows, cols = t32.shape + H = hessian.float().clone() + dead = torch.diag(H) == 0 + H[dead, dead] = 1 + damp = 0.01 * torch.mean(torch.diag(H)) + H[torch.arange(cols), torch.arange(cols)] += damp + perm = torch.argsort(torch.diag(H), descending=True) + inv_perm = torch.argsort(perm) + W = t32[:, perm].clone() + W[:, dead[perm]] = 0 + H = H[perm][:, perm] + try: + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + except torch._C._LinAlgError: + H[torch.arange(cols), torch.arange(cols)] += 0.1 * torch.mean(torch.diag(H)) + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + best_q = Q[:, inv_perm] + return best_q, s + best_q, best_scale, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + recon = Q.float() * sf[:, None] + mse = (W - recon).pow(2).mean().item() + if mse < best_err: + best_q, best_scale, best_err = Q, s, mse + best_q = best_q[:, inv_perm] + return best_q, best_scale + +def quantize_int6_per_row(t, clip_range=31, sdclip_k: float = 0.0): + t32 = t.float() if not t.is_floating_point() else t.float() + if t32.ndim == 2: + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + return q, s + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + recon = q.float() * s.float()[:, None] + err = (t32 - recon).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, s, err + return best_q, best_s + if sdclip_k > 0: + clip_val = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_val / clip_range if clip_val > 0 else 1.0, dtype=torch.float16) + else: + amax = t32.abs().max().item() + scale = torch.tensor(amax / clip_range if amax > 0 else 1.0, dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -clip_range, clip_range).to(torch.int8) + return q, scale + +def mixed_quantize_int6_gptq(state_dict, hessians=None): + result = {} + meta = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + if not t.is_floating_point() or t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + is_block = any(k in name for k in ("flat_blocks.", "crawler_blocks.")) + if is_block and t.ndim == 2: + H = hessians.get(name) if hessians else None + q, s = quantize_int6_gptq(t, hessian=H, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + else: + q, s = quantize_int6_per_row(t, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + return result, meta + +def dequantize_mixed_int6(result, meta, template_sd): + out = {} + for name, orig in template_sd.items(): + info = meta.get(name) + if info is None: + continue + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = 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) + +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) + +def _fake_quantize_ste(w: Tensor, n_bits: int) -> Tensor: + max_val = 2 ** (n_bits - 1) - 1 + min_val = -(2 ** (n_bits - 1)) + scale = w.abs().amax(dim=-1, keepdim=True) / max_val + scale = scale.clamp_min(1e-8) + w_q = (w / scale).round().clamp(min_val, max_val) * scale + return w + (w_q - w).detach() + +_QAT_ENABLED = False +_QAT_BITS = 6 +_QAT_MLP_BITS = 0 +_ACTIVE_CRAWLER_LOOPS = 1 + +class CastedLinear(nn.Linear): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._is_mlp = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if _QAT_ENABLED and self.weight.ndim == 2 and self.weight.numel() > 65536: + bits = (_QAT_MLP_BITS if (_QAT_MLP_BITS > 0 and self._is_mlp) else _QAT_BITS) + w = _fake_quantize_ste(w, bits) + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0): + super().__init__() + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + +class CausalSelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int, + rope_base: float, + qk_gain_init: float, + ): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + 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(3) + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, q_delta=None, v_delta=None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x) + (q_delta if q_delta is not None else 0) + k = self.c_k(x) + v = self.c_v(x) + (v_delta if v_delta is not None else 0) + q = q.reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = k.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = v.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + rope_dim = cos.size(-1) + partial = rope_dim // 2 + if partial > 0: + q_rope, q_pass = q[..., :partial*2], q[..., partial*2:] + k_rope, k_pass = k[..., :partial*2], k[..., partial*2:] + q_rope = apply_rotary_emb(q_rope, cos[..., :partial], sin[..., :partial]) + k_rope = apply_rotary_emb(k_rope, cos[..., :partial], sin[..., :partial]) + q = torch.cat([q_rope, q_pass], dim=-1) + k = torch.cat([k_rope, k_pass], dim=-1) + else: + 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 = self._xsa_efficient(y.transpose(1, 2), v.transpose(1, 2)).contiguous().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): + super().__init__() + hidden = mlp_mult * dim + self.fc = CastedLinear(dim, hidden, bias=False) + self.fc._is_mlp = True + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + self.proj._is_mlp = True + + def forward(self, x: Tensor) -> Tensor: + x = torch.relu(self.fc(x)) + return self.proj(x.square()) + +class ValueEmbedding(nn.Module): + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int, num_loops_active: int): + super().__init__() + self.table = nn.Embedding(vocab_size, ve_dim) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) + self.scales = nn.ParameterList([nn.Parameter(torch.ones(1)) for _ in range(num_loops_active)]) + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor, loop_idx: int) -> Tensor: + return self.scales[loop_idx] * self.proj(self.table(input_ids)) + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate).to(dtype=x.dtype) + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1.0 - g) * x + g * x_prev + +class BigramHashEmbedding(nn.Module): + def __init__(self, num_buckets: int, hash_dim: int, model_dim: int): + super().__init__() + self.num_buckets = num_buckets + self.table = nn.Embedding(num_buckets, hash_dim) + self.proj = CastedLinear(hash_dim, model_dim, bias=False) + self.proj._zero_init = True + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor) -> Tensor: + bsz, seqlen = input_ids.shape + prev_ids = torch.cat([ + torch.zeros(bsz, 1, dtype=input_ids.dtype, device=input_ids.device), + input_ids[:, :-1], + ], dim=1) + h = ((prev_ids.long() * 92821 + input_ids.long()) % self.num_buckets).long() + return self.proj(self.table(h)) + +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, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init) + self.mlp = MLP(dim, mlp_mult) + + def forward( + self, x: Tensor, x0: Tensor, + attn_scale: Tensor, mlp_scale: Tensor, resid_mix: Tensor, + q_delta_fn=None, v_delta_fn=None, v_embed=None, + ) -> Tensor: + mix = resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + n = self.attn_norm(x) + qd = q_delta_fn(n) if q_delta_fn is not None else None + vd = v_delta_fn(n) if v_delta_fn is not None else None + if v_embed is not None: + vd = (vd + v_embed) if vd is not None else v_embed + attn_out = self.attn(n, qd, vd) + x = x + attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x)) + return x + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_flat_blocks: int, + num_crawler_blocks: int, + crawler_loops: 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, + use_smear_gate: bool = True, + bigram_buckets: int = 10240, + bigram_dim: int = 128, + embed_bottleneck: int = 0, + ve_enabled: bool = False, + ve_dim: int = 128, + ve_last_n: int = 2, + temperature: float = 1.0, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.temperature = temperature + self.embed_bottleneck = embed_bottleneck + self.num_flat_blocks = num_flat_blocks + self.num_crawler_blocks = num_crawler_blocks + self.crawler_loops = crawler_loops + self._active_crawler_loops = crawler_loops + self._n_enc = num_flat_blocks // 2 + num_loops = num_flat_blocks + num_crawler_blocks * crawler_loops + self.num_loops = num_loops + if embed_bottleneck > 0: + self.tok_emb = nn.Embedding(vocab_size, embed_bottleneck) + self.embed_proj = CastedLinear(embed_bottleneck, model_dim, bias=False) + self.embed_proj_rev = CastedLinear(model_dim, embed_bottleneck, bias=False) + else: + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.embed_proj = None + self.embed_proj_rev = None + self.bigram = BigramHashEmbedding(bigram_buckets, bigram_dim, model_dim) + self.smear = SmearGate(model_dim) if use_smear_gate else None + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve = ValueEmbedding(vocab_size, ve_dim, kv_dim, ve_last_n) if ve_enabled else None + self.ve_last_n = ve_last_n + self.flat_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_flat_blocks) + ]) + self.crawler_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_crawler_blocks) + ]) + self.crawler_residual_scales = nn.ParameterList([ + nn.Parameter(torch.tensor(0.5, dtype=torch.float32)) + for _ in range(crawler_loops) + ]) + self.attn_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.mlp_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.resid_mixes = nn.Parameter( + torch.stack([ + torch.stack((torch.ones(model_dim), torch.zeros(model_dim))) + for _ in range(num_loops) + ]).float() + ) + self.num_encoder_loops = num_loops // 2 + self.num_decoder_loops = num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + self.skip_weights = nn.Parameter(torch.ones(self.num_skips, model_dim, dtype=torch.float32)) + self.xsa_last_n = int(os.environ.get("XSA_LAST_N", 7)) + 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._rebuild_schedule() + self._init_weights() + + def _rebuild_schedule(self, active_loops: int | None = None): + if active_loops is not None: + self._active_crawler_loops = active_loops + schedule = [] + for i in range(self._n_enc): + schedule.append(('flat', i)) + for loop in range(self._active_crawler_loops): + for c in range(self.num_crawler_blocks): + schedule.append(('crawler', c)) + for i in range(self._n_enc, self.num_flat_blocks): + schedule.append(('flat', i)) + self._loop_schedule = schedule + self.num_loops = len(schedule) + self.num_encoder_loops = self.num_loops // 2 + self.num_decoder_loops = self.num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + block_list = [] + for kind, idx in schedule: + block_list.append(self.flat_blocks[idx] if kind == 'flat' else self.crawler_blocks[idx]) + self._block_list = block_list + + def _get_block(self, loop_idx: int) -> 'Block': + return self._block_list[loop_idx] + + 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) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and min(module.weight.shape) >= 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 * self.num_loops)) + + def _embed(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.embed_proj is not None: + x = self.embed_proj(x) + return x + + def _logits(self, x: Tensor) -> Tensor: + if self.embed_proj_rev is not None: + x = self.embed_proj_rev(x) + logits = F.linear(x, self.tok_emb.weight) + elif self.tie_embeddings: + logits = F.linear(x, self.tok_emb.weight) + else: + logits = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits / self.logit_softcap) + + def _run_blocks(self, x, x0, input_ids, lora=None): + active_loops = _ACTIVE_CRAWLER_LOOPS + n_enc = self._n_enc + loop_idx = 0 + xsa_n = self.xsa_last_n + total_depth = self.num_flat_blocks + self.num_crawler_blocks * active_loops + + if xsa_n > 0: + for blk in self.flat_blocks: + blk.attn.use_xsa = (loop_idx >= total_depth - xsa_n) if loop_idx < n_enc or loop_idx >= n_enc + self.num_crawler_blocks * active_loops else False + loop_idx += 1 + for blk in self.crawler_blocks: + for _ in range(active_loops): + blk.attn.use_xsa = True + loop_idx = 0 + + skips: list[Tensor] = [] + for i in range(n_enc): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[i](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + skips.append(x) + loop_idx += 1 + + for lp in range(active_loops): + for ci, cblock in enumerate(self.crawler_blocks): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x_out = cblock(x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + if lp > 0: + alpha = self.crawler_residual_scales[lp].to(dtype=x.dtype) + x = x + alpha * (x_out - x) + else: + x = x_out + loop_idx += 1 + + n_dec_flat = self.num_flat_blocks - n_enc + for i in range(n_dec_flat): + fi = n_enc + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[fi](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + loop_idx += 1 + return x + + def forward(self, input_ids: Tensor, target_ids: Tensor, lora=None) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids, lora) + unused = sum(p.sum() * 0.0 for p in self.crawler_residual_scales) + x = x + unused + x = self.final_norm(x) + logits = self._logits(x) + logits = logits + (lora.lm_head_lora(x) if lora else 0) + if lora: + bsz, sl, V = logits.shape + return F.cross_entropy( + logits.float().reshape(-1, V), target_ids.reshape(-1), reduction="none").reshape(bsz, sl) + return F.cross_entropy(logits.float().reshape(-1, logits.size(-1)), target_ids.reshape(-1), reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids) + x = self.final_norm(x) + return self._logits(x) + +def _compute_chunk_window(ci: int, pred_len: int, num_chunks: int, chunk_size: int, eval_seq_len: int): + chunk_start = ci * chunk_size + chunk_end = pred_len if ci == num_chunks - 1 else (ci + 1) * chunk_size + win_start = max(0, chunk_end - eval_seq_len) + win_len = chunk_end - win_start + chunk_offset = chunk_start - win_start + chunk_len = chunk_end - chunk_start + return win_start, win_len, chunk_offset, chunk_len + +def _accumulate_bpb( + ptl: Tensor, x: Tensor, y: Tensor, + batch_i: int, chunk_offset: int, chunk_len: int, + base_bytes_lut: Tensor, has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + loss_sum: Tensor, byte_sum: Tensor, token_count: Tensor, +): + lbl = ptl[batch_i, chunk_offset:chunk_offset + chunk_len].to(torch.float64) + prev = x[batch_i, chunk_offset:chunk_offset + chunk_len] + tgt = y[batch_i, chunk_offset:chunk_offset + chunk_len] + tok_bytes = base_bytes_lut[tgt].to(torch.float64) + tok_bytes += has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev] + loss_sum += lbl.sum() + byte_sum += tok_bytes.sum() + token_count += chunk_len + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: GPT, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + 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}") + + 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_blocks = min(args.ttt_freeze_blocks, base_model.num_flat_blocks + base_model.num_crawler_blocks) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = False + for bi in range(freeze_blocks): + if f"flat_blocks.{bi}." in name or f"crawler_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)}") + + 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 + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + 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 = [] + 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) + loss_sum += nll[i, s:wlen].to(torch.float64).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() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + 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) + start_tok = chunk_start + (my_seq_s + bs) * seq_len + end_tok = chunk_start + (my_seq_s + 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) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or is_last_chunk): + 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)) + 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 + +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 = "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, timeout=datetime.timedelta(seconds=1800)) + 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) + torch._dynamo.config.optimize_ddp = 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) + + 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}") + + base_model = GPT( + vocab_size=args.vocab_size, + num_flat_blocks=args.num_flat_blocks, + num_crawler_blocks=args.num_crawler_blocks, + crawler_loops=args.crawler_loops, + 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, + temperature=args.temperature, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + use_smear_gate=args.use_smear_gate, + bigram_buckets=args.bigram_buckets, + bigram_dim=args.bigram_dim, + embed_bottleneck=args.embed_bottleneck, + ve_enabled=args.ve_enabled, + ve_dim=args.ve_dim, + ve_last_n=args.ve_last_n, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + if isinstance(module, Rotary): + module.inv_freq.data = module.inv_freq.data.float() + restore_low_dim_params_to_fp32(base_model) + + if args.resume_from and os.path.isfile(args.resume_from): + log0(f"resuming_from:{args.resume_from}") + saved = torch.load(args.resume_from, map_location=device) + base_model.load_state_dict(saved, strict=True) + restore_low_dim_params_to_fp32(base_model) + log0("resume:loaded model weights (optimizer states reset)") + global _QAT_ENABLED, _QAT_BITS, _QAT_MLP_BITS, _ACTIVE_CRAWLER_LOOPS + _QAT_BITS = args.qat_bits + _QAT_MLP_BITS = args.qat_mlp_bits + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + _qat_activated = False + if args.qat_enabled and args.late_qat_threshold >= 1.0: + _QAT_ENABLED = True + _qat_activated = True + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:enabled from step 0 attn={_QAT_BITS}bit{mlp_info}") + elif args.qat_enabled: + _QAT_ENABLED = False + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:late_start threshold={args.late_qat_threshold} attn={_QAT_BITS}bit{mlp_info}") + else: + _QAT_ENABLED = False + _use_compile = bool(int(os.environ.get("TORCH_COMPILE", "1"))) + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) if _use_compile else base_model + _use_ddp = distributed and world_size > 1 + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + + block_named_params = list(base_model.flat_blocks.named_parameters()) + list(base_model.crawler_blocks.named_parameters()) + matrix_params = [ + p + for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p + for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params.append(base_model.attn_scales) + scalar_params.append(base_model.mlp_scales) + scalar_params.append(base_model.resid_mixes) + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + if base_model.smear is not None: + scalar_params.append(base_model.smear.gate) + bigram_named = list(base_model.bigram.named_parameters()) + for name, p in bigram_named: + if p.ndim == 2 and "proj" in name: + matrix_params.append(p) + elif p.ndim == 2: + pass + else: + scalar_params.append(p) + ve_table_params = [] + if base_model.ve is not None: + for name, p in base_model.ve.named_parameters(): + if "table" in name: + ve_table_params.append(p) + elif p.ndim == 2: + matrix_params.append(p) + else: + scalar_params.append(p) + 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, base_model.bigram.table.weight] + + ([base_model.embed_proj.weight, base_model.embed_proj_rev.weight] if base_model.embed_proj is not None else []) + + ve_table_params, + "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.weight_decay, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + flat_params = sum(p.numel() for p in base_model.flat_blocks.parameters()) + crawler_params = sum(p.numel() for p in base_model.crawler_blocks.parameters()) + loop_params = base_model.attn_scales.numel() + base_model.mlp_scales.numel() + base_model.resid_mixes.numel() + log0(f"architecture:crawler flat_blocks:{args.num_flat_blocks} crawler_blocks:{args.num_crawler_blocks} crawler_loops:{args.crawler_loops} effective_depth:{base_model.num_loops} flat_params:{flat_params} crawler_params:{crawler_params} per_loop_params:{loop_params}") + log0(f"model_params:{n_params}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + 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_frac > 0 and max_wallclock_ms is not None: + warmdown_ms = args.warmdown_frac * max_wallclock_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.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 + + progressive_steps: list[tuple[int, int]] = [] + if args.progressive_schedule: + for entry in args.progressive_schedule.split(","): + s, loops = entry.strip().split(":") + progressive_steps.append((int(s), int(loops))) + progressive_steps.sort() + + 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] + prog_variants = sorted(set([1] + [loops for _, loops in progressive_steps])) if progressive_steps else [base_model._active_crawler_loops] + steps_per_variant = max(1, args.warmup_steps // (len(prog_variants) * 2)) + model.train() + warmup_step = 0 + for variant_loops in prog_variants: + if variant_loops != base_model._active_crawler_loops: + base_model._rebuild_schedule(active_loops=variant_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"warmup:precompile variant={variant_loops} loops, depth={base_model.num_loops}") + for _ in range(steps_per_variant): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{args.warmup_steps}") + remaining = args.warmup_steps - warmup_step + if remaining > 0: + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + for _ in range(remaining): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{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() + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + if _use_ddp: + model.require_backward_grad_sync = True + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + if progressive_steps: + _ACTIVE_CRAWLER_LOOPS = 1 + log0(f"progressive:enabled schedule={progressive_steps} starting with 1 crawler loop") + else: + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + _current_crawler_loops = _ACTIVE_CRAWLER_LOOPS + + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_checkpoints: list[dict[str, Tensor]] = [] + ema_sd: dict[str, Tensor] | None = None + if args.ema_decay > 0: + ema_sd = {k: v.detach().float().clone() for k, v in base_model.state_dict().items()} + log0(f"ema:enabled decay={args.ema_decay}") + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_activated and scale <= args.late_qat_threshold: + _QAT_ENABLED = True + _qat_activated = True + log0(f"late_qat:activated at step {step} scale={scale:.4f} threshold={args.late_qat_threshold}") + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + if args.swa_start_frac > 0 and step % args.swa_every == 0: + should_collect = torch.tensor(int(scale < args.swa_start_frac), device=device) + if distributed: + dist.all_reduce(should_collect, op=dist.ReduceOp.MIN) + if should_collect.item(): + swa_checkpoints.append({k: v.detach().cpu().clone() for k, v in base_model.state_dict().items()}) + + if ema_sd is not None: + d = args.ema_decay + with torch.no_grad(): + for k, v in base_model.state_dict().items(): + ema_sd[k].mul_(d).add_(v.detach().float(), alpha=1.0 - d) + + step += 1 + for prog_step, prog_loops in progressive_steps: + if step == prog_step and prog_loops != _current_crawler_loops: + _ACTIVE_CRAWLER_LOOPS = prog_loops + _current_crawler_loops = prog_loops + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"progressive:step {step} -> {prog_loops} crawler loops, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * prog_loops} (recompiled)") + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + _QAT_ENABLED = False + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + log0(f"eval:restored full crawler loops={args.crawler_loops}, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * args.crawler_loops}") + + if swa_checkpoints: + log0(f"swa:averaging {len(swa_checkpoints)} checkpoints") + avg_sd = {} + for key in swa_checkpoints[0]: + stacked = torch.stack([ckpt[key].float() for ckpt in swa_checkpoints]) + avg_sd[key] = stacked.mean(dim=0).to(dtype=swa_checkpoints[0][key].dtype) + base_model.load_state_dict(avg_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + swa_val_loss, swa_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"swa_eval val_loss:{swa_val_loss:.4f} val_bpb:{swa_val_bpb:.4f}") + del swa_checkpoints + + if ema_sd is not None: + log0("ema:loading averaged weights") + model_sd = base_model.state_dict() + for k in ema_sd: + ema_sd[k] = ema_sd[k].to(dtype=model_sd[k].dtype, device=model_sd[k].device) + base_model.load_state_dict(ema_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + ema_val_loss, ema_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"ema_eval val_loss:{ema_val_loss:.4f} val_bpb:{ema_val_bpb:.4f}") + del ema_sd + + if master_process: + torch.save(base_model.state_dict(), "final_model.pt") + import shutil + shutil.copy2("final_model.pt", f"final_model_{args.run_id}.pt") + log0(f"saved backup: final_model_{args.run_id}.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + quant_obj, quant_stats = quantize_state_dict_int8( + base_model.state_dict(), + qat_bits=args.qat_bits if args.qat_enabled else 8, + qat_mlp_bits=args.qat_mlp_bits if args.qat_enabled else 0, + ) + quant_buf = io.BytesIO() + torch.save(quant_obj, quant_buf) + quant_raw = quant_buf.getvalue() + try: + import zstandard as zstd + quant_blob = zstd.ZstdCompressor(level=22).compress(quant_raw) + compress_method = "zstd-22" + except ImportError: + quant_blob = zlib.compress(quant_raw, level=9) + compress_method = "zlib-9" + quant_raw_bytes = len(quant_raw) + if master_process: + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int8_payload_bytes"], 1) + log0( + f"Serialized model int8+{compress_method}: {quant_file_bytes} bytes " + f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" + ) + log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + try: + import zstandard as zstd + decompressed = zstd.ZstdDecompressor().decompress(quant_blob_disk) + except Exception: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + torch.cuda.synchronize() + t_qeval = time.perf_counter() + q_val_loss, q_val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + if master_process: + log0("gptq:loading calibration data from training shards...") + base_model.load_state_dict(torch.load("final_model.pt", map_location=device), strict=True) + restore_low_dim_params_to_fp32(base_model) + t_gptq = time.perf_counter() + ar_tokens = generate_calib_from_data( + args.train_files, device, num_seqs=64, seq_len=args.train_seq_len, seed=args.seed, + ) + log0(f"gptq:loaded {len(ar_tokens)} calibration sequences in {time.perf_counter()-t_gptq:.1f}s") + log0("gptq:collecting hessians...") + hessians = collect_hessians_from_tokens(base_model, ar_tokens, device) + log0(f"gptq:collected hessians for {len(hessians)} layers") + del ar_tokens + torch.cuda.empty_cache() + log0("gptq:quantizing int6 with full Hessian GPTQ...") + gptq_result, gptq_meta = mixed_quantize_int6_gptq( + base_model.state_dict(), hessians=hessians, + ) + del hessians + target_bytes = 15_900_000 + code_bytes = len(code.encode("utf-8")) + ones_info = [] + for name, info in gptq_meta.items(): + if not (isinstance(info, dict) and info.get("type") == "int6"): + continue + qk, sk = name + ".q", name + ".scale" + if qk not in gptq_result or sk not in gptq_result: + continue + q, s = gptq_result[qk], gptq_result[sk] + if s.ndim > 0: + ones_mask = (q.abs() == 1) + if ones_mask.any(): + row_idx = torch.arange(q.shape[0]).unsqueeze(1).expand_as(q)[ones_mask] + flat_idx = torch.arange(q.numel()).reshape(q.shape)[ones_mask] + errors = s.float()[row_idx].pow(2) + for fi, err in zip(flat_idx.tolist(), errors.tolist()): + ones_info.append((qk, fi, err)) + ones_info.sort(key=lambda x: x[2]) + def _try_prune(n): + tmp = {k: v.clone() for k, v in gptq_result.items()} + for i in range(min(n, len(ones_info))): + tmp[ones_info[i][0]].view(-1)[ones_info[i][1]] = 0 + buf = io.BytesIO() + torch.save({"w": tmp, "m": gptq_meta}, buf) + return len(brotli.compress(buf.getvalue(), quality=11)) + code_bytes, tmp + no_prune_sz, _ = _try_prune(0) + log0(f"selective_prune: {len(ones_info)} candidates, unpruned={no_prune_sz/1e6:.2f}MB target={target_bytes/1e6:.1f}MB") + if no_prune_sz <= target_bytes: + log0("selective_prune: already fits, no pruning needed") + final_result = gptq_result + else: + full_sz, _ = _try_prune(len(ones_info)) + log0(f"selective_prune: full prune={full_sz/1e6:.2f}MB") + if full_sz > target_bytes: + log0("selective_prune: even full prune not enough, applying all") + _, final_result = _try_prune(len(ones_info)) + else: + lo, hi = 0, len(ones_info) + while lo < hi: + mid = (lo + hi) // 2 + sz, _ = _try_prune(mid) + if sz <= target_bytes: + hi = mid + else: + lo = mid + 1 + log0(f"selective_prune: pruning {lo}/{len(ones_info)} values ({100*lo/len(ones_info):.1f}%) to fit") + _, final_result = _try_prune(lo) + gptq_buf = io.BytesIO() + torch.save({"w": final_result, "m": gptq_meta}, gptq_buf) + gptq_raw = gptq_buf.getvalue() + gptq_blob = brotli.compress(gptq_raw, quality=11) + gptq_bytes = len(gptq_blob) + total_bytes = gptq_bytes + code_bytes + log0(f"gptq_int6_brotli: {gptq_bytes:,} bytes | code: {code_bytes:,} | total: {total_bytes:,} ({total_bytes/1e6:.2f}MB)") + with open("final_model.int6_gptq.ptz", "wb") as f: + f.write(gptq_blob) + gptq_state = torch.load( + io.BytesIO(brotli.decompress(gptq_blob)), map_location="cpu", weights_only=False + ) + restored = dequantize_mixed_int6(gptq_state["w"], gptq_state["m"], base_model.state_dict()) + base_model.load_state_dict(restored, strict=True) + restore_low_dim_params_to_fp32(base_model) + gq_val_loss, gq_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"gptq_int6_brotli_roundtrip val_loss:{gq_val_loss:.4f} val_bpb:{gq_val_bpb:.4f} time:{time.perf_counter()-t_gptq:.1f}s") + + if args.ttt_enabled: + torch._dynamo.reset() + # TTT runs on the GPTQ artifact (already loaded at line 1980-1982) + torch.cuda.synchronize() + t_ttt_sw = time.perf_counter() + all_val_tokens = torch.cat([load_data_shard(Path(p)) for p in sorted(glob.glob(args.val_files))]).contiguous() + ttt_sw_loss, ttt_sw_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + all_val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.sliding_window_stride if args.sliding_window_stride > 0 else 64, + log0=log0, + ) + torch.cuda.synchronize() + log0( + f"final_ttt_sliding val_loss:{ttt_sw_loss:.4f} val_bpb:{ttt_sw_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt_sw):.0f}ms" + ) + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main() + + +==================================================================================================== +Running Python 3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0] +Running PyTorch 2.6.0+cu124 +Sat Apr 11 23:57:01 2026 ++-----------------------------------------------------------------------------------------+ +| NVIDIA-SMI 580.126.09 Driver Version: 580.126.09 CUDA Version: 13.0 | ++-----------------------------------------+------------------------+----------------------+ +| 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 RTX 6000 Ada Gene... Off | 00000000:01:00.0 On | Off | +| 39% 59C P8 33W / 300W | 1438MiB / 49140MiB | 9% Default | +| | | N/A | ++-----------------------------------------+------------------------+----------------------+ + ++-----------------------------------------------------------------------------------------+ +| Processes: | +| GPU GI CI PID Type Process name GPU Memory | +| ID ID Usage | +|=========================================================================================| +| 0 N/A N/A 2640 G /usr/lib/xorg/Xorg 294MiB | +| 0 N/A N/A 2821 G /usr/bin/gnome-shell 260MiB | +| 0 N/A N/A 3400 G ...exec/xdg-desktop-portal-gnome 31MiB | +| 0 N/A N/A 444032 G /usr/bin/nautilus 86MiB | +| 0 N/A N/A 767208 G .../8054/usr/lib/firefox/firefox 569MiB | +| 0 N/A N/A 3548448 G /proc/self/exe 70MiB | ++-----------------------------------------------------------------------------------------+ + +==================================================================================================== +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_8192_bpe.model +train_loader:dataset:fineweb10B_sp8192 train_shards:128 +val_loader:shards pattern=./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin tokens:40546304 +qat:enabled from step 0 attn=6bit +architecture:crawler flat_blocks:3 crawler_blocks:2 crawler_loops:2 effective_depth:7 flat_params:17876016 crawler_params:11917344 per_loop_params:20608 +model_params:38346836 +world_size:1 grad_accum_steps:8 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:16 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:18000.000 +seed:1337 +warmup_step:1/100 +warmup_step:2/100 +warmup_step:3/100 +warmup_step:4/100 +warmup_step:5/100 +warmup_step:6/100 +warmup_step:7/100 +warmup_step:8/100 +warmup_step:9/100 +warmup_step:10/100 +warmup_step:11/100 +warmup_step:12/100 +warmup_step:13/100 +warmup_step:14/100 +warmup_step:15/100 +warmup_step:16/100 +warmup_step:17/100 +warmup_step:18/100 +warmup_step:19/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:8.9999 val_bpb:3.4847 train_time:0ms step_avg:0.01ms +step:1/20000 train_loss:9.0002 train_time:9417ms step_avg:9416.77ms +step:2/20000 train_loss:8.8349 train_time:12288ms step_avg:6144.07ms +step:3/20000 train_loss:9.4661 train_time:15200ms step_avg:5066.65ms +step:4/20000 train_loss:9.2167 train_time:18126ms step_avg:4531.58ms +step:5/20000 train_loss:8.9424 train_time:21063ms step_avg:4212.63ms +step:6/20000 train_loss:8.5051 train_time:24012ms step_avg:4002.02ms +step:7/20000 train_loss:8.0528 train_time:26972ms step_avg:3853.10ms +step:8/20000 train_loss:7.6669 train_time:29938ms step_avg:3742.23ms +step:9/20000 train_loss:7.2347 train_time:32912ms step_avg:3656.92ms +step:10/20000 train_loss:6.9912 train_time:35894ms step_avg:3589.40ms +step:100/20000 train_loss:4.6083 train_time:307271ms step_avg:3072.71ms +step:200/20000 train_loss:4.0201 train_time:608202ms step_avg:3041.01ms +step:300/20000 train_loss:3.6721 train_time:907540ms step_avg:3025.13ms +step:400/20000 train_loss:3.6490 train_time:1205808ms step_avg:3014.52ms +step:500/20000 train_loss:3.4560 train_time:1503130ms step_avg:3006.26ms +step:500/20000 val_loss:3.5246 val_bpb:1.3647 train_time:1503141ms step_avg:3006.28ms +step:600/20000 train_loss:3.4968 train_time:1800265ms step_avg:3000.44ms +step:700/20000 train_loss:3.3170 train_time:2098108ms step_avg:2997.30ms +step:800/20000 train_loss:3.3872 train_time:2396748ms step_avg:2995.93ms +step:900/20000 train_loss:3.3626 train_time:2695499ms step_avg:2995.00ms +step:1000/20000 train_loss:3.2063 train_time:2994262ms step_avg:2994.26ms +step:1000/20000 val_loss:3.3010 val_bpb:1.2782 train_time:2994273ms step_avg:2994.27ms +step:1100/20000 train_loss:3.3161 train_time:3293037ms step_avg:2993.67ms +step:1200/20000 train_loss:3.3378 train_time:3591918ms step_avg:2993.26ms +step:1300/20000 train_loss:3.2597 train_time:3891288ms step_avg:2993.30ms +step:1400/20000 train_loss:3.1856 train_time:4190168ms step_avg:2992.98ms +step:1500/20000 train_loss:3.1806 train_time:4488829ms step_avg:2992.55ms +step:1500/20000 val_loss:3.2349 val_bpb:1.2525 train_time:4488840ms step_avg:2992.56ms +step:1600/20000 train_loss:3.2749 train_time:4787505ms step_avg:2992.19ms +step:1700/20000 train_loss:3.2821 train_time:5086174ms step_avg:2991.87ms +step:1800/20000 train_loss:3.2693 train_time:5384058ms step_avg:2991.14ms +step:1900/20000 train_loss:3.2575 train_time:5681937ms step_avg:2990.49ms +step:2000/20000 train_loss:3.2307 train_time:5980004ms step_avg:2990.00ms +step:2000/20000 val_loss:3.2052 val_bpb:1.2411 train_time:5980016ms step_avg:2990.01ms +step:2100/20000 train_loss:3.1999 train_time:6278072ms step_avg:2989.56ms +step:2200/20000 train_loss:3.2041 train_time:6576041ms step_avg:2989.11ms +step:2300/20000 train_loss:3.2646 train_time:6874072ms step_avg:2988.73ms +step:2400/20000 train_loss:3.2319 train_time:7172051ms step_avg:2988.35ms +step:2500/20000 train_loss:3.1826 train_time:7470054ms step_avg:2988.02ms +step:2500/20000 val_loss:3.1812 val_bpb:1.2317 train_time:7470064ms step_avg:2988.03ms +step:2600/20000 train_loss:3.1806 train_time:7767846ms step_avg:2987.63ms +step:2700/20000 train_loss:3.1319 train_time:8065981ms step_avg:2987.40ms +step:2800/20000 train_loss:3.1802 train_time:8363424ms step_avg:2986.94ms +step:2900/20000 train_loss:3.2104 train_time:8660960ms step_avg:2986.54ms +step:3000/20000 train_loss:3.0762 train_time:8958193ms step_avg:2986.06ms +step:3000/20000 val_loss:3.1490 val_bpb:1.2193 train_time:8958204ms step_avg:2986.07ms +step:3100/20000 train_loss:3.1027 train_time:9255247ms step_avg:2985.56ms +step:3200/20000 train_loss:3.1454 train_time:9552546ms step_avg:2985.17ms +step:3300/20000 train_loss:3.1856 train_time:9849931ms step_avg:2984.83ms +step:3400/20000 train_loss:3.1329 train_time:10147567ms step_avg:2984.58ms +step:3500/20000 train_loss:3.1053 train_time:10444922ms step_avg:2984.26ms +step:3500/20000 val_loss:3.1195 val_bpb:1.2079 train_time:10444934ms step_avg:2984.27ms +step:3600/20000 train_loss:3.1105 train_time:10742599ms step_avg:2984.06ms +step:3700/20000 train_loss:3.0893 train_time:11040741ms step_avg:2983.98ms +step:3800/20000 train_loss:3.1714 train_time:11338585ms step_avg:2983.84ms +step:3900/20000 train_loss:3.0760 train_time:11636090ms step_avg:2983.61ms +step:4000/20000 train_loss:3.1469 train_time:11933432ms step_avg:2983.36ms +step:4000/20000 val_loss:3.0825 val_bpb:1.1935 train_time:11933442ms step_avg:2983.36ms +step:4100/20000 train_loss:3.2154 train_time:12230405ms step_avg:2983.03ms +step:4200/20000 train_loss:3.1199 train_time:12527509ms step_avg:2982.74ms +step:4300/20000 train_loss:3.0751 train_time:12824480ms step_avg:2982.44ms +step:4400/20000 train_loss:3.0637 train_time:13121714ms step_avg:2982.21ms +step:4500/20000 train_loss:2.9973 train_time:13419250ms step_avg:2982.06ms +step:4500/20000 val_loss:3.0481 val_bpb:1.1802 train_time:13419260ms step_avg:2982.06ms +step:4600/20000 train_loss:2.9975 train_time:13716423ms step_avg:2981.83ms +step:4700/20000 train_loss:3.0079 train_time:14013217ms step_avg:2981.54ms +step:4800/20000 train_loss:3.0275 train_time:14310102ms step_avg:2981.27ms +step:4900/20000 train_loss:3.0434 train_time:14607662ms step_avg:2981.16ms +step:5000/20000 train_loss:2.9330 train_time:14905280ms step_avg:2981.06ms +step:5000/20000 val_loss:3.0047 val_bpb:1.1634 train_time:14905291ms step_avg:2981.06ms +step:5100/20000 train_loss:2.9578 train_time:15202289ms step_avg:2980.84ms +step:5200/20000 train_loss:2.9865 train_time:15499700ms step_avg:2980.71ms +step:5300/20000 train_loss:3.0451 train_time:15796822ms step_avg:2980.53ms +step:5400/20000 train_loss:2.9772 train_time:16094890ms step_avg:2980.54ms +step:5500/20000 train_loss:2.9313 train_time:16391993ms step_avg:2980.36ms +step:5500/20000 val_loss:2.9527 val_bpb:1.1433 train_time:16392004ms step_avg:2980.36ms +step:5600/20000 train_loss:2.9685 train_time:16688890ms step_avg:2980.16ms +step:5700/20000 train_loss:2.9909 train_time:16986051ms step_avg:2980.01ms +step:5800/20000 train_loss:2.9636 train_time:17283332ms step_avg:2979.88ms +step:5900/20000 train_loss:2.8982 train_time:17580412ms step_avg:2979.73ms +step:6000/20000 train_loss:2.8514 train_time:17877332ms step_avg:2979.56ms +step:6000/20000 val_loss:2.9049 val_bpb:1.1248 train_time:17877343ms step_avg:2979.56ms +step:6042/20000 val_loss:2.9035 val_bpb:1.1242 train_time:18001609ms step_avg:2979.41ms +stopping_early: wallclock_cap train_time:18001609ms step:6042/20000 +peak memory allocated: 16543 MiB reserved: 17772 MiB +eval:restored full crawler loops=2, depth=7 +swa:averaging 14 checkpoints +swa_eval val_loss:2.9009 val_bpb:1.1232 +saved backup: final_model_v5_d736_honest_seed1337.pt +Serialized model: 136629271 bytes +Code size: 90756 bytes +Total submission size: 136720027 bytes +Serialized model int8+zstd-22: 16709260 bytes (payload:38578440 raw_torch:38603741 payload_ratio:3.54x) +Total submission size int8+zlib: 16800016 bytes +final_int8_zlib_roundtrip val_loss:3.0091 val_bpb:1.1651 eval_time:68069ms +final_int8_zlib_roundtrip_exact val_loss:3.00909891 val_bpb:1.16512018 +gptq:loading calibration data from training shards... +gptq:loaded 64 calibration sequences in 4.4s +gptq:collecting hessians... +gptq:collected hessians for 32 layers +gptq:quantizing int6 with full Hessian GPTQ... +selective_prune: 12628044 candidates, unpruned=15.03MB target=15.9MB +selective_prune: already fits, no pruning needed +gptq_int6_brotli: 14,934,784 bytes | code: 90,756 | total: 15,025,540 (15.03MB) +gptq_int6_brotli_roundtrip val_loss:3.0315 val_bpb:1.1738 time:228.4s +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633560 stride=64 +ttt_sliding:params unfrozen=26429492 frozen=11917344 + ttt_chunk [1/1238] bpb=1.235882 time=4.1s + ttt_chunk [11/1238] bpb=1.157259 time=48.5s + ttt_chunk [21/1238] bpb=1.158188 time=92.7s + ttt_chunk [31/1238] bpb=1.152016 time=136.9s + ttt_chunk [41/1238] bpb=1.158436 time=181.1s + ttt_chunk [51/1238] bpb=1.153962 time=225.3s + ttt_chunk [61/1238] bpb=1.150062 time=269.5s + ttt_chunk [71/1238] bpb=1.151934 time=313.7s + ttt_chunk [81/1238] bpb=1.147508 time=357.9s + ttt_chunk [91/1238] bpb=1.145130 time=402.2s + ttt_chunk [101/1238] bpb=1.145042 time=446.4s + ttt_chunk [111/1238] bpb=1.147055 time=490.6s + ttt_chunk [121/1238] bpb=1.147729 time=534.8s + ttt_chunk [131/1238] bpb=1.149781 time=579.1s + ttt_chunk [141/1238] bpb=1.148469 time=623.3s + ttt_chunk [151/1238] bpb=1.148508 time=667.6s + ttt_chunk [161/1238] bpb=1.147791 time=711.8s + ttt_chunk [171/1238] bpb=1.147403 time=756.1s + ttt_chunk [181/1238] bpb=1.146846 time=800.4s + ttt_chunk [191/1238] bpb=1.147160 time=844.7s + ttt_chunk [201/1238] bpb=1.147619 time=888.9s + ttt_chunk [211/1238] bpb=1.148262 time=933.1s + ttt_chunk [221/1238] bpb=1.147273 time=977.3s + ttt_chunk [231/1238] bpb=1.147880 time=1021.6s + ttt_chunk [241/1238] bpb=1.148054 time=1065.8s + ttt_chunk [251/1238] bpb=1.148162 time=1110.1s + ttt_chunk [261/1238] bpb=1.148399 time=1154.3s + ttt_chunk [271/1238] bpb=1.147067 time=1198.5s + ttt_chunk [281/1238] bpb=1.147743 time=1242.8s + ttt_chunk [291/1238] bpb=1.146700 time=1287.0s + ttt_chunk [301/1238] bpb=1.146617 time=1331.2s + ttt_chunk [311/1238] bpb=1.146323 time=1375.4s + ttt_chunk [321/1238] bpb=1.146242 time=1419.6s + ttt_chunk [331/1238] bpb=1.145756 time=1463.9s + ttt_chunk [341/1238] bpb=1.144933 time=1508.1s + ttt_chunk [351/1238] bpb=1.145329 time=1552.3s + ttt_chunk [361/1238] bpb=1.145041 time=1596.5s + ttt_chunk [371/1238] bpb=1.144582 time=1640.7s + ttt_chunk [381/1238] bpb=1.144067 time=1684.9s + ttt_chunk [391/1238] bpb=1.143544 time=1729.1s + ttt_chunk [401/1238] bpb=1.143056 time=1773.2s + ttt_chunk [411/1238] bpb=1.142639 time=1817.5s + ttt_chunk [421/1238] bpb=1.142238 time=1861.7s + ttt_chunk [431/1238] bpb=1.141273 time=1905.9s + ttt_chunk [441/1238] bpb=1.140484 time=1950.1s + ttt_chunk [451/1238] bpb=1.140502 time=1994.4s + ttt_chunk [461/1238] bpb=1.139339 time=2038.6s + ttt_chunk [471/1238] bpb=1.139193 time=2082.8s + ttt_chunk [481/1238] bpb=1.139453 time=2127.0s + ttt_chunk [491/1238] bpb=1.139016 time=2171.3s + ttt_chunk [501/1238] bpb=1.138997 time=2215.5s + ttt_chunk [511/1238] bpb=1.139022 time=2259.8s + ttt_chunk [521/1238] bpb=1.138666 time=2304.1s + ttt_chunk [531/1238] bpb=1.138662 time=2348.3s + ttt_chunk [541/1238] bpb=1.138545 time=2392.6s + ttt_chunk [551/1238] bpb=1.138039 time=2436.8s + ttt_chunk [561/1238] bpb=1.137976 time=2481.1s + ttt_chunk [571/1238] bpb=1.138238 time=2525.3s + ttt_chunk [581/1238] bpb=1.137958 time=2569.5s + ttt_chunk [591/1238] bpb=1.137544 time=2613.8s + ttt_chunk [601/1238] bpb=1.137458 time=2658.0s + ttt_chunk [611/1238] bpb=1.137383 time=2702.2s + ttt_chunk [621/1238] bpb=1.137983 time=2746.4s + ttt_chunk [631/1238] bpb=1.138263 time=2790.6s + ttt_chunk [641/1238] bpb=1.138652 time=2834.8s + ttt_chunk [651/1238] bpb=1.138662 time=2879.1s + ttt_chunk [661/1238] bpb=1.139027 time=2923.3s + ttt_chunk [671/1238] bpb=1.139435 time=2967.5s + ttt_chunk [681/1238] bpb=1.140103 time=3011.8s + ttt_chunk [691/1238] bpb=1.140155 time=3056.1s + ttt_chunk [701/1238] bpb=1.140226 time=3100.3s + ttt_chunk [711/1238] bpb=1.140497 time=3144.5s + ttt_chunk [721/1238] bpb=1.140640 time=3188.8s + ttt_chunk [731/1238] bpb=1.140282 time=3233.0s + ttt_chunk [741/1238] bpb=1.139939 time=3277.3s + ttt_chunk [751/1238] bpb=1.139677 time=3321.5s + ttt_chunk [761/1238] bpb=1.139510 time=3365.7s + ttt_chunk [771/1238] bpb=1.139005 time=3410.0s + ttt_chunk [781/1238] bpb=1.139373 time=3454.2s + ttt_chunk [791/1238] bpb=1.138901 time=3498.5s + ttt_chunk [801/1238] bpb=1.139205 time=3542.7s + ttt_chunk [811/1238] bpb=1.138799 time=3586.9s + ttt_chunk [821/1238] bpb=1.138111 time=3631.2s + ttt_chunk [831/1238] bpb=1.137716 time=3675.4s + ttt_chunk [841/1238] bpb=1.137326 time=3719.7s + ttt_chunk [851/1238] bpb=1.136996 time=3763.9s + ttt_chunk [861/1238] bpb=1.136624 time=3808.2s + ttt_chunk [871/1238] bpb=1.136190 time=3852.5s + ttt_chunk [881/1238] bpb=1.135921 time=3896.7s + ttt_chunk [891/1238] bpb=1.136048 time=3941.0s + ttt_chunk [901/1238] bpb=1.136391 time=3985.2s + ttt_chunk [911/1238] bpb=1.136253 time=4029.5s + ttt_chunk [921/1238] bpb=1.136338 time=4073.6s + ttt_chunk [931/1238] bpb=1.136289 time=4117.9s + ttt_chunk [941/1238] bpb=1.136680 time=4162.1s + ttt_chunk [951/1238] bpb=1.136553 time=4206.3s + ttt_chunk [961/1238] bpb=1.137063 time=4250.6s + ttt_chunk [971/1238] bpb=1.137208 time=4294.8s + ttt_chunk [981/1238] bpb=1.137248 time=4339.0s + ttt_chunk [991/1238] bpb=1.137200 time=4383.2s + ttt_chunk [1001/1238] bpb=1.137512 time=4427.3s + ttt_chunk [1011/1238] bpb=1.137658 time=4471.6s + ttt_chunk [1021/1238] bpb=1.137898 time=4515.8s + ttt_chunk [1031/1238] bpb=1.138091 time=4560.0s + ttt_chunk [1041/1238] bpb=1.138220 time=4604.2s + ttt_chunk [1051/1238] bpb=1.138456 time=4648.4s + ttt_chunk [1061/1238] bpb=1.138436 time=4692.7s + ttt_chunk [1071/1238] bpb=1.138475 time=4736.9s + ttt_chunk [1081/1238] bpb=1.138548 time=4781.1s + ttt_chunk [1091/1238] bpb=1.138738 time=4825.3s + ttt_chunk [1101/1238] bpb=1.138920 time=4869.6s + ttt_chunk [1111/1238] bpb=1.138962 time=4913.8s + ttt_chunk [1121/1238] bpb=1.138892 time=4958.1s + ttt_chunk [1131/1238] bpb=1.138973 time=5002.4s + ttt_chunk [1141/1238] bpb=1.138668 time=5046.7s + ttt_chunk [1151/1238] bpb=1.138614 time=5090.9s + ttt_chunk [1161/1238] bpb=1.138482 time=5135.2s + ttt_chunk [1171/1238] bpb=1.138089 time=5179.5s + ttt_chunk [1181/1238] bpb=1.137942 time=5223.7s + ttt_chunk [1191/1238] bpb=1.137941 time=5268.0s + ttt_chunk [1201/1238] bpb=1.137889 time=5312.3s + ttt_chunk [1211/1238] bpb=1.137556 time=5356.5s + ttt_chunk [1221/1238] bpb=1.137488 time=5400.8s + ttt_chunk [1231/1238] bpb=1.137192 time=5445.0s + ttt_chunk [1238/1238] bpb=1.137200 time=5473.2s +ttt_sliding:done val_loss=2.937027 val_bpb=1.137200 elapsed=5473.4s +final_ttt_sliding val_loss:2.9370 val_bpb:1.1372 eval_time:5473600ms diff --git a/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_seed2024.log b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_seed2024.log new file mode 100644 index 0000000000..be807a01fc --- /dev/null +++ b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_seed2024.log @@ -0,0 +1,2246 @@ +logs/v5_d736_honest_seed2024.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_8192_bpe.model +train_loader:dataset:fineweb10B_sp8192 train_shards:128 +val_loader:shards pattern=./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin tokens:40546304 +qat:enabled from step 0 attn=6bit +architecture:crawler flat_blocks:3 crawler_blocks:2 crawler_loops:2 effective_depth:7 flat_params:17876016 crawler_params:11917344 per_loop_params:20608 +model_params:38346836 +world_size:1 grad_accum_steps:8 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:16 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:18000.000 +seed:2024 +warmup_step:1/100 +warmup_step:2/100 +warmup_step:3/100 +warmup_step:4/100 +warmup_step:5/100 +warmup_step:6/100 +warmup_step:7/100 +warmup_step:8/100 +warmup_step:9/100 +warmup_step:10/100 +warmup_step:11/100 +warmup_step:12/100 +warmup_step:13/100 +warmup_step:14/100 +warmup_step:15/100 +warmup_step:16/100 +warmup_step:17/100 +warmup_step:18/100 +warmup_step:19/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:8.9979 val_bpb:3.4840 train_time:0ms step_avg:0.01ms +step:1/20000 train_loss:8.9985 train_time:9154ms step_avg:9153.77ms +step:2/20000 train_loss:8.8442 train_time:12042ms step_avg:6021.11ms +step:3/20000 train_loss:9.5443 train_time:14982ms step_avg:4993.95ms +step:4/20000 train_loss:9.3783 train_time:17928ms step_avg:4482.11ms +step:5/20000 train_loss:9.0613 train_time:20887ms step_avg:4177.39ms +step:6/20000 train_loss:8.6121 train_time:23859ms step_avg:3976.55ms +step:7/20000 train_loss:8.1236 train_time:26838ms step_avg:3833.97ms +step:8/20000 train_loss:7.7478 train_time:29814ms step_avg:3726.72ms +step:9/20000 train_loss:7.3007 train_time:32801ms step_avg:3644.52ms +step:10/20000 train_loss:7.0257 train_time:35788ms step_avg:3578.84ms +step:100/20000 train_loss:4.5913 train_time:308505ms step_avg:3085.05ms +step:200/20000 train_loss:3.9909 train_time:610988ms step_avg:3054.94ms +step:300/20000 train_loss:3.6547 train_time:912024ms step_avg:3040.08ms +step:400/20000 train_loss:3.6317 train_time:1212321ms step_avg:3030.80ms +step:500/20000 train_loss:3.4434 train_time:1511796ms step_avg:3023.59ms +step:500/20000 val_loss:3.5154 val_bpb:1.3612 train_time:1511807ms step_avg:3023.61ms +step:600/20000 train_loss:3.4873 train_time:1810740ms step_avg:3017.90ms +step:700/20000 train_loss:3.3120 train_time:2109767ms step_avg:3013.95ms +step:800/20000 train_loss:3.3792 train_time:2409950ms step_avg:3012.44ms +step:900/20000 train_loss:3.3532 train_time:2708987ms step_avg:3009.99ms +step:1000/20000 train_loss:3.1959 train_time:3007827ms step_avg:3007.83ms +step:1000/20000 val_loss:3.2950 val_bpb:1.2758 train_time:3007837ms step_avg:3007.84ms +step:1100/20000 train_loss:3.3101 train_time:3306387ms step_avg:3005.81ms +step:1200/20000 train_loss:3.3326 train_time:3605722ms step_avg:3004.77ms +step:1300/20000 train_loss:3.2536 train_time:3904658ms step_avg:3003.58ms +step:1400/20000 train_loss:3.1792 train_time:4203358ms step_avg:3002.40ms +step:1500/20000 train_loss:3.1747 train_time:4501748ms step_avg:3001.17ms +step:1500/20000 val_loss:3.2322 val_bpb:1.2515 train_time:4501759ms step_avg:3001.17ms +step:1600/20000 train_loss:3.2703 train_time:4800387ms step_avg:3000.24ms +step:1700/20000 train_loss:3.2802 train_time:5099140ms step_avg:2999.49ms +step:1800/20000 train_loss:3.2649 train_time:5398037ms step_avg:2998.91ms +step:1900/20000 train_loss:3.2537 train_time:5696910ms step_avg:2998.37ms +step:2000/20000 train_loss:3.2246 train_time:5995628ms step_avg:2997.81ms +step:2000/20000 val_loss:3.2020 val_bpb:1.2398 train_time:5995639ms step_avg:2997.82ms +step:2100/20000 train_loss:3.2014 train_time:6295882ms step_avg:2998.04ms +step:2200/20000 train_loss:3.2036 train_time:6598084ms step_avg:2999.13ms +step:2300/20000 train_loss:3.2649 train_time:6900274ms step_avg:3000.12ms +step:2400/20000 train_loss:3.2296 train_time:7202436ms step_avg:3001.01ms +step:2500/20000 train_loss:3.1817 train_time:7504995ms step_avg:3002.00ms +step:2500/20000 val_loss:3.1792 val_bpb:1.2310 train_time:7505006ms step_avg:3002.00ms +step:2600/20000 train_loss:3.1787 train_time:7807654ms step_avg:3002.94ms +step:2700/20000 train_loss:3.1308 train_time:8109422ms step_avg:3003.49ms +step:2800/20000 train_loss:3.1756 train_time:8411635ms step_avg:3004.16ms +step:2900/20000 train_loss:3.2080 train_time:8713913ms step_avg:3004.80ms +step:3000/20000 train_loss:3.0750 train_time:9023452ms step_avg:3007.82ms +step:3000/20000 val_loss:3.1454 val_bpb:1.2179 train_time:9023462ms step_avg:3007.82ms +step:3100/20000 train_loss:3.0976 train_time:9330588ms step_avg:3009.87ms +step:3200/20000 train_loss:3.1408 train_time:9637979ms step_avg:3011.87ms +step:3300/20000 train_loss:3.1849 train_time:9943226ms step_avg:3013.10ms +step:3400/20000 train_loss:3.1284 train_time:10244256ms step_avg:3013.02ms +step:3500/20000 train_loss:3.1003 train_time:10546594ms step_avg:3013.31ms +step:3500/20000 val_loss:3.1149 val_bpb:1.2061 train_time:10546604ms step_avg:3013.32ms +step:3600/20000 train_loss:3.1072 train_time:10847569ms step_avg:3013.21ms +step:3700/20000 train_loss:3.0846 train_time:11149057ms step_avg:3013.26ms +step:3800/20000 train_loss:3.1645 train_time:11450073ms step_avg:3013.18ms +step:3900/20000 train_loss:3.0697 train_time:11750799ms step_avg:3013.03ms +step:4000/20000 train_loss:3.1413 train_time:12051422ms step_avg:3012.86ms +step:4000/20000 val_loss:3.0763 val_bpb:1.1912 train_time:12051433ms step_avg:3012.86ms +step:4100/20000 train_loss:3.2114 train_time:12352011ms step_avg:3012.69ms +step:4200/20000 train_loss:3.1149 train_time:12652918ms step_avg:3012.60ms +step:4300/20000 train_loss:3.0717 train_time:12953568ms step_avg:3012.46ms +step:4400/20000 train_loss:3.0558 train_time:13254465ms step_avg:3012.38ms +step:4500/20000 train_loss:2.9917 train_time:13554738ms step_avg:3012.16ms +step:4500/20000 val_loss:3.0429 val_bpb:1.1782 train_time:13554749ms step_avg:3012.17ms +step:4600/20000 train_loss:2.9929 train_time:13855555ms step_avg:3012.08ms +step:4700/20000 train_loss:2.9993 train_time:14156653ms step_avg:3012.05ms +step:4800/20000 train_loss:3.0195 train_time:14457770ms step_avg:3012.04ms +step:4900/20000 train_loss:3.0339 train_time:14758836ms step_avg:3012.01ms +step:5000/20000 train_loss:2.9252 train_time:15059542ms step_avg:3011.91ms +step:5000/20000 val_loss:2.9982 val_bpb:1.1609 train_time:15059554ms step_avg:3011.91ms +step:5100/20000 train_loss:2.9508 train_time:15360092ms step_avg:3011.78ms +step:5200/20000 train_loss:2.9765 train_time:15660946ms step_avg:3011.72ms +step:5300/20000 train_loss:3.0363 train_time:15961815ms step_avg:3011.66ms +step:5400/20000 train_loss:2.9683 train_time:16263499ms step_avg:3011.76ms +step:5500/20000 train_loss:2.9221 train_time:16562189ms step_avg:3011.31ms +step:5500/20000 val_loss:2.9440 val_bpb:1.1399 train_time:16562200ms step_avg:3011.31ms +step:5600/20000 train_loss:2.9594 train_time:16863002ms step_avg:3011.25ms +step:5700/20000 train_loss:2.9820 train_time:17164375ms step_avg:3011.29ms +step:5800/20000 train_loss:2.9548 train_time:17466353ms step_avg:3011.44ms +step:5900/20000 train_loss:2.8919 train_time:17768518ms step_avg:3011.61ms +step:5977/20000 val_loss:2.9011 val_bpb:1.1233 train_time:18001266ms step_avg:3011.76ms +stopping_early: wallclock_cap train_time:18001266ms step:5977/20000 +peak memory allocated: 16543 MiB reserved: 17772 MiB +eval:restored full crawler loops=2, depth=7 +swa:averaging 14 checkpoints +swa_eval val_loss:2.8983 val_bpb:1.1222 +saved backup: final_model_v5_d736_honest_seed2024.pt +Serialized model: 136629271 bytes +Code size: 90756 bytes +Total submission size: 136720027 bytes +Serialized model int8+zstd-22: 16739898 bytes (payload:38578440 raw_torch:38603741 payload_ratio:3.54x) +Total submission size int8+zlib: 16830654 bytes +final_int8_zlib_roundtrip val_loss:3.0091 val_bpb:1.1651 eval_time:68980ms +final_int8_zlib_roundtrip_exact val_loss:3.00910640 val_bpb:1.16512308 +gptq:loading calibration data from training shards... +gptq:loaded 64 calibration sequences in 4.7s +gptq:collecting hessians... +gptq:collected hessians for 32 layers +gptq:quantizing int6 with full Hessian GPTQ... +selective_prune: 12704738 candidates, unpruned=15.08MB target=15.9MB +selective_prune: already fits, no pruning needed +gptq_int6_brotli: 14,984,356 bytes | code: 90,756 | total: 15,075,112 (15.08MB) +gptq_int6_brotli_roundtrip val_loss:3.0335 val_bpb:1.1746 time:245.2s +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633560 stride=64 +ttt_sliding:params unfrozen=26429492 frozen=11917344 + ttt_chunk [1/1238] bpb=1.236547 time=4.4s + ttt_chunk [11/1238] bpb=1.156854 time=51.7s + ttt_chunk [21/1238] bpb=1.158441 time=98.9s + ttt_chunk [31/1238] bpb=1.152176 time=146.0s + ttt_chunk [41/1238] bpb=1.158188 time=193.3s + ttt_chunk [51/1238] bpb=1.153843 time=240.9s + ttt_chunk [61/1238] bpb=1.149850 time=288.4s + ttt_chunk [71/1238] bpb=1.151636 time=335.6s + ttt_chunk [81/1238] bpb=1.147172 time=383.2s + ttt_chunk [91/1238] bpb=1.144845 time=432.8s + ttt_chunk [101/1238] bpb=1.144776 time=482.3s + ttt_chunk [111/1238] bpb=1.146817 time=533.1s + ttt_chunk [121/1238] bpb=1.147500 time=583.6s + ttt_chunk [131/1238] bpb=1.149573 time=633.0s + ttt_chunk [141/1238] bpb=1.148279 time=681.4s + ttt_chunk [151/1238] bpb=1.148338 time=730.4s + ttt_chunk [161/1238] bpb=1.147643 time=779.8s + ttt_chunk [171/1238] bpb=1.147288 time=828.2s + ttt_chunk [181/1238] bpb=1.146785 time=876.9s + ttt_chunk [191/1238] bpb=1.147097 time=926.1s + ttt_chunk [201/1238] bpb=1.147536 time=974.8s + ttt_chunk [211/1238] bpb=1.148242 time=1023.2s + ttt_chunk [221/1238] bpb=1.147240 time=1072.1s + ttt_chunk [231/1238] bpb=1.147805 time=1120.5s + ttt_chunk [241/1238] bpb=1.148025 time=1170.3s + ttt_chunk [251/1238] bpb=1.148119 time=1220.6s + ttt_chunk [261/1238] bpb=1.148321 time=1271.0s + ttt_chunk [271/1238] bpb=1.146951 time=1321.6s + ttt_chunk [281/1238] bpb=1.147596 time=1370.8s + ttt_chunk [291/1238] bpb=1.146565 time=1421.2s + ttt_chunk [301/1238] bpb=1.146495 time=1470.3s + ttt_chunk [311/1238] bpb=1.146206 time=1519.4s + ttt_chunk [321/1238] bpb=1.146118 time=1565.2s + ttt_chunk [331/1238] bpb=1.145627 time=1612.1s + ttt_chunk [341/1238] bpb=1.144829 time=1659.3s + ttt_chunk [351/1238] bpb=1.145217 time=1707.8s + ttt_chunk [361/1238] bpb=1.144928 time=1758.3s + ttt_chunk [371/1238] bpb=1.144474 time=1809.2s + ttt_chunk [381/1238] bpb=1.143944 time=1860.9s + ttt_chunk [391/1238] bpb=1.143432 time=1910.3s + ttt_chunk [401/1238] bpb=1.142925 time=1959.0s + ttt_chunk [411/1238] bpb=1.142513 time=2006.5s + ttt_chunk [421/1238] bpb=1.142094 time=2052.7s + ttt_chunk [431/1238] bpb=1.141122 time=2099.5s + ttt_chunk [441/1238] bpb=1.140331 time=2149.0s + ttt_chunk [451/1238] bpb=1.140319 time=2198.7s + ttt_chunk [461/1238] bpb=1.139144 time=2247.6s + ttt_chunk [471/1238] bpb=1.139022 time=2295.6s + ttt_chunk [481/1238] bpb=1.139269 time=2343.7s + ttt_chunk [491/1238] bpb=1.138840 time=2391.8s + ttt_chunk [501/1238] bpb=1.138800 time=2442.9s + ttt_chunk [511/1238] bpb=1.138831 time=2492.8s + ttt_chunk [521/1238] bpb=1.138469 time=2541.6s + ttt_chunk [531/1238] bpb=1.138478 time=2590.6s + ttt_chunk [541/1238] bpb=1.138338 time=2639.6s + ttt_chunk [551/1238] bpb=1.137816 time=2688.2s + ttt_chunk [561/1238] bpb=1.137739 time=2736.0s + ttt_chunk [571/1238] bpb=1.138005 time=2785.1s + ttt_chunk [581/1238] bpb=1.137721 time=2831.2s + ttt_chunk [591/1238] bpb=1.137306 time=2876.3s + ttt_chunk [601/1238] bpb=1.137235 time=2920.8s + ttt_chunk [611/1238] bpb=1.137146 time=2965.2s + ttt_chunk [621/1238] bpb=1.137724 time=3009.9s + ttt_chunk [631/1238] bpb=1.137995 time=3054.3s + ttt_chunk [641/1238] bpb=1.138389 time=3098.8s + ttt_chunk [651/1238] bpb=1.138391 time=3143.1s + ttt_chunk [661/1238] bpb=1.138756 time=3187.5s + ttt_chunk [671/1238] bpb=1.139146 time=3231.9s + ttt_chunk [681/1238] bpb=1.139803 time=3276.3s + ttt_chunk [691/1238] bpb=1.139855 time=3320.7s + ttt_chunk [701/1238] bpb=1.139933 time=3365.1s + ttt_chunk [711/1238] bpb=1.140198 time=3409.5s + ttt_chunk [721/1238] bpb=1.140354 time=3453.9s + ttt_chunk [731/1238] bpb=1.140005 time=3498.4s + ttt_chunk [741/1238] bpb=1.139663 time=3542.8s + ttt_chunk [751/1238] bpb=1.139394 time=3587.2s + ttt_chunk [761/1238] bpb=1.139239 time=3631.6s + ttt_chunk [771/1238] bpb=1.138722 time=3676.0s + ttt_chunk [781/1238] bpb=1.139084 time=3720.6s + ttt_chunk [791/1238] bpb=1.138613 time=3765.7s + ttt_chunk [801/1238] bpb=1.138918 time=3811.5s + ttt_chunk [811/1238] bpb=1.138512 time=3856.2s + ttt_chunk [821/1238] bpb=1.137832 time=3901.1s + ttt_chunk [831/1238] bpb=1.137441 time=3946.5s + ttt_chunk [841/1238] bpb=1.137055 time=3991.6s + ttt_chunk [851/1238] bpb=1.136724 time=4036.0s + ttt_chunk [861/1238] bpb=1.136350 time=4080.6s + ttt_chunk [871/1238] bpb=1.135907 time=4125.1s + ttt_chunk [881/1238] bpb=1.135633 time=4169.5s + ttt_chunk [891/1238] bpb=1.135749 time=4213.9s + ttt_chunk [901/1238] bpb=1.136089 time=4258.4s + ttt_chunk [911/1238] bpb=1.135953 time=4302.8s + ttt_chunk [921/1238] bpb=1.136035 time=4347.3s + ttt_chunk [931/1238] bpb=1.135995 time=4391.7s + ttt_chunk [941/1238] bpb=1.136379 time=4436.3s + ttt_chunk [951/1238] bpb=1.136246 time=4480.7s + ttt_chunk [961/1238] bpb=1.136755 time=4525.1s + ttt_chunk [971/1238] bpb=1.136897 time=4569.5s + ttt_chunk [981/1238] bpb=1.136933 time=4613.9s + ttt_chunk [991/1238] bpb=1.136876 time=4658.3s + ttt_chunk [1001/1238] bpb=1.137191 time=4702.8s + ttt_chunk [1011/1238] bpb=1.137346 time=4747.4s + ttt_chunk [1021/1238] bpb=1.137573 time=4792.3s + ttt_chunk [1031/1238] bpb=1.137761 time=4837.0s + ttt_chunk [1041/1238] bpb=1.137881 time=4881.6s + ttt_chunk [1051/1238] bpb=1.138111 time=4926.5s + ttt_chunk [1061/1238] bpb=1.138082 time=4971.1s + ttt_chunk [1071/1238] bpb=1.138124 time=5015.6s + ttt_chunk [1081/1238] bpb=1.138190 time=5060.7s + ttt_chunk [1091/1238] bpb=1.138383 time=5105.2s + ttt_chunk [1101/1238] bpb=1.138557 time=5150.3s + ttt_chunk [1111/1238] bpb=1.138604 time=5194.7s + ttt_chunk [1121/1238] bpb=1.138535 time=5239.5s + ttt_chunk [1131/1238] bpb=1.138625 time=5284.1s + ttt_chunk [1141/1238] bpb=1.138310 time=5328.9s + ttt_chunk [1151/1238] bpb=1.138253 time=5373.4s + ttt_chunk [1161/1238] bpb=1.138129 time=5422.7s + ttt_chunk [1171/1238] bpb=1.137736 time=5473.6s + ttt_chunk [1181/1238] bpb=1.137595 time=5524.8s + ttt_chunk [1191/1238] bpb=1.137587 time=5576.0s + ttt_chunk [1201/1238] bpb=1.137536 time=5626.8s + ttt_chunk [1211/1238] bpb=1.137208 time=5677.3s + ttt_chunk [1221/1238] bpb=1.137136 time=5728.0s + ttt_chunk [1231/1238] bpb=1.136839 time=5779.3s + ttt_chunk [1238/1238] bpb=1.136837 time=5811.7s +ttt_sliding:done val_loss=2.936090 val_bpb=1.136837 elapsed=5811.9s +final_ttt_sliding val_loss:2.9361 val_bpb:1.1368 eval_time:5812107ms + = scale[improved] + best_err[improved] = err[improved] + return best_q.contiguous(), best_scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous() + + if sdclip_k > 0: + # SDClip for 1D: use global std + clip_abs = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + else: + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / max_val if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), min_val, max_val).to(torch.int8).contiguous() + return q, scale + +def quantize_state_dict_int8(state_dict: dict[str, Tensor], qat_bits: int = 8, qat_mlp_bits: int = 0): + quantized: dict[str, Tensor] = {} + scales: dict[str, Tensor] = {} + dtypes: dict[str, str] = {} + passthrough: dict[str, Tensor] = {} + passthrough_orig_dtypes: dict[str, str] = {} + qmeta: dict[str, dict[str, object]] = {} + stats = dict.fromkeys( + ("param_count", "num_tensors", "num_float_tensors", "num_nonfloat_tensors", "baseline_tensor_bytes", "int8_payload_bytes"), + 0, + ) + + for name, tensor in state_dict.items(): + t = tensor.detach().to("cpu").contiguous() + stats["param_count"] += int(t.numel()) + stats["num_tensors"] += 1 + stats["baseline_tensor_bytes"] += tensor_nbytes(t) + + if not t.is_floating_point(): + stats["num_nonfloat_tensors"] += 1 + passthrough[name] = t + stats["int8_payload_bytes"] += tensor_nbytes(t) + continue + + if t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + kept = keep_float_tensor(name, t, passthrough_orig_dtypes) + passthrough[name] = kept + stats["int8_payload_bytes"] += tensor_nbytes(kept) + continue + + stats["num_float_tensors"] += 1 + is_block_weight = any(k in name for k in ("flat_blocks.", "crawler_blocks.", "bigram.proj.")) + is_embed_weight = ("tok_emb.weight" in name) + is_mlp_weight = any(k in name for k in ("mlp.fc.weight", "mlp.proj.weight")) + if qat_bits < 8 and is_block_weight and t.ndim == 2: + n_bits = (qat_mlp_bits if (qat_mlp_bits > 0 and is_mlp_weight) else qat_bits) + sdclip_k = 12.85 + elif is_embed_weight: + n_bits = 8 + sdclip_k = 20.0 + else: + n_bits = 8 + sdclip_k = 20.0 + q, s = quantize_float_tensor(t, n_bits=n_bits, sdclip_k=sdclip_k) + if s.ndim > 0: + qmeta[name] = {"scheme": "per_row", "axis": 0} + quantized[name] = q + scales[name] = s + dtypes[name] = str(t.dtype).removeprefix("torch.") + stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + obj: dict[str, object] = { + "__quant_format__": "int8_clean_per_row_v1", + "quantized": quantized, + "scales": scales, + "dtypes": dtypes, + "passthrough": passthrough, + } + if qmeta: + obj["qmeta"] = qmeta + if passthrough_orig_dtypes: + obj["passthrough_orig_dtypes"] = passthrough_orig_dtypes + return obj, stats + +def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + qmeta = obj.get("qmeta", {}) + passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {}) + for name, q in obj["quantized"].items(): + dtype = getattr(torch, obj["dtypes"][name]) + s = obj["scales"][name] + if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: + s = s.to(dtype=torch.float32) + 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 + +def generate_calib_from_data(train_files, device, num_seqs=64, seq_len=2048, seed=42): + rng = random.Random(seed) + shard_files = sorted(glob.glob(train_files)) + all_tokens = [] + while len(all_tokens) < num_seqs: + shard = Path(rng.choice(shard_files)) + data = load_data_shard(shard) + max_start = data.numel() - seq_len - 1 + if max_start <= 0: + continue + start = rng.randint(0, max_start) + seq = data[start:start + seq_len + 1].unsqueeze(0).to(device=device, dtype=torch.int64) + all_tokens.append(seq) + return all_tokens[:num_seqs] + +def collect_hessians_from_tokens(hessian_model, token_seqs, device): + hessians = {} + hooks = [] + for name, module in hessian_model.named_modules(): + if isinstance(module, CastedLinear): + param_name = name + ".weight" + cols = module.weight.shape[1] + hessians[param_name] = torch.zeros(cols, cols, dtype=torch.float32, device='cpu') + def make_hook(pname): + def hook_fn(module, input, output): + x = input[0].detach().float() + if x.ndim == 3: + x = x.reshape(-1, x.shape[-1]) + hessians[pname] += (x.T @ x).cpu() + return hook_fn + h = module.register_forward_hook(make_hook(param_name)) + hooks.append(h) + hessian_model.eval() + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16): + for seq in token_seqs: + x = seq[:, :-1].to(device) + y = seq[:, 1:].to(device) + hessian_model(x, y) + for h in hooks: + h.remove() + for name in hessians: + H = hessians[name] + H /= len(token_seqs) + damp = 0.01 * torch.diag(H).mean().clamp_min(1e-6) + H += damp * torch.eye(H.shape[0]) + hessians[name] = H + return hessians + +def quantize_int6_gptq(weight, hessian=None, clip_range=31, block_size=128, sdclip_k: float = 0.0): + t32 = weight.float() + if t32.ndim != 2 or hessian is None: + return quantize_int6_per_row(t32, clip_range, sdclip_k=sdclip_k) + rows, cols = t32.shape + H = hessian.float().clone() + dead = torch.diag(H) == 0 + H[dead, dead] = 1 + damp = 0.01 * torch.mean(torch.diag(H)) + H[torch.arange(cols), torch.arange(cols)] += damp + perm = torch.argsort(torch.diag(H), descending=True) + inv_perm = torch.argsort(perm) + W = t32[:, perm].clone() + W[:, dead[perm]] = 0 + H = H[perm][:, perm] + try: + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + except torch._C._LinAlgError: + H[torch.arange(cols), torch.arange(cols)] += 0.1 * torch.mean(torch.diag(H)) + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + best_q = Q[:, inv_perm] + return best_q, s + best_q, best_scale, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + recon = Q.float() * sf[:, None] + mse = (W - recon).pow(2).mean().item() + if mse < best_err: + best_q, best_scale, best_err = Q, s, mse + best_q = best_q[:, inv_perm] + return best_q, best_scale + +def quantize_int6_per_row(t, clip_range=31, sdclip_k: float = 0.0): + t32 = t.float() if not t.is_floating_point() else t.float() + if t32.ndim == 2: + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + return q, s + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + recon = q.float() * s.float()[:, None] + err = (t32 - recon).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, s, err + return best_q, best_s + if sdclip_k > 0: + clip_val = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_val / clip_range if clip_val > 0 else 1.0, dtype=torch.float16) + else: + amax = t32.abs().max().item() + scale = torch.tensor(amax / clip_range if amax > 0 else 1.0, dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -clip_range, clip_range).to(torch.int8) + return q, scale + +def mixed_quantize_int6_gptq(state_dict, hessians=None): + result = {} + meta = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + if not t.is_floating_point() or t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + is_block = any(k in name for k in ("flat_blocks.", "crawler_blocks.")) + if is_block and t.ndim == 2: + H = hessians.get(name) if hessians else None + q, s = quantize_int6_gptq(t, hessian=H, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + else: + q, s = quantize_int6_per_row(t, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + return result, meta + +def dequantize_mixed_int6(result, meta, template_sd): + out = {} + for name, orig in template_sd.items(): + info = meta.get(name) + if info is None: + continue + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = 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) + +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) + +def _fake_quantize_ste(w: Tensor, n_bits: int) -> Tensor: + max_val = 2 ** (n_bits - 1) - 1 + min_val = -(2 ** (n_bits - 1)) + scale = w.abs().amax(dim=-1, keepdim=True) / max_val + scale = scale.clamp_min(1e-8) + w_q = (w / scale).round().clamp(min_val, max_val) * scale + return w + (w_q - w).detach() + +_QAT_ENABLED = False +_QAT_BITS = 6 +_QAT_MLP_BITS = 0 +_ACTIVE_CRAWLER_LOOPS = 1 + +class CastedLinear(nn.Linear): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._is_mlp = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if _QAT_ENABLED and self.weight.ndim == 2 and self.weight.numel() > 65536: + bits = (_QAT_MLP_BITS if (_QAT_MLP_BITS > 0 and self._is_mlp) else _QAT_BITS) + w = _fake_quantize_ste(w, bits) + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0): + super().__init__() + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + +class CausalSelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int, + rope_base: float, + qk_gain_init: float, + ): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + 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(3) + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, q_delta=None, v_delta=None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x) + (q_delta if q_delta is not None else 0) + k = self.c_k(x) + v = self.c_v(x) + (v_delta if v_delta is not None else 0) + q = q.reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = k.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = v.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + rope_dim = cos.size(-1) + partial = rope_dim // 2 + if partial > 0: + q_rope, q_pass = q[..., :partial*2], q[..., partial*2:] + k_rope, k_pass = k[..., :partial*2], k[..., partial*2:] + q_rope = apply_rotary_emb(q_rope, cos[..., :partial], sin[..., :partial]) + k_rope = apply_rotary_emb(k_rope, cos[..., :partial], sin[..., :partial]) + q = torch.cat([q_rope, q_pass], dim=-1) + k = torch.cat([k_rope, k_pass], dim=-1) + else: + 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 = self._xsa_efficient(y.transpose(1, 2), v.transpose(1, 2)).contiguous().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): + super().__init__() + hidden = mlp_mult * dim + self.fc = CastedLinear(dim, hidden, bias=False) + self.fc._is_mlp = True + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + self.proj._is_mlp = True + + def forward(self, x: Tensor) -> Tensor: + x = torch.relu(self.fc(x)) + return self.proj(x.square()) + +class ValueEmbedding(nn.Module): + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int, num_loops_active: int): + super().__init__() + self.table = nn.Embedding(vocab_size, ve_dim) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) + self.scales = nn.ParameterList([nn.Parameter(torch.ones(1)) for _ in range(num_loops_active)]) + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor, loop_idx: int) -> Tensor: + return self.scales[loop_idx] * self.proj(self.table(input_ids)) + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate).to(dtype=x.dtype) + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1.0 - g) * x + g * x_prev + +class BigramHashEmbedding(nn.Module): + def __init__(self, num_buckets: int, hash_dim: int, model_dim: int): + super().__init__() + self.num_buckets = num_buckets + self.table = nn.Embedding(num_buckets, hash_dim) + self.proj = CastedLinear(hash_dim, model_dim, bias=False) + self.proj._zero_init = True + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor) -> Tensor: + bsz, seqlen = input_ids.shape + prev_ids = torch.cat([ + torch.zeros(bsz, 1, dtype=input_ids.dtype, device=input_ids.device), + input_ids[:, :-1], + ], dim=1) + h = ((prev_ids.long() * 92821 + input_ids.long()) % self.num_buckets).long() + return self.proj(self.table(h)) + +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, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init) + self.mlp = MLP(dim, mlp_mult) + + def forward( + self, x: Tensor, x0: Tensor, + attn_scale: Tensor, mlp_scale: Tensor, resid_mix: Tensor, + q_delta_fn=None, v_delta_fn=None, v_embed=None, + ) -> Tensor: + mix = resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + n = self.attn_norm(x) + qd = q_delta_fn(n) if q_delta_fn is not None else None + vd = v_delta_fn(n) if v_delta_fn is not None else None + if v_embed is not None: + vd = (vd + v_embed) if vd is not None else v_embed + attn_out = self.attn(n, qd, vd) + x = x + attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x)) + return x + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_flat_blocks: int, + num_crawler_blocks: int, + crawler_loops: 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, + use_smear_gate: bool = True, + bigram_buckets: int = 10240, + bigram_dim: int = 128, + embed_bottleneck: int = 0, + ve_enabled: bool = False, + ve_dim: int = 128, + ve_last_n: int = 2, + temperature: float = 1.0, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.temperature = temperature + self.embed_bottleneck = embed_bottleneck + self.num_flat_blocks = num_flat_blocks + self.num_crawler_blocks = num_crawler_blocks + self.crawler_loops = crawler_loops + self._active_crawler_loops = crawler_loops + self._n_enc = num_flat_blocks // 2 + num_loops = num_flat_blocks + num_crawler_blocks * crawler_loops + self.num_loops = num_loops + if embed_bottleneck > 0: + self.tok_emb = nn.Embedding(vocab_size, embed_bottleneck) + self.embed_proj = CastedLinear(embed_bottleneck, model_dim, bias=False) + self.embed_proj_rev = CastedLinear(model_dim, embed_bottleneck, bias=False) + else: + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.embed_proj = None + self.embed_proj_rev = None + self.bigram = BigramHashEmbedding(bigram_buckets, bigram_dim, model_dim) + self.smear = SmearGate(model_dim) if use_smear_gate else None + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve = ValueEmbedding(vocab_size, ve_dim, kv_dim, ve_last_n) if ve_enabled else None + self.ve_last_n = ve_last_n + self.flat_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_flat_blocks) + ]) + self.crawler_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_crawler_blocks) + ]) + self.crawler_residual_scales = nn.ParameterList([ + nn.Parameter(torch.tensor(0.5, dtype=torch.float32)) + for _ in range(crawler_loops) + ]) + self.attn_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.mlp_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.resid_mixes = nn.Parameter( + torch.stack([ + torch.stack((torch.ones(model_dim), torch.zeros(model_dim))) + for _ in range(num_loops) + ]).float() + ) + self.num_encoder_loops = num_loops // 2 + self.num_decoder_loops = num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + self.skip_weights = nn.Parameter(torch.ones(self.num_skips, model_dim, dtype=torch.float32)) + self.xsa_last_n = int(os.environ.get("XSA_LAST_N", 7)) + 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._rebuild_schedule() + self._init_weights() + + def _rebuild_schedule(self, active_loops: int | None = None): + if active_loops is not None: + self._active_crawler_loops = active_loops + schedule = [] + for i in range(self._n_enc): + schedule.append(('flat', i)) + for loop in range(self._active_crawler_loops): + for c in range(self.num_crawler_blocks): + schedule.append(('crawler', c)) + for i in range(self._n_enc, self.num_flat_blocks): + schedule.append(('flat', i)) + self._loop_schedule = schedule + self.num_loops = len(schedule) + self.num_encoder_loops = self.num_loops // 2 + self.num_decoder_loops = self.num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + block_list = [] + for kind, idx in schedule: + block_list.append(self.flat_blocks[idx] if kind == 'flat' else self.crawler_blocks[idx]) + self._block_list = block_list + + def _get_block(self, loop_idx: int) -> 'Block': + return self._block_list[loop_idx] + + 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) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and min(module.weight.shape) >= 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 * self.num_loops)) + + def _embed(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.embed_proj is not None: + x = self.embed_proj(x) + return x + + def _logits(self, x: Tensor) -> Tensor: + if self.embed_proj_rev is not None: + x = self.embed_proj_rev(x) + logits = F.linear(x, self.tok_emb.weight) + elif self.tie_embeddings: + logits = F.linear(x, self.tok_emb.weight) + else: + logits = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits / self.logit_softcap) + + def _run_blocks(self, x, x0, input_ids, lora=None): + active_loops = _ACTIVE_CRAWLER_LOOPS + n_enc = self._n_enc + loop_idx = 0 + xsa_n = self.xsa_last_n + total_depth = self.num_flat_blocks + self.num_crawler_blocks * active_loops + + if xsa_n > 0: + for blk in self.flat_blocks: + blk.attn.use_xsa = (loop_idx >= total_depth - xsa_n) if loop_idx < n_enc or loop_idx >= n_enc + self.num_crawler_blocks * active_loops else False + loop_idx += 1 + for blk in self.crawler_blocks: + for _ in range(active_loops): + blk.attn.use_xsa = True + loop_idx = 0 + + skips: list[Tensor] = [] + for i in range(n_enc): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[i](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + skips.append(x) + loop_idx += 1 + + for lp in range(active_loops): + for ci, cblock in enumerate(self.crawler_blocks): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x_out = cblock(x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + if lp > 0: + alpha = self.crawler_residual_scales[lp].to(dtype=x.dtype) + x = x + alpha * (x_out - x) + else: + x = x_out + loop_idx += 1 + + n_dec_flat = self.num_flat_blocks - n_enc + for i in range(n_dec_flat): + fi = n_enc + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[fi](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + loop_idx += 1 + return x + + def forward(self, input_ids: Tensor, target_ids: Tensor, lora=None) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids, lora) + unused = sum(p.sum() * 0.0 for p in self.crawler_residual_scales) + x = x + unused + x = self.final_norm(x) + logits = self._logits(x) + logits = logits + (lora.lm_head_lora(x) if lora else 0) + if lora: + bsz, sl, V = logits.shape + return F.cross_entropy( + logits.float().reshape(-1, V), target_ids.reshape(-1), reduction="none").reshape(bsz, sl) + return F.cross_entropy(logits.float().reshape(-1, logits.size(-1)), target_ids.reshape(-1), reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids) + x = self.final_norm(x) + return self._logits(x) + +def _compute_chunk_window(ci: int, pred_len: int, num_chunks: int, chunk_size: int, eval_seq_len: int): + chunk_start = ci * chunk_size + chunk_end = pred_len if ci == num_chunks - 1 else (ci + 1) * chunk_size + win_start = max(0, chunk_end - eval_seq_len) + win_len = chunk_end - win_start + chunk_offset = chunk_start - win_start + chunk_len = chunk_end - chunk_start + return win_start, win_len, chunk_offset, chunk_len + +def _accumulate_bpb( + ptl: Tensor, x: Tensor, y: Tensor, + batch_i: int, chunk_offset: int, chunk_len: int, + base_bytes_lut: Tensor, has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + loss_sum: Tensor, byte_sum: Tensor, token_count: Tensor, +): + lbl = ptl[batch_i, chunk_offset:chunk_offset + chunk_len].to(torch.float64) + prev = x[batch_i, chunk_offset:chunk_offset + chunk_len] + tgt = y[batch_i, chunk_offset:chunk_offset + chunk_len] + tok_bytes = base_bytes_lut[tgt].to(torch.float64) + tok_bytes += has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev] + loss_sum += lbl.sum() + byte_sum += tok_bytes.sum() + token_count += chunk_len + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: GPT, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + 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}") + + 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_blocks = min(args.ttt_freeze_blocks, base_model.num_flat_blocks + base_model.num_crawler_blocks) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = False + for bi in range(freeze_blocks): + if f"flat_blocks.{bi}." in name or f"crawler_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)}") + + 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 + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + 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 = [] + 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) + loss_sum += nll[i, s:wlen].to(torch.float64).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() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + 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) + start_tok = chunk_start + (my_seq_s + bs) * seq_len + end_tok = chunk_start + (my_seq_s + 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) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or is_last_chunk): + 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)) + 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 + +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 = "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, timeout=datetime.timedelta(seconds=1800)) + 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) + torch._dynamo.config.optimize_ddp = 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) + + 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}") + + base_model = GPT( + vocab_size=args.vocab_size, + num_flat_blocks=args.num_flat_blocks, + num_crawler_blocks=args.num_crawler_blocks, + crawler_loops=args.crawler_loops, + 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, + temperature=args.temperature, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + use_smear_gate=args.use_smear_gate, + bigram_buckets=args.bigram_buckets, + bigram_dim=args.bigram_dim, + embed_bottleneck=args.embed_bottleneck, + ve_enabled=args.ve_enabled, + ve_dim=args.ve_dim, + ve_last_n=args.ve_last_n, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + if isinstance(module, Rotary): + module.inv_freq.data = module.inv_freq.data.float() + restore_low_dim_params_to_fp32(base_model) + + if args.resume_from and os.path.isfile(args.resume_from): + log0(f"resuming_from:{args.resume_from}") + saved = torch.load(args.resume_from, map_location=device) + base_model.load_state_dict(saved, strict=True) + restore_low_dim_params_to_fp32(base_model) + log0("resume:loaded model weights (optimizer states reset)") + global _QAT_ENABLED, _QAT_BITS, _QAT_MLP_BITS, _ACTIVE_CRAWLER_LOOPS + _QAT_BITS = args.qat_bits + _QAT_MLP_BITS = args.qat_mlp_bits + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + _qat_activated = False + if args.qat_enabled and args.late_qat_threshold >= 1.0: + _QAT_ENABLED = True + _qat_activated = True + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:enabled from step 0 attn={_QAT_BITS}bit{mlp_info}") + elif args.qat_enabled: + _QAT_ENABLED = False + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:late_start threshold={args.late_qat_threshold} attn={_QAT_BITS}bit{mlp_info}") + else: + _QAT_ENABLED = False + _use_compile = bool(int(os.environ.get("TORCH_COMPILE", "1"))) + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) if _use_compile else base_model + _use_ddp = distributed and world_size > 1 + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + + block_named_params = list(base_model.flat_blocks.named_parameters()) + list(base_model.crawler_blocks.named_parameters()) + matrix_params = [ + p + for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p + for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params.append(base_model.attn_scales) + scalar_params.append(base_model.mlp_scales) + scalar_params.append(base_model.resid_mixes) + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + if base_model.smear is not None: + scalar_params.append(base_model.smear.gate) + bigram_named = list(base_model.bigram.named_parameters()) + for name, p in bigram_named: + if p.ndim == 2 and "proj" in name: + matrix_params.append(p) + elif p.ndim == 2: + pass + else: + scalar_params.append(p) + ve_table_params = [] + if base_model.ve is not None: + for name, p in base_model.ve.named_parameters(): + if "table" in name: + ve_table_params.append(p) + elif p.ndim == 2: + matrix_params.append(p) + else: + scalar_params.append(p) + 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, base_model.bigram.table.weight] + + ([base_model.embed_proj.weight, base_model.embed_proj_rev.weight] if base_model.embed_proj is not None else []) + + ve_table_params, + "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.weight_decay, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + flat_params = sum(p.numel() for p in base_model.flat_blocks.parameters()) + crawler_params = sum(p.numel() for p in base_model.crawler_blocks.parameters()) + loop_params = base_model.attn_scales.numel() + base_model.mlp_scales.numel() + base_model.resid_mixes.numel() + log0(f"architecture:crawler flat_blocks:{args.num_flat_blocks} crawler_blocks:{args.num_crawler_blocks} crawler_loops:{args.crawler_loops} effective_depth:{base_model.num_loops} flat_params:{flat_params} crawler_params:{crawler_params} per_loop_params:{loop_params}") + log0(f"model_params:{n_params}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + 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_frac > 0 and max_wallclock_ms is not None: + warmdown_ms = args.warmdown_frac * max_wallclock_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.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 + + progressive_steps: list[tuple[int, int]] = [] + if args.progressive_schedule: + for entry in args.progressive_schedule.split(","): + s, loops = entry.strip().split(":") + progressive_steps.append((int(s), int(loops))) + progressive_steps.sort() + + 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] + prog_variants = sorted(set([1] + [loops for _, loops in progressive_steps])) if progressive_steps else [base_model._active_crawler_loops] + steps_per_variant = max(1, args.warmup_steps // (len(prog_variants) * 2)) + model.train() + warmup_step = 0 + for variant_loops in prog_variants: + if variant_loops != base_model._active_crawler_loops: + base_model._rebuild_schedule(active_loops=variant_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"warmup:precompile variant={variant_loops} loops, depth={base_model.num_loops}") + for _ in range(steps_per_variant): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{args.warmup_steps}") + remaining = args.warmup_steps - warmup_step + if remaining > 0: + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + for _ in range(remaining): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{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() + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + if _use_ddp: + model.require_backward_grad_sync = True + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + if progressive_steps: + _ACTIVE_CRAWLER_LOOPS = 1 + log0(f"progressive:enabled schedule={progressive_steps} starting with 1 crawler loop") + else: + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + _current_crawler_loops = _ACTIVE_CRAWLER_LOOPS + + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_checkpoints: list[dict[str, Tensor]] = [] + ema_sd: dict[str, Tensor] | None = None + if args.ema_decay > 0: + ema_sd = {k: v.detach().float().clone() for k, v in base_model.state_dict().items()} + log0(f"ema:enabled decay={args.ema_decay}") + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_activated and scale <= args.late_qat_threshold: + _QAT_ENABLED = True + _qat_activated = True + log0(f"late_qat:activated at step {step} scale={scale:.4f} threshold={args.late_qat_threshold}") + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + if args.swa_start_frac > 0 and step % args.swa_every == 0: + should_collect = torch.tensor(int(scale < args.swa_start_frac), device=device) + if distributed: + dist.all_reduce(should_collect, op=dist.ReduceOp.MIN) + if should_collect.item(): + swa_checkpoints.append({k: v.detach().cpu().clone() for k, v in base_model.state_dict().items()}) + + if ema_sd is not None: + d = args.ema_decay + with torch.no_grad(): + for k, v in base_model.state_dict().items(): + ema_sd[k].mul_(d).add_(v.detach().float(), alpha=1.0 - d) + + step += 1 + for prog_step, prog_loops in progressive_steps: + if step == prog_step and prog_loops != _current_crawler_loops: + _ACTIVE_CRAWLER_LOOPS = prog_loops + _current_crawler_loops = prog_loops + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"progressive:step {step} -> {prog_loops} crawler loops, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * prog_loops} (recompiled)") + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + _QAT_ENABLED = False + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + log0(f"eval:restored full crawler loops={args.crawler_loops}, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * args.crawler_loops}") + + if swa_checkpoints: + log0(f"swa:averaging {len(swa_checkpoints)} checkpoints") + avg_sd = {} + for key in swa_checkpoints[0]: + stacked = torch.stack([ckpt[key].float() for ckpt in swa_checkpoints]) + avg_sd[key] = stacked.mean(dim=0).to(dtype=swa_checkpoints[0][key].dtype) + base_model.load_state_dict(avg_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + swa_val_loss, swa_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"swa_eval val_loss:{swa_val_loss:.4f} val_bpb:{swa_val_bpb:.4f}") + del swa_checkpoints + + if ema_sd is not None: + log0("ema:loading averaged weights") + model_sd = base_model.state_dict() + for k in ema_sd: + ema_sd[k] = ema_sd[k].to(dtype=model_sd[k].dtype, device=model_sd[k].device) + base_model.load_state_dict(ema_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + ema_val_loss, ema_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"ema_eval val_loss:{ema_val_loss:.4f} val_bpb:{ema_val_bpb:.4f}") + del ema_sd + + if master_process: + torch.save(base_model.state_dict(), "final_model.pt") + import shutil + shutil.copy2("final_model.pt", f"final_model_{args.run_id}.pt") + log0(f"saved backup: final_model_{args.run_id}.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + quant_obj, quant_stats = quantize_state_dict_int8( + base_model.state_dict(), + qat_bits=args.qat_bits if args.qat_enabled else 8, + qat_mlp_bits=args.qat_mlp_bits if args.qat_enabled else 0, + ) + quant_buf = io.BytesIO() + torch.save(quant_obj, quant_buf) + quant_raw = quant_buf.getvalue() + try: + import zstandard as zstd + quant_blob = zstd.ZstdCompressor(level=22).compress(quant_raw) + compress_method = "zstd-22" + except ImportError: + quant_blob = zlib.compress(quant_raw, level=9) + compress_method = "zlib-9" + quant_raw_bytes = len(quant_raw) + if master_process: + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int8_payload_bytes"], 1) + log0( + f"Serialized model int8+{compress_method}: {quant_file_bytes} bytes " + f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" + ) + log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + try: + import zstandard as zstd + decompressed = zstd.ZstdDecompressor().decompress(quant_blob_disk) + except Exception: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + torch.cuda.synchronize() + t_qeval = time.perf_counter() + q_val_loss, q_val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + if master_process: + log0("gptq:loading calibration data from training shards...") + base_model.load_state_dict(torch.load("final_model.pt", map_location=device), strict=True) + restore_low_dim_params_to_fp32(base_model) + t_gptq = time.perf_counter() + ar_tokens = generate_calib_from_data( + args.train_files, device, num_seqs=64, seq_len=args.train_seq_len, seed=args.seed, + ) + log0(f"gptq:loaded {len(ar_tokens)} calibration sequences in {time.perf_counter()-t_gptq:.1f}s") + log0("gptq:collecting hessians...") + hessians = collect_hessians_from_tokens(base_model, ar_tokens, device) + log0(f"gptq:collected hessians for {len(hessians)} layers") + del ar_tokens + torch.cuda.empty_cache() + log0("gptq:quantizing int6 with full Hessian GPTQ...") + gptq_result, gptq_meta = mixed_quantize_int6_gptq( + base_model.state_dict(), hessians=hessians, + ) + del hessians + target_bytes = 15_900_000 + code_bytes = len(code.encode("utf-8")) + ones_info = [] + for name, info in gptq_meta.items(): + if not (isinstance(info, dict) and info.get("type") == "int6"): + continue + qk, sk = name + ".q", name + ".scale" + if qk not in gptq_result or sk not in gptq_result: + continue + q, s = gptq_result[qk], gptq_result[sk] + if s.ndim > 0: + ones_mask = (q.abs() == 1) + if ones_mask.any(): + row_idx = torch.arange(q.shape[0]).unsqueeze(1).expand_as(q)[ones_mask] + flat_idx = torch.arange(q.numel()).reshape(q.shape)[ones_mask] + errors = s.float()[row_idx].pow(2) + for fi, err in zip(flat_idx.tolist(), errors.tolist()): + ones_info.append((qk, fi, err)) + ones_info.sort(key=lambda x: x[2]) + def _try_prune(n): + tmp = {k: v.clone() for k, v in gptq_result.items()} + for i in range(min(n, len(ones_info))): + tmp[ones_info[i][0]].view(-1)[ones_info[i][1]] = 0 + buf = io.BytesIO() + torch.save({"w": tmp, "m": gptq_meta}, buf) + return len(brotli.compress(buf.getvalue(), quality=11)) + code_bytes, tmp + no_prune_sz, _ = _try_prune(0) + log0(f"selective_prune: {len(ones_info)} candidates, unpruned={no_prune_sz/1e6:.2f}MB target={target_bytes/1e6:.1f}MB") + if no_prune_sz <= target_bytes: + log0("selective_prune: already fits, no pruning needed") + final_result = gptq_result + else: + full_sz, _ = _try_prune(len(ones_info)) + log0(f"selective_prune: full prune={full_sz/1e6:.2f}MB") + if full_sz > target_bytes: + log0("selective_prune: even full prune not enough, applying all") + _, final_result = _try_prune(len(ones_info)) + else: + lo, hi = 0, len(ones_info) + while lo < hi: + mid = (lo + hi) // 2 + sz, _ = _try_prune(mid) + if sz <= target_bytes: + hi = mid + else: + lo = mid + 1 + log0(f"selective_prune: pruning {lo}/{len(ones_info)} values ({100*lo/len(ones_info):.1f}%) to fit") + _, final_result = _try_prune(lo) + gptq_buf = io.BytesIO() + torch.save({"w": final_result, "m": gptq_meta}, gptq_buf) + gptq_raw = gptq_buf.getvalue() + gptq_blob = brotli.compress(gptq_raw, quality=11) + gptq_bytes = len(gptq_blob) + total_bytes = gptq_bytes + code_bytes + log0(f"gptq_int6_brotli: {gptq_bytes:,} bytes | code: {code_bytes:,} | total: {total_bytes:,} ({total_bytes/1e6:.2f}MB)") + with open("final_model.int6_gptq.ptz", "wb") as f: + f.write(gptq_blob) + gptq_state = torch.load( + io.BytesIO(brotli.decompress(gptq_blob)), map_location="cpu", weights_only=False + ) + restored = dequantize_mixed_int6(gptq_state["w"], gptq_state["m"], base_model.state_dict()) + base_model.load_state_dict(restored, strict=True) + restore_low_dim_params_to_fp32(base_model) + gq_val_loss, gq_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"gptq_int6_brotli_roundtrip val_loss:{gq_val_loss:.4f} val_bpb:{gq_val_bpb:.4f} time:{time.perf_counter()-t_gptq:.1f}s") + + if args.ttt_enabled: + torch._dynamo.reset() + # TTT runs on the GPTQ artifact (already loaded at line 1980-1982) + torch.cuda.synchronize() + t_ttt_sw = time.perf_counter() + all_val_tokens = torch.cat([load_data_shard(Path(p)) for p in sorted(glob.glob(args.val_files))]).contiguous() + ttt_sw_loss, ttt_sw_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + all_val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.sliding_window_stride if args.sliding_window_stride > 0 else 64, + log0=log0, + ) + torch.cuda.synchronize() + log0( + f"final_ttt_sliding val_loss:{ttt_sw_loss:.4f} val_bpb:{ttt_sw_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt_sw):.0f}ms" + ) + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main() + + +==================================================================================================== +Running Python 3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0] +Running PyTorch 2.6.0+cu124 +Sun Apr 12 14:00:01 2026 ++-----------------------------------------------------------------------------------------+ +| NVIDIA-SMI 580.126.09 Driver Version: 580.126.09 CUDA Version: 13.0 | ++-----------------------------------------+------------------------+----------------------+ +| 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 RTX 6000 Ada Gene... Off | 00000000:01:00.0 On | Off | +| 67% 80C P0 113W / 300W | 1555MiB / 49140MiB | 1% Default | +| | | N/A | ++-----------------------------------------+------------------------+----------------------+ + ++-----------------------------------------------------------------------------------------+ +| Processes: | +| GPU GI CI PID Type Process name GPU Memory | +| ID ID Usage | +|=========================================================================================| +| 0 N/A N/A 2640 G /usr/lib/xorg/Xorg 330MiB | +| 0 N/A N/A 2821 G /usr/bin/gnome-shell 255MiB | +| 0 N/A N/A 3400 G ...exec/xdg-desktop-portal-gnome 31MiB | +| 0 N/A N/A 444032 G /usr/bin/nautilus 94MiB | +| 0 N/A N/A 767208 G .../8054/usr/lib/firefox/firefox 654MiB | +| 0 N/A N/A 3548448 G /proc/self/exe 62MiB | ++-----------------------------------------------------------------------------------------+ + +==================================================================================================== +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_8192_bpe.model +train_loader:dataset:fineweb10B_sp8192 train_shards:128 +val_loader:shards pattern=./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin tokens:40546304 +qat:enabled from step 0 attn=6bit +architecture:crawler flat_blocks:3 crawler_blocks:2 crawler_loops:2 effective_depth:7 flat_params:17876016 crawler_params:11917344 per_loop_params:20608 +model_params:38346836 +world_size:1 grad_accum_steps:8 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:16 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:18000.000 +seed:2024 +warmup_step:1/100 +warmup_step:2/100 +warmup_step:3/100 +warmup_step:4/100 +warmup_step:5/100 +warmup_step:6/100 +warmup_step:7/100 +warmup_step:8/100 +warmup_step:9/100 +warmup_step:10/100 +warmup_step:11/100 +warmup_step:12/100 +warmup_step:13/100 +warmup_step:14/100 +warmup_step:15/100 +warmup_step:16/100 +warmup_step:17/100 +warmup_step:18/100 +warmup_step:19/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:8.9979 val_bpb:3.4840 train_time:0ms step_avg:0.01ms +step:1/20000 train_loss:8.9985 train_time:9154ms step_avg:9153.77ms +step:2/20000 train_loss:8.8442 train_time:12042ms step_avg:6021.11ms +step:3/20000 train_loss:9.5443 train_time:14982ms step_avg:4993.95ms +step:4/20000 train_loss:9.3783 train_time:17928ms step_avg:4482.11ms +step:5/20000 train_loss:9.0613 train_time:20887ms step_avg:4177.39ms +step:6/20000 train_loss:8.6121 train_time:23859ms step_avg:3976.55ms +step:7/20000 train_loss:8.1236 train_time:26838ms step_avg:3833.97ms +step:8/20000 train_loss:7.7478 train_time:29814ms step_avg:3726.72ms +step:9/20000 train_loss:7.3007 train_time:32801ms step_avg:3644.52ms +step:10/20000 train_loss:7.0257 train_time:35788ms step_avg:3578.84ms +step:100/20000 train_loss:4.5913 train_time:308505ms step_avg:3085.05ms +step:200/20000 train_loss:3.9909 train_time:610988ms step_avg:3054.94ms +step:300/20000 train_loss:3.6547 train_time:912024ms step_avg:3040.08ms +step:400/20000 train_loss:3.6317 train_time:1212321ms step_avg:3030.80ms +step:500/20000 train_loss:3.4434 train_time:1511796ms step_avg:3023.59ms +step:500/20000 val_loss:3.5154 val_bpb:1.3612 train_time:1511807ms step_avg:3023.61ms +step:600/20000 train_loss:3.4873 train_time:1810740ms step_avg:3017.90ms +step:700/20000 train_loss:3.3120 train_time:2109767ms step_avg:3013.95ms +step:800/20000 train_loss:3.3792 train_time:2409950ms step_avg:3012.44ms +step:900/20000 train_loss:3.3532 train_time:2708987ms step_avg:3009.99ms +step:1000/20000 train_loss:3.1959 train_time:3007827ms step_avg:3007.83ms +step:1000/20000 val_loss:3.2950 val_bpb:1.2758 train_time:3007837ms step_avg:3007.84ms +step:1100/20000 train_loss:3.3101 train_time:3306387ms step_avg:3005.81ms +step:1200/20000 train_loss:3.3326 train_time:3605722ms step_avg:3004.77ms +step:1300/20000 train_loss:3.2536 train_time:3904658ms step_avg:3003.58ms +step:1400/20000 train_loss:3.1792 train_time:4203358ms step_avg:3002.40ms +step:1500/20000 train_loss:3.1747 train_time:4501748ms step_avg:3001.17ms +step:1500/20000 val_loss:3.2322 val_bpb:1.2515 train_time:4501759ms step_avg:3001.17ms +step:1600/20000 train_loss:3.2703 train_time:4800387ms step_avg:3000.24ms +step:1700/20000 train_loss:3.2802 train_time:5099140ms step_avg:2999.49ms +step:1800/20000 train_loss:3.2649 train_time:5398037ms step_avg:2998.91ms +step:1900/20000 train_loss:3.2537 train_time:5696910ms step_avg:2998.37ms +step:2000/20000 train_loss:3.2246 train_time:5995628ms step_avg:2997.81ms +step:2000/20000 val_loss:3.2020 val_bpb:1.2398 train_time:5995639ms step_avg:2997.82ms +step:2100/20000 train_loss:3.2014 train_time:6295882ms step_avg:2998.04ms +step:2200/20000 train_loss:3.2036 train_time:6598084ms step_avg:2999.13ms +step:2300/20000 train_loss:3.2649 train_time:6900274ms step_avg:3000.12ms +step:2400/20000 train_loss:3.2296 train_time:7202436ms step_avg:3001.01ms +step:2500/20000 train_loss:3.1817 train_time:7504995ms step_avg:3002.00ms +step:2500/20000 val_loss:3.1792 val_bpb:1.2310 train_time:7505006ms step_avg:3002.00ms +step:2600/20000 train_loss:3.1787 train_time:7807654ms step_avg:3002.94ms +step:2700/20000 train_loss:3.1308 train_time:8109422ms step_avg:3003.49ms +step:2800/20000 train_loss:3.1756 train_time:8411635ms step_avg:3004.16ms +step:2900/20000 train_loss:3.2080 train_time:8713913ms step_avg:3004.80ms +step:3000/20000 train_loss:3.0750 train_time:9023452ms step_avg:3007.82ms +step:3000/20000 val_loss:3.1454 val_bpb:1.2179 train_time:9023462ms step_avg:3007.82ms +step:3100/20000 train_loss:3.0976 train_time:9330588ms step_avg:3009.87ms +step:3200/20000 train_loss:3.1408 train_time:9637979ms step_avg:3011.87ms +step:3300/20000 train_loss:3.1849 train_time:9943226ms step_avg:3013.10ms +step:3400/20000 train_loss:3.1284 train_time:10244256ms step_avg:3013.02ms +step:3500/20000 train_loss:3.1003 train_time:10546594ms step_avg:3013.31ms +step:3500/20000 val_loss:3.1149 val_bpb:1.2061 train_time:10546604ms step_avg:3013.32ms +step:3600/20000 train_loss:3.1072 train_time:10847569ms step_avg:3013.21ms +step:3700/20000 train_loss:3.0846 train_time:11149057ms step_avg:3013.26ms +step:3800/20000 train_loss:3.1645 train_time:11450073ms step_avg:3013.18ms +step:3900/20000 train_loss:3.0697 train_time:11750799ms step_avg:3013.03ms +step:4000/20000 train_loss:3.1413 train_time:12051422ms step_avg:3012.86ms +step:4000/20000 val_loss:3.0763 val_bpb:1.1912 train_time:12051433ms step_avg:3012.86ms +step:4100/20000 train_loss:3.2114 train_time:12352011ms step_avg:3012.69ms +step:4200/20000 train_loss:3.1149 train_time:12652918ms step_avg:3012.60ms +step:4300/20000 train_loss:3.0717 train_time:12953568ms step_avg:3012.46ms +step:4400/20000 train_loss:3.0558 train_time:13254465ms step_avg:3012.38ms +step:4500/20000 train_loss:2.9917 train_time:13554738ms step_avg:3012.16ms +step:4500/20000 val_loss:3.0429 val_bpb:1.1782 train_time:13554749ms step_avg:3012.17ms +step:4600/20000 train_loss:2.9929 train_time:13855555ms step_avg:3012.08ms +step:4700/20000 train_loss:2.9993 train_time:14156653ms step_avg:3012.05ms +step:4800/20000 train_loss:3.0195 train_time:14457770ms step_avg:3012.04ms +step:4900/20000 train_loss:3.0339 train_time:14758836ms step_avg:3012.01ms +step:5000/20000 train_loss:2.9252 train_time:15059542ms step_avg:3011.91ms +step:5000/20000 val_loss:2.9982 val_bpb:1.1609 train_time:15059554ms step_avg:3011.91ms +step:5100/20000 train_loss:2.9508 train_time:15360092ms step_avg:3011.78ms +step:5200/20000 train_loss:2.9765 train_time:15660946ms step_avg:3011.72ms +step:5300/20000 train_loss:3.0363 train_time:15961815ms step_avg:3011.66ms +step:5400/20000 train_loss:2.9683 train_time:16263499ms step_avg:3011.76ms +step:5500/20000 train_loss:2.9221 train_time:16562189ms step_avg:3011.31ms +step:5500/20000 val_loss:2.9440 val_bpb:1.1399 train_time:16562200ms step_avg:3011.31ms +step:5600/20000 train_loss:2.9594 train_time:16863002ms step_avg:3011.25ms +step:5700/20000 train_loss:2.9820 train_time:17164375ms step_avg:3011.29ms +step:5800/20000 train_loss:2.9548 train_time:17466353ms step_avg:3011.44ms +step:5900/20000 train_loss:2.8919 train_time:17768518ms step_avg:3011.61ms +step:5977/20000 val_loss:2.9011 val_bpb:1.1233 train_time:18001266ms step_avg:3011.76ms +stopping_early: wallclock_cap train_time:18001266ms step:5977/20000 +peak memory allocated: 16543 MiB reserved: 17772 MiB +eval:restored full crawler loops=2, depth=7 +swa:averaging 14 checkpoints +swa_eval val_loss:2.8983 val_bpb:1.1222 +saved backup: final_model_v5_d736_honest_seed2024.pt +Serialized model: 136629271 bytes +Code size: 90756 bytes +Total submission size: 136720027 bytes +Serialized model int8+zstd-22: 16739898 bytes (payload:38578440 raw_torch:38603741 payload_ratio:3.54x) +Total submission size int8+zlib: 16830654 bytes +final_int8_zlib_roundtrip val_loss:3.0091 val_bpb:1.1651 eval_time:68980ms +final_int8_zlib_roundtrip_exact val_loss:3.00910640 val_bpb:1.16512308 +gptq:loading calibration data from training shards... +gptq:loaded 64 calibration sequences in 4.7s +gptq:collecting hessians... +gptq:collected hessians for 32 layers +gptq:quantizing int6 with full Hessian GPTQ... +selective_prune: 12704738 candidates, unpruned=15.08MB target=15.9MB +selective_prune: already fits, no pruning needed +gptq_int6_brotli: 14,984,356 bytes | code: 90,756 | total: 15,075,112 (15.08MB) +gptq_int6_brotli_roundtrip val_loss:3.0335 val_bpb:1.1746 time:245.2s +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633560 stride=64 +ttt_sliding:params unfrozen=26429492 frozen=11917344 + ttt_chunk [1/1238] bpb=1.236547 time=4.4s + ttt_chunk [11/1238] bpb=1.156854 time=51.7s + ttt_chunk [21/1238] bpb=1.158441 time=98.9s + ttt_chunk [31/1238] bpb=1.152176 time=146.0s + ttt_chunk [41/1238] bpb=1.158188 time=193.3s + ttt_chunk [51/1238] bpb=1.153843 time=240.9s + ttt_chunk [61/1238] bpb=1.149850 time=288.4s + ttt_chunk [71/1238] bpb=1.151636 time=335.6s + ttt_chunk [81/1238] bpb=1.147172 time=383.2s + ttt_chunk [91/1238] bpb=1.144845 time=432.8s + ttt_chunk [101/1238] bpb=1.144776 time=482.3s + ttt_chunk [111/1238] bpb=1.146817 time=533.1s + ttt_chunk [121/1238] bpb=1.147500 time=583.6s + ttt_chunk [131/1238] bpb=1.149573 time=633.0s + ttt_chunk [141/1238] bpb=1.148279 time=681.4s + ttt_chunk [151/1238] bpb=1.148338 time=730.4s + ttt_chunk [161/1238] bpb=1.147643 time=779.8s + ttt_chunk [171/1238] bpb=1.147288 time=828.2s + ttt_chunk [181/1238] bpb=1.146785 time=876.9s + ttt_chunk [191/1238] bpb=1.147097 time=926.1s + ttt_chunk [201/1238] bpb=1.147536 time=974.8s + ttt_chunk [211/1238] bpb=1.148242 time=1023.2s + ttt_chunk [221/1238] bpb=1.147240 time=1072.1s + ttt_chunk [231/1238] bpb=1.147805 time=1120.5s + ttt_chunk [241/1238] bpb=1.148025 time=1170.3s + ttt_chunk [251/1238] bpb=1.148119 time=1220.6s + ttt_chunk [261/1238] bpb=1.148321 time=1271.0s + ttt_chunk [271/1238] bpb=1.146951 time=1321.6s + ttt_chunk [281/1238] bpb=1.147596 time=1370.8s + ttt_chunk [291/1238] bpb=1.146565 time=1421.2s + ttt_chunk [301/1238] bpb=1.146495 time=1470.3s + ttt_chunk [311/1238] bpb=1.146206 time=1519.4s + ttt_chunk [321/1238] bpb=1.146118 time=1565.2s + ttt_chunk [331/1238] bpb=1.145627 time=1612.1s + ttt_chunk [341/1238] bpb=1.144829 time=1659.3s + ttt_chunk [351/1238] bpb=1.145217 time=1707.8s + ttt_chunk [361/1238] bpb=1.144928 time=1758.3s + ttt_chunk [371/1238] bpb=1.144474 time=1809.2s + ttt_chunk [381/1238] bpb=1.143944 time=1860.9s + ttt_chunk [391/1238] bpb=1.143432 time=1910.3s + ttt_chunk [401/1238] bpb=1.142925 time=1959.0s + ttt_chunk [411/1238] bpb=1.142513 time=2006.5s + ttt_chunk [421/1238] bpb=1.142094 time=2052.7s + ttt_chunk [431/1238] bpb=1.141122 time=2099.5s + ttt_chunk [441/1238] bpb=1.140331 time=2149.0s + ttt_chunk [451/1238] bpb=1.140319 time=2198.7s + ttt_chunk [461/1238] bpb=1.139144 time=2247.6s + ttt_chunk [471/1238] bpb=1.139022 time=2295.6s + ttt_chunk [481/1238] bpb=1.139269 time=2343.7s + ttt_chunk [491/1238] bpb=1.138840 time=2391.8s + ttt_chunk [501/1238] bpb=1.138800 time=2442.9s + ttt_chunk [511/1238] bpb=1.138831 time=2492.8s + ttt_chunk [521/1238] bpb=1.138469 time=2541.6s + ttt_chunk [531/1238] bpb=1.138478 time=2590.6s + ttt_chunk [541/1238] bpb=1.138338 time=2639.6s + ttt_chunk [551/1238] bpb=1.137816 time=2688.2s + ttt_chunk [561/1238] bpb=1.137739 time=2736.0s + ttt_chunk [571/1238] bpb=1.138005 time=2785.1s + ttt_chunk [581/1238] bpb=1.137721 time=2831.2s + ttt_chunk [591/1238] bpb=1.137306 time=2876.3s + ttt_chunk [601/1238] bpb=1.137235 time=2920.8s + ttt_chunk [611/1238] bpb=1.137146 time=2965.2s + ttt_chunk [621/1238] bpb=1.137724 time=3009.9s + ttt_chunk [631/1238] bpb=1.137995 time=3054.3s + ttt_chunk [641/1238] bpb=1.138389 time=3098.8s + ttt_chunk [651/1238] bpb=1.138391 time=3143.1s + ttt_chunk [661/1238] bpb=1.138756 time=3187.5s + ttt_chunk [671/1238] bpb=1.139146 time=3231.9s + ttt_chunk [681/1238] bpb=1.139803 time=3276.3s + ttt_chunk [691/1238] bpb=1.139855 time=3320.7s + ttt_chunk [701/1238] bpb=1.139933 time=3365.1s + ttt_chunk [711/1238] bpb=1.140198 time=3409.5s + ttt_chunk [721/1238] bpb=1.140354 time=3453.9s + ttt_chunk [731/1238] bpb=1.140005 time=3498.4s + ttt_chunk [741/1238] bpb=1.139663 time=3542.8s + ttt_chunk [751/1238] bpb=1.139394 time=3587.2s + ttt_chunk [761/1238] bpb=1.139239 time=3631.6s + ttt_chunk [771/1238] bpb=1.138722 time=3676.0s + ttt_chunk [781/1238] bpb=1.139084 time=3720.6s + ttt_chunk [791/1238] bpb=1.138613 time=3765.7s + ttt_chunk [801/1238] bpb=1.138918 time=3811.5s + ttt_chunk [811/1238] bpb=1.138512 time=3856.2s + ttt_chunk [821/1238] bpb=1.137832 time=3901.1s + ttt_chunk [831/1238] bpb=1.137441 time=3946.5s + ttt_chunk [841/1238] bpb=1.137055 time=3991.6s + ttt_chunk [851/1238] bpb=1.136724 time=4036.0s + ttt_chunk [861/1238] bpb=1.136350 time=4080.6s + ttt_chunk [871/1238] bpb=1.135907 time=4125.1s + ttt_chunk [881/1238] bpb=1.135633 time=4169.5s + ttt_chunk [891/1238] bpb=1.135749 time=4213.9s + ttt_chunk [901/1238] bpb=1.136089 time=4258.4s + ttt_chunk [911/1238] bpb=1.135953 time=4302.8s + ttt_chunk [921/1238] bpb=1.136035 time=4347.3s + ttt_chunk [931/1238] bpb=1.135995 time=4391.7s + ttt_chunk [941/1238] bpb=1.136379 time=4436.3s + ttt_chunk [951/1238] bpb=1.136246 time=4480.7s + ttt_chunk [961/1238] bpb=1.136755 time=4525.1s + ttt_chunk [971/1238] bpb=1.136897 time=4569.5s + ttt_chunk [981/1238] bpb=1.136933 time=4613.9s + ttt_chunk [991/1238] bpb=1.136876 time=4658.3s + ttt_chunk [1001/1238] bpb=1.137191 time=4702.8s + ttt_chunk [1011/1238] bpb=1.137346 time=4747.4s + ttt_chunk [1021/1238] bpb=1.137573 time=4792.3s + ttt_chunk [1031/1238] bpb=1.137761 time=4837.0s + ttt_chunk [1041/1238] bpb=1.137881 time=4881.6s + ttt_chunk [1051/1238] bpb=1.138111 time=4926.5s + ttt_chunk [1061/1238] bpb=1.138082 time=4971.1s + ttt_chunk [1071/1238] bpb=1.138124 time=5015.6s + ttt_chunk [1081/1238] bpb=1.138190 time=5060.7s + ttt_chunk [1091/1238] bpb=1.138383 time=5105.2s + ttt_chunk [1101/1238] bpb=1.138557 time=5150.3s + ttt_chunk [1111/1238] bpb=1.138604 time=5194.7s + ttt_chunk [1121/1238] bpb=1.138535 time=5239.5s + ttt_chunk [1131/1238] bpb=1.138625 time=5284.1s + ttt_chunk [1141/1238] bpb=1.138310 time=5328.9s + ttt_chunk [1151/1238] bpb=1.138253 time=5373.4s + ttt_chunk [1161/1238] bpb=1.138129 time=5422.7s + ttt_chunk [1171/1238] bpb=1.137736 time=5473.6s + ttt_chunk [1181/1238] bpb=1.137595 time=5524.8s + ttt_chunk [1191/1238] bpb=1.137587 time=5576.0s + ttt_chunk [1201/1238] bpb=1.137536 time=5626.8s + ttt_chunk [1211/1238] bpb=1.137208 time=5677.3s + ttt_chunk [1221/1238] bpb=1.137136 time=5728.0s + ttt_chunk [1231/1238] bpb=1.136839 time=5779.3s + ttt_chunk [1238/1238] bpb=1.136837 time=5811.7s +ttt_sliding:done val_loss=2.936090 val_bpb=1.136837 elapsed=5811.9s +final_ttt_sliding val_loss:2.9361 val_bpb:1.1368 eval_time:5812107ms diff --git a/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_seed42.log b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_seed42.log new file mode 100644 index 0000000000..eea0e6565b --- /dev/null +++ b/records/track_10min_16mb/2026-04-11_CrawlerTransformer_3f2cx2_SP8192_SDClip_TTT/train_seed42.log @@ -0,0 +1,2248 @@ +logs/v5_d736_honest_seed42.txt +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_8192_bpe.model +train_loader:dataset:fineweb10B_sp8192 train_shards:128 +val_loader:shards pattern=./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin tokens:40546304 +qat:enabled from step 0 attn=6bit +architecture:crawler flat_blocks:3 crawler_blocks:2 crawler_loops:2 effective_depth:7 flat_params:17876016 crawler_params:11917344 per_loop_params:20608 +model_params:38346836 +world_size:1 grad_accum_steps:8 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:16 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:18000.000 +seed:42 +warmup_step:1/100 +warmup_step:2/100 +warmup_step:3/100 +warmup_step:4/100 +warmup_step:5/100 +warmup_step:6/100 +warmup_step:7/100 +warmup_step:8/100 +warmup_step:9/100 +warmup_step:10/100 +warmup_step:11/100 +warmup_step:12/100 +warmup_step:13/100 +warmup_step:14/100 +warmup_step:15/100 +warmup_step:16/100 +warmup_step:17/100 +warmup_step:18/100 +warmup_step:19/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:8.9975 val_bpb:3.4838 train_time:0ms step_avg:0.01ms +step:1/20000 train_loss:8.9981 train_time:9106ms step_avg:9106.36ms +step:2/20000 train_loss:8.8448 train_time:12002ms step_avg:6000.80ms +step:3/20000 train_loss:9.5108 train_time:14946ms step_avg:4982.01ms +step:4/20000 train_loss:9.3126 train_time:17892ms step_avg:4472.94ms +step:5/20000 train_loss:8.9713 train_time:20844ms step_avg:4168.84ms +step:6/20000 train_loss:8.4572 train_time:23799ms step_avg:3966.51ms +step:7/20000 train_loss:8.0264 train_time:26767ms step_avg:3823.85ms +step:8/20000 train_loss:7.6690 train_time:29738ms step_avg:3717.21ms +step:9/20000 train_loss:7.2852 train_time:32716ms step_avg:3635.11ms +step:10/20000 train_loss:6.9981 train_time:35705ms step_avg:3570.45ms +step:100/20000 train_loss:4.6127 train_time:307805ms step_avg:3078.05ms +step:200/20000 train_loss:3.9858 train_time:608213ms step_avg:3041.06ms +step:300/20000 train_loss:3.6700 train_time:908008ms step_avg:3026.69ms +step:400/20000 train_loss:3.6354 train_time:1207238ms step_avg:3018.09ms +step:500/20000 train_loss:3.4467 train_time:1506294ms step_avg:3012.59ms +step:500/20000 val_loss:3.5181 val_bpb:1.3622 train_time:1506305ms step_avg:3012.61ms +step:600/20000 train_loss:3.4952 train_time:1805073ms step_avg:3008.46ms +step:700/20000 train_loss:3.3177 train_time:2104278ms step_avg:3006.11ms +step:800/20000 train_loss:3.3843 train_time:2403910ms step_avg:3004.89ms +step:900/20000 train_loss:3.3627 train_time:2703416ms step_avg:3003.80ms +step:1000/20000 train_loss:3.2050 train_time:3002709ms step_avg:3002.71ms +step:1000/20000 val_loss:3.3001 val_bpb:1.2778 train_time:3002719ms step_avg:3002.72ms +step:1100/20000 train_loss:3.3120 train_time:3300823ms step_avg:3000.75ms +step:1200/20000 train_loss:3.3373 train_time:3598552ms step_avg:2998.79ms +step:1300/20000 train_loss:3.2603 train_time:3896625ms step_avg:2997.40ms +step:1400/20000 train_loss:3.1850 train_time:4195245ms step_avg:2996.60ms +step:1500/20000 train_loss:3.1807 train_time:4494135ms step_avg:2996.09ms +step:1500/20000 val_loss:3.2335 val_bpb:1.2520 train_time:4494147ms step_avg:2996.10ms +step:1600/20000 train_loss:3.2755 train_time:4792192ms step_avg:2995.12ms +step:1700/20000 train_loss:3.2789 train_time:5090282ms step_avg:2994.28ms +step:1800/20000 train_loss:3.2658 train_time:5388457ms step_avg:2993.59ms +step:1900/20000 train_loss:3.2539 train_time:5686612ms step_avg:2992.95ms +step:2000/20000 train_loss:3.2267 train_time:5984300ms step_avg:2992.15ms +step:2000/20000 val_loss:3.2054 val_bpb:1.2411 train_time:5984310ms step_avg:2992.15ms +step:2100/20000 train_loss:3.2010 train_time:6282080ms step_avg:2991.47ms +step:2200/20000 train_loss:3.2040 train_time:6580281ms step_avg:2991.04ms +step:2300/20000 train_loss:3.2689 train_time:6878595ms step_avg:2990.69ms +step:2400/20000 train_loss:3.2325 train_time:7176607ms step_avg:2990.25ms +step:2500/20000 train_loss:3.1842 train_time:7474783ms step_avg:2989.91ms +step:2500/20000 val_loss:3.1808 val_bpb:1.2316 train_time:7474793ms step_avg:2989.92ms +step:2600/20000 train_loss:3.1802 train_time:7772875ms step_avg:2989.57ms +step:2700/20000 train_loss:3.1311 train_time:8070951ms step_avg:2989.24ms +step:2800/20000 train_loss:3.1808 train_time:8369157ms step_avg:2988.98ms +step:2900/20000 train_loss:3.2103 train_time:8667329ms step_avg:2988.73ms +step:3000/20000 train_loss:3.0760 train_time:8965787ms step_avg:2988.60ms +step:3000/20000 val_loss:3.1475 val_bpb:1.2187 train_time:8965798ms step_avg:2988.60ms +step:3100/20000 train_loss:3.1017 train_time:9263848ms step_avg:2988.34ms +step:3200/20000 train_loss:3.1447 train_time:9561395ms step_avg:2987.94ms +step:3300/20000 train_loss:3.1859 train_time:9859019ms step_avg:2987.58ms +step:3400/20000 train_loss:3.1344 train_time:10157253ms step_avg:2987.43ms +step:3500/20000 train_loss:3.1046 train_time:10455208ms step_avg:2987.20ms +step:3500/20000 val_loss:3.1181 val_bpb:1.2073 train_time:10455218ms step_avg:2987.21ms +step:3600/20000 train_loss:3.1087 train_time:10753070ms step_avg:2986.96ms +step:3700/20000 train_loss:3.0919 train_time:11051570ms step_avg:2986.91ms +step:3800/20000 train_loss:3.1706 train_time:11350158ms step_avg:2986.88ms +step:3900/20000 train_loss:3.0733 train_time:11648893ms step_avg:2986.90ms +step:4000/20000 train_loss:3.1437 train_time:11948103ms step_avg:2987.03ms +step:4000/20000 val_loss:3.0804 val_bpb:1.1927 train_time:11948113ms step_avg:2987.03ms +step:4100/20000 train_loss:3.2186 train_time:12246116ms step_avg:2986.86ms +step:4200/20000 train_loss:3.1195 train_time:12544061ms step_avg:2986.68ms +step:4300/20000 train_loss:3.0739 train_time:12842252ms step_avg:2986.57ms +step:4400/20000 train_loss:3.0618 train_time:13140653ms step_avg:2986.51ms +step:4500/20000 train_loss:2.9970 train_time:13441487ms step_avg:2987.00ms +step:4500/20000 val_loss:3.0478 val_bpb:1.1801 train_time:13441496ms step_avg:2987.00ms +step:4600/20000 train_loss:2.9977 train_time:13740489ms step_avg:2987.06ms +step:4700/20000 train_loss:3.0050 train_time:14039732ms step_avg:2987.18ms +step:4800/20000 train_loss:3.0284 train_time:14338716ms step_avg:2987.23ms +step:4900/20000 train_loss:3.0412 train_time:14638168ms step_avg:2987.38ms +step:5000/20000 train_loss:2.9317 train_time:14940019ms step_avg:2988.00ms +step:5000/20000 val_loss:3.0045 val_bpb:1.1633 train_time:14940030ms step_avg:2988.01ms +step:5100/20000 train_loss:2.9587 train_time:15245106ms step_avg:2989.24ms +step:5200/20000 train_loss:2.9829 train_time:15550576ms step_avg:2990.50ms +step:5300/20000 train_loss:3.0442 train_time:15856106ms step_avg:2991.72ms +step:5400/20000 train_loss:2.9758 train_time:16161774ms step_avg:2992.92ms +step:5500/20000 train_loss:2.9297 train_time:16467025ms step_avg:2994.00ms +step:5500/20000 val_loss:2.9514 val_bpb:1.1428 train_time:16467036ms step_avg:2994.01ms +step:5600/20000 train_loss:2.9650 train_time:16768052ms step_avg:2994.29ms +step:5700/20000 train_loss:2.9885 train_time:17067544ms step_avg:2994.31ms +step:5800/20000 train_loss:2.9606 train_time:17366927ms step_avg:2994.30ms +step:5900/20000 train_loss:2.8959 train_time:17666194ms step_avg:2994.27ms +step:6000/20000 train_loss:2.8509 train_time:17965325ms step_avg:2994.22ms +step:6000/20000 val_loss:2.9049 val_bpb:1.1248 train_time:17965336ms step_avg:2994.22ms +step:6012/20000 val_loss:2.9048 val_bpb:1.1247 train_time:18001254ms step_avg:2994.22ms +stopping_early: wallclock_cap train_time:18001254ms step:6012/20000 +peak memory allocated: 16543 MiB reserved: 17772 MiB +eval:restored full crawler loops=2, depth=7 +swa:averaging 15 checkpoints +swa_eval val_loss:2.9017 val_bpb:1.1235 +saved backup: final_model_v5_d736_honest_seed42.pt +Serialized model: 136629271 bytes +Code size: 90756 bytes +Total submission size: 136720027 bytes +Serialized model int8+zstd-22: 16667734 bytes (payload:38578440 raw_torch:38603741 payload_ratio:3.54x) +Total submission size int8+zlib: 16758490 bytes +final_int8_zlib_roundtrip val_loss:3.0116 val_bpb:1.1661 eval_time:68673ms +final_int8_zlib_roundtrip_exact val_loss:3.01164901 val_bpb:1.16610757 +gptq:loading calibration data from training shards... +gptq:loaded 64 calibration sequences in 4.5s +gptq:collecting hessians... +gptq:collected hessians for 32 layers +gptq:quantizing int6 with full Hessian GPTQ... +selective_prune: 12569931 candidates, unpruned=15.02MB target=15.9MB +selective_prune: already fits, no pruning needed +gptq_int6_brotli: 14,930,293 bytes | code: 90,756 | total: 15,021,049 (15.02MB) +gptq_int6_brotli_roundtrip val_loss:3.0300 val_bpb:1.1732 time:238.1s +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633560 stride=64 +ttt_sliding:params unfrozen=26429492 frozen=11917344 + ttt_chunk [1/1238] bpb=1.233653 time=4.2s + ttt_chunk [11/1238] bpb=1.155887 time=49.9s + ttt_chunk [21/1238] bpb=1.157537 time=95.5s + ttt_chunk [31/1238] bpb=1.151930 time=141.0s + ttt_chunk [41/1238] bpb=1.158136 time=186.6s + ttt_chunk [51/1238] bpb=1.153850 time=232.1s + ttt_chunk [61/1238] bpb=1.150055 time=277.7s + ttt_chunk [71/1238] bpb=1.151922 time=323.3s + ttt_chunk [81/1238] bpb=1.147518 time=368.9s + ttt_chunk [91/1238] bpb=1.145157 time=414.5s + ttt_chunk [101/1238] bpb=1.145026 time=460.0s + ttt_chunk [111/1238] bpb=1.147174 time=505.6s + ttt_chunk [121/1238] bpb=1.147851 time=551.2s + ttt_chunk [131/1238] bpb=1.149939 time=596.8s + ttt_chunk [141/1238] bpb=1.148629 time=642.3s + ttt_chunk [151/1238] bpb=1.148658 time=687.9s + ttt_chunk [161/1238] bpb=1.147947 time=733.4s + ttt_chunk [171/1238] bpb=1.147632 time=779.0s + ttt_chunk [181/1238] bpb=1.147103 time=824.5s + ttt_chunk [191/1238] bpb=1.147403 time=870.0s + ttt_chunk [201/1238] bpb=1.147856 time=915.6s + ttt_chunk [211/1238] bpb=1.148572 time=961.2s + ttt_chunk [221/1238] bpb=1.147625 time=1006.7s + ttt_chunk [231/1238] bpb=1.148178 time=1052.3s + ttt_chunk [241/1238] bpb=1.148413 time=1097.9s + ttt_chunk [251/1238] bpb=1.148517 time=1143.4s + ttt_chunk [261/1238] bpb=1.148775 time=1189.0s + ttt_chunk [271/1238] bpb=1.147430 time=1234.6s + ttt_chunk [281/1238] bpb=1.148082 time=1280.2s + ttt_chunk [291/1238] bpb=1.147061 time=1325.8s + ttt_chunk [301/1238] bpb=1.147005 time=1371.3s + ttt_chunk [311/1238] bpb=1.146725 time=1416.9s + ttt_chunk [321/1238] bpb=1.146615 time=1462.5s + ttt_chunk [331/1238] bpb=1.146134 time=1508.0s + ttt_chunk [341/1238] bpb=1.145330 time=1553.6s + ttt_chunk [351/1238] bpb=1.145717 time=1599.2s + ttt_chunk [361/1238] bpb=1.145441 time=1644.8s + ttt_chunk [371/1238] bpb=1.144983 time=1690.4s + ttt_chunk [381/1238] bpb=1.144453 time=1736.0s + ttt_chunk [391/1238] bpb=1.143942 time=1781.6s + ttt_chunk [401/1238] bpb=1.143470 time=1827.1s + ttt_chunk [411/1238] bpb=1.143078 time=1872.7s + ttt_chunk [421/1238] bpb=1.142710 time=1918.3s + ttt_chunk [431/1238] bpb=1.141750 time=1963.9s + ttt_chunk [441/1238] bpb=1.140960 time=2009.5s + ttt_chunk [451/1238] bpb=1.140952 time=2055.0s + ttt_chunk [461/1238] bpb=1.139782 time=2100.6s + ttt_chunk [471/1238] bpb=1.139646 time=2146.2s + ttt_chunk [481/1238] bpb=1.139896 time=2191.8s + ttt_chunk [491/1238] bpb=1.139448 time=2237.4s + ttt_chunk [501/1238] bpb=1.139410 time=2282.9s + ttt_chunk [511/1238] bpb=1.139458 time=2328.5s + ttt_chunk [521/1238] bpb=1.139094 time=2374.1s + ttt_chunk [531/1238] bpb=1.139083 time=2419.7s + ttt_chunk [541/1238] bpb=1.138933 time=2465.3s + ttt_chunk [551/1238] bpb=1.138416 time=2510.8s + ttt_chunk [561/1238] bpb=1.138350 time=2556.4s + ttt_chunk [571/1238] bpb=1.138633 time=2601.9s + ttt_chunk [581/1238] bpb=1.138356 time=2647.5s + ttt_chunk [591/1238] bpb=1.137954 time=2693.1s + ttt_chunk [601/1238] bpb=1.137884 time=2738.6s + ttt_chunk [611/1238] bpb=1.137791 time=2784.2s + ttt_chunk [621/1238] bpb=1.138379 time=2829.8s + ttt_chunk [631/1238] bpb=1.138653 time=2875.4s + ttt_chunk [641/1238] bpb=1.139055 time=2921.0s + ttt_chunk [651/1238] bpb=1.139072 time=2966.5s + ttt_chunk [661/1238] bpb=1.139428 time=3012.1s + ttt_chunk [671/1238] bpb=1.139825 time=3057.6s + ttt_chunk [681/1238] bpb=1.140486 time=3103.2s + ttt_chunk [691/1238] bpb=1.140546 time=3148.8s + ttt_chunk [701/1238] bpb=1.140626 time=3194.3s + ttt_chunk [711/1238] bpb=1.140893 time=3239.9s + ttt_chunk [721/1238] bpb=1.141043 time=3285.4s + ttt_chunk [731/1238] bpb=1.140679 time=3331.0s + ttt_chunk [741/1238] bpb=1.140336 time=3376.6s + ttt_chunk [751/1238] bpb=1.140076 time=3422.1s + ttt_chunk [761/1238] bpb=1.139915 time=3467.7s + ttt_chunk [771/1238] bpb=1.139411 time=3513.3s + ttt_chunk [781/1238] bpb=1.139766 time=3558.9s + ttt_chunk [791/1238] bpb=1.139296 time=3604.5s + ttt_chunk [801/1238] bpb=1.139598 time=3650.1s + ttt_chunk [811/1238] bpb=1.139193 time=3695.6s + ttt_chunk [821/1238] bpb=1.138511 time=3741.2s + ttt_chunk [831/1238] bpb=1.138118 time=3786.7s + ttt_chunk [841/1238] bpb=1.137727 time=3832.2s + ttt_chunk [851/1238] bpb=1.137401 time=3877.7s + ttt_chunk [861/1238] bpb=1.137034 time=3923.3s + ttt_chunk [871/1238] bpb=1.136602 time=3968.8s + ttt_chunk [881/1238] bpb=1.136328 time=4014.3s + ttt_chunk [891/1238] bpb=1.136451 time=4059.9s + ttt_chunk [901/1238] bpb=1.136797 time=4105.5s + ttt_chunk [911/1238] bpb=1.136666 time=4151.0s + ttt_chunk [921/1238] bpb=1.136745 time=4196.6s + ttt_chunk [931/1238] bpb=1.136699 time=4242.1s + ttt_chunk [941/1238] bpb=1.137073 time=4287.6s + ttt_chunk [951/1238] bpb=1.136942 time=4333.1s + ttt_chunk [961/1238] bpb=1.137454 time=4378.6s + ttt_chunk [971/1238] bpb=1.137599 time=4424.2s + ttt_chunk [981/1238] bpb=1.137635 time=4469.7s + ttt_chunk [991/1238] bpb=1.137582 time=4515.3s + ttt_chunk [1001/1238] bpb=1.137895 time=4560.8s + ttt_chunk [1011/1238] bpb=1.138040 time=4606.4s + ttt_chunk [1021/1238] bpb=1.138270 time=4651.9s + ttt_chunk [1031/1238] bpb=1.138454 time=4697.5s + ttt_chunk [1041/1238] bpb=1.138573 time=4743.0s + ttt_chunk [1051/1238] bpb=1.138813 time=4788.6s + ttt_chunk [1061/1238] bpb=1.138789 time=4834.2s + ttt_chunk [1071/1238] bpb=1.138828 time=4879.7s + ttt_chunk [1081/1238] bpb=1.138899 time=4925.3s + ttt_chunk [1091/1238] bpb=1.139086 time=4970.9s + ttt_chunk [1101/1238] bpb=1.139268 time=5016.4s + ttt_chunk [1111/1238] bpb=1.139311 time=5062.0s + ttt_chunk [1121/1238] bpb=1.139250 time=5107.5s + ttt_chunk [1131/1238] bpb=1.139330 time=5153.7s + ttt_chunk [1141/1238] bpb=1.139021 time=5200.7s + ttt_chunk [1151/1238] bpb=1.138974 time=5246.8s + ttt_chunk [1161/1238] bpb=1.138848 time=5293.4s + ttt_chunk [1171/1238] bpb=1.138453 time=5339.9s + ttt_chunk [1181/1238] bpb=1.138314 time=5386.4s + ttt_chunk [1191/1238] bpb=1.138305 time=5432.3s + ttt_chunk [1201/1238] bpb=1.138258 time=5478.0s + ttt_chunk [1211/1238] bpb=1.137932 time=5524.8s + ttt_chunk [1221/1238] bpb=1.137861 time=5570.5s + ttt_chunk [1231/1238] bpb=1.137570 time=5616.3s + ttt_chunk [1238/1238] bpb=1.137569 time=5645.6s +ttt_sliding:done val_loss=2.937979 val_bpb=1.137569 elapsed=5645.7s +final_ttt_sliding val_loss:2.9380 val_bpb:1.1376 eval_time:5645938ms +ntiguous() + + if sdclip_k > 0: + # SDClip for 1D: use global std + clip_abs = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + else: + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_abs / max_val if clip_abs > 0 else 1.0, dtype=torch.float32) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), min_val, max_val).to(torch.int8).contiguous() + return q, scale + +def quantize_state_dict_int8(state_dict: dict[str, Tensor], qat_bits: int = 8, qat_mlp_bits: int = 0): + quantized: dict[str, Tensor] = {} + scales: dict[str, Tensor] = {} + dtypes: dict[str, str] = {} + passthrough: dict[str, Tensor] = {} + passthrough_orig_dtypes: dict[str, str] = {} + qmeta: dict[str, dict[str, object]] = {} + stats = dict.fromkeys( + ("param_count", "num_tensors", "num_float_tensors", "num_nonfloat_tensors", "baseline_tensor_bytes", "int8_payload_bytes"), + 0, + ) + + for name, tensor in state_dict.items(): + t = tensor.detach().to("cpu").contiguous() + stats["param_count"] += int(t.numel()) + stats["num_tensors"] += 1 + stats["baseline_tensor_bytes"] += tensor_nbytes(t) + + if not t.is_floating_point(): + stats["num_nonfloat_tensors"] += 1 + passthrough[name] = t + stats["int8_payload_bytes"] += tensor_nbytes(t) + continue + + if t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + kept = keep_float_tensor(name, t, passthrough_orig_dtypes) + passthrough[name] = kept + stats["int8_payload_bytes"] += tensor_nbytes(kept) + continue + + stats["num_float_tensors"] += 1 + is_block_weight = any(k in name for k in ("flat_blocks.", "crawler_blocks.", "bigram.proj.")) + is_embed_weight = ("tok_emb.weight" in name) + is_mlp_weight = any(k in name for k in ("mlp.fc.weight", "mlp.proj.weight")) + if qat_bits < 8 and is_block_weight and t.ndim == 2: + n_bits = (qat_mlp_bits if (qat_mlp_bits > 0 and is_mlp_weight) else qat_bits) + sdclip_k = 12.85 + elif is_embed_weight: + n_bits = 8 + sdclip_k = 20.0 + else: + n_bits = 8 + sdclip_k = 20.0 + q, s = quantize_float_tensor(t, n_bits=n_bits, sdclip_k=sdclip_k) + if s.ndim > 0: + qmeta[name] = {"scheme": "per_row", "axis": 0} + quantized[name] = q + scales[name] = s + dtypes[name] = str(t.dtype).removeprefix("torch.") + stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + obj: dict[str, object] = { + "__quant_format__": "int8_clean_per_row_v1", + "quantized": quantized, + "scales": scales, + "dtypes": dtypes, + "passthrough": passthrough, + } + if qmeta: + obj["qmeta"] = qmeta + if passthrough_orig_dtypes: + obj["passthrough_orig_dtypes"] = passthrough_orig_dtypes + return obj, stats + +def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + qmeta = obj.get("qmeta", {}) + passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {}) + for name, q in obj["quantized"].items(): + dtype = getattr(torch, obj["dtypes"][name]) + s = obj["scales"][name] + if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: + s = s.to(dtype=torch.float32) + 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 + +def generate_calib_from_data(train_files, device, num_seqs=64, seq_len=2048, seed=42): + rng = random.Random(seed) + shard_files = sorted(glob.glob(train_files)) + all_tokens = [] + while len(all_tokens) < num_seqs: + shard = Path(rng.choice(shard_files)) + data = load_data_shard(shard) + max_start = data.numel() - seq_len - 1 + if max_start <= 0: + continue + start = rng.randint(0, max_start) + seq = data[start:start + seq_len + 1].unsqueeze(0).to(device=device, dtype=torch.int64) + all_tokens.append(seq) + return all_tokens[:num_seqs] + +def collect_hessians_from_tokens(hessian_model, token_seqs, device): + hessians = {} + hooks = [] + for name, module in hessian_model.named_modules(): + if isinstance(module, CastedLinear): + param_name = name + ".weight" + cols = module.weight.shape[1] + hessians[param_name] = torch.zeros(cols, cols, dtype=torch.float32, device='cpu') + def make_hook(pname): + def hook_fn(module, input, output): + x = input[0].detach().float() + if x.ndim == 3: + x = x.reshape(-1, x.shape[-1]) + hessians[pname] += (x.T @ x).cpu() + return hook_fn + h = module.register_forward_hook(make_hook(param_name)) + hooks.append(h) + hessian_model.eval() + with torch.inference_mode(), torch.autocast(device_type="cuda", dtype=torch.bfloat16): + for seq in token_seqs: + x = seq[:, :-1].to(device) + y = seq[:, 1:].to(device) + hessian_model(x, y) + for h in hooks: + h.remove() + for name in hessians: + H = hessians[name] + H /= len(token_seqs) + damp = 0.01 * torch.diag(H).mean().clamp_min(1e-6) + H += damp * torch.eye(H.shape[0]) + hessians[name] = H + return hessians + +def quantize_int6_gptq(weight, hessian=None, clip_range=31, block_size=128, sdclip_k: float = 0.0): + t32 = weight.float() + if t32.ndim != 2 or hessian is None: + return quantize_int6_per_row(t32, clip_range, sdclip_k=sdclip_k) + rows, cols = t32.shape + H = hessian.float().clone() + dead = torch.diag(H) == 0 + H[dead, dead] = 1 + damp = 0.01 * torch.mean(torch.diag(H)) + H[torch.arange(cols), torch.arange(cols)] += damp + perm = torch.argsort(torch.diag(H), descending=True) + inv_perm = torch.argsort(perm) + W = t32[:, perm].clone() + W[:, dead[perm]] = 0 + H = H[perm][:, perm] + try: + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + except torch._C._LinAlgError: + H[torch.arange(cols), torch.arange(cols)] += 0.1 * torch.mean(torch.diag(H)) + Hinv = torch.linalg.cholesky(H) + Hinv = torch.cholesky_inverse(Hinv) + Hinv = torch.linalg.cholesky(Hinv, upper=True) + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + best_q = Q[:, inv_perm] + return best_q, s + best_q, best_scale, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + sf = s.float() + Q = torch.zeros_like(W, dtype=torch.int8) + W_work = W.clone() + for i1 in range(0, cols, block_size): + i2 = min(i1 + block_size, cols) + count = i2 - i1 + W1 = W_work[:, i1:i2].clone() + Q1 = torch.zeros(rows, count, dtype=torch.int8) + Err1 = torch.zeros(rows, count) + Hinv1 = Hinv[i1:i2, i1:i2] + for i in range(count): + w = W1[:, i] + d = Hinv1[i, i] + q = torch.clamp(torch.round(w / sf), -clip_range, clip_range).to(torch.int8) + Q1[:, i] = q + err = (w - q.float() * sf) / d + W1[:, i:] -= err.unsqueeze(1) * Hinv1[i, i:].unsqueeze(0) + Err1[:, i] = err + Q[:, i1:i2] = Q1 + if i2 < cols: + W_work[:, i2:] -= Err1 @ Hinv[i1:i2, i2:] + recon = Q.float() * sf[:, None] + mse = (W - recon).pow(2).mean().item() + if mse < best_err: + best_q, best_scale, best_err = Q, s, mse + best_q = best_q[:, inv_perm] + return best_q, best_scale + +def quantize_int6_per_row(t, clip_range=31, sdclip_k: float = 0.0): + t32 = t.float() if not t.is_floating_point() else t.float() + if t32.ndim == 2: + if sdclip_k > 0: + # SDClip: clip = k * std(row) + row_clip = sdclip_k * t32.std(dim=1) + row_clip = row_clip.clamp_min(1e-8) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + return q, s + best_q, best_s, best_err = None, None, float('inf') + for pct in [0.9990, 0.9995, 0.9999, 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) + s = (row_clip / clip_range).clamp_min(1.0 / clip_range).to(torch.float16) + q = torch.clamp(torch.round(t32 / s.float()[:, None]), -clip_range, clip_range).to(torch.int8) + recon = q.float() * s.float()[:, None] + err = (t32 - recon).pow(2).mean().item() + if err < best_err: + best_q, best_s, best_err = q, s, err + return best_q, best_s + if sdclip_k > 0: + clip_val = float((sdclip_k * t32.std()).item()) if t32.numel() else 0.0 + scale = torch.tensor(clip_val / clip_range if clip_val > 0 else 1.0, dtype=torch.float16) + else: + amax = t32.abs().max().item() + scale = torch.tensor(amax / clip_range if amax > 0 else 1.0, dtype=torch.float16) + q = torch.clamp(torch.round(t32 / scale.float()), -clip_range, clip_range).to(torch.int8) + return q, scale + +def mixed_quantize_int6_gptq(state_dict, hessians=None): + result = {} + meta = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + if not t.is_floating_point() or t.numel() <= INT8_KEEP_FLOAT_MAX_NUMEL: + result[name] = t.to(torch.float16) if t.is_floating_point() else t + meta[name] = "passthrough" + continue + if any(p in name for p in CONTROL_TENSOR_NAME_PATTERNS): + result[name] = t.float() + meta[name] = "passthrough_ctrl" + continue + is_block = any(k in name for k in ("flat_blocks.", "crawler_blocks.")) + if is_block and t.ndim == 2: + H = hessians.get(name) if hessians else None + q, s = quantize_int6_gptq(t, hessian=H, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + else: + q, s = quantize_int6_per_row(t, clip_range=31, sdclip_k=12.85) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + return result, meta + +def dequantize_mixed_int6(result, meta, template_sd): + out = {} + for name, orig in template_sd.items(): + info = meta.get(name) + if info is None: + continue + orig_dtype = orig.dtype + if info in ("passthrough", "passthrough_ctrl"): + t = result[name] + if t.dtype == torch.float16 and orig_dtype in (torch.float32, torch.bfloat16): + t = t.to(orig_dtype) + out[name] = t + continue + q, s = result[name + ".q"], result[name + ".scale"] + if s.ndim > 0: + out[name] = (q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1)))).to(orig_dtype) + else: + out[name] = (q.float() * float(s.item())).to(orig_dtype) + return out + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + +class DistributedTokenLoader: + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = 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) + +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) + +def _fake_quantize_ste(w: Tensor, n_bits: int) -> Tensor: + max_val = 2 ** (n_bits - 1) - 1 + min_val = -(2 ** (n_bits - 1)) + scale = w.abs().amax(dim=-1, keepdim=True) / max_val + scale = scale.clamp_min(1e-8) + w_q = (w / scale).round().clamp(min_val, max_val) * scale + return w + (w_q - w).detach() + +_QAT_ENABLED = False +_QAT_BITS = 6 +_QAT_MLP_BITS = 0 +_ACTIVE_CRAWLER_LOOPS = 1 + +class CastedLinear(nn.Linear): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._is_mlp = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if _QAT_ENABLED and self.weight.ndim == 2 and self.weight.numel() > 65536: + bits = (_QAT_MLP_BITS if (_QAT_MLP_BITS > 0 and self._is_mlp) else _QAT_BITS) + w = _fake_quantize_ste(w, bits) + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + with torch.no_grad(): + for name, param in module.named_parameters(): + if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + param.data = param.data.float() + +class Rotary(nn.Module): + def __init__(self, dim: int, base: float = 10000.0): + super().__init__() + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self._seq_len_cached = 0 + self._cos_cached: Tensor | None = None + self._sin_cached: Tensor | None = None + + def forward(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor]: + if ( + self._cos_cached is None + or self._sin_cached is None + or self._seq_len_cached != seq_len + or self._cos_cached.device != device + ): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.outer(t, self.inv_freq.to(device)) + self._cos_cached = freqs.cos()[None, None, :, :] + self._sin_cached = freqs.sin()[None, None, :, :] + self._seq_len_cached = seq_len + return self._cos_cached.to(dtype=dtype), self._sin_cached.to(dtype=dtype) + +def apply_rotary_emb(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor: + half = x.size(-1) // 2 + x1, x2 = x[..., :half], x[..., half:] + return torch.cat((x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos), dim=-1) + +class CausalSelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + num_kv_heads: int, + rope_base: float, + qk_gain_init: float, + ): + super().__init__() + if dim % num_heads != 0: + raise ValueError("model_dim must be divisible by num_heads") + if num_heads % num_kv_heads != 0: + raise ValueError("num_heads must be divisible by num_kv_heads") + self.num_heads = num_heads + self.num_kv_heads = num_kv_heads + self.head_dim = dim // num_heads + if self.head_dim % 2 != 0: + raise ValueError("head_dim must be even for RoPE") + kv_dim = self.num_kv_heads * self.head_dim + self.c_q = CastedLinear(dim, dim, bias=False) + self.c_k = CastedLinear(dim, kv_dim, bias=False) + self.c_v = CastedLinear(dim, kv_dim, bias=False) + self.proj = CastedLinear(dim, dim, bias=False) + self.proj._zero_init = True + self.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) + self.rotary = Rotary(self.head_dim, base=rope_base) + self.use_xsa = False + + def _xsa_efficient(self, y: Tensor, v: Tensor) -> Tensor: + 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(3) + proj = (y_g * vn).sum(dim=-1, keepdim=True) * vn + return (y_g - proj).reshape(B, T, H, D) + + def forward(self, x: Tensor, q_delta=None, v_delta=None) -> Tensor: + bsz, seqlen, dim = x.shape + q = self.c_q(x) + (q_delta if q_delta is not None else 0) + k = self.c_k(x) + v = self.c_v(x) + (v_delta if v_delta is not None else 0) + q = q.reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = k.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = v.reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + rope_dim = cos.size(-1) + partial = rope_dim // 2 + if partial > 0: + q_rope, q_pass = q[..., :partial*2], q[..., partial*2:] + k_rope, k_pass = k[..., :partial*2], k[..., partial*2:] + q_rope = apply_rotary_emb(q_rope, cos[..., :partial], sin[..., :partial]) + k_rope = apply_rotary_emb(k_rope, cos[..., :partial], sin[..., :partial]) + q = torch.cat([q_rope, q_pass], dim=-1) + k = torch.cat([k_rope, k_pass], dim=-1) + else: + 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 = self._xsa_efficient(y.transpose(1, 2), v.transpose(1, 2)).contiguous().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): + super().__init__() + hidden = mlp_mult * dim + self.fc = CastedLinear(dim, hidden, bias=False) + self.fc._is_mlp = True + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + self.proj._is_mlp = True + + def forward(self, x: Tensor) -> Tensor: + x = torch.relu(self.fc(x)) + return self.proj(x.square()) + +class ValueEmbedding(nn.Module): + def __init__(self, vocab_size: int, ve_dim: int, kv_dim: int, num_loops_active: int): + super().__init__() + self.table = nn.Embedding(vocab_size, ve_dim) + self.proj = CastedLinear(ve_dim, kv_dim, bias=False) + self.scales = nn.ParameterList([nn.Parameter(torch.ones(1)) for _ in range(num_loops_active)]) + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor, loop_idx: int) -> Tensor: + return self.scales[loop_idx] * self.proj(self.table(input_ids)) + +class SmearGate(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.gate = nn.Parameter(torch.zeros(dim, dtype=torch.float32)) + + def forward(self, x: Tensor) -> Tensor: + g = torch.sigmoid(self.gate).to(dtype=x.dtype) + x_prev = torch.cat([torch.zeros_like(x[:, :1]), x[:, :-1]], dim=1) + return (1.0 - g) * x + g * x_prev + +class BigramHashEmbedding(nn.Module): + def __init__(self, num_buckets: int, hash_dim: int, model_dim: int): + super().__init__() + self.num_buckets = num_buckets + self.table = nn.Embedding(num_buckets, hash_dim) + self.proj = CastedLinear(hash_dim, model_dim, bias=False) + self.proj._zero_init = True + nn.init.normal_(self.table.weight, std=0.01) + + def forward(self, input_ids: Tensor) -> Tensor: + bsz, seqlen = input_ids.shape + prev_ids = torch.cat([ + torch.zeros(bsz, 1, dtype=input_ids.dtype, device=input_ids.device), + input_ids[:, :-1], + ], dim=1) + h = ((prev_ids.long() * 92821 + input_ids.long()) % self.num_buckets).long() + return self.proj(self.table(h)) + +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, + ): + super().__init__() + self.attn_norm = RMSNorm() + self.mlp_norm = RMSNorm() + self.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init) + self.mlp = MLP(dim, mlp_mult) + + def forward( + self, x: Tensor, x0: Tensor, + attn_scale: Tensor, mlp_scale: Tensor, resid_mix: Tensor, + q_delta_fn=None, v_delta_fn=None, v_embed=None, + ) -> Tensor: + mix = resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + n = self.attn_norm(x) + qd = q_delta_fn(n) if q_delta_fn is not None else None + vd = v_delta_fn(n) if v_delta_fn is not None else None + if v_embed is not None: + vd = (vd + v_embed) if vd is not None else v_embed + attn_out = self.attn(n, qd, vd) + x = x + attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x)) + return x + +class GPT(nn.Module): + def __init__( + self, + vocab_size: int, + num_flat_blocks: int, + num_crawler_blocks: int, + crawler_loops: 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, + use_smear_gate: bool = True, + bigram_buckets: int = 10240, + bigram_dim: int = 128, + embed_bottleneck: int = 0, + ve_enabled: bool = False, + ve_dim: int = 128, + ve_last_n: int = 2, + temperature: float = 1.0, + ): + super().__init__() + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap + self.temperature = temperature + self.embed_bottleneck = embed_bottleneck + self.num_flat_blocks = num_flat_blocks + self.num_crawler_blocks = num_crawler_blocks + self.crawler_loops = crawler_loops + self._active_crawler_loops = crawler_loops + self._n_enc = num_flat_blocks // 2 + num_loops = num_flat_blocks + num_crawler_blocks * crawler_loops + self.num_loops = num_loops + if embed_bottleneck > 0: + self.tok_emb = nn.Embedding(vocab_size, embed_bottleneck) + self.embed_proj = CastedLinear(embed_bottleneck, model_dim, bias=False) + self.embed_proj_rev = CastedLinear(model_dim, embed_bottleneck, bias=False) + else: + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.embed_proj = None + self.embed_proj_rev = None + self.bigram = BigramHashEmbedding(bigram_buckets, bigram_dim, model_dim) + self.smear = SmearGate(model_dim) if use_smear_gate else None + kv_dim = num_kv_heads * (model_dim // num_heads) + self.ve = ValueEmbedding(vocab_size, ve_dim, kv_dim, ve_last_n) if ve_enabled else None + self.ve_last_n = ve_last_n + self.flat_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_flat_blocks) + ]) + self.crawler_blocks = nn.ModuleList([ + Block(model_dim, num_heads, num_kv_heads, mlp_mult, rope_base, qk_gain_init) + for _ in range(num_crawler_blocks) + ]) + self.crawler_residual_scales = nn.ParameterList([ + nn.Parameter(torch.tensor(0.5, dtype=torch.float32)) + for _ in range(crawler_loops) + ]) + self.attn_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.mlp_scales = nn.Parameter(torch.ones(num_loops, model_dim, dtype=torch.float32)) + self.resid_mixes = nn.Parameter( + torch.stack([ + torch.stack((torch.ones(model_dim), torch.zeros(model_dim))) + for _ in range(num_loops) + ]).float() + ) + self.num_encoder_loops = num_loops // 2 + self.num_decoder_loops = num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + self.skip_weights = nn.Parameter(torch.ones(self.num_skips, model_dim, dtype=torch.float32)) + self.xsa_last_n = int(os.environ.get("XSA_LAST_N", 7)) + 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._rebuild_schedule() + self._init_weights() + + def _rebuild_schedule(self, active_loops: int | None = None): + if active_loops is not None: + self._active_crawler_loops = active_loops + schedule = [] + for i in range(self._n_enc): + schedule.append(('flat', i)) + for loop in range(self._active_crawler_loops): + for c in range(self.num_crawler_blocks): + schedule.append(('crawler', c)) + for i in range(self._n_enc, self.num_flat_blocks): + schedule.append(('flat', i)) + self._loop_schedule = schedule + self.num_loops = len(schedule) + self.num_encoder_loops = self.num_loops // 2 + self.num_decoder_loops = self.num_loops - self.num_encoder_loops + self.num_skips = min(self.num_encoder_loops, self.num_decoder_loops) + block_list = [] + for kind, idx in schedule: + block_list.append(self.flat_blocks[idx] if kind == 'flat' else self.crawler_blocks[idx]) + self._block_list = block_list + + def _get_block(self, loop_idx: int) -> 'Block': + return self._block_list[loop_idx] + + 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) + for name, module in self.named_modules(): + if isinstance(module, nn.Linear): + if getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + elif module.weight.ndim == 2 and min(module.weight.shape) >= 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 * self.num_loops)) + + def _embed(self, input_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) + if self.embed_proj is not None: + x = self.embed_proj(x) + return x + + def _logits(self, x: Tensor) -> Tensor: + if self.embed_proj_rev is not None: + x = self.embed_proj_rev(x) + logits = F.linear(x, self.tok_emb.weight) + elif self.tie_embeddings: + logits = F.linear(x, self.tok_emb.weight) + else: + logits = self.lm_head(x) + return self.logit_softcap * torch.tanh(logits / self.logit_softcap) + + def _run_blocks(self, x, x0, input_ids, lora=None): + active_loops = _ACTIVE_CRAWLER_LOOPS + n_enc = self._n_enc + loop_idx = 0 + xsa_n = self.xsa_last_n + total_depth = self.num_flat_blocks + self.num_crawler_blocks * active_loops + + if xsa_n > 0: + for blk in self.flat_blocks: + blk.attn.use_xsa = (loop_idx >= total_depth - xsa_n) if loop_idx < n_enc or loop_idx >= n_enc + self.num_crawler_blocks * active_loops else False + loop_idx += 1 + for blk in self.crawler_blocks: + for _ in range(active_loops): + blk.attn.use_xsa = True + loop_idx = 0 + + skips: list[Tensor] = [] + for i in range(n_enc): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[i](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + skips.append(x) + loop_idx += 1 + + for lp in range(active_loops): + for ci, cblock in enumerate(self.crawler_blocks): + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x_out = cblock(x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + if lp > 0: + alpha = self.crawler_residual_scales[lp].to(dtype=x.dtype) + x = x + alpha * (x_out - x) + else: + x = x_out + loop_idx += 1 + + n_dec_flat = self.num_flat_blocks - n_enc + for i in range(n_dec_flat): + fi = n_enc + i + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + qd = lora.q_loras[loop_idx] if lora else None + vd = lora.v_loras[loop_idx] if lora else None + ve = None + if self.ve is not None and loop_idx >= total_depth - self.ve_last_n: + ve = self.ve(input_ids, loop_idx - (total_depth - self.ve_last_n)) + x = self.flat_blocks[fi](x, x0, self.attn_scales[loop_idx], self.mlp_scales[loop_idx], self.resid_mixes[loop_idx], qd, vd, v_embed=ve) + loop_idx += 1 + return x + + def forward(self, input_ids: Tensor, target_ids: Tensor, lora=None) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids, lora) + unused = sum(p.sum() * 0.0 for p in self.crawler_residual_scales) + x = x + unused + x = self.final_norm(x) + logits = self._logits(x) + logits = logits + (lora.lm_head_lora(x) if lora else 0) + if lora: + bsz, sl, V = logits.shape + return F.cross_entropy( + logits.float().reshape(-1, V), target_ids.reshape(-1), reduction="none").reshape(bsz, sl) + return F.cross_entropy(logits.float().reshape(-1, logits.size(-1)), target_ids.reshape(-1), reduction="mean") + + def forward_logits(self, input_ids: Tensor) -> Tensor: + x = self._embed(input_ids) + x = x + self.bigram(input_ids) + x = F.rms_norm(x, (x.size(-1),)) + if self.smear is not None: + x = self.smear(x) + x0 = x + x = self._run_blocks(x, x0, input_ids) + x = self.final_norm(x) + return self._logits(x) + +def _compute_chunk_window(ci: int, pred_len: int, num_chunks: int, chunk_size: int, eval_seq_len: int): + chunk_start = ci * chunk_size + chunk_end = pred_len if ci == num_chunks - 1 else (ci + 1) * chunk_size + win_start = max(0, chunk_end - eval_seq_len) + win_len = chunk_end - win_start + chunk_offset = chunk_start - win_start + chunk_len = chunk_end - chunk_start + return win_start, win_len, chunk_offset, chunk_len + +def _accumulate_bpb( + ptl: Tensor, x: Tensor, y: Tensor, + batch_i: int, chunk_offset: int, chunk_len: int, + base_bytes_lut: Tensor, has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + loss_sum: Tensor, byte_sum: Tensor, token_count: Tensor, +): + lbl = ptl[batch_i, chunk_offset:chunk_offset + chunk_len].to(torch.float64) + prev = x[batch_i, chunk_offset:chunk_offset + chunk_len] + tgt = y[batch_i, chunk_offset:chunk_offset + chunk_len] + tok_bytes = base_bytes_lut[tgt].to(torch.float64) + tok_bytes += has_leading_space_lut[tgt] & ~is_boundary_token_lut[prev] + loss_sum += lbl.sum() + byte_sum += tok_bytes.sum() + token_count += chunk_len + +def eval_val_sliding_ttt( + args: Hyperparameters, base_model: GPT, rank: int, world_size: int, + device: torch.device, val_tokens: Tensor, base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, is_boundary_token_lut: Tensor, + stride: int, batch_seqs: int = 32, log0=print, +) -> tuple[float, float]: + 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}") + + 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_blocks = min(args.ttt_freeze_blocks, base_model.num_flat_blocks + base_model.num_crawler_blocks) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = False + for bi in range(freeze_blocks): + if f"flat_blocks.{bi}." in name or f"crawler_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)}") + + 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 + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + + 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 = [] + 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) + loss_sum += nll[i, s:wlen].to(torch.float64).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() + + is_last_chunk = (ci == num_chunks - 1) + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + cos_lr = args.ttt_lr * 0.5 * (1.0 + math.cos(math.pi * ci / max(num_chunks - 1, 1))) + for pg in optimizer.param_groups: + pg['lr'] = cos_lr + 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) + start_tok = chunk_start + (my_seq_s + bs) * seq_len + end_tok = chunk_start + (my_seq_s + 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) + torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) + optimizer.step() + + if rank == 0 and (ci % 10 == 0 or is_last_chunk): + 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)) + 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 + +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 = "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, timeout=datetime.timedelta(seconds=1800)) + 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) + torch._dynamo.config.optimize_ddp = 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) + + 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}") + + base_model = GPT( + vocab_size=args.vocab_size, + num_flat_blocks=args.num_flat_blocks, + num_crawler_blocks=args.num_crawler_blocks, + crawler_loops=args.crawler_loops, + 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, + temperature=args.temperature, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + use_smear_gate=args.use_smear_gate, + bigram_buckets=args.bigram_buckets, + bigram_dim=args.bigram_dim, + embed_bottleneck=args.embed_bottleneck, + ve_enabled=args.ve_enabled, + ve_dim=args.ve_dim, + ve_last_n=args.ve_last_n, + ).to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + if isinstance(module, Rotary): + module.inv_freq.data = module.inv_freq.data.float() + restore_low_dim_params_to_fp32(base_model) + + if args.resume_from and os.path.isfile(args.resume_from): + log0(f"resuming_from:{args.resume_from}") + saved = torch.load(args.resume_from, map_location=device) + base_model.load_state_dict(saved, strict=True) + restore_low_dim_params_to_fp32(base_model) + log0("resume:loaded model weights (optimizer states reset)") + global _QAT_ENABLED, _QAT_BITS, _QAT_MLP_BITS, _ACTIVE_CRAWLER_LOOPS + _QAT_BITS = args.qat_bits + _QAT_MLP_BITS = args.qat_mlp_bits + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + _qat_activated = False + if args.qat_enabled and args.late_qat_threshold >= 1.0: + _QAT_ENABLED = True + _qat_activated = True + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:enabled from step 0 attn={_QAT_BITS}bit{mlp_info}") + elif args.qat_enabled: + _QAT_ENABLED = False + mlp_info = f", MLP={_QAT_MLP_BITS}bit" if _QAT_MLP_BITS > 0 else "" + log0(f"qat:late_start threshold={args.late_qat_threshold} attn={_QAT_BITS}bit{mlp_info}") + else: + _QAT_ENABLED = False + _use_compile = bool(int(os.environ.get("TORCH_COMPILE", "1"))) + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) if _use_compile else base_model + _use_ddp = distributed and world_size > 1 + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + + block_named_params = list(base_model.flat_blocks.named_parameters()) + list(base_model.crawler_blocks.named_parameters()) + matrix_params = [ + p + for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p + for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params.append(base_model.attn_scales) + scalar_params.append(base_model.mlp_scales) + scalar_params.append(base_model.resid_mixes) + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + if base_model.smear is not None: + scalar_params.append(base_model.smear.gate) + bigram_named = list(base_model.bigram.named_parameters()) + for name, p in bigram_named: + if p.ndim == 2 and "proj" in name: + matrix_params.append(p) + elif p.ndim == 2: + pass + else: + scalar_params.append(p) + ve_table_params = [] + if base_model.ve is not None: + for name, p in base_model.ve.named_parameters(): + if "table" in name: + ve_table_params.append(p) + elif p.ndim == 2: + matrix_params.append(p) + else: + scalar_params.append(p) + 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, base_model.bigram.table.weight] + + ([base_model.embed_proj.weight, base_model.embed_proj_rev.weight] if base_model.embed_proj is not None else []) + + ve_table_params, + "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + weight_decay=args.weight_decay, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.AdamW( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + weight_decay=args.weight_decay, + fused=True, + ) + optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] + if base_model.lm_head is not None: + optimizer_head = torch.optim.Adam( + [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.insert(1, optimizer_head) + + n_params = sum(p.numel() for p in base_model.parameters()) + flat_params = sum(p.numel() for p in base_model.flat_blocks.parameters()) + crawler_params = sum(p.numel() for p in base_model.crawler_blocks.parameters()) + loop_params = base_model.attn_scales.numel() + base_model.mlp_scales.numel() + base_model.resid_mixes.numel() + log0(f"architecture:crawler flat_blocks:{args.num_flat_blocks} crawler_blocks:{args.num_crawler_blocks} crawler_loops:{args.crawler_loops} effective_depth:{base_model.num_loops} flat_params:{flat_params} crawler_params:{crawler_params} per_loop_params:{loop_params}") + log0(f"model_params:{n_params}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") + log0( + f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " + f"head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} " + f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" + ) + log0( + f"train_batch_tokens:{args.train_batch_tokens} train_seq_len:{args.train_seq_len} " + f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " + f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" + ) + log0(f"seed:{args.seed}") + + 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_frac > 0 and max_wallclock_ms is not None: + warmdown_ms = args.warmdown_frac * max_wallclock_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.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 + + progressive_steps: list[tuple[int, int]] = [] + if args.progressive_schedule: + for entry in args.progressive_schedule.split(","): + s, loops = entry.strip().split(":") + progressive_steps.append((int(s), int(loops))) + progressive_steps.sort() + + 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] + prog_variants = sorted(set([1] + [loops for _, loops in progressive_steps])) if progressive_steps else [base_model._active_crawler_loops] + steps_per_variant = max(1, args.warmup_steps // (len(prog_variants) * 2)) + model.train() + warmup_step = 0 + for variant_loops in prog_variants: + if variant_loops != base_model._active_crawler_loops: + base_model._rebuild_schedule(active_loops=variant_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"warmup:precompile variant={variant_loops} loops, depth={base_model.num_loops}") + for _ in range(steps_per_variant): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{args.warmup_steps}") + remaining = args.warmup_steps - warmup_step + if remaining > 0: + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + for _ in range(remaining): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if _use_ddp: + 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() + warmup_step += 1 + if warmup_step <= 20 or warmup_step % 10 == 0: + log0(f"warmup_step:{warmup_step}/{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() + base_model._rebuild_schedule(active_loops=1 if progressive_steps else args.crawler_loops) + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + if _use_ddp: + model.require_backward_grad_sync = True + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + if progressive_steps: + _ACTIVE_CRAWLER_LOOPS = 1 + log0(f"progressive:enabled schedule={progressive_steps} starting with 1 crawler loop") + else: + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + _current_crawler_loops = _ACTIVE_CRAWLER_LOOPS + + training_time_ms = 0.0 + stop_after_step: int | None = None + swa_checkpoints: list[dict[str, Tensor]] = [] + ema_sd: dict[str, Tensor] | None = None + if args.ema_decay > 0: + ema_sd = {k: v.detach().float().clone() for k, v in base_model.state_dict().items()} + log0(f"ema:enabled decay={args.ema_decay}") + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + + should_validate = last_step or (args.val_loss_every > 0 and step % args.val_loss_every == 0) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + f"step:{step}/{args.iterations}" + ) + break + + elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + scale = lr_mul(step, elapsed_ms) + if args.qat_enabled and not _qat_activated and scale <= args.late_qat_threshold: + _QAT_ENABLED = True + _qat_activated = True + log0(f"late_qat:activated at step {step} scale={scale:.4f} threshold={args.late_qat_threshold}") + zero_grad_all() + train_loss = torch.zeros((), device=device) + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = micro_step == grad_accum_steps - 1 + x, y = train_loader.next_batch(args.train_batch_tokens, args.train_seq_len, grad_accum_steps) + with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=True): + loss = model(x, y) + train_loss += loss.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + + frac = min(step / args.muon_momentum_warmup_steps, 1.0) if args.muon_momentum_warmup_steps > 0 else 1.0 + muon_momentum = (1 - frac) * args.muon_momentum_warmup_start + frac * args.muon_momentum + for group in optimizer_muon.param_groups: + group["momentum"] = muon_momentum + + for opt in optimizers: + for group in opt.param_groups: + group["lr"] = group["base_lr"] * scale + + if args.grad_clip_norm > 0: + torch.nn.utils.clip_grad_norm_(base_model.parameters(), args.grad_clip_norm) + for opt in optimizers: + opt.step() + zero_grad_all() + + if args.swa_start_frac > 0 and step % args.swa_every == 0: + should_collect = torch.tensor(int(scale < args.swa_start_frac), device=device) + if distributed: + dist.all_reduce(should_collect, op=dist.ReduceOp.MIN) + if should_collect.item(): + swa_checkpoints.append({k: v.detach().cpu().clone() for k, v in base_model.state_dict().items()}) + + if ema_sd is not None: + d = args.ema_decay + with torch.no_grad(): + for k, v in base_model.state_dict().items(): + ema_sd[k].mul_(d).add_(v.detach().float(), alpha=1.0 - d) + + step += 1 + for prog_step, prog_loops in progressive_steps: + if step == prog_step and prog_loops != _current_crawler_loops: + _ACTIVE_CRAWLER_LOOPS = prog_loops + _current_crawler_loops = prog_loops + torch._dynamo.reset() + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if _use_ddp else compiled_model + log0(f"progressive:step {step} -> {prog_loops} crawler loops, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * prog_loops} (recompiled)") + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + should_log_train = ( + args.train_log_every > 0 + and (step <= 10 or step % args.train_log_every == 0 or stop_after_step is not None) + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" + ) + + reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + _QAT_ENABLED = False + _ACTIVE_CRAWLER_LOOPS = args.crawler_loops + log0(f"eval:restored full crawler loops={args.crawler_loops}, depth={base_model.num_flat_blocks + base_model.num_crawler_blocks * args.crawler_loops}") + + if swa_checkpoints: + log0(f"swa:averaging {len(swa_checkpoints)} checkpoints") + avg_sd = {} + for key in swa_checkpoints[0]: + stacked = torch.stack([ckpt[key].float() for ckpt in swa_checkpoints]) + avg_sd[key] = stacked.mean(dim=0).to(dtype=swa_checkpoints[0][key].dtype) + base_model.load_state_dict(avg_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + swa_val_loss, swa_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"swa_eval val_loss:{swa_val_loss:.4f} val_bpb:{swa_val_bpb:.4f}") + del swa_checkpoints + + if ema_sd is not None: + log0("ema:loading averaged weights") + model_sd = base_model.state_dict() + for k in ema_sd: + ema_sd[k] = ema_sd[k].to(dtype=model_sd[k].dtype, device=model_sd[k].device) + base_model.load_state_dict(ema_sd, strict=True) + restore_low_dim_params_to_fp32(base_model) + ema_val_loss, ema_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"ema_eval val_loss:{ema_val_loss:.4f} val_bpb:{ema_val_bpb:.4f}") + del ema_sd + + if master_process: + torch.save(base_model.state_dict(), "final_model.pt") + import shutil + shutil.copy2("final_model.pt", f"final_model_{args.run_id}.pt") + log0(f"saved backup: final_model_{args.run_id}.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + quant_obj, quant_stats = quantize_state_dict_int8( + base_model.state_dict(), + qat_bits=args.qat_bits if args.qat_enabled else 8, + qat_mlp_bits=args.qat_mlp_bits if args.qat_enabled else 0, + ) + quant_buf = io.BytesIO() + torch.save(quant_obj, quant_buf) + quant_raw = quant_buf.getvalue() + try: + import zstandard as zstd + quant_blob = zstd.ZstdCompressor(level=22).compress(quant_raw) + compress_method = "zstd-22" + except ImportError: + quant_blob = zlib.compress(quant_raw, level=9) + compress_method = "zlib-9" + quant_raw_bytes = len(quant_raw) + if master_process: + with open("final_model.int8.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") + code_bytes = len(code.encode("utf-8")) + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int8_payload_bytes"], 1) + log0( + f"Serialized model int8+{compress_method}: {quant_file_bytes} bytes " + f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" + ) + log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int8.ptz", "rb") as f: + quant_blob_disk = f.read() + try: + import zstandard as zstd + decompressed = zstd.ZstdDecompressor().decompress(quant_blob_disk) + except Exception: + decompressed = zlib.decompress(quant_blob_disk) + quant_state = torch.load(io.BytesIO(decompressed), map_location="cpu") + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + torch.cuda.synchronize() + t_qeval = time.perf_counter() + q_val_loss, q_val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") + + if master_process: + log0("gptq:loading calibration data from training shards...") + base_model.load_state_dict(torch.load("final_model.pt", map_location=device), strict=True) + restore_low_dim_params_to_fp32(base_model) + t_gptq = time.perf_counter() + ar_tokens = generate_calib_from_data( + args.train_files, device, num_seqs=64, seq_len=args.train_seq_len, seed=args.seed, + ) + log0(f"gptq:loaded {len(ar_tokens)} calibration sequences in {time.perf_counter()-t_gptq:.1f}s") + log0("gptq:collecting hessians...") + hessians = collect_hessians_from_tokens(base_model, ar_tokens, device) + log0(f"gptq:collected hessians for {len(hessians)} layers") + del ar_tokens + torch.cuda.empty_cache() + log0("gptq:quantizing int6 with full Hessian GPTQ...") + gptq_result, gptq_meta = mixed_quantize_int6_gptq( + base_model.state_dict(), hessians=hessians, + ) + del hessians + target_bytes = 15_900_000 + code_bytes = len(code.encode("utf-8")) + ones_info = [] + for name, info in gptq_meta.items(): + if not (isinstance(info, dict) and info.get("type") == "int6"): + continue + qk, sk = name + ".q", name + ".scale" + if qk not in gptq_result or sk not in gptq_result: + continue + q, s = gptq_result[qk], gptq_result[sk] + if s.ndim > 0: + ones_mask = (q.abs() == 1) + if ones_mask.any(): + row_idx = torch.arange(q.shape[0]).unsqueeze(1).expand_as(q)[ones_mask] + flat_idx = torch.arange(q.numel()).reshape(q.shape)[ones_mask] + errors = s.float()[row_idx].pow(2) + for fi, err in zip(flat_idx.tolist(), errors.tolist()): + ones_info.append((qk, fi, err)) + ones_info.sort(key=lambda x: x[2]) + def _try_prune(n): + tmp = {k: v.clone() for k, v in gptq_result.items()} + for i in range(min(n, len(ones_info))): + tmp[ones_info[i][0]].view(-1)[ones_info[i][1]] = 0 + buf = io.BytesIO() + torch.save({"w": tmp, "m": gptq_meta}, buf) + return len(brotli.compress(buf.getvalue(), quality=11)) + code_bytes, tmp + no_prune_sz, _ = _try_prune(0) + log0(f"selective_prune: {len(ones_info)} candidates, unpruned={no_prune_sz/1e6:.2f}MB target={target_bytes/1e6:.1f}MB") + if no_prune_sz <= target_bytes: + log0("selective_prune: already fits, no pruning needed") + final_result = gptq_result + else: + full_sz, _ = _try_prune(len(ones_info)) + log0(f"selective_prune: full prune={full_sz/1e6:.2f}MB") + if full_sz > target_bytes: + log0("selective_prune: even full prune not enough, applying all") + _, final_result = _try_prune(len(ones_info)) + else: + lo, hi = 0, len(ones_info) + while lo < hi: + mid = (lo + hi) // 2 + sz, _ = _try_prune(mid) + if sz <= target_bytes: + hi = mid + else: + lo = mid + 1 + log0(f"selective_prune: pruning {lo}/{len(ones_info)} values ({100*lo/len(ones_info):.1f}%) to fit") + _, final_result = _try_prune(lo) + gptq_buf = io.BytesIO() + torch.save({"w": final_result, "m": gptq_meta}, gptq_buf) + gptq_raw = gptq_buf.getvalue() + gptq_blob = brotli.compress(gptq_raw, quality=11) + gptq_bytes = len(gptq_blob) + total_bytes = gptq_bytes + code_bytes + log0(f"gptq_int6_brotli: {gptq_bytes:,} bytes | code: {code_bytes:,} | total: {total_bytes:,} ({total_bytes/1e6:.2f}MB)") + with open("final_model.int6_gptq.ptz", "wb") as f: + f.write(gptq_blob) + gptq_state = torch.load( + io.BytesIO(brotli.decompress(gptq_blob)), map_location="cpu", weights_only=False + ) + restored = dequantize_mixed_int6(gptq_state["w"], gptq_state["m"], base_model.state_dict()) + base_model.load_state_dict(restored, strict=True) + restore_low_dim_params_to_fp32(base_model) + gq_val_loss, gq_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"gptq_int6_brotli_roundtrip val_loss:{gq_val_loss:.4f} val_bpb:{gq_val_bpb:.4f} time:{time.perf_counter()-t_gptq:.1f}s") + + if args.ttt_enabled: + torch._dynamo.reset() + # TTT runs on the GPTQ artifact (already loaded at line 1980-1982) + torch.cuda.synchronize() + t_ttt_sw = time.perf_counter() + all_val_tokens = torch.cat([load_data_shard(Path(p)) for p in sorted(glob.glob(args.val_files))]).contiguous() + ttt_sw_loss, ttt_sw_bpb = eval_val_sliding_ttt( + args, base_model, rank, world_size, device, + all_val_tokens, base_bytes_lut, has_leading_space_lut, is_boundary_token_lut, + stride=args.sliding_window_stride if args.sliding_window_stride > 0 else 64, + log0=log0, + ) + torch.cuda.synchronize() + log0( + f"final_ttt_sliding val_loss:{ttt_sw_loss:.4f} val_bpb:{ttt_sw_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt_sw):.0f}ms" + ) + + if distributed: + dist.destroy_process_group() + +if __name__ == "__main__": + main() + + +==================================================================================================== +Running Python 3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0] +Running PyTorch 2.6.0+cu124 +Sun Apr 12 06:57:01 2026 ++-----------------------------------------------------------------------------------------+ +| NVIDIA-SMI 580.126.09 Driver Version: 580.126.09 CUDA Version: 13.0 | ++-----------------------------------------+------------------------+----------------------+ +| 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 RTX 6000 Ada Gene... Off | 00000000:01:00.0 Off | Off | +| 66% 78C P0 96W / 300W | 1340MiB / 49140MiB | 0% Default | +| | | N/A | ++-----------------------------------------+------------------------+----------------------+ + ++-----------------------------------------------------------------------------------------+ +| Processes: | +| GPU GI CI PID Type Process name GPU Memory | +| ID ID Usage | +|=========================================================================================| +| 0 N/A N/A 2640 G /usr/lib/xorg/Xorg 285MiB | +| 0 N/A N/A 2821 G /usr/bin/gnome-shell 190MiB | +| 0 N/A N/A 3400 G ...exec/xdg-desktop-portal-gnome 31MiB | +| 0 N/A N/A 444032 G /usr/bin/nautilus 94MiB | +| 0 N/A N/A 767208 G .../8054/usr/lib/firefox/firefox 535MiB | +| 0 N/A N/A 3548448 G /proc/self/exe 67MiB | ++-----------------------------------------------------------------------------------------+ + +==================================================================================================== +val_bpb:enabled tokenizer_kind=sentencepiece tokenizer_path=./data/tokenizers/fineweb_8192_bpe.model +train_loader:dataset:fineweb10B_sp8192 train_shards:128 +val_loader:shards pattern=./data/datasets/fineweb10B_sp8192/fineweb_val_*.bin tokens:40546304 +qat:enabled from step 0 attn=6bit +architecture:crawler flat_blocks:3 crawler_blocks:2 crawler_loops:2 effective_depth:7 flat_params:17876016 crawler_params:11917344 per_loop_params:20608 +model_params:38346836 +world_size:1 grad_accum_steps:8 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +attention_mode:gqa num_heads:16 num_kv_heads:8 +tie_embeddings:True embed_lr:0.02 head_lr:0.0 matrix_lr:0.02 scalar_lr:0.01 +train_batch_tokens:524288 train_seq_len:2048 iterations:20000 warmup_steps:100 max_wallclock_seconds:18000.000 +seed:42 +warmup_step:1/100 +warmup_step:2/100 +warmup_step:3/100 +warmup_step:4/100 +warmup_step:5/100 +warmup_step:6/100 +warmup_step:7/100 +warmup_step:8/100 +warmup_step:9/100 +warmup_step:10/100 +warmup_step:11/100 +warmup_step:12/100 +warmup_step:13/100 +warmup_step:14/100 +warmup_step:15/100 +warmup_step:16/100 +warmup_step:17/100 +warmup_step:18/100 +warmup_step:19/100 +warmup_step:20/100 +warmup_step:30/100 +warmup_step:40/100 +warmup_step:50/100 +warmup_step:60/100 +warmup_step:70/100 +warmup_step:80/100 +warmup_step:90/100 +warmup_step:100/100 +step:0/20000 val_loss:8.9975 val_bpb:3.4838 train_time:0ms step_avg:0.01ms +step:1/20000 train_loss:8.9981 train_time:9106ms step_avg:9106.36ms +step:2/20000 train_loss:8.8448 train_time:12002ms step_avg:6000.80ms +step:3/20000 train_loss:9.5108 train_time:14946ms step_avg:4982.01ms +step:4/20000 train_loss:9.3126 train_time:17892ms step_avg:4472.94ms +step:5/20000 train_loss:8.9713 train_time:20844ms step_avg:4168.84ms +step:6/20000 train_loss:8.4572 train_time:23799ms step_avg:3966.51ms +step:7/20000 train_loss:8.0264 train_time:26767ms step_avg:3823.85ms +step:8/20000 train_loss:7.6690 train_time:29738ms step_avg:3717.21ms +step:9/20000 train_loss:7.2852 train_time:32716ms step_avg:3635.11ms +step:10/20000 train_loss:6.9981 train_time:35705ms step_avg:3570.45ms +step:100/20000 train_loss:4.6127 train_time:307805ms step_avg:3078.05ms +step:200/20000 train_loss:3.9858 train_time:608213ms step_avg:3041.06ms +step:300/20000 train_loss:3.6700 train_time:908008ms step_avg:3026.69ms +step:400/20000 train_loss:3.6354 train_time:1207238ms step_avg:3018.09ms +step:500/20000 train_loss:3.4467 train_time:1506294ms step_avg:3012.59ms +step:500/20000 val_loss:3.5181 val_bpb:1.3622 train_time:1506305ms step_avg:3012.61ms +step:600/20000 train_loss:3.4952 train_time:1805073ms step_avg:3008.46ms +step:700/20000 train_loss:3.3177 train_time:2104278ms step_avg:3006.11ms +step:800/20000 train_loss:3.3843 train_time:2403910ms step_avg:3004.89ms +step:900/20000 train_loss:3.3627 train_time:2703416ms step_avg:3003.80ms +step:1000/20000 train_loss:3.2050 train_time:3002709ms step_avg:3002.71ms +step:1000/20000 val_loss:3.3001 val_bpb:1.2778 train_time:3002719ms step_avg:3002.72ms +step:1100/20000 train_loss:3.3120 train_time:3300823ms step_avg:3000.75ms +step:1200/20000 train_loss:3.3373 train_time:3598552ms step_avg:2998.79ms +step:1300/20000 train_loss:3.2603 train_time:3896625ms step_avg:2997.40ms +step:1400/20000 train_loss:3.1850 train_time:4195245ms step_avg:2996.60ms +step:1500/20000 train_loss:3.1807 train_time:4494135ms step_avg:2996.09ms +step:1500/20000 val_loss:3.2335 val_bpb:1.2520 train_time:4494147ms step_avg:2996.10ms +step:1600/20000 train_loss:3.2755 train_time:4792192ms step_avg:2995.12ms +step:1700/20000 train_loss:3.2789 train_time:5090282ms step_avg:2994.28ms +step:1800/20000 train_loss:3.2658 train_time:5388457ms step_avg:2993.59ms +step:1900/20000 train_loss:3.2539 train_time:5686612ms step_avg:2992.95ms +step:2000/20000 train_loss:3.2267 train_time:5984300ms step_avg:2992.15ms +step:2000/20000 val_loss:3.2054 val_bpb:1.2411 train_time:5984310ms step_avg:2992.15ms +step:2100/20000 train_loss:3.2010 train_time:6282080ms step_avg:2991.47ms +step:2200/20000 train_loss:3.2040 train_time:6580281ms step_avg:2991.04ms +step:2300/20000 train_loss:3.2689 train_time:6878595ms step_avg:2990.69ms +step:2400/20000 train_loss:3.2325 train_time:7176607ms step_avg:2990.25ms +step:2500/20000 train_loss:3.1842 train_time:7474783ms step_avg:2989.91ms +step:2500/20000 val_loss:3.1808 val_bpb:1.2316 train_time:7474793ms step_avg:2989.92ms +step:2600/20000 train_loss:3.1802 train_time:7772875ms step_avg:2989.57ms +step:2700/20000 train_loss:3.1311 train_time:8070951ms step_avg:2989.24ms +step:2800/20000 train_loss:3.1808 train_time:8369157ms step_avg:2988.98ms +step:2900/20000 train_loss:3.2103 train_time:8667329ms step_avg:2988.73ms +step:3000/20000 train_loss:3.0760 train_time:8965787ms step_avg:2988.60ms +step:3000/20000 val_loss:3.1475 val_bpb:1.2187 train_time:8965798ms step_avg:2988.60ms +step:3100/20000 train_loss:3.1017 train_time:9263848ms step_avg:2988.34ms +step:3200/20000 train_loss:3.1447 train_time:9561395ms step_avg:2987.94ms +step:3300/20000 train_loss:3.1859 train_time:9859019ms step_avg:2987.58ms +step:3400/20000 train_loss:3.1344 train_time:10157253ms step_avg:2987.43ms +step:3500/20000 train_loss:3.1046 train_time:10455208ms step_avg:2987.20ms +step:3500/20000 val_loss:3.1181 val_bpb:1.2073 train_time:10455218ms step_avg:2987.21ms +step:3600/20000 train_loss:3.1087 train_time:10753070ms step_avg:2986.96ms +step:3700/20000 train_loss:3.0919 train_time:11051570ms step_avg:2986.91ms +step:3800/20000 train_loss:3.1706 train_time:11350158ms step_avg:2986.88ms +step:3900/20000 train_loss:3.0733 train_time:11648893ms step_avg:2986.90ms +step:4000/20000 train_loss:3.1437 train_time:11948103ms step_avg:2987.03ms +step:4000/20000 val_loss:3.0804 val_bpb:1.1927 train_time:11948113ms step_avg:2987.03ms +step:4100/20000 train_loss:3.2186 train_time:12246116ms step_avg:2986.86ms +step:4200/20000 train_loss:3.1195 train_time:12544061ms step_avg:2986.68ms +step:4300/20000 train_loss:3.0739 train_time:12842252ms step_avg:2986.57ms +step:4400/20000 train_loss:3.0618 train_time:13140653ms step_avg:2986.51ms +step:4500/20000 train_loss:2.9970 train_time:13441487ms step_avg:2987.00ms +step:4500/20000 val_loss:3.0478 val_bpb:1.1801 train_time:13441496ms step_avg:2987.00ms +step:4600/20000 train_loss:2.9977 train_time:13740489ms step_avg:2987.06ms +step:4700/20000 train_loss:3.0050 train_time:14039732ms step_avg:2987.18ms +step:4800/20000 train_loss:3.0284 train_time:14338716ms step_avg:2987.23ms +step:4900/20000 train_loss:3.0412 train_time:14638168ms step_avg:2987.38ms +step:5000/20000 train_loss:2.9317 train_time:14940019ms step_avg:2988.00ms +step:5000/20000 val_loss:3.0045 val_bpb:1.1633 train_time:14940030ms step_avg:2988.01ms +step:5100/20000 train_loss:2.9587 train_time:15245106ms step_avg:2989.24ms +step:5200/20000 train_loss:2.9829 train_time:15550576ms step_avg:2990.50ms +step:5300/20000 train_loss:3.0442 train_time:15856106ms step_avg:2991.72ms +step:5400/20000 train_loss:2.9758 train_time:16161774ms step_avg:2992.92ms +step:5500/20000 train_loss:2.9297 train_time:16467025ms step_avg:2994.00ms +step:5500/20000 val_loss:2.9514 val_bpb:1.1428 train_time:16467036ms step_avg:2994.01ms +step:5600/20000 train_loss:2.9650 train_time:16768052ms step_avg:2994.29ms +step:5700/20000 train_loss:2.9885 train_time:17067544ms step_avg:2994.31ms +step:5800/20000 train_loss:2.9606 train_time:17366927ms step_avg:2994.30ms +step:5900/20000 train_loss:2.8959 train_time:17666194ms step_avg:2994.27ms +step:6000/20000 train_loss:2.8509 train_time:17965325ms step_avg:2994.22ms +step:6000/20000 val_loss:2.9049 val_bpb:1.1248 train_time:17965336ms step_avg:2994.22ms +step:6012/20000 val_loss:2.9048 val_bpb:1.1247 train_time:18001254ms step_avg:2994.22ms +stopping_early: wallclock_cap train_time:18001254ms step:6012/20000 +peak memory allocated: 16543 MiB reserved: 17772 MiB +eval:restored full crawler loops=2, depth=7 +swa:averaging 15 checkpoints +swa_eval val_loss:2.9017 val_bpb:1.1235 +saved backup: final_model_v5_d736_honest_seed42.pt +Serialized model: 136629271 bytes +Code size: 90756 bytes +Total submission size: 136720027 bytes +Serialized model int8+zstd-22: 16667734 bytes (payload:38578440 raw_torch:38603741 payload_ratio:3.54x) +Total submission size int8+zlib: 16758490 bytes +final_int8_zlib_roundtrip val_loss:3.0116 val_bpb:1.1661 eval_time:68673ms +final_int8_zlib_roundtrip_exact val_loss:3.01164901 val_bpb:1.16610757 +gptq:loading calibration data from training shards... +gptq:loaded 64 calibration sequences in 4.5s +gptq:collecting hessians... +gptq:collected hessians for 32 layers +gptq:quantizing int6 with full Hessian GPTQ... +selective_prune: 12569931 candidates, unpruned=15.02MB target=15.9MB +selective_prune: already fits, no pruning needed +gptq_int6_brotli: 14,930,293 bytes | code: 90,756 | total: 15,021,049 (15.02MB) +gptq_int6_brotli_roundtrip val_loss:3.0300 val_bpb:1.1732 time:238.1s +ttt_sliding:start chunks=1238 chunk_tokens=32768 total_windows=633560 stride=64 +ttt_sliding:params unfrozen=26429492 frozen=11917344 + ttt_chunk [1/1238] bpb=1.233653 time=4.2s + ttt_chunk [11/1238] bpb=1.155887 time=49.9s + ttt_chunk [21/1238] bpb=1.157537 time=95.5s + ttt_chunk [31/1238] bpb=1.151930 time=141.0s + ttt_chunk [41/1238] bpb=1.158136 time=186.6s + ttt_chunk [51/1238] bpb=1.153850 time=232.1s + ttt_chunk [61/1238] bpb=1.150055 time=277.7s + ttt_chunk [71/1238] bpb=1.151922 time=323.3s + ttt_chunk [81/1238] bpb=1.147518 time=368.9s + ttt_chunk [91/1238] bpb=1.145157 time=414.5s + ttt_chunk [101/1238] bpb=1.145026 time=460.0s + ttt_chunk [111/1238] bpb=1.147174 time=505.6s + ttt_chunk [121/1238] bpb=1.147851 time=551.2s + ttt_chunk [131/1238] bpb=1.149939 time=596.8s + ttt_chunk [141/1238] bpb=1.148629 time=642.3s + ttt_chunk [151/1238] bpb=1.148658 time=687.9s + ttt_chunk [161/1238] bpb=1.147947 time=733.4s + ttt_chunk [171/1238] bpb=1.147632 time=779.0s + ttt_chunk [181/1238] bpb=1.147103 time=824.5s + ttt_chunk [191/1238] bpb=1.147403 time=870.0s + ttt_chunk [201/1238] bpb=1.147856 time=915.6s + ttt_chunk [211/1238] bpb=1.148572 time=961.2s + ttt_chunk [221/1238] bpb=1.147625 time=1006.7s + ttt_chunk [231/1238] bpb=1.148178 time=1052.3s + ttt_chunk [241/1238] bpb=1.148413 time=1097.9s + ttt_chunk [251/1238] bpb=1.148517 time=1143.4s + ttt_chunk [261/1238] bpb=1.148775 time=1189.0s + ttt_chunk [271/1238] bpb=1.147430 time=1234.6s + ttt_chunk [281/1238] bpb=1.148082 time=1280.2s + ttt_chunk [291/1238] bpb=1.147061 time=1325.8s + ttt_chunk [301/1238] bpb=1.147005 time=1371.3s + ttt_chunk [311/1238] bpb=1.146725 time=1416.9s + ttt_chunk [321/1238] bpb=1.146615 time=1462.5s + ttt_chunk [331/1238] bpb=1.146134 time=1508.0s + ttt_chunk [341/1238] bpb=1.145330 time=1553.6s + ttt_chunk [351/1238] bpb=1.145717 time=1599.2s + ttt_chunk [361/1238] bpb=1.145441 time=1644.8s + ttt_chunk [371/1238] bpb=1.144983 time=1690.4s + ttt_chunk [381/1238] bpb=1.144453 time=1736.0s + ttt_chunk [391/1238] bpb=1.143942 time=1781.6s + ttt_chunk [401/1238] bpb=1.143470 time=1827.1s + ttt_chunk [411/1238] bpb=1.143078 time=1872.7s + ttt_chunk [421/1238] bpb=1.142710 time=1918.3s + ttt_chunk [431/1238] bpb=1.141750 time=1963.9s + ttt_chunk [441/1238] bpb=1.140960 time=2009.5s + ttt_chunk [451/1238] bpb=1.140952 time=2055.0s + ttt_chunk [461/1238] bpb=1.139782 time=2100.6s + ttt_chunk [471/1238] bpb=1.139646 time=2146.2s + ttt_chunk [481/1238] bpb=1.139896 time=2191.8s + ttt_chunk [491/1238] bpb=1.139448 time=2237.4s + ttt_chunk [501/1238] bpb=1.139410 time=2282.9s + ttt_chunk [511/1238] bpb=1.139458 time=2328.5s + ttt_chunk [521/1238] bpb=1.139094 time=2374.1s + ttt_chunk [531/1238] bpb=1.139083 time=2419.7s + ttt_chunk [541/1238] bpb=1.138933 time=2465.3s + ttt_chunk [551/1238] bpb=1.138416 time=2510.8s + ttt_chunk [561/1238] bpb=1.138350 time=2556.4s + ttt_chunk [571/1238] bpb=1.138633 time=2601.9s + ttt_chunk [581/1238] bpb=1.138356 time=2647.5s + ttt_chunk [591/1238] bpb=1.137954 time=2693.1s + ttt_chunk [601/1238] bpb=1.137884 time=2738.6s + ttt_chunk [611/1238] bpb=1.137791 time=2784.2s + ttt_chunk [621/1238] bpb=1.138379 time=2829.8s + ttt_chunk [631/1238] bpb=1.138653 time=2875.4s + ttt_chunk [641/1238] bpb=1.139055 time=2921.0s + ttt_chunk [651/1238] bpb=1.139072 time=2966.5s + ttt_chunk [661/1238] bpb=1.139428 time=3012.1s + ttt_chunk [671/1238] bpb=1.139825 time=3057.6s + ttt_chunk [681/1238] bpb=1.140486 time=3103.2s + ttt_chunk [691/1238] bpb=1.140546 time=3148.8s + ttt_chunk [701/1238] bpb=1.140626 time=3194.3s + ttt_chunk [711/1238] bpb=1.140893 time=3239.9s + ttt_chunk [721/1238] bpb=1.141043 time=3285.4s + ttt_chunk [731/1238] bpb=1.140679 time=3331.0s + ttt_chunk [741/1238] bpb=1.140336 time=3376.6s + ttt_chunk [751/1238] bpb=1.140076 time=3422.1s + ttt_chunk [761/1238] bpb=1.139915 time=3467.7s + ttt_chunk [771/1238] bpb=1.139411 time=3513.3s + ttt_chunk [781/1238] bpb=1.139766 time=3558.9s + ttt_chunk [791/1238] bpb=1.139296 time=3604.5s + ttt_chunk [801/1238] bpb=1.139598 time=3650.1s + ttt_chunk [811/1238] bpb=1.139193 time=3695.6s + ttt_chunk [821/1238] bpb=1.138511 time=3741.2s + ttt_chunk [831/1238] bpb=1.138118 time=3786.7s + ttt_chunk [841/1238] bpb=1.137727 time=3832.2s + ttt_chunk [851/1238] bpb=1.137401 time=3877.7s + ttt_chunk [861/1238] bpb=1.137034 time=3923.3s + ttt_chunk [871/1238] bpb=1.136602 time=3968.8s + ttt_chunk [881/1238] bpb=1.136328 time=4014.3s + ttt_chunk [891/1238] bpb=1.136451 time=4059.9s + ttt_chunk [901/1238] bpb=1.136797 time=4105.5s + ttt_chunk [911/1238] bpb=1.136666 time=4151.0s + ttt_chunk [921/1238] bpb=1.136745 time=4196.6s + ttt_chunk [931/1238] bpb=1.136699 time=4242.1s + ttt_chunk [941/1238] bpb=1.137073 time=4287.6s + ttt_chunk [951/1238] bpb=1.136942 time=4333.1s + ttt_chunk [961/1238] bpb=1.137454 time=4378.6s + ttt_chunk [971/1238] bpb=1.137599 time=4424.2s + ttt_chunk [981/1238] bpb=1.137635 time=4469.7s + ttt_chunk [991/1238] bpb=1.137582 time=4515.3s + ttt_chunk [1001/1238] bpb=1.137895 time=4560.8s + ttt_chunk [1011/1238] bpb=1.138040 time=4606.4s + ttt_chunk [1021/1238] bpb=1.138270 time=4651.9s + ttt_chunk [1031/1238] bpb=1.138454 time=4697.5s + ttt_chunk [1041/1238] bpb=1.138573 time=4743.0s + ttt_chunk [1051/1238] bpb=1.138813 time=4788.6s + ttt_chunk [1061/1238] bpb=1.138789 time=4834.2s + ttt_chunk [1071/1238] bpb=1.138828 time=4879.7s + ttt_chunk [1081/1238] bpb=1.138899 time=4925.3s + ttt_chunk [1091/1238] bpb=1.139086 time=4970.9s + ttt_chunk [1101/1238] bpb=1.139268 time=5016.4s + ttt_chunk [1111/1238] bpb=1.139311 time=5062.0s + ttt_chunk [1121/1238] bpb=1.139250 time=5107.5s + ttt_chunk [1131/1238] bpb=1.139330 time=5153.7s + ttt_chunk [1141/1238] bpb=1.139021 time=5200.7s + ttt_chunk [1151/1238] bpb=1.138974 time=5246.8s + ttt_chunk [1161/1238] bpb=1.138848 time=5293.4s + ttt_chunk [1171/1238] bpb=1.138453 time=5339.9s + ttt_chunk [1181/1238] bpb=1.138314 time=5386.4s + ttt_chunk [1191/1238] bpb=1.138305 time=5432.3s + ttt_chunk [1201/1238] bpb=1.138258 time=5478.0s + ttt_chunk [1211/1238] bpb=1.137932 time=5524.8s + ttt_chunk [1221/1238] bpb=1.137861 time=5570.5s + ttt_chunk [1231/1238] bpb=1.137570 time=5616.3s + ttt_chunk [1238/1238] bpb=1.137569 time=5645.6s +ttt_sliding:done val_loss=2.937979 val_bpb=1.137569 elapsed=5645.7s +final_ttt_sliding val_loss:2.9380 val_bpb:1.1376 eval_time:5645938ms diff --git a/requirements.txt b/requirements.txt index 911b0e52f0..bc408cf90c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,5 @@ setuptools typing-extensions==4.15.0 datasets tiktoken -sentencepiece \ No newline at end of file +sentencepiece +zstandard \ No newline at end of file