Download serving/loadtest_rivinity.py from RANITBAG/on_the_way: direct link, hf CLI and curl.
- Browser
- Download file 9.84 kB
-
https://huggingface.co/RANITBAG/on_the_way/resolve/main/serving/loadtest_rivinity.py
- Command line
-
hf download hf://RANITBAG/on_the_way/serving/loadtest_rivinity.py
-
curl -L -o loadtest_rivinity.py https://huggingface.co/RANITBAG/on_the_way/resolve/main/serving/loadtest_rivinity.py
9.84 kB
| #!/usr/bin/env python3 | |
| """loadtest_rivinity.py -- measure llama-server OpenAI-compatible serving. | |
| Stdlib-only (urllib + threading). Per request: time-to-first-token (TTFT), | |
| decode tokens/sec, end-to-end latency; aggregate p50/p95; concurrent | |
| throughput; prompt-processing rate via max_tokens=1 probes; optional RSS | |
| memory (psutil, else /proc, else skipped). | |
| Nothing is assumed: every number in the report comes from this run on this | |
| machine (Phase-9 task 7/10). | |
| Usage: | |
| python serving/loadtest_rivinity.py --base-url http://127.0.0.1:8080 \ | |
| --model rivinity --requests 16 --concurrency 1,4 --json-out reports/load.json | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import statistics | |
| import threading | |
| import time | |
| import urllib.request | |
| from urllib.error import HTTPError, URLError | |
| def percentile(sorted_vals, p: float): | |
| """p in [0,100] on pre-sorted data (linear interpolation).""" | |
| if not sorted_vals: | |
| return None | |
| k = (len(sorted_vals) - 1) * (p / 100.0) | |
| lo = int(k) | |
| hi = min(lo + 1, len(sorted_vals) - 1) | |
| return sorted_vals[lo] + (sorted_vals[hi] - sorted_vals[lo]) * (k - lo) | |
| def sse_json_events(line_stream): | |
| """Yield parsed objects from an OpenAI-style SSE byte stream (file-like, | |
| iterating lines). Blank lines and non-data lines are skipped.""" | |
| for raw in line_stream: | |
| line = raw.decode("utf-8", "replace").strip() if isinstance(raw, bytes) else raw.strip() | |
| if not line.startswith("data:"): | |
| continue | |
| payload = line[5:].strip() | |
| if payload == "[DONE]": | |
| return | |
| try: | |
| yield json.loads(payload) | |
| except json.JSONDecodeError: | |
| continue | |
| def summarize(records) -> dict: | |
| """records: list of per-request dicts from run_request(). Pure function.""" | |
| ok = [r for r in records if r.get("ok")] | |
| out = {"requests": len(records), "ok": len(ok), | |
| "errors": len(records) - len(ok)} | |
| if not ok: | |
| return out | |
| def stat(key, scale=1.0): | |
| vals = sorted(r[key] * scale for r in ok if r.get(key) is not None) | |
| if not vals: | |
| return None | |
| return {"mean": round(statistics.fmean(vals), 4), | |
| "p50": round(percentile(vals, 50), 4), | |
| "p95": round(percentile(vals, 95), 4), | |
| "min": round(vals[0], 4), "max": round(vals[-1], 4)} | |
| out["ttft_s"] = stat("ttft_s") | |
| out["latency_s"] = stat("latency_s") | |
| out["decode_tok_per_s"] = stat("decode_tok_per_s") | |
| out["completion_tokens_mean"] = round( | |
| statistics.fmean(r["completion_tokens"] for r in ok), 2) | |
| wall = sum(r["latency_s"] for r in ok) | |
| out["aggregate_decode_tok_per_s"] = round( | |
| sum(r["completion_tokens"] for r in ok) / wall, 4) if wall > 0 else None | |
| return out | |
| def run_request(base_url, headers, payload, timeout_s) -> dict: | |
| """One streaming chat completion; returns a metric record.""" | |
| rec = {"ok": False, "ttft_s": None, "decode_tok_per_s": None, | |
| "latency_s": None, "completion_tokens": 0, "prompt_tokens": None, | |
| "error": None} | |
| req = urllib.request.Request(base_url.rstrip("/") + "/v1/chat/completions", | |
| data=json.dumps(payload).encode("utf-8"), | |
| headers={**headers, "Content-Type": "application/json"}, | |
| method="POST") | |
| t0 = time.perf_counter() | |
| try: | |
| if not payload.get("stream", False): | |
| with urllib.request.urlopen(req, timeout=timeout_s) as resp: | |
| body = json.loads(resp.read().decode("utf-8")) | |
| usage = body.get("usage") or {} | |
| rec["latency_s"] = time.perf_counter() - t0 | |
| rec["ttft_s"] = rec["latency_s"] | |
| rec["prompt_tokens"] = usage.get("prompt_tokens") | |
| rec["completion_tokens"] = usage.get("completion_tokens") or 0 | |
| rec["ok"] = True | |
| return rec | |
| with urllib.request.urlopen(req, timeout=timeout_s) as resp: | |
| first = True | |
| n_chunks = 0 | |
| for ev in sse_json_events(resp): | |
| if ev.get("usage"): | |
| rec["prompt_tokens"] = ev["usage"].get("prompt_tokens") | |
| rec["completion_tokens"] = ev["usage"].get("completion_tokens") or n_chunks | |
| continue | |
| choices = ev.get("choices") or [] | |
| if choices and (choices[0].get("delta", {}).get("content") | |
| or choices[0].get("text")): | |
| n_chunks += 1 | |
| if first: | |
| rec["ttft_s"] = time.perf_counter() - t0 | |
| first = False | |
| rec["latency_s"] = time.perf_counter() - t0 | |
| if rec["completion_tokens"] == 0: | |
| rec["completion_tokens"] = n_chunks | |
| decode_t = rec["latency_s"] - (rec["ttft_s"] or 0.0) | |
| if rec["completion_tokens"] > 1 and decode_t > 0: | |
| rec["decode_tok_per_s"] = (rec["completion_tokens"] - 1) / decode_t | |
| rec["ok"] = True | |
| except (HTTPError, URLError, TimeoutError, OSError) as exc: | |
| rec["error"] = f"{type(exc).__name__}: {exc}" | |
| rec["latency_s"] = time.perf_counter() - t0 | |
| return rec | |
| def rss_bytes(pid) -> int | None: | |
| """Process RSS via psutil or /proc; None when unavailable (no fabrication).""" | |
| try: | |
| import psutil # optional dependency | |
| return psutil.Process(pid).memory_info().rss | |
| except Exception: | |
| pass | |
| try: | |
| for line in open(f"/proc/{pid}/status", encoding="utf-8"): | |
| if line.startswith("VmRSS:"): | |
| return int(line.split()[1]) * 1024 | |
| except OSError: | |
| return None | |
| return None | |
| def _worker(base_url, headers, payload, timeout_s, records, lock, counter, total): | |
| while True: | |
| with lock: | |
| if counter[0] >= total: | |
| return | |
| counter[0] += 1 | |
| rec = run_request(base_url, headers, payload, timeout_s) | |
| with lock: | |
| records.append(rec) | |
| def memory_note(args) -> str: | |
| if args.memory_pid is None: | |
| return "memory: not requested (use --memory-pid to enable)" | |
| rss = rss_bytes(args.memory_pid) | |
| if rss is None: | |
| return "memory: unavailable (install psutil or run on Linux /proc)" | |
| return f"memory: server RSS ~{rss / 1e6:.0f} MB (pid {args.memory_pid})" | |
| def main(argv=None) -> int: | |
| p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| p.add_argument("--base-url", default="http://127.0.0.1:8080") | |
| p.add_argument("--model", default="rivinity") | |
| p.add_argument("--api-key-env", default=None) | |
| p.add_argument("--requests", type=int, default=16) | |
| p.add_argument("--concurrency", default="1,4", | |
| help="comma-separated concurrency levels to sweep") | |
| p.add_argument("--max-tokens", type=int, default=64) | |
| p.add_argument("--prompt", default="Explain quantization-aware training in three sentences.") | |
| p.add_argument("--timeout", type=float, default=180.0) | |
| p.add_argument("--memory-pid", type=int, default=None, | |
| help="llama-server pid for RSS sampling (optional)") | |
| p.add_argument("--json-out", type=str, default=None) | |
| args = p.parse_args(argv) | |
| headers = {} | |
| if args.api_key_env: | |
| import os | |
| key = os.environ.get(args.api_key_env) | |
| if not key: | |
| print(f"WARNING: env {args.api_key_env} not set; proceeding without key") | |
| else: | |
| headers["Authorization"] = f"Bearer {key}" | |
| payload = {"model": args.model, | |
| "messages": [{"role": "user", "content": args.prompt}], | |
| "max_tokens": args.max_tokens, "temperature": 0, | |
| "stream": True, "stream_options": {"include_usage": True}} | |
| # prefill probe: one max_tokens=1 request -> prompt tokens / TTFT | |
| probe = run_request(args.base_url, headers, | |
| {**payload, "max_tokens": 1, "stream": False}, args.timeout) | |
| prefill = None | |
| if probe["ok"] and probe.get("prompt_tokens") and probe.get("latency_s"): | |
| prefill = round(probe["prompt_tokens"] / probe["latency_s"], 4) | |
| elif not probe["ok"]: | |
| print(f"ERROR: server unreachable or error on probe: {probe['error']}") | |
| print("start the server first (serving/start_rivinity_server.bat)") | |
| return 2 | |
| report = {"base_url": args.base_url, "model": args.model, | |
| "prompt": args.prompt, "max_tokens": args.max_tokens, | |
| "prompt_tokens": probe.get("prompt_tokens"), | |
| "prompt_tok_per_s_prefill_probe": prefill, | |
| "levels": {}} | |
| for level in [int(x) for x in args.concurrency.split(",") if x.strip()]: | |
| records, lock, counter = [], threading.Lock(), [0] | |
| wall0 = time.perf_counter() | |
| threads = [threading.Thread(target=_worker, args=( | |
| args.base_url, headers, payload, args.timeout, | |
| records, lock, counter, args.requests)) for _ in range(level)] | |
| for t in threads: | |
| t.start() | |
| for t in threads: | |
| t.join() | |
| wall = time.perf_counter() - wall0 | |
| summary = summarize(records) | |
| ok = summary.get("ok", 0) | |
| summary["wall_s"] = round(wall, 4) | |
| summary["throughput_req_per_s"] = round(ok / wall, 4) if wall > 0 else None | |
| report["levels"][str(level)] = summary | |
| report["memory_note"] = memory_note(args) | |
| text = json.dumps(report, indent=2, sort_keys=True) | |
| print(text) | |
| if args.json_out: | |
| from pathlib import Path | |
| Path(args.json_out).parent.mkdir(parents=True, exist_ok=True) | |
| Path(args.json_out).write_text(text + "\n", encoding="utf-8") | |
| print(f"report -> {args.json_out}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |