okami.mom/strata

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

Niko1221Gate check: a Qwen serve engine must answer requests that make prompt lookup propose long windows (the Metal 12-row refusal went unseen because no gate request repeated text)2fb096b93

main
5.3 KiB122 linesraw
1#!/usr/bin/env python3
2"""Gate check: a Qwen serve engine answers a request that makes prompt lookup propose long windows.
3
4The #4040 default (--lookup-max-t 12) builds verify windows of up to 12 rows when the build holds 8: on Metal that was refused
5with "metal window: window size out of range" at the first request that repeated text, and no gate request repeated any.  This
6starts the engine as the Terminal would (serve, the build's defaults - no --lookup-max-t), sends a chat that asks for a text to be
7repeated three times, twice, and fails on an ERR line or on a request that did not end with DONE.  With --need-drafts it also
8requires that drafts were offered, i.e. that lookup windows really ran.
9
10  check_lookup_window_serve.py --exe build/strata --pack-tokenizer PACK/tokenizer -- <engine args without --serve>
11Exit 0 = pass, 1 = fail.
12"""
13import argparse
14import json
15import queue
16import subprocess
17import sys
18import threading
19import time
20from pathlib import Path
21
22TEXT = ("The quick brown fox jumps over the lazy dog near the quiet river bank, while the old farmer counts seventeen sheep, "
23        "nine goats and four noisy geese before supper. The quick brown fox jumps over the lazy dog near the quiet river bank.")
24PROMPT = ("<|im_start|>user\nRepeat the following text exactly, three times in a row, with no other words:\n\n" + TEXT +
25          "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n")
26
27
28def prompt_ids(tokenizer_dir: Path) -> list:
29    sys.path.insert(0, str(Path(__file__).resolve().parent))
30    import strata_tokenizer as ST
31    vocab = json.loads((tokenizer_dir / "vocab.json").read_text(encoding="utf-8"))
32    tokens = [None] * len(vocab)
33    for t, i in vocab.items():
34        tokens[i] = t
35    merges = (tokenizer_dir / "merges.txt").read_text(encoding="utf-8").split("\n")
36    types = json.loads((tokenizer_dir / "token_type.json").read_text())
37    try:
38        tcfg = json.loads((tokenizer_dir / "tokenizer.json").read_text(encoding="utf-8"))
39    except (OSError, ValueError):
40        tcfg = {}
41    tok = ST.Tokenizer(tokens, merges, types, tcfg.get("pre") or "qwen35", tcfg.get("special_ids") or None)
42    return list(tok.encode(PROMPT, parse_special=True))
43
44
45def check(exe, engine_args, ids, max_new=96, start_timeout=900, request_timeout=1200, need_drafts=False, env=None, cwd=None):
46    """Returns (ok, lines): one summary line per request (or the reason it failed)."""
47    p = subprocess.Popen([exe, "--serve", *engine_args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
48                         text=True, env=env, cwd=cwd)
49    q = queue.Queue()
50
51    def pump():
52        for line in p.stdout:
53            q.put(line.rstrip("\n"))
54        q.put(None)
55
56    threading.Thread(target=pump, daemon=True).start()
57
58    def until(prefixes, timeout):
59        end = time.monotonic() + timeout
60        got = []
61        while time.monotonic() < end:
62            try:
63                line = q.get(timeout=1)
64            except queue.Empty:
65                continue
66            if line is None:
67                got.append("<engine exited>")
68                return got
69            got.append(line)
70            if line.startswith(prefixes):
71                return got
72        got.append("<timeout>")
73        return got
74
75    lines, ok = [], True
76    try:
77        r = until(("READY",), start_timeout)
78        if not r[-1].startswith("READY"):
79            return False, ["engine did not start: " + " | ".join(r[-3:])]
80        for n in (1, 2):
81            p.stdin.write(f"GEN {max_new} " + ",".join(map(str, ids)) + "\n")
82            p.stdin.flush()
83            out = until(("DONE", "ERR"), request_timeout)
84            last = out[-1]
85            toks = sum(1 for x in out if x.startswith("T "))
86            f = last.split()
87            offered = int(f[7]) if last.startswith("DONE") and len(f) > 7 and f[7].isdigit() else 0
88            good = last.startswith("DONE") and (offered > 0 or not need_drafts)
89            ok = ok and good
90            lines.append(f"request {n}: {last[:160]} | {toks} tokens | drafts offered {offered}" + ("" if good else "  <-- FAIL"))
91            if not good:
92                break
93        return ok, lines
94    finally:
95        try:
96            p.stdin.write("QUIT\n")
97            p.stdin.flush()
98        except (OSError, ValueError):
99            pass
100        time.sleep(1)
101        if p.poll() is None:
102            p.terminate()
103
104
105def main(argv=None):
106    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
107    ap.add_argument("--exe", required=True)
108    ap.add_argument("--pack-tokenizer", required=True, help="the pack's tokenizer folder (vocab.json, merges.txt, token_type.json)")
109    ap.add_argument("--max-new", type=int, default=96)
110    ap.add_argument("--need-drafts", action="store_true", help="also fail if no draft was offered (lookup windows did not run)")
111    ap.add_argument("--cwd")
112    ap.add_argument("engine_args", nargs=argparse.REMAINDER)
113    a = ap.parse_args(argv)
114    args = a.engine_args[1:] if a.engine_args[:1] == ["--"] else a.engine_args
115    ok, lines = check(a.exe, args, prompt_ids(Path(a.pack_tokenizer)), a.max_new, need_drafts=a.need_drafts, cwd=a.cwd)
116    print("\n".join(lines))
117    print("LOOKUP-WINDOW SERVE CHECK:", "PASS" if ok else "FAIL")
118    return 0 if ok else 1
119
120
121if __name__ == "__main__":
122    sys.exit(main())