AR-4B-base / training_code /ar /eval /val_loss.py
AjayRangoji's picture
Add complete pretraining codebase and cluster scripts under training_code/
df64241 verified
Raw History Blame Contribute Delete
1.96 kB
"""Validation loss on held-out data the model never trained on."""
import argparse
import math
import os
import numpy as np
import torch
import torch.nn.functional as F
from ar.data.tokenizer import Tokenizer
from ar.eval.generate import load_model
from ar.model.mask import build_doc_block_mask
@torch.no_grad()
def val_loss(model, path, eot_id, device, seq_len=4096, max_windows=200):
data = np.memmap(path, dtype=np.uint32, mode="r")
n = min(max_windows, (len(data) - 1) // seq_len)
total = 0.0
for i in range(n):
# fixed, non-overlapping windows from the start -> same numbers every run,
# so scores from different checkpoints are directly comparable
chunk = data[i * seq_len : (i + 1) * seq_len + 1].astype(np.int64)
chunk = torch.from_numpy(chunk).to(device)
x, y = chunk[:-1][None], chunk[1:][None]
# same same-document masking as training
is_eot = (x == eot_id).int()
seg = (torch.cumsum(is_eot, dim=1) - is_eot).int()
mask = build_doc_block_mask(seg, seq_len, device=device)
logits = model(x, mask)
total += F.cross_entropy(logits.float().view(-1, logits.size(-1)), y.view(-1)).item()
return total / n, n * seq_len
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("--model", required=True)
p.add_argument("--data", nargs="+", required=True)
args = p.parse_args()
device = "cuda"
tok = Tokenizer()
model = load_model(args.model, device)
for path in args.data:
if not os.path.exists(path):
print(f"{os.path.basename(path)}: not found, skipping", flush=True)
continue
loss, ntok = val_loss(model, path, tok.eot_id, device)
# perplexity = e^loss: roughly "how many tokens the model is torn between"
print(f"{os.path.basename(path)}: loss {loss:.4f} | ppl {math.exp(loss):.2f} "
f"| {ntok/1e6:.1f}M tokens", flush=True)