File size: 14,489 Bytes
590b382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
"""OpenAI-compatible SSE streaming benchmark and parity scorer (stdlib only).

Works with vLLM, SGLang, llama-server, or TokenSpeed without extra pip installs.
Measures TTFT, inter-token latency (ITL), per-stream and aggregate throughput across
concurrency levels, detects repetition runaways, and compares exact output parity
between Stock (A) and Candidate (B).

Self-test (CPU only, $0):
  python3 rtx-pro-inkling/bench_client.py --self-test
"""
from __future__ import annotations

import argparse
import concurrent.futures
import http.server
import json
import statistics
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any


def load_prompts(path: Path) -> list[dict[str, Any]]:
    rows = []
    for line in path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if line:
            rows.append(json.loads(line))
    return rows


def detect_runaway(text: str, min_unit: int = 16, min_repeats: int = 4) -> bool:
    """Flag obvious tail repetition loops."""
    if len(text) < min_unit * min_repeats:
        return False
    tail = text[-80 * min_repeats :]
    for u in range(min_unit, min(80, len(tail) // min_repeats) + 1):
        chunk = tail[-u:]
        if chunk.strip() and tail.endswith(chunk * min_repeats):
            return True
    return False


def stream_one(
    base_url: str,
    model: str,
    prompt_row: dict[str, Any],
    timeout_s: float = 120.0,
    seed: int = 42,
) -> dict[str, Any]:
    url = base_url.rstrip("/") + "/v1/chat/completions"
    payload = {
        "model": model,
        "messages": [{"role": "user", "content": prompt_row["prompt"]}],
        "temperature": 0.0,
        "top_p": 1.0,
        "seed": seed,
        "max_tokens": int(prompt_row.get("max_tokens", 256)),
        "stream": True,
        "stream_options": {"include_usage": True},
    }
    req = urllib.request.Request(
        url,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
        method="POST",
    )

    t0 = time.perf_counter()
    first_tok_t: float | None = None
    chunk_times: list[float] = []
    parts: list[str] = []
    answer_parts: list[str] = []
    completion_tokens: int | None = None
    finish_reason: str | None = None
    error: str | None = None
    done = False

    try:
        with urllib.request.urlopen(req, timeout=timeout_s) as resp:
            for raw_line in resp:
                line = raw_line.decode("utf-8", errors="replace").strip()
                if not line or not line.startswith("data:"):
                    continue
                data_s = line[5:].strip()
                if data_s == "[DONE]":
                    done = True
                    break
                ev = json.loads(data_s)
                if ev.get("error"):
                    raise ValueError(f"Server rejected stream: {ev['error']}")
                if ev.get("usage") and ev["usage"].get("completion_tokens") is not None:
                    completion_tokens = int(ev["usage"]["completion_tokens"])
                choices = ev.get("choices") or []
                if choices:
                    delta = choices[0].get("delta") or {}
                    answer = delta.get("content") or ""
                    answer_parts.append(answer)
                    piece = (delta.get("reasoning_content") or delta.get("reasoning") or "") + answer
                    if piece:
                        now = time.perf_counter()
                        if first_tok_t is None:
                            first_tok_t = now
                        chunk_times.append(now)
                        parts.append(piece)
                    if choices[0].get("finish_reason"):
                        finish_reason = choices[0]["finish_reason"]
            if not done:
                raise ValueError("Stream closed before [DONE]")
    except Exception as exc:  # noqa: BLE001
        error = f"{type(exc).__name__}: {exc}"

    t1 = time.perf_counter()
    text = "".join(parts)
    # Fallback token count if server didn't emit usage in stream
    est_tokens = completion_tokens if completion_tokens is not None else max(len(chunk_times), len(text.split()))
    ttft_ms = round((first_tok_t - t0) * 1000.0, 2) if first_tok_t is not None else None
    total_s = max(t1 - t0, 1e-6)
    gen_s = max((t1 - first_tok_t), 1e-6) if first_tok_t is not None else total_s
    itl_ms = None
    if len(chunk_times) >= 2:
        gaps = [(chunk_times[i] - chunk_times[i - 1]) * 1000.0 for i in range(1, len(chunk_times))]
        itl_ms = round(statistics.median(gaps), 2)

    return {
        "id": prompt_row["id"],
        "cat": prompt_row.get("cat", ""),
        "ok": error is None and len(text) > 0,
        "error": error,
        "finish_reason": finish_reason,
        "tokens": est_tokens,
        "reported_tokens": completion_tokens,
        "max_tokens": payload["max_tokens"],
        "ttft_ms": ttft_ms,
        "itl_ms": itl_ms,
        "total_s": round(total_s, 4),
        "stream_tok_s": round(est_tokens / gen_s, 2) if error is None and est_tokens > 0 else 0.0,
        "runaway": detect_runaway(text),
        "text": text,
        "answer": "".join(answer_parts),
    }


def _pct(vals: list[float], p: float) -> float | None:
    if not vals:
        return None
    s = sorted(vals)
    idx = min(len(s) - 1, max(0, int(round((p / 100.0) * (len(s) - 1)))))
    return round(s[idx], 2)


def run_concurrency_level(
    base_url: str,
    model: str,
    prompts: list[dict[str, Any]],
    concurrency: int,
    n_requests: int | None = None,
    timeout_s: float = 120.0,
) -> dict[str, Any]:
    count = n_requests if n_requests is not None else max(len(prompts), concurrency)
    work = [prompts[i % len(prompts)] for i in range(count)]

    t_start = time.perf_counter()
    rows: list[dict[str, Any]] = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as ex:
        futs = [ex.submit(stream_one, base_url, model, p, timeout_s) for p in work]
        for fut in futs:
            rows.append(fut.result())
    wall_s = max(time.perf_counter() - t_start, 1e-6)

    ok_rows = [r for r in rows if r["ok"]]
    ttfts = [r["ttft_ms"] for r in ok_rows if r["ttft_ms"] is not None]
    itls = [r["itl_ms"] for r in ok_rows if r["itl_ms"] is not None]
    tot_tokens = sum(r["tokens"] for r in ok_rows)

    return {
        "concurrency": concurrency,
        "requests": len(rows),
        "ok": len(ok_rows),
        "errors": len(rows) - len(ok_rows),
        "runaways": sum(1 for r in ok_rows if r["runaway"]),
        "unmetered": sum(1 for r in ok_rows if r["reported_tokens"] is None),
        "wall_s": round(wall_s, 3),
        "total_tokens": tot_tokens,
        "agg_tok_s": round(tot_tokens / wall_s, 2),
        "ttft_p50_ms": _pct(ttfts, 50),
        "ttft_p95_ms": _pct(ttfts, 95),
        "itl_p50_ms": _pct(itls, 50),
        "rows": rows,
    }


def compare_parity(stock_rows: list[dict[str, Any]], cand_rows: list[dict[str, Any]]) -> dict[str, Any]:
    """Compare exact C=1 output text; a native server may clamp the requested temperature."""
    s_map = {r["id"]: r for r in stock_rows}
    c_map = {r["id"]: r for r in cand_rows}
    common = sorted(set(s_map) & set(c_map))
    exact = 0
    prefix_ratios = []
    diffs = []
    for pid in common:
        st = s_map[pid]["text"]
        ct = c_map[pid]["text"]
        if st == ct:
            exact += 1
            prefix_ratios.append(1.0)
        else:
            mlen = min(len(st), len(ct))
            pref = 0
            while pref < mlen and st[pref] == ct[pref]:
                pref += 1
            denom = max(len(st), len(ct), 1)
            prefix_ratios.append(pref / denom)
            diffs.append({"id": pid, "stock_len": len(st), "cand_len": len(ct), "common_prefix_chars": pref})
    return {
        "compared": len(common),
        "exact_match": exact,
        "exact_rate": round(exact / max(len(common), 1), 4),
        "mean_prefix_ratio": round(sum(prefix_ratios) / max(len(prefix_ratios), 1), 4),
        "diffs": diffs[:10],
    }


def run_suite(
    base_url: str,
    model: str,
    prompts_path: Path,
    concurrencies: list[int],
    warmup: int = 2,
    timeout_s: float = 120.0,
    *, min_max_tokens: int = 0, measure_level=run_concurrency_level,
) -> dict[str, Any]:
    prompts = load_prompts(prompts_path)
    if not prompts or len({p['id'] for p in prompts}) != len(prompts):
        raise ValueError('prompt set must be nonempty with unique IDs')
    # Change the request, not the frozen input file. Use the same floor on every runtime.
    prompts = [dict(p, max_tokens=max(min_max_tokens, int(p.get('max_tokens', 256)))) for p in prompts]
    for p in prompts[:warmup]:
        stream_one(base_url, model, p, timeout_s=timeout_s)
    levels = {}
    for c in concurrencies:
        levels[str(c)] = measure_level(base_url, model, prompts, concurrency=c, timeout_s=timeout_s)
    return {
        "base_url": base_url,
        "model": model,
        "prompts": str(prompts_path),
        "prompt_ids": [p["id"] for p in prompts],
        "min_max_tokens": min_max_tokens,
        "levels": levels,
    }


def heldout_quality(stock, cand, *, require_parity):
    """Fail closed on incomplete answers, unmetered tokens or missing exact comparisons."""
    bad = []
    ids = stock['prompt_ids']
    if not ids or len(set(ids)) != len(ids) or ids != cand['prompt_ids']:
        raise ValueError('held-out suites did not measure the same prompt set')
    for name, result in (("stock", stock), ("cand", cand)):
        if set(result['levels']) != {'1', '4', '8'}:
            raise ValueError('held-out qualification requires C=1,4,8')
        for level, stats in result['levels'].items():
            expected = [ids[i % len(ids)] for i in range(max(len(ids), int(level)))]
            if [r['id'] for r in stats['rows']] != expected:
                raise ValueError(f'{name} C={level} did not complete the request set')
            for row in stats['rows']:
                if not (row['ok'] and not row['runaway'] and row['answer'].strip()
                        and 0 < (row['reported_tokens'] or 0) <= row['max_tokens'] and row['max_tokens'] >= 1024
                        and row['finish_reason'] == 'stop'):
                    bad.append((name, level, row['id'], row['finish_reason']))
    left, right = (res['levels']['1']['rows'] for res in (stock, cand))
    equal = bool(left) and len(left) == len(right) and all(
        (s['id'], s['answer'], s['text']) == (c['id'], c['answer'], c['text']) for s, c in zip(left, right))
    return {'passed': not bad and (equal or not require_parity), 'bad_rows': bad,
            'c1_exact': equal, 'c1_samples': {'stock': left, 'cand': right}}


def _self_test() -> int:
    class MockHandler(http.server.BaseHTTPRequestHandler):
        def log_message(self, format: str, *args: Any) -> None:
            return

        def do_POST(self) -> None:
            ln = int(self.headers.get("Content-Length", "0"))
            body = json.loads(self.rfile.read(ln).decode("utf-8"))
            msg = body["messages"][0]["content"][:24]
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream")
            self.end_headers()
            toks = ["Hello", " from", " mock:", " ", msg]
            for i, tok in enumerate(toks):
                time.sleep(0.005)
                ev = {"choices": [{"delta": {"content": tok}, "finish_reason": None}]}
                if i == len(toks) - 1:
                    ev["choices"][0]["finish_reason"] = "stop"
                    ev["usage"] = {"completion_tokens": len(toks)}
                self.wfile.write(f"data: {json.dumps(ev)}\n\n".encode("utf-8"))
                self.wfile.flush()
            self.wfile.write(b"data: [DONE]\n\n")
            self.wfile.flush()

    srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), MockHandler)
    port = srv.server_address[1]
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    try:
        prompts_path = Path(__file__).parent / "prompts_dev.jsonl"
        a = run_suite(f"http://127.0.0.1:{port}", "mock-inkling", prompts_path, [1, 4, 8], warmup=1, min_max_tokens=1024)
        b = run_suite(f"http://127.0.0.1:{port}", "mock-inkling", prompts_path, [1, 4, 8], warmup=1, min_max_tokens=1024)
        parity = compare_parity(a["levels"]["1"]["rows"], b["levels"]["1"]["rows"])
        assert a["levels"]["1"]["errors"] == 0, a
        assert a["levels"]["4"]["errors"] == 0, a
        assert parity["exact_rate"] == 1.0, parity
        assert heldout_quality(a, b, require_parity=True)['passed']
        b['levels']['8']['rows'][0]['reported_tokens'] = None
        assert not heldout_quality(a, b, require_parity=True)['passed']
        assert detect_runaway("abc " * 40) is True
        assert detect_runaway("abcdefghij0123456789 " * 4)
        assert detect_runaway("Normal unique sentence with no runaway loop.") is False
        print("SELF_TEST_OK", json.dumps({
            "c1_tok_s": a["levels"]["1"]["agg_tok_s"],
            "c4_tok_s": a["levels"]["4"]["agg_tok_s"],
            "parity_exact": parity["exact_rate"],
        }))
        return 0
    finally:
        srv.shutdown()


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description="Streaming SSE benchmark + parity scorer.")
    ap.add_argument("--self-test", action="store_true")
    ap.add_argument("--url", default="http://127.0.0.1:8000")
    ap.add_argument("--model", default="thinkingmachines/Inkling-2-Mini")
    ap.add_argument("--prompts", type=Path, default=Path(__file__).parent / "prompts_dev.jsonl")
    ap.add_argument("--conc", default="1,4,8,16")
    ap.add_argument("--out", type=Path, default=None)
    args = ap.parse_args(argv)

    if args.self_test:
        return _self_test()

    concs = [int(x) for x in args.conc.split(",") if x.strip()]
    res = run_suite(args.url, args.model, args.prompts, concs)
    summary = {
        c: {k: v for k, v in d.items() if k != "rows"}
        for c, d in res["levels"].items()
    }
    print(json.dumps(summary, indent=2))
    if args.out:
        args.out.parent.mkdir(parents=True, exist_ok=True)
        args.out.write_text(json.dumps(res, indent=2), encoding="utf-8")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())