okami.mom/strata

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

Yasei-no-otokobench: report Coder IQ1_M on Threadripper 3990X and RX 6900 XT (#628)cc86ad90d

main
7.2 KiB172 linesraw
1#!/usr/bin/env python3
2"""Run one cached-prefix continuation after the fresh 32K benchmark suite.
3
4Run once immediately after the measured 32k-run-3 result is present, before
5another request changes the engine's active conversation prefix.
6"""
7import argparse
8import copy
9import json
10import time
11import urllib.request
12from pathlib import Path
13
14
15def get_json(url, headers):
16    request = urllib.request.Request(url, headers=headers)
17    with urllib.request.urlopen(request, timeout=30) as response:
18        return json.loads(response.read().decode("utf-8"))
19
20
21def post_json(url, payload, headers, timeout=1800):
22    request = urllib.request.Request(
23        url,
24        data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
25        headers=headers,
26    )
27    with urllib.request.urlopen(request, timeout=timeout) as response:
28        return json.loads(response.read().decode("utf-8"))
29
30
31def latest_engine_record(metrics, request_started):
32    for record in metrics.get("requests", []):
33        if record.get("time", 0) >= request_started - 0.1:
34            return record
35    return None
36
37
38def main():
39    parser = argparse.ArgumentParser(description=__doc__)
40    parser.add_argument("--url", default="http://127.0.0.1:8081")
41    parser.add_argument("--raw", type=Path, default=Path(__file__).resolve().parent /
42                        "workers-31-long" / "raw.jsonl")
43    parser.add_argument("--out", type=Path, default=Path(__file__).resolve().parent /
44                        "workers-31-long" / "followup.json")
45    parser.add_argument("--api-key", default="")
46    args = parser.parse_args()
47
48    source = None
49    with args.raw.open("r", encoding="utf-8") as stream:
50        for line in stream:
51            if not line.strip():
52                continue
53            row = json.loads(line)
54            if row.get("label") == "32k-run-3" and not row.get("warmup"):
55                source = row
56    if source is None:
57        raise SystemExit(f"No completed 32k-run-3 record found in {args.raw}; no request was sent.")
58    original = source.get("request_body") or {}
59    original_messages = original.get("messages") or []
60    if len(original_messages) != 1 or original_messages[0].get("role") != "user":
61        raise SystemExit("The saved 32k-run-3 request does not contain the expected single user message.")
62    assistant_text = source.get("output_text") or ""
63    if not assistant_text:
64        raise SystemExit("The saved 32k-run-3 response is empty; no request was sent.")
65
66    payload = copy.deepcopy(original)
67    payload["messages"] = [
68        original_messages[0],
69        {"role": "assistant", "content": assistant_text},
70        {"role": "user", "content": "Continue the review with concrete tests."},
71    ]
72    payload["max_tokens"] = 256
73    payload["temperature"] = 0
74    payload["reasoning_effort"] = "none"
75    payload["stream"] = True
76    payload["stream_options"] = {"include_usage": True}
77
78    base = args.url.rstrip("/")
79    headers = {"Content-Type": "application/json"}
80    get_headers = {}
81    if args.api_key:
82        headers["Authorization"] = "Bearer " + args.api_key
83        get_headers["Authorization"] = "Bearer " + args.api_key
84
85    before = get_json(base + "/metrics", get_headers)
86    started_wall = time.time()
87    started = time.perf_counter()
88    request = urllib.request.Request(
89        base + "/v1/chat/completions",
90        data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
91        headers=headers,
92    )
93    chunks, text_parts, reasoning_parts = [], [], []
94    usage, finish_reason, first_text, stream_error = None, None, None, None
95    with urllib.request.urlopen(request, timeout=1800) as response:
96        for line in response:
97            if not line.startswith(b"data: "):
98                continue
99            data = line[6:].strip()
100            if data == b"[DONE]":
101                break
102            try:
103                chunk = json.loads(data.decode("utf-8"))
104            except (UnicodeDecodeError, json.JSONDecodeError):
105                continue
106            chunks.append(chunk)
107            if chunk.get("error"):
108                stream_error = chunk["error"]
109            if "usage" in chunk:
110                usage = chunk["usage"]
111            for choice in chunk.get("choices", []):
112                delta = choice.get("delta") or {}
113                content = delta.get("content") or ""
114                reasoning = delta.get("reasoning_content") or ""
115                if content or reasoning:
116                    if first_text is None:
117                        first_text = time.perf_counter() - started
118                    text_parts.append(content)
119                    reasoning_parts.append(reasoning)
120                finish_reason = choice.get("finish_reason") or finish_reason
121    total = time.perf_counter() - started
122    after = get_json(base + "/metrics", get_headers)
123    engine = latest_engine_record(after, started_wall)
124    timings_chunk = next((chunk["timings"] for chunk in reversed(chunks) if chunk.get("timings")), None)
125    engine_timings = None
126    if engine:
127        fresh = max(0, (engine.get("prompt_tokens") or 0) - (engine.get("reused") or 0))
128        engine_timings = {
129            "prompt_tokens": engine.get("prompt_tokens"),
130            "fresh_prompt_tokens": fresh,
131            "reused_tokens": engine.get("reused"),
132            "prompt_ms": engine.get("prompt_ms"),
133            "prefill_tok_s": fresh / (engine["prompt_ms"] / 1000) if engine.get("prompt_ms") else None,
134            "generated_tokens": engine.get("engine_generated"),
135            "decode_ms": engine.get("decode_ms"),
136            "decode_tok_s": engine.get("decode_tok_s"),
137        }
138    result = {
139        "source_run": "32k-run-3",
140        "source_request_sha256": source.get("request_sha256"),
141        "url": base,
142        "request_body": payload,
143        "client_ttft_s": first_text,
144        "client_total_latency_s": total,
145        "finish_reason": finish_reason,
146        "usage": usage,
147        "prefix_reused_tokens": (engine or {}).get("reused"),
148        "api_cached_tokens": ((usage or {}).get("prompt_tokens_details") or {}).get("cached_tokens"),
149        "engine": engine,
150        "engine_timings": timings_chunk or engine_timings,
151        "output_text": "".join(text_parts),
152        "reasoning_text": "".join(reasoning_parts),
153        "raw_stream_chunks": chunks,
154        "stream_error": stream_error,
155        "metrics_before": before,
156        "metrics_after": after,
157        "cache_note": "This is a continuation of the saved 32k-run-3 conversation. Reuse is reported from the "
158                      "engine history/API usage, not inferred from the repeated messages.",
159    }
160    args.out.parent.mkdir(parents=True, exist_ok=True)
161    args.out.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
162    print(json.dumps({"output": str(args.out), "ttft_s": first_text, "total_s": total,
163                      "prompt_tokens": (engine or {}).get("prompt_tokens"),
164                      "reused_tokens": result["prefix_reused_tokens"], "decode_tok_s":
165                      (engine or {}).get("decode_tok_s"), "finish_reason": finish_reason,
166                      "error": stream_error}, ensure_ascii=False))
167    if stream_error:
168        raise SystemExit(f"The stream reported an error; details saved in {args.out}")
169
170
171if __name__ == "__main__":
172    main()