#!/usr/bin/env python3 """Synthetic 1k-in / 1k-out throughput benchmark for Qwen3.8-27B on Trainium2. Boots the candidate's ``server.py`` (see ``launcher.py``), replays a fixed-volume Request Factory trace against ``/v1/completions`` (every request: 1024 prompt tokens, 1024 generated tokens, EOS ignored, greedy), saturated arrivals capped at ``--concurrency`` in flight, then stops the server. The headline metric ``output_tokens_per_s`` is Request Factory's ``output_token_throughput_per_s``: all generated tokens divided by the replay's wall-clock time. """ from __future__ import annotations import argparse import asyncio import csv import json import math import subprocess import sys import tempfile from collections.abc import Mapping from pathlib import Path from typing import Any sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from benchmark import launcher _MODEL = "Qwen/Qwen3.8-27B" _METRICS = {"output_tokens_per_s": {"unit": "tok/s", "direction": "max"}} _UNDERSIZED_POOL_WARNING = "synthetic content will repeat within a single request" def _write_trace(path: Path, count: int, input_len: int, output_len: int) -> None: with path.open("w", newline="", encoding="utf-8") as output: writer = csv.writer(output) writer.writerow(("id", "arrival_time", "input_len", "output_len")) for index in range(count): writer.writerow((f"request-{index:05d}", 0, input_len, output_len)) def _write_corpus(path: Path, token_pool_limit: int) -> None: seed = "The server processes a synthetic request and returns generated text" with path.open("w", encoding="utf-8") as corpus: for index in range(token_pool_limit): corpus.write(f"{seed} sample {index} token sequence {index}\n") def _token_pool_limit(input_len: int, total_requests: int) -> int: minimum = max(2 * input_len, total_requests) return 1 << (minimum - 1).bit_length() def _failed_requests(log_path: Path, limit: int = 5) -> str: """The first failed requests' outcomes from the RF request log, one per line. The log lives in a temporary directory and RF's progress lines fill the output, so a failure restates these at the end, where an output tail still shows them. """ try: rows = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines()] except (OSError, ValueError) as exc: return f"(no request log: {exc})" failed = [ (index, row.get("outcome", {})) for index, row in enumerate(rows) if row.get("outcome", {}).get("error") is not None or row.get("outcome", {}).get("output_len_actual") != row.get("source", {}).get("data", {}).get("output_len_target") ] lines = [f"{len(failed)} of {len(rows)} requests failed; first {min(limit, len(failed))}:"] lines += [ f" log row {index}: {json.dumps(outcome)[:600]}" for index, outcome in failed[:limit] ] return "\n".join(lines) def _replay(args: argparse.Namespace, base_url: str) -> dict[str, Any]: with tempfile.TemporaryDirectory(prefix="qwen38-trn2-rf-") as directory: temporary = Path(directory) trace = temporary / "requests.csv" summary_path = temporary / "summary.json" log_path = temporary / "requests.jsonl" corpus = temporary / "corpus.txt" _write_trace(trace, args.request_count, args.input_len, args.output_len) token_pool_limit = _token_pool_limit(args.input_len, args.request_count) _write_corpus(corpus, token_pool_limit) command = [ args.request_factory_engine, "--trace", str(trace), "--input-file-format", "text-generation-independent", "--text-file", str(corpus), "--tokenizer", args.tokenizer, "--model", _MODEL, "--backend", "openai", "--dialect", "openai", "--base-url", base_url.rstrip("/") + "/v1", "--temperature", "0", "--arrival-mode", "saturated", "--max-concurrency", str(args.concurrency), "--token-pool-limit", str(token_pool_limit), "--request-log", "true", "--log-path", str(log_path), "--timeline", "false", "--summary-path", str(summary_path), ] # fmt: skip completed = subprocess.run(command, check=False, text=True, capture_output=True) if completed.stdout: print(completed.stdout, end="", flush=True) if completed.stderr: print(completed.stderr, end="", file=sys.stderr, flush=True) if _UNDERSIZED_POOL_WARNING in completed.stderr: raise ValueError("Request Factory token pool is shorter than the prompt length") if completed.returncode != 0: raise RuntimeError(f"Request Factory exited with status {completed.returncode}") try: summary = json.loads(summary_path.read_text(encoding="utf-8")) replay = summary.get("replay") common = replay.get("common") if isinstance(replay, Mapping) else None if not isinstance(common, Mapping): raise ValueError("RF summary is missing replay.common") expected_counts = { "attempted_steps": args.request_count, "success_steps": args.request_count, "failed_steps": 0, "output_mismatch_steps": 0, } for name, expected in expected_counts.items(): if common.get(name) != expected: raise ValueError(f"RF summary {name}={common.get(name)!r}, expected {expected}") throughput = common.get("output_token_throughput_per_s") if isinstance(throughput, bool) or not isinstance(throughput, int | float): raise ValueError(f"RF throughput is missing or not numeric: {throughput!r}") throughput = float(throughput) if not math.isfinite(throughput) or throughput <= 0: raise ValueError(f"RF throughput is invalid: {throughput!r}") rows = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines()] if len(rows) != args.request_count: raise ValueError( f"RF request log has {len(rows)} records, expected {args.request_count}" ) for row in rows: source, outcome = row.get("source", {}).get("data", {}), row.get("outcome", {}) if ( source.get("input_len") != args.input_len or source.get("output_len_target") != args.output_len ): raise ValueError(f"RF request log has wrong trace lengths: {source!r}") if ( outcome.get("error") is not None or outcome.get("output_len_actual") != args.output_len ): raise ValueError(f"RF request did not complete at target length: {outcome!r}") except ValueError as exc: raise ValueError(f"{exc}\n{_failed_requests(log_path)}") from exc return { "output_tokens_per_s": throughput, "input_len": args.input_len, "output_len": args.output_len, "concurrency": args.concurrency, "request_count": args.request_count, "request_throughput_per_s": common.get("request_throughput_per_s"), "ttft_ms_p50": common.get("ttft_ms_p50"), "ttft_ms_p90": common.get("ttft_ms_p90"), "tpot_ms_p50": common.get("tpot_ms_p50"), "tpot_ms_p90": common.get("tpot_ms_p90"), } async def _measure(args: argparse.Namespace) -> dict[str, Any]: workspace = Path(args.workspace).resolve() async with launcher.server_endpoint( base_url=args.base_url, workspace=workspace, model_path=args.model_path, log_path=workspace / ".vibesys-benchmark-server.log", ) as base_url: # The replay is a blocking subprocess; keep it off the event loop. try: return await asyncio.to_thread(_replay, args, base_url) except Exception as exc: if args.base_url is not None: raise server_log = launcher.tail_server_log(workspace / ".vibesys-benchmark-server.log") raise RuntimeError(f"{exc}\nlast server log output:\n{server_log}") from exc def _append(path: Path | None, record: dict[str, Any]) -> None: if path: with path.open("a", encoding="utf-8") as output: output.write(json.dumps(record, allow_nan=False) + "\n") def run(args: argparse.Namespace) -> int: result_path = Path(args.vs_output) if args.vs_output else None if result_path: result_path.parent.mkdir(parents=True, exist_ok=True) result_path.write_text( json.dumps({"kind": "hello", "protocol": 2, "metrics": _METRICS}) + "\n", encoding="utf-8", ) try: result = asyncio.run(_measure(args)) if args.output_json: Path(args.output_json).write_text( json.dumps(result, indent=2, allow_nan=False) + "\n", encoding="utf-8" ) _append( result_path, { "kind": "result", "label": "", "values": {"output_tokens_per_s": result["output_tokens_per_s"]}, }, ) print(json.dumps(result, allow_nan=False), flush=True) return 0 except Exception as exc: _append(result_path, {"kind": "error", "message": str(exc)}) print(f"benchmark failed: {exc}", file=sys.stderr) return 1 def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--request-factory-engine", default="session_runner") parser.add_argument( "--base-url", default=None, help="a running server; default: boot the candidate's server.py" ) parser.add_argument("--workspace", default=".", help="candidate root holding server.py") parser.add_argument("--model-path", default=launcher.DEFAULT_MODEL_PATH) parser.add_argument("--tokenizer", default=None, help="default: --model-path") parser.add_argument("--request-count", type=int, default=64) parser.add_argument("--concurrency", type=int, default=64) parser.add_argument("--input-len", type=int, default=1024) parser.add_argument("--output-len", type=int, default=1024) parser.add_argument("--output-json") parser.add_argument("--vs-output") args = parser.parse_args() if args.tokenizer is None: args.tokenizer = args.model_path if min(args.request_count, args.concurrency, args.input_len, args.output_len) < 1: parser.error("request count, concurrency, and lengths must be positive") return run(args) if __name__ == "__main__": raise SystemExit(main())