Datasets:
File size: 11,874 Bytes
9bd0d59 64bb357 7521d9e 9bd0d59 7b16592 9bd0d59 64bb357 7b16592 92088c4 9bd0d59 7521d9e 92088c4 9bd0d59 7b16592 64bb357 5dbfa46 9bd0d59 7b16592 9bd0d59 7b16592 9bd0d59 7b16592 9bd0d59 64bb357 9bd0d59 7b16592 9bd0d59 5dbfa46 9bd0d59 64bb357 9bd0d59 7b16592 9bd0d59 27ec80d 9bd0d59 27ec80d 9bd0d59 64bb357 9bd0d59 7b16592 64bb357 7b16592 64bb357 9bd0d59 27ec80d 9bd0d59 7b16592 64bb357 7b16592 9bd0d59 64bb357 9bd0d59 64bb357 9bd0d59 7b16592 9bd0d59 64bb357 9bd0d59 64bb357 | 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 | #!/usr/bin/env python3
# llm-serving-bench v3.3: single-stream serving speed of any OpenAI-compatible server (stdlib only, greedy, streamed, timed on the wire).
# Prompts come from the HF dataset Francesco/llm-serving-bench (pinned revision), downloaded once into a cache folder:
# short 60 prompts: Spec-Bench (6 tasks x 10, first turn) code 20 prompts: HumanEval 0-19
# long LongBench v2, one Code Repository Understanding question, repository cut from the middle to fill each window.
# Request 1 times the prefill; request 2 continues the chat and times decode at that depth.
# Before timing it warms up: one short request and one ~4K-token prompt, untimed.
# python3 bench.py --url http://127.0.0.1:8003/v1 --out result.json [--windows 32K,224K,512K] [--short-only] [--label "3090 A on"]
import argparse, json, os, re, statistics, subprocess, time, urllib.error, urllib.request
from pathlib import Path
DATASET, REVISION = "Francesco/llm-serving-bench", "v3.3"
FILES = ("short.jsonl", "code.jsonl", "agent.jsonl", "long.jsonl")
WINDOWS = {"4K": 4_096, "8K": 8_192, "16K": 16_384, "32K": 32_768, "224K": 229_376, "512K": 512_000}
ap = argparse.ArgumentParser()
ap.add_argument("--url", default="http://127.0.0.1:8003/v1")
ap.add_argument("--out", default="llm-serving-bench-result.json")
ap.add_argument("--cache", default=os.environ.get("LLM_SERVING_BENCH_CACHE", str(Path.home() / ".cache" / "llm-serving-bench")))
ap.add_argument("--windows", default="4K,8K,16K,32K,224K,512K")
ap.add_argument("--short-only", action="store_true")
ap.add_argument("--label", default="")
ap.add_argument("--temperature", type=float, default=0.0, help="0 (default): greedy, repeatable; 1: as most models are served (speculative decoding accepts less)")
ap.add_argument("--repeat", type=int, default=3, help="runs of each long window up to 32K; mean and standard deviation are reported")
ap.add_argument("--repeat-long", type=int, default=1, help="runs of the 224K and 512K windows (each costs 30 s to minutes)")
ap.add_argument("--limit", type=int, default=0, help="first N prompts of each short set (smoke test); 0 = all")
args = ap.parse_args()
URL, CACHE = args.url.rstrip("/"), Path(args.cache)
# [Agent] Download each file once; later runs read the cache, so the timed part never touches the network.
CACHE.mkdir(parents=True, exist_ok=True)
for name in FILES:
if not (CACHE / name).exists():
with urllib.request.urlopen(f"https://huggingface.co/datasets/{DATASET}/resolve/{REVISION}/{name}") as r:
(CACHE / (name + ".part")).write_bytes(r.read())
(CACHE / (name + ".part")).rename(CACHE / name)
rows = lambda name: [json.loads(l) for l in open(CACHE / name)]
def ask(messages, max_tokens):
body = json.dumps({"model": MODEL, "messages": messages, "max_tokens": max_tokens, "temperature": args.temperature, "stream": True,
"stream_options": {"include_usage": True}}).encode()
req = urllib.request.Request(f"{URL}/chat/completions", body, {"Content-Type": "application/json"})
t0, first, last, text, usage = time.time(), None, None, "", {}
with urllib.request.urlopen(req, timeout=3600) as r:
for raw in r:
line = raw.decode().strip()
if not line.startswith("data:") or line == "data: [DONE]":
continue
chunk = json.loads(line[5:])
usage = chunk.get("usage") or usage
for c in chunk.get("choices", []):
d = c.get("delta", {})
piece = (d.get("content") or "") + (d.get("reasoning_content") or "") + (d.get("reasoning") or "")
if piece:
first = first or time.time()
last = time.time()
text += d.get("content") or ""
n, p = usage.get("completion_tokens", 0), usage.get("prompt_tokens", 0)
ttft = (first or time.time()) - t0
decode = (n - 1) / (last - first) if first and last and last > first and n > 1 else None
return {"prompt": p, "out": n, "ttft": round(ttft, 3), "decode": decode and round(decode, 1), "text": text}
def rate(rs): # token-weighted decode speed: all tokens after the first over all decode seconds
rs = [r for r in rs if r["decode"]]
return round(sum(r["out"] - 1 for r in rs) / sum((r["out"] - 1) / r["decode"] for r in rs), 1) if rs else None
def long_prompt(s, budget_chars):
ctx = s["context"]
if len(ctx) > budget_chars: # LongBench's truncation: keep the start and the end, cut the middle
ctx = ctx[: budget_chars // 2] + ctx[-budget_chars // 2:]
choices = "".join(f"\n({k}) {v}" for k, v in s["choices"].items())
return ("Please read the following text and answer the question below.\n\n<text>\n" + ctx + "\n</text>\n\n"
f"What is the correct answer to this question: {s['question']}\nChoices:{choices}\n\n"
"Format your response as follows: \"The correct answer is (insert answer here)\".")
def gpu():
try:
return subprocess.run(["nvidia-smi", "--query-gpu=name,clocks.sm,power.limit,temperature.gpu", "--format=csv,noheader"],
capture_output=True, text=True, timeout=10).stdout.strip()
except Exception:
return ""
info = json.load(urllib.request.urlopen(f"{URL}/models"))
MODEL = (info.get("data") or [{}])[0].get("id", "default") # [Agent] vLLM wants the served model name in every request
max_len = max((m.get("max_model_len") or 0) for m in info.get("data", [{}])) or None
long_row = rows("long.jsonl")[0]
res = {"bench": "llm-serving-bench v3.3", "dataset": f"{DATASET}@{REVISION}", "label": args.label, "url": URL, "server": info,
"date": time.strftime("%Y-%m-%d %H:%M"), "short": {}, "long": {}}
ask([{"role": "user", "content": "Say hi."}], 8) # warm-up 1
probe = ask([{"role": "user", "content": long_prompt(long_row, 12_000)}], 8) # warm-up 2: ~4K tokens
# [Agent] Tokens per character from two prompt sizes: the difference cancels the template and question tokens, so the cut fills the window (one probe alone left it ~6 % short).
small = ask([{"role": "user", "content": long_prompt(long_row, 4_000)}], 1)
per_char = (probe["prompt"] - small["prompt"]) / 8_000
print(f"warm-up done ({probe['prompt']} tokens in the 4K prompt)", flush=True)
by_cat = {}
for r in rows("short.jsonl") + rows("code.jsonl"):
by_cat.setdefault(r["category"], []).append(r)
if args.limit:
by_cat = {c: rs[: args.limit] for c, rs in by_cat.items()}
for cat, rs in by_cat.items():
out = [ask([{"role": "user", "content": r["prompt"]}], r["max_tokens"]) for r in rs]
ttfts = sorted(o["ttft"] for o in out)
res["short"][cat] = {"decode_tok_s": rate(out), "ttft_median_s": round(statistics.median(ttfts), 3),
"ttft_p90_s": round(ttfts[min(len(ttfts) - 1, int(0.9 * len(ttfts)))], 3),
"rows": [{k: v for k, v in o.items() if k != "text"} for o in out]}
print(f"{cat:18s} decode {res['short'][cat]['decode_tok_s']} tok/s", flush=True)
res["short_all_decode_tok_s"] = rate([o for c in res["short"].values() for o in c["rows"]])
# [Agent] Agent sessions: each user turn (system prompt, issue, then tool outputs) is sent with the recorded agent replies before it,
# as a coding agent resends its conversation; a server that keeps the previous turn's cache only reads what is new.
res["agent"] = []
for s_ in rows("agent.jsonl")[: args.limit or None]:
turns = [i for i, m in enumerate(s_["messages"]) if m["role"] == "user"]
res["agent"].append([{k: v for k, v in ask(s_["messages"][: i + 1], s_["max_tokens"]).items() if k != "text"} for i in turns])
agent_turns = [o for session in res["agent"] for o in session]
res["agent_decode_tok_s"] = rate(agent_turns)
res["agent_followup_ttft_median_s"] = round(statistics.median(o["ttft"] for session in res["agent"] for o in session[1:]), 3)
print(f"agent sessions decode {res['agent_decode_tok_s']} tok/s, follow-up TTFT {res['agent_followup_ttft_median_s']} s", flush=True)
if not args.short_only:
for name in args.windows.split(","):
window = WINDOWS[name]
key = "512K (512,000)" if name == "512K" else name
if max_len and window > max_len:
res["long"][key] = "does not fit"
continue
prompt = long_prompt(long_row, int((window - 2_048) / per_char))
n_runs = args.repeat if window <= 32_768 else args.repeat_long
try:
runs = []
for i in range(n_runs):
# [Agent] A tag in front makes every run a new prompt, so no run is served from another run's prefix cache.
msgs = [{"role": "user", "content": f"[run {i + 1} of {n_runs}]\n" + prompt}]
a = ask(msgs, long_row["max_tokens"])
b = ask(msgs + [{"role": "assistant", "content": a["text"]}, {"role": "user", "content": "Explain your answer step by step."}],
long_row["max_tokens"])
runs.append((a, b))
r1, r2 = runs[0]
except urllib.error.HTTPError as e: # the server refuses a prompt longer than its context
res["long"][key] = f"does not fit ({e.code})"
continue
except Exception as e: # [Agent] a server that crashes or hangs up on a long prompt is a result, not a script error
res["long"][key] = f"failed ({type(e).__name__}: {str(e)[:80]})"
print(f"long {key}: {res['long'][key]}", flush=True)
continue
m = re.search(r"correct answer is \(?([A-D])\)?", r1["text"]) # [Agent] score only when an answer letter is there; a model still thinking at max_tokens has none
letter = m.group(1) if m else None
pre = [a["prompt"] / a["ttft"] for a, _ in runs]
dec = [b["decode"] for _, b in runs if b["decode"]]
sd = lambda xs: round(statistics.stdev(xs), 1) if len(xs) > 1 else 0.0
res["long"][key] = {"prompt_tokens": r1["prompt"], "runs": len(runs), "prefill_tok_s": round(statistics.mean(pre), 1),
"prefill_std": sd(pre), "ttft_s": round(statistics.mean(a["ttft"] for a, _ in runs), 3),
"decode_at_depth_tok_s": dec and round(statistics.mean(dec), 1), "decode_std": sd(dec),
"followup_ttft_s": round(statistics.mean(b["ttft"] for _, b in runs), 3),
"answer": letter or f"no answer within {long_row['max_tokens']} tokens",
"correct": None if letter is None else letter == long_row["answer"], "answer_text": r1["text"][:300]}
print(f"long {key}: {res['long'][key]}", flush=True)
res["gpu_end"] = gpu()
json.dump(res, open(args.out, "w"), indent=1)
print(f"\n**llm-serving-bench v3.3** {args.label} ({res['date']}, GPU {res['gpu_end']})\n")
print("| set | decode tok/s | TTFT s, median / p90 |\n|---|---|---|")
for c, v in res["short"].items():
print(f"| {c} | {v['decode_tok_s']} | {v['ttft_median_s']} / {v['ttft_p90_s']} |")
print(f"| **all short+code** | **{res['short_all_decode_tok_s']}** | |")
print(f"| agent sessions ({len(agent_turns)} turns) | {res['agent_decode_tok_s']} | {res['agent_followup_ttft_median_s']} (follow-ups) |")
if res["long"]:
print("\n| window | prompt tokens | runs | prefill tok/s (mean ± sd) | TTFT s | decode at depth tok/s (mean ± sd) | answer |\n|---|---|---|---|---|---|---|")
for w, v in res["long"].items():
if not isinstance(v, dict):
print(f"| {w} | {v} | | | | | |")
continue
verdict = "" if v["correct"] is None else (" ok" if v["correct"] else " wrong")
print(f"| {w} | {v['prompt_tokens']} | {v['runs']} | {v['prefill_tok_s']} ± {v['prefill_std']} | {v['ttft_s']} | "
f"{v['decode_at_depth_tok_s']} ± {v['decode_std']} | {v['answer']}{verdict} |")
|