okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge df2-metal (a9df88afc): window_rule.hpp and its test (add/add) and generate.cpp (8 hunks) conflicted; mainline draft_fallback/draft_on/lookup_default kept, Metal's defer_df2 call taken3dfb046bf

main
4.6 KiB108 linesraw
1"""Checks the Metal engine's DFlash2 drafter against the torch port (dflash2_ref.py) on a real round.
2
3    python check_metal_dump.py <dump.bin> <drafter.safetensors> <drafter_config.json>
4
5dump.bin is written by the Metal engine with STRATA_DF2_DUMP=<file> [STRATA_DF2_DUMP_ROUND=n] (metal/src/engine/dflash2.inc): every context row the
6drafter was given (positions 0 .. s-1: a prompt short enough that the whole context was fed), the anchor and mask embeddings, and the engine's answer
7of that round (the 8 final normalized rows, the selector's hidden projection, the top-16 per row, the picked tokens and their probabilities, the
8draft head's logits).  The checks:
9  1. the 8 final rows against the torch port run on the same context (weights fp32 against the engine's Q8_0: cosine similarity, not equality),
10  2. the engine's top-16 per row against a sort of its own logits,
11  3. the selector's walk (torch, on the engine's own rows and candidates) against the engine's picks.
12"""
13import struct
14import sys
15from pathlib import Path
16
17import numpy as np
18import torch
19
20sys.path.insert(0, str(Path(__file__).parent))
21import dflash2_ref as R
22
23
24class Embed:
25    def __init__(self, rows):
26        self.rows = rows
27
28    def __getitem__(self, ids):
29        return torch.stack([self.rows[int(i)] for i in ids])
30
31
32def main():
33    dump, st, cfgp = sys.argv[1:4]
34    raw = open(dump, "rb").read()
35    magic, ver, s, anchor, nd, nt, H, mask = struct.unpack_from("<8i", raw, 0)
36    assert magic == 0x32465344, "not a DF2 dump"
37    off = 32
38    def take(n, dt=np.float32):
39        nonlocal off
40        a = np.frombuffer(raw, dt, n, off)
41        off += a.nbytes
42        return a
43    taps = take(s * nt * H).reshape(s, nt * H)
44    emb_a, emb_m = take(H), take(H)
45    fn = take(8 * H).reshape(8, H)
46    hsel = take(7 * 256).reshape(7, 256)
47    topval = take(7 * 16).reshape(7, 16)
48    toptok = take(7 * 16, np.int32).reshape(7, 16)
49    out = take(32, np.int32)
50    out_prob = np.frombuffer(out.tobytes(), np.float32)[16:23]
51    out_tok = out[:7]
52    rest = len(raw) - off
53    has_map = rest > 7 * nd * 4
54    vmap = take(nd, np.int32) if has_map else None
55    logits = take(7 * nd).reshape(7, nd)
56    print("dump: %d context rows, anchor %d, %d-token head%s" % (s, anchor, nd, " (mapped)" if has_map else ""))
57
58    d = R.Drafter(st, cfgp, Embed({anchor: torch.from_numpy(emb_a.copy()), mask: torch.from_numpy(emb_m.copy())}), torch.randn(64, H), threads=6)
59    d.set_context(torch.from_numpy(taps.copy()))
60    d.draft(s, anchor, 8)
61    ref = d.last_all.numpy()
62    bad = 0
63    print("1. final rows against the torch port (fp32 weights):")
64    worst = 1.0
65    for r in range(8):
66        a, b = fn[r].astype(np.float64), ref[r].astype(np.float64)
67        cs = float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30))
68        worst = min(worst, cs)
69        print("   row %d: cos %.5f  norm ratio %.4f" % (r, cs, np.linalg.norm(a) / (np.linalg.norm(b) + 1e-30)))
70    if worst < 0.98:
71        print("   FAIL: a row's cosine similarity %.4f is below 0.98" % worst)
72        bad += 1
73
74    print("2. top-16 of the engine's logits:")
75    for i in range(7):
76        order = np.lexsort((np.arange(nd), -logits[i]))[:16]   # value descending, ties to the lower column
77        want = (vmap[order] if has_map else order).astype(np.int32)
78        if not (np.array_equal(want, toptok[i]) and np.allclose(logits[i][order], topval[i])):
79            print("   FAIL row %d: engine %s, sort %s" % (i, toptok[i].tolist(), want.tolist()))
80            bad += 1
81    if not bad:
82        print("   all 7 rows equal")
83
84    print("3. the selector's walk on the engine's rows and candidates:")
85    w = d.w
86    hp = torch.from_numpy(fn[1:].copy()) @ w["candidate_selector.hidden_projection.weight"].T
87    A, B = w["candidate_selector.predecessor_codebook"], w["candidate_selector.successor_codebook"]
88    pred = anchor
89    same = 0
90    for i in range(7):
91        cand = torch.from_numpy(toptok[i].astype(np.int64))
92        sc = torch.from_numpy(topval[i].copy()) + (B[cand].float() @ (A[pred].float() * hp[i]))
93        j = int(torch.argmax(sc))
94        p = float(torch.softmax(sc, dim=-1)[j])
95        pick = int(cand[j])
96        ok = pick == int(out_tok[i]) and abs(p - float(out_prob[i])) < 0.02
97        same += ok
98        print("   %d: engine %d (p %.3f)  torch %d (p %.3f)  %s" % (i, out_tok[i], out_prob[i], pick, p, "ok" if ok else "DIFF"))
99        pred = int(out_tok[i])
100    if same < 7:
101        bad += 1
102    print("hsel against torch: max abs diff %.4f" % float(np.abs(hsel - hp.numpy()).max()))
103    print("check_metal_dump: %s" % ("FAIL" if bad else "ok"))
104    return 1 if bad else 0
105
106
107if __name__ == "__main__":
108    sys.exit(main())