File size: 1,963 Bytes
df64241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)