Download tools/bench.py from RightNowAI/RightNow-Mini: direct link, hf CLI and curl.
- Browser
- Download file 9.62 kB
-
https://huggingface.co/RightNowAI/RightNow-Mini/resolve/main/tools/bench.py
- Command line
-
hf download hf://RightNowAI/RightNow-Mini/tools/bench.py
-
curl -L -o bench.py https://huggingface.co/RightNowAI/RightNow-Mini/resolve/main/tools/bench.py
9.62 kB
| """Speed of one OpenAI-compatible endpoint, measured the same way for every engine. | |
| python tools/bench.py --url http://127.0.0.1:9000 --model inkling-2-mini --label vllm-plain --out results/raw/speed | |
| Measures, with greedy decoding on fixed coding prompts: | |
| single stream : time to first token, output tokens per second after the first token | |
| concurrency : the same at 8, 32 and 64 streams at once (per stream and summed) | |
| prefill : prompt tokens per second for prompts of about 4K and 64K tokens (max_tokens=1) | |
| Token counts come from the server's own usage report. Nothing is estimated: a failed request is counted as failed. | |
| """ | |
| import argparse | |
| import asyncio | |
| import glob | |
| import json | |
| import statistics | |
| import time | |
| import uuid | |
| import aiohttp | |
| TOPICS = [ | |
| "an LRU cache with O(1) get and put", "a trie with insert, search and prefix counting", "Dijkstra's shortest path with a binary heap", | |
| "a thread-safe bounded queue", "a tokenizer for arithmetic expressions and a recursive descent parser for them", | |
| "a rate limiter using the token bucket algorithm", "an interval tree with overlap queries", "a union-find structure with path compression", | |
| "a streaming median with two heaps", "topological sort with cycle detection", "a binary search over a rotated sorted array", | |
| "a least-squares line fit without numpy", "a retry decorator with exponential backoff and jitter", "a diff of two text files, line by line", | |
| "an async worker pool with a concurrency limit", "a Bloom filter with a configurable false positive rate", | |
| ] | |
| ASKS = [ | |
| "Write a complete, tested Python implementation of {t}. Explain the design first, then give the code and five unit tests.", | |
| "Review the idea of implementing {t} in Python. List the edge cases, then write the code with type hints and docstrings.", | |
| "Implement {t} in Python, then walk through its time and space complexity step by step and show a usage example.", | |
| "Write {t} in Python as a small module with a command line entry point, input validation and clear error messages.", | |
| ] | |
| PROMPTS = [a.format(t=t) for t in TOPICS for a in ASKS] # 64 fixed prompts | |
| def long_prompt(target_tokens, salt): | |
| """Real source text of about target_tokens tokens. The salt at the start defeats prefix caching.""" | |
| budget = int(target_tokens * 3.3) | |
| parts, size = [], 0 | |
| for p in sorted(glob.glob("/usr/lib/python3*/*.py")): | |
| try: | |
| t = open(p, encoding="utf-8", errors="ignore").read() | |
| except OSError: | |
| continue | |
| parts.append(f"# file: {p}\n{t}\n") | |
| size += len(parts[-1]) | |
| if size >= budget: | |
| break | |
| return f"Run id {salt}. Below is source code. After it, answer with the single word: done.\n\n" + "".join(parts)[:budget] + "\n\nAnswer now." | |
| async def one(session, url, model, prompt, max_tokens, extra): | |
| body = {"model": model, "messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens, "temperature": 0, | |
| "stream": True, "stream_options": {"include_usage": True}} | |
| body.update(extra) | |
| t0 = time.perf_counter() | |
| first = last = None | |
| usage = None | |
| chunks = 0 | |
| try: | |
| async with session.post(url + "/v1/chat/completions", json=body) as r: | |
| if r.status != 200: | |
| return {"ok": False, "status": r.status, "error": (await r.text())[:200]} | |
| async for raw in r.content: | |
| line = raw.decode("utf-8", "ignore").strip() | |
| if not line.startswith("data:"): | |
| continue | |
| data = line[5:].strip() | |
| if data == "[DONE]": | |
| break | |
| d = json.loads(data) | |
| if d.get("usage"): | |
| usage = d["usage"] | |
| for c in d.get("choices") or []: | |
| delta = c.get("delta") or {} | |
| if any(delta.get(k) for k in ("content", "reasoning_content", "reasoning", "tool_calls")): | |
| now = time.perf_counter() | |
| first = first or now | |
| last = now | |
| chunks += 1 | |
| except Exception as e: | |
| return {"ok": False, "status": "exception", "error": f"{type(e).__name__}: {e}"[:200]} | |
| if not usage or first is None: | |
| return {"ok": False, "status": "no_usage_or_no_token", "chunks": chunks} | |
| out = usage.get("completion_tokens", 0) | |
| return {"ok": True, "ttft": first - t0, "total": last - t0, "out": out, "in": usage.get("prompt_tokens", 0), | |
| "decode_tps": (out - 1) / (last - first) if out > 1 and last > first else None, "chunks": chunks} | |
| async def prefill_one(session, url, model, prompt, extra): | |
| """One long prompt, one output token, not streamed: the whole request time is the prefill (plus one token).""" | |
| body = {"model": model, "messages": [{"role": "user", "content": prompt}], "max_tokens": 1, "temperature": 0} | |
| body.update(extra) | |
| t0 = time.perf_counter() | |
| try: | |
| async with session.post(url + "/v1/chat/completions", json=body) as r: | |
| if r.status != 200: | |
| return {"ok": False, "status": r.status, "error": (await r.text())[:200]} | |
| d = await r.json() | |
| except Exception as e: | |
| return {"ok": False, "status": "exception", "error": f"{type(e).__name__}: {e}"[:200]} | |
| u = d.get("usage") or {} | |
| if not u.get("prompt_tokens"): | |
| return {"ok": False, "status": "no_usage"} | |
| cached = ((u.get("prompt_tokens_details") or {}).get("cached_tokens")) or 0 | |
| return {"ok": True, "ttft": time.perf_counter() - t0, "in": u["prompt_tokens"], "cached": cached} | |
| def summarize(rs, wall): | |
| ok = [r for r in rs if r.get("ok")] | |
| tps = [r["decode_tps"] for r in ok if r["decode_tps"]] | |
| ttft = sorted(r["ttft"] for r in ok) | |
| pct = lambda xs, p: xs[min(len(xs) - 1, int(round(p * (len(xs) - 1))))] if xs else None | |
| return {"requests": len(rs), "ok": len(ok), "failed": len(rs) - len(ok), | |
| "errors": sorted({str(r.get("status")) + ":" + str(r.get("error", ""))[:80] for r in rs if not r.get("ok")})[:3], | |
| "out_tokens": sum(r["out"] for r in ok), "wall_s": round(wall, 3), | |
| "sum_out_tps": round(sum(r["out"] for r in ok) / wall, 1) if wall else None, | |
| "per_stream_decode_tps_median": round(statistics.median(tps), 1) if tps else None, | |
| "per_stream_decode_tps_min": round(min(tps), 1) if tps else None, | |
| "ttft_ms_median": round(pct(ttft, 0.5) * 1000, 1) if ttft else None, | |
| "ttft_ms_p90": round(pct(ttft, 0.9) * 1000, 1) if ttft else None} | |
| async def run_level(session, a, conc, n, max_tokens, extra): | |
| sem = asyncio.Semaphore(conc) | |
| prompts = [PROMPTS[i % len(PROMPTS)] for i in range(n)] | |
| async def guarded(p): | |
| async with sem: | |
| return await one(session, a.url, a.model, p, max_tokens, extra) | |
| t0 = time.perf_counter() | |
| rs = await asyncio.gather(*[guarded(p) for p in prompts]) | |
| return summarize(rs, time.perf_counter() - t0), rs | |
| async def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--url", required=True) | |
| ap.add_argument("--model", required=True) | |
| ap.add_argument("--label", required=True) | |
| ap.add_argument("--out", default="results/raw/speed") | |
| ap.add_argument("--max-tokens", type=int, default=512) | |
| ap.add_argument("--levels", default="1,8,32,64") | |
| ap.add_argument("--prefill", default="4000,64000") | |
| ap.add_argument("--extra", default="{}", help="JSON merged into every request body") | |
| a = ap.parse_args() | |
| extra = json.loads(a.extra) | |
| res = {"label": a.label, "url": a.url, "model": a.model, "max_tokens": a.max_tokens, "temperature": 0, | |
| "prompts": len(PROMPTS), "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "extra": extra, "levels": {}, "prefill": {}} | |
| timeout = aiohttp.ClientTimeout(total=3600, sock_read=1800) | |
| async with aiohttp.ClientSession(timeout=timeout, connector=aiohttp.TCPConnector(limit=0)) as s: | |
| await run_level(s, a, 1, 2, 64, extra) # warm-up, not recorded | |
| for conc in [int(x) for x in a.levels.split(",") if x]: | |
| n = 16 if conc == 1 else max(2 * conc, 32) | |
| summary, rs = await run_level(s, a, conc, n, a.max_tokens, extra) | |
| res["levels"][str(conc)] = summary | |
| print(a.label, "concurrency", conc, json.dumps(summary), flush=True) | |
| for target in [int(x) for x in a.prefill.split(",") if x]: | |
| reps = [] | |
| for _ in range(3): | |
| r = await prefill_one(s, a.url, a.model, long_prompt(target, uuid.uuid4().hex), extra) | |
| reps.append(r) | |
| ok = [r for r in reps if r.get("ok")] | |
| res["prefill"][str(target)] = { | |
| "reps": len(reps), "ok": len(ok), "prompt_tokens": [r["in"] for r in ok], | |
| "cached_tokens": [r["cached"] for r in ok], | |
| "request_s": [round(r["ttft"], 3) for r in ok], | |
| "prefill_tps_median": round(statistics.median(r["in"] / r["ttft"] for r in ok), 1) if ok else None, | |
| "errors": [str(r.get("status")) + ":" + str(r.get("error", ""))[:120] for r in reps if not r.get("ok")][:2]} | |
| print(a.label, "prefill", target, json.dumps(res["prefill"][str(target)]), flush=True) | |
| import os | |
| os.makedirs(a.out, exist_ok=True) | |
| with open(f"{a.out}/{a.label}.json", "w", encoding="utf-8") as f: | |
| json.dump(res, f, indent=1) | |
| print("wrote", f"{a.out}/{a.label}.json") | |
| if __name__ == "__main__": | |
| asyncio.run(main()) | |