okami.mom/strata

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

Niko1221Merge branch 'f-139b-par' into f-139-relf5410ae2b

main
4.4 KiB89 linesraw
1#!/usr/bin/env python3
2"""Conversation parking test: a follow-up to conversation A must decode the same tokens whether A's state was still
3live (reference engine: A, then the follow-up) or came back from the parking cache (second engine: A, then B, which
4parks A, then the follow-up).  Greedy; run with --extra "--pcie-frac 0 --adapt-every 1000000" for exactness.
5
6  python3 tools/parking_test.py --exe engine/strata --config strata-<model>.json \
7      --extra "--layer-split 12,24,36 --conversation-cache-mib 8192 --conversation-cache-slots 4 --pcie-frac 0"
8"""
9import argparse, json, re, sys, time
10from pathlib import Path
11
12sys.path.insert(0, str(Path(__file__).resolve().parent))
13from batch_test import Engine, tokenizer  # noqa: E402
14
15DOC = ("The history of the printing press begins with movable type in East Asia and continues with Gutenberg's "
16       "press in Mainz around 1450, which spread across Europe within decades, lowered the cost of books, changed "
17       "how scholars, merchants and churches shared knowledge, and fed the Reformation and the scientific "
18       "revolution. ")
19
20
21def chat(user):
22    return f"<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
23
24
25def gen(eng, out, ids, n):
26    eng.send(f"GEN {n} " + ",".join(map(str, ids)))
27    got = []
28    for line in out:
29        if line.startswith("T "):
30            got.append(int(line.split()[1]))
31        elif line.startswith("DONE") or line.startswith("ERR"):
32            return got, line
33    raise SystemExit("the engine ended")
34
35
36def run(a, cfg, tok, with_b):
37    # STRATA_SNAPSHOT_VERIFY: the engine reads the restored draft ring back (on the GPU that holds it) after a restore
38    eng = Engine(a.exe, cfg, 0, {"STRATA_IQ_MT_MIN": "1", "STRATA_SNAPSHOT_VERIFY": "1"}, a.extra.split())
39    out = eng.lines()
40    pa = tok.encode(chat(DOC * a.repeat + "\nSummarize this text in five sentences."), parse_special=True)
41    ans, _ = gen(eng, out, pa, a.max_new)
42    if with_b:
43        pb = tok.encode(chat("Write a short poem about the sea, then explain its metaphors." * 20), parse_special=True)
44        gen(eng, out, pb, a.max_new)
45    end = tok.encode("<|im_end|>\n", parse_special=True)
46    follow = pa + ans + ([] if ans and ans[-1] in end else end) + \
47        tok.encode(chat("Now give three keywords for that text, with one sentence each.")[0:], parse_special=True)
48    t0 = time.time()
49    got, done = gen(eng, out, follow, a.max_new)
50    dt = time.time() - t0
51    if with_b:   # B again: A is parked a second time, from retained K/V (every stage's) - only its new tail copied
52        gen(eng, out, pb, 8)
53    eng.send("QUIT")
54    eng.p.wait(timeout=180)
55    log = open("/tmp/batch_test_engine.log").read()
56    restored = re.findall(r"restored \d+ tokens[^\n]*", log)
57    if with_b and "SNAPSHOT_VERIFY draft=" not in log:
58        print("no SNAPSHOT_VERIFY line: the draft ring was not read back", flush=True)
59    reparked = [int(x) for x in re.findall(r"parked \d+ tokens .*reused_kv_bytes=(\d+)", log)]
60    return len(pa), len(follow), got, done, dt, restored, reparked
61
62
63def main():
64    ap = argparse.ArgumentParser()
65    ap.add_argument("--exe", required=True)
66    ap.add_argument("--config", required=True)
67    ap.add_argument("--repeat", type=int, default=60, help="copies of the paragraph in conversation A")
68    ap.add_argument("--max-new", type=int, default=120)
69    ap.add_argument("--extra", default="")
70    a = ap.parse_args()
71    cfg = json.loads(Path(a.config).read_text())
72    tok = tokenizer(cfg["tokenizer"])
73    ref = run(a, cfg, tok, with_b=False)
74    park = run(a, cfg, tok, with_b=True)
75    for name, r in (("live (reference)", ref), ("parked (A, B, A)", park)):
76        f = r[3].split()
77        print(f"{name}: prompt A {r[0]} tokens, follow-up {r[1]} tokens, reused {f[8] if len(f) > 8 else '?'}, "
78              f"follow-up in {r[4]:.2f} s; restore lines: {r[5][-1:] or 'none'}")
79    same = ref[2] == park[2]
80    first = next((k for k in range(min(len(ref[2]), len(park[2]))) if ref[2][k] != park[2][k]), None)
81    print("follow-up tokens:", "IDENTICAL" if same else f"DIFFER at {first}", f"({len(ref[2])} / {len(park[2])})")
82    print("   ", repr(tok.decode(park[2])[:200]))
83    reused = park[6][-1] if park[6] else 0
84    print(f"second park of A: {reused} bytes of K/V reused (retained from its restore)")
85    return 0 if same and park[5] and reused > 0 else 1
86
87
88if __name__ == "__main__":
89    sys.exit(main())