File size: 3,361 Bytes
031489f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Held-out loss on assistant-side tokens. Usage: eval_nll.py <model_dir|native> <sequences.json> <out.json> <tag> [--fp32] [--actquant input,hidden]

Counts only tokens the model would generate itself (assistant messages: reasoning, text, tool calls, and the
end-of-turn token). Stores per-sequence sums so variants can be compared with paired statistics.
"""
import json, os, sys, time
import numpy as np
import mlx.core as mx
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import qlab

MODEL_TOK, END_MSG, EOS = 200001, 200010, 200006

def assistant_mask(ids):
    mask, inside = [], False
    for t in ids:
        if t == MODEL_TOK:
            inside = True
        mask.append(inside or t == EOS)
        if t == END_MSG:
            inside = False
    return mask

def main():
    args = sys.argv[1:]
    fp32 = "--fp32" in args
    if fp32: args.remove("--fp32")
    aq = None
    if "--actquant" in args:
        i = args.index("--actquant"); aq = tuple(args[i + 1].split(",")); del args[i:i + 2]
    recipe = None
    if "--recipe" in args:
        i = args.index("--recipe"); rfile, rname = args[i + 1].split(":"); del args[i:i + 2]
        recipe = json.load(open(rfile))[rname]
    model_dir, seq_path, out_path, tag = args[:4]
    path = qlab.NATIVE if model_dir == "native" else model_dir
    model, _ = qlab.load_native(fp32=False, path=path)
    size = None
    if recipe is not None:
        import recipes as R
        R.apply(model, recipe, os.path.join(qlab.ROOT, "q", "shards"))
        size = R.nbytes(model) / 2**30
    if fp32:
        qlab.to_fp32(model); mx.eval(model.parameters())
    if aq:
        import actquant
        actquant.install(model, aq)
    seqs = qlab.load_sequences(seq_path, split="eval", max_len=1024)
    rows, t0 = [], time.time()
    for s in seqs:
        ids = s["ids"]
        lg = qlab.logits_for(model, ids)
        lp = qlab.log_softmax(lg)[:-1]
        nxt = mx.array(ids[1:])
        nll = -mx.take_along_axis(lp, nxt[:, None], axis=-1)[:, 0]
        m = mx.array(assistant_mask(ids)[1:]).astype(mx.float32)
        hit = (mx.argmax(lp, axis=-1) == nxt).astype(mx.float32)
        vals = [(nll * m).sum(), m.sum(), (hit * m).sum()]
        mx.eval(vals)
        rows.append(dict(name=s["name"], kind=s["kind"].split(":")[0], nll=vals[0].item(), n=int(vals[1].item()), hit=vals[2].item()))
        del lg, lp
    res = json.load(open(out_path)) if os.path.exists(out_path) else {}
    n = sum(r["n"] for r in rows)
    summ = dict(tokens=n, nll=sum(r["nll"] for r in rows) / n, acc=sum(r["hit"] for r in rows) / n, seconds=round(time.time() - t0),
                peak_gb=round(mx.get_peak_memory() / 2**30, 2), weights_gib=size, activations="fp32" if fp32 else "bf16", actquant=aq)
    for kind in sorted({r["kind"] for r in rows}):
        sel = [r for r in rows if r["kind"] == kind]
        summ[kind] = dict(tokens=sum(r["n"] for r in sel), nll=sum(r["nll"] for r in sel) / max(1, sum(r["n"] for r in sel)))
    summ["rows"] = rows
    res[tag] = summ
    json.dump(res, open(out_path, "w"))
    print(f"{tag:28s} tokens {n} NLL {summ['nll']:.4f} ppl {np.exp(summ['nll']):.3f} acc {summ['acc']:.4f} "
          + " ".join(f"{k} {summ[k]['nll']:.4f}" for k in ("chat", "code", "wikitext") if k in summ) + f" ({summ['seconds']}s)", flush=True)

if __name__ == "__main__":
    main()