From 1a9a8b988be848e1650b0446b0e968f3cf0d3abf Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 15:47:16 -0700 Subject: [PATCH 01/25] jepa test --- train_gpt.py | 784 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 572 insertions(+), 212 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index 651beb2b8..4471ec8fb 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -9,6 +9,7 @@ import copy import glob import io +import json import math import os import random @@ -20,7 +21,6 @@ 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 @@ -30,23 +30,27 @@ # ----------------------------- # HYPERPARAMETERS # ----------------------------- -# Default Simple Baseline run: -# - 9 transformer blocks at width 512 -# - 8 attention heads with 4 KV heads (GQA) and 2x MLP expansion -# - vocab size 1024, sequence length 1024, tied embeddings -# - 524,288 train tokens per step for 20,000 iterations with a ~10 minute cap +# Default JEPA run: +# - pure-byte FineWeb export (`byte260`) +# - byte-patch JEPA with latent next-patch prediction plus a small causal byte decoder +# - 10 JEPA blocks at width 384, 6 heads with 3 KV heads +# - sequence length 4095 so the reconstructed AR stream has 4096 bytes, cleanly divisible by patch size 8 +# - 524,160 train tokens per step for 20,000 iterations with a ~10 minute cap + class Hyperparameters: # Data paths are shard globs produced by the existing preprocessing pipeline. - data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_sp1024") + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_byte260") 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") + tokenizer_path = os.environ.get( + "TOKENIZER_PATH", "./data/tokenizers/fineweb_pure_byte_260.json" + ) run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) seed = int(os.environ.get("SEED", 1337)) # Validation cadence and batch size. Validation always uses the full fineweb_val split. - val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_160)) val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200)) @@ -54,46 +58,58 @@ class Hyperparameters: 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)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 524_160)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 4095)) max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + use_compile = bool(int(os.environ.get("USE_COMPILE", "1"))) # Model shape. - vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) - num_layers = int(os.environ.get("NUM_LAYERS", 9)) - num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 4)) - model_dim = int(os.environ.get("MODEL_DIM", 512)) - num_heads = int(os.environ.get("NUM_HEADS", 8)) + vocab_size = int(os.environ.get("VOCAB_SIZE", 260)) + num_layers = int(os.environ.get("NUM_LAYERS", 10)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 3)) + model_dim = int(os.environ.get("MODEL_DIM", 384)) + num_heads = int(os.environ.get("NUM_HEADS", 6)) 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)) + patch_size = int(os.environ.get("PATCH_SIZE", 8)) + latent_dim = int(os.environ.get("LATENT_DIM", 192)) + decoder_layers = int(os.environ.get("DECODER_LAYERS", 2)) + decoder_heads = int(os.environ.get("DECODER_HEADS", 4)) + sigreg_weight = float(os.environ.get("SIGREG_WEIGHT", 0.02)) + sigreg_knots = int(os.environ.get("SIGREG_KNOTS", 17)) + sigreg_num_proj = int(os.environ.get("SIGREG_NUM_PROJ", 256)) + jepa_pred_weight = float(os.environ.get("JEPA_PRED_WEIGHT", 2.0)) + jepa_ce_weight = float(os.environ.get("JEPA_CE_WEIGHT", 1.0)) # Optimizer hyperparameters. - embed_lr = float(os.environ.get("EMBED_LR", 0.6)) - head_lr = float(os.environ.get("HEAD_LR", 0.008)) - tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.05)) - tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) - matrix_lr = float(os.environ.get("MATRIX_LR", 0.04)) - scalar_lr = float(os.environ.get("SCALAR_LR", 0.04)) + embed_lr = float(os.environ.get("EMBED_LR", 0.1)) + head_lr = float(os.environ.get("HEAD_LR", 0.02)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.015)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.015)) 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_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.0)) + # ----------------------------- -# MUON OPTIMIZER +# MUON OPTIMIZER # ----------------------------- -# +# # As borrowed from modded-nanogpt # Background on Muon: https://kellerjordan.github.io/posts/muon/ -def zeropower_via_newtonschulz5(G: Tensor, steps: int = 10, eps: float = 1e-7) -> Tensor: + +def zeropower_via_newtonschulz5( + G: Tensor, steps: int = 10, eps: float = 1e-7 +) -> Tensor: # Orthogonalize a 2D update matrix with a fast Newton-Schulz iteration. # Muon uses this to normalize matrix-shaped gradients before applying them. a, b, c = (3.4445, -4.7750, 2.0315) @@ -110,10 +126,19 @@ def zeropower_via_newtonschulz5(G: Tensor, steps: int = 10, eps: float = 1e-7) - class Muon(torch.optim.Optimizer): - def __init__(self, params, lr: float, momentum: float, backend_steps: int, nesterov: bool = True): + def __init__( + self, + params, + lr: float, + momentum: float, + backend_steps: int, + nesterov: bool = True, + ): super().__init__( params, - dict(lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov), + dict( + lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov + ), ) @torch.no_grad() @@ -137,7 +162,9 @@ def step(self, closure=None): 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) + updates_flat = torch.zeros( + total_params, device=params[0].device, dtype=torch.bfloat16 + ) curr = 0 for i, p in enumerate(params): @@ -169,41 +196,52 @@ def step(self, closure=None): # ----------------------------- -# TOKENIZER-AGNOSTIC EVALUATION SETUP +# TOKENIZER-AGNOSTIC EVALUATION SETUP # ----------------------------- # -# It's common for small models have a large fraction of their parameters be embeddings, since the 2 * d_model * d_vocab vectors can be gigantic. -# Instead of locking the tokenizer, we let you bring your own and calculate our validation metrics on the average compression of the validation set. -# We calculate BPB (bits-per-byte) instead of validation loss, so we need methods to count the number of bits per token in the tokenizer. -# Note: Submissions that edit the tokenizer will be examined more carefully, since screwing this up might unjustly improve your score. - -def build_sentencepiece_luts( - sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device +# We score BPB (bits-per-byte), but the model is fixed to a pure-byte vocabulary: +# 4 special ids followed by raw UTF-8 bytes. That makes byte accounting exact. +def build_pure_byte_luts( + 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) + table_size = max(vocab_size, 260) base_bytes_np = np.zeros((table_size,), dtype=np.int16) + base_bytes_np[4 : min(table_size, 260)] = 1 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), + torch.tensor(base_bytes_np[:vocab_size], dtype=torch.int16, device=device), + torch.tensor( + has_leading_space_np[:vocab_size], dtype=torch.bool, device=device + ), + torch.tensor( + is_boundary_token_np[:vocab_size], dtype=torch.bool, device=device + ), ) +def load_pure_byte_luts( + tokenizer_path: str, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + path = Path(tokenizer_path) + if path.suffix != ".json": + raise ValueError( + f"Pure-byte JEPA expects a tokenizer JSON at {tokenizer_path!r}" + ) + payload = json.loads(path.read_text(encoding="utf-8")) + tokenizer_type = payload.get("tokenizer_type") or payload.get("kind") + json_vocab_size = int(payload.get("vocab_size", vocab_size)) + if tokenizer_type != "pure_byte": + raise ValueError( + f"Unsupported tokenizer JSON {tokenizer_path}: expected pure_byte, got {tokenizer_type!r}" + ) + if json_vocab_size != vocab_size: + raise ValueError( + f"VOCAB_SIZE={vocab_size} does not match tokenizer vocab_size={json_vocab_size}" + ) + return build_pure_byte_luts(vocab_size, device) + + def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: files = [Path(p) for p in sorted(glob.glob(pattern))] if not files: @@ -252,18 +290,23 @@ def eval_val( 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) + 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_loss = model(x, y) + batch_loss = batch_loss.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) + 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(): @@ -277,6 +320,7 @@ def eval_val( model.train() return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + # ----------------------------- # POST-TRAINING QUANTIZATION # ----------------------------- @@ -307,10 +351,14 @@ def eval_val( 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: + +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}: @@ -318,6 +366,7 @@ def keep_float_tensor(name: str, t: Tensor, passthrough_orig_dtypes: dict[str, s return t.to(dtype=INT8_KEEP_FLOAT_STORE_DTYPE).contiguous() return t + def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: t32 = t.float() if t32.ndim == 2: @@ -328,17 +377,34 @@ def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: if t32.numel() else torch.empty((t32.shape[0],), dtype=torch.float32) ) - clipped = torch.maximum(torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None]) + clipped = torch.maximum( + torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None] + ) scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) - q = torch.clamp(torch.round(clipped / scale[:, None]), -127, 127).to(torch.int8).contiguous() + q = ( + torch.clamp(torch.round(clipped / scale[:, None]), -127, 127) + .to(torch.int8) + .contiguous() + ) return q, scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous() # Vectors / scalars use a simpler per-tensor scale. - clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 + clip_abs = ( + float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) + if t32.numel() + else 0.0 + ) scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) - q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127).to(torch.int8).contiguous() + q = ( + torch.clamp( + torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127 + ) + .to(torch.int8) + .contiguous() + ) return q, scale + def quantize_state_dict_int8(state_dict: dict[str, Tensor]): # Single supported clean-script export format: # - per-row int8 for 2D float tensors @@ -352,7 +418,14 @@ def quantize_state_dict_int8(state_dict: 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"), + ( + "param_count", + "num_tensors", + "num_float_tensors", + "num_nonfloat_tensors", + "baseline_tensor_bytes", + "int8_payload_bytes", + ), 0, ) @@ -398,6 +471,7 @@ def quantize_state_dict_int8(state_dict: dict[str, Tensor]): 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", {}) @@ -408,7 +482,11 @@ def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: s = s.to(dtype=torch.float32) # Broadcast the saved row scale back across trailing dimensions. - out[name] = (q.float() * s.view(q.shape[0], *([1] * (q.ndim - 1)))).to(dtype=dtype).contiguous() + 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() @@ -423,9 +501,10 @@ def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: # ----------------------------- -# DATA LOADING +# DATA LOADING # ----------------------------- + def load_data_shard(file: Path) -> Tensor: header_bytes = 256 * np.dtype(" Tensor: num_tokens = int(header[2]) expected_size = header_bytes + num_tokens * token_bytes if file.stat().st_size != expected_size: - raise ValueError(f"Shard size mismatch for {file}: expected {expected_size} bytes") + raise ValueError( + f"Shard size mismatch for {file}: expected {expected_size} bytes" + ) tokens_np = np.fromfile(file, dtype=" tuple[Tensor, Tensor]: + 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) @@ -491,12 +574,16 @@ def next_batch(self, global_tokens: int, seq_len: int, grad_accum_steps: int) -> 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) + return x.to(self.device, non_blocking=True), y.to( + self.device, non_blocking=True + ) + # ----------------------------- # TRANSFORMER MODULES # ----------------------------- + class RMSNorm(nn.Module): def __init__(self, eps: float | None = None): super().__init__() @@ -517,7 +604,10 @@ def restore_low_dim_params_to_fp32(module: nn.Module) -> None: # Keep small/control parameters in fp32 even when the model body runs in bf16. with torch.no_grad(): for name, param in module.named_parameters(): - if (param.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS)) and param.dtype != torch.float32: + 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() @@ -531,7 +621,9 @@ def __init__(self, dim: int, base: float = 10000.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]: + 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 @@ -577,14 +669,28 @@ def __init__( 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.q_gain = nn.Parameter( + torch.full((num_heads,), qk_gain_init, dtype=torch.float32) + ) self.rotary = Rotary(self.head_dim, base=rope_base) def forward(self, x: Tensor) -> Tensor: bsz, seqlen, dim = x.shape - q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) - k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) - v = self.c_v(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + q = ( + self.c_q(x) + .reshape(bsz, seqlen, self.num_heads, self.head_dim) + .transpose(1, 2) + ) + k = ( + self.c_k(x) + .reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + .transpose(1, 2) + ) + v = ( + self.c_v(x) + .reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + .transpose(1, 2) + ) q = F.rms_norm(q, (q.size(-1),)) k = F.rms_norm(k, (k.size(-1),)) cos, sin = self.rotary(seqlen, x.device, q.dtype) @@ -630,47 +736,112 @@ def __init__( 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.attn = CausalSelfAttention( + dim, num_heads, num_kv_heads, rope_base, qk_gain_init + ) self.mlp = MLP(dim, mlp_mult) self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) - self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) + self.resid_mix = nn.Parameter( + torch.stack((torch.ones(dim), torch.zeros(dim))).float() + ) def forward(self, x: Tensor, x0: Tensor) -> Tensor: mix = self.resid_mix.to(dtype=x.dtype) x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 attn_out = self.attn(self.attn_norm(x)) x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out - x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x)) + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp( + self.mlp_norm(x) + ) return x -class GPT(nn.Module): +class SIGReg(nn.Module): + # Sketch regularizer from LeWM, adapted to local (per-rank) batches. + def __init__(self, knots: int = 17, num_proj: int = 256): + super().__init__() + self.num_proj = num_proj + t = torch.linspace(0, 3, knots, dtype=torch.float32) + dt = 3 / max(knots - 1, 1) + weights = torch.full((knots,), 2 * dt, dtype=torch.float32) + if knots > 1: + weights[[0, -1]] = dt + window = torch.exp(-t.square() / 2.0) + self.register_buffer("t", t, persistent=False) + self.register_buffer("phi", window, persistent=False) + self.register_buffer("weights", weights * window, persistent=False) + + def forward(self, proj: Tensor) -> Tensor: + if proj.ndim != 3: + raise ValueError(f"SIGReg expects (T, B, D), got {tuple(proj.shape)}") + A = torch.randn( + proj.size(-1), self.num_proj, device=proj.device, dtype=proj.dtype + ) + A = A / (A.norm(p=2, dim=0, keepdim=True).clamp_min(1e-6)) + x_t = (proj @ A).unsqueeze(-1) * self.t.to(dtype=proj.dtype) + err = ( + x_t.cos().mean(-3) - self.phi.to(dtype=proj.dtype) + ).square() + x_t.sin().mean(-3).square() + statistic = (err @ self.weights.to(dtype=proj.dtype)) * proj.size(-2) + return statistic.mean().float() + + +class LatentMLP(nn.Module): + def __init__(self, input_dim: int, output_dim: int, hidden_mult: int = 2): + super().__init__() + hidden = hidden_mult * input_dim + self.norm = RMSNorm() + self.fc = CastedLinear(input_dim, hidden, bias=False) + self.proj = CastedLinear(hidden, output_dim, bias=False) + + def forward(self, x: Tensor) -> Tensor: + x = self.norm(x) + x = F.silu(self.fc(x)) + return self.proj(x) + + +class BytePatchJEPA(nn.Module): def __init__( self, + *, vocab_size: int, num_layers: int, model_dim: int, num_heads: int, num_kv_heads: int, mlp_mult: int, - tie_embeddings: bool, - tied_embed_init_std: float, - logit_softcap: float, rope_base: float, qk_gain_init: float, + patch_size: int, + latent_dim: int, + decoder_layers: int, + decoder_heads: int, + sigreg_knots: int, + sigreg_num_proj: int, + sigreg_weight: float, + jepa_pred_weight: float, + jepa_ce_weight: float, ): 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 + if patch_size < 2: + raise ValueError(f"PATCH_SIZE must be >=2, got {patch_size}") + if decoder_heads <= 0 or model_dim % decoder_heads != 0: + raise ValueError( + f"DECODER_HEADS={decoder_heads} must divide MODEL_DIM={model_dim}" + ) + self.vocab_size = vocab_size + self.patch_size = patch_size + self.sigreg_weight = sigreg_weight + self.jepa_pred_weight = jepa_pred_weight + self.jepa_ce_weight = jepa_ce_weight + self.bos_id = 1 + self.tok_emb = nn.Embedding(vocab_size, model_dim) - self.num_encoder_layers = num_layers // 2 - self.num_decoder_layers = num_layers - self.num_encoder_layers - self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers) - self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32)) + self.patch_pos = nn.Parameter( + torch.zeros(patch_size, model_dim, dtype=torch.float32) + ) + self.patch_in = CastedLinear(patch_size * model_dim, model_dim, bias=False) self.blocks = nn.ModuleList( [ Block( @@ -681,53 +852,142 @@ def __init__( rope_base, qk_gain_init, ) - for i in range(num_layers) + for _ in range(num_layers) ] ) self.final_norm = RMSNorm() - self.lm_head = None if tie_embeddings else CastedLinear(model_dim, vocab_size, bias=False) - if self.lm_head is not None: - self.lm_head._zero_init = True + self.projector = LatentMLP(model_dim, latent_dim) + self.predictor = LatentMLP(model_dim, latent_dim) + self.sigreg = SIGReg(knots=sigreg_knots, num_proj=sigreg_num_proj) + + self.start_latent = nn.Parameter(torch.zeros(latent_dim, dtype=torch.float32)) + self.decoder_token_emb = nn.Embedding(vocab_size, model_dim) + self.decoder_pos = nn.Parameter( + torch.zeros(patch_size, model_dim, dtype=torch.float32) + ) + self.decoder_cond = CastedLinear(latent_dim, model_dim, bias=False) + self.decoder_blocks = nn.ModuleList( + [ + Block( + model_dim, + decoder_heads, + decoder_heads, + mlp_mult, + rope_base, + qk_gain_init, + ) + for _ in range(decoder_layers) + ] + ) + self.decoder_norm = RMSNorm() + self.decoder_out = CastedLinear(model_dim, vocab_size, bias=False) 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) + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02) + nn.init.normal_(self.decoder_token_emb.weight, mean=0.0, std=0.02) + nn.init.normal_(self.patch_pos, mean=0.0, std=0.02) + nn.init.normal_(self.decoder_pos, mean=0.0, std=0.02) + nn.init.normal_(self.start_latent, mean=0.0, std=0.02) for module in self.modules(): if isinstance(module, nn.Linear) and getattr(module, "_zero_init", False): nn.init.zeros_(module.weight) - def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: - x = self.tok_emb(input_ids) + def _build_full_sequence( + self, input_ids: Tensor, target_ids: Tensor | None + ) -> Tensor: + if target_ids is None: + raise ValueError( + "BytePatchJEPA requires target_ids so it can reconstruct the full autoregressive stream" + ) + if input_ids.shape != target_ids.shape: + raise ValueError( + f"input_ids and target_ids must match, got {tuple(input_ids.shape)} vs {tuple(target_ids.shape)}" + ) + full = torch.cat((input_ids[:, :1], target_ids), dim=1) + if full.size(1) % self.patch_size != 0: + raise ValueError( + f"Sequence length {full.size(1)} must be divisible by PATCH_SIZE={self.patch_size}; " + "set TRAIN_SEQ_LEN so TRAIN_SEQ_LEN+1 is divisible by PATCH_SIZE" + ) + return full + + def _patchify(self, full_ids: Tensor) -> Tensor: + bsz, seqlen = full_ids.shape + num_patches = seqlen // self.patch_size + return full_ids.view(bsz, num_patches, self.patch_size) + + def _encode_patches(self, patches: Tensor) -> Tensor: + x = self.tok_emb(patches) + x = x + self.patch_pos.to(dtype=x.dtype)[None, None, :, :] x = F.rms_norm(x, (x.size(-1),)) + return self.patch_in(x.reshape(x.size(0), x.size(1), -1)) + + def _contextualize(self, patch_emb: Tensor) -> Tensor: + x = F.rms_norm(patch_emb, (patch_emb.size(-1),)) x0 = x - skips: list[Tensor] = [] - - # First half stores skips; second half reuses them in reverse order. - for i in range(self.num_encoder_layers): - x = self.blocks[i](x, x0) - skips.append(x) - for i in range(self.num_decoder_layers): - if skips: - x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() - x = self.blocks[self.num_encoder_layers + i](x, x0) - - x = self.final_norm(x).reshape(-1, x.size(-1)) - targets = target_ids.reshape(-1) - if self.tie_embeddings: - logits_proj = F.linear(x, self.tok_emb.weight) - else: - if self.lm_head is None: - raise RuntimeError("lm_head is required when tie_embeddings=False") - logits_proj = self.lm_head(x) - logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) - return F.cross_entropy(logits.float(), targets, reduction="mean") + for block in self.blocks: + x = block(x, x0) + return self.final_norm(x) + + def _decode_logits(self, cond_latent: Tensor, target_patches: Tensor) -> Tensor: + prev = torch.empty_like(target_patches) + prev[..., 0] = self.bos_id + prev[..., 1:] = target_patches[..., :-1] + x = self.decoder_token_emb(prev) + x = x + self.decoder_pos.to(dtype=x.dtype)[None, None, :, :] + x = x + self.decoder_cond(cond_latent).to(dtype=x.dtype)[:, :, None, :] + bsz, num_patches, patch_size, dim = x.shape + x = x.reshape(bsz * num_patches, patch_size, dim) + x0 = x + for block in self.decoder_blocks: + x = block(x, x0) + x = self.decoder_norm(x) + return self.decoder_out(x).reshape( + bsz, num_patches, patch_size, self.vocab_size + ) + + def forward( + self, input_ids: Tensor, target_ids: Tensor | None + ) -> tuple[Tensor, Tensor]: + full = self._build_full_sequence(input_ids, target_ids) + patches = self._patchify(full) + patch_emb = self._encode_patches(patches) + target_latent = self.projector(patch_emb) + context = self._contextualize(patch_emb) + pred_latent = self.predictor(context[:, :-1]) + pred_loss = F.mse_loss( + pred_latent.float(), target_latent[:, 1:].detach().float(), reduction="mean" + ) + sigreg_loss = self.sigreg(target_latent.transpose(0, 1)) + + start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( + patches.size(0), 1, -1 + ) + cond_latent = torch.cat((start, pred_latent), dim=1) + logits = self._decode_logits(cond_latent, patches) + ce = F.cross_entropy( + logits.reshape(-1, self.vocab_size).float(), + patches.reshape(-1), + reduction="none", + ) + ce = ce.reshape_as(patches).float() + mask = torch.ones_like(ce) + mask[:, 0, 0] = 0.0 + nll = (ce * mask).sum() / mask.sum() + total = ( + self.jepa_ce_weight * nll + + self.jepa_pred_weight * pred_loss + + self.sigreg_weight * sigreg_loss + ) + return total, nll # ----------------------------- # TRAINING # ----------------------------- + def main() -> None: global zeropower_via_newtonschulz5 @@ -746,7 +1006,9 @@ def main() -> None: 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") + 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(): @@ -761,7 +1023,12 @@ def main() -> None: # Fast math knobs torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True - from torch.backends.cuda import enable_cudnn_sdp, enable_flash_sdp, enable_math_sdp, enable_mem_efficient_sdp + 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) @@ -788,7 +1055,13 @@ def log0(msg: str, console: bool = True) -> None: 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, + subprocess.run( + ["nvidia-smi"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + check=False, + ).stdout, console=False, ) log0("=" * 100, console=False) @@ -802,20 +1075,18 @@ def log0(msg: str, console: bool = True) -> None: 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: + if (args.train_seq_len + 1) % args.patch_size != 0: raise ValueError( - f"VOCAB_SIZE={args.vocab_size} does not match tokenizer vocab_size={int(sp.vocab_size())}" + f"JEPA requires TRAIN_SEQ_LEN+1 to be divisible by PATCH_SIZE; " + f"got TRAIN_SEQ_LEN={args.train_seq_len}, PATCH_SIZE={args.patch_size}" ) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = load_pure_byte_luts( + args.tokenizer_path, args.vocab_size, device + ) 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"val_bpb:enabled tokenizer_kind=byte 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}") @@ -823,83 +1094,114 @@ def log0(msg: str, console: bool = True) -> None: # MODEL + OPTIMIZER SETUP # ----------------------------- - base_model = GPT( + base_model: nn.Module = BytePatchJEPA( vocab_size=args.vocab_size, num_layers=args.num_layers, model_dim=args.model_dim, num_heads=args.num_heads, num_kv_heads=args.num_kv_heads, mlp_mult=args.mlp_mult, - tie_embeddings=args.tie_embeddings, - tied_embed_init_std=args.tied_embed_init_std, - logit_softcap=args.logit_softcap, rope_base=args.rope_base, qk_gain_init=args.qk_gain_init, - ).to(device).bfloat16() + patch_size=args.patch_size, + latent_dim=args.latent_dim, + decoder_layers=args.decoder_layers, + decoder_heads=args.decoder_heads, + sigreg_knots=args.sigreg_knots, + sigreg_num_proj=args.sigreg_num_proj, + sigreg_weight=args.sigreg_weight, + jepa_pred_weight=args.jepa_pred_weight, + jepa_ce_weight=args.jepa_ce_weight, + ) + base_model = base_model.to(device).bfloat16() for module in base_model.modules(): if isinstance(module, CastedLinear): module.float() restore_low_dim_params_to_fp32(base_model) - compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) - model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if distributed else compiled_model - - # Optimizer split: - # - token embedding (Adam) uses EMBED_LR - # - untied lm_head (Adam) uses HEAD_LR - # - matrix params in transformer blocks use MATRIX_LR via Muon - # - vectors/scalars use SCALAR_LR via Adam - block_named_params = list(base_model.blocks.named_parameters()) - matrix_params = [ - p - for name, p in block_named_params - if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) - ] - scalar_params = [ - p - for name, p in block_named_params - if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) - ] - if base_model.skip_weights.numel() > 0: - scalar_params.append(base_model.skip_weights) - token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr - optimizer_tok = torch.optim.Adam( - [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}], - betas=(args.beta1, args.beta2), - eps=args.adam_eps, - fused=True, + compiled_model = ( + torch.compile(base_model, dynamic=False, fullgraph=False) + if args.use_compile + else base_model ) - optimizer_muon = Muon( - matrix_params, - lr=args.matrix_lr, - momentum=args.muon_momentum, - backend_steps=args.muon_backend_steps, + model: nn.Module = ( + DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) + if distributed + else compiled_model ) - for group in optimizer_muon.param_groups: - group["base_lr"] = args.matrix_lr - optimizer_scalar = torch.optim.Adam( - [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], - betas=(args.beta1, args.beta2), - eps=args.adam_eps, - fused=True, - ) - optimizers: list[torch.optim.Optimizer] = [optimizer_tok, optimizer_muon, optimizer_scalar] - if base_model.lm_head is not None: + + embedding_tags = ("tok_emb", "decoder_token_emb", "patch_pos", "decoder_pos") + head_names = {"decoder_out.weight"} + embedding_params: list[Tensor] = [] + head_params: list[Tensor] = [] + matrix_params: list[Tensor] = [] + scalar_params: list[Tensor] = [] + for name, param in base_model.named_parameters(): + if not param.requires_grad: + continue + if name in head_names: + head_params.append(param) + elif any(tag in name for tag in embedding_tags): + embedding_params.append(param) + elif param.ndim == 2 and not any( + pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS + ): + matrix_params.append(param) + else: + scalar_params.append(param) + + token_lr = args.embed_lr + optimizers: list[torch.optim.Optimizer] = [] + if embedding_params: + optimizer_embed = torch.optim.Adam( + [{"params": embedding_params, "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.append(optimizer_embed) + optimizer_muon = None + if matrix_params: + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizers.append(optimizer_muon) + if head_params: optimizer_head = torch.optim.Adam( - [{"params": [base_model.lm_head.weight], "lr": args.head_lr, "base_lr": args.head_lr}], + [{"params": head_params, "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) + optimizers.append(optimizer_head) + if scalar_params: + optimizer_scalar = torch.optim.Adam( + [ + { + "params": scalar_params, + "lr": args.scalar_lr, + "base_lr": args.scalar_lr, + } + ], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.append(optimizer_scalar) n_params = sum(p.numel() for p in base_model.parameters()) log0(f"model_params:{n_params}") log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") - log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") log0( - f"tie_embeddings:{args.tie_embeddings} embed_lr:{token_lr} " - f"head_lr:{args.head_lr if base_model.lm_head is not None else 0.0} " + f"model_family:jepa attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}" + ) + log0( + f"embed_lr:{token_lr} head_lr:{args.head_lr if head_params else 0.0} " f"matrix_lr:{args.matrix_lr} scalar_lr:{args.scalar_lr}" ) log0( @@ -907,6 +1209,11 @@ def log0(msg: str, console: bool = True) -> None: f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" ) + log0( + f"jepa:patch_size:{args.patch_size} latent_dim:{args.latent_dim} " + f"decoder_layers:{args.decoder_layers} decoder_heads:{args.decoder_heads} " + f"sigreg_weight:{args.sigreg_weight} pred_weight:{args.jepa_pred_weight} ce_weight:{args.jepa_ce_weight}" + ) log0(f"seed:{args.seed}") # ----------------------------- @@ -919,38 +1226,63 @@ 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 + 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 + 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 + return ( + remaining_ms / max(warmdown_ms, 1e-9) + if remaining_ms <= warmdown_ms + else 1.0 + ) # Warmup primes the compiled forward/backward/optimizer paths, then we restore the # initial weights/optimizer state so measured training starts from the true init. if args.warmup_steps > 0: - initial_model_state = {name: tensor.detach().cpu().clone() for name, tensor in base_model.state_dict().items()} - initial_optimizer_states = [copy.deepcopy(opt.state_dict()) for opt in optimizers] + 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) + 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: + 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): @@ -958,7 +1290,9 @@ def lr_mul(step: int, elapsed_ms: float) -> float: zero_grad_all() if distributed: model.require_backward_grad_sync = True - train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + train_loader = DistributedTokenLoader( + args.train_files, rank, world_size, device + ) # ----------------------------- # MAIN TRAINING LOOP @@ -971,9 +1305,13 @@ def lr_mul(step: int, elapsed_ms: float) -> float: step = 0 while True: - last_step = step == args.iterations or (stop_after_step is not None and step >= stop_after_step) + 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) + 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) @@ -1008,20 +1346,32 @@ def lr_mul(step: int, elapsed_ms: float) -> float: scale = lr_mul(step, elapsed_ms) zero_grad_all() train_loss = torch.zeros((), device=device) + train_nll = 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) + 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) + loss, nll = model(x, y) train_loss += loss.detach() + train_nll += nll.detach() (loss * grad_scale).backward() train_loss /= grad_accum_steps + train_nll /= 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 + if optimizer_muon is not None: + 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: @@ -1035,18 +1385,22 @@ def lr_mul(step: int, elapsed_ms: float) -> float: 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) + 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" + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms " + f"train_nll:{train_nll.item():.4f}" ) # Needed to sync whether we've reached the wallclock cap. - reached_cap = max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + 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) @@ -1084,7 +1438,9 @@ def lr_mul(step: int, elapsed_ms: float) -> float: 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) + ratio = quant_stats["baseline_tensor_bytes"] / max( + quant_stats["int8_payload_bytes"], 1 + ) log0( f"Serialized model int8+zlib: {quant_file_bytes} bytes " f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" @@ -1095,7 +1451,9 @@ def lr_mul(step: int, elapsed_ms: float) -> float: dist.barrier() with open("final_model.int8.ptz", "rb") as f: quant_blob_disk = f.read() - quant_state = torch.load(io.BytesIO(zlib.decompress(quant_blob_disk)), map_location="cpu") + quant_state = torch.load( + io.BytesIO(zlib.decompress(quant_blob_disk)), map_location="cpu" + ) base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) torch.cuda.synchronize() t_qeval = time.perf_counter() @@ -1116,7 +1474,9 @@ def lr_mul(step: int, elapsed_ms: float) -> float: 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}") + log0( + f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}" + ) if distributed: dist.destroy_process_group() From d69711b504e9ca5b4849a11525083704cec1fbb0 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 16:05:19 -0700 Subject: [PATCH 02/25] Switch tokenizer config to pure byte export --- data/tokenizer_specs.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/data/tokenizer_specs.json b/data/tokenizer_specs.json index d7ad1ca05..28e6f9b40 100644 --- a/data/tokenizer_specs.json +++ b/data/tokenizer_specs.json @@ -1,9 +1,10 @@ { "tokenizers": [ { - "name": "sp_bpe_1024", - "dataset_suffix": "sp1024", - "vocab_size": 1024 + "name": "pure_byte_260", + "kind": "pure_byte", + "dataset_suffix": "byte260", + "filename": "fineweb_pure_byte_260.json" } ] } From ea4df4ddf0f42d09bc5e9b906b66f3393516b2ba Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 17:13:51 -0700 Subject: [PATCH 03/25] Make JEPA target loss fully end-to-end --- train_gpt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/train_gpt.py b/train_gpt.py index 4471ec8fb..2e118f4ba 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -957,7 +957,7 @@ def forward( context = self._contextualize(patch_emb) pred_latent = self.predictor(context[:, :-1]) pred_loss = F.mse_loss( - pred_latent.float(), target_latent[:, 1:].detach().float(), reduction="mean" + pred_latent.float(), target_latent[:, 1:].float(), reduction="mean" ) sigreg_loss = self.sigreg(target_latent.transpose(0, 1)) From 7ed0372453e39428da13e68403d1c008c8692d66 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 17:27:40 -0700 Subject: [PATCH 04/25] Restore detached JEPA target loss --- train_gpt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/train_gpt.py b/train_gpt.py index 2e118f4ba..4471ec8fb 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -957,7 +957,7 @@ def forward( context = self._contextualize(patch_emb) pred_latent = self.predictor(context[:, :-1]) pred_loss = F.mse_loss( - pred_latent.float(), target_latent[:, 1:].float(), reduction="mean" + pred_latent.float(), target_latent[:, 1:].detach().float(), reduction="mean" ) sigreg_loss = self.sigreg(target_latent.transpose(0, 1)) From 60682ed82139deb577e640169a6b2d9f3665bd72 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 18:38:25 -0700 Subject: [PATCH 05/25] Full-sequence byte decoder with cross-patch causal attention Replace the isolated per-patch decoder (8-byte window with no cross-patch information flow) with a full-sequence causal decoder over all bytes. Each byte can now attend to all preceding bytes across patch boundaries, with patch-level context upsampled and added as conditioning. This removes the critical information bottleneck where byte predictions at patch boundaries had no access to preceding bytes from other patches. --- train_gpt.py | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index 4471ec8fb..b5a25f76f 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -862,9 +862,6 @@ def __init__( self.start_latent = nn.Parameter(torch.zeros(latent_dim, dtype=torch.float32)) self.decoder_token_emb = nn.Embedding(vocab_size, model_dim) - self.decoder_pos = nn.Parameter( - torch.zeros(patch_size, model_dim, dtype=torch.float32) - ) self.decoder_cond = CastedLinear(latent_dim, model_dim, bias=False) self.decoder_blocks = nn.ModuleList( [ @@ -887,7 +884,6 @@ def _init_weights(self) -> None: nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02) nn.init.normal_(self.decoder_token_emb.weight, mean=0.0, std=0.02) nn.init.normal_(self.patch_pos, mean=0.0, std=0.02) - nn.init.normal_(self.decoder_pos, mean=0.0, std=0.02) nn.init.normal_(self.start_latent, mean=0.0, std=0.02) for module in self.modules(): if isinstance(module, nn.Linear) and getattr(module, "_zero_init", False): @@ -931,14 +927,15 @@ def _contextualize(self, patch_emb: Tensor) -> Tensor: return self.final_norm(x) def _decode_logits(self, cond_latent: Tensor, target_patches: Tensor) -> Tensor: - prev = torch.empty_like(target_patches) - prev[..., 0] = self.bos_id - prev[..., 1:] = target_patches[..., :-1] + bsz, num_patches, patch_size = target_patches.shape + total_bytes = num_patches * patch_size + flat_bytes = target_patches.reshape(bsz, total_bytes) + prev = torch.cat( + [flat_bytes.new_full((bsz, 1), self.bos_id), flat_bytes[:, :-1]], dim=1 + ) x = self.decoder_token_emb(prev) - x = x + self.decoder_pos.to(dtype=x.dtype)[None, None, :, :] - x = x + self.decoder_cond(cond_latent).to(dtype=x.dtype)[:, :, None, :] - bsz, num_patches, patch_size, dim = x.shape - x = x.reshape(bsz * num_patches, patch_size, dim) + cond = self.decoder_cond(cond_latent).to(dtype=x.dtype) + x = x + cond.repeat_interleave(patch_size, dim=1) x0 = x for block in self.decoder_blocks: x = block(x, x0) @@ -1129,7 +1126,7 @@ def log0(msg: str, console: bool = True) -> None: else compiled_model ) - embedding_tags = ("tok_emb", "decoder_token_emb", "patch_pos", "decoder_pos") + embedding_tags = ("tok_emb", "decoder_token_emb", "patch_pos") head_names = {"decoder_out.weight"} embedding_params: list[Tensor] = [] head_params: list[Tensor] = [] From 4c105379535d7151aed50afa727d462cafbef4fd Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 19:22:10 -0700 Subject: [PATCH 06/25] Rebalance params: depth-recurrent encoder (5x2) + 6-layer decoder Shift parameter budget from the encoder to the decoder, where val_bpb is determined. Encoder goes from 10 unique blocks to 5 unique blocks cycled 2x (same 10 effective layers, half the unique params). Decoder grows from 2 to 6 layers, tripling capacity for byte-level prediction. Total unique params drops ~1.5M but decoder gets ~4M more. --- train_gpt.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index b5a25f76f..71d07d325 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -66,7 +66,8 @@ class Hyperparameters: # Model shape. vocab_size = int(os.environ.get("VOCAB_SIZE", 260)) - num_layers = int(os.environ.get("NUM_LAYERS", 10)) + num_layers = int(os.environ.get("NUM_LAYERS", 5)) + encoder_repeats = int(os.environ.get("ENCODER_REPEATS", 2)) num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 3)) model_dim = int(os.environ.get("MODEL_DIM", 384)) num_heads = int(os.environ.get("NUM_HEADS", 6)) @@ -74,7 +75,7 @@ class Hyperparameters: rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) patch_size = int(os.environ.get("PATCH_SIZE", 8)) latent_dim = int(os.environ.get("LATENT_DIM", 192)) - decoder_layers = int(os.environ.get("DECODER_LAYERS", 2)) + decoder_layers = int(os.environ.get("DECODER_LAYERS", 6)) decoder_heads = int(os.environ.get("DECODER_HEADS", 4)) sigreg_weight = float(os.environ.get("SIGREG_WEIGHT", 0.02)) sigreg_knots = int(os.environ.get("SIGREG_KNOTS", 17)) @@ -807,6 +808,7 @@ def __init__( *, vocab_size: int, num_layers: int, + encoder_repeats: int, model_dim: int, num_heads: int, num_kv_heads: int, @@ -832,6 +834,7 @@ def __init__( ) self.vocab_size = vocab_size self.patch_size = patch_size + self.encoder_repeats = encoder_repeats self.sigreg_weight = sigreg_weight self.jepa_pred_weight = jepa_pred_weight self.jepa_ce_weight = jepa_ce_weight @@ -922,8 +925,9 @@ def _encode_patches(self, patches: Tensor) -> Tensor: def _contextualize(self, patch_emb: Tensor) -> Tensor: x = F.rms_norm(patch_emb, (patch_emb.size(-1),)) x0 = x - for block in self.blocks: - x = block(x, x0) + for _ in range(self.encoder_repeats): + for block in self.blocks: + x = block(x, x0) return self.final_norm(x) def _decode_logits(self, cond_latent: Tensor, target_patches: Tensor) -> Tensor: @@ -1094,6 +1098,7 @@ def log0(msg: str, console: bool = True) -> None: base_model: nn.Module = BytePatchJEPA( vocab_size=args.vocab_size, num_layers=args.num_layers, + encoder_repeats=args.encoder_repeats, model_dim=args.model_dim, num_heads=args.num_heads, num_kv_heads=args.num_kv_heads, @@ -1208,6 +1213,7 @@ def log0(msg: str, console: bool = True) -> None: ) log0( f"jepa:patch_size:{args.patch_size} latent_dim:{args.latent_dim} " + f"encoder_layers:{args.num_layers}x{args.encoder_repeats} " f"decoder_layers:{args.decoder_layers} decoder_heads:{args.decoder_heads} " f"sigreg_weight:{args.sigreg_weight} pred_weight:{args.jepa_pred_weight} ce_weight:{args.jepa_ce_weight}" ) From 7cdf6511d95c870f9eb52c389a16bf1107151ed4 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 19:40:53 -0700 Subject: [PATCH 07/25] Teacher-forced decoder: condition on encoder context, not predicted latents Replace the decoder's conditioning signal from pred_latent (predictor's noisy estimate, routed through a latent_dim bottleneck) with the encoder's context output directly (model_dim, shifted by 1 patch for causality). The JEPA predictor + MSE loss remain as an auxiliary training objective, but the decoder now receives the exact encoder representations instead of a noisy compressed proxy. Removes decoder_cond projection layer since context is already model_dim. --- train_gpt.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index 71d07d325..9a6ce5122 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -863,9 +863,8 @@ def __init__( self.predictor = LatentMLP(model_dim, latent_dim) self.sigreg = SIGReg(knots=sigreg_knots, num_proj=sigreg_num_proj) - self.start_latent = nn.Parameter(torch.zeros(latent_dim, dtype=torch.float32)) + self.start_context = nn.Parameter(torch.zeros(model_dim, dtype=torch.float32)) self.decoder_token_emb = nn.Embedding(vocab_size, model_dim) - self.decoder_cond = CastedLinear(latent_dim, model_dim, bias=False) self.decoder_blocks = nn.ModuleList( [ Block( @@ -887,7 +886,7 @@ def _init_weights(self) -> None: nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02) nn.init.normal_(self.decoder_token_emb.weight, mean=0.0, std=0.02) nn.init.normal_(self.patch_pos, mean=0.0, std=0.02) - nn.init.normal_(self.start_latent, mean=0.0, std=0.02) + nn.init.normal_(self.start_context, mean=0.0, std=0.02) for module in self.modules(): if isinstance(module, nn.Linear) and getattr(module, "_zero_init", False): nn.init.zeros_(module.weight) @@ -938,8 +937,7 @@ def _decode_logits(self, cond_latent: Tensor, target_patches: Tensor) -> Tensor: [flat_bytes.new_full((bsz, 1), self.bos_id), flat_bytes[:, :-1]], dim=1 ) x = self.decoder_token_emb(prev) - cond = self.decoder_cond(cond_latent).to(dtype=x.dtype) - x = x + cond.repeat_interleave(patch_size, dim=1) + x = x + cond_latent.to(dtype=x.dtype).repeat_interleave(patch_size, dim=1) x0 = x for block in self.decoder_blocks: x = block(x, x0) @@ -962,11 +960,11 @@ def forward( ) sigreg_loss = self.sigreg(target_latent.transpose(0, 1)) - start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( + start = self.start_context.to(dtype=context.dtype)[None, None, :].expand( patches.size(0), 1, -1 ) - cond_latent = torch.cat((start, pred_latent), dim=1) - logits = self._decode_logits(cond_latent, patches) + cond_context = torch.cat((start, context[:, :-1]), dim=1) + logits = self._decode_logits(cond_context, patches) ce = F.cross_entropy( logits.reshape(-1, self.vocab_size).float(), patches.reshape(-1), From b773b911267e860eb77a2a0cafb3f78dee7cb6bd Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 19:56:17 -0700 Subject: [PATCH 08/25] Revert "Teacher-forced decoder: condition on encoder context, not predicted latents" This reverts commit 7cdf6511d95c870f9eb52c389a16bf1107151ed4. --- train_gpt.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index 9a6ce5122..71d07d325 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -863,8 +863,9 @@ def __init__( self.predictor = LatentMLP(model_dim, latent_dim) self.sigreg = SIGReg(knots=sigreg_knots, num_proj=sigreg_num_proj) - self.start_context = nn.Parameter(torch.zeros(model_dim, dtype=torch.float32)) + self.start_latent = nn.Parameter(torch.zeros(latent_dim, dtype=torch.float32)) self.decoder_token_emb = nn.Embedding(vocab_size, model_dim) + self.decoder_cond = CastedLinear(latent_dim, model_dim, bias=False) self.decoder_blocks = nn.ModuleList( [ Block( @@ -886,7 +887,7 @@ def _init_weights(self) -> None: nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02) nn.init.normal_(self.decoder_token_emb.weight, mean=0.0, std=0.02) nn.init.normal_(self.patch_pos, mean=0.0, std=0.02) - nn.init.normal_(self.start_context, mean=0.0, std=0.02) + nn.init.normal_(self.start_latent, mean=0.0, std=0.02) for module in self.modules(): if isinstance(module, nn.Linear) and getattr(module, "_zero_init", False): nn.init.zeros_(module.weight) @@ -937,7 +938,8 @@ def _decode_logits(self, cond_latent: Tensor, target_patches: Tensor) -> Tensor: [flat_bytes.new_full((bsz, 1), self.bos_id), flat_bytes[:, :-1]], dim=1 ) x = self.decoder_token_emb(prev) - x = x + cond_latent.to(dtype=x.dtype).repeat_interleave(patch_size, dim=1) + cond = self.decoder_cond(cond_latent).to(dtype=x.dtype) + x = x + cond.repeat_interleave(patch_size, dim=1) x0 = x for block in self.decoder_blocks: x = block(x, x0) @@ -960,11 +962,11 @@ def forward( ) sigreg_loss = self.sigreg(target_latent.transpose(0, 1)) - start = self.start_context.to(dtype=context.dtype)[None, None, :].expand( + start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( patches.size(0), 1, -1 ) - cond_context = torch.cat((start, context[:, :-1]), dim=1) - logits = self._decode_logits(cond_context, patches) + cond_latent = torch.cat((start, pred_latent), dim=1) + logits = self._decode_logits(cond_latent, patches) ce = F.cross_entropy( logits.reshape(-1, self.vocab_size).float(), patches.reshape(-1), From a43966c00007b18cfd1ea4d6a6e2969dd39aa897 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 19:56:26 -0700 Subject: [PATCH 09/25] Rebalance loss: CE weight 3.0, pred weight 0.5 The JEPA prediction loss had 2x the gradient weight of the actual compression objective (CE). Flip the ratio: CE gets 3x weight, pred gets 0.5x. This directs more gradient signal toward byte-level prediction quality, with JEPA serving as a lighter regularizer. --- train_gpt.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index 71d07d325..f7bc3bc95 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -80,8 +80,8 @@ class Hyperparameters: sigreg_weight = float(os.environ.get("SIGREG_WEIGHT", 0.02)) sigreg_knots = int(os.environ.get("SIGREG_KNOTS", 17)) sigreg_num_proj = int(os.environ.get("SIGREG_NUM_PROJ", 256)) - jepa_pred_weight = float(os.environ.get("JEPA_PRED_WEIGHT", 2.0)) - jepa_ce_weight = float(os.environ.get("JEPA_CE_WEIGHT", 1.0)) + jepa_pred_weight = float(os.environ.get("JEPA_PRED_WEIGHT", 0.5)) + jepa_ce_weight = float(os.environ.get("JEPA_CE_WEIGHT", 3.0)) # Optimizer hyperparameters. embed_lr = float(os.environ.get("EMBED_LR", 0.1)) From 73d2645aad8ef35f6669db75ee0e590d84dbfbc0 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 20:16:06 -0700 Subject: [PATCH 10/25] Scale up model to fill 16MB budget: dim 480, 8 decoder layers Current compressed model is only 9MB of the 16MB limit. Increase model_dim from 384 to 480 and decoder_layers from 6 to 8, bringing total params from ~14.7M to ~26.4M (compressed ~15.8MB). Nearly all the extra capacity goes to the decoder where val_bpb is determined. --- train_gpt.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index f7bc3bc95..d269e0d12 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -69,13 +69,13 @@ class Hyperparameters: num_layers = int(os.environ.get("NUM_LAYERS", 5)) encoder_repeats = int(os.environ.get("ENCODER_REPEATS", 2)) num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 3)) - model_dim = int(os.environ.get("MODEL_DIM", 384)) + model_dim = int(os.environ.get("MODEL_DIM", 480)) num_heads = int(os.environ.get("NUM_HEADS", 6)) mlp_mult = int(os.environ.get("MLP_MULT", 2)) rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) patch_size = int(os.environ.get("PATCH_SIZE", 8)) latent_dim = int(os.environ.get("LATENT_DIM", 192)) - decoder_layers = int(os.environ.get("DECODER_LAYERS", 6)) + decoder_layers = int(os.environ.get("DECODER_LAYERS", 8)) decoder_heads = int(os.environ.get("DECODER_HEADS", 4)) sigreg_weight = float(os.environ.get("SIGREG_WEIGHT", 0.02)) sigreg_knots = int(os.environ.get("SIGREG_KNOTS", 17)) From cec28e9d1eb9cce5d77198f1ab066360f9f595ec Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 21:51:50 -0700 Subject: [PATCH 11/25] Add sliding window evaluation for final val_bpb Sliding window eval scores each byte with near-maximum context. Windows of seq_len advance by stride (default 512 bytes = 64 patches). Only the tail stride bytes per window are scored (first window scores all). Adds forward_logits() method that returns per-position logits without computing loss. Only the final int8+zlib roundtrip eval uses sliding window; periodic training eval stays fast (non-overlapping). --- train_gpt.py | 103 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 100 insertions(+), 3 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index d269e0d12..2dd946264 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -52,6 +52,8 @@ class Hyperparameters: # Validation cadence and batch size. Validation always uses the full fineweb_val split. val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_160)) val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) + val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 512)) + val_sliding_batch = int(os.environ.get("VAL_SLIDING_BATCH", 8)) train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200)) # Training length. @@ -322,6 +324,86 @@ def eval_val( return float(val_loss.item()), float(bits_per_token * tokens_per_byte) +def eval_val_sliding( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + seq_len = args.train_seq_len + stride = args.val_sliding_stride + batch_seqs = args.val_sliding_batch + total_tokens = val_tokens.numel() - 1 + + window_starts = [ + ws for ws in range(0, total_tokens, stride) + if min(ws + seq_len, total_tokens) - ws >= seq_len + ] + total_windows = len(window_starts) + my_s = (total_windows * rank) // world_size + my_e = (total_windows * (rank + 1)) // world_size + my_windows = window_starts[my_s:my_e] + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + base_model.eval() + with torch.inference_mode(): + for bi in range(0, len(my_windows), batch_seqs): + batch_ws = my_windows[bi : bi + batch_seqs] + bsz = len(batch_ws) + x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) + for i, ws in enumerate(batch_ws): + chunk = val_tokens[ws : ws + seq_len + 1].to( + dtype=torch.int64, device=device + ) + x_batch[i] = chunk[:-1] + y_batch[i] = chunk[1:] + + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch, y_batch) + + # logits[:, 0] predicts full[0] = x[0] (skip it) + # logits[:, k] predicts full[k] = y[k-1] for k >= 1 + nll = F.cross_entropy( + logits[:, 1:].reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + + for i, ws in enumerate(batch_ws): + score_start = 0 if ws == 0 else seq_len - stride + scored = nll[i, score_start:seq_len].to(torch.float64) + loss_sum += scored.sum() + n = seq_len - score_start + token_count += float(n) + tgt = y_batch[i, score_start:seq_len] + prev = x_batch[i, score_start:seq_len] + 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() + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) + + val_loss = loss_sum / token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = token_count.item() / byte_count.item() + base_model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + # ----------------------------- # POST-TRAINING QUANTIZATION # ----------------------------- @@ -983,6 +1065,22 @@ def forward( ) return total, nll + def forward_logits( + self, input_ids: Tensor, target_ids: Tensor + ) -> Tensor: + full = self._build_full_sequence(input_ids, target_ids) + patches = self._patchify(full) + patch_emb = self._encode_patches(patches) + context = self._contextualize(patch_emb) + pred_latent = self.predictor(context[:, :-1]) + start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( + patches.size(0), 1, -1 + ) + cond_latent = torch.cat((start, pred_latent), dim=1) + logits = self._decode_logits(cond_latent, patches) + bsz = logits.size(0) + return logits.reshape(bsz, -1, self.vocab_size) + # ----------------------------- # TRAINING @@ -1460,13 +1558,12 @@ def lr_mul(step: int, elapsed_ms: float) -> float: 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( + q_val_loss, q_val_bpb = eval_val_sliding( args, - model, + base_model, rank, world_size, device, - grad_accum_steps, val_tokens, base_bytes_lut, has_leading_space_lut, From 2380ba9095e3da073cd6ab38d1e127c5290a5739 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 22:28:29 -0700 Subject: [PATCH 12/25] =?UTF-8?q?Add=20LeakyReLU(0.5)=C2=B2,=20EMA+SWA,=20?= =?UTF-8?q?and=20test-time=20training?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - MLP activation: relu² → LeakyReLU(0.5)² (matching SOTA) - EMA weight averaging (decay=0.997) applied before serialization - SWA snapshots collected every 50 steps when lr scale < 0.2 - Test-time training: score-first legal TTT with SGD (lr=0.002, momentum=0.9, 3 epochs, 32K chunks, cosine LR decay) - Eval stride reduced to 64 (matching SOTA) --- train_gpt.py | 228 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 226 insertions(+), 2 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index 2dd946264..bb9de1041 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -52,8 +52,18 @@ class Hyperparameters: # Validation cadence and batch size. Validation always uses the full fineweb_val split. val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_160)) val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) - val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 512)) + val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 64)) val_sliding_batch = int(os.environ.get("VAL_SLIDING_BATCH", 8)) + ema_decay = float(os.environ.get("EMA_DECAY", 0.997)) + swa_every = int(os.environ.get("SWA_EVERY", 50)) + 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", 0)) + ttt_momentum = float(os.environ.get("TTT_MOMENTUM", 0.9)) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", 8)) + ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", 1.0)) train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200)) # Training length. @@ -404,6 +414,164 @@ def eval_val_sliding( return float(val_loss.item()), float(bits_per_token * tokens_per_byte) +def eval_val_sliding_ttt( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, + log_fn=print, +) -> tuple[float, float]: + seq_len = args.train_seq_len + stride = args.val_sliding_stride + batch_seqs = args.ttt_batch_seqs + 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 >= seq_len + ] + 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) + + log_fn( + f"ttt:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"windows={len(window_starts)} stride={stride} " + f"lr={args.ttt_lr} epochs={args.ttt_epochs} freeze={args.ttt_freeze_blocks}" + ) + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + 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 + + 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) + for i, ws in enumerate(batch_ws): + chunk_tok = val_tokens[ws : ws + seq_len + 1].to( + dtype=torch.int64, device=device + ) + x_batch[i] = chunk_tok[:-1] + y_batch[i] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch, y_batch) + nll = F.cross_entropy( + logits[:, 1:].reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + s = 0 if ws == 0 else seq_len - stride + scored = nll[i, s:seq_len].to(torch.float64) + loss_sum += scored.sum() + token_count += float(seq_len - s) + tgt = y_batch[i, s:seq_len] + prev = x_batch[i, s:seq_len] + 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_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + 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 + for _ep in range(args.ttt_epochs): + for bs in range(my_seq_s, my_seq_e, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_seq_e) + start_tok = chunk_start + bs * seq_len + end_tok = chunk_start + 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): + total_loss, _ = base_model(x, y) + total_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 % 50 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = ( + rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) + if token_count.item() > 0 + else 0.0 + ) + log_fn(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() + return val_loss, val_bpb + + # ----------------------------- # POST-TRAINING QUANTIZATION # ----------------------------- @@ -802,7 +970,7 @@ def __init__(self, dim: int, mlp_mult: int): self.proj._zero_init = True def forward(self, x: Tensor) -> Tensor: - x = torch.relu(self.fc(x)) + x = F.leaky_relu(self.fc(x), negative_slope=0.5) return self.proj(x.square()) @@ -1399,6 +1567,13 @@ def lr_mul(step: int, elapsed_ms: float) -> float: # MAIN TRAINING LOOP # ----------------------------- + ema_state = { + name: t.detach().float().clone() + for name, t in base_model.state_dict().items() + } + swa_state: dict[str, Tensor] | None = None + swa_count = 0 + training_time_ms = 0.0 stop_after_step: int | None = None torch.cuda.synchronize() @@ -1484,6 +1659,23 @@ def lr_mul(step: int, elapsed_ms: float) -> float: opt.step() zero_grad_all() + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(args.ema_decay).add_( + t.detach().float(), alpha=1.0 - args.ema_decay + ) + if scale < 0.2 and (step + 1) % args.swa_every == 0: + if swa_state is None: + swa_state = { + name: t.detach().float().clone() + for name, t in base_model.state_dict().items() + } + swa_count = 1 + else: + for name, t in base_model.state_dict().items(): + swa_state[name] += t.detach().float() + swa_count += 1 + step += 1 approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) should_log_train = args.train_log_every > 0 and ( @@ -1514,6 +1706,15 @@ def lr_mul(step: int, elapsed_ms: float) -> float: f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" ) + current_sd = base_model.state_dict() + ema_avg = { + name: t.to(dtype=current_sd[name].dtype) for name, t in ema_state.items() + } + base_model.load_state_dict(ema_avg, strict=True) + log0(f"ema:applied EMA weights (decay={args.ema_decay})") + if swa_state is not None and swa_count > 0: + log0(f"swa:collected {swa_count} snapshots (not applied, using EMA)") + # ----------------------------- # SERIALIZATION + ROUNDTRIP VALIDATION # ----------------------------- @@ -1578,6 +1779,29 @@ def lr_mul(step: int, elapsed_ms: float) -> float: f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}" ) + if args.ttt_enabled: + base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb = eval_val_sliding_ttt( + args, + base_model, + rank, + world_size, + device, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + log_fn=log0, + ) + torch.cuda.synchronize() + log0( + f"final_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms" + ) + log0(f"final_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + if distributed: dist.destroy_process_group() From 1e7a26eb98ad4a97fc11fcac6004adaa0f5f1aed Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 22:38:45 -0700 Subject: [PATCH 13/25] Apply SWA weights during warmdown and use pure CE for TTT SWA snapshots collected during warmdown are now averaged and applied instead of being discarded. TTT adaptation uses forward_logits + CE loss directly, avoiding unnecessary prediction/SIGReg gradient signal. --- train_gpt.py | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index bb9de1041..d7bcc75dd 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -539,8 +539,12 @@ def eval_val_sliding_ttt( y = local[1:].reshape(-1, seq_len) optimizer.zero_grad(set_to_none=True) with torch.autocast(device_type="cuda", dtype=torch.bfloat16): - total_loss, _ = base_model(x, y) - total_loss.backward() + logits = base_model.forward_logits(x, y) + ce = F.cross_entropy( + logits[:, 1:].reshape(-1, logits.size(-1)).float(), + y.reshape(-1), + ) + ce.backward() if world_size > 1: for p in ttt_params: if p.grad is not None: @@ -1707,13 +1711,19 @@ def lr_mul(step: int, elapsed_ms: float) -> float: ) current_sd = base_model.state_dict() - ema_avg = { - name: t.to(dtype=current_sd[name].dtype) for name, t in ema_state.items() - } - base_model.load_state_dict(ema_avg, strict=True) - log0(f"ema:applied EMA weights (decay={args.ema_decay})") - if swa_state is not None and swa_count > 0: - log0(f"swa:collected {swa_count} snapshots (not applied, using EMA)") + if swa_state is not None and swa_count > 1: + swa_avg = { + name: (t / swa_count).to(dtype=current_sd[name].dtype) + for name, t in swa_state.items() + } + base_model.load_state_dict(swa_avg, strict=True) + log0(f"swa:applied SWA weights ({swa_count} snapshots, every {args.swa_every} steps)") + else: + ema_avg = { + name: t.to(dtype=current_sd[name].dtype) for name, t in ema_state.items() + } + base_model.load_state_dict(ema_avg, strict=True) + log0(f"ema:applied EMA weights (decay={args.ema_decay})") # ----------------------------- # SERIALIZATION + ROUNDTRIP VALIDATION From 4c6d3ad30ee2570e6089ca36fb5499852e465c7f Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 22:41:45 -0700 Subject: [PATCH 14/25] Remove SWA, use EMA-only weight averaging --- train_gpt.py | 34 +++++----------------------------- 1 file changed, 5 insertions(+), 29 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index d7bcc75dd..75f03bb0f 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -55,7 +55,6 @@ class Hyperparameters: val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 64)) val_sliding_batch = int(os.environ.get("VAL_SLIDING_BATCH", 8)) ema_decay = float(os.environ.get("EMA_DECAY", 0.997)) - swa_every = int(os.environ.get("SWA_EVERY", 50)) 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)) @@ -1575,9 +1574,6 @@ def lr_mul(step: int, elapsed_ms: float) -> float: name: t.detach().float().clone() for name, t in base_model.state_dict().items() } - swa_state: dict[str, Tensor] | None = None - swa_count = 0 - training_time_ms = 0.0 stop_after_step: int | None = None torch.cuda.synchronize() @@ -1668,18 +1664,6 @@ def lr_mul(step: int, elapsed_ms: float) -> float: ema_state[name].mul_(args.ema_decay).add_( t.detach().float(), alpha=1.0 - args.ema_decay ) - if scale < 0.2 and (step + 1) % args.swa_every == 0: - if swa_state is None: - swa_state = { - name: t.detach().float().clone() - for name, t in base_model.state_dict().items() - } - swa_count = 1 - else: - for name, t in base_model.state_dict().items(): - swa_state[name] += t.detach().float() - swa_count += 1 - step += 1 approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) should_log_train = args.train_log_every > 0 and ( @@ -1711,19 +1695,11 @@ def lr_mul(step: int, elapsed_ms: float) -> float: ) current_sd = base_model.state_dict() - if swa_state is not None and swa_count > 1: - swa_avg = { - name: (t / swa_count).to(dtype=current_sd[name].dtype) - for name, t in swa_state.items() - } - base_model.load_state_dict(swa_avg, strict=True) - log0(f"swa:applied SWA weights ({swa_count} snapshots, every {args.swa_every} steps)") - else: - ema_avg = { - name: t.to(dtype=current_sd[name].dtype) for name, t in ema_state.items() - } - base_model.load_state_dict(ema_avg, strict=True) - log0(f"ema:applied EMA weights (decay={args.ema_decay})") + ema_avg = { + name: t.to(dtype=current_sd[name].dtype) for name, t in ema_state.items() + } + base_model.load_state_dict(ema_avg, strict=True) + log0(f"ema:applied EMA weights (decay={args.ema_decay})") # ----------------------------- # SERIALIZATION + ROUNDTRIP VALIDATION From 9a74c9583b8191f04b5ebe0f2fc29a7539f0e611 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 23:16:58 -0700 Subject: [PATCH 15/25] INT6 optimal-clip quantization, late QAT, LZMA compression Replace INT8+zlib with mixed INT6/INT8+LZMA to reduce serialized model size. MLP/attn/other weights use INT6 ([-31,31]) with per-row MSE-optimal clip search; embeddings stay INT8. Add STE quantization-aware training that activates during warmdown (LR scale < 0.15). Switch compression from zlib to LZMA for better entropy exploitation on low-range values. Also bump eval batch defaults (val_sliding_batch, ttt_batch_seqs) from 8 to 32 to match SOTA, and add infer/adapt timing breakdown to TTT logs. --- train_gpt.py | 290 ++++++++++++++++++++++++++++----------------------- 1 file changed, 157 insertions(+), 133 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index 75f03bb0f..7b1e52979 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -10,6 +10,7 @@ import glob import io import json +import lzma import math import os import random @@ -17,7 +18,7 @@ import sys import time import uuid -import zlib + from pathlib import Path import numpy as np @@ -53,15 +54,16 @@ class Hyperparameters: val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_160)) val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 64)) - val_sliding_batch = int(os.environ.get("VAL_SLIDING_BATCH", 8)) + val_sliding_batch = int(os.environ.get("VAL_SLIDING_BATCH", 32)) ema_decay = float(os.environ.get("EMA_DECAY", 0.997)) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", 0.15)) 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", 0)) ttt_momentum = float(os.environ.get("TTT_MOMENTUM", 0.9)) - ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", 8)) + ttt_batch_seqs = int(os.environ.get("TTT_BATCH_SEQS", 32)) ttt_grad_clip = float(os.environ.get("TTT_GRAD_CLIP", 1.0)) train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200)) @@ -467,6 +469,8 @@ def eval_val_sliding_ttt( optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) t0 = time.perf_counter() + t_infer_total = 0.0 + t_adapt_total = 0.0 for ci in range(num_chunks): windows = chunk_windows[ci] @@ -477,6 +481,8 @@ def eval_val_sliding_ttt( my_e = (len(windows) * (rank + 1)) // world_size my_windows = windows[my_s:my_e] + torch.cuda.synchronize() + t_infer = time.perf_counter() base_model.eval() with torch.inference_mode(): for bi in range(0, len(my_windows), batch_seqs): @@ -510,7 +516,11 @@ def eval_val_sliding_ttt( ).to(torch.float64) byte_count += tb.sum() + torch.cuda.synchronize() + t_infer_total += time.perf_counter() - t_infer + is_last_chunk = ci == num_chunks - 1 + t_adapt = time.perf_counter() if not is_last_chunk and args.ttt_epochs > 0: base_model.train() chunk_start = ci * ttt_chunk @@ -551,6 +561,9 @@ def eval_val_sliding_ttt( torch.nn.utils.clip_grad_norm_(ttt_params, args.ttt_grad_clip) optimizer.step() + torch.cuda.synchronize() + t_adapt_total += time.perf_counter() - t_adapt + if rank == 0 and (ci % 50 == 0 or ci == num_chunks - 1): elapsed = time.perf_counter() - t0 rl = loss_sum.item() / max(token_count.item(), 1) @@ -559,7 +572,10 @@ def eval_val_sliding_ttt( if token_count.item() > 0 else 0.0 ) - log_fn(f" ttt_chunk [{ci + 1}/{num_chunks}] bpb={rbpb:.6f} time={elapsed:.1f}s") + log_fn( + f" ttt_chunk [{ci + 1}/{num_chunks}] bpb={rbpb:.6f} " + f"time={elapsed:.1f}s infer={t_infer_total:.1f}s adapt={t_adapt_total:.1f}s" + ) if dist.is_available() and dist.is_initialized(): dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) @@ -591,36 +607,12 @@ def eval_val_sliding_ttt( ).split(",") if pattern ) -INT8_KEEP_FLOAT_FP32_NAME_PATTERNS = tuple( - pattern - for pattern in os.environ.get( - "INT8_KEEP_FLOAT_FP32_NAME_PATTERNS", - ",".join(CONTROL_TENSOR_NAME_PATTERNS), - ).split(",") - if pattern -) INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 -INT8_KEEP_FLOAT_STORE_DTYPE = torch.float16 INT8_PER_ROW_SCALE_DTYPE = torch.float16 INT8_CLIP_PERCENTILE = 99.99984 INT8_CLIP_Q = INT8_CLIP_PERCENTILE / 100.0 -def tensor_nbytes(t: Tensor) -> int: - return int(t.numel()) * int(t.element_size()) - - -def keep_float_tensor( - name: str, t: Tensor, passthrough_orig_dtypes: dict[str, str] -) -> Tensor: - if any(pattern in name for pattern in INT8_KEEP_FLOAT_FP32_NAME_PATTERNS): - return t.float().contiguous() - if t.dtype in {torch.float32, torch.bfloat16}: - passthrough_orig_dtypes[name] = str(t.dtype).removeprefix("torch.") - return t.to(dtype=INT8_KEEP_FLOAT_STORE_DTYPE).contiguous() - return t - - def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: t32 = t.float() if t32.ndim == 2: @@ -659,98 +651,109 @@ def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: return q, scale -def quantize_state_dict_int8(state_dict: dict[str, Tensor]): - # Single supported clean-script export format: - # - per-row int8 for 2D float tensors - # - per-tensor int8 for other float tensors - # - exact passthrough for non-floats - # - passthrough for small float tensors, stored as fp16 to save bytes - quantized: dict[str, Tensor] = {} - scales: dict[str, Tensor] = {} - dtypes: dict[str, str] = {} - passthrough: dict[str, Tensor] = {} - passthrough_orig_dtypes: dict[str, str] = {} - qmeta: dict[str, dict[str, object]] = {} - stats = dict.fromkeys( - ( - "param_count", - "num_tensors", - "num_float_tensors", - "num_nonfloat_tensors", - "baseline_tensor_bytes", - "int8_payload_bytes", - ), - 0, - ) +# ------------------------------------ +# INT6 OPTIMAL-CLIP QUANTIZATION +# ------------------------------------ - 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 - # Small float tensors are cheap enough to keep directly. We still downcast - # fp32/bf16 passthrough tensors to fp16 so metadata does not dominate size. - 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 +def _classify_param_jepa(name: str) -> str: + if "tok_emb" in name or "decoder_token_emb" in name or "decoder_out" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if ".attn." in name: + return "attn" + return "other" - stats["num_float_tensors"] += 1 - q, s = quantize_float_tensor(t) - if s.ndim > 0: - qmeta[name] = {"scheme": "per_row", "axis": 0} - quantized[name] = q - scales[name] = s - dtypes[name] = str(t.dtype).removeprefix("torch.") - stats["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 quantize_int6_per_row( + t: Tensor, clip_range: int = 31 +) -> tuple[Tensor, Tensor]: + t32 = t.float() + if t32.ndim == 2: + 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 + 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 dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: +def mixed_quantize_int6( + state_dict: dict[str, Tensor], int6_cats: set[str] +) -> tuple[dict[str, Tensor], dict[str, object]]: + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param_jepa(name) + 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 + if cat in int6_cats and t.ndim >= 1: + q, s = quantize_int6_per_row(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return result, meta + + +def dequantize_mixed_int6( + result: dict[str, Tensor], + meta: dict[str, object], + template_sd: dict[str, Tensor], +) -> dict[str, Tensor]: out: dict[str, Tensor] = {} - qmeta = obj.get("qmeta", {}) - passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {}) - for name, q in obj["quantized"].items(): - dtype = getattr(torch, obj["dtypes"][name]) - s = obj["scales"][name] - if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: - s = s.to(dtype=torch.float32) - # Broadcast the saved row scale back across trailing dimensions. + 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.view(q.shape[0], *([1] * (q.ndim - 1)))) - .to(dtype=dtype) - .contiguous() - ) + q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1))) + ).to(orig_dtype) else: - scale = float(s.item()) - out[name] = (q.float() * scale).to(dtype=dtype).contiguous() - for name, t in obj["passthrough"].items(): - # Restore small tensors, undoing the temporary fp16 storage cast if needed. - out_t = t.detach().to("cpu").contiguous() - orig_dtype = passthrough_orig_dtypes.get(name) - if isinstance(orig_dtype, str): - out_t = out_t.to(dtype=getattr(torch, orig_dtype)).contiguous() - out[name] = out_t + out[name] = (q.float() * float(s.item())).to(orig_dtype) return out @@ -849,9 +852,22 @@ def forward(self, x: Tensor) -> Tensor: class CastedLinear(nn.Linear): # Keep weights in fp32 for optimizer/state quality, cast at matmul time for bf16 compute. + _qat_enabled: bool = False + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if CastedLinear._qat_enabled and self.training and w.ndim == 2: + with torch.no_grad(): + w32 = self.weight.float() + row_max = w32.abs().amax(dim=1) + scale = (row_max / 31.0).clamp_min(1.0 / 31.0) + w_q = ( + torch.clamp(torch.round(w32 / scale[:, None]), -31, 31) + * scale[:, None] + ).to(x.dtype) + w = w + (w_q - w).detach() bias = self.bias.to(x.dtype) if self.bias is not None else None - return F.linear(x, self.weight.to(x.dtype), bias) + return F.linear(x, w, bias) def restore_low_dim_params_to_fp32(module: nn.Module) -> None: @@ -1620,6 +1636,13 @@ def lr_mul(step: int, elapsed_ms: float) -> float: elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) scale = lr_mul(step, elapsed_ms) + if ( + args.late_qat_threshold > 0 + and scale < args.late_qat_threshold + and not CastedLinear._qat_enabled + ): + CastedLinear._qat_enabled = True + log0(f"late_qat:enabled step:{step} scale:{scale:.4f}") zero_grad_all() train_loss = torch.zeros((), device=device) train_nll = torch.zeros((), device=device) @@ -1715,34 +1738,32 @@ def lr_mul(step: int, elapsed_ms: float) -> float: 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()) + template_sd = {k: v.cpu() for k, v in base_model.state_dict().items()} + int6_cats = {"mlp", "attn", "other"} + quant_result, quant_meta = mixed_quantize_int6( + base_model.state_dict(), int6_cats + ) quant_buf = io.BytesIO() - torch.save(quant_obj, quant_buf) + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) quant_raw = quant_buf.getvalue() - quant_blob = zlib.compress(quant_raw, level=9) - quant_raw_bytes = len(quant_raw) + quant_blob = lzma.compress(quant_raw, preset=6) if master_process: - with open("final_model.int8.ptz", "wb") as f: + with open("final_model.int6.ptz", "wb") as f: f.write(quant_blob) - quant_file_bytes = os.path.getsize("final_model.int8.ptz") + quant_file_bytes = len(quant_blob) code_bytes = len(code.encode("utf-8")) - ratio = quant_stats["baseline_tensor_bytes"] / max( - quant_stats["int8_payload_bytes"], 1 - ) - log0( - f"Serialized model int8+zlib: {quant_file_bytes} bytes " - f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" - ) - log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes") + log0(f"Serialized model int6+lzma: {quant_file_bytes} bytes") + log0(f"Total submission size int6+lzma: {quant_file_bytes + code_bytes} bytes") if distributed: dist.barrier() - with open("final_model.int8.ptz", "rb") as f: + with open("final_model.int6.ptz", "rb") as f: quant_blob_disk = f.read() quant_state = torch.load( - io.BytesIO(zlib.decompress(quant_blob_disk)), map_location="cpu" + io.BytesIO(lzma.decompress(quant_blob_disk)), map_location="cpu" ) - base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + deq_sd = dequantize_mixed_int6(quant_state["w"], quant_state["m"], template_sd) + base_model.load_state_dict(deq_sd, strict=True) torch.cuda.synchronize() t_qeval = time.perf_counter() q_val_loss, q_val_bpb = eval_val_sliding( @@ -1758,15 +1779,18 @@ def lr_mul(step: int, elapsed_ms: float) -> float: ) torch.cuda.synchronize() log0( - f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"final_int6_lzma_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}" + f"final_int6_lzma_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}" ) if args.ttt_enabled: - base_model.load_state_dict(dequantize_state_dict_int8(quant_state), strict=True) + deq_sd = dequantize_mixed_int6( + quant_state["w"], quant_state["m"], template_sd + ) + base_model.load_state_dict(deq_sd, strict=True) torch.cuda.synchronize() t_ttt = time.perf_counter() ttt_loss, ttt_bpb = eval_val_sliding_ttt( From b751bd85dbcd2b9531b9e84c6aa33de03915b633 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 23:19:24 -0700 Subject: [PATCH 16/25] Reduce default train_seq_len from 4095 to 2047 Halves context length to ~4x reduce attention cost per forward pass, making sliding window eval and TTT feasible within time budget. --- train_gpt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/train_gpt.py b/train_gpt.py index 7b1e52979..0faef2280 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -72,7 +72,7 @@ class Hyperparameters: 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_160)) - train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 4095)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2047)) max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) use_compile = bool(int(os.environ.get("USE_COMPILE", "1"))) From 8e73b0c750fcef2729c2b82e1d876e87f890cad8 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 23:21:05 -0700 Subject: [PATCH 17/25] Fix train_batch_tokens alignment for seq_len 2047 524032 = 2047 * 32 * 8, ensuring divisibility across 8 GPUs. --- train_gpt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/train_gpt.py b/train_gpt.py index 0faef2280..ff12a4491 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -71,7 +71,7 @@ class Hyperparameters: 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_160)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 524_032)) train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2047)) max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) From 2db8fafb282b432f1ccb6919972660055e2696c8 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 23:37:14 -0700 Subject: [PATCH 18/25] Fit within 16MB budget: LZMA preset 9, INT6 for all categories Bump LZMA compression from preset 6 to 9 and quantize embeddings to INT6 (previously INT8). Previous run was 363KB over budget. --- train_gpt.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index ff12a4491..ea77d6e0a 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -1739,14 +1739,14 @@ def lr_mul(step: int, elapsed_ms: float) -> float: log0(f"Total submission size: {model_bytes + code_bytes} bytes") template_sd = {k: v.cpu() for k, v in base_model.state_dict().items()} - int6_cats = {"mlp", "attn", "other"} + int6_cats = {"mlp", "attn", "other", "embed"} quant_result, quant_meta = mixed_quantize_int6( base_model.state_dict(), int6_cats ) quant_buf = io.BytesIO() torch.save({"w": quant_result, "m": quant_meta}, quant_buf) quant_raw = quant_buf.getvalue() - quant_blob = lzma.compress(quant_raw, preset=6) + quant_blob = lzma.compress(quant_raw, preset=9) if master_process: with open("final_model.int6.ptz", "wb") as f: f.write(quant_blob) From 3a54844f6ad652ee6241f3e0f09417b53eaf9f5b Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 23:45:40 -0700 Subject: [PATCH 19/25] Fix TTT divergence: freeze encoder, disable QAT during eval TTT was catastrophically diverging (bpb 1.24 -> 2.53) because sequential adaptation was destroying the JEPA encoder. Now only decoder parameters adapt during TTT. Also disable QAT during TTT to avoid injecting quantization noise on already-dequantized weights. --- train_gpt.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index ea77d6e0a..ae409d2d7 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -460,12 +460,13 @@ def eval_val_sliding_ttt( frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) ttt_params = [] for name, p in base_model.named_parameters(): - freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) - if freeze: - p.requires_grad_(False) - else: + is_decoder = name.startswith("decoder_") or name.startswith("start_latent") + freeze_block = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if is_decoder and not freeze_block: p.requires_grad_(True) ttt_params.append(p) + else: + p.requires_grad_(False) optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) t0 = time.perf_counter() @@ -1787,6 +1788,7 @@ def lr_mul(step: int, elapsed_ms: float) -> float: ) if args.ttt_enabled: + CastedLinear._qat_enabled = False deq_sd = dequantize_mixed_int6( quant_state["w"], quant_state["m"], template_sd ) From 6ab7b514fb91f0eef0ac5fc187d687c2f8a5ec18 Mon Sep 17 00:00:00 2001 From: John Tian Date: Tue, 24 Mar 2026 23:46:42 -0700 Subject: [PATCH 20/25] Speed up eval: stride 256, TTT epochs 1 Revert encoder freeze (divergence was from QAT during TTT, not encoder adaptation). Increase sliding window stride from 64 to 256 and reduce TTT epochs from 3 to 1 for faster eval. --- train_gpt.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index ae409d2d7..69c3a717a 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -53,13 +53,13 @@ class Hyperparameters: # Validation cadence and batch size. Validation always uses the full fineweb_val split. val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_160)) val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) - val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 64)) + val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 256)) val_sliding_batch = int(os.environ.get("VAL_SLIDING_BATCH", 32)) ema_decay = float(os.environ.get("EMA_DECAY", 0.997)) late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", 0.15)) 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_epochs = int(os.environ.get("TTT_EPOCHS", 1)) ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 0)) ttt_momentum = float(os.environ.get("TTT_MOMENTUM", 0.9)) @@ -460,13 +460,12 @@ def eval_val_sliding_ttt( frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) ttt_params = [] for name, p in base_model.named_parameters(): - is_decoder = name.startswith("decoder_") or name.startswith("start_latent") - freeze_block = any(f"blocks.{bi}." in name for bi in frozen_block_ids) - if is_decoder and not freeze_block: + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: p.requires_grad_(True) ttt_params.append(p) - else: - p.requires_grad_(False) optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) t0 = time.perf_counter() From 2f8a8ad075046a20c019f443fee70cab8ce3b52d Mon Sep 17 00:00:00 2001 From: John Tian Date: Wed, 25 Mar 2026 00:01:45 -0700 Subject: [PATCH 21/25] Reduce decoder layers from 8 to 7 to fit 16MB budget Each decoder block is ~1.84M params (~1.1MB compressed). Previous run was 572KB over the 16MB limit. Dropping one decoder layer should provide enough headroom. --- train_gpt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/train_gpt.py b/train_gpt.py index 69c3a717a..f00d1bad3 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -88,7 +88,7 @@ class Hyperparameters: rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) patch_size = int(os.environ.get("PATCH_SIZE", 8)) latent_dim = int(os.environ.get("LATENT_DIM", 192)) - decoder_layers = int(os.environ.get("DECODER_LAYERS", 8)) + decoder_layers = int(os.environ.get("DECODER_LAYERS", 7)) decoder_heads = int(os.environ.get("DECODER_HEADS", 4)) sigreg_weight = float(os.environ.get("SIGREG_WEIGHT", 0.02)) sigreg_knots = int(os.environ.get("SIGREG_KNOTS", 17)) From 237b2d6d3f353f3010d6bc7b919b954c90fe1fd5 Mon Sep 17 00:00:00 2001 From: John Tian Date: Wed, 25 Mar 2026 00:13:13 -0700 Subject: [PATCH 22/25] Remove standalone sliding window eval, use TTT epochs 2 Drop eval_val_sliding (was burning 88s for a diagnostic log). TTT already does sliding window evaluation with adaptation. Bump TTT epochs from 1 to 2 with the freed time budget. --- train_gpt.py | 109 +-------------------------------------------------- 1 file changed, 2 insertions(+), 107 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index f00d1bad3..cbd59e2ec 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -59,7 +59,7 @@ class Hyperparameters: late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", 0.15)) 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", 1)) + ttt_epochs = int(os.environ.get("TTT_EPOCHS", 2)) ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 0)) ttt_momentum = float(os.environ.get("TTT_MOMENTUM", 0.9)) @@ -335,86 +335,6 @@ def eval_val( return float(val_loss.item()), float(bits_per_token * tokens_per_byte) -def eval_val_sliding( - args: Hyperparameters, - base_model: nn.Module, - rank: int, - world_size: int, - device: torch.device, - val_tokens: Tensor, - base_bytes_lut: Tensor, - has_leading_space_lut: Tensor, - is_boundary_token_lut: Tensor, -) -> tuple[float, float]: - seq_len = args.train_seq_len - stride = args.val_sliding_stride - batch_seqs = args.val_sliding_batch - total_tokens = val_tokens.numel() - 1 - - window_starts = [ - ws for ws in range(0, total_tokens, stride) - if min(ws + seq_len, total_tokens) - ws >= seq_len - ] - total_windows = len(window_starts) - my_s = (total_windows * rank) // world_size - my_e = (total_windows * (rank + 1)) // world_size - my_windows = window_starts[my_s:my_e] - - loss_sum = torch.zeros((), device=device, dtype=torch.float64) - token_count = torch.zeros((), device=device, dtype=torch.float64) - byte_count = torch.zeros((), device=device, dtype=torch.float64) - - base_model.eval() - with torch.inference_mode(): - for bi in range(0, len(my_windows), batch_seqs): - batch_ws = my_windows[bi : bi + batch_seqs] - bsz = len(batch_ws) - x_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) - y_batch = torch.zeros(bsz, seq_len, dtype=torch.int64, device=device) - for i, ws in enumerate(batch_ws): - chunk = val_tokens[ws : ws + seq_len + 1].to( - dtype=torch.int64, device=device - ) - x_batch[i] = chunk[:-1] - y_batch[i] = chunk[1:] - - with torch.autocast(device_type="cuda", dtype=torch.bfloat16): - logits = base_model.forward_logits(x_batch, y_batch) - - # logits[:, 0] predicts full[0] = x[0] (skip it) - # logits[:, k] predicts full[k] = y[k-1] for k >= 1 - nll = F.cross_entropy( - logits[:, 1:].reshape(-1, logits.size(-1)).float(), - y_batch.reshape(-1), - reduction="none", - ).reshape(bsz, seq_len) - - for i, ws in enumerate(batch_ws): - score_start = 0 if ws == 0 else seq_len - stride - scored = nll[i, score_start:seq_len].to(torch.float64) - loss_sum += scored.sum() - n = seq_len - score_start - token_count += float(n) - tgt = y_batch[i, score_start:seq_len] - prev = x_batch[i, score_start:seq_len] - 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() - - if dist.is_available() and dist.is_initialized(): - dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM) - dist.all_reduce(token_count, op=dist.ReduceOp.SUM) - dist.all_reduce(byte_count, op=dist.ReduceOp.SUM) - - val_loss = loss_sum / token_count - bits_per_token = val_loss.item() / math.log(2.0) - tokens_per_byte = token_count.item() / byte_count.item() - base_model.train() - return float(val_loss.item()), float(bits_per_token * tokens_per_byte) - - def eval_val_sliding_ttt( args: Hyperparameters, base_model: nn.Module, @@ -1762,36 +1682,11 @@ def lr_mul(step: int, elapsed_ms: float) -> float: quant_state = torch.load( io.BytesIO(lzma.decompress(quant_blob_disk)), map_location="cpu" ) + CastedLinear._qat_enabled = False deq_sd = dequantize_mixed_int6(quant_state["w"], quant_state["m"], template_sd) base_model.load_state_dict(deq_sd, strict=True) - torch.cuda.synchronize() - t_qeval = time.perf_counter() - q_val_loss, q_val_bpb = eval_val_sliding( - args, - base_model, - rank, - world_size, - device, - val_tokens, - base_bytes_lut, - has_leading_space_lut, - is_boundary_token_lut, - ) - torch.cuda.synchronize() - log0( - f"final_int6_lzma_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_int6_lzma_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}" - ) if args.ttt_enabled: - CastedLinear._qat_enabled = False - deq_sd = dequantize_mixed_int6( - quant_state["w"], quant_state["m"], template_sd - ) - base_model.load_state_dict(deq_sd, strict=True) torch.cuda.synchronize() t_ttt = time.perf_counter() ttt_loss, ttt_bpb = eval_val_sliding_ttt( From f864f911725055d2a41f4bc03adac31781efe2d5 Mon Sep 17 00:00:00 2001 From: John Tian Date: Wed, 25 Mar 2026 00:21:10 -0700 Subject: [PATCH 23/25] Adopt SOTA optimizer hyperparameters Match the #1 record's optimizer settings: - MATRIX_LR/SCALAR_LR: 0.015 -> 0.025 - MUON_MOMENTUM: 0.95 -> 0.99 - MUON_MOMENTUM_WARMUP_START: 0.85 -> 0.92 - MUON_MOMENTUM_WARMUP_STEPS: 500 -> 1500 - WARMDOWN_ITERS: 1200 -> 3500 --- train_gpt.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/train_gpt.py b/train_gpt.py index cbd59e2ec..e95bed0d3 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -69,7 +69,7 @@ class Hyperparameters: # Training length. iterations = int(os.environ.get("ITERATIONS", 20000)) - warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 1200)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3500)) warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 524_032)) train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2047)) @@ -99,14 +99,14 @@ class Hyperparameters: # Optimizer hyperparameters. embed_lr = float(os.environ.get("EMBED_LR", 0.1)) head_lr = float(os.environ.get("HEAD_LR", 0.02)) - matrix_lr = float(os.environ.get("MATRIX_LR", 0.015)) - scalar_lr = float(os.environ.get("SCALAR_LR", 0.015)) - muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.95)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.025)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.025)) + 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) + os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92) ) - muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 500)) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) beta1 = float(os.environ.get("BETA1", 0.9)) beta2 = float(os.environ.get("BETA2", 0.95)) adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) From 7dc65d1264cfad0b58870383418d0f56196f214a Mon Sep 17 00:00:00 2001 From: John Tian Date: Wed, 25 Mar 2026 01:20:09 -0700 Subject: [PATCH 24/25] prepare non-record submission --- .../README.md | 76 + .../submission.json | 17 + .../tokenizer_specs.json | 10 + .../train.log | 1989 +++++++++++++++++ .../train_gpt.py | 1708 ++++++++++++++ 5 files changed, 3800 insertions(+) create mode 100644 records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/README.md create mode 100644 records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/submission.json create mode 100644 records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/tokenizer_specs.json create mode 100644 records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/train.log create mode 100644 records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/train_gpt.py diff --git a/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/README.md b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/README.md new file mode 100644 index 000000000..a5856e624 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/README.md @@ -0,0 +1,76 @@ +Non-record submission using JEPA (Joint Embedding Predictive Architecture) encoder-decoder as an alternative to GPT. + +Architecture: + +Unlike the standard causal GPT used by all leaderboard entries, this submission uses a two-stage JEPA architecture: + +| Component | Config | +|-----------|--------| +| Tokenizer | Pure byte-level (vocab 260, no BPE) | +| Encoder | 5 layers × 2 depth-recurrent repeats, dim 480, 6 heads (3 KV), GQA | +| Encoder output | Patch-based (patch_size=8), latent projection (dim 192) with SIGReg regularization | +| Decoder | 7 causal layers, dim 480, 4 heads, conditioned on encoder latents | +| Total blocks per forward | 17 (10 encoder + 7 decoder) + projector/predictor MLPs | + +The encoder processes input patches into latent representations via a JEPA objective (predicting latent targets with a predictor network, regularized by SIGReg). The decoder autoregressively predicts bytes conditioned on these latents. Training uses a combined loss: JEPA prediction loss (weight 0.5) + byte cross-entropy (weight 3.0). + +Quantization & Compression: + +- INT6 optimal-clip quantization: All weight categories (MLP, attention, embeddings, other) quantized to [-31, 31] range stored as int8, with per-row scales in fp16. Clip percentile grid search over [0.9990, 0.9995, 0.9999, 0.99999, 1.0] minimizing reconstruction MSE. +- STE QAT: Straight-through estimator quantization-aware training activated during warmdown when LR scale drops below 0.15, simulating INT6 rounding in the forward pass. +- LZMA compression (preset 9): Exploits the reduced entropy from INT6's 63-value range for better compression than zlib/zstd. +- Small/control tensors passed through as fp16. + +Test-Time Training: + +- Sliding window TTT with chunk-sequential adaptation (chunk_tokens=32768) +- SGD optimizer (lr=0.002, momentum=0.9, cosine LR across chunks) +- 2 epochs per chunk, stride 256, batch_seqs=32 +- All parameters adapt + +Results: + +| Metric | Value | +|--------|-------| +| Pre-quantization val_bpb | 1.2957 | +| Final TTT val_bpb | 1.2622 | +| Training steps | 10,635 / 20,000 | +| Step avg | 56.39 ms | +| Model params | 24,593,530 | +| Compressed model (INT6+LZMA) | 15,625,312 bytes | +| Code size | 66,315 bytes | +| Total submission size | 15,691,627 bytes | +| TTT eval time | 542s | +| Peak memory | 9,994 MiB allocated | + +Setup & Run: + +This submission uses a pure byte-level tokenizer (vocab 260) instead of the upstream default SentencePiece BPE (vocab 1024). The byte260 variant is not in the pre-built HuggingFace cache, so generate it locally with the export pipeline using the included `tokenizer_specs.json`: + +```bash +python3 data/download_hf_docs_and_tokenize.py --output-root data \ + --tokenizer-config records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/tokenizer_specs.json +``` + +This downloads `docs_selected.jsonl` from HuggingFace, byte-tokenizes it, and populates `./data/datasets/fineweb10B_byte260/` and `./data/tokenizers/fineweb_pure_byte_260.json`. + +Then run: + +```bash +torchrun --standalone --nproc_per_node=8 train_gpt.py +``` + +The script defaults to the byte260 paths (`DATA_PATH=./data/datasets/fineweb10B_byte260`, `TOKENIZER_PATH=./data/tokenizers/fineweb_pure_byte_260.json`). + +Hyperparams (UNTUNED!): + +``` +NUM_LAYERS=5 ENCODER_REPEATS=2 DECODER_LAYERS=7 +MODEL_DIM=480 NUM_HEADS=6 NUM_KV_HEADS=3 DECODER_HEADS=4 +TRAIN_SEQ_LEN=2047 TRAIN_BATCH_TOKENS=524032 +WARMDOWN_ITERS=3500 MUON_MOMENTUM=0.99 +MATRIX_LR=0.025 SCALAR_LR=0.025 +EMA_DECAY=0.997 LATE_QAT_THRESHOLD=0.15 +TTT_ENABLED=1 TTT_LR=0.002 TTT_EPOCHS=2 TTT_CHUNK_TOKENS=32768 +TTT_BATCH_SEQS=32 VAL_SLIDING_STRIDE=256 +``` diff --git a/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/submission.json b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/submission.json new file mode 100644 index 000000000..cc01ff187 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/submission.json @@ -0,0 +1,17 @@ +{ + "author": "John Tian", + "github_id": "gravelBridge", + "name": "JEPA Byte-Level Encoder-Decoder + INT6 Optimal-Clip + TTT", + "blurb": "Non-record submission using JEPA (Joint Embedding Predictive Architecture) encoder-decoder as an alternative to standard GPT for the 16MB track. Byte-level tokenizer (vocab 260), patched encoder (5x2 depth-recurrent) with latent predictor, 7-layer causal decoder. INT6 optimal-clip quantization with LZMA compression, STE QAT during warmdown, and test-time training. Final TTT val_bpb: 1.2622.", + "date": "2026-03-25T06:30:00Z", + "track": "non-record-16mb", + "val_loss": 0.87456928, + "val_bpb": 1.26215432, + "pre_quant_val_loss": 0.8978, + "pre_quant_val_bpb": 1.2957, + "step_stop": 10635, + "wallclock_seconds": 599.732, + "bytes_total": 15691627, + "bytes_model_int6_lzma": 15625312, + "bytes_code": 66315 +} diff --git a/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/tokenizer_specs.json b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/tokenizer_specs.json new file mode 100644 index 000000000..28e6f9b40 --- /dev/null +++ b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/tokenizer_specs.json @@ -0,0 +1,10 @@ +{ + "tokenizers": [ + { + "name": "pure_byte_260", + "kind": "pure_byte", + "dataset_suffix": "byte260", + "filename": "fineweb_pure_byte_260.json" + } + ] +} diff --git a/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/train.log b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/train.log new file mode 100644 index 000000000..3b7e90dcb --- /dev/null +++ b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/train.log @@ -0,0 +1,1989 @@ +""" +The `train_gpt.py` and `train_gpt_mlx.py` scripts are intended as good launching-off points for new participants, not SOTA configs. We'll accept PRs that tune, improve, or simplify these scripts without significantly increasing complexity, but competitive submissions should stay in the `/records` folder. + +Hard stop: To keep readable for newcomers, let's make sure `train_gpt.py` and `train_gpt_mlx.py` never are longer than 1500 lines. +""" + +from __future__ import annotations + +import copy +import glob +import io +import json +import lzma +import math +import os +import random +import subprocess +import sys +import time +import uuid + +from pathlib import Path + +import numpy as np +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 + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- +# Default JEPA run: +# - pure-byte FineWeb export (`byte260`) +# - byte-patch JEPA with latent next-patch prediction plus a small causal byte decoder +# - 10 JEPA blocks at width 384, 6 heads with 3 KV heads +# - sequence length 4095 so the reconstructed AR stream has 4096 bytes, cleanly divisible by patch size 8 +# - 524,160 train tokens per step for 20,000 iterations with a ~10 minute cap + + +class Hyperparameters: + # Data paths are shard globs produced by the existing preprocessing pipeline. + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_byte260") + 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_pure_byte_260.json" + ) + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 1337)) + + # Validation cadence and batch size. Validation always uses the full fineweb_val split. + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_160)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) + val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 256)) + val_sliding_batch = int(os.environ.get("VAL_SLIDING_BATCH", 32)) + ema_decay = float(os.environ.get("EMA_DECAY", 0.997)) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", 0.15)) + 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", 2)) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 0)) + 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)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200)) + + # Training length. + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3500)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 524_032)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2047)) + max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + use_compile = bool(int(os.environ.get("USE_COMPILE", "1"))) + + # Model shape. + vocab_size = int(os.environ.get("VOCAB_SIZE", 260)) + num_layers = int(os.environ.get("NUM_LAYERS", 5)) + encoder_repeats = int(os.environ.get("ENCODER_REPEATS", 2)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 3)) + model_dim = int(os.environ.get("MODEL_DIM", 480)) + num_heads = int(os.environ.get("NUM_HEADS", 6)) + mlp_mult = int(os.environ.get("MLP_MULT", 2)) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + patch_size = int(os.environ.get("PATCH_SIZE", 8)) + latent_dim = int(os.environ.get("LATENT_DIM", 192)) + decoder_layers = int(os.environ.get("DECODER_LAYERS", 7)) + decoder_heads = int(os.environ.get("DECODER_HEADS", 4)) + sigreg_weight = float(os.environ.get("SIGREG_WEIGHT", 0.02)) + sigreg_knots = int(os.environ.get("SIGREG_KNOTS", 17)) + sigreg_num_proj = int(os.environ.get("SIGREG_NUM_PROJ", 256)) + jepa_pred_weight = float(os.environ.get("JEPA_PRED_WEIGHT", 0.5)) + jepa_ce_weight = float(os.environ.get("JEPA_CE_WEIGHT", 3.0)) + + # Optimizer hyperparameters. + embed_lr = float(os.environ.get("EMBED_LR", 0.1)) + head_lr = float(os.environ.get("HEAD_LR", 0.02)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.025)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.025)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float( + os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92) + ) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.0)) + + +# ----------------------------- +# MUON OPTIMIZER +# ----------------------------- +# +# As borrowed from modded-nanogpt +# Background on Muon: https://kellerjordan.github.io/posts/muon/ + + +def zeropower_via_newtonschulz5( + G: Tensor, steps: int = 10, eps: float = 1e-7 +) -> Tensor: + # Orthogonalize a 2D update matrix with a fast Newton-Schulz iteration. + # Muon uses this to normalize matrix-shaped gradients before applying them. + a, b, c = (3.4445, -4.7750, 2.0315) + X = G.bfloat16() + X /= X.norm() + eps + transposed = G.size(0) > G.size(1) + if transposed: + X = X.T + for _ in range(steps): + A = X @ X.T + B = b * A + c * A @ A + X = a * X + B @ X + return X.T if transposed else X + + +class Muon(torch.optim.Optimizer): + def __init__( + self, + params, + lr: float, + momentum: float, + backend_steps: int, + nesterov: bool = True, + ): + super().__init__( + params, + dict( + lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov + ), + ) + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + distributed = dist.is_available() and dist.is_initialized() + world_size = dist.get_world_size() if distributed else 1 + rank = dist.get_rank() if distributed else 0 + + for group in self.param_groups: + params = group["params"] + if not params: + continue + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + + total_params = sum(int(p.numel()) for p in params) + updates_flat = torch.zeros( + total_params, device=params[0].device, dtype=torch.bfloat16 + ) + + curr = 0 + for i, p in enumerate(params): + if i % world_size == rank and p.grad is not None: + g = p.grad + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(g) + if nesterov: + g = g.add(buf, alpha=momentum) + g = zeropower_via_newtonschulz5(g, steps=backend_steps) + # Scale correction from Muon reference implementations. + g *= max(1, g.size(0) / g.size(1)) ** 0.5 + updates_flat[curr : curr + p.numel()] = g.reshape(-1) + curr += p.numel() + + if distributed: + dist.all_reduce(updates_flat, op=dist.ReduceOp.SUM) + + 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) + curr += p.numel() + + return loss + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION SETUP +# ----------------------------- +# +# We score BPB (bits-per-byte), but the model is fixed to a pure-byte vocabulary: +# 4 special ids followed by raw UTF-8 bytes. That makes byte accounting exact. +def build_pure_byte_luts( + vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + table_size = max(vocab_size, 260) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + base_bytes_np[4 : min(table_size, 260)] = 1 + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + return ( + torch.tensor(base_bytes_np[:vocab_size], dtype=torch.int16, device=device), + torch.tensor( + has_leading_space_np[:vocab_size], dtype=torch.bool, device=device + ), + torch.tensor( + is_boundary_token_np[:vocab_size], dtype=torch.bool, device=device + ), + ) + + +def load_pure_byte_luts( + tokenizer_path: str, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + path = Path(tokenizer_path) + if path.suffix != ".json": + raise ValueError( + f"Pure-byte JEPA expects a tokenizer JSON at {tokenizer_path!r}" + ) + payload = json.loads(path.read_text(encoding="utf-8")) + tokenizer_type = payload.get("tokenizer_type") or payload.get("kind") + json_vocab_size = int(payload.get("vocab_size", vocab_size)) + if tokenizer_type != "pure_byte": + raise ValueError( + f"Unsupported tokenizer JSON {tokenizer_path}: expected pure_byte, got {tokenizer_type!r}" + ) + if json_vocab_size != vocab_size: + raise ValueError( + f"VOCAB_SIZE={vocab_size} does not match tokenizer vocab_size={json_vocab_size}" + ) + return build_pure_byte_luts(vocab_size, device) + + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + # The export pipeline writes the fixed first-50k-doc validation set to fineweb_val_*. + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + # Validation computes two metrics: + # - val_loss: token cross-entropy (natural log) + # - val_bpb: tokenizer-agnostic compression metric used by the challenge + 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) + batch_loss = batch_loss.detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += ( + has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids] + ).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +def eval_val_sliding_ttt( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, + log_fn=print, +) -> tuple[float, float]: + seq_len = args.train_seq_len + stride = args.val_sliding_stride + batch_seqs = args.ttt_batch_seqs + 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 >= seq_len + ] + 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) + + log_fn( + f"ttt:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"windows={len(window_starts)} stride={stride} " + f"lr={args.ttt_lr} epochs={args.ttt_epochs} freeze={args.ttt_freeze_blocks}" + ) + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) + t0 = time.perf_counter() + t_infer_total = 0.0 + t_adapt_total = 0.0 + + for ci in range(num_chunks): + windows = chunk_windows[ci] + if not windows: + continue + + my_s = (len(windows) * rank) // world_size + my_e = (len(windows) * (rank + 1)) // world_size + my_windows = windows[my_s:my_e] + + torch.cuda.synchronize() + t_infer = time.perf_counter() + 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) + for i, ws in enumerate(batch_ws): + chunk_tok = val_tokens[ws : ws + seq_len + 1].to( + dtype=torch.int64, device=device + ) + x_batch[i] = chunk_tok[:-1] + y_batch[i] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch, y_batch) + nll = F.cross_entropy( + logits[:, 1:].reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + s = 0 if ws == 0 else seq_len - stride + scored = nll[i, s:seq_len].to(torch.float64) + loss_sum += scored.sum() + token_count += float(seq_len - s) + tgt = y_batch[i, s:seq_len] + prev = x_batch[i, s:seq_len] + 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() + + torch.cuda.synchronize() + t_infer_total += time.perf_counter() - t_infer + + is_last_chunk = ci == num_chunks - 1 + t_adapt = time.perf_counter() + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + 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 + for _ep in range(args.ttt_epochs): + for bs in range(my_seq_s, my_seq_e, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_seq_e) + start_tok = chunk_start + bs * seq_len + end_tok = chunk_start + 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): + logits = base_model.forward_logits(x, y) + ce = F.cross_entropy( + logits[:, 1:].reshape(-1, logits.size(-1)).float(), + y.reshape(-1), + ) + ce.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() + + torch.cuda.synchronize() + t_adapt_total += time.perf_counter() - t_adapt + + if rank == 0 and (ci % 50 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = ( + rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) + if token_count.item() > 0 + else 0.0 + ) + log_fn( + f" ttt_chunk [{ci + 1}/{num_chunks}] bpb={rbpb:.6f} " + f"time={elapsed:.1f}s infer={t_infer_total:.1f}s adapt={t_adapt_total:.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() + return val_loss, val_bpb + + +# ----------------------------- +# POST-TRAINING QUANTIZATION +# ----------------------------- +# +# It's silly to export our model, which is trained in bf16 and fp32, at that same precision. +# Instead, we get approximately the same model (with a small hit) by quantizing the model to int8 & zlib compressing. +# We can then decompress the model and run in higher precision for evaluation, after closing in under the size limit. + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights", + ).split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 +INT8_PER_ROW_SCALE_DTYPE = torch.float16 +INT8_CLIP_PERCENTILE = 99.99984 +INT8_CLIP_Q = INT8_CLIP_PERCENTILE / 100.0 + + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + t32 = t.float() + if t32.ndim == 2: + # Matrices get one scale per row, which usually tracks output-channel + # ranges much better than a single tensor-wide scale. + clip_abs = ( + torch.quantile(t32.abs(), INT8_CLIP_Q, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + clipped = torch.maximum( + torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None] + ) + scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) + q = ( + torch.clamp(torch.round(clipped / scale[:, None]), -127, 127) + .to(torch.int8) + .contiguous() + ) + return q, scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous() + + # Vectors / scalars use a simpler per-tensor scale. + clip_abs = ( + float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) + if t32.numel() + else 0.0 + ) + scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) + q = ( + torch.clamp( + torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127 + ) + .to(torch.int8) + .contiguous() + ) + return q, scale + + +# ------------------------------------ +# INT6 OPTIMAL-CLIP QUANTIZATION +# ------------------------------------ + + +def _classify_param_jepa(name: str) -> str: + if "tok_emb" in name or "decoder_token_emb" in name or "decoder_out" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if ".attn." in name: + return "attn" + return "other" + + +def quantize_int6_per_row( + t: Tensor, clip_range: int = 31 +) -> tuple[Tensor, Tensor]: + t32 = t.float() + if t32.ndim == 2: + 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 + 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( + state_dict: dict[str, Tensor], int6_cats: set[str] +) -> tuple[dict[str, Tensor], dict[str, object]]: + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param_jepa(name) + 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 + if cat in int6_cats and t.ndim >= 1: + q, s = quantize_int6_per_row(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return result, meta + + +def dequantize_mixed_int6( + result: dict[str, Tensor], + meta: dict[str, object], + template_sd: dict[str, Tensor], +) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + for name, orig in template_sd.items(): + info = meta.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 + + +# ----------------------------- +# DATA LOADING +# ----------------------------- + + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + + +class DistributedTokenLoader: + # Each call consumes a contiguous chunk from the shared token stream, then slices out + # one disjoint span per rank. The extra "+1" token lets us build (x, y) by shifting. + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = rank + self.world_size = world_size + self.device = device + self.stream = TokenStream(pattern) + + def next_batch( + self, global_tokens: int, seq_len: int, grad_accum_steps: int + ) -> tuple[Tensor, Tensor]: + local_tokens = global_tokens // (self.world_size * grad_accum_steps) + per_rank_span = local_tokens + 1 + chunk = self.stream.take(per_rank_span * self.world_size) + start = self.rank * per_rank_span + local = chunk[start : start + per_rank_span].to(dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + return x.to(self.device, non_blocking=True), y.to( + self.device, non_blocking=True + ) + + +# ----------------------------- +# TRANSFORMER MODULES +# ----------------------------- + + +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + + +class CastedLinear(nn.Linear): + # Keep weights in fp32 for optimizer/state quality, cast at matmul time for bf16 compute. + _qat_enabled: bool = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if CastedLinear._qat_enabled and self.training and w.ndim == 2: + with torch.no_grad(): + w32 = self.weight.float() + row_max = w32.abs().amax(dim=1) + scale = (row_max / 31.0).clamp_min(1.0 / 31.0) + w_q = ( + torch.clamp(torch.round(w32 / scale[:, None]), -31, 31) + * scale[:, None] + ).to(x.dtype) + w = w + (w_q - w).detach() + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + # Keep small/control parameters in fp32 even when the model body runs in bf16. + with torch.no_grad(): + for name, param in module.named_parameters(): + if ( + param.ndim < 2 + or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + # Caches cos/sin tables per sequence length on the current device. + 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) + + def forward(self, x: Tensor) -> Tensor: + bsz, seqlen, dim = x.shape + q = ( + self.c_q(x) + .reshape(bsz, seqlen, self.num_heads, self.head_dim) + .transpose(1, 2) + ) + k = ( + self.c_k(x) + .reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + .transpose(1, 2) + ) + v = ( + self.c_v(x) + .reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + .transpose(1, 2) + ) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, + is_causal=True, + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + y = y.transpose(1, 2).contiguous().reshape(bsz, seqlen, dim) + return self.proj(y) + + +class MLP(nn.Module): + # relu^2 MLP from the original modded-nanogpt setup + def __init__(self, dim: int, mlp_mult: int): + super().__init__() + hidden = mlp_mult * dim + self.fc = CastedLinear(dim, hidden, bias=False) + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + + def forward(self, x: Tensor) -> Tensor: + x = F.leaky_relu(self.fc(x), negative_slope=0.5) + return self.proj(x.square()) + + +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) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter( + torch.stack((torch.ones(dim), torch.zeros(dim))).float() + ) + + def forward(self, x: Tensor, x0: Tensor) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + attn_out = self.attn(self.attn_norm(x)) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp( + self.mlp_norm(x) + ) + return x + + +class SIGReg(nn.Module): + # Sketch regularizer from LeWM, adapted to local (per-rank) batches. + def __init__(self, knots: int = 17, num_proj: int = 256): + super().__init__() + self.num_proj = num_proj + t = torch.linspace(0, 3, knots, dtype=torch.float32) + dt = 3 / max(knots - 1, 1) + weights = torch.full((knots,), 2 * dt, dtype=torch.float32) + if knots > 1: + weights[[0, -1]] = dt + window = torch.exp(-t.square() / 2.0) + self.register_buffer("t", t, persistent=False) + self.register_buffer("phi", window, persistent=False) + self.register_buffer("weights", weights * window, persistent=False) + + def forward(self, proj: Tensor) -> Tensor: + if proj.ndim != 3: + raise ValueError(f"SIGReg expects (T, B, D), got {tuple(proj.shape)}") + A = torch.randn( + proj.size(-1), self.num_proj, device=proj.device, dtype=proj.dtype + ) + A = A / (A.norm(p=2, dim=0, keepdim=True).clamp_min(1e-6)) + x_t = (proj @ A).unsqueeze(-1) * self.t.to(dtype=proj.dtype) + err = ( + x_t.cos().mean(-3) - self.phi.to(dtype=proj.dtype) + ).square() + x_t.sin().mean(-3).square() + statistic = (err @ self.weights.to(dtype=proj.dtype)) * proj.size(-2) + return statistic.mean().float() + + +class LatentMLP(nn.Module): + def __init__(self, input_dim: int, output_dim: int, hidden_mult: int = 2): + super().__init__() + hidden = hidden_mult * input_dim + self.norm = RMSNorm() + self.fc = CastedLinear(input_dim, hidden, bias=False) + self.proj = CastedLinear(hidden, output_dim, bias=False) + + def forward(self, x: Tensor) -> Tensor: + x = self.norm(x) + x = F.silu(self.fc(x)) + return self.proj(x) + + +class BytePatchJEPA(nn.Module): + def __init__( + self, + *, + vocab_size: int, + num_layers: int, + encoder_repeats: int, + model_dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: int, + rope_base: float, + qk_gain_init: float, + patch_size: int, + latent_dim: int, + decoder_layers: int, + decoder_heads: int, + sigreg_knots: int, + sigreg_num_proj: int, + sigreg_weight: float, + jepa_pred_weight: float, + jepa_ce_weight: float, + ): + super().__init__() + if patch_size < 2: + raise ValueError(f"PATCH_SIZE must be >=2, got {patch_size}") + if decoder_heads <= 0 or model_dim % decoder_heads != 0: + raise ValueError( + f"DECODER_HEADS={decoder_heads} must divide MODEL_DIM={model_dim}" + ) + self.vocab_size = vocab_size + self.patch_size = patch_size + self.encoder_repeats = encoder_repeats + self.sigreg_weight = sigreg_weight + self.jepa_pred_weight = jepa_pred_weight + self.jepa_ce_weight = jepa_ce_weight + self.bos_id = 1 + + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.patch_pos = nn.Parameter( + torch.zeros(patch_size, model_dim, dtype=torch.float32) + ) + self.patch_in = CastedLinear(patch_size * model_dim, model_dim, bias=False) + self.blocks = nn.ModuleList( + [ + Block( + model_dim, + num_heads, + num_kv_heads, + mlp_mult, + rope_base, + qk_gain_init, + ) + for _ in range(num_layers) + ] + ) + self.final_norm = RMSNorm() + self.projector = LatentMLP(model_dim, latent_dim) + self.predictor = LatentMLP(model_dim, latent_dim) + self.sigreg = SIGReg(knots=sigreg_knots, num_proj=sigreg_num_proj) + + self.start_latent = nn.Parameter(torch.zeros(latent_dim, dtype=torch.float32)) + self.decoder_token_emb = nn.Embedding(vocab_size, model_dim) + self.decoder_cond = CastedLinear(latent_dim, model_dim, bias=False) + self.decoder_blocks = nn.ModuleList( + [ + Block( + model_dim, + decoder_heads, + decoder_heads, + mlp_mult, + rope_base, + qk_gain_init, + ) + for _ in range(decoder_layers) + ] + ) + self.decoder_norm = RMSNorm() + self.decoder_out = CastedLinear(model_dim, vocab_size, bias=False) + self._init_weights() + + def _init_weights(self) -> None: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02) + nn.init.normal_(self.decoder_token_emb.weight, mean=0.0, std=0.02) + nn.init.normal_(self.patch_pos, mean=0.0, std=0.02) + nn.init.normal_(self.start_latent, mean=0.0, std=0.02) + for module in self.modules(): + if isinstance(module, nn.Linear) and getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + + def _build_full_sequence( + self, input_ids: Tensor, target_ids: Tensor | None + ) -> Tensor: + if target_ids is None: + raise ValueError( + "BytePatchJEPA requires target_ids so it can reconstruct the full autoregressive stream" + ) + if input_ids.shape != target_ids.shape: + raise ValueError( + f"input_ids and target_ids must match, got {tuple(input_ids.shape)} vs {tuple(target_ids.shape)}" + ) + full = torch.cat((input_ids[:, :1], target_ids), dim=1) + if full.size(1) % self.patch_size != 0: + raise ValueError( + f"Sequence length {full.size(1)} must be divisible by PATCH_SIZE={self.patch_size}; " + "set TRAIN_SEQ_LEN so TRAIN_SEQ_LEN+1 is divisible by PATCH_SIZE" + ) + return full + + def _patchify(self, full_ids: Tensor) -> Tensor: + bsz, seqlen = full_ids.shape + num_patches = seqlen // self.patch_size + return full_ids.view(bsz, num_patches, self.patch_size) + + def _encode_patches(self, patches: Tensor) -> Tensor: + x = self.tok_emb(patches) + x = x + self.patch_pos.to(dtype=x.dtype)[None, None, :, :] + x = F.rms_norm(x, (x.size(-1),)) + return self.patch_in(x.reshape(x.size(0), x.size(1), -1)) + + def _contextualize(self, patch_emb: Tensor) -> Tensor: + x = F.rms_norm(patch_emb, (patch_emb.size(-1),)) + x0 = x + for _ in range(self.encoder_repeats): + for block in self.blocks: + x = block(x, x0) + return self.final_norm(x) + + def _decode_logits(self, cond_latent: Tensor, target_patches: Tensor) -> Tensor: + bsz, num_patches, patch_size = target_patches.shape + total_bytes = num_patches * patch_size + flat_bytes = target_patches.reshape(bsz, total_bytes) + prev = torch.cat( + [flat_bytes.new_full((bsz, 1), self.bos_id), flat_bytes[:, :-1]], dim=1 + ) + x = self.decoder_token_emb(prev) + cond = self.decoder_cond(cond_latent).to(dtype=x.dtype) + x = x + cond.repeat_interleave(patch_size, dim=1) + x0 = x + for block in self.decoder_blocks: + x = block(x, x0) + x = self.decoder_norm(x) + return self.decoder_out(x).reshape( + bsz, num_patches, patch_size, self.vocab_size + ) + + def forward( + self, input_ids: Tensor, target_ids: Tensor | None + ) -> tuple[Tensor, Tensor]: + full = self._build_full_sequence(input_ids, target_ids) + patches = self._patchify(full) + patch_emb = self._encode_patches(patches) + target_latent = self.projector(patch_emb) + context = self._contextualize(patch_emb) + pred_latent = self.predictor(context[:, :-1]) + pred_loss = F.mse_loss( + pred_latent.float(), target_latent[:, 1:].detach().float(), reduction="mean" + ) + sigreg_loss = self.sigreg(target_latent.transpose(0, 1)) + + start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( + patches.size(0), 1, -1 + ) + cond_latent = torch.cat((start, pred_latent), dim=1) + logits = self._decode_logits(cond_latent, patches) + ce = F.cross_entropy( + logits.reshape(-1, self.vocab_size).float(), + patches.reshape(-1), + reduction="none", + ) + ce = ce.reshape_as(patches).float() + mask = torch.ones_like(ce) + mask[:, 0, 0] = 0.0 + nll = (ce * mask).sum() / mask.sum() + total = ( + self.jepa_ce_weight * nll + + self.jepa_pred_weight * pred_loss + + self.sigreg_weight * sigreg_loss + ) + return total, nll + + def forward_logits( + self, input_ids: Tensor, target_ids: Tensor + ) -> Tensor: + full = self._build_full_sequence(input_ids, target_ids) + patches = self._patchify(full) + patch_emb = self._encode_patches(patches) + context = self._contextualize(patch_emb) + pred_latent = self.predictor(context[:, :-1]) + start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( + patches.size(0), 1, -1 + ) + cond_latent = torch.cat((start, pred_latent), dim=1) + logits = self._decode_logits(cond_latent, patches) + bsz = logits.size(0) + return logits.reshape(bsz, -1, self.vocab_size) + + +# ----------------------------- +# TRAINING +# ----------------------------- + + +def main() -> None: + global zeropower_via_newtonschulz5 + + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + zeropower_via_newtonschulz5 = torch.compile(zeropower_via_newtonschulz5) + + # ----------------------------- + # DISTRIBUTED + CUDA SETUP + # ----------------------------- + + distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size <= 0: + raise ValueError(f"WORLD_SIZE must be positive, got {world_size}") + if 8 % world_size != 0: + raise ValueError( + f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral" + ) + grad_accum_steps = 8 // world_size + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + + # Fast math knobs + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + from torch.backends.cuda import ( + enable_cudnn_sdp, + enable_flash_sdp, + enable_math_sdp, + enable_mem_efficient_sdp, + ) + + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + + logfile = None + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + + def log0(msg: str, console: bool = True) -> None: + if not master_process: + return + if console: + print(msg) + if logfile is not None: + with open(logfile, "a", encoding="utf-8") as f: + print(msg, file=f) + + log0(code, console=False) + log0("=" * 100, console=False) + log0(f"Running Python {sys.version}", console=False) + log0(f"Running PyTorch {torch.__version__}", console=False) + log0( + subprocess.run( + ["nvidia-smi"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + check=False, + ).stdout, + console=False, + ) + log0("=" * 100, console=False) + + # ----------------------------- + # TOKENIZER + VALIDATION METRIC SETUP + # ----------------------------- + + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + + if (args.train_seq_len + 1) % args.patch_size != 0: + raise ValueError( + f"JEPA requires TRAIN_SEQ_LEN+1 to be divisible by PATCH_SIZE; " + f"got TRAIN_SEQ_LEN={args.train_seq_len}, PATCH_SIZE={args.patch_size}" + ) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = load_pure_byte_luts( + args.tokenizer_path, args.vocab_size, device + ) + 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) + log0(f"val_bpb:enabled tokenizer_kind=byte tokenizer_path={args.tokenizer_path}") + log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}") + log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}") + + # ----------------------------- + # MODEL + OPTIMIZER SETUP + # ----------------------------- + + base_model: nn.Module = BytePatchJEPA( + vocab_size=args.vocab_size, + num_layers=args.num_layers, + encoder_repeats=args.encoder_repeats, + model_dim=args.model_dim, + num_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + mlp_mult=args.mlp_mult, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + patch_size=args.patch_size, + latent_dim=args.latent_dim, + decoder_layers=args.decoder_layers, + decoder_heads=args.decoder_heads, + sigreg_knots=args.sigreg_knots, + sigreg_num_proj=args.sigreg_num_proj, + sigreg_weight=args.sigreg_weight, + jepa_pred_weight=args.jepa_pred_weight, + jepa_ce_weight=args.jepa_ce_weight, + ) + base_model = base_model.to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + compiled_model = ( + torch.compile(base_model, dynamic=False, fullgraph=False) + if args.use_compile + else base_model + ) + model: nn.Module = ( + DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) + if distributed + else compiled_model + ) + + embedding_tags = ("tok_emb", "decoder_token_emb", "patch_pos") + head_names = {"decoder_out.weight"} + embedding_params: list[Tensor] = [] + head_params: list[Tensor] = [] + matrix_params: list[Tensor] = [] + scalar_params: list[Tensor] = [] + for name, param in base_model.named_parameters(): + if not param.requires_grad: + continue + if name in head_names: + head_params.append(param) + elif any(tag in name for tag in embedding_tags): + embedding_params.append(param) + elif param.ndim == 2 and not any( + pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS + ): + matrix_params.append(param) + else: + scalar_params.append(param) + + token_lr = args.embed_lr + optimizers: list[torch.optim.Optimizer] = [] + if embedding_params: + optimizer_embed = torch.optim.Adam( + [{"params": embedding_params, "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.append(optimizer_embed) + optimizer_muon = None + if matrix_params: + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizers.append(optimizer_muon) + if head_params: + optimizer_head = torch.optim.Adam( + [{"params": head_params, "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.append(optimizer_head) + if scalar_params: + optimizer_scalar = torch.optim.Adam( + [ + { + "params": scalar_params, + "lr": args.scalar_lr, + "base_lr": args.scalar_lr, + } + ], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.append(optimizer_scalar) + + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0( + f"model_family:jepa attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}" + ) + log0( + f"embed_lr:{token_lr} head_lr:{args.head_lr if head_params 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"jepa:patch_size:{args.patch_size} latent_dim:{args.latent_dim} " + f"encoder_layers:{args.num_layers}x{args.encoder_repeats} " + f"decoder_layers:{args.decoder_layers} decoder_heads:{args.decoder_heads} " + f"sigreg_weight:{args.sigreg_weight} pred_weight:{args.jepa_pred_weight} ce_weight:{args.jepa_ce_weight}" + ) + log0(f"seed:{args.seed}") + + # ----------------------------- + # DATA LOADER & MODEL WARMUP + # ----------------------------- + + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + + max_wallclock_ms = ( + 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + ) + + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return ( + max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) + if warmdown_start <= step < args.iterations + else 1.0 + ) + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return ( + remaining_ms / max(warmdown_ms, 1e-9) + if remaining_ms <= warmdown_ms + else 1.0 + ) + + # Warmup primes the compiled forward/backward/optimizer paths, then we restore the + # initial weights/optimizer state so measured training starts from the true init. + if args.warmup_steps > 0: + initial_model_state = { + name: tensor.detach().cpu().clone() + for name, tensor in base_model.state_dict().items() + } + initial_optimizer_states = [ + copy.deepcopy(opt.state_dict()) for opt in optimizers + ] + model.train() + for warmup_step in range(args.warmup_steps): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = ( + micro_step == grad_accum_steps - 1 + ) + x, y = train_loader.next_batch( + args.train_batch_tokens, args.train_seq_len, grad_accum_steps + ) + with torch.autocast( + device_type="cuda", dtype=torch.bfloat16, enabled=True + ): + warmup_loss, _ = model(x, y) + (warmup_loss * grad_scale).backward() + for opt in optimizers: + opt.step() + zero_grad_all() + if ( + args.warmup_steps <= 20 + or (warmup_step + 1) % 10 == 0 + or warmup_step + 1 == args.warmup_steps + ): + log0(f"warmup_step:{warmup_step + 1}/{args.warmup_steps}") + base_model.load_state_dict(initial_model_state, strict=True) + for opt, state in zip(optimizers, initial_optimizer_states, strict=True): + opt.load_state_dict(state) + zero_grad_all() + if distributed: + model.require_backward_grad_sync = True + train_loader = DistributedTokenLoader( + args.train_files, rank, world_size, device + ) + + # ----------------------------- + # MAIN TRAINING LOOP + # ----------------------------- + + ema_state = { + name: t.detach().float().clone() + for name, t in base_model.state_dict().items() + } + training_time_ms = 0.0 + stop_after_step: int | None = None + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or ( + stop_after_step is not None and step >= stop_after_step + ) + + should_validate = last_step or ( + args.val_loss_every > 0 and step % args.val_loss_every == 0 + ) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + 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.late_qat_threshold > 0 + and scale < args.late_qat_threshold + and not CastedLinear._qat_enabled + ): + CastedLinear._qat_enabled = True + log0(f"late_qat:enabled step:{step} scale:{scale:.4f}") + zero_grad_all() + train_loss = torch.zeros((), device=device) + train_nll = 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, nll = model(x, y) + train_loss += loss.detach() + train_nll += nll.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + train_nll /= grad_accum_steps + + if optimizer_muon is not None: + 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() + + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(args.ema_decay).add_( + t.detach().float(), alpha=1.0 - args.ema_decay + ) + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + should_log_train = args.train_log_every > 0 and ( + step <= 10 + or step % args.train_log_every == 0 + or stop_after_step is not None + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms " + f"train_nll:{train_nll.item():.4f}" + ) + + # Needed to sync whether we've reached the wallclock cap. + reached_cap = ( + max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + ) + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + current_sd = base_model.state_dict() + ema_avg = { + name: t.to(dtype=current_sd[name].dtype) for name, t in ema_state.items() + } + base_model.load_state_dict(ema_avg, strict=True) + log0(f"ema:applied EMA weights (decay={args.ema_decay})") + + # ----------------------------- + # SERIALIZATION + ROUNDTRIP VALIDATION + # ----------------------------- + # Save the raw state (useful for debugging/loading in PyTorch directly), then always produce + # the compressed int8+zlib artifact and validate the round-tripped weights. + + if master_process: + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + template_sd = {k: v.cpu() for k, v in base_model.state_dict().items()} + int6_cats = {"mlp", "attn", "other", "embed"} + quant_result, quant_meta = mixed_quantize_int6( + base_model.state_dict(), int6_cats + ) + quant_buf = io.BytesIO() + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + quant_raw = quant_buf.getvalue() + quant_blob = lzma.compress(quant_raw, preset=9) + if master_process: + with open("final_model.int6.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = len(quant_blob) + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int6+lzma: {quant_file_bytes} bytes") + log0(f"Total submission size int6+lzma: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int6.ptz", "rb") as f: + quant_blob_disk = f.read() + quant_state = torch.load( + io.BytesIO(lzma.decompress(quant_blob_disk)), map_location="cpu" + ) + CastedLinear._qat_enabled = False + deq_sd = dequantize_mixed_int6(quant_state["w"], quant_state["m"], template_sd) + base_model.load_state_dict(deq_sd, strict=True) + + if args.ttt_enabled: + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb = eval_val_sliding_ttt( + args, + base_model, + rank, + world_size, + device, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + log_fn=log0, + ) + torch.cuda.synchronize() + log0( + f"final_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms" + ) + log0(f"final_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + + if distributed: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() + +==================================================================================================== +Running Python 3.12.3 (main, Nov 6 2025, 13:44:16) [GCC 13.3.0] +Running PyTorch 2.9.1+cu128 +Wed Mar 25 07:21:53 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 H100 80GB HBM3 On | 00000000:18:00.0 Off | 0 | +| N/A 32C P0 116W / 700W | 1521MiB / 81559MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 1 NVIDIA H100 80GB HBM3 On | 00000000:2A:00.0 Off | 0 | +| N/A 33C P0 115W / 700W | 1521MiB / 81559MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 2 NVIDIA H100 80GB HBM3 On | 00000000:3A:00.0 Off | 0 | +| N/A 35C P0 120W / 700W | 1521MiB / 81559MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 3 NVIDIA H100 80GB HBM3 On | 00000000:5D:00.0 Off | 0 | +| N/A 32C P0 118W / 700W | 1521MiB / 81559MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 4 NVIDIA H100 80GB HBM3 On | 00000000:9A:00.0 Off | 0 | +| N/A 32C P0 115W / 700W | 1521MiB / 81559MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 5 NVIDIA H100 80GB HBM3 On | 00000000:AB:00.0 Off | 0 | +| N/A 35C P0 125W / 700W | 1521MiB / 81559MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 6 NVIDIA H100 80GB HBM3 On | 00000000:BA:00.0 Off | 0 | +| N/A 36C P0 124W / 700W | 1521MiB / 81559MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ +| 7 NVIDIA H100 80GB HBM3 On | 00000000:DB:00.0 Off | 0 | +| N/A 34C P0 117W / 700W | 1521MiB / 81559MiB | 0% Default | +| | | Disabled | ++-----------------------------------------+------------------------+----------------------+ + ++-----------------------------------------------------------------------------------------+ +| Processes: | +| GPU GI CI PID Type Process name GPU Memory | +| ID ID Usage | +|=========================================================================================| +| 0 N/A N/A 113127 C /usr/local/bin/python 1512MiB | +| 1 N/A N/A 113128 C /usr/local/bin/python 1512MiB | +| 2 N/A N/A 113129 C /usr/local/bin/python 1512MiB | +| 3 N/A N/A 113130 C /usr/local/bin/python 1512MiB | +| 4 N/A N/A 113131 C /usr/local/bin/python 1512MiB | +| 5 N/A N/A 113132 C /usr/local/bin/python 1512MiB | +| 6 N/A N/A 113133 C /usr/local/bin/python 1512MiB | +| 7 N/A N/A 113134 C /usr/local/bin/python 1574MiB | ++-----------------------------------------------------------------------------------------+ + +==================================================================================================== +val_bpb:enabled tokenizer_kind=byte tokenizer_path=./data/tokenizers/fineweb_pure_byte_260.json +train_loader:dataset:fineweb10B_byte260 train_shards:476 +val_loader:shards pattern=./data/datasets/fineweb10B_byte260/fineweb_val_*.bin tokens:151130010 +model_params:24593530 +world_size:8 grad_accum_steps:1 +sdp_backends:cudnn=False flash=True mem_efficient=False math=False +model_family:jepa attention_mode:gqa num_heads:6 num_kv_heads:3 +embed_lr:0.1 head_lr:0.02 matrix_lr:0.025 scalar_lr:0.025 +train_batch_tokens:524032 train_seq_len:2047 iterations:20000 warmup_steps:20 max_wallclock_seconds:600.000 +jepa:patch_size:8 latent_dim:192 encoder_layers:5x2 decoder_layers:7 decoder_heads:4 sigreg_weight:0.02 pred_weight:0.5 ce_weight:3.0 +seed:1337 +warmup_step:1/20 +warmup_step:2/20 +warmup_step:3/20 +warmup_step:4/20 +warmup_step:5/20 +warmup_step:6/20 +warmup_step:7/20 +warmup_step:8/20 +warmup_step:9/20 +warmup_step:10/20 +warmup_step:11/20 +warmup_step:12/20 +warmup_step:13/20 +warmup_step:14/20 +warmup_step:15/20 +warmup_step:16/20 +warmup_step:17/20 +warmup_step:18/20 +warmup_step:19/20 +warmup_step:20/20 +step:0/20000 val_loss:5.7267 val_bpb:8.2646 train_time:0ms step_avg:0.02ms +step:1/20000 train_loss:17.4625 train_time:51ms step_avg:51.26ms train_nll:5.7258 +step:2/20000 train_loss:10.6920 train_time:129ms step_avg:64.30ms train_nll:3.4483 +step:3/20000 train_loss:14.9531 train_time:201ms step_avg:66.88ms train_nll:4.8705 +step:4/20000 train_loss:17.4393 train_time:293ms step_avg:73.37ms train_nll:5.7000 +step:5/20000 train_loss:16.3567 train_time:360ms step_avg:71.95ms train_nll:5.3382 +step:6/20000 train_loss:13.6743 train_time:422ms step_avg:70.27ms train_nll:4.4436 +step:7/20000 train_loss:12.1056 train_time:484ms step_avg:69.16ms train_nll:3.9231 +step:8/20000 train_loss:11.5807 train_time:549ms step_avg:68.61ms train_nll:3.7465 +step:9/20000 train_loss:10.5678 train_time:622ms step_avg:69.15ms train_nll:3.4076 +step:10/20000 train_loss:9.4190 train_time:689ms step_avg:68.86ms train_nll:3.0247 +step:200/20000 train_loss:4.6065 train_time:10651ms step_avg:53.25ms train_nll:1.3689 +step:400/20000 train_loss:3.8563 train_time:21124ms step_avg:52.81ms train_nll:1.1215 +step:600/20000 train_loss:3.7338 train_time:31561ms step_avg:52.60ms train_nll:1.0938 +step:800/20000 train_loss:3.6790 train_time:42042ms step_avg:52.55ms train_nll:1.0575 +step:1000/20000 train_loss:3.5428 train_time:52542ms step_avg:52.54ms train_nll:1.0218 +step:1000/20000 val_loss:1.0499 val_bpb:1.5151 train_time:52557ms step_avg:52.56ms +step:1200/20000 train_loss:3.5167 train_time:63001ms step_avg:52.50ms train_nll:1.0131 +step:1400/20000 train_loss:3.2587 train_time:73463ms step_avg:52.47ms train_nll:0.9166 +step:1600/20000 train_loss:3.6064 train_time:83983ms step_avg:52.49ms train_nll:1.0351 +step:1800/20000 train_loss:3.5310 train_time:94458ms step_avg:52.48ms train_nll:0.9978 +step:2000/20000 train_loss:3.7186 train_time:105368ms step_avg:52.68ms train_nll:1.0663 +step:2000/20000 val_loss:1.0029 val_bpb:1.4473 train_time:105386ms step_avg:52.69ms +step:2200/20000 train_loss:3.7677 train_time:115842ms step_avg:52.66ms train_nll:1.0780 +step:2400/20000 train_loss:3.7093 train_time:126351ms step_avg:52.65ms train_nll:1.0675 +step:2600/20000 train_loss:3.3906 train_time:136837ms step_avg:52.63ms train_nll:0.9562 +step:2800/20000 train_loss:3.2422 train_time:147379ms step_avg:52.64ms train_nll:0.9160 +step:3000/20000 train_loss:3.4084 train_time:157852ms step_avg:52.62ms train_nll:0.9649 +step:3000/20000 val_loss:0.9708 val_bpb:1.4011 train_time:158088ms step_avg:52.70ms +step:3200/20000 train_loss:3.5958 train_time:168550ms step_avg:52.67ms train_nll:1.0260 +step:3400/20000 train_loss:3.1654 train_time:179031ms step_avg:52.66ms train_nll:0.8834 +step:3600/20000 train_loss:3.6967 train_time:189518ms step_avg:52.64ms train_nll:1.0675 +step:3800/20000 train_loss:3.2243 train_time:200025ms step_avg:52.64ms train_nll:0.9105 +step:4000/20000 train_loss:3.3632 train_time:210512ms step_avg:52.63ms train_nll:0.9515 +step:4000/20000 val_loss:0.9552 val_bpb:1.3785 train_time:210559ms step_avg:52.64ms +step:4200/20000 train_loss:3.8358 train_time:221110ms step_avg:52.65ms train_nll:1.1118 +step:4400/20000 train_loss:3.3259 train_time:231669ms step_avg:52.65ms train_nll:0.9440 +step:4600/20000 train_loss:3.3795 train_time:242224ms step_avg:52.66ms train_nll:0.9569 +step:4800/20000 train_loss:3.5052 train_time:252868ms step_avg:52.68ms train_nll:0.9996 +step:5000/20000 train_loss:3.2205 train_time:263367ms step_avg:52.67ms train_nll:0.9033 +step:5000/20000 val_loss:0.9456 val_bpb:1.3647 train_time:263377ms step_avg:52.68ms +step:5200/20000 train_loss:3.4042 train_time:273844ms step_avg:52.66ms train_nll:0.9668 +step:5400/20000 train_loss:3.1148 train_time:284411ms step_avg:52.67ms train_nll:0.8684 +step:5600/20000 train_loss:3.1827 train_time:295250ms step_avg:52.72ms train_nll:0.8938 +step:5800/20000 train_loss:3.3356 train_time:305722ms step_avg:52.71ms train_nll:0.9434 +step:6000/20000 train_loss:3.2738 train_time:316172ms step_avg:52.70ms train_nll:0.9186 +step:6000/20000 val_loss:0.9366 val_bpb:1.3516 train_time:316213ms step_avg:52.70ms +step:6200/20000 train_loss:3.3231 train_time:326677ms step_avg:52.69ms train_nll:0.9383 +step:6400/20000 train_loss:3.2536 train_time:337255ms step_avg:52.70ms train_nll:0.9176 +step:6600/20000 train_loss:3.5093 train_time:347780ms step_avg:52.69ms train_nll:0.9987 +step:6800/20000 train_loss:3.2054 train_time:358289ms step_avg:52.69ms train_nll:0.9062 +step:7000/20000 train_loss:3.1688 train_time:368788ms step_avg:52.68ms train_nll:0.8903 +step:7000/20000 val_loss:0.9303 val_bpb:1.3426 train_time:368876ms step_avg:52.70ms +step:7200/20000 train_loss:3.3735 train_time:379371ms step_avg:52.69ms train_nll:0.9595 +step:7400/20000 train_loss:3.3234 train_time:389858ms step_avg:52.68ms train_nll:0.9411 +step:7600/20000 train_loss:3.1800 train_time:400349ms step_avg:52.68ms train_nll:0.8939 +step:7800/20000 train_loss:3.3215 train_time:410873ms step_avg:52.68ms train_nll:0.9446 +step:8000/20000 train_loss:3.3581 train_time:421985ms step_avg:52.75ms train_nll:0.9566 +step:8000/20000 val_loss:0.9255 val_bpb:1.3357 train_time:422026ms step_avg:52.75ms +step:8200/20000 train_loss:3.0966 train_time:432446ms step_avg:52.74ms train_nll:0.8692 +step:8400/20000 train_loss:3.1878 train_time:443052ms step_avg:52.74ms train_nll:0.9005 +step:8600/20000 train_loss:3.3169 train_time:453513ms step_avg:52.73ms train_nll:0.9429 +step:8800/20000 train_loss:3.1833 train_time:464027ms step_avg:52.73ms train_nll:0.8965 +step:9000/20000 train_loss:3.2438 train_time:474607ms step_avg:52.73ms train_nll:0.9195 +step:9000/20000 val_loss:0.9159 val_bpb:1.3218 train_time:474648ms step_avg:52.74ms +step:9200/20000 train_loss:3.4596 train_time:485132ms step_avg:52.73ms train_nll:0.9910 +step:9400/20000 train_loss:3.1521 train_time:495634ms step_avg:52.73ms train_nll:0.8895 +step:9600/20000 train_loss:3.1821 train_time:506153ms step_avg:52.72ms train_nll:0.8979 +step:9800/20000 train_loss:2.9465 train_time:518663ms step_avg:52.92ms train_nll:0.8222 +step:10000/20000 train_loss:3.2177 train_time:536754ms step_avg:53.68ms train_nll:0.9111 +step:10000/20000 val_loss:0.9049 val_bpb:1.3060 train_time:536788ms step_avg:53.68ms +step:10200/20000 train_loss:3.4921 train_time:554442ms step_avg:54.36ms train_nll:1.0035 +late_qat:enabled step:10307 scale:0.1499 +step:10400/20000 train_loss:3.2117 train_time:576285ms step_avg:55.41ms train_nll:0.9103 +step:10600/20000 train_loss:3.2104 train_time:597777ms step_avg:56.39ms train_nll:0.9100 +step:10635/20000 val_loss:0.8978 val_bpb:1.2957 train_time:599732ms step_avg:56.39ms +stopping_early: wallclock_cap train_time:599732ms step:10635/20000 +peak memory allocated: 9994 MiB reserved: 10674 MiB +ema:applied EMA weights (decay=0.997) +Serialized model: 97916829 bytes +Code size: 66315 bytes +Total submission size: 97983144 bytes +Serialized model int6+lzma: 15625312 bytes +Total submission size int6+lzma: 15691627 bytes +ttt:start chunks=4613 chunk_tokens=32768 windows=590344 stride=256 lr=0.002 epochs=2 freeze=0 + ttt_chunk [1/4613] bpb=1.383510 time=0.7s infer=0.1s adapt=0.6s + ttt_chunk [51/4613] bpb=1.248402 time=7.0s infer=1.1s adapt=5.8s + ttt_chunk [101/4613] bpb=1.266169 time=12.9s infer=2.2s adapt=10.6s + ttt_chunk [151/4613] bpb=1.264800 time=18.7s infer=3.2s adapt=15.4s + ttt_chunk [201/4613] bpb=1.255718 time=24.6s infer=4.3s adapt=20.2s + ttt_chunk [251/4613] bpb=1.254907 time=30.5s infer=5.4s adapt=24.9s + ttt_chunk [301/4613] bpb=1.250381 time=36.4s infer=6.4s adapt=29.7s + ttt_chunk [351/4613] bpb=1.255968 time=42.3s infer=7.5s adapt=34.5s + ttt_chunk [401/4613] bpb=1.262355 time=48.6s infer=8.5s adapt=39.7s + ttt_chunk [451/4613] bpb=1.264830 time=54.4s infer=9.6s adapt=44.5s + ttt_chunk [501/4613] bpb=1.265259 time=60.3s infer=10.7s adapt=49.2s + ttt_chunk [551/4613] bpb=1.264232 time=66.1s infer=11.7s adapt=54.0s + ttt_chunk [601/4613] bpb=1.262626 time=71.9s infer=12.8s adapt=58.7s + ttt_chunk [651/4613] bpb=1.259686 time=77.8s infer=13.9s adapt=63.5s + ttt_chunk [701/4613] bpb=1.262247 time=83.8s infer=14.9s adapt=68.3s + ttt_chunk [751/4613] bpb=1.263253 time=89.7s infer=16.0s adapt=73.1s + ttt_chunk [801/4613] bpb=1.263017 time=95.5s infer=17.1s adapt=77.9s + ttt_chunk [851/4613] bpb=1.266006 time=101.4s infer=18.1s adapt=82.6s + ttt_chunk [901/4613] bpb=1.264395 time=107.3s infer=19.2s adapt=87.4s + ttt_chunk [951/4613] bpb=1.264736 time=113.3s infer=20.3s adapt=92.3s + ttt_chunk [1001/4613] bpb=1.261512 time=119.5s infer=21.3s adapt=97.4s + ttt_chunk [1051/4613] bpb=1.260506 time=125.4s infer=22.4s adapt=102.2s + ttt_chunk [1101/4613] bpb=1.259694 time=131.2s infer=23.5s adapt=106.9s + ttt_chunk [1151/4613] bpb=1.260782 time=137.1s infer=24.5s adapt=111.7s + ttt_chunk [1201/4613] bpb=1.260247 time=142.9s infer=25.6s adapt=116.4s + ttt_chunk [1251/4613] bpb=1.258353 time=148.7s infer=26.6s adapt=121.2s + ttt_chunk [1301/4613] bpb=1.258421 time=154.6s infer=27.7s adapt=126.0s + ttt_chunk [1351/4613] bpb=1.259165 time=160.5s infer=28.8s adapt=130.8s + ttt_chunk [1401/4613] bpb=1.259510 time=166.4s infer=29.8s adapt=135.6s + ttt_chunk [1451/4613] bpb=1.260058 time=172.3s infer=30.9s adapt=140.4s + ttt_chunk [1501/4613] bpb=1.259122 time=178.2s infer=31.9s adapt=145.1s + ttt_chunk [1551/4613] bpb=1.258331 time=184.0s infer=33.0s adapt=149.9s + ttt_chunk [1601/4613] bpb=1.257210 time=189.9s infer=34.0s adapt=154.7s + ttt_chunk [1651/4613] bpb=1.256086 time=195.8s infer=35.1s adapt=159.5s + ttt_chunk [1701/4613] bpb=1.256455 time=201.7s infer=36.1s adapt=164.2s + ttt_chunk [1751/4613] bpb=1.256436 time=207.5s infer=37.2s adapt=169.0s + ttt_chunk [1801/4613] bpb=1.257130 time=213.1s infer=38.2s adapt=173.5s + ttt_chunk [1851/4613] bpb=1.257146 time=218.7s infer=39.3s adapt=178.0s + ttt_chunk [1901/4613] bpb=1.257087 time=224.3s infer=40.3s adapt=182.5s + ttt_chunk [1951/4613] bpb=1.256750 time=229.9s infer=41.4s adapt=187.1s + ttt_chunk [2001/4613] bpb=1.257252 time=235.5s infer=42.4s adapt=191.6s + ttt_chunk [2051/4613] bpb=1.256094 time=241.1s infer=43.5s adapt=196.1s + ttt_chunk [2101/4613] bpb=1.256414 time=246.7s infer=44.5s adapt=200.6s + ttt_chunk [2151/4613] bpb=1.256680 time=252.3s infer=45.5s adapt=205.1s + ttt_chunk [2201/4613] bpb=1.256376 time=257.8s infer=46.6s adapt=209.6s + ttt_chunk [2251/4613] bpb=1.256196 time=263.4s infer=47.6s adapt=214.1s + ttt_chunk [2301/4613] bpb=1.256939 time=269.1s infer=48.7s adapt=218.6s + ttt_chunk [2351/4613] bpb=1.257198 time=274.8s infer=49.7s adapt=223.2s + ttt_chunk [2401/4613] bpb=1.256933 time=280.4s infer=50.8s adapt=227.8s + ttt_chunk [2451/4613] bpb=1.257694 time=286.1s infer=51.8s adapt=232.3s + ttt_chunk [2501/4613] bpb=1.258277 time=291.8s infer=52.9s adapt=236.9s + ttt_chunk [2551/4613] bpb=1.259083 time=297.5s infer=54.0s adapt=241.4s + ttt_chunk [2601/4613] bpb=1.259337 time=304.1s infer=55.0s adapt=247.0s + ttt_chunk [2651/4613] bpb=1.259552 time=310.6s infer=56.0s adapt=252.4s + ttt_chunk [2701/4613] bpb=1.259383 time=316.2s infer=57.0s adapt=256.9s + ttt_chunk [2751/4613] bpb=1.258928 time=322.1s infer=58.1s adapt=261.8s + ttt_chunk [2801/4613] bpb=1.259509 time=328.2s infer=59.1s adapt=266.7s + ttt_chunk [2851/4613] bpb=1.259320 time=334.2s infer=60.2s adapt=271.7s + ttt_chunk [2901/4613] bpb=1.259253 time=340.1s infer=61.2s adapt=276.4s + ttt_chunk [2951/4613] bpb=1.259022 time=346.0s infer=62.2s adapt=281.2s + ttt_chunk [3001/4613] bpb=1.259039 time=351.8s infer=63.3s adapt=285.9s + ttt_chunk [3051/4613] bpb=1.258344 time=357.6s infer=64.3s adapt=290.7s + ttt_chunk [3101/4613] bpb=1.257677 time=363.4s infer=65.4s adapt=295.4s + ttt_chunk [3151/4613] bpb=1.257152 time=369.2s infer=66.4s adapt=300.2s + ttt_chunk [3201/4613] bpb=1.256702 time=375.0s infer=67.4s adapt=304.9s + ttt_chunk [3251/4613] bpb=1.256289 time=381.0s infer=68.5s adapt=309.8s + ttt_chunk [3301/4613] bpb=1.256041 time=386.8s infer=69.5s adapt=314.5s + ttt_chunk [3351/4613] bpb=1.256386 time=392.6s infer=70.6s adapt=319.3s + ttt_chunk [3401/4613] bpb=1.256062 time=398.5s infer=71.6s adapt=324.0s + ttt_chunk [3451/4613] bpb=1.256089 time=404.4s infer=72.7s adapt=328.8s + ttt_chunk [3501/4613] bpb=1.256422 time=410.3s infer=73.7s adapt=333.6s + ttt_chunk [3551/4613] bpb=1.256380 time=416.2s infer=74.8s adapt=338.3s + ttt_chunk [3601/4613] bpb=1.257363 time=422.1s infer=75.9s adapt=343.1s + ttt_chunk [3651/4613] bpb=1.257763 time=428.0s infer=76.9s adapt=347.9s + ttt_chunk [3701/4613] bpb=1.258106 time=433.8s infer=78.0s adapt=352.7s + ttt_chunk [3751/4613] bpb=1.258644 time=439.6s infer=79.1s adapt=357.4s + ttt_chunk [3801/4613] bpb=1.259198 time=445.4s infer=80.1s adapt=362.1s + ttt_chunk [3851/4613] bpb=1.259429 time=451.2s infer=81.2s adapt=366.8s + ttt_chunk [3901/4613] bpb=1.259626 time=457.1s infer=82.2s adapt=371.6s + ttt_chunk [3951/4613] bpb=1.260085 time=462.9s infer=83.3s adapt=376.3s + ttt_chunk [4001/4613] bpb=1.260107 time=468.7s infer=84.4s adapt=381.0s + ttt_chunk [4051/4613] bpb=1.260225 time=474.6s infer=85.4s adapt=385.8s + ttt_chunk [4101/4613] bpb=1.260508 time=480.9s infer=86.5s adapt=390.6s + ttt_chunk [4151/4613] bpb=1.260518 time=486.7s infer=87.6s adapt=395.3s + ttt_chunk [4201/4613] bpb=1.260612 time=492.7s infer=88.6s adapt=400.1s + ttt_chunk [4251/4613] bpb=1.260404 time=498.7s infer=89.7s adapt=405.0s + ttt_chunk [4301/4613] bpb=1.260108 time=504.6s infer=90.7s adapt=409.8s + ttt_chunk [4351/4613] bpb=1.259661 time=510.6s infer=91.8s adapt=414.7s + ttt_chunk [4401/4613] bpb=1.259447 time=516.6s infer=92.9s adapt=419.5s + ttt_chunk [4451/4613] bpb=1.259507 time=522.5s infer=93.9s adapt=424.3s + ttt_chunk [4501/4613] bpb=1.259333 time=528.4s infer=95.0s adapt=429.1s + ttt_chunk [4551/4613] bpb=1.259071 time=534.6s infer=96.0s adapt=434.0s + ttt_chunk [4601/4613] bpb=1.258839 time=540.5s infer=97.1s adapt=438.9s + ttt_chunk [4613/4613] bpb=1.258990 time=541.9s infer=97.3s adapt=439.9s +final_ttt val_loss:0.8746 val_bpb:1.2622 eval_time:542243ms +final_ttt_exact val_loss:0.87456928 val_bpb:1.26215432 diff --git a/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/train_gpt.py b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/train_gpt.py new file mode 100644 index 000000000..cafb3b63d --- /dev/null +++ b/records/track_non_record_16mb/2026-03-25_JEPA_BytePatch_INT6_LZMA_TTT/train_gpt.py @@ -0,0 +1,1708 @@ +""" +The `train_gpt.py` and `train_gpt_mlx.py` scripts are intended as good launching-off points for new participants, not SOTA configs. We'll accept PRs that tune, improve, or simplify these scripts without significantly increasing complexity, but competitive submissions should stay in the `/records` folder. + +Hard stop: To keep readable for newcomers, let's make sure `train_gpt.py` and `train_gpt_mlx.py` never are longer than 1500 lines. +""" + +from __future__ import annotations + +import copy +import glob +import io +import json +import lzma +import math +import os +import random +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import numpy as np +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 + +# ----------------------------- +# HYPERPARAMETERS +# ----------------------------- +# Default JEPA run: +# - pure-byte FineWeb export (`byte260`) +# - byte-patch JEPA with latent next-patch prediction plus a small causal byte decoder +# - 5 encoder layers × 2 depth-recurrent repeats at width 480, 6 heads with 3 KV heads +# - 7-layer causal decoder at width 480, 4 heads +# - sequence length 2047 so the reconstructed AR stream has 2048 bytes, cleanly divisible by patch size 8 +# - 524,032 train tokens per step for 20,000 iterations with a ~10 minute cap + + +class Hyperparameters: + # Data paths are shard globs produced by the existing preprocessing pipeline. + data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_byte260") + 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_pure_byte_260.json" + ) + run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) + seed = int(os.environ.get("SEED", 1337)) + + # Validation cadence and batch size. Validation always uses the full fineweb_val split. + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_160)) + val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) + val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 256)) + val_sliding_batch = int(os.environ.get("VAL_SLIDING_BATCH", 32)) + ema_decay = float(os.environ.get("EMA_DECAY", 0.997)) + late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", 0.15)) + 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", 2)) + ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) + ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 0)) + 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)) + train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200)) + + # Training length. + iterations = int(os.environ.get("ITERATIONS", 20000)) + warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3500)) + warmup_steps = int(os.environ.get("WARMUP_STEPS", 20)) + train_batch_tokens = int(os.environ.get("TRAIN_BATCH_TOKENS", 524_032)) + train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2047)) + max_wallclock_seconds = float(os.environ.get("MAX_WALLCLOCK_SECONDS", 600.0)) + qk_gain_init = float(os.environ.get("QK_GAIN_INIT", 1.5)) + use_compile = bool(int(os.environ.get("USE_COMPILE", "1"))) + + # Model shape. + vocab_size = int(os.environ.get("VOCAB_SIZE", 260)) + num_layers = int(os.environ.get("NUM_LAYERS", 5)) + encoder_repeats = int(os.environ.get("ENCODER_REPEATS", 2)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 3)) + model_dim = int(os.environ.get("MODEL_DIM", 480)) + num_heads = int(os.environ.get("NUM_HEADS", 6)) + mlp_mult = int(os.environ.get("MLP_MULT", 2)) + rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) + patch_size = int(os.environ.get("PATCH_SIZE", 8)) + latent_dim = int(os.environ.get("LATENT_DIM", 192)) + decoder_layers = int(os.environ.get("DECODER_LAYERS", 7)) + decoder_heads = int(os.environ.get("DECODER_HEADS", 4)) + sigreg_weight = float(os.environ.get("SIGREG_WEIGHT", 0.02)) + sigreg_knots = int(os.environ.get("SIGREG_KNOTS", 17)) + sigreg_num_proj = int(os.environ.get("SIGREG_NUM_PROJ", 256)) + jepa_pred_weight = float(os.environ.get("JEPA_PRED_WEIGHT", 0.5)) + jepa_ce_weight = float(os.environ.get("JEPA_CE_WEIGHT", 3.0)) + + # Optimizer hyperparameters. + embed_lr = float(os.environ.get("EMBED_LR", 0.1)) + head_lr = float(os.environ.get("HEAD_LR", 0.02)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.025)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.025)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) + muon_momentum_warmup_start = float( + os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92) + ) + muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + beta1 = float(os.environ.get("BETA1", 0.9)) + beta2 = float(os.environ.get("BETA2", 0.95)) + adam_eps = float(os.environ.get("ADAM_EPS", 1e-8)) + grad_clip_norm = float(os.environ.get("GRAD_CLIP_NORM", 0.0)) + + +# ----------------------------- +# MUON OPTIMIZER +# ----------------------------- +# +# As borrowed from modded-nanogpt +# Background on Muon: https://kellerjordan.github.io/posts/muon/ + + +def zeropower_via_newtonschulz5( + G: Tensor, steps: int = 10, eps: float = 1e-7 +) -> Tensor: + # Orthogonalize a 2D update matrix with a fast Newton-Schulz iteration. + # Muon uses this to normalize matrix-shaped gradients before applying them. + a, b, c = (3.4445, -4.7750, 2.0315) + X = G.bfloat16() + X /= X.norm() + eps + transposed = G.size(0) > G.size(1) + if transposed: + X = X.T + for _ in range(steps): + A = X @ X.T + B = b * A + c * A @ A + X = a * X + B @ X + return X.T if transposed else X + + +class Muon(torch.optim.Optimizer): + def __init__( + self, + params, + lr: float, + momentum: float, + backend_steps: int, + nesterov: bool = True, + ): + super().__init__( + params, + dict( + lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov + ), + ) + + @torch.no_grad() + def step(self, closure=None): + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + distributed = dist.is_available() and dist.is_initialized() + world_size = dist.get_world_size() if distributed else 1 + rank = dist.get_rank() if distributed else 0 + + for group in self.param_groups: + params = group["params"] + if not params: + continue + lr = group["lr"] + momentum = group["momentum"] + backend_steps = group["backend_steps"] + nesterov = group["nesterov"] + + total_params = sum(int(p.numel()) for p in params) + updates_flat = torch.zeros( + total_params, device=params[0].device, dtype=torch.bfloat16 + ) + + curr = 0 + for i, p in enumerate(params): + if i % world_size == rank and p.grad is not None: + g = p.grad + state = self.state[p] + if "momentum_buffer" not in state: + state["momentum_buffer"] = torch.zeros_like(g) + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(g) + if nesterov: + g = g.add(buf, alpha=momentum) + g = zeropower_via_newtonschulz5(g, steps=backend_steps) + # Scale correction from Muon reference implementations. + g *= max(1, g.size(0) / g.size(1)) ** 0.5 + updates_flat[curr : curr + p.numel()] = g.reshape(-1) + curr += p.numel() + + if distributed: + dist.all_reduce(updates_flat, op=dist.ReduceOp.SUM) + + 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) + curr += p.numel() + + return loss + + +# ----------------------------- +# TOKENIZER-AGNOSTIC EVALUATION SETUP +# ----------------------------- +# +# We score BPB (bits-per-byte), but the model is fixed to a pure-byte vocabulary: +# 4 special ids followed by raw UTF-8 bytes. That makes byte accounting exact. +def build_pure_byte_luts( + vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + table_size = max(vocab_size, 260) + base_bytes_np = np.zeros((table_size,), dtype=np.int16) + base_bytes_np[4 : min(table_size, 260)] = 1 + has_leading_space_np = np.zeros((table_size,), dtype=np.bool_) + is_boundary_token_np = np.ones((table_size,), dtype=np.bool_) + return ( + torch.tensor(base_bytes_np[:vocab_size], dtype=torch.int16, device=device), + torch.tensor( + has_leading_space_np[:vocab_size], dtype=torch.bool, device=device + ), + torch.tensor( + is_boundary_token_np[:vocab_size], dtype=torch.bool, device=device + ), + ) + + +def load_pure_byte_luts( + tokenizer_path: str, vocab_size: int, device: torch.device +) -> tuple[Tensor, Tensor, Tensor]: + path = Path(tokenizer_path) + if path.suffix != ".json": + raise ValueError( + f"Pure-byte JEPA expects a tokenizer JSON at {tokenizer_path!r}" + ) + payload = json.loads(path.read_text(encoding="utf-8")) + tokenizer_type = payload.get("tokenizer_type") or payload.get("kind") + json_vocab_size = int(payload.get("vocab_size", vocab_size)) + if tokenizer_type != "pure_byte": + raise ValueError( + f"Unsupported tokenizer JSON {tokenizer_path}: expected pure_byte, got {tokenizer_type!r}" + ) + if json_vocab_size != vocab_size: + raise ValueError( + f"VOCAB_SIZE={vocab_size} does not match tokenizer vocab_size={json_vocab_size}" + ) + return build_pure_byte_luts(vocab_size, device) + + +def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: + files = [Path(p) for p in sorted(glob.glob(pattern))] + if not files: + raise FileNotFoundError(f"No files found for pattern: {pattern}") + # The export pipeline writes the fixed first-50k-doc validation set to fineweb_val_*. + tokens = torch.cat([load_data_shard(file) for file in files]).contiguous() + usable = ((tokens.numel() - 1) // seq_len) * seq_len + if usable <= 0: + raise ValueError(f"Validation split is too short for TRAIN_SEQ_LEN={seq_len}") + return tokens[: usable + 1] + + +def eval_val( + args: Hyperparameters, + model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + grad_accum_steps: int, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, +) -> tuple[float, float]: + # Validation computes two metrics: + # - val_loss: token cross-entropy (natural log) + # - val_bpb: tokenizer-agnostic compression metric used by the challenge + 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) + batch_loss = batch_loss.detach() + batch_token_count = float(y.numel()) + val_loss_sum += batch_loss.to(torch.float64) * batch_token_count + val_token_count += batch_token_count + prev_ids = x.reshape(-1) + tgt_ids = y.reshape(-1) + token_bytes = base_bytes_lut[tgt_ids].to(dtype=torch.int16) + token_bytes += ( + has_leading_space_lut[tgt_ids] & ~is_boundary_token_lut[prev_ids] + ).to(dtype=torch.int16) + val_byte_count += token_bytes.to(torch.float64).sum() + + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(val_loss_sum, op=dist.ReduceOp.SUM) + dist.all_reduce(val_token_count, op=dist.ReduceOp.SUM) + dist.all_reduce(val_byte_count, op=dist.ReduceOp.SUM) + + val_loss = val_loss_sum / val_token_count + bits_per_token = val_loss.item() / math.log(2.0) + tokens_per_byte = val_token_count.item() / val_byte_count.item() + model.train() + return float(val_loss.item()), float(bits_per_token * tokens_per_byte) + + +def eval_val_sliding_ttt( + args: Hyperparameters, + base_model: nn.Module, + rank: int, + world_size: int, + device: torch.device, + val_tokens: Tensor, + base_bytes_lut: Tensor, + has_leading_space_lut: Tensor, + is_boundary_token_lut: Tensor, + log_fn=print, +) -> tuple[float, float]: + seq_len = args.train_seq_len + stride = args.val_sliding_stride + batch_seqs = args.ttt_batch_seqs + 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 >= seq_len + ] + 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) + + log_fn( + f"ttt:start chunks={num_chunks} chunk_tokens={ttt_chunk} " + f"windows={len(window_starts)} stride={stride} " + f"lr={args.ttt_lr} epochs={args.ttt_epochs} freeze={args.ttt_freeze_blocks}" + ) + + loss_sum = torch.zeros((), device=device, dtype=torch.float64) + token_count = torch.zeros((), device=device, dtype=torch.float64) + byte_count = torch.zeros((), device=device, dtype=torch.float64) + + frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) + ttt_params = [] + for name, p in base_model.named_parameters(): + freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) + if freeze: + p.requires_grad_(False) + else: + p.requires_grad_(True) + ttt_params.append(p) + + optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) + t0 = time.perf_counter() + t_infer_total = 0.0 + t_adapt_total = 0.0 + + for ci in range(num_chunks): + windows = chunk_windows[ci] + if not windows: + continue + + my_s = (len(windows) * rank) // world_size + my_e = (len(windows) * (rank + 1)) // world_size + my_windows = windows[my_s:my_e] + + torch.cuda.synchronize() + t_infer = time.perf_counter() + 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) + for i, ws in enumerate(batch_ws): + chunk_tok = val_tokens[ws : ws + seq_len + 1].to( + dtype=torch.int64, device=device + ) + x_batch[i] = chunk_tok[:-1] + y_batch[i] = chunk_tok[1:] + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + logits = base_model.forward_logits(x_batch, y_batch) + nll = F.cross_entropy( + logits[:, 1:].reshape(-1, logits.size(-1)).float(), + y_batch.reshape(-1), + reduction="none", + ).reshape(bsz, seq_len) + for i, ws in enumerate(batch_ws): + s = 0 if ws == 0 else seq_len - stride + scored = nll[i, s:seq_len].to(torch.float64) + loss_sum += scored.sum() + token_count += float(seq_len - s) + tgt = y_batch[i, s:seq_len] + prev = x_batch[i, s:seq_len] + 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() + + torch.cuda.synchronize() + t_infer_total += time.perf_counter() - t_infer + + is_last_chunk = ci == num_chunks - 1 + t_adapt = time.perf_counter() + if not is_last_chunk and args.ttt_epochs > 0: + base_model.train() + chunk_start = ci * ttt_chunk + chunk_end = min((ci + 1) * ttt_chunk, total_tokens) + chunk_seqs = (chunk_end - chunk_start) // seq_len + if chunk_seqs > 0: + 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 + for _ep in range(args.ttt_epochs): + for bs in range(my_seq_s, my_seq_e, args.ttt_batch_seqs): + be = min(bs + args.ttt_batch_seqs, my_seq_e) + start_tok = chunk_start + bs * seq_len + end_tok = chunk_start + 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): + logits = base_model.forward_logits(x, y) + ce = F.cross_entropy( + logits[:, 1:].reshape(-1, logits.size(-1)).float(), + y.reshape(-1), + ) + ce.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() + + torch.cuda.synchronize() + t_adapt_total += time.perf_counter() - t_adapt + + if rank == 0 and (ci % 50 == 0 or ci == num_chunks - 1): + elapsed = time.perf_counter() - t0 + rl = loss_sum.item() / max(token_count.item(), 1) + rbpb = ( + rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) + if token_count.item() > 0 + else 0.0 + ) + log_fn( + f" ttt_chunk [{ci + 1}/{num_chunks}] bpb={rbpb:.6f} " + f"time={elapsed:.1f}s infer={t_infer_total:.1f}s adapt={t_adapt_total:.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() + return val_loss, val_bpb + + +# ----------------------------- +# POST-TRAINING QUANTIZATION +# ----------------------------- +# +# It's silly to export our model, which is trained in bf16 and fp32, at that same precision. +# Instead, we get approximately the same model (with a small hit) by quantizing the model to int8 & zlib compressing. +# We can then decompress the model and run in higher precision for evaluation, after closing in under the size limit. + +CONTROL_TENSOR_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "CONTROL_TENSOR_NAME_PATTERNS", + "attn_scale,attn_scales,mlp_scale,mlp_scales,resid_mix,resid_mixes,q_gain,skip_weight,skip_weights", + ).split(",") + if pattern +) +INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 +INT8_PER_ROW_SCALE_DTYPE = torch.float16 +INT8_CLIP_PERCENTILE = 99.99984 +INT8_CLIP_Q = INT8_CLIP_PERCENTILE / 100.0 + + +def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: + t32 = t.float() + if t32.ndim == 2: + # Matrices get one scale per row, which usually tracks output-channel + # ranges much better than a single tensor-wide scale. + clip_abs = ( + torch.quantile(t32.abs(), INT8_CLIP_Q, dim=1) + if t32.numel() + else torch.empty((t32.shape[0],), dtype=torch.float32) + ) + clipped = torch.maximum( + torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None] + ) + scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) + q = ( + torch.clamp(torch.round(clipped / scale[:, None]), -127, 127) + .to(torch.int8) + .contiguous() + ) + return q, scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous() + + # Vectors / scalars use a simpler per-tensor scale. + clip_abs = ( + float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) + if t32.numel() + else 0.0 + ) + scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) + q = ( + torch.clamp( + torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127 + ) + .to(torch.int8) + .contiguous() + ) + return q, scale + + +# ------------------------------------ +# INT6 OPTIMAL-CLIP QUANTIZATION +# ------------------------------------ + + +def _classify_param_jepa(name: str) -> str: + if "tok_emb" in name or "decoder_token_emb" in name or "decoder_out" in name: + return "embed" + if ".mlp." in name: + return "mlp" + if ".attn." in name: + return "attn" + return "other" + + +def quantize_int6_per_row(t: Tensor, clip_range: int = 31) -> tuple[Tensor, Tensor]: + t32 = t.float() + if t32.ndim == 2: + 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 + 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( + state_dict: dict[str, Tensor], int6_cats: set[str] +) -> tuple[dict[str, Tensor], dict[str, object]]: + result: dict[str, Tensor] = {} + meta: dict[str, object] = {} + for name, tensor in state_dict.items(): + t = tensor.detach().cpu().contiguous() + cat = _classify_param_jepa(name) + 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 + if cat in int6_cats and t.ndim >= 1: + q, s = quantize_int6_per_row(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int6"} + else: + q, s = quantize_float_tensor(t) + result[name + ".q"] = q + result[name + ".scale"] = s + meta[name] = {"type": "int8"} + return result, meta + + +def dequantize_mixed_int6( + result: dict[str, Tensor], + meta: dict[str, object], + template_sd: dict[str, Tensor], +) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + for name, orig in template_sd.items(): + info = meta.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 + + +# ----------------------------- +# DATA LOADING +# ----------------------------- + + +def load_data_shard(file: Path) -> Tensor: + header_bytes = 256 * np.dtype(" None: + self.file_idx = (self.file_idx + 1) % len(self.files) + self.tokens = load_data_shard(self.files[self.file_idx]) + self.pos = 0 + + def take(self, n: int) -> Tensor: + chunks: list[Tensor] = [] + remaining = n + while remaining > 0: + avail = self.tokens.numel() - self.pos + if avail <= 0: + self._advance_file() + continue + k = min(remaining, avail) + chunks.append(self.tokens[self.pos : self.pos + k]) + self.pos += k + remaining -= k + return chunks[0] if len(chunks) == 1 else torch.cat(chunks) + + +class DistributedTokenLoader: + # Each call consumes a contiguous chunk from the shared token stream, then slices out + # one disjoint span per rank. The extra "+1" token lets us build (x, y) by shifting. + def __init__(self, pattern: str, rank: int, world_size: int, device: torch.device): + self.rank = rank + self.world_size = world_size + self.device = device + self.stream = TokenStream(pattern) + + def next_batch( + self, global_tokens: int, seq_len: int, grad_accum_steps: int + ) -> tuple[Tensor, Tensor]: + local_tokens = global_tokens // (self.world_size * grad_accum_steps) + per_rank_span = local_tokens + 1 + chunk = self.stream.take(per_rank_span * self.world_size) + start = self.rank * per_rank_span + local = chunk[start : start + per_rank_span].to(dtype=torch.int64) + x = local[:-1].reshape(-1, seq_len) + y = local[1:].reshape(-1, seq_len) + return x.to(self.device, non_blocking=True), y.to( + self.device, non_blocking=True + ) + + +# ----------------------------- +# TRANSFORMER MODULES +# ----------------------------- + + +class RMSNorm(nn.Module): + def __init__(self, eps: float | None = None): + super().__init__() + self.eps = eps + + def forward(self, x: Tensor) -> Tensor: + return F.rms_norm(x, (x.size(-1),), eps=self.eps) + + +class CastedLinear(nn.Linear): + # Keep weights in fp32 for optimizer/state quality, cast at matmul time for bf16 compute. + _qat_enabled: bool = False + + def forward(self, x: Tensor) -> Tensor: + w = self.weight.to(x.dtype) + if CastedLinear._qat_enabled and self.training and w.ndim == 2: + with torch.no_grad(): + w32 = self.weight.float() + row_max = w32.abs().amax(dim=1) + scale = (row_max / 31.0).clamp_min(1.0 / 31.0) + w_q = ( + torch.clamp(torch.round(w32 / scale[:, None]), -31, 31) + * scale[:, None] + ).to(x.dtype) + w = w + (w_q - w).detach() + bias = self.bias.to(x.dtype) if self.bias is not None else None + return F.linear(x, w, bias) + + +def restore_low_dim_params_to_fp32(module: nn.Module) -> None: + # Keep small/control parameters in fp32 even when the model body runs in bf16. + with torch.no_grad(): + for name, param in module.named_parameters(): + if ( + param.ndim < 2 + or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ) and param.dtype != torch.float32: + param.data = param.data.float() + + +class Rotary(nn.Module): + # Caches cos/sin tables per sequence length on the current device. + 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) + + def forward(self, x: Tensor) -> Tensor: + bsz, seqlen, dim = x.shape + q = ( + self.c_q(x) + .reshape(bsz, seqlen, self.num_heads, self.head_dim) + .transpose(1, 2) + ) + k = ( + self.c_k(x) + .reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + .transpose(1, 2) + ) + v = ( + self.c_v(x) + .reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) + .transpose(1, 2) + ) + q = F.rms_norm(q, (q.size(-1),)) + k = F.rms_norm(k, (k.size(-1),)) + cos, sin = self.rotary(seqlen, x.device, q.dtype) + q = apply_rotary_emb(q, cos, sin) + k = apply_rotary_emb(k, cos, sin) + q = q * self.q_gain.to(dtype=q.dtype)[None, :, None, None] + y = F.scaled_dot_product_attention( + q, + k, + v, + attn_mask=None, + is_causal=True, + enable_gqa=(self.num_kv_heads != self.num_heads), + ) + y = y.transpose(1, 2).contiguous().reshape(bsz, seqlen, dim) + return self.proj(y) + + +class MLP(nn.Module): + # relu^2 MLP from the original modded-nanogpt setup + def __init__(self, dim: int, mlp_mult: int): + super().__init__() + hidden = mlp_mult * dim + self.fc = CastedLinear(dim, hidden, bias=False) + self.proj = CastedLinear(hidden, dim, bias=False) + self.proj._zero_init = True + + def forward(self, x: Tensor) -> Tensor: + x = F.leaky_relu(self.fc(x), negative_slope=0.5) + return self.proj(x.square()) + + +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) + self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) + self.resid_mix = nn.Parameter( + torch.stack((torch.ones(dim), torch.zeros(dim))).float() + ) + + def forward(self, x: Tensor, x0: Tensor) -> Tensor: + mix = self.resid_mix.to(dtype=x.dtype) + x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 + attn_out = self.attn(self.attn_norm(x)) + x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp( + self.mlp_norm(x) + ) + return x + + +class SIGReg(nn.Module): + # Sketch regularizer from LeWM, adapted to local (per-rank) batches. + def __init__(self, knots: int = 17, num_proj: int = 256): + super().__init__() + self.num_proj = num_proj + t = torch.linspace(0, 3, knots, dtype=torch.float32) + dt = 3 / max(knots - 1, 1) + weights = torch.full((knots,), 2 * dt, dtype=torch.float32) + if knots > 1: + weights[[0, -1]] = dt + window = torch.exp(-t.square() / 2.0) + self.register_buffer("t", t, persistent=False) + self.register_buffer("phi", window, persistent=False) + self.register_buffer("weights", weights * window, persistent=False) + + def forward(self, proj: Tensor) -> Tensor: + if proj.ndim != 3: + raise ValueError(f"SIGReg expects (T, B, D), got {tuple(proj.shape)}") + A = torch.randn( + proj.size(-1), self.num_proj, device=proj.device, dtype=proj.dtype + ) + A = A / (A.norm(p=2, dim=0, keepdim=True).clamp_min(1e-6)) + x_t = (proj @ A).unsqueeze(-1) * self.t.to(dtype=proj.dtype) + err = ( + x_t.cos().mean(-3) - self.phi.to(dtype=proj.dtype) + ).square() + x_t.sin().mean(-3).square() + statistic = (err @ self.weights.to(dtype=proj.dtype)) * proj.size(-2) + return statistic.mean().float() + + +class LatentMLP(nn.Module): + def __init__(self, input_dim: int, output_dim: int, hidden_mult: int = 2): + super().__init__() + hidden = hidden_mult * input_dim + self.norm = RMSNorm() + self.fc = CastedLinear(input_dim, hidden, bias=False) + self.proj = CastedLinear(hidden, output_dim, bias=False) + + def forward(self, x: Tensor) -> Tensor: + x = self.norm(x) + x = F.silu(self.fc(x)) + return self.proj(x) + + +class BytePatchJEPA(nn.Module): + def __init__( + self, + *, + vocab_size: int, + num_layers: int, + encoder_repeats: int, + model_dim: int, + num_heads: int, + num_kv_heads: int, + mlp_mult: int, + rope_base: float, + qk_gain_init: float, + patch_size: int, + latent_dim: int, + decoder_layers: int, + decoder_heads: int, + sigreg_knots: int, + sigreg_num_proj: int, + sigreg_weight: float, + jepa_pred_weight: float, + jepa_ce_weight: float, + ): + super().__init__() + if patch_size < 2: + raise ValueError(f"PATCH_SIZE must be >=2, got {patch_size}") + if decoder_heads <= 0 or model_dim % decoder_heads != 0: + raise ValueError( + f"DECODER_HEADS={decoder_heads} must divide MODEL_DIM={model_dim}" + ) + self.vocab_size = vocab_size + self.patch_size = patch_size + self.encoder_repeats = encoder_repeats + self.sigreg_weight = sigreg_weight + self.jepa_pred_weight = jepa_pred_weight + self.jepa_ce_weight = jepa_ce_weight + self.bos_id = 1 + + self.tok_emb = nn.Embedding(vocab_size, model_dim) + self.patch_pos = nn.Parameter( + torch.zeros(patch_size, model_dim, dtype=torch.float32) + ) + self.patch_in = CastedLinear(patch_size * model_dim, model_dim, bias=False) + self.blocks = nn.ModuleList( + [ + Block( + model_dim, + num_heads, + num_kv_heads, + mlp_mult, + rope_base, + qk_gain_init, + ) + for _ in range(num_layers) + ] + ) + self.final_norm = RMSNorm() + self.projector = LatentMLP(model_dim, latent_dim) + self.predictor = LatentMLP(model_dim, latent_dim) + self.sigreg = SIGReg(knots=sigreg_knots, num_proj=sigreg_num_proj) + + self.start_latent = nn.Parameter(torch.zeros(latent_dim, dtype=torch.float32)) + self.decoder_token_emb = nn.Embedding(vocab_size, model_dim) + self.decoder_cond = CastedLinear(latent_dim, model_dim, bias=False) + self.decoder_blocks = nn.ModuleList( + [ + Block( + model_dim, + decoder_heads, + decoder_heads, + mlp_mult, + rope_base, + qk_gain_init, + ) + for _ in range(decoder_layers) + ] + ) + self.decoder_norm = RMSNorm() + self.decoder_out = CastedLinear(model_dim, vocab_size, bias=False) + self._init_weights() + + def _init_weights(self) -> None: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02) + nn.init.normal_(self.decoder_token_emb.weight, mean=0.0, std=0.02) + nn.init.normal_(self.patch_pos, mean=0.0, std=0.02) + nn.init.normal_(self.start_latent, mean=0.0, std=0.02) + for module in self.modules(): + if isinstance(module, nn.Linear) and getattr(module, "_zero_init", False): + nn.init.zeros_(module.weight) + + def _build_full_sequence( + self, input_ids: Tensor, target_ids: Tensor | None + ) -> Tensor: + if target_ids is None: + raise ValueError( + "BytePatchJEPA requires target_ids so it can reconstruct the full autoregressive stream" + ) + if input_ids.shape != target_ids.shape: + raise ValueError( + f"input_ids and target_ids must match, got {tuple(input_ids.shape)} vs {tuple(target_ids.shape)}" + ) + full = torch.cat((input_ids[:, :1], target_ids), dim=1) + if full.size(1) % self.patch_size != 0: + raise ValueError( + f"Sequence length {full.size(1)} must be divisible by PATCH_SIZE={self.patch_size}; " + "set TRAIN_SEQ_LEN so TRAIN_SEQ_LEN+1 is divisible by PATCH_SIZE" + ) + return full + + def _patchify(self, full_ids: Tensor) -> Tensor: + bsz, seqlen = full_ids.shape + num_patches = seqlen // self.patch_size + return full_ids.view(bsz, num_patches, self.patch_size) + + def _encode_patches(self, patches: Tensor) -> Tensor: + x = self.tok_emb(patches) + x = x + self.patch_pos.to(dtype=x.dtype)[None, None, :, :] + x = F.rms_norm(x, (x.size(-1),)) + return self.patch_in(x.reshape(x.size(0), x.size(1), -1)) + + def _contextualize(self, patch_emb: Tensor) -> Tensor: + x = F.rms_norm(patch_emb, (patch_emb.size(-1),)) + x0 = x + for _ in range(self.encoder_repeats): + for block in self.blocks: + x = block(x, x0) + return self.final_norm(x) + + def _decode_logits(self, cond_latent: Tensor, target_patches: Tensor) -> Tensor: + bsz, num_patches, patch_size = target_patches.shape + total_bytes = num_patches * patch_size + flat_bytes = target_patches.reshape(bsz, total_bytes) + prev = torch.cat( + [flat_bytes.new_full((bsz, 1), self.bos_id), flat_bytes[:, :-1]], dim=1 + ) + x = self.decoder_token_emb(prev) + cond = self.decoder_cond(cond_latent).to(dtype=x.dtype) + x = x + cond.repeat_interleave(patch_size, dim=1) + x0 = x + for block in self.decoder_blocks: + x = block(x, x0) + x = self.decoder_norm(x) + return self.decoder_out(x).reshape( + bsz, num_patches, patch_size, self.vocab_size + ) + + def forward( + self, input_ids: Tensor, target_ids: Tensor | None + ) -> tuple[Tensor, Tensor]: + full = self._build_full_sequence(input_ids, target_ids) + patches = self._patchify(full) + patch_emb = self._encode_patches(patches) + target_latent = self.projector(patch_emb) + context = self._contextualize(patch_emb) + pred_latent = self.predictor(context[:, :-1]) + pred_loss = F.mse_loss( + pred_latent.float(), target_latent[:, 1:].detach().float(), reduction="mean" + ) + sigreg_loss = self.sigreg(target_latent.transpose(0, 1)) + + start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( + patches.size(0), 1, -1 + ) + cond_latent = torch.cat((start, pred_latent), dim=1) + logits = self._decode_logits(cond_latent, patches) + ce = F.cross_entropy( + logits.reshape(-1, self.vocab_size).float(), + patches.reshape(-1), + reduction="none", + ) + ce = ce.reshape_as(patches).float() + mask = torch.ones_like(ce) + mask[:, 0, 0] = 0.0 + nll = (ce * mask).sum() / mask.sum() + total = ( + self.jepa_ce_weight * nll + + self.jepa_pred_weight * pred_loss + + self.sigreg_weight * sigreg_loss + ) + return total, nll + + def forward_logits(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + full = self._build_full_sequence(input_ids, target_ids) + patches = self._patchify(full) + patch_emb = self._encode_patches(patches) + context = self._contextualize(patch_emb) + pred_latent = self.predictor(context[:, :-1]) + start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( + patches.size(0), 1, -1 + ) + cond_latent = torch.cat((start, pred_latent), dim=1) + logits = self._decode_logits(cond_latent, patches) + bsz = logits.size(0) + return logits.reshape(bsz, -1, self.vocab_size) + + +# ----------------------------- +# TRAINING +# ----------------------------- + + +def main() -> None: + global zeropower_via_newtonschulz5 + + code = Path(__file__).read_text(encoding="utf-8") + args = Hyperparameters() + zeropower_via_newtonschulz5 = torch.compile(zeropower_via_newtonschulz5) + + # ----------------------------- + # DISTRIBUTED + CUDA SETUP + # ----------------------------- + + distributed = "RANK" in os.environ and "WORLD_SIZE" in os.environ + rank = int(os.environ.get("RANK", "0")) + world_size = int(os.environ.get("WORLD_SIZE", "1")) + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + if world_size <= 0: + raise ValueError(f"WORLD_SIZE must be positive, got {world_size}") + if 8 % world_size != 0: + raise ValueError( + f"WORLD_SIZE={world_size} must divide 8 so grad_accum_steps stays integral" + ) + grad_accum_steps = 8 // world_size + grad_scale = 1.0 / grad_accum_steps + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required") + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + if distributed: + dist.init_process_group(backend="nccl", device_id=device) + dist.barrier() + master_process = rank == 0 + + # Fast math knobs + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + from torch.backends.cuda import ( + enable_cudnn_sdp, + enable_flash_sdp, + enable_math_sdp, + enable_mem_efficient_sdp, + ) + + enable_cudnn_sdp(False) + enable_flash_sdp(True) + enable_mem_efficient_sdp(False) + enable_math_sdp(False) + + logfile = None + if master_process: + os.makedirs("logs", exist_ok=True) + logfile = f"logs/{args.run_id}.txt" + print(logfile) + + def log0(msg: str, console: bool = True) -> None: + if not master_process: + return + if console: + print(msg) + if logfile is not None: + with open(logfile, "a", encoding="utf-8") as f: + print(msg, file=f) + + log0(code, console=False) + log0("=" * 100, console=False) + log0(f"Running Python {sys.version}", console=False) + log0(f"Running PyTorch {torch.__version__}", console=False) + log0( + subprocess.run( + ["nvidia-smi"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + check=False, + ).stdout, + console=False, + ) + log0("=" * 100, console=False) + + # ----------------------------- + # TOKENIZER + VALIDATION METRIC SETUP + # ----------------------------- + + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + torch.cuda.manual_seed_all(args.seed) + + if (args.train_seq_len + 1) % args.patch_size != 0: + raise ValueError( + f"JEPA requires TRAIN_SEQ_LEN+1 to be divisible by PATCH_SIZE; " + f"got TRAIN_SEQ_LEN={args.train_seq_len}, PATCH_SIZE={args.patch_size}" + ) + base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = load_pure_byte_luts( + args.tokenizer_path, args.vocab_size, device + ) + 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) + log0(f"val_bpb:enabled tokenizer_kind=byte tokenizer_path={args.tokenizer_path}") + log0(f"train_loader:dataset:{dataset_dir.name} train_shards:{actual_train_files}") + log0(f"val_loader:shards pattern={args.val_files} tokens:{val_tokens.numel() - 1}") + + # ----------------------------- + # MODEL + OPTIMIZER SETUP + # ----------------------------- + + base_model: nn.Module = BytePatchJEPA( + vocab_size=args.vocab_size, + num_layers=args.num_layers, + encoder_repeats=args.encoder_repeats, + model_dim=args.model_dim, + num_heads=args.num_heads, + num_kv_heads=args.num_kv_heads, + mlp_mult=args.mlp_mult, + rope_base=args.rope_base, + qk_gain_init=args.qk_gain_init, + patch_size=args.patch_size, + latent_dim=args.latent_dim, + decoder_layers=args.decoder_layers, + decoder_heads=args.decoder_heads, + sigreg_knots=args.sigreg_knots, + sigreg_num_proj=args.sigreg_num_proj, + sigreg_weight=args.sigreg_weight, + jepa_pred_weight=args.jepa_pred_weight, + jepa_ce_weight=args.jepa_ce_weight, + ) + base_model = base_model.to(device).bfloat16() + for module in base_model.modules(): + if isinstance(module, CastedLinear): + module.float() + restore_low_dim_params_to_fp32(base_model) + compiled_model = ( + torch.compile(base_model, dynamic=False, fullgraph=False) + if args.use_compile + else base_model + ) + model: nn.Module = ( + DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) + if distributed + else compiled_model + ) + + embedding_tags = ("tok_emb", "decoder_token_emb", "patch_pos") + head_names = {"decoder_out.weight"} + embedding_params: list[Tensor] = [] + head_params: list[Tensor] = [] + matrix_params: list[Tensor] = [] + scalar_params: list[Tensor] = [] + for name, param in base_model.named_parameters(): + if not param.requires_grad: + continue + if name in head_names: + head_params.append(param) + elif any(tag in name for tag in embedding_tags): + embedding_params.append(param) + elif param.ndim == 2 and not any( + pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS + ): + matrix_params.append(param) + else: + scalar_params.append(param) + + token_lr = args.embed_lr + optimizers: list[torch.optim.Optimizer] = [] + if embedding_params: + optimizer_embed = torch.optim.Adam( + [{"params": embedding_params, "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.append(optimizer_embed) + optimizer_muon = None + if matrix_params: + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, + ) + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizers.append(optimizer_muon) + if head_params: + optimizer_head = torch.optim.Adam( + [{"params": head_params, "lr": args.head_lr, "base_lr": args.head_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.append(optimizer_head) + if scalar_params: + optimizer_scalar = torch.optim.Adam( + [ + { + "params": scalar_params, + "lr": args.scalar_lr, + "base_lr": args.scalar_lr, + } + ], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, + ) + optimizers.append(optimizer_scalar) + + n_params = sum(p.numel() for p in base_model.parameters()) + log0(f"model_params:{n_params}") + log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") + log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0( + f"model_family:jepa attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}" + ) + log0( + f"embed_lr:{token_lr} head_lr:{args.head_lr if head_params 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"jepa:patch_size:{args.patch_size} latent_dim:{args.latent_dim} " + f"encoder_layers:{args.num_layers}x{args.encoder_repeats} " + f"decoder_layers:{args.decoder_layers} decoder_heads:{args.decoder_heads} " + f"sigreg_weight:{args.sigreg_weight} pred_weight:{args.jepa_pred_weight} ce_weight:{args.jepa_ce_weight}" + ) + log0(f"seed:{args.seed}") + + # ----------------------------- + # DATA LOADER & MODEL WARMUP + # ----------------------------- + + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) + + def zero_grad_all() -> None: + for opt in optimizers: + opt.zero_grad(set_to_none=True) + + max_wallclock_ms = ( + 1000.0 * args.max_wallclock_seconds if args.max_wallclock_seconds > 0 else None + ) + + def lr_mul(step: int, elapsed_ms: float) -> float: + if args.warmdown_iters <= 0: + return 1.0 + if max_wallclock_ms is None: + warmdown_start = max(args.iterations - args.warmdown_iters, 0) + return ( + max((args.iterations - step) / max(args.warmdown_iters, 1), 0.0) + if warmdown_start <= step < args.iterations + else 1.0 + ) + step_ms = elapsed_ms / max(step, 1) + warmdown_ms = args.warmdown_iters * step_ms + remaining_ms = max(max_wallclock_ms - elapsed_ms, 0.0) + return ( + remaining_ms / max(warmdown_ms, 1e-9) + if remaining_ms <= warmdown_ms + else 1.0 + ) + + # Warmup primes the compiled forward/backward/optimizer paths, then we restore the + # initial weights/optimizer state so measured training starts from the true init. + if args.warmup_steps > 0: + initial_model_state = { + name: tensor.detach().cpu().clone() + for name, tensor in base_model.state_dict().items() + } + initial_optimizer_states = [ + copy.deepcopy(opt.state_dict()) for opt in optimizers + ] + model.train() + for warmup_step in range(args.warmup_steps): + zero_grad_all() + for micro_step in range(grad_accum_steps): + if distributed: + model.require_backward_grad_sync = ( + micro_step == grad_accum_steps - 1 + ) + x, y = train_loader.next_batch( + args.train_batch_tokens, args.train_seq_len, grad_accum_steps + ) + with torch.autocast( + device_type="cuda", dtype=torch.bfloat16, enabled=True + ): + warmup_loss, _ = model(x, y) + (warmup_loss * grad_scale).backward() + for opt in optimizers: + opt.step() + zero_grad_all() + if ( + args.warmup_steps <= 20 + or (warmup_step + 1) % 10 == 0 + or warmup_step + 1 == args.warmup_steps + ): + log0(f"warmup_step:{warmup_step + 1}/{args.warmup_steps}") + base_model.load_state_dict(initial_model_state, strict=True) + for opt, state in zip(optimizers, initial_optimizer_states, strict=True): + opt.load_state_dict(state) + zero_grad_all() + if distributed: + model.require_backward_grad_sync = True + train_loader = DistributedTokenLoader( + args.train_files, rank, world_size, device + ) + + # ----------------------------- + # MAIN TRAINING LOOP + # ----------------------------- + + ema_state = { + name: t.detach().float().clone() for name, t in base_model.state_dict().items() + } + training_time_ms = 0.0 + stop_after_step: int | None = None + torch.cuda.synchronize() + t0 = time.perf_counter() + + step = 0 + while True: + last_step = step == args.iterations or ( + stop_after_step is not None and step >= stop_after_step + ) + + should_validate = last_step or ( + args.val_loss_every > 0 and step % args.val_loss_every == 0 + ) + if should_validate: + torch.cuda.synchronize() + training_time_ms += 1000.0 * (time.perf_counter() - t0) + val_loss, val_bpb = eval_val( + args, + model, + rank, + world_size, + device, + grad_accum_steps, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + ) + log0( + f"step:{step}/{args.iterations} val_loss:{val_loss:.4f} val_bpb:{val_bpb:.4f} " + f"train_time:{training_time_ms:.0f}ms step_avg:{training_time_ms / max(step, 1):.2f}ms" + ) + torch.cuda.synchronize() + t0 = time.perf_counter() + + if last_step: + if stop_after_step is not None and step < args.iterations: + log0( + f"stopping_early: wallclock_cap train_time:{training_time_ms:.0f}ms " + 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.late_qat_threshold > 0 + and scale < args.late_qat_threshold + and not CastedLinear._qat_enabled + ): + CastedLinear._qat_enabled = True + log0(f"late_qat:enabled step:{step} scale:{scale:.4f}") + zero_grad_all() + train_loss = torch.zeros((), device=device) + train_nll = 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, nll = model(x, y) + train_loss += loss.detach() + train_nll += nll.detach() + (loss * grad_scale).backward() + train_loss /= grad_accum_steps + train_nll /= grad_accum_steps + + if optimizer_muon is not None: + 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() + + with torch.no_grad(): + for name, t in base_model.state_dict().items(): + ema_state[name].mul_(args.ema_decay).add_( + t.detach().float(), alpha=1.0 - args.ema_decay + ) + step += 1 + approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) + should_log_train = args.train_log_every > 0 and ( + step <= 10 + or step % args.train_log_every == 0 + or stop_after_step is not None + ) + if should_log_train: + log0( + f"step:{step}/{args.iterations} train_loss:{train_loss.item():.4f} " + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms " + f"train_nll:{train_nll.item():.4f}" + ) + + # Needed to sync whether we've reached the wallclock cap. + reached_cap = ( + max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms + ) + if distributed and max_wallclock_ms is not None: + reached_cap_tensor = torch.tensor(int(reached_cap), device=device) + dist.all_reduce(reached_cap_tensor, op=dist.ReduceOp.MAX) + reached_cap = bool(reached_cap_tensor.item()) + if stop_after_step is None and reached_cap: + stop_after_step = step + + log0( + f"peak memory allocated: {torch.cuda.max_memory_allocated() // 1024 // 1024} MiB " + f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" + ) + + current_sd = base_model.state_dict() + ema_avg = { + name: t.to(dtype=current_sd[name].dtype) for name, t in ema_state.items() + } + base_model.load_state_dict(ema_avg, strict=True) + log0(f"ema:applied EMA weights (decay={args.ema_decay})") + + # ----------------------------- + # SERIALIZATION + ROUNDTRIP VALIDATION + # ----------------------------- + # Save the raw state (useful for debugging/loading in PyTorch directly), then always produce + # the compressed int8+zlib artifact and validate the round-tripped weights. + + if master_process: + torch.save(base_model.state_dict(), "final_model.pt") + model_bytes = os.path.getsize("final_model.pt") + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model: {model_bytes} bytes") + log0(f"Code size: {code_bytes} bytes") + log0(f"Total submission size: {model_bytes + code_bytes} bytes") + + template_sd = {k: v.cpu() for k, v in base_model.state_dict().items()} + int6_cats = {"mlp", "attn", "other", "embed"} + quant_result, quant_meta = mixed_quantize_int6(base_model.state_dict(), int6_cats) + quant_buf = io.BytesIO() + torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + quant_raw = quant_buf.getvalue() + quant_blob = lzma.compress(quant_raw, preset=9) + if master_process: + with open("final_model.int6.ptz", "wb") as f: + f.write(quant_blob) + quant_file_bytes = len(quant_blob) + code_bytes = len(code.encode("utf-8")) + log0(f"Serialized model int6+lzma: {quant_file_bytes} bytes") + log0(f"Total submission size int6+lzma: {quant_file_bytes + code_bytes} bytes") + + if distributed: + dist.barrier() + with open("final_model.int6.ptz", "rb") as f: + quant_blob_disk = f.read() + quant_state = torch.load( + io.BytesIO(lzma.decompress(quant_blob_disk)), map_location="cpu" + ) + CastedLinear._qat_enabled = False + deq_sd = dequantize_mixed_int6(quant_state["w"], quant_state["m"], template_sd) + base_model.load_state_dict(deq_sd, strict=True) + + if args.ttt_enabled: + torch.cuda.synchronize() + t_ttt = time.perf_counter() + ttt_loss, ttt_bpb = eval_val_sliding_ttt( + args, + base_model, + rank, + world_size, + device, + val_tokens, + base_bytes_lut, + has_leading_space_lut, + is_boundary_token_lut, + log_fn=log0, + ) + torch.cuda.synchronize() + log0( + f"final_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms" + ) + log0(f"final_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + + if distributed: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() From 9fafabe59e0f2a6051e090eed579df00484634b5 Mon Sep 17 00:00:00 2001 From: John Tian Date: Wed, 25 Mar 2026 01:22:22 -0700 Subject: [PATCH 25/25] Revert non-records files to upstream versions for clean merge --- data/tokenizer_specs.json | 7 +- train_gpt.py | 1266 ++++++++++--------------------------- 2 files changed, 341 insertions(+), 932 deletions(-) diff --git a/data/tokenizer_specs.json b/data/tokenizer_specs.json index 28e6f9b40..d7ad1ca05 100644 --- a/data/tokenizer_specs.json +++ b/data/tokenizer_specs.json @@ -1,10 +1,9 @@ { "tokenizers": [ { - "name": "pure_byte_260", - "kind": "pure_byte", - "dataset_suffix": "byte260", - "filename": "fineweb_pure_byte_260.json" + "name": "sp_bpe_1024", + "dataset_suffix": "sp1024", + "vocab_size": 1024 } ] } diff --git a/train_gpt.py b/train_gpt.py index e95bed0d3..651beb2b8 100644 --- a/train_gpt.py +++ b/train_gpt.py @@ -9,8 +9,6 @@ import copy import glob import io -import json -import lzma import math import os import random @@ -18,10 +16,11 @@ 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 @@ -31,99 +30,70 @@ # ----------------------------- # HYPERPARAMETERS # ----------------------------- -# Default JEPA run: -# - pure-byte FineWeb export (`byte260`) -# - byte-patch JEPA with latent next-patch prediction plus a small causal byte decoder -# - 10 JEPA blocks at width 384, 6 heads with 3 KV heads -# - sequence length 4095 so the reconstructed AR stream has 4096 bytes, cleanly divisible by patch size 8 -# - 524,160 train tokens per step for 20,000 iterations with a ~10 minute cap - +# Default Simple Baseline run: +# - 9 transformer blocks at width 512 +# - 8 attention heads with 4 KV heads (GQA) and 2x MLP expansion +# - vocab size 1024, sequence length 1024, tied embeddings +# - 524,288 train tokens per step for 20,000 iterations with a ~10 minute cap class Hyperparameters: # Data paths are shard globs produced by the existing preprocessing pipeline. - data_path = os.environ.get("DATA_PATH", "./data/datasets/fineweb10B_byte260") + 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_pure_byte_260.json" - ) + tokenizer_path = os.environ.get("TOKENIZER_PATH", "./data/tokenizers/fineweb_1024_bpe.model") run_id = os.environ.get("RUN_ID", str(uuid.uuid4())) seed = int(os.environ.get("SEED", 1337)) # Validation cadence and batch size. Validation always uses the full fineweb_val split. - val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_160)) + val_batch_size = int(os.environ.get("VAL_BATCH_SIZE", 524_288)) val_loss_every = int(os.environ.get("VAL_LOSS_EVERY", 1000)) - val_sliding_stride = int(os.environ.get("VAL_SLIDING_STRIDE", 256)) - val_sliding_batch = int(os.environ.get("VAL_SLIDING_BATCH", 32)) - ema_decay = float(os.environ.get("EMA_DECAY", 0.997)) - late_qat_threshold = float(os.environ.get("LATE_QAT_THRESHOLD", 0.15)) - 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", 2)) - ttt_chunk_tokens = int(os.environ.get("TTT_CHUNK_TOKENS", 32768)) - ttt_freeze_blocks = int(os.environ.get("TTT_FREEZE_BLOCKS", 0)) - 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)) train_log_every = int(os.environ.get("TRAIN_LOG_EVERY", 200)) # Training length. iterations = int(os.environ.get("ITERATIONS", 20000)) - warmdown_iters = int(os.environ.get("WARMDOWN_ITERS", 3500)) + 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_032)) - train_seq_len = int(os.environ.get("TRAIN_SEQ_LEN", 2047)) + 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)) - use_compile = bool(int(os.environ.get("USE_COMPILE", "1"))) # Model shape. - vocab_size = int(os.environ.get("VOCAB_SIZE", 260)) - num_layers = int(os.environ.get("NUM_LAYERS", 5)) - encoder_repeats = int(os.environ.get("ENCODER_REPEATS", 2)) - num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 3)) - model_dim = int(os.environ.get("MODEL_DIM", 480)) - num_heads = int(os.environ.get("NUM_HEADS", 6)) + vocab_size = int(os.environ.get("VOCAB_SIZE", 1024)) + num_layers = int(os.environ.get("NUM_LAYERS", 9)) + num_kv_heads = int(os.environ.get("NUM_KV_HEADS", 4)) + model_dim = int(os.environ.get("MODEL_DIM", 512)) + num_heads = int(os.environ.get("NUM_HEADS", 8)) mlp_mult = int(os.environ.get("MLP_MULT", 2)) + tie_embeddings = bool(int(os.environ.get("TIE_EMBEDDINGS", "1"))) rope_base = float(os.environ.get("ROPE_BASE", 10000.0)) - patch_size = int(os.environ.get("PATCH_SIZE", 8)) - latent_dim = int(os.environ.get("LATENT_DIM", 192)) - decoder_layers = int(os.environ.get("DECODER_LAYERS", 7)) - decoder_heads = int(os.environ.get("DECODER_HEADS", 4)) - sigreg_weight = float(os.environ.get("SIGREG_WEIGHT", 0.02)) - sigreg_knots = int(os.environ.get("SIGREG_KNOTS", 17)) - sigreg_num_proj = int(os.environ.get("SIGREG_NUM_PROJ", 256)) - jepa_pred_weight = float(os.environ.get("JEPA_PRED_WEIGHT", 0.5)) - jepa_ce_weight = float(os.environ.get("JEPA_CE_WEIGHT", 3.0)) + logit_softcap = float(os.environ.get("LOGIT_SOFTCAP", 30.0)) # Optimizer hyperparameters. - embed_lr = float(os.environ.get("EMBED_LR", 0.1)) - head_lr = float(os.environ.get("HEAD_LR", 0.02)) - matrix_lr = float(os.environ.get("MATRIX_LR", 0.025)) - scalar_lr = float(os.environ.get("SCALAR_LR", 0.025)) - muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.99)) + embed_lr = float(os.environ.get("EMBED_LR", 0.6)) + head_lr = float(os.environ.get("HEAD_LR", 0.008)) + tied_embed_lr = float(os.environ.get("TIED_EMBED_LR", 0.05)) + tied_embed_init_std = float(os.environ.get("TIED_EMBED_INIT_STD", 0.005)) + matrix_lr = float(os.environ.get("MATRIX_LR", 0.04)) + scalar_lr = float(os.environ.get("SCALAR_LR", 0.04)) + muon_momentum = float(os.environ.get("MUON_MOMENTUM", 0.95)) muon_backend_steps = int(os.environ.get("MUON_BACKEND_STEPS", 5)) - muon_momentum_warmup_start = float( - os.environ.get("MUON_MOMENTUM_WARMUP_START", 0.92) - ) - muon_momentum_warmup_steps = int(os.environ.get("MUON_MOMENTUM_WARMUP_STEPS", 1500)) + 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.0)) - # ----------------------------- -# MUON OPTIMIZER +# MUON OPTIMIZER # ----------------------------- -# +# # As borrowed from modded-nanogpt # Background on Muon: https://kellerjordan.github.io/posts/muon/ - -def zeropower_via_newtonschulz5( - G: Tensor, steps: int = 10, eps: float = 1e-7 -) -> Tensor: +def zeropower_via_newtonschulz5(G: Tensor, steps: int = 10, eps: float = 1e-7) -> Tensor: # Orthogonalize a 2D update matrix with a fast Newton-Schulz iteration. # Muon uses this to normalize matrix-shaped gradients before applying them. a, b, c = (3.4445, -4.7750, 2.0315) @@ -140,19 +110,10 @@ def zeropower_via_newtonschulz5( class Muon(torch.optim.Optimizer): - def __init__( - self, - params, - lr: float, - momentum: float, - backend_steps: int, - nesterov: bool = True, - ): + def __init__(self, params, lr: float, momentum: float, backend_steps: int, nesterov: bool = True): super().__init__( params, - dict( - lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov - ), + dict(lr=lr, momentum=momentum, backend_steps=backend_steps, nesterov=nesterov), ) @torch.no_grad() @@ -176,9 +137,7 @@ def step(self, closure=None): 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 - ) + updates_flat = torch.zeros(total_params, device=params[0].device, dtype=torch.bfloat16) curr = 0 for i, p in enumerate(params): @@ -210,52 +169,41 @@ def step(self, closure=None): # ----------------------------- -# TOKENIZER-AGNOSTIC EVALUATION SETUP +# TOKENIZER-AGNOSTIC EVALUATION SETUP # ----------------------------- # -# We score BPB (bits-per-byte), but the model is fixed to a pure-byte vocabulary: -# 4 special ids followed by raw UTF-8 bytes. That makes byte accounting exact. -def build_pure_byte_luts( - vocab_size: int, device: torch.device +# It's common for small models have a large fraction of their parameters be embeddings, since the 2 * d_model * d_vocab vectors can be gigantic. +# Instead of locking the tokenizer, we let you bring your own and calculate our validation metrics on the average compression of the validation set. +# We calculate BPB (bits-per-byte) instead of validation loss, so we need methods to count the number of bits per token in the tokenizer. +# Note: Submissions that edit the tokenizer will be examined more carefully, since screwing this up might unjustly improve your score. + +def build_sentencepiece_luts( + sp: spm.SentencePieceProcessor, vocab_size: int, device: torch.device ) -> tuple[Tensor, Tensor, Tensor]: - table_size = max(vocab_size, 260) + 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) - base_bytes_np[4 : min(table_size, 260)] = 1 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[:vocab_size], dtype=torch.int16, device=device), - torch.tensor( - has_leading_space_np[:vocab_size], dtype=torch.bool, device=device - ), - torch.tensor( - is_boundary_token_np[:vocab_size], dtype=torch.bool, device=device - ), + 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_pure_byte_luts( - tokenizer_path: str, vocab_size: int, device: torch.device -) -> tuple[Tensor, Tensor, Tensor]: - path = Path(tokenizer_path) - if path.suffix != ".json": - raise ValueError( - f"Pure-byte JEPA expects a tokenizer JSON at {tokenizer_path!r}" - ) - payload = json.loads(path.read_text(encoding="utf-8")) - tokenizer_type = payload.get("tokenizer_type") or payload.get("kind") - json_vocab_size = int(payload.get("vocab_size", vocab_size)) - if tokenizer_type != "pure_byte": - raise ValueError( - f"Unsupported tokenizer JSON {tokenizer_path}: expected pure_byte, got {tokenizer_type!r}" - ) - if json_vocab_size != vocab_size: - raise ValueError( - f"VOCAB_SIZE={vocab_size} does not match tokenizer vocab_size={json_vocab_size}" - ) - return build_pure_byte_luts(vocab_size, device) - - def load_validation_tokens(pattern: str, seq_len: int) -> Tensor: files = [Path(p) for p in sorted(glob.glob(pattern))] if not files: @@ -304,23 +252,18 @@ def eval_val( 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 - ) + 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) - batch_loss = batch_loss.detach() + 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) + 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(): @@ -334,183 +277,6 @@ def eval_val( model.train() return float(val_loss.item()), float(bits_per_token * tokens_per_byte) - -def eval_val_sliding_ttt( - args: Hyperparameters, - base_model: nn.Module, - rank: int, - world_size: int, - device: torch.device, - val_tokens: Tensor, - base_bytes_lut: Tensor, - has_leading_space_lut: Tensor, - is_boundary_token_lut: Tensor, - log_fn=print, -) -> tuple[float, float]: - seq_len = args.train_seq_len - stride = args.val_sliding_stride - batch_seqs = args.ttt_batch_seqs - 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 >= seq_len - ] - 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) - - log_fn( - f"ttt:start chunks={num_chunks} chunk_tokens={ttt_chunk} " - f"windows={len(window_starts)} stride={stride} " - f"lr={args.ttt_lr} epochs={args.ttt_epochs} freeze={args.ttt_freeze_blocks}" - ) - - loss_sum = torch.zeros((), device=device, dtype=torch.float64) - token_count = torch.zeros((), device=device, dtype=torch.float64) - byte_count = torch.zeros((), device=device, dtype=torch.float64) - - frozen_block_ids = set(range(min(args.ttt_freeze_blocks, len(base_model.blocks)))) - ttt_params = [] - for name, p in base_model.named_parameters(): - freeze = any(f"blocks.{bi}." in name for bi in frozen_block_ids) - if freeze: - p.requires_grad_(False) - else: - p.requires_grad_(True) - ttt_params.append(p) - - optimizer = torch.optim.SGD(ttt_params, lr=args.ttt_lr, momentum=args.ttt_momentum) - t0 = time.perf_counter() - t_infer_total = 0.0 - t_adapt_total = 0.0 - - for ci in range(num_chunks): - windows = chunk_windows[ci] - if not windows: - continue - - my_s = (len(windows) * rank) // world_size - my_e = (len(windows) * (rank + 1)) // world_size - my_windows = windows[my_s:my_e] - - torch.cuda.synchronize() - t_infer = time.perf_counter() - 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) - for i, ws in enumerate(batch_ws): - chunk_tok = val_tokens[ws : ws + seq_len + 1].to( - dtype=torch.int64, device=device - ) - x_batch[i] = chunk_tok[:-1] - y_batch[i] = chunk_tok[1:] - with torch.autocast(device_type="cuda", dtype=torch.bfloat16): - logits = base_model.forward_logits(x_batch, y_batch) - nll = F.cross_entropy( - logits[:, 1:].reshape(-1, logits.size(-1)).float(), - y_batch.reshape(-1), - reduction="none", - ).reshape(bsz, seq_len) - for i, ws in enumerate(batch_ws): - s = 0 if ws == 0 else seq_len - stride - scored = nll[i, s:seq_len].to(torch.float64) - loss_sum += scored.sum() - token_count += float(seq_len - s) - tgt = y_batch[i, s:seq_len] - prev = x_batch[i, s:seq_len] - 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() - - torch.cuda.synchronize() - t_infer_total += time.perf_counter() - t_infer - - is_last_chunk = ci == num_chunks - 1 - t_adapt = time.perf_counter() - if not is_last_chunk and args.ttt_epochs > 0: - base_model.train() - chunk_start = ci * ttt_chunk - chunk_end = min((ci + 1) * ttt_chunk, total_tokens) - chunk_seqs = (chunk_end - chunk_start) // seq_len - if chunk_seqs > 0: - 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 - for _ep in range(args.ttt_epochs): - for bs in range(my_seq_s, my_seq_e, args.ttt_batch_seqs): - be = min(bs + args.ttt_batch_seqs, my_seq_e) - start_tok = chunk_start + bs * seq_len - end_tok = chunk_start + 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): - logits = base_model.forward_logits(x, y) - ce = F.cross_entropy( - logits[:, 1:].reshape(-1, logits.size(-1)).float(), - y.reshape(-1), - ) - ce.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() - - torch.cuda.synchronize() - t_adapt_total += time.perf_counter() - t_adapt - - if rank == 0 and (ci % 50 == 0 or ci == num_chunks - 1): - elapsed = time.perf_counter() - t0 - rl = loss_sum.item() / max(token_count.item(), 1) - rbpb = ( - rl / math.log(2.0) * (token_count.item() / max(byte_count.item(), 1)) - if token_count.item() > 0 - else 0.0 - ) - log_fn( - f" ttt_chunk [{ci + 1}/{num_chunks}] bpb={rbpb:.6f} " - f"time={elapsed:.1f}s infer={t_infer_total:.1f}s adapt={t_adapt_total:.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() - return val_loss, val_bpb - - # ----------------------------- # POST-TRAINING QUANTIZATION # ----------------------------- @@ -527,11 +293,30 @@ def eval_val_sliding_ttt( ).split(",") if pattern ) +INT8_KEEP_FLOAT_FP32_NAME_PATTERNS = tuple( + pattern + for pattern in os.environ.get( + "INT8_KEEP_FLOAT_FP32_NAME_PATTERNS", + ",".join(CONTROL_TENSOR_NAME_PATTERNS), + ).split(",") + if pattern +) INT8_KEEP_FLOAT_MAX_NUMEL = 65_536 +INT8_KEEP_FLOAT_STORE_DTYPE = torch.float16 INT8_PER_ROW_SCALE_DTYPE = torch.float16 INT8_CLIP_PERCENTILE = 99.99984 INT8_CLIP_Q = INT8_CLIP_PERCENTILE / 100.0 +def tensor_nbytes(t: Tensor) -> int: + return int(t.numel()) * int(t.element_size()) + +def keep_float_tensor(name: str, t: Tensor, passthrough_orig_dtypes: dict[str, str]) -> Tensor: + if any(pattern in name for pattern in INT8_KEEP_FLOAT_FP32_NAME_PATTERNS): + return t.float().contiguous() + if t.dtype in {torch.float32, torch.bfloat16}: + passthrough_orig_dtypes[name] = str(t.dtype).removeprefix("torch.") + return t.to(dtype=INT8_KEEP_FLOAT_STORE_DTYPE).contiguous() + return t def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: t32 = t.float() @@ -543,145 +328,104 @@ def quantize_float_tensor(t: Tensor) -> tuple[Tensor, Tensor]: if t32.numel() else torch.empty((t32.shape[0],), dtype=torch.float32) ) - clipped = torch.maximum( - torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None] - ) + clipped = torch.maximum(torch.minimum(t32, clip_abs[:, None]), -clip_abs[:, None]) scale = (clip_abs / 127.0).clamp_min(1.0 / 127.0) - q = ( - torch.clamp(torch.round(clipped / scale[:, None]), -127, 127) - .to(torch.int8) - .contiguous() - ) + q = torch.clamp(torch.round(clipped / scale[:, None]), -127, 127).to(torch.int8).contiguous() return q, scale.to(dtype=INT8_PER_ROW_SCALE_DTYPE).contiguous() # Vectors / scalars use a simpler per-tensor scale. - clip_abs = ( - float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) - if t32.numel() - else 0.0 - ) + clip_abs = float(torch.quantile(t32.abs().flatten(), INT8_CLIP_Q).item()) if t32.numel() else 0.0 scale = torch.tensor(clip_abs / 127.0 if clip_abs > 0 else 1.0, dtype=torch.float32) - q = ( - torch.clamp( - torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127 - ) - .to(torch.int8) - .contiguous() - ) + q = torch.clamp(torch.round(torch.clamp(t32, -clip_abs, clip_abs) / scale), -127, 127).to(torch.int8).contiguous() return q, scale - -# ------------------------------------ -# INT6 OPTIMAL-CLIP QUANTIZATION -# ------------------------------------ - - -def _classify_param_jepa(name: str) -> str: - if "tok_emb" in name or "decoder_token_emb" in name or "decoder_out" in name: - return "embed" - if ".mlp." in name: - return "mlp" - if ".attn." in name: - return "attn" - return "other" - - -def quantize_int6_per_row( - t: Tensor, clip_range: int = 31 -) -> tuple[Tensor, Tensor]: - t32 = t.float() - if t32.ndim == 2: - 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 - amax = t32.abs().max().item() - scale = torch.tensor( - amax / clip_range if amax > 0 else 1.0, dtype=torch.float16 +def quantize_state_dict_int8(state_dict: dict[str, Tensor]): + # Single supported clean-script export format: + # - per-row int8 for 2D float tensors + # - per-tensor int8 for other float tensors + # - exact passthrough for non-floats + # - passthrough for small float tensors, stored as fp16 to save bytes + quantized: dict[str, Tensor] = {} + scales: dict[str, Tensor] = {} + dtypes: dict[str, str] = {} + passthrough: dict[str, Tensor] = {} + passthrough_orig_dtypes: dict[str, str] = {} + qmeta: dict[str, dict[str, object]] = {} + stats = dict.fromkeys( + ("param_count", "num_tensors", "num_float_tensors", "num_nonfloat_tensors", "baseline_tensor_bytes", "int8_payload_bytes"), + 0, ) - q = torch.clamp( - torch.round(t32 / scale.float()), -clip_range, clip_range - ).to(torch.int8) - return q, scale - -def mixed_quantize_int6( - state_dict: dict[str, Tensor], int6_cats: set[str] -) -> tuple[dict[str, Tensor], dict[str, object]]: - result: dict[str, Tensor] = {} - meta: dict[str, object] = {} for name, tensor in state_dict.items(): - t = tensor.detach().cpu().contiguous() - cat = _classify_param_jepa(name) - 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 - if cat in int6_cats and t.ndim >= 1: - q, s = quantize_int6_per_row(t) - result[name + ".q"] = q - result[name + ".scale"] = s - meta[name] = {"type": "int6"} - else: - q, s = quantize_float_tensor(t) - result[name + ".q"] = q - result[name + ".scale"] = s - meta[name] = {"type": "int8"} - return result, meta - - -def dequantize_mixed_int6( - result: dict[str, Tensor], - meta: dict[str, object], - template_sd: dict[str, Tensor], -) -> dict[str, Tensor]: - out: dict[str, Tensor] = {} - for name, orig in template_sd.items(): - info = meta.get(name) - if info is None: + 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 - 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 + + # Small float tensors are cheap enough to keep directly. We still downcast + # fp32/bf16 passthrough tensors to fp16 so metadata does not dominate size. + 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 - q, s = result[name + ".q"], result[name + ".scale"] + + stats["num_float_tensors"] += 1 + q, s = quantize_float_tensor(t) if s.ndim > 0: - out[name] = ( - q.float() * s.float().view(q.shape[0], *([1] * (q.ndim - 1))) - ).to(orig_dtype) + qmeta[name] = {"scheme": "per_row", "axis": 0} + quantized[name] = q + scales[name] = s + dtypes[name] = str(t.dtype).removeprefix("torch.") + stats["int8_payload_bytes"] += tensor_nbytes(q) + tensor_nbytes(s) + + obj: dict[str, object] = { + "__quant_format__": "int8_clean_per_row_v1", + "quantized": quantized, + "scales": scales, + "dtypes": dtypes, + "passthrough": passthrough, + } + if qmeta: + obj["qmeta"] = qmeta + if passthrough_orig_dtypes: + obj["passthrough_orig_dtypes"] = passthrough_orig_dtypes + return obj, stats + +def dequantize_state_dict_int8(obj: dict[str, object]) -> dict[str, Tensor]: + out: dict[str, Tensor] = {} + qmeta = obj.get("qmeta", {}) + passthrough_orig_dtypes = obj.get("passthrough_orig_dtypes", {}) + for name, q in obj["quantized"].items(): + dtype = getattr(torch, obj["dtypes"][name]) + s = obj["scales"][name] + if qmeta.get(name, {}).get("scheme") == "per_row" or s.ndim > 0: + s = s.to(dtype=torch.float32) + # Broadcast the saved row scale back across trailing dimensions. + out[name] = (q.float() * s.view(q.shape[0], *([1] * (q.ndim - 1)))).to(dtype=dtype).contiguous() else: - out[name] = (q.float() * float(s.item())).to(orig_dtype) + scale = float(s.item()) + out[name] = (q.float() * scale).to(dtype=dtype).contiguous() + for name, t in obj["passthrough"].items(): + # Restore small tensors, undoing the temporary fp16 storage cast if needed. + out_t = t.detach().to("cpu").contiguous() + orig_dtype = passthrough_orig_dtypes.get(name) + if isinstance(orig_dtype, str): + out_t = out_t.to(dtype=getattr(torch, orig_dtype)).contiguous() + out[name] = out_t return out # ----------------------------- -# DATA LOADING +# DATA LOADING # ----------------------------- - def load_data_shard(file: Path) -> Tensor: header_bytes = 256 * np.dtype(" Tensor: num_tokens = int(header[2]) expected_size = header_bytes + num_tokens * token_bytes if file.stat().st_size != expected_size: - raise ValueError( - f"Shard size mismatch for {file}: expected {expected_size} bytes" - ) + raise ValueError(f"Shard size mismatch for {file}: expected {expected_size} bytes") tokens_np = np.fromfile(file, dtype=" tuple[Tensor, Tensor]: + 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) @@ -751,16 +491,12 @@ def next_batch( 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 - ) - + return x.to(self.device, non_blocking=True), y.to(self.device, non_blocking=True) # ----------------------------- # TRANSFORMER MODULES # ----------------------------- - class RMSNorm(nn.Module): def __init__(self, eps: float | None = None): super().__init__() @@ -772,32 +508,16 @@ def forward(self, x: Tensor) -> Tensor: class CastedLinear(nn.Linear): # Keep weights in fp32 for optimizer/state quality, cast at matmul time for bf16 compute. - _qat_enabled: bool = False - def forward(self, x: Tensor) -> Tensor: - w = self.weight.to(x.dtype) - if CastedLinear._qat_enabled and self.training and w.ndim == 2: - with torch.no_grad(): - w32 = self.weight.float() - row_max = w32.abs().amax(dim=1) - scale = (row_max / 31.0).clamp_min(1.0 / 31.0) - w_q = ( - torch.clamp(torch.round(w32 / scale[:, None]), -31, 31) - * scale[:, None] - ).to(x.dtype) - w = w + (w_q - w).detach() bias = self.bias.to(x.dtype) if self.bias is not None else None - return F.linear(x, w, bias) + return F.linear(x, self.weight.to(x.dtype), bias) def restore_low_dim_params_to_fp32(module: nn.Module) -> None: # Keep small/control parameters in fp32 even when the model body runs in bf16. with torch.no_grad(): for name, param in module.named_parameters(): - if ( - param.ndim < 2 - or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) - ) and param.dtype != torch.float32: + 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() @@ -811,9 +531,7 @@ def __init__(self, dim: int, base: float = 10000.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]: + 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 @@ -859,28 +577,14 @@ def __init__( 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.q_gain = nn.Parameter(torch.full((num_heads,), qk_gain_init, dtype=torch.float32)) self.rotary = Rotary(self.head_dim, base=rope_base) def forward(self, x: Tensor) -> Tensor: bsz, seqlen, dim = x.shape - q = ( - self.c_q(x) - .reshape(bsz, seqlen, self.num_heads, self.head_dim) - .transpose(1, 2) - ) - k = ( - self.c_k(x) - .reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) - .transpose(1, 2) - ) - v = ( - self.c_v(x) - .reshape(bsz, seqlen, self.num_kv_heads, self.head_dim) - .transpose(1, 2) - ) + q = self.c_q(x).reshape(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2) + k = self.c_k(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) + v = self.c_v(x).reshape(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2) q = F.rms_norm(q, (q.size(-1),)) k = F.rms_norm(k, (k.size(-1),)) cos, sin = self.rotary(seqlen, x.device, q.dtype) @@ -909,7 +613,7 @@ def __init__(self, dim: int, mlp_mult: int): self.proj._zero_init = True def forward(self, x: Tensor) -> Tensor: - x = F.leaky_relu(self.fc(x), negative_slope=0.5) + x = torch.relu(self.fc(x)) return self.proj(x.square()) @@ -926,114 +630,47 @@ def __init__( 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.attn = CausalSelfAttention(dim, num_heads, num_kv_heads, rope_base, qk_gain_init) self.mlp = MLP(dim, mlp_mult) self.attn_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) self.mlp_scale = nn.Parameter(torch.ones(dim, dtype=torch.float32)) - self.resid_mix = nn.Parameter( - torch.stack((torch.ones(dim), torch.zeros(dim))).float() - ) + self.resid_mix = nn.Parameter(torch.stack((torch.ones(dim), torch.zeros(dim))).float()) def forward(self, x: Tensor, x0: Tensor) -> Tensor: mix = self.resid_mix.to(dtype=x.dtype) x = mix[0][None, None, :] * x + mix[1][None, None, :] * x0 attn_out = self.attn(self.attn_norm(x)) x = x + self.attn_scale.to(dtype=x.dtype)[None, None, :] * attn_out - x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp( - self.mlp_norm(x) - ) + x = x + self.mlp_scale.to(dtype=x.dtype)[None, None, :] * self.mlp(self.mlp_norm(x)) return x -class SIGReg(nn.Module): - # Sketch regularizer from LeWM, adapted to local (per-rank) batches. - def __init__(self, knots: int = 17, num_proj: int = 256): - super().__init__() - self.num_proj = num_proj - t = torch.linspace(0, 3, knots, dtype=torch.float32) - dt = 3 / max(knots - 1, 1) - weights = torch.full((knots,), 2 * dt, dtype=torch.float32) - if knots > 1: - weights[[0, -1]] = dt - window = torch.exp(-t.square() / 2.0) - self.register_buffer("t", t, persistent=False) - self.register_buffer("phi", window, persistent=False) - self.register_buffer("weights", weights * window, persistent=False) - - def forward(self, proj: Tensor) -> Tensor: - if proj.ndim != 3: - raise ValueError(f"SIGReg expects (T, B, D), got {tuple(proj.shape)}") - A = torch.randn( - proj.size(-1), self.num_proj, device=proj.device, dtype=proj.dtype - ) - A = A / (A.norm(p=2, dim=0, keepdim=True).clamp_min(1e-6)) - x_t = (proj @ A).unsqueeze(-1) * self.t.to(dtype=proj.dtype) - err = ( - x_t.cos().mean(-3) - self.phi.to(dtype=proj.dtype) - ).square() + x_t.sin().mean(-3).square() - statistic = (err @ self.weights.to(dtype=proj.dtype)) * proj.size(-2) - return statistic.mean().float() - - -class LatentMLP(nn.Module): - def __init__(self, input_dim: int, output_dim: int, hidden_mult: int = 2): - super().__init__() - hidden = hidden_mult * input_dim - self.norm = RMSNorm() - self.fc = CastedLinear(input_dim, hidden, bias=False) - self.proj = CastedLinear(hidden, output_dim, bias=False) - - def forward(self, x: Tensor) -> Tensor: - x = self.norm(x) - x = F.silu(self.fc(x)) - return self.proj(x) - - -class BytePatchJEPA(nn.Module): +class GPT(nn.Module): def __init__( self, - *, vocab_size: int, num_layers: int, - encoder_repeats: 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, - patch_size: int, - latent_dim: int, - decoder_layers: int, - decoder_heads: int, - sigreg_knots: int, - sigreg_num_proj: int, - sigreg_weight: float, - jepa_pred_weight: float, - jepa_ce_weight: float, ): super().__init__() - if patch_size < 2: - raise ValueError(f"PATCH_SIZE must be >=2, got {patch_size}") - if decoder_heads <= 0 or model_dim % decoder_heads != 0: - raise ValueError( - f"DECODER_HEADS={decoder_heads} must divide MODEL_DIM={model_dim}" - ) - self.vocab_size = vocab_size - self.patch_size = patch_size - self.encoder_repeats = encoder_repeats - self.sigreg_weight = sigreg_weight - self.jepa_pred_weight = jepa_pred_weight - self.jepa_ce_weight = jepa_ce_weight - self.bos_id = 1 - + if logit_softcap <= 0.0: + raise ValueError(f"logit_softcap must be positive, got {logit_softcap}") + self.tie_embeddings = tie_embeddings + self.tied_embed_init_std = tied_embed_init_std + self.logit_softcap = logit_softcap self.tok_emb = nn.Embedding(vocab_size, model_dim) - self.patch_pos = nn.Parameter( - torch.zeros(patch_size, model_dim, dtype=torch.float32) - ) - self.patch_in = CastedLinear(patch_size * model_dim, model_dim, bias=False) + self.num_encoder_layers = num_layers // 2 + self.num_decoder_layers = num_layers - self.num_encoder_layers + self.num_skip_weights = min(self.num_encoder_layers, self.num_decoder_layers) + self.skip_weights = nn.Parameter(torch.ones(self.num_skip_weights, model_dim, dtype=torch.float32)) self.blocks = nn.ModuleList( [ Block( @@ -1044,156 +681,53 @@ def __init__( rope_base, qk_gain_init, ) - for _ in range(num_layers) + for i in range(num_layers) ] ) self.final_norm = RMSNorm() - self.projector = LatentMLP(model_dim, latent_dim) - self.predictor = LatentMLP(model_dim, latent_dim) - self.sigreg = SIGReg(knots=sigreg_knots, num_proj=sigreg_num_proj) - - self.start_latent = nn.Parameter(torch.zeros(latent_dim, dtype=torch.float32)) - self.decoder_token_emb = nn.Embedding(vocab_size, model_dim) - self.decoder_cond = CastedLinear(latent_dim, model_dim, bias=False) - self.decoder_blocks = nn.ModuleList( - [ - Block( - model_dim, - decoder_heads, - decoder_heads, - mlp_mult, - rope_base, - qk_gain_init, - ) - for _ in range(decoder_layers) - ] - ) - self.decoder_norm = RMSNorm() - self.decoder_out = CastedLinear(model_dim, vocab_size, bias=False) + 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: - nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02) - nn.init.normal_(self.decoder_token_emb.weight, mean=0.0, std=0.02) - nn.init.normal_(self.patch_pos, mean=0.0, std=0.02) - nn.init.normal_(self.start_latent, mean=0.0, std=0.02) + if self.tie_embeddings: + nn.init.normal_(self.tok_emb.weight, mean=0.0, std=self.tied_embed_init_std) for module in self.modules(): if isinstance(module, nn.Linear) and getattr(module, "_zero_init", False): nn.init.zeros_(module.weight) - def _build_full_sequence( - self, input_ids: Tensor, target_ids: Tensor | None - ) -> Tensor: - if target_ids is None: - raise ValueError( - "BytePatchJEPA requires target_ids so it can reconstruct the full autoregressive stream" - ) - if input_ids.shape != target_ids.shape: - raise ValueError( - f"input_ids and target_ids must match, got {tuple(input_ids.shape)} vs {tuple(target_ids.shape)}" - ) - full = torch.cat((input_ids[:, :1], target_ids), dim=1) - if full.size(1) % self.patch_size != 0: - raise ValueError( - f"Sequence length {full.size(1)} must be divisible by PATCH_SIZE={self.patch_size}; " - "set TRAIN_SEQ_LEN so TRAIN_SEQ_LEN+1 is divisible by PATCH_SIZE" - ) - return full - - def _patchify(self, full_ids: Tensor) -> Tensor: - bsz, seqlen = full_ids.shape - num_patches = seqlen // self.patch_size - return full_ids.view(bsz, num_patches, self.patch_size) - - def _encode_patches(self, patches: Tensor) -> Tensor: - x = self.tok_emb(patches) - x = x + self.patch_pos.to(dtype=x.dtype)[None, None, :, :] + def forward(self, input_ids: Tensor, target_ids: Tensor) -> Tensor: + x = self.tok_emb(input_ids) x = F.rms_norm(x, (x.size(-1),)) - return self.patch_in(x.reshape(x.size(0), x.size(1), -1)) - - def _contextualize(self, patch_emb: Tensor) -> Tensor: - x = F.rms_norm(patch_emb, (patch_emb.size(-1),)) - x0 = x - for _ in range(self.encoder_repeats): - for block in self.blocks: - x = block(x, x0) - return self.final_norm(x) - - def _decode_logits(self, cond_latent: Tensor, target_patches: Tensor) -> Tensor: - bsz, num_patches, patch_size = target_patches.shape - total_bytes = num_patches * patch_size - flat_bytes = target_patches.reshape(bsz, total_bytes) - prev = torch.cat( - [flat_bytes.new_full((bsz, 1), self.bos_id), flat_bytes[:, :-1]], dim=1 - ) - x = self.decoder_token_emb(prev) - cond = self.decoder_cond(cond_latent).to(dtype=x.dtype) - x = x + cond.repeat_interleave(patch_size, dim=1) x0 = x - for block in self.decoder_blocks: - x = block(x, x0) - x = self.decoder_norm(x) - return self.decoder_out(x).reshape( - bsz, num_patches, patch_size, self.vocab_size - ) - - def forward( - self, input_ids: Tensor, target_ids: Tensor | None - ) -> tuple[Tensor, Tensor]: - full = self._build_full_sequence(input_ids, target_ids) - patches = self._patchify(full) - patch_emb = self._encode_patches(patches) - target_latent = self.projector(patch_emb) - context = self._contextualize(patch_emb) - pred_latent = self.predictor(context[:, :-1]) - pred_loss = F.mse_loss( - pred_latent.float(), target_latent[:, 1:].detach().float(), reduction="mean" - ) - sigreg_loss = self.sigreg(target_latent.transpose(0, 1)) - - start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( - patches.size(0), 1, -1 - ) - cond_latent = torch.cat((start, pred_latent), dim=1) - logits = self._decode_logits(cond_latent, patches) - ce = F.cross_entropy( - logits.reshape(-1, self.vocab_size).float(), - patches.reshape(-1), - reduction="none", - ) - ce = ce.reshape_as(patches).float() - mask = torch.ones_like(ce) - mask[:, 0, 0] = 0.0 - nll = (ce * mask).sum() / mask.sum() - total = ( - self.jepa_ce_weight * nll - + self.jepa_pred_weight * pred_loss - + self.sigreg_weight * sigreg_loss - ) - return total, nll - - def forward_logits( - self, input_ids: Tensor, target_ids: Tensor - ) -> Tensor: - full = self._build_full_sequence(input_ids, target_ids) - patches = self._patchify(full) - patch_emb = self._encode_patches(patches) - context = self._contextualize(patch_emb) - pred_latent = self.predictor(context[:, :-1]) - start = self.start_latent.to(dtype=pred_latent.dtype)[None, None, :].expand( - patches.size(0), 1, -1 - ) - cond_latent = torch.cat((start, pred_latent), dim=1) - logits = self._decode_logits(cond_latent, patches) - bsz = logits.size(0) - return logits.reshape(bsz, -1, self.vocab_size) + skips: list[Tensor] = [] + + # First half stores skips; second half reuses them in reverse order. + for i in range(self.num_encoder_layers): + x = self.blocks[i](x, x0) + skips.append(x) + for i in range(self.num_decoder_layers): + if skips: + x = x + self.skip_weights[i].to(dtype=x.dtype)[None, None, :] * skips.pop() + x = self.blocks[self.num_encoder_layers + i](x, x0) + + x = self.final_norm(x).reshape(-1, x.size(-1)) + targets = target_ids.reshape(-1) + if self.tie_embeddings: + logits_proj = F.linear(x, self.tok_emb.weight) + else: + if self.lm_head is None: + raise RuntimeError("lm_head is required when tie_embeddings=False") + logits_proj = self.lm_head(x) + logits = self.logit_softcap * torch.tanh(logits_proj / self.logit_softcap) + return F.cross_entropy(logits.float(), targets, reduction="mean") # ----------------------------- # TRAINING # ----------------------------- - def main() -> None: global zeropower_via_newtonschulz5 @@ -1212,9 +746,7 @@ def main() -> None: 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" - ) + 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(): @@ -1229,12 +761,7 @@ def main() -> None: # Fast math knobs torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True - from torch.backends.cuda import ( - enable_cudnn_sdp, - enable_flash_sdp, - enable_math_sdp, - enable_mem_efficient_sdp, - ) + 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) @@ -1261,13 +788,7 @@ def log0(msg: str, console: bool = True) -> None: 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, + subprocess.run(["nvidia-smi"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False).stdout, console=False, ) log0("=" * 100, console=False) @@ -1281,18 +802,20 @@ def log0(msg: str, console: bool = True) -> None: torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) - if (args.train_seq_len + 1) % args.patch_size != 0: + 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"JEPA requires TRAIN_SEQ_LEN+1 to be divisible by PATCH_SIZE; " - f"got TRAIN_SEQ_LEN={args.train_seq_len}, PATCH_SIZE={args.patch_size}" + f"VOCAB_SIZE={args.vocab_size} does not match tokenizer vocab_size={int(sp.vocab_size())}" ) - base_bytes_lut, has_leading_space_lut, is_boundary_token_lut = load_pure_byte_luts( - args.tokenizer_path, args.vocab_size, device - ) 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) - log0(f"val_bpb:enabled tokenizer_kind=byte tokenizer_path={args.tokenizer_path}") + 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}") @@ -1300,115 +823,83 @@ def log0(msg: str, console: bool = True) -> None: # MODEL + OPTIMIZER SETUP # ----------------------------- - base_model: nn.Module = BytePatchJEPA( + base_model = GPT( vocab_size=args.vocab_size, num_layers=args.num_layers, - encoder_repeats=args.encoder_repeats, 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, - patch_size=args.patch_size, - latent_dim=args.latent_dim, - decoder_layers=args.decoder_layers, - decoder_heads=args.decoder_heads, - sigreg_knots=args.sigreg_knots, - sigreg_num_proj=args.sigreg_num_proj, - sigreg_weight=args.sigreg_weight, - jepa_pred_weight=args.jepa_pred_weight, - jepa_ce_weight=args.jepa_ce_weight, - ) - base_model = base_model.to(device).bfloat16() + ).to(device).bfloat16() for module in base_model.modules(): if isinstance(module, CastedLinear): module.float() restore_low_dim_params_to_fp32(base_model) - compiled_model = ( - torch.compile(base_model, dynamic=False, fullgraph=False) - if args.use_compile - else base_model + compiled_model = torch.compile(base_model, dynamic=False, fullgraph=True) + model: nn.Module = DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) if distributed else compiled_model + + # Optimizer split: + # - token embedding (Adam) uses EMBED_LR + # - untied lm_head (Adam) uses HEAD_LR + # - matrix params in transformer blocks use MATRIX_LR via Muon + # - vectors/scalars use SCALAR_LR via Adam + block_named_params = list(base_model.blocks.named_parameters()) + matrix_params = [ + p + for name, p in block_named_params + if p.ndim == 2 and not any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + scalar_params = [ + p + for name, p in block_named_params + if p.ndim < 2 or any(pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS) + ] + if base_model.skip_weights.numel() > 0: + scalar_params.append(base_model.skip_weights) + token_lr = args.tied_embed_lr if args.tie_embeddings else args.embed_lr + optimizer_tok = torch.optim.Adam( + [{"params": [base_model.tok_emb.weight], "lr": token_lr, "base_lr": token_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + fused=True, ) - model: nn.Module = ( - DDP(compiled_model, device_ids=[local_rank], broadcast_buffers=False) - if distributed - else compiled_model + optimizer_muon = Muon( + matrix_params, + lr=args.matrix_lr, + momentum=args.muon_momentum, + backend_steps=args.muon_backend_steps, ) - - embedding_tags = ("tok_emb", "decoder_token_emb", "patch_pos") - head_names = {"decoder_out.weight"} - embedding_params: list[Tensor] = [] - head_params: list[Tensor] = [] - matrix_params: list[Tensor] = [] - scalar_params: list[Tensor] = [] - for name, param in base_model.named_parameters(): - if not param.requires_grad: - continue - if name in head_names: - head_params.append(param) - elif any(tag in name for tag in embedding_tags): - embedding_params.append(param) - elif param.ndim == 2 and not any( - pattern in name for pattern in CONTROL_TENSOR_NAME_PATTERNS - ): - matrix_params.append(param) - else: - scalar_params.append(param) - - token_lr = args.embed_lr - optimizers: list[torch.optim.Optimizer] = [] - if embedding_params: - optimizer_embed = torch.optim.Adam( - [{"params": embedding_params, "lr": token_lr, "base_lr": token_lr}], - betas=(args.beta1, args.beta2), - eps=args.adam_eps, - fused=True, - ) - optimizers.append(optimizer_embed) - optimizer_muon = None - if matrix_params: - optimizer_muon = Muon( - matrix_params, - lr=args.matrix_lr, - momentum=args.muon_momentum, - backend_steps=args.muon_backend_steps, - ) - for group in optimizer_muon.param_groups: - group["base_lr"] = args.matrix_lr - optimizers.append(optimizer_muon) - if head_params: + for group in optimizer_muon.param_groups: + group["base_lr"] = args.matrix_lr + optimizer_scalar = torch.optim.Adam( + [{"params": scalar_params, "lr": args.scalar_lr, "base_lr": args.scalar_lr}], + betas=(args.beta1, args.beta2), + eps=args.adam_eps, + 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": head_params, "lr": args.head_lr, "base_lr": args.head_lr}], + [{"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.append(optimizer_head) - if scalar_params: - optimizer_scalar = torch.optim.Adam( - [ - { - "params": scalar_params, - "lr": args.scalar_lr, - "base_lr": args.scalar_lr, - } - ], - betas=(args.beta1, args.beta2), - eps=args.adam_eps, - fused=True, - ) - optimizers.append(optimizer_scalar) + optimizers.insert(1, optimizer_head) n_params = sum(p.numel() for p in base_model.parameters()) log0(f"model_params:{n_params}") log0(f"world_size:{world_size} grad_accum_steps:{grad_accum_steps}") log0("sdp_backends:cudnn=False flash=True mem_efficient=False math=False") + log0(f"attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}") log0( - f"model_family:jepa attention_mode:gqa num_heads:{args.num_heads} num_kv_heads:{args.num_kv_heads}" - ) - log0( - f"embed_lr:{token_lr} head_lr:{args.head_lr if head_params else 0.0} " + 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( @@ -1416,12 +907,6 @@ def log0(msg: str, console: bool = True) -> None: f"iterations:{args.iterations} warmup_steps:{args.warmup_steps} " f"max_wallclock_seconds:{args.max_wallclock_seconds:.3f}" ) - log0( - f"jepa:patch_size:{args.patch_size} latent_dim:{args.latent_dim} " - f"encoder_layers:{args.num_layers}x{args.encoder_repeats} " - f"decoder_layers:{args.decoder_layers} decoder_heads:{args.decoder_heads} " - f"sigreg_weight:{args.sigreg_weight} pred_weight:{args.jepa_pred_weight} ce_weight:{args.jepa_ce_weight}" - ) log0(f"seed:{args.seed}") # ----------------------------- @@ -1434,63 +919,38 @@ 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 - ) + 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 - ) + 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 - ) + return remaining_ms / max(warmdown_ms, 1e-9) if remaining_ms <= warmdown_ms else 1.0 # Warmup primes the compiled forward/backward/optimizer paths, then we restore the # initial weights/optimizer state so measured training starts from the true init. if args.warmup_steps > 0: - initial_model_state = { - name: tensor.detach().cpu().clone() - for name, tensor in base_model.state_dict().items() - } - initial_optimizer_states = [ - copy.deepcopy(opt.state_dict()) for opt in optimizers - ] + 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) + 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 - ): + 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): @@ -1498,18 +958,12 @@ def lr_mul(step: int, elapsed_ms: float) -> float: zero_grad_all() if distributed: model.require_backward_grad_sync = True - train_loader = DistributedTokenLoader( - args.train_files, rank, world_size, device - ) + train_loader = DistributedTokenLoader(args.train_files, rank, world_size, device) # ----------------------------- # MAIN TRAINING LOOP # ----------------------------- - ema_state = { - name: t.detach().float().clone() - for name, t in base_model.state_dict().items() - } training_time_ms = 0.0 stop_after_step: int | None = None torch.cuda.synchronize() @@ -1517,13 +971,9 @@ def lr_mul(step: int, elapsed_ms: float) -> float: step = 0 while True: - last_step = step == args.iterations or ( - stop_after_step is not None and step >= stop_after_step - ) + 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 - ) + 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) @@ -1556,41 +1006,22 @@ def lr_mul(step: int, elapsed_ms: float) -> float: elapsed_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) scale = lr_mul(step, elapsed_ms) - if ( - args.late_qat_threshold > 0 - and scale < args.late_qat_threshold - and not CastedLinear._qat_enabled - ): - CastedLinear._qat_enabled = True - log0(f"late_qat:enabled step:{step} scale:{scale:.4f}") zero_grad_all() train_loss = torch.zeros((), device=device) - train_nll = 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 - ) + 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, nll = model(x, y) + loss = model(x, y) train_loss += loss.detach() - train_nll += nll.detach() (loss * grad_scale).backward() train_loss /= grad_accum_steps - train_nll /= grad_accum_steps - if optimizer_muon is not None: - 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 + 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: @@ -1602,29 +1033,20 @@ def lr_mul(step: int, elapsed_ms: float) -> float: opt.step() zero_grad_all() - with torch.no_grad(): - for name, t in base_model.state_dict().items(): - ema_state[name].mul_(args.ema_decay).add_( - t.detach().float(), alpha=1.0 - args.ema_decay - ) step += 1 approx_training_time_ms = training_time_ms + 1000.0 * (time.perf_counter() - t0) - should_log_train = args.train_log_every > 0 and ( - step <= 10 - or step % args.train_log_every == 0 - or stop_after_step is not None + 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 " - f"train_nll:{train_nll.item():.4f}" + f"train_time:{approx_training_time_ms:.0f}ms step_avg:{approx_training_time_ms / step:.2f}ms" ) # Needed to sync whether we've reached the wallclock cap. - reached_cap = ( - max_wallclock_ms is not None and approx_training_time_ms >= max_wallclock_ms - ) + 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) @@ -1637,13 +1059,6 @@ def lr_mul(step: int, elapsed_ms: float) -> float: f"reserved: {torch.cuda.max_memory_reserved() // 1024 // 1024} MiB" ) - current_sd = base_model.state_dict() - ema_avg = { - name: t.to(dtype=current_sd[name].dtype) for name, t in ema_state.items() - } - base_model.load_state_dict(ema_avg, strict=True) - log0(f"ema:applied EMA weights (decay={args.ema_decay})") - # ----------------------------- # SERIALIZATION + ROUNDTRIP VALIDATION # ----------------------------- @@ -1658,55 +1073,50 @@ def lr_mul(step: int, elapsed_ms: float) -> float: log0(f"Code size: {code_bytes} bytes") log0(f"Total submission size: {model_bytes + code_bytes} bytes") - template_sd = {k: v.cpu() for k, v in base_model.state_dict().items()} - int6_cats = {"mlp", "attn", "other", "embed"} - quant_result, quant_meta = mixed_quantize_int6( - base_model.state_dict(), int6_cats - ) + quant_obj, quant_stats = quantize_state_dict_int8(base_model.state_dict()) quant_buf = io.BytesIO() - torch.save({"w": quant_result, "m": quant_meta}, quant_buf) + torch.save(quant_obj, quant_buf) quant_raw = quant_buf.getvalue() - quant_blob = lzma.compress(quant_raw, preset=9) + quant_blob = zlib.compress(quant_raw, level=9) + quant_raw_bytes = len(quant_raw) if master_process: - with open("final_model.int6.ptz", "wb") as f: + with open("final_model.int8.ptz", "wb") as f: f.write(quant_blob) - quant_file_bytes = len(quant_blob) + quant_file_bytes = os.path.getsize("final_model.int8.ptz") code_bytes = len(code.encode("utf-8")) - log0(f"Serialized model int6+lzma: {quant_file_bytes} bytes") - log0(f"Total submission size int6+lzma: {quant_file_bytes + code_bytes} bytes") + ratio = quant_stats["baseline_tensor_bytes"] / max(quant_stats["int8_payload_bytes"], 1) + log0( + f"Serialized model int8+zlib: {quant_file_bytes} bytes " + f"(payload:{quant_stats['int8_payload_bytes']} raw_torch:{quant_raw_bytes} payload_ratio:{ratio:.2f}x)" + ) + log0(f"Total submission size int8+zlib: {quant_file_bytes + code_bytes} bytes") if distributed: dist.barrier() - with open("final_model.int6.ptz", "rb") as f: + with open("final_model.int8.ptz", "rb") as f: quant_blob_disk = f.read() - quant_state = torch.load( - io.BytesIO(lzma.decompress(quant_blob_disk)), map_location="cpu" + quant_state = torch.load(io.BytesIO(zlib.decompress(quant_blob_disk)), 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, ) - CastedLinear._qat_enabled = False - deq_sd = dequantize_mixed_int6(quant_state["w"], quant_state["m"], template_sd) - base_model.load_state_dict(deq_sd, strict=True) - - if args.ttt_enabled: - torch.cuda.synchronize() - t_ttt = time.perf_counter() - ttt_loss, ttt_bpb = eval_val_sliding_ttt( - args, - base_model, - rank, - world_size, - device, - val_tokens, - base_bytes_lut, - has_leading_space_lut, - is_boundary_token_lut, - log_fn=log0, - ) - torch.cuda.synchronize() - log0( - f"final_ttt val_loss:{ttt_loss:.4f} val_bpb:{ttt_bpb:.4f} " - f"eval_time:{1000.0 * (time.perf_counter() - t_ttt):.0f}ms" - ) - log0(f"final_ttt_exact val_loss:{ttt_loss:.8f} val_bpb:{ttt_bpb:.8f}") + torch.cuda.synchronize() + log0( + f"final_int8_zlib_roundtrip val_loss:{q_val_loss:.4f} val_bpb:{q_val_bpb:.4f} " + f"eval_time:{1000.0 * (time.perf_counter() - t_qeval):.0f}ms" + ) + log0(f"final_int8_zlib_roundtrip_exact val_loss:{q_val_loss:.8f} val_bpb:{q_val_bpb:.8f}") if distributed: dist.destroy_process_group()