Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(bench): schedule fixed-rate arrivals and account for client backlog
ZacharyZcRdf6cf53aa72f
diff --git a/c/tests/test_benchmark_http_serving.py b/c/tests/test_benchmark_http_serving.pyindex 117b10d4..14626279 100644--- a/c/tests/test_benchmark_http_serving.py+++ b/c/tests/test_benchmark_http_serving.py@@ -8,6 +8,8 @@ import tempfileimport threadingimport timeimport unittest+from unittest.mock import patch+from concurrent.futures import Futurefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom tools import benchmark_http_serving as benchfrom openai_server import APIServer@@ -42,6 +44,7 @@ class Handler(BaseHTTPRequestHandler):try:if self.server.barrier:self.server.barrier.wait(timeout=5)+ time.sleep(self.server.delay)self.send_response(self.server.status)self.send_header("Content-Type", self.server.content_type)if self.server.status == 302:@@ -63,6 +66,7 @@ class BenchmarkTest(unittest.TestCase):self.server.content_type = "text/event-stream"self.server.body = stream({"content": "hello"})self.server.barrier = None+ self.server.delay = 0self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": .01})self.thread.start()self.url = f"http://127.0.0.1:{self.server.server_port}/v1/chat/completions"@@ -145,6 +149,21 @@ class BenchmarkTest(unittest.TestCase):stream_options={"include_usage": True}, max_tokens=8,temperature=0, n=1))+ def test_fixed_rate_keeps_client_wait_visible(self):+ self.server.delay = .04+ rows, summary = bench.run(self.url, self.workload, "fixture", 1, 3, 8, 0, "", 2,+ request_rate=1000)+ self.assertEqual(summary["succeeded"], 3)+ self.assertEqual(self.server.peak, 1)+ self.assertEqual([r["scheduled_seconds"] for r in rows], [0, .001, .002])+ self.assertGreater(rows[-1]["dispatch_delay_seconds"], .05)+ for row in rows:+ self.assertAlmostEqual(row["arrival_duration_seconds"],+ row["duration_seconds"] + row["dispatch_delay_seconds"])+ self.assertAlmostEqual(row["arrival_first_output_seconds"],+ row["first_output_seconds"] + row["dispatch_delay_seconds"])+ self.assertEqual(summary["arrival_timing"]["dispatch_delay_seconds"]["count"], 3)+def test_cli_report_and_failure_exit(self):with tempfile.TemporaryDirectory() as directory:workload = Path(directory) / "prompts.jsonl"@@ -152,7 +171,7 @@ class BenchmarkTest(unittest.TestCase):workload.write_text(json.dumps(self.workload[0]) + "\n", encoding="utf-8")command = [sys.executable, bench.__file__, "--base-url", self.url.rsplit("/", 1)[0],"--model", "fixture", "--workload", str(workload), "--output", str(output),- "--slo-first-output", "5", "--slo-duration", "5"]+ "--slo-first-output", "5", "--slo-duration", "5", "--request-rate", "10"]for status, exit_code in ((200, 0), (503, 1)):self.server.status = statuscompleted = subprocess.run(command, capture_output=True, text=True, timeout=10)@@ -162,6 +181,9 @@ class BenchmarkTest(unittest.TestCase):self.assertEqual(len(report["config"]["workload_sha256"]), 64)self.assertNotIn("messages", report["config"])self.assertEqual(report["config"]["slo_duration_seconds"], 5)+ self.assertEqual(report["config"]["load_model"], "fixed_rate")+ self.assertEqual(report["config"]["request_rate"], 10)+ self.assertEqual(report["summary"]["latency_slo"]["timing_basis"], "scheduled_arrival")self.assertEqual(report["summary"]["latency_slo"]["requests_met"], 1 - exit_code)@@ -234,6 +256,47 @@ class ParsingTest(unittest.TestCase):self.assertEqual(slo["requests_met"], 0)self.assertEqual(slo["goodput_requests_per_second"], 0)+ def test_fixed_rate_slo_includes_client_backlog(self):+ row = {"success": True, "first_output_seconds": .1, "duration_seconds": .2,+ "completion_tokens": None, "scheduled_seconds": 0,+ "dispatch_delay_seconds": 2, "arrival_first_output_seconds": 2.1,+ "arrival_duration_seconds": 2.2}+ summary = bench.summarize([row], 3, slo_first_output=1, slo_duration=1)+ self.assertEqual(summary["latency_slo"]["requests_met"], 0)+ self.assertEqual(summary["latency_slo"]["timing_basis"], "scheduled_arrival")+ row.update(success=False, arrival_first_output_seconds=None)+ self.assertEqual(bench.summarize([row], 3)["arrival_timing"]["successful_first_output_seconds"]["count"], 0)++ def test_arrival_schedule_uses_absolute_deadlines(self):+ now = [100.0]+ sleeps = []+ def sleep(delay):+ sleeps.append(delay)+ now[0] += delay + .01 # deterministic late wakeup+ def submit(_fn, _url, _payload, _key, _timeout, index, origin):+ future = Future()+ future.set_result({"index": index, "start_seconds": now[0] - origin,+ "success": True, "first_output_seconds": .01,+ "duration_seconds": .02, "completion_tokens": 1})+ now[0] += .02+ return future+ with patch.object(bench.time, "perf_counter", side_effect=lambda: now[0]), \+ patch.object(bench.time, "sleep", side_effect=sleep), \+ patch.object(bench.concurrent.futures, "ThreadPoolExecutor") as executor:+ executor.return_value.__enter__.return_value.submit.side_effect = submit+ rows, _ = bench.run("unused", [{"messages": []}], "fixture", 1, 3, 8, 0, "", 2,+ request_rate=10)+ self.assertEqual(len(sleeps), 2)+ self.assertAlmostEqual(sleeps[0], .08)+ self.assertAlmostEqual(sleeps[1], .07)+ for row, expected in zip(rows, [0, .11, .21]):+ self.assertAlmostEqual(row["start_seconds"], expected)++ def test_request_rate_must_be_positive_and_finite(self):+ for value in ("0", "-1", "nan", "inf"):+ with self.subTest(value=value), self.assertRaises(bench.argparse.ArgumentTypeError):+ bench.positive_float(value)+def test_nearest_rank_distribution(self):self.assertEqual(bench.distribution(list(range(1, 101)))["p95"], 95)self.assertIsNone(bench.distribution([])["p95"])diff --git a/c/tools/benchmark_http_serving.py b/c/tools/benchmark_http_serving.pyindex 8ea3a8fd..2d612fc4 100644--- a/c/tools/benchmark_http_serving.py+++ b/c/tools/benchmark_http_serving.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Bounded, closed-loop OpenAI chat streaming benchmark (stdlib only)."""+"""OpenAI chat streaming benchmark with bounded concurrency (stdlib only)."""import argparseimport concurrent.futuresimport hashlib@@ -160,15 +160,26 @@ def summarize(results, elapsed, slo_first_output=None, slo_duration=None):"successful_first_output_seconds": distribution([r["first_output_seconds"] for r in successful if r["first_output_seconds"] is not None])}+ paced = all(row.get("scheduled_seconds") is not None for row in results)+ summary["arrival_timing"] = None+ if paced:+ summary["arrival_timing"] = {+ "dispatch_delay_seconds": distribution([r["dispatch_delay_seconds"] for r in results]),+ "successful_duration_seconds": distribution([r["arrival_duration_seconds"] for r in successful]),+ "successful_first_output_seconds": distribution([+ r["arrival_first_output_seconds"] for r in successful+ if r["arrival_first_output_seconds"] is not None])}+ prefix = "arrival_" if paced else ""summary["latency_slo"] = Noneif slo_first_output is not None or slo_duration is not None:met = sum(- (slo_duration is None or row["duration_seconds"] <= slo_duration)+ (slo_duration is None or row[prefix + "duration_seconds"] <= slo_duration)and (slo_first_output is None or (- row["first_output_seconds"] is not None- and row["first_output_seconds"] <= slo_first_output))+ row[prefix + "first_output_seconds"] is not None+ and row[prefix + "first_output_seconds"] <= slo_first_output))for row in successful)summary["latency_slo"] = {+ "timing_basis": "scheduled_arrival" if paced else "request_start","first_output_seconds": slo_first_output, "duration_seconds": slo_duration,"requests_met": met, "fraction_of_attempts": met / len(results),"goodput_requests_per_second": met / elapsed}@@ -176,18 +187,30 @@ def summarize(results, elapsed, slo_first_output=None, slo_duration=None):def run(url, workload, model, concurrency, repeats, max_tokens, temperature, key, timeout,- slo_first_output=None, slo_duration=None):+ slo_first_output=None, slo_duration=None, request_rate=None):origin = time.perf_counter()- # Workers take the next request as soon as the previous stream ends. Timers- # begin inside workers, excluding time waiting in the local executor queue.+ # Without a rate, workers immediately take the next request. With a rate,+ # absolute arrival deadlines keep submission independent of response time.with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:futures = []for index in range(len(workload) * repeats):+ if request_rate is not None:+ delay = origin + index / request_rate - time.perf_counter()+ if delay > 0:+ time.sleep(delay)payload = dict(workload[index % len(workload)], model=model, stream=True,stream_options={"include_usage": True}, max_tokens=max_tokens,temperature=temperature, n=1)futures.append(pool.submit(request_one, url, payload, key, timeout, index, origin))results = [future.result() for future in futures]+ if request_rate is not None:+ for row in results:+ row["scheduled_seconds"] = row["index"] / request_rate+ wait = max(0.0, row["start_seconds"] - row["scheduled_seconds"])+ row["dispatch_delay_seconds"] = wait+ row["arrival_duration_seconds"] = wait + row["duration_seconds"]+ first = row["first_output_seconds"]+ row["arrival_first_output_seconds"] = None if first is None else wait + firstreturn results, summarize(results, time.perf_counter() - origin, slo_first_output, slo_duration)@@ -213,6 +236,7 @@ def main():parser.add_argument("--output", required=True, help="JSON report path")parser.add_argument("--concurrency", type=positive_int, default=1)parser.add_argument("--repeats", type=positive_int, default=1)+ parser.add_argument("--request-rate", type=positive_float, help="fixed scheduled arrivals per second")parser.add_argument("--max-tokens", type=positive_int, default=128)parser.add_argument("--temperature", type=float, default=0)parser.add_argument("--timeout", type=positive_float, default=60, help="socket operation timeout in seconds")@@ -232,10 +256,12 @@ def main():results, summary = run(url, workload, args.model, args.concurrency, args.repeats,args.max_tokens, args.temperature,os.environ.get(args.api_key_env, ""), args.timeout,- args.slo_first_output, args.slo_duration)+ args.slo_first_output, args.slo_duration, args.request_rate)report = {"schema_version": 1, "config": {"endpoint": url, "model": args.model, "workload_sha256": digest,"workload_rows": len(workload), "concurrency": args.concurrency,+ "load_model": "fixed_rate" if args.request_rate is not None else "closed_loop",+ "request_rate": args.request_rate,"repeats": args.repeats, "max_tokens": args.max_tokens,"temperature": args.temperature, "socket_timeout_seconds": args.timeout,"slo_first_output_seconds": args.slo_first_output, "slo_duration_seconds": args.slo_duration,diff --git a/docs/benchmarking.md b/docs/benchmarking.mdindex 3009a267..65d5139e 100644--- a/docs/benchmarking.md+++ b/docs/benchmarking.md@@ -120,9 +120,9 @@ observed output/usage.Measurement boundaries:-- Concurrency is closed-loop: at most that many requests are in flight, and each- worker starts its next request after its previous stream ends. There is no- arrival-rate model, warmup, automatic retry, or cache flush. Repeats reuse the+- Without `--request-rate`, concurrency is closed-loop: at most that many+ requests are in flight, and each worker starts its next request after its+ previous stream ends. There is no warmup, automatic retry, or cache flush. Repeats reuse theconversations in file order; prefix caching and scheduling can affect results.- Request timing begins inside the worker, before HTTP connection setup, andexcludes waiting for a local worker. Each request uses a new connection.@@ -156,12 +156,14 @@ then increase it to expose queueing and prefill interference.Add `--slo-first-output 1 --slo-duration 15` to require first output within onesecond and protocol completion within fifteen seconds. Either flag can be usedalone; values are finite positive seconds and the boundary is inclusive.-`summary.latency_slo` reports the thresholds, `requests_met`, the fraction of+`summary.latency_slo` reports the thresholds, timing basis, `requests_met`, the fraction of**all attempts** meeting them, and `goodput_requests_per_second` (qualifyingsuccessful requests divided by the entire batch wall time). Without thresholds,this field is null. Failures never qualify, even if they emitted output beforefailing. When a first-output target is set, empty-output successes also do not-qualify. Missing token usage does not prevent evaluating these latency targets.+qualify. Missing token usage does not prevent evaluating these latency targets. In+closed-loop mode the targets start at the HTTP request; fixed-rate mode uses+the scheduled arrival time and includes client dispatch delay.This follows the latency-constrained goodput approach used by[vLLM's serving benchmark](https://docs.vllm.ai/en/latest/api/vllm/benchmarks/serve/),@@ -174,8 +176,41 @@ improvement.Keep the load model fixed when comparing reports.[SGLang's serving benchmark](https://github.com/sgl-project/sglang/blob/main/python/sglang/benchmark/serving.py)-also supports request-rate-driven arrivals and trace timestamps. This tool still-uses closed-loop concurrency: slow responses reduce the rate at which new-requests start. Its goodput cannot establish an open-loop arrival-rate capacity-or a production SLO guarantee. Rate-controlled arrivals and warmup/cache policy-remain separate measurement needs.+also supports request-rate-driven arrivals and trace timestamps. This tool uses+closed-loop concurrency by default; `--request-rate` selects periodic arrivals+as described below. Neither mode alone establishes a production SLO guarantee;+warmup/cache policy, workload representativeness and repeated-run controls still+matter.++### Schedule arrivals independently of response time++Add `--request-rate 5` to schedule five arrivals per second. Request `i` is due at+`i / rate` seconds from batch start; the first is due immediately. Absolute+monotonic deadlines prevent accumulated timer drift. This is a deterministic+periodic schedule, not Poisson traffic or trace replay. Requests are not retried+or dropped, and the finite workload drains before the report is written.++`--concurrency` still caps simultaneous HTTP requests. Arrivals accumulate in+the client's executor queue when all workers are busy. Therefore the configured+rate is **scheduled arrivals, not guaranteed wire or server arrival rate**.+Delayed producer wakeups also contribute to dispatch delay; inspect client load+before attributing all delay to the server. The queue and retained results can+grow to the workload's total request count, so size workloads accordingly.++Fixed-rate per-request records add:++- `scheduled_seconds`: planned arrival relative to batch start;+- `dispatch_delay_seconds`: actual worker start minus scheduled arrival;+- `arrival_first_output_seconds`: dispatch delay plus HTTP first-output latency,+ or null if no output was observed;+- `arrival_duration_seconds`: dispatch delay plus HTTP request duration.++`summary.arrival_timing` reports dispatch-delay samples for all attempts and+arrival-based latency samples for successes. Existing HTTP timing fields retain+their original meaning. With a rate set, SLO evaluation uses arrival-based times+and records `timing_basis: scheduled_arrival`; without one it records+`request_start`. This prevents a request waiting two seconds for a worker and+then completing in 100 ms from meeting a one-second total-latency target.+Goodput still divides qualifying completions by the entire batch wall time,+including the drain after the last scheduled arrival. Keep rate, concurrency,+request count, latency targets and timing basis equal across compared reports.