okami.mom/strata

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

Niko1221Merge branch 'f-1402-r' into f-1402d19c07650

main
7.1 KiB144 linesraw
1"""A scripted research run against a running Strata server: one long document, then many different questions.
2
3Reads the document once, then asks each question and reports, per question, the time to the first streamed token and
4the whole request, and the run's total.  Greedy (temperature 0), so two runs of the same file give the same answers and
5a change in how the server keeps the document (the shared prefix below) can be compared answer by answer.
6
7    python tools/research_run.py --url http://127.0.0.1:8080 --doc paper.txt --questions questions.txt
8    python tools/research_run.py --doc paper.txt --questions q.txt --prefix off --json base.json
9    python tools/research_run.py --doc paper.txt --questions q.txt --prefix on  --json fork.json
10    python tools/research_run.py --compare base.json fork.json
11
12--layout split  (the default): the document is the first message, the question the second.
13--layout joined: one message, "document + question" (a client that cannot split them).
14--prefix on: the request carries "strata_prefix" naming the document as the shared prefix (docs/DETAILS.md): the
15server reads it once and every question starts from it.  off: the field is left out.
16--parallel N: N questions at a time (the server needs "parallel": N for them to run together).
17"""
18from __future__ import annotations
19
20import argparse
21import json
22import statistics
23import sys
24import threading
25import time
26import urllib.request
27from pathlib import Path
28
29
30def request_body(doc: str, question: str, layout: str, prefix: bool, max_tokens: int, model: str | None) -> dict:
31    if layout == "joined":
32        body = {"messages": [{"role": "user", "content": doc + "\n\nQuestion: " + question + "\nAnswer:"}]}
33        if prefix:
34            body["strata_prefix"] = {"message": 0, "chars": len(doc) + 2}
35    else:
36        body = {"messages": [{"role": "user", "content": doc}, {"role": "user", "content": question}]}
37        if prefix:
38            body["strata_prefix"] = {"messages": 1}
39    body.update(temperature=0, max_tokens=max_tokens, stream=True)
40    if model:
41        body["model"] = model
42    return body
43
44
45def ask(url: str, body: dict, headers: dict, timeout: float) -> dict:
46    t0 = time.time()
47    req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers=headers)
48    first, parts = None, []
49    with urllib.request.urlopen(req, timeout=timeout) as r:
50        for raw in r:
51            line = raw.decode("utf-8", "replace").strip()
52            if not line.startswith("data:") or line.endswith("[DONE]"):
53                continue
54            event = json.loads(line[5:])
55            for choice in event.get("choices", []):
56                delta = choice.get("delta", {})
57                piece = (delta.get("reasoning_content") or "") + (delta.get("content") or "")
58                if piece and first is None:
59                    first = time.time() - t0
60                parts.append(piece)
61    return {"ttft_s": round(first or 0.0, 3), "wall_s": round(time.time() - t0, 2), "text": "".join(parts)}
62
63
64def run(args) -> dict:
65    doc = Path(args.doc).read_text(encoding="utf-8", errors="replace")
66    if args.limit_chars:
67        doc = doc[:args.limit_chars]
68    questions = [x.strip() for x in Path(args.questions).read_text(encoding="utf-8").splitlines() if x.strip()]
69    questions = questions[:args.n] if args.n else questions
70    headers = {"Content-Type": "application/json"}
71    if args.api_key:
72        headers["Authorization"] = "Bearer " + args.api_key
73    rows: list[dict | None] = [None] * len(questions)
74    started = time.time()
75    for k in range(0, len(questions), max(1, args.parallel)):
76        group = list(range(k, min(k + max(1, args.parallel), len(questions))))
77
78        def one(i):
79            try:
80                rows[i] = {"q": i, **ask(args.url, request_body(doc, questions[i], args.layout, args.prefix == "on",
81                                                                  args.max_tokens, args.model), headers, args.timeout)}
82            except Exception as e:  # noqa: BLE001 - a failed question is reported, the run goes on
83                rows[i] = {"q": i, "error": repr(e)}
84        threads = [threading.Thread(target=one, args=(i,)) for i in group]
85        [t.start() for t in threads]
86        [t.join() for t in threads]
87        for i in group:
88            r = rows[i]
89            print(f"q{i:02d}  first token {r.get('ttft_s', '-')} s  total {r.get('wall_s', '-')} s  "
90                  f"{r.get('error') or repr(r['text'][:60])}", flush=True)
91    out = {"url": args.url, "layout": args.layout, "prefix": args.prefix, "doc_chars": len(doc), "questions": rows,
92           "total_s": round(time.time() - started, 1)}
93    later = [r["ttft_s"] for r in rows[1:] if r and "ttft_s" in r]
94    if later:
95        out["first_token_median_after_first_s"] = round(statistics.median(later), 3)
96    print(f"total {out['total_s']} s" + (f", median first token after the first question {out['first_token_median_after_first_s']} s"
97                                         if later else ""), flush=True)
98    return out
99
100
101def compare(a_path: str, b_path: str) -> int:
102    a, b = (json.loads(Path(p).read_text(encoding="utf-8")) for p in (a_path, b_path))
103    same = diff = 0
104    for x, y in zip(a["questions"], b["questions"]):
105        if "text" in x and "text" in y:
106            if x["text"] == y["text"]:
107                same += 1
108            else:
109                diff += 1
110                print(f"q{x['q']:02d}: the answers differ")
111    print(f"{same} answers identical, {diff} differ; total {a['total_s']} s -> {b['total_s']} s; median first token "
112          f"{a.get('first_token_median_after_first_s')} s -> {b.get('first_token_median_after_first_s')} s")
113    return 1 if diff else 0
114
115
116def main(argv=None) -> int:
117    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
118    ap.add_argument("--url", default="http://127.0.0.1:8080")
119    ap.add_argument("--api-key", default="")
120    ap.add_argument("--model", default=None)
121    ap.add_argument("--doc")
122    ap.add_argument("--questions", help="a text file, one question per line")
123    ap.add_argument("--n", type=int, default=0, help="only the first N questions")
124    ap.add_argument("--layout", choices=("split", "joined"), default="split")
125    ap.add_argument("--prefix", choices=("on", "off"), default="on")
126    ap.add_argument("--parallel", type=int, default=1)
127    ap.add_argument("--max-tokens", type=int, default=128)
128    ap.add_argument("--limit-chars", type=int, default=0, help="use only the first N characters of the document")
129    ap.add_argument("--timeout", type=float, default=7200.0)
130    ap.add_argument("--json", help="write the per-question results here")
131    ap.add_argument("--compare", nargs=2, metavar=("A.json", "B.json"), help="compare two saved runs' answers and times")
132    args = ap.parse_args(argv)
133    if args.compare:
134        return compare(*args.compare)
135    if not args.doc or not args.questions:
136        ap.error("--doc and --questions are needed")
137    out = run(args)
138    if args.json:
139        Path(args.json).write_text(json.dumps(out, indent=1), encoding="utf-8")
140    return 1 if any("error" in r for r in out["questions"]) else 0
141
142
143if __name__ == "__main__":
144    sys.exit(main())