okami.mom/strata

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

Niko1221Int3 merge f-0291-bw-df2serve (eeb21d0e4); generate.cpp: draft_df2 and draft_long both keptea9a58d8a

main
5.3 KiB124 linesraw
1"""Serve-API test of the DFlash2 drafter: runs `strata --serve` on one arm and a scenario of greedy requests, writes the tokens and the engine's DONE figures.
2
3    python serve_test.py --exe ENGINE --arm df2 --scenario scenario.json --out out_df2.json --log arm.log -- <the engine arguments, as in the run config>
4
5The wire is the engine's own: stdin `GEN <max_new> <id>,<id>,...`, stdout `T <id>` ... `DONE <n> <prompt> <prompt_ms> <decode_ms> <finish> <accepted> <offered> <resume> ...`
6(serve/server.py is the Python client).  A scenario is {"requests": [{"name", "ids": [...]} | {"name", "after": "<name>", "follow": [...]}, ...], "max_new": N}:
7a request with `after` continues that request's conversation (its prompt + its output + `follow`), which is what a chat client sends for the next turn.
8Pure standard library: it runs on any box that has the engine.
9
10compare mode:  python serve_test.py --compare nd.json mtp.json df2.json
11prints, per request, the first token where the arm differs from the no-draft arm (the engine's windows are not bitwise equal to one-token decode at near-ties,
12for the MTP as well; the DFlash2 arm must not be worse than the MTP arm), the drafts accepted / offered, and the figures the park test needs.
13"""
14import json
15import subprocess
16import sys
17import threading
18import time
19
20
21def run(exe, args, scenario, log_path, ready_timeout=900, req_timeout=600):
22    log = open(log_path, "ab")
23    proc = subprocess.Popen([exe, "--serve", *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log, text=True, bufsize=1)
24    lines = []
25    cv = threading.Condition()
26
27    def pump():
28        for ln in proc.stdout:
29            with cv:
30                lines.append(ln.rstrip("\n"))
31                cv.notify_all()
32        with cv:
33            lines.append(None)
34            cv.notify_all()
35
36    threading.Thread(target=pump, daemon=True).start()
37    pos = 0
38
39    def next_line(timeout):
40        nonlocal pos
41        end = time.time() + timeout
42        with cv:
43            while pos >= len(lines):
44                left = end - time.time()
45                if left <= 0:
46                    raise TimeoutError("no line from the engine")
47                cv.wait(left)
48            ln = lines[pos]
49            pos += 1
50            return ln
51
52    while True:
53        ln = next_line(ready_timeout)
54        if ln is None:
55            raise RuntimeError("the engine ended before READY")
56        if ln.startswith("READY"):
57            break
58    done = {}
59    results = []
60    for req in scenario["requests"]:
61        if "after" in req:
62            prev = done[req["after"]]
63            ids = prev["ids"] + prev["out"] + req.get("follow", [])
64        else:
65            ids = list(req["ids"])
66        proc.stdin.write("GEN %d %s\n" % (req.get("max_new", scenario.get("max_new", 100)), ",".join(str(int(t)) for t in ids)))
67        proc.stdin.flush()
68        out, stats, resume = [], {}, None
69        while True:
70            ln = next_line(req_timeout)
71            if ln is None:
72                raise RuntimeError("the engine ended during %s" % req["name"])
73            if ln.startswith("T "):
74                out.append(int(ln.split()[1]))
75            elif ln.startswith("RESUME "):
76                resume = int(ln.split()[1])
77            elif ln.startswith("ERR"):
78                raise RuntimeError("engine: " + ln)
79            elif ln.startswith("DONE"):
80                f = ln.split()
81                stats = {"produced": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]), "decode_ms": float(f[4]), "finish": f[5],
82                         "accepted": int(f[6]), "offered": int(f[7]), "resume": int(f[8])}
83                break
84        done[req["name"]] = {"ids": ids, "out": out}
85        results.append({"name": req["name"], "prompt_len": len(ids), "out": out, "resume": resume, **stats})
86        print("%-14s prompt %5d resume %5s tokens %3d drafts %s/%s  %.1f tok/s" % (
87            req["name"], len(ids), resume, len(out), stats.get("accepted"), stats.get("offered"),
88            1000.0 * len(out) / max(1e-9, stats.get("decode_ms", 0.0))), flush=True)
89    try:
90        proc.stdin.close()
91        proc.wait(60)
92    except Exception:
93        proc.kill()
94    return results
95
96
97def compare(nd_path, mtp_path, df2_path):
98    nd, mtp, df2 = (json.load(open(p)) for p in (nd_path, mtp_path, df2_path))
99    worst = 0
100    print("%-14s %7s %9s %9s %12s %12s" % ("request", "tokens", "mtp diff@", "df2 diff@", "mtp drafts", "df2 drafts"))
101    for a, b, c in zip(nd["results"], mtp["results"], df2["results"]):
102        def first(x, y):
103            n = min(len(x), len(y))
104            return next((i for i in range(n) if x[i] != y[i]), None)
105        fm, fd = first(a["out"], b["out"]), first(a["out"], c["out"])
106        print("%-14s %7d %9s %9s %12s %12s" % (a["name"], len(a["out"]), fm, fd, "%d/%d" % (b["accepted"], b["offered"]), "%d/%d" % (c["accepted"], c["offered"])))
107    return worst
108
109
110if __name__ == "__main__":
111    argv = sys.argv[1:]
112    if argv and argv[0] == "--compare":
113        compare(*argv[1:4])
114        sys.exit(0)
115    opts = {}
116    i = 0
117    while i < len(argv) and argv[i] != "--":
118        opts[argv[i].lstrip("-")] = argv[i + 1]
119        i += 2
120    engine_args = argv[i + 1:]
121    scenario = json.load(open(opts["scenario"]))
122    res = run(opts["exe"], engine_args, scenario, opts.get("log", "serve_test.log"))
123    json.dump({"arm": opts.get("arm"), "results": res}, open(opts["out"], "w"))
124    print("SERVE_TEST_DONE")