okami.mom/strata

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

Niko1221Merge f-023-int into f-023-guifcb0c2d0e

main
3.7 KiB88 linesraw
1"""Builds the input of src/core/dflash2_parity.cpp and the torch reference answer.
2
3    python mk_parity_case.py <drafter.safetensors> <drafter_config.json> <out.bin> [n_ctx=2300] [vp=20000] [seed=1]
4
5The case: n_ctx random tap rows (positions 0 .. n_ctx-1), an anchor token at position n_ctx, a head of `vp` random rows (Q8_0, the draft vocabulary
6subset path: dvocab maps a row to a token id) and the target embedding rows of the anchor and the mask token.  The torch port (dflash2_ref.py,
7equal to z-lab's module) gives the reference: the final normalized block rows, the walk's tokens and their probabilities.  A context longer than the
82048-token window exercises the ring wrap and the window mask.
9"""
10import struct
11import sys
12from pathlib import Path
13
14import numpy as np
15import torch
16
17sys.path.insert(0, str(Path(__file__).parent))
18import dflash2_ref as R
19
20
21class Embed:
22    def __init__(self, rows):
23        self.rows = rows
24
25    def __getitem__(self, ids):
26        return torch.stack([self.rows[int(i)] for i in ids])
27
28
29def quant_q8_0(w):
30    rows, cols = w.shape
31    b = w.reshape(rows, cols // 32, 32)
32    amax = np.abs(b).max(axis=-1)
33    d = amax / 127.0
34    inv = np.where(d != 0, 1.0 / np.where(d == 0, 1, d), 0.0)
35    q = np.rint(b * inv[..., None]).astype(np.int8)
36    out = np.empty((rows, cols // 32, 34), np.uint8)
37    out[..., :2] = d.astype(np.float16).view(np.uint8).reshape(rows, cols // 32, 2)
38    out[..., 2:] = q.view(np.uint8)
39    return out.tobytes(), (q.astype(np.float32) * d.astype(np.float16).astype(np.float32)[..., None]).reshape(rows, cols)
40
41
42def main():
43    st, cfgp, out = sys.argv[1:4]
44    n_ctx = int(sys.argv[4]) if len(sys.argv) > 4 else 2300
45    vp = int(sys.argv[5]) if len(sys.argv) > 5 else 20000
46    seed = int(sys.argv[6]) if len(sys.argv) > 6 else 1
47    rng = np.random.default_rng(seed)
48    H, V = 2560, 248320
49    mask_id = 248077
50    anchor = int(rng.integers(1000, 200000))
51    taps = (rng.standard_normal((n_ctx, 5 * H)) * 1.0).astype(np.float32)
52    emb = (rng.standard_normal((2, H)) * 1.0).astype(np.float32)
53    dvocab = np.sort(rng.choice(V, size=vp, replace=False)).astype(np.int32)
54    head = (rng.standard_normal((vp, H)) * 0.05).astype(np.float32)
55    head_blob, head_dq = quant_q8_0(head)
56    embed = Embed({anchor: torch.from_numpy(emb[0]), mask_id: torch.from_numpy(emb[1])})
57    d = R.Drafter(st, cfgp, embed, torch.from_numpy(head_dq), threads=6)
58    d.set_context(torch.from_numpy(taps))
59    path, _ = d.draft(n_ctx, anchor, 8)           # runs the forward; the tail below redoes the selector with the token map
60    fn = d.last_all.clone()                       # [8][H]
61    out_rows = fn[1:]
62    logits = out_rows @ torch.from_numpy(head_dq).T
63    unary, idx = torch.topk(logits, 16, dim=-1)
64    cand = torch.from_numpy(dvocab.astype(np.int64))[idx]
65    hp = out_rows @ d.w["candidate_selector.hidden_projection.weight"].T
66    A, B = d.w["candidate_selector.predecessor_codebook"], d.w["candidate_selector.successor_codebook"]
67    pred = anchor
68    toks, probs = [], []
69    for i in range(7):
70        sc = unary[i] + (B[cand[i]].float() @ (A[pred].float() * hp[i]))
71        j = int(torch.argmax(sc))
72        probs.append(float(torch.softmax(sc, dim=-1)[j]))
73        pred = int(cand[i][j])
74        toks.append(pred)
75    with open(out, "wb") as f:
76        f.write(struct.pack("<4i", n_ctx, anchor, vp, 0))
77        f.write(taps.tobytes())
78        f.write(emb.tobytes())
79        f.write(dvocab.tobytes())
80        f.write(head_blob)
81        f.write(struct.pack("<7i", *toks))
82        f.write(struct.pack("<7f", *probs))
83        f.write(fn.numpy().astype(np.float32).tobytes())
84    print("case written:", out, "n_ctx", n_ctx, "anchor", anchor, "tokens", toks, "probs", [round(p, 3) for p in probs])
85
86
87if __name__ == "__main__":
88    main()