okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
28.9 KiB544 linesraw
1#!/usr/bin/env python3
2"""Shared load harness for the parallelism program (research tool, standard library only).
3
4Wraps the OpenAI-compatible server the way tools/serve_load.py does, and adds what an SLO-capacity harness needs:
5
6  * closed-loop concurrency staircases (fixed work, shared wall window incl. the final drain),
7  * open-loop seeded Poisson arrivals (offered rate independent of completions; late/unfinished requests are failures),
8  * token counts from the server's `usage` (completion_tokens / prompt_tokens), NEVER from SSE chunks; a request with
9    no usage is marked `tokens_source: "sse"` and the run is flagged invalid,
10  * per request: TTFT, TPOT, max gap between content chunks (a chunk can hold several tokens when the engine flushes
11    speculative windows, so "gap" is a chunk gap), client scheduling lag, finish reason, cached prompt tokens,
12  * aggregate tok/s = total committed completion tokens / ONE shared wall-clock window (first submit to last completion),
13  * the workloads W1 solo, W2 short concurrent, W4 long joiner, W6 shared-prefix cohorts,
14  * one JSON ledger per run (args, server status before/after, per-request records, per-level blocks).
15
16    python3 tools/par_load.py http://127.0.0.1:8080 --workload w2 --conc 1,2,4,8 --rounds 3 --out run.json
17    python3 tools/par_load.py URL --workload w1 --prompt-tokens 512 --max-tokens 512 --rounds 3 --out w1.json
18    python3 tools/par_load.py URL --workload w4 --conc 4 --joiner-tokens 32768 --out w4.json
19    python3 tools/par_load.py URL --workload w6 --conc 4 --share 0,0.5,0.9 --out w6.json
20    python3 tools/par_load.py URL --workload w2 --open-rates 0.25,0.5,1 --duration 120 --slo-ttft 10 --out open.json
21
22Labelling for the paired analysis (tools/par_analyze.py): --arm A|B --pair N --label "free text".  The ledger's
23`blocks` list holds one entry per (workload, level) with the headline metrics.  See Desktop 30thOctober results/par/HARNESS.md.
24Prompts are deterministic from --seed and carry a unique nonce, so the prompt cache cannot help unless W6 asks for a shared prefix.
25"""
26import argparse, http.client, json, os, platform, random, statistics, sys, threading, time, urllib.parse, urllib.request
27
28HARNESS_VERSION = "1.0"
29WORDS = ("time year people way day man thing woman life child world school state family student group country problem hand "
30         "part place case week company system program question work government number night point home water room mother area "
31         "money story fact month lot right study book eye job word business issue side kind head house service friend father "
32         "power hour game line end member law car city community name president team minute idea kid body information back "
33         "parent face others level office door health person art war history party result change morning reason research girl "
34         "guy moment air teacher force education foot boy age policy music market sense nation plan college interest death "
35         "experience effect use class control care field development role effort rate heart drug show leader light voice wife "
36         "police mind price report decision son view relationship town road arm difference value building action model season "
37         "society tax director position player record paper space ground form event official matter center couple site project "
38         "activity star table need court oil situation cost industry figure street image phone data picture practice piece "
39         "land product doctor wall patient worker news test movie north love support technology step baby computer type "
40         "attention film tree source organization hair window culture chance brother energy period course summer plant").split()
41TOPICS = ["the history of lighthouses", "how a mechanical watch keeps time", "why bridges are built as arches",
42          "the water cycle and droughts", "how bread rises", "the design of a medieval castle",
43          "how a transistor switches", "the life of a honey bee colony"]
44
45
46# ----------------------------------------------------------------------------------------------------------- prompts
47class Prompter:
48    """Deterministic filler text of a target token count.  The words-per-token ratio is calibrated once against the
49    server's own usage.prompt_tokens (a max_tokens=1 probe), so the target counts tokens after the real template."""
50
51    def __init__(self, url, key, model, seed, think, calib=None):
52        self.url, self.key, self.model, self.seed, self.think = url, key, model, seed, think
53        self.tok_per_word = (calib or {}).get("tok_per_word")
54        self.overhead = (calib or {}).get("overhead", 40)
55        self.calib = calib or {}
56
57    def words(self, n, rng):
58        return " ".join(rng.choice(WORDS) for _ in range(n))
59
60    def body_text(self, key, n_words):
61        return self.words(n_words, random.Random(f"{self.seed}/{key}"))
62
63    def calibrate(self):
64        if self.tok_per_word:
65            return
66        n = 1500
67        text = "[calibration] " + self.body_text("calib", n) + "\nSay ok."
68        u = chat_once(self.url, self.key, self.model, text, 1, self.think)
69        pt = u.get("usage", {}).get("prompt_tokens")
70        if not pt:
71            self.tok_per_word, self.overhead = 1.3, 40            # server gave no usage: a guess, the ledger says so
72            self.calib = {"tok_per_word": 1.3, "overhead": 40, "guess": True}
73            return
74        # prompt = template overhead (about 25-40 tokens) + n words; assume the overhead is the same as the tail
75        self.overhead = 40
76        self.tok_per_word = max(0.5, (pt - self.overhead) / n)
77        self.calib = {"tok_per_word": self.tok_per_word, "overhead": self.overhead, "probe_prompt_tokens": pt, "probe_words": n}
78
79    def make(self, key, target_tokens, prefix=None, share=0.0, tail="Now write a long, detailed essay about "):
80        """A prompt of ~target_tokens.  With prefix (a stable string) and share: the first share*target tokens are
81        the prefix's words (the same text for the whole cohort), the rest is unique to `key`."""
82        self.calibrate()
83        nw = max(8, int((target_tokens - self.overhead) / self.tok_per_word))
84        topic = TOPICS[hash_int(key) % len(TOPICS)]
85        nonce = f"[req {key}] "
86        if prefix is not None and share > 0:
87            ns = int(nw * share)
88            pre = self.body_text("prefix/" + prefix, ns)
89            rest = self.body_text(key, nw - ns)
90            return pre + "\n" + nonce + rest + f"\n{tail}{topic}."
91        return nonce + self.body_text(key, nw) + f"\n{tail}{topic}."
92
93
94def hash_int(s):
95    h = 1469598103934665603
96    for ch in s.encode():
97        h = ((h ^ ch) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
98    return h
99
100
101# ------------------------------------------------------------------------------------------------------------ request
102def _conn(url):
103    u = urllib.parse.urlparse(url)
104    cls = http.client.HTTPSConnection if u.scheme == "https" else http.client.HTTPConnection
105    return cls(u.hostname, u.port or (443 if u.scheme == "https" else 80), timeout=1800), u.path.rstrip("/")
106
107
108def _body(model, text, max_tokens, think, stream, extra=None):
109    b = {"model": model, "stream": stream, "max_tokens": max_tokens, "temperature": 0,
110         "messages": [{"role": "user", "content": text}]}
111    if stream:
112        b["stream_options"] = {"include_usage": True}
113    if not think:
114        b["reasoning_effort"] = "none"
115        b["chat_template_kwargs"] = {"enable_thinking": False}
116    if extra:
117        b.update(extra)
118    return b
119
120
121def chat_once(url, key, model, text, max_tokens, think):
122    c, base = _conn(url)
123    h = {"Content-Type": "application/json", **({"Authorization": "Bearer " + key} if key else {})}
124    c.request("POST", base + "/v1/chat/completions", json.dumps(_body(model, text, max_tokens, think, False)), h)
125    r = c.getresponse()
126    d = json.loads(r.read() or b"{}")
127    c.close()
128    return d
129
130
131def stream_request(url, key, model, text, max_tokens, think, sched_t0, extra=None, keep_times=False, keep_text=False):
132    """One streamed chat request.  Times are seconds on the perf_counter clock of this process; the record also
133    carries them relative to the run start (t_rel_*) by the caller."""
134    rec = {"t_sched": sched_t0, "t_send": None, "t_first": None, "t_last": None, "t_end": None, "completion_tokens": None,
135           "prompt_tokens": None, "cached_tokens": 0, "finish": None, "tokens_source": None, "chunks": 0, "max_gap": 0.0,
136           "gaps_ge1s": 0, "err": None, "timings": None, "reasoning_chars": 0, "content_chars": 0}
137    times = [] if keep_times else None
138    texts = [] if keep_text else None
139    rec["t_send"] = time.perf_counter()
140    last = None
141    sse_tokens = 0
142    try:
143        c, base = _conn(url)
144        h = {"Content-Type": "application/json", **({"Authorization": "Bearer " + key} if key else {})}
145        c.request("POST", base + "/v1/chat/completions", json.dumps(_body(model, text, max_tokens, think, True, extra)), h)
146        r = c.getresponse()
147        if r.status != 200:
148            rec["err"] = f"http {r.status}: {r.read(300).decode('utf-8', 'replace')}"
149        else:
150            while True:
151                raw = r.readline()
152                if not raw:
153                    break
154                line = raw.decode("utf-8", "replace").strip()
155                if not line.startswith("data:"):
156                    continue
157                d = line[5:].strip()
158                if d == "[DONE]":
159                    break
160                try:
161                    j = json.loads(d)
162                except ValueError:
163                    continue
164                now = time.perf_counter()
165                if j.get("error"):
166                    rec["err"] = str(j["error"])[:300]
167                for ch in j.get("choices", []):
168                    dl = ch.get("delta", {})
169                    a, b = dl.get("content") or "", dl.get("reasoning_content") or ""
170                    if a or b:
171                        if rec["t_first"] is None:
172                            rec["t_first"] = now
173                        elif last is not None:
174                            g = now - last
175                            if g > rec["max_gap"]:
176                                rec["max_gap"] = g
177                            if g >= 1.0:
178                                rec["gaps_ge1s"] += 1
179                        last = now
180                        rec["t_last"] = now
181                        rec["chunks"] += 1
182                        sse_tokens += 1
183                        rec["content_chars"] += len(a)
184                        if texts is not None:
185                            texts.append(a + b)
186                        rec["reasoning_chars"] += len(b)
187                        if times is not None:
188                            times.append(now)
189                    if ch.get("finish_reason"):
190                        rec["finish"] = ch["finish_reason"]
191                u = j.get("usage")
192                if u:
193                    rec["completion_tokens"] = u.get("completion_tokens")
194                    rec["prompt_tokens"] = u.get("prompt_tokens")
195                    rec["cached_tokens"] = (u.get("prompt_tokens_details") or {}).get("cached_tokens", 0) or 0
196                    rec["tokens_source"] = "usage"
197                if j.get("timings"):
198                    rec["timings"] = j["timings"]
199        c.close()
200    except Exception as e:  # noqa: BLE001
201        rec["err"] = repr(e)[:300]
202    rec["t_end"] = time.perf_counter()
203    if rec["completion_tokens"] is None:
204        rec["completion_tokens"] = sse_tokens
205        rec["tokens_source"] = "sse"                      # NOT a valid token count; the ledger marks the run invalid
206    if times is not None:
207        rec["chunk_times"] = times
208    if texts is not None:
209        rec["text"] = "".join(texts)
210    return rec
211
212
213def finish_record(rec, t0):
214    """Derived per-request metrics, and times relative to the run start."""
215    ttft = rec["t_first"] - rec["t_send"] if rec["t_first"] is not None else None
216    n = rec["completion_tokens"] or 0
217    tpot = (rec["t_last"] - rec["t_first"]) / (n - 1) if (ttft is not None and n > 1 and rec["t_last"] is not None) else None
218    out = {k: rec[k] for k in ("completion_tokens", "prompt_tokens", "cached_tokens", "finish", "tokens_source", "chunks", "max_gap",
219                               "gaps_ge1s", "err", "timings", "reasoning_chars", "content_chars")}
220    out.update({"t_sched": rec["t_sched"] - t0, "t_send": rec["t_send"] - t0, "t_end": rec["t_end"] - t0,
221                "t_first": (rec["t_first"] - t0) if rec["t_first"] is not None else None,
222                "lag": rec["t_send"] - rec["t_sched"], "ttft": ttft, "tpot": tpot, "latency": rec["t_end"] - rec["t_send"]})
223    if "text" in rec:
224        out["text"] = rec["text"]
225    if "chunk_times" in rec:
226        out["chunk_t"] = [round(x - t0, 4) for x in rec["chunk_times"]]
227    return out
228
229
230# --------------------------------------------------------------------------------------------------------- aggregates
231def pct(v, p):
232    v = sorted(x for x in v if x is not None)
233    if not v:
234        return None
235    k = (len(v) - 1) * p
236    lo = int(k)
237    hi = min(lo + 1, len(v) - 1)
238    return v[lo] + (v[hi] - v[lo]) * (k - lo)
239
240
241def aggregate(recs, window_s, slo=None):
242    """Level metrics.  window_s = one shared wall window for all requests (first submit to last completion)."""
243    ok = [r for r in recs if not r["err"]]
244    toks = sum(r["completion_tokens"] or 0 for r in ok)
245    agg = {"requests": len(recs), "errors": len(recs) - len(ok), "window_s": window_s, "tokens": toks,
246           "agg_tps": toks / window_s if window_s > 0 else None,
247           "prompt_tokens": sum(r["prompt_tokens"] or 0 for r in ok),
248           "invalid_token_source": sum(1 for r in recs if r["tokens_source"] != "usage"),
249           "length_stops": sum(1 for r in ok if r["finish"] == "length"), "early_stops": sum(1 for r in ok if r["finish"] == "stop")}
250    for k in ("ttft", "tpot", "max_gap", "latency", "lag"):
251        v = [r[k] for r in ok]
252        agg[k + "_p50"], agg[k + "_p95"], agg[k + "_max"] = pct(v, .5), pct(v, .95), (max(x for x in v if x is not None) if any(x is not None for x in v) else None)
253    per = [(r["completion_tokens"] - 1) / (r["t_end"] - r["t_first"]) for r in ok
254           if r["t_first"] is not None and (r["completion_tokens"] or 0) > 1 and r["t_end"] > r["t_first"]]
255    agg["per_req_tps_p50"] = pct(per, .5)
256    if slo:
257        good = [r for r in ok if (slo.get("ttft") is None or (r["ttft"] is not None and r["ttft"] <= slo["ttft"]))
258                and (slo.get("gap") is None or r["max_gap"] <= slo["gap"])]
259        agg["slo"] = slo
260        agg["slo_pass"] = len(good)
261        agg["goodput_tps"] = sum(r["completion_tokens"] or 0 for r in good) / window_s if window_s > 0 else None
262    return agg
263
264
265# --------------------------------------------------------------------------------------------------------- runners
266class Ctx:
267    def __init__(self, a, prompter):
268        self.a, self.p = a, prompter
269
270
271def closed_loop(ctx, level, n_requests, make_job, label):
272    """level concurrent clients pull jobs 0..n_requests-1 from one queue; the window is first submit -> last end."""
273    a = ctx.a
274    jobs = list(range(n_requests))
275    lock = threading.Lock()
276    recs = [None] * n_requests
277    t0 = time.perf_counter()
278
279    def worker():
280        while True:
281            with lock:
282                if not jobs:
283                    return
284                i = jobs.pop(0)
285            text, mt, extra = make_job(i)
286            recs[i] = stream_request(a.url, a.key, a.model, text, mt, a.think, time.perf_counter(), extra, a.keep_times, a.keep_text)
287
288    th = [threading.Thread(target=worker) for _ in range(level)]
289    for t in th:
290        t.start()
291    for t in th:
292        t.join()
293    t1 = max(r["t_end"] for r in recs)
294    fr = [finish_record(r, t0) for r in recs]
295    return fr, t1 - t0
296
297
298def run_closed(ctx, wl, levels):
299    a = ctx.a
300    blocks, allreq = [], []
301    for c in levels:
302        n = max(c * a.rounds, a.min_requests)
303        tag = f"{a.nonce}-{wl}-c{c}"
304
305        def make_job(i, c=c, tag=tag):
306            return ctx.p.make(f"{tag}-{i}", a.prompt_tokens), a.max_tokens, None
307
308        if a.warm_requests:                                      # warmup outside the measured window
309            for w in range(a.warm_requests):
310                stream_request(a.url, a.key, a.model, ctx.p.make(f"{tag}-warm{w}", a.prompt_tokens), min(a.max_tokens, 64), a.think, time.perf_counter())
311        fr, wall = closed_loop(ctx, c, n, make_job, tag)
312        agg = aggregate(fr, wall)
313        agg.update({"workload": wl, "level": c, "mode": "closed", "prompt_target": a.prompt_tokens, "max_tokens": a.max_tokens})
314        blocks.append(agg)
315        for i, r in enumerate(fr):
316            r.update({"workload": wl, "level": c, "idx": i})
317        allreq += fr
318        print(f"{wl} c={c}: {agg['tokens']} tokens / {wall:.1f}s = {agg['agg_tps']:.1f} tok/s  ttft p50/p95 "
319              f"{fmt(agg['ttft_p50'])}/{fmt(agg['ttft_p95'])}  tpot p50 {fmt(agg['tpot_p50'], 4)}  max_gap p95 {fmt(agg['max_gap_p95'])}"
320              f"  err {agg['errors']}", flush=True)
321    return blocks, allreq
322
323
324def fmt(x, d=2):
325    return "n/a" if x is None else f"{x:.{d}f}"
326
327
328def run_w4(ctx, levels):
329    """W4: c W2-style decoders running, then one long joiner (joiner_tokens) arrives joiner_at seconds after they start."""
330    a = ctx.a
331    blocks, allreq = [], []
332    for c in levels:
333        for rd in range(a.rounds):
334            tag = f"{a.nonce}-w4-c{c}-r{rd}"
335            res = {}
336            t0 = time.perf_counter()
337
338            def dec(i):
339                res[("d", i)] = stream_request(a.url, a.key, a.model, ctx.p.make(f"{tag}-d{i}", a.prompt_tokens), a.decoder_tokens, a.think, time.perf_counter(), None, a.keep_times or True)
340
341            def joiner():
342                time.sleep(a.joiner_at)
343                res[("j", 0)] = stream_request(a.url, a.key, a.model, ctx.p.make(f"{tag}-j", a.joiner_tokens), a.joiner_out, a.think, time.perf_counter(), None, True)
344
345            th = [threading.Thread(target=dec, args=(i,)) for i in range(c)] + [threading.Thread(target=joiner)]
346            for t in th:
347                t.start()
348            for t in th:
349                t.join()
350            wall = max(r["t_end"] for r in res.values()) - t0
351            fr = {k: finish_record(r, t0) for k, r in res.items()}
352            j = fr[("j", 0)]
353            ts_j = j["t_send"]
354            te_j = j["t_first"] if j["t_first"] is not None else j["t_end"]
355            # incumbent gaps between the joiner's submit and its first token (the interference window)
356            gaps = []
357            for (k, i), r in fr.items():
358                if k != "d":
359                    continue
360                ct = [x for x in r.get("chunk_t", [])]
361                for x, y in zip(ct, ct[1:]):
362                    if y >= ts_j and x <= te_j + 1.0:
363                        gaps.append(y - x)
364            agg = aggregate(list(fr.values()), wall)
365            allreq += [dict(r, workload="w4", level=c, round=rd, role=k[0]) for k, r in fr.items()]
366            for r in allreq[-len(fr):]:
367                r.pop("chunk_t", None) if not a.keep_times else None
368            decs = [r for k, r in fr.items() if k[0] == "d"]
369            agg.update({"workload": "w4", "level": c, "mode": "closed", "round": rd, "joiner_tokens": a.joiner_tokens,
370                        "joiner_ttft": j["ttft"], "joiner_prompt_tokens": j["prompt_tokens"],
371                        "incumbent_gap_max_during_join": max(gaps) if gaps else None,
372                        "incumbent_gap_p99_during_join": pct(gaps, .99),
373                        "incumbent_tps_p50": pct([(d["completion_tokens"] - 1) / max(d["t_end"] - d["t_first"], 1e-9) for d in decs if d["t_first"] is not None and d["completion_tokens"] and d["completion_tokens"] > 1], .5),
374                        "makespan_s": wall})
375            blocks.append(agg)
376            print(f"w4 c={c} r={rd}: makespan {wall:.1f}s agg {fmt(agg['agg_tps'], 1)} tok/s, joiner ttft {fmt(j['ttft'])}s ({j['prompt_tokens']} prompt tok), "
377                  f"incumbent max gap during join {fmt(agg['incumbent_gap_max_during_join'])}s", flush=True)
378    return blocks, allreq
379
380
381def run_w6(ctx, levels):
382    a = ctx.a
383    blocks, allreq = [], []
384    for c in levels:
385        for share in [float(x) for x in a.share.split(",")]:
386            tag = f"{a.nonce}-w6-c{c}-s{share}"
387            prefix = f"{tag}"
388            if a.prime and share > 0:                           # prefix-warm: one priming request, not measured
389                stream_request(a.url, a.key, a.model, ctx.p.make(f"{tag}-prime", a.prompt_tokens, prefix, share), 8, a.think, time.perf_counter())
390            n = max(c * a.rounds, a.min_requests)
391
392            def make_job(i, tag=tag, prefix=prefix, share=share):
393                return ctx.p.make(f"{tag}-{i}", a.prompt_tokens, prefix, share), a.max_tokens, None
394
395            fr, wall = closed_loop(ctx, c, n, make_job, tag)
396            agg = aggregate(fr, wall)
397            agg.update({"workload": "w6", "level": c, "share": share, "primed": bool(a.prime), "mode": "closed",
398                        "cached_tokens_mean": statistics.mean(r["cached_tokens"] for r in fr) if fr else None})
399            blocks.append(agg)
400            for i, r in enumerate(fr):
401                r.update({"workload": "w6", "level": c, "share": share, "idx": i})
402            allreq += fr
403            print(f"w6 c={c} share={share}: {fmt(agg['agg_tps'], 1)} tok/s ttft p50 {fmt(agg['ttft_p50'])} cached mean {agg['cached_tokens_mean']:.0f}", flush=True)
404    return blocks, allreq
405
406
407def run_open(ctx, wl, rates):
408    """Open loop: seeded exponential inter-arrival times, independent of completions.  Requests still running at
409    duration + drain_s are failures (kept in the ledger as unfinished)."""
410    a = ctx.a
411    blocks, allreq = [], []
412    for rate in rates:
413        rng = random.Random(f"{a.seed}/open/{rate}")
414        sched, t = [], 0.0
415        while True:
416            t += rng.expovariate(rate)
417            if t >= a.duration:
418                break
419            sched.append(t)
420        tag = f"{a.nonce}-{wl}-open{rate}"
421        t0 = time.perf_counter()
422        res = [None] * len(sched)
423        th = []
424
425        def one(i, at):
426            res[i] = stream_request(a.url, a.key, a.model, ctx.p.make(f"{tag}-{i}", a.prompt_tokens), a.max_tokens, a.think, t0 + at, None, False)
427
428        def launcher():
429            for i, at in enumerate(sched):
430                d = t0 + at - time.perf_counter()
431                if d > 0:
432                    time.sleep(d)
433                t_ = threading.Thread(target=one, args=(i, at), daemon=True)
434                t_.start()
435                th.append(t_)
436
437        lt = threading.Thread(target=launcher)
438        lt.start()
439        lt.join()
440        deadline = t0 + a.duration + a.drain_s
441        for t_ in th:
442            t_.join(max(0.0, deadline - time.perf_counter()))
443        done = [r for r in res if r is not None and r["t_end"] is not None]
444        unfinished = len(sched) - len(done)
445        window = max([r["t_end"] for r in done], default=t0) - t0
446        fr = [finish_record(r, t0) for r in done]
447        slo = {"ttft": a.slo_ttft, "gap": a.slo_gap}
448        # tokens finished inside the arrival window over that window; the drain is reported separately
449        inwin = [r for r in fr if r["t_end"] <= a.duration]
450        agg = aggregate(fr, window, slo)
451        agg["tps_in_window"] = sum(r["completion_tokens"] or 0 for r in inwin if not r["err"]) / a.duration
452        agg.update({"workload": wl, "mode": "open", "offered_rate": rate, "offered_requests": len(sched), "unfinished": unfinished,
453                    "duration": a.duration, "drain_s": a.drain_s, "achieved_rate": len(inwin) / a.duration,
454                    "slo_pass_frac": (agg.get("slo_pass", 0) / len(sched)) if sched else None})
455        blocks.append(agg)
456        allreq += [dict(r, workload=wl, offered_rate=rate, idx=i) for i, r in enumerate(fr)]
457        print(f"{wl} open rate={rate}/s: offered {len(sched)}, done {len(done)}, unfinished {unfinished}, slo pass {agg.get('slo_pass')}, "
458              f"goodput {fmt(agg.get('goodput_tps'), 1)} tok/s, ttft p95 {fmt(agg['ttft_p95'])}, lag max {fmt(agg['lag_max'], 3)}", flush=True)
459    return blocks, allreq
460
461
462# ------------------------------------------------------------------------------------------------------------- main
463def get_json(url):
464    try:
465        with urllib.request.urlopen(url, timeout=10) as r:
466            return json.loads(r.read())
467    except Exception as e:  # noqa: BLE001
468        return {"error": repr(e)[:200]}
469
470
471def main(argv=None):
472    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
473    ap.add_argument("url")
474    ap.add_argument("--workload", default="w2", choices=["w1", "w2", "w3", "w4", "w6"])
475    ap.add_argument("--conc", default="1,2,4,8", help="closed-loop concurrency levels (w1 forces 1)")
476    ap.add_argument("--rounds", type=int, default=3, help="requests per client per level (a level runs conc*rounds requests)")
477    ap.add_argument("--min-requests", type=int, default=0)
478    ap.add_argument("--warm-requests", type=int, default=0, help="unmeasured short requests before each level")
479    ap.add_argument("--prompt-tokens", type=int, default=None, help="default: w1 512, w2 1024, w3 8192, w6 2048")
480    ap.add_argument("--max-tokens", type=int, default=None, help="default: w1 512, w2 256, w3 128, w6 128")
481    ap.add_argument("--joiner-tokens", type=int, default=28000)
482    ap.add_argument("--joiner-out", type=int, default=64)
483    ap.add_argument("--joiner-at", type=float, default=6.0, help="seconds after the decoders start")
484    ap.add_argument("--decoder-tokens", type=int, default=512)
485    ap.add_argument("--share", default="0,0.5,0.9", help="w6 shared-prefix fractions")
486    ap.add_argument("--prime", action="store_true", help="w6: one unmeasured request primes the prefix (prefix-warm)")
487    ap.add_argument("--open-rates", default=None, help="open-loop offered rates (req/s), e.g. 0.25,0.5,1")
488    ap.add_argument("--duration", type=float, default=120.0, help="open loop: arrival window (s)")
489    ap.add_argument("--drain-s", type=float, default=120.0, help="open loop: extra time to finish before counting failures")
490    ap.add_argument("--slo-ttft", type=float, default=None)
491    ap.add_argument("--slo-gap", type=float, default=None)
492    ap.add_argument("--seed", default="par29")
493    ap.add_argument("--nonce", default=str(int(time.time())))
494    ap.add_argument("--model", default="strata")
495    ap.add_argument("--key", default=os.environ.get("STRATA_KEY", ""))
496    ap.add_argument("--think", action="store_true")
497    ap.add_argument("--keep-times", action="store_true", help="keep every chunk timestamp in the ledger (large)")
498    ap.add_argument("--keep-text", action="store_true", help="keep every answer's text in the ledger (identity checks)")
499    ap.add_argument("--calib", default=None, help="a ledger/calibration JSON to reuse the words-per-token calibration from")
500    ap.add_argument("--arm", default="")
501    ap.add_argument("--pair", default="")
502    ap.add_argument("--label", default="")
503    ap.add_argument("--settings", default=None, help="file with the effective engine settings/provenance to embed (launcher writes it)")
504    ap.add_argument("--out", required=True)
505    a = ap.parse_args(argv)
506    a.url = a.url.rstrip("/")
507    d = {"w1": (512, 512), "w2": (1024, 256), "w3": (8192, 128), "w4": (1024, 256), "w6": (2048, 128)}[a.workload]
508    a.prompt_tokens = a.prompt_tokens or d[0]
509    a.max_tokens = a.max_tokens or d[1]
510    levels = [1] if a.workload == "w1" else [int(x) for x in a.conc.split(",")]
511    calib = None
512    if a.calib and os.path.exists(a.calib):
513        calib = json.load(open(a.calib)).get("calibration")
514    p = Prompter(a.url, a.key, a.model, a.seed, a.think, calib)
515    ctx = Ctx(a, p)
516    status0 = get_json(a.url + "/v1/status")
517    started = time.time()
518    if a.open_rates:
519        blocks, reqs = run_open(ctx, a.workload, [float(x) for x in a.open_rates.split(",")])
520    elif a.workload == "w4":
521        blocks, reqs = run_w4(ctx, levels)
522    elif a.workload == "w6":
523        blocks, reqs = run_w6(ctx, levels)
524    else:
525        blocks, reqs = run_closed(ctx, a.workload, levels)
526    status1 = get_json(a.url + "/v1/status")
527    settings = None
528    if a.settings and os.path.exists(a.settings):
529        settings = open(a.settings, errors="replace").read()[:20000]
530    for b in blocks:
531        b.update({"arm": a.arm, "pair": a.pair, "label": a.label})
532    invalid = sum(b.get("invalid_token_source", 0) for b in blocks)
533    ledger = {"harness": "par_load", "version": HARNESS_VERSION, "started": started, "host": platform.node(), "argv": sys.argv[1:],
534              "args": {k: v for k, v in vars(a).items() if k != "key"}, "calibration": p.calib, "valid": invalid == 0,
535              "invalid_reason": None if invalid == 0 else f"{invalid} requests without server usage: token counts are SSE chunks",
536              "status_before": status0, "status_after": status1, "settings": settings, "blocks": blocks, "requests": reqs}
537    os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
538    json.dump(ledger, open(a.out, "w"), indent=1)
539    print("ledger:", a.out, "valid" if invalid == 0 else "INVALID (no usage)")
540    return 0 if invalid == 0 and all(b["errors"] == 0 for b in blocks) else 1
541
542
543if __name__ == "__main__":
544    sys.exit(main())