Repository navigation
Expand file tree
/
Copy pathbench_openai.py
More file actions
139 lines (123 loc) · 7.15 KB
/
Copy pathbench_openai.py
File metadata and controls
139 lines (123 loc) · 7.15 KB
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
"""Single-stream decode speed of an OpenAI-compatible server, measured from the stream.
Decode tok/s = (completion tokens - 1) / (last token time - first token time), the same span the
CUDA engine's bench times (the first sampled token excluded). Each row also carries bench_metrics'
figures (prompt tokens over client TTFT for a cold request, token ITL/TPOT where each chunk holds one token,
chunk-level estimates and round gaps) and bench_stream's boundaries, medians over the reps;
docs/cache-benchmarks.md defines them. Standard library only, so it runs on a bare host.
python3 tools/bench_openai.py http://127.0.0.1:8080 MODEL --tokens 64 --reps 5 --output out.json
"""
import argparse
import json
import statistics
import sys
import time
import urllib.request
from bench_auth import authorize, read_api_key, redact
from bench_args import validate_temperatures
import bench_metrics
import bench_stream
import bench_thinking
if sys.version_info < (3, 11):
sys.exit(f"Python 3.11+ is required (this is {sys.version.split()[0]}); "
"TensorFold's tools use PEP 604 unions. Try: python3.12 tools/bench_openai.py ...")
PROMPTS = [
{"name": "fibonacci-raw", "kind": "completion",
"prompt": "Write a short Python function that computes the Fibonacci sequence and explain it."},
{"name": "gpu-chat-no-think", "kind": "chat",
"prompt": "Explain how matrix multiplication uses a GPU in plain English, then give a small numerical example."},
]
def stream(base: str, model: str, item: dict, tokens: int, temperature: float, seed: int | None,
*, api_key: str | None = None) -> dict:
body = {"model": model, "max_tokens": tokens, "temperature": temperature, "stream": True,
"stream_options": {"include_usage": True}, "ignore_eos": True}
if seed is not None:
body["seed"] = seed
if temperature > 0:
body.update(top_k=20, top_p=0.95)
if item["kind"] == "chat":
url = base + "/v1/chat/completions"
body["messages"] = [{"role": "user", "content": item["prompt"]}]
if bench_thinking.request_off(item):
body["chat_template_kwargs"] = {"enable_thinking": False}
else:
url = base + "/v1/completions"
body["prompt"] = item["prompt"]
req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
authorize(req, api_key)
start = time.perf_counter()
reply = bench_stream.Collector(start)
with urllib.request.urlopen(req, timeout=600) as resp:
reply.read(resp)
if reply.end == "error":
raise RuntimeError("server_stream_error")
complete = reply.end == "done"
pieces = reply.pieces
first, last = (pieces[0][0], pieces[-1][0]) if pieces else (None, None)
observed = reply.evidence.finish(reply.usage, reply.runtime, complete)
n = observed["tokens"]
span = last - first if first is not None else None
out = {"ttft_s": first - start if complete and first is not None else None, "decode_s": span, **observed,
"decode_tps": (n - 1) / span if complete and n is not None and n > 1 and span else None,
"text": "".join(reply.text), "pieces": pieces, **reply.receipt()}
return {**out, **bench_metrics.request(out), **bench_thinking.receipt(item)}
METRICS = ("prompt_ttft_tps", "prefill_tps", "itl_mean_ms", "itl_p50_ms", "itl_p95_ms", "tpot_ms",
"chunk_tpot_estimate_ms", "round_gap_p50_ms", "round_gap_p95_ms", "tokens_per_chunk",
*bench_stream.BOUNDARIES)
def median(values) -> float | None:
"""The median of the values that are not None, rounded to 3 places; None when there are none."""
got = [v for v in values if v is not None]
return round(statistics.median(got), 3) if got else None
def main() -> None:
p = argparse.ArgumentParser()
p.add_argument("base")
p.add_argument("model")
p.add_argument("--tokens", type=int, default=64)
p.add_argument("--reps", type=int, default=5)
p.add_argument("--temperatures", default="1.0,0")
p.add_argument("--label", default="")
p.add_argument("--output")
p.add_argument("--compare-receipt", metavar="FILE", help="flag rows whose thinking label differs from this receipt")
p.add_argument("--api-key-env", metavar="NAME", help="read the bearer API key from this environment variable")
p.add_argument("--seed-from-prompt", action="store_true",
help="send no seed; requires native serve --prompt-seed to match prompt-keyed engine benches, "
"so the reply equals the bench's and the timings compare directly")
args = p.parse_args()
if args.tokens < 1:
p.error("--tokens must be greater than 0")
if args.reps < 1:
p.error("--reps must be greater than 0")
api_key = read_api_key(p, args.api_key_env)
validate_temperatures(p, args.temperatures)
try:
previous = bench_thinking.load_comparison(args.compare_receipt)
except (OSError, ValueError, TypeError):
p.error("cannot read comparison receipt")
prompts = bench_thinking.configure(PROMPTS, bench_thinking.discover(args.base, args.model, api_key))
results = []
for temp in [float(t) for t in args.temperatures.split(",")]:
for item in prompts:
seeds = [None] * args.reps if args.seed_from_prompt else [1234 + i for i in range(args.reps)]
try:
stream(args.base, args.model, item, args.tokens, temp, seeds[0], api_key=api_key) # warm-up
runs = [stream(args.base, args.model, item, args.tokens, temp, seed, api_key=api_key) for seed in seeds]
except Exception as exc:
p.exit(1, f"benchmark request failed: {type(exc).__name__}\n")
tps = [r["decode_tps"] for r in runs if r["decode_tps"]]
ttfts = [r["ttft_s"] for r in runs if r["ttft_s"] is not None]
row = {"label": args.label, "prompt": item["name"], "temperature": temp, "tokens": args.tokens, **bench_thinking.receipt(item),
"decode_tps_median": statistics.median(tps) if tps else None, "decode_tps_all": [round(x, 2) for x in tps],
"ttft_s_median": statistics.median(ttfts) if ttfts else None,
**{k + "_median": median(r[k] for r in runs) for k in METRICS},
"evidence": [{k: r[k] for k in ("prompt_tokens", "cached_tokens", "tokens", "cache_state",
"complete", "token_sha", "output_sha256", "completion", "tool_sha256")} for r in runs],
"sample": redact(runs[0]["text"], api_key)[:160], "deprecated_keys": bench_metrics.NOTE}
row = bench_thinking.comparison(redact(row, api_key), previous)
shown = ("label", "prompt", "temperature", "thinking", "thinking_off_requested", "decode_tps_median", "decode_tps_all", "ttft_s_median",
*(k + "_median" for k in METRICS))
print(json.dumps({**{k: row[k] for k in shown}, **{k: row[k] for k in ("thinking_comparable", "comparison_warning", "comparison_thinking") if k in row}}), flush=True)
results.append(row)
if args.output:
with open(args.output, "w") as f:
json.dump(results, f, indent=1)
if __name__ == "__main__":
main()