"""Evaluate a checkpoint's loss on TinyStories. Two measurements: 1. Exhaustive validation loss — every non-overlapping seq_len-token window in val.bin, token-weighted. Deterministic, no sampling noise. 2. Train-split loss on a random sample of batches, for the generalization gap. Usage: uv run python scripts/eval_final_loss.py uv run python scripts/eval_final_loss.py --checkpoint checkpoints/step_049500.pt """ import argparse import math import sys import time from pathlib import Path import numpy as np import torch PROJECT_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(PROJECT_ROOT)) from src.model import GPT # noqa: E402 def load_model(checkpoint_path: str, device: torch.device): ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False) config = ckpt["config"] model = GPT(config.model) model.load_state_dict(ckpt["model"]) model.to(device) model.eval() return model, ckpt["step"], config @torch.no_grad() def _batch_loss(model, x, y, device, amp_dtype): x = x.to(device, non_blocking=True) y = y.to(device, non_blocking=True) with torch.amp.autocast("cuda", dtype=amp_dtype, enabled=amp_dtype is not None): _, loss = model(x, y) return loss.item(), x.numel() def _windows(data, starts, seq_len): """Build (x, y) tensors from a list of start offsets.""" x = torch.stack( [torch.from_numpy(data[i : i + seq_len].astype(np.int64)) for i in starts] ) y = torch.stack( [torch.from_numpy(data[i + 1 : i + seq_len + 1].astype(np.int64)) for i in starts] ) return x, y def eval_exhaustive(model, data, seq_len, batch_size, device, amp_dtype, split="", max_windows: int | None = None): """Token-weighted loss over every non-overlapping window.""" n_windows = (len(data) - 1) // seq_len if max_windows is not None: n_windows = min(n_windows, max_windows) total_loss = 0.0 total_tokens = 0 t0 = time.time() n_batches = (n_windows + batch_size - 1) // batch_size for bi, start in enumerate(range(0, n_windows, batch_size)): starts = [ w * seq_len for w in range(start, min(start + batch_size, n_windows)) ] x, y = _windows(data, starts, seq_len) loss, n_tok = _batch_loss(model, x, y, device, amp_dtype) total_loss += loss * n_tok total_tokens += n_tok if bi % 50 == 0 or bi == n_batches - 1: elapsed = time.time() - t0 eta = elapsed / (bi + 1) * (n_batches - bi - 1) print( f" [{split}] batch {bi + 1}/{n_batches} | " f"running loss {total_loss / total_tokens:.4f} | " f"elapsed {elapsed / 60:.1f}m | eta {eta / 60:.1f}m", flush=True, ) return total_loss / total_tokens, total_tokens def eval_random(model, data, seq_len, batch_size, n_batches, device, amp_dtype, seed=1234): """Training-style estimate: random-offset batches (equivalent to estimate_loss).""" gen = torch.Generator().manual_seed(seed) max_start = len(data) - seq_len - 1 total_loss = 0.0 total_tokens = 0 for _ in range(n_batches): ix = torch.randint(0, max_start, (batch_size,), generator=gen).tolist() x, y = _windows(data, ix, seq_len) loss, n_tok = _batch_loss(model, x, y, device, amp_dtype) total_loss += loss * n_tok total_tokens += n_tok return total_loss / total_tokens def main(): ap = argparse.ArgumentParser() ap.add_argument("--checkpoint", default="checkpoints/step_050000.pt") ap.add_argument("--batch-size", type=int, default=16) ap.add_argument("--seq-len", type=int, default=1024) ap.add_argument("--train-batches", type=int, default=200, help="Random batches for the train-split sample") ap.add_argument("--random-val-batches", type=int, default=50, help="Training-style random val estimate (0 to skip)") ap.add_argument("--limit-val-batches", type=int, default=0, help="Debug: only run N exhaustive val batches (0 = all)") args = ap.parse_args() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") amp_dtype = ( torch.bfloat16 if device.type == "cuda" and torch.cuda.is_bf16_supported() else None ) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cuda.enable_flash_sdp(True) val_path = PROJECT_ROOT / "data" / "tinystories" / "val.bin" train_path = PROJECT_ROOT / "data" / "tinystories" / "train.bin" val = np.memmap(str(val_path), dtype=np.uint16, mode="r") train = np.memmap(str(train_path), dtype=np.uint16, mode="r") print(f"Device: {device} | amp dtype: {amp_dtype}") print(f"Checkpoint: {args.checkpoint}") print(f"Val tokens: {len(val):,} | Train tokens: {len(train):,}") print() model, step, config = load_model(args.checkpoint, device) print(f"Loaded checkpoint at step {step} " f"(config max_steps={config.training.max_steps})") n_params = sum(p.numel() for p in model.parameters()) print(f"Model: {n_params / 1e6:.1f}M params | dropout={config.model.dropout} " f"| eval mode\n") # ── 1. Exhaustive validation loss ────────────────────────────── n_windows = (len(val) - 1) // args.seq_len if args.limit_val_batches: n_windows = min(n_windows, args.limit_val_batches * args.batch_size) print(f"[debug] limiting val eval to {n_windows:,} windows") print(f"-- Exhaustive validation loss over {n_windows:,} windows " f"({n_windows * args.seq_len:,} tokens) --") val_loss, val_tokens = eval_exhaustive( model, val, args.seq_len, args.batch_size, device, amp_dtype, split="val", max_windows=n_windows, ) val_ppl = math.exp(val_loss) print(f"\n VAL loss = {val_loss:.4f} | ppl = {val_ppl:.1f} " f"| tokens = {val_tokens:,}") # ── 2. Training-style random val estimate (comparability) ───── if args.random_val_batches > 0: rnd = eval_random( model, val, args.seq_len, args.batch_size, args.random_val_batches, device, amp_dtype, ) print(f" VAL loss (training-style random {args.random_val_batches} " f"batches × {args.batch_size}) = {rnd:.4f}") # ── 3. Train-split sample loss ───────────────────────────────── print(f"\n-- Train split sample ({args.train_batches} random batches x " f"{args.batch_size}) --") train_loss = eval_random( model, train, args.seq_len, args.batch_size, args.train_batches, device, amp_dtype, seed=4321, ) print(f"\n TRAIN loss = {train_loss:.4f} | ppl = {math.exp(train_loss):.1f}") print("\n" + "=" * 64) print(f" Final checkpoint step : {step}") print(f" Validation loss : {val_loss:.4f} (ppl {val_ppl:.1f})") print(f" Train-split loss (sam.): {train_loss:.4f}") print(f" Train->val gap : {val_loss - train_loss:+.4f}") print("=" * 64) if __name__ == "__main__": main()