File size: 7,315 Bytes
7f1e014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""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()