okami.mom/strata

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

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

main
3.6 KiB70 linesraw
1"""Offline DFlash2 acceptance on OUR quantized target: walks each prompt's dumped sequence the way the speculative loop would
2(anchor, draft block, accept the leading matches of the drafted path against the engine's own greedy tokens, move on)."""
3import json, sys, time
4from pathlib import Path
5import numpy as np
6import torch
7sys.path.insert(0, r"C:\dflash2-work")
8import dflash2_ref as R
9
10W = Path(r"C:\dflash2-work")
11names = sys.argv[1].split(",")
12blocks = [int(x) for x in sys.argv[2].split(",")] if len(sys.argv) > 2 else [4, 8]
13threads = int(sys.argv[3]) if len(sys.argv) > 3 else 6
14
15t0 = time.time()
16embed = R.load_dequant(str(W / "embd_iq4xs.bin"), 248320, 2560, R.gguf.GGMLQuantizationType.IQ4_XS)
17head = R.load_dequant(str(W / "head_q6k.bin"), 248320, 2560, R.gguf.GGMLQuantizationType.Q6_K)
18print("dequantized embed/head in %.0f s" % (time.time() - t0), flush=True)
19d = R.Drafter(str(W / "drafter.safetensors"), str(W / "drafter_config.json"), embed, head, threads=threads)
20res_path = W / "eval_results.json"
21results = json.load(open(res_path)) if res_path.exists() else {}
22
23for name in names:
24    seqj = json.load(open(W / "p" / ("%s.seq.json" % name)))
25    prompt, out = seqj["prompt"], seqj["out"]
26    seq = prompt + out
27    layers, pos, tok, taps = R.read_taps(str(W / "taps" / ("%s.bin" % name)))
28    keep = pos < len(seq)             # the tail of the last window is padding (zeros) past the sequence
29    pos, tok, taps = pos[keep], tok[keep], taps[keep]
30    n = int(pos.max()) + 1
31    feats = np.zeros((n, taps.shape[1]), np.float32)
32    seen = np.zeros(n, bool)
33    for i in range(len(pos)):          # the last record of a position wins
34        feats[pos[i]] = taps[i]
35        seen[pos[i]] = True
36        assert tok[i] == seq[pos[i]], ("token mismatch at", pos[i], tok[i], seq[pos[i]])
37    if not seen[0] and seen[1]:        # position 0 goes through the batched prefill (no tap): the next row stands in
38        feats[0] = feats[1]
39        seen[0] = True
40    assert seen.all(), "positions missing: %s" % np.where(~seen)[0][:5]
41    d.set_context(torch.from_numpy(feats))
42    print("%s: prompt %d, generated %d, tap records %d, layers %s" % (name, len(prompt), len(out), len(pos), layers), flush=True)
43    results.setdefault(name, {})
44    for b in blocks:
45        s = len(prompt)                # the first generated token is the first anchor, as after a prefill
46        cyc, cond_ok, cond_n = [], np.zeros(b - 1), np.zeros(b - 1)
47        top1_ok = np.zeros(b - 1)
48        t1 = time.time()
49        with torch.no_grad():
50            while s + b <= len(seq) - 0 and s < n:
51                path, top1 = d.draft(s, seq[s], b)
52                truth = seq[s + 1:s + b]
53                a = 0
54                while a < b - 1 and path[a] == truth[a]:
55                    a += 1
56                for i in range(b - 1):                  # conditional on all earlier correct
57                    if i <= a:
58                        cond_n[i] += 1
59                        cond_ok[i] += (i < a)
60                    if i <= a and top1[i] == truth[i]:
61                        top1_ok[i] += 1
62                cyc.append(a + 1)
63                s += a + 1
64        tau = float(np.mean(cyc))
65        results[name]["b%d" % b] = {"anchors": len(cyc), "tokens_per_round": tau,
66                                    "cond_accept": (cond_ok / np.maximum(cond_n, 1)).round(3).tolist(),
67                                    "hist": np.bincount(cyc, minlength=b + 1).tolist()}
68        print("  block %d: %d rounds, %.3f tokens per round, cond %s  (%.0f s)" %
69              (b, len(cyc), tau, (cond_ok / np.maximum(cond_n, 1)).round(2).tolist(), time.time() - t1), flush=True)
70    json.dump(results, open(res_path, "w"), indent=1)