okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
11.0 KiB226 linesraw
1"""Decoding streams while long cold prompts join: how smooth the streams stay, and what the joining prompt pays.
2
3Runs against a running `serve/server.py` (OpenAI API). N streams decode long greedy answers (thinking off); after a
4delay one or two long cold prompts join. Every streamed token's arrival is timed on the client. Reported per scenario:
5
6  joiner_ttft_s            the joining prompt's time to first token
7  worst_max_gap_s          the longest time any decoding stream received no token during the join window
8  mean_stalled_s           per stream, the sum of gaps above 0.5 s during the window (mean over the streams)
9  stream_tokens_during_join   tokens the decoding streams received from the first joiner's arrival to the last
10                           joiner's first token + 1 s
11  aggregate_tok_s          the streams' tokens / the run's wall time (throughput of the whole run)
12
13Two scenarios without decoding streams (#1504's test): `followup` reads a cold 45K prompt alone and sends a short
14prompt 1 s later (followup_ttft_s: how long the short one waits behind the read; long_ttft_s: what the read pays);
15`read_alone` is the same read without the follow-up (what the read costs by itself).
16
17The prompts are synthetic: the joiners are text from this repository's own files (src, include, serve, tools, docs), so
18they route to most experts the way real code and tool output do; a joiner never repeats an earlier prompt (the
19conversation cache would turn it into a warm read). `--determinism` instead sends fixed greedy prompts and prints the
20SHA-256 of each answer (to compare two builds' output tokens).
21
22  python tools/piped_read_join_bench.py --port 8080 --out join.json
23  python tools/piped_read_join_bench.py --port 8080 --scenarios two_joiners,followup --repeat 3
24  python tools/piped_read_join_bench.py --port 8080 --determinism
25"""
26import argparse
27import hashlib
28import http.client
29import json
30import statistics
31import threading
32import time
33from pathlib import Path
34
35ROOT = Path(__file__).resolve().parent.parent
36CODING = ["Write a Python function that parses an INI file into nested dicts, with tests. Explain each step.",
37          "Implement a thread-safe LRU cache in C++ with a short explanation of the design and its complexity.",
38          "Explain, with code, how to stream a large CSV file in Go and aggregate per-key statistics.",
39          "Write a TypeScript debounce and throttle pair with tests and explain where each one fits."]
40DETERMINISM = ["Count from 1 to 40, comma separated.", "List the planets of the solar system in order, one per line.",
41               "Write the first 12 Fibonacci numbers.", "Explain in three sentences what a hash map is.",
42               'Translate "good morning, how are you" into French, German and Spanish.',
43               "Write a haiku about compilers."]
44# name -> the joins (delay s, size in K tokens) beside decoding streams, or (size, follow-up delay s) with none decoding
45SCENARIOS = {"cold32k": [(6, 32)], "cold64k": [(6, 64)], "two_joiners": [(6, 64), (12, 32)],
46             "followup": (45, 1.0), "read_alone": (45, 0)}
47_FILES = []
48
49
50def corpus(chars, offset):
51    """About `chars` characters of this repository's own files, from the `offset`-th file on (at most 60,000 each)."""
52    if not _FILES:
53        for sub, pat in (("src", "*.cpp"), ("src", "*.cu"), ("include", "*.hpp"), ("serve", "*.py"), ("tools", "*.py"),
54                         ("docs", "*.md")):
55            _FILES.extend(sorted((ROOT / sub).rglob(pat)))
56    parts, n, i = [], 0, offset
57    while n < chars:
58        p = _FILES[i % len(_FILES)]
59        i += 1
60        text = p.read_text(encoding="utf-8", errors="replace")[:60000]
61        parts.append("=== %s ===\n%s\n" % (p.relative_to(ROOT).as_posix(), text))
62        n += len(parts[-1])
63    return "".join(parts)[:chars]
64
65
66def request(content, max_tokens, model):
67    """One streamed greedy chat request with thinking off."""
68    return json.dumps({"model": model, "messages": [{"role": "user", "content": content}], "temperature": 0,
69                       "max_tokens": max_tokens, "stream": True, "stream_options": {"include_usage": True},
70                       "chat_template_kwargs": {"enable_thinking": False}}).encode()
71
72
73def stream(port, raw, timeout=1800):
74    """-> (token arrival times, text, usage, the time the request was sent)"""
75    c = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout)
76    ts, text, usage = [], [], None
77    t0 = time.monotonic()
78    c.request("POST", "/v1/chat/completions", raw, {"Content-Type": "application/json", "Connection": "close"})
79    r = c.getresponse()
80    if r.status != 200:
81        raise RuntimeError("HTTP %d" % r.status)
82    while True:
83        line = r.readline(1 << 20)
84        if not line:
85            break
86        if not line.startswith(b"data:"):
87            continue
88        data = line[5:].strip()
89        if data == b"[DONE]":
90            break
91        item = json.loads(data)
92        if item.get("usage"):
93            usage = item["usage"]
94        for ch in item.get("choices") or []:
95            d = (ch.get("delta") or {}).get("content")
96            if d:
97                ts.append(time.monotonic())
98                text.append(d)
99    c.close()
100    return ts, "".join(text), usage or {}, t0
101
102
103def pct(v, p):
104    v = sorted(v)
105    return v[min(len(v) - 1, max(0, int(round(p / 100 * (len(v) - 1)))))] if v else 0
106
107
108def smooth(ts, lo, hi):
109    """One stream's arrivals in [lo, hi]: tokens, the longest and p99 gap, and the time in gaps above 0.5 s."""
110    inside = [t for t in ts if lo <= t <= hi]
111    gaps = [b - a for a, b in zip(ts, ts[1:]) if b >= lo and a <= hi]
112    return {"tokens": len(inside), "max_gap_s": round(max(gaps or [0]), 3), "p99_gap_s": round(pct(gaps, 99), 3),
113            "stalled_s": round(sum(g for g in gaps if g > 0.5), 3)}
114
115
116def scenario(port, model, name, n, joins, max_tokens, tag):
117    """`n` streams decode; each join (delay s, size in K tokens) then sends a cold prompt of this repository's text."""
118    events, joined = {}, {}
119
120    def decode(i):
121        content = "Stream %s-%s-%d. %s" % (tag, name, i, CODING[i % len(CODING)])
122        events[i] = stream(port, request(content, max_tokens, model))[0]
123
124    def join(k, delay, size):
125        time.sleep(delay)
126        text = corpus(int(size * 1024 * 3.3), 7 * size + k + 131 * len(name))
127        content = "Join %s-%s-%d.\n%s\nName the file that defines the class above in one line." % (tag, name, k, text)
128        ts, _, usage, t0 = stream(port, request(content, 64, model))
129        joined[k] = {"sent": t0, "first": ts[0] if ts else None, "usage": usage}
130
131    t0 = time.monotonic()
132    threads = [threading.Thread(target=decode, args=(i,)) for i in range(n)]
133    threads += [threading.Thread(target=join, args=(k, d, size)) for k, (d, size) in enumerate(joins)]
134    for t in threads:
135        t.start()
136    for t in threads:
137        t.join()
138    lo = min(v["sent"] for v in joined.values())
139    hi = max(v["first"] for v in joined.values()) + 1.0
140    per = [smooth(ts, lo, hi) for _, ts in sorted(events.items())]
141    ends = [ts[-1] for ts in events.values() if ts]
142    joins_in_order = [v for _, v in sorted(joined.items())]
143    return {"joiner_ttft_s": [round(v["first"] - v["sent"], 3) for v in joins_in_order],
144            "joiner_prompt_tokens": [v["usage"].get("prompt_tokens") for v in joins_in_order],
145            "joiner_cached_tokens": [(v["usage"].get("prompt_tokens_details") or {}).get("cached_tokens")
146                                     for v in joins_in_order],
147            "worst_max_gap_s": max(p["max_gap_s"] for p in per),
148            "mean_stalled_s": round(statistics.mean(p["stalled_s"] for p in per), 3),
149            "stream_tokens_during_join": sum(p["tokens"] for p in per),
150            "aggregate_tok_s": round(sum(len(t) for t in events.values()) / (max(ends) - t0), 1),
151            "streams": per}
152
153
154def alone(port, model, name, size, follow, tag):
155    """A cold prompt of `size` K tokens with nothing decoding; with `follow`, a short prompt `follow` s after it."""
156    got = {}
157
158    def long_read():
159        text = corpus(int(size * 1024 * 3.3), 11 * size + 131 * len(name))
160        content = "Read %s-%s.\n%s\nName the file that defines the class above in one line." % (tag, name, text)
161        ts, _, usage, t0 = stream(port, request(content, 64, model))
162        got["long"] = (t0, ts[0] if ts else None, usage)
163
164    def short():
165        time.sleep(follow)
166        content = "Follow-up %s-%s: what is 17 x 23? Reply with the number only." % (tag, name)
167        ts, _, usage, t0 = stream(port, request(content, 16, model))
168        got["short"] = (t0, ts[0] if ts else None, usage)
169
170    threads = [threading.Thread(target=long_read)] + ([threading.Thread(target=short)] if follow else [])
171    for t in threads:
172        t.start()
173    for t in threads:
174        t.join()
175    out = {"long_ttft_s": round(got["long"][1] - got["long"][0], 3),
176           "long_prompt_tokens": got["long"][2].get("prompt_tokens")}
177    if follow:
178        out["followup_ttft_s"] = round(got["short"][1] - got["short"][0], 3)
179        out["followup_prompt_tokens"] = got["short"][2].get("prompt_tokens")
180    return out
181
182
183def main():
184    ap = argparse.ArgumentParser()
185    ap.add_argument("--port", type=int, default=8080)
186    ap.add_argument("--model", default=None, help="default: the server's own model id")
187    ap.add_argument("--streams", type=int, default=4)
188    ap.add_argument("--max-tokens", type=int, default=2048)
189    ap.add_argument("--scenarios", default="cold32k,cold64k,two_joiners",
190                    help="comma-separated: " + ", ".join(SCENARIOS))
191    ap.add_argument("--repeat", type=int, default=1, help="runs of each scenario (each with its own cold prompts)")
192    ap.add_argument("--out")
193    ap.add_argument("--determinism", action="store_true")
194    a = ap.parse_args()
195    tag = time.strftime("%H%M%S")
196    if a.model is None:
197        c = http.client.HTTPConnection("127.0.0.1", a.port, timeout=30)
198        c.request("GET", "/v1/models")
199        a.model = json.loads(c.getresponse().read())["data"][0]["id"]
200        c.close()
201    if a.determinism:
202        rows = []
203        for p in DETERMINISM:
204            _, text, usage, _ = stream(a.port, request(p, 128, a.model))
205            rows.append({"prompt_sha256": hashlib.sha256(p.encode()).hexdigest()[:12],
206                         "answer_sha256": hashlib.sha256(text.encode()).hexdigest(),
207                         "tokens": usage.get("completion_tokens")})
208        print(json.dumps(rows, indent=1))
209        return
210    out = {}
211    for rep in range(a.repeat):
212        for name in a.scenarios.split(","):
213            spec, run_tag = SCENARIOS[name], "%s.%d" % (tag, rep)
214            key = name if a.repeat == 1 else "%s#%d" % (name, rep + 1)
215            if isinstance(spec, tuple):
216                out[key] = alone(a.port, a.model, name, spec[0], spec[1], run_tag)
217            else:
218                out[key] = scenario(a.port, a.model, name, a.streams, spec, a.max_tokens, run_tag)
219            print(json.dumps({"scenario": key, **{k: v for k, v in out[key].items() if k != "streams"}}), flush=True)
220            time.sleep(3)
221    if a.out:
222        Path(a.out).write_text(json.dumps(out, indent=1))
223
224
225if __name__ == "__main__":
226    main()