"""Drive one load point with the pinned AIPerf and read back what it measured.""" import json import shutil import subprocess import tempfile from collections import Counter from pathlib import Path from .ci_artifacts import read_json from .ci_process import command from .inference_checks import verify_corpus from .inference_inputs import downloaded_path, safe_relative AIPERF = ["uv", "tool", "run", "--python", "3.12", "--constraints", "ci/aiperf-requirements.lock", "--from", "aiperf==0.13.0", "aiperf", "profile"] # A conversation point replays recorded conversations, each turn sent with the turns before it, # instead of generated prompts. `bound` is what ends it: AgentX paces its turns from the traces' # own gaps, so it runs for a time; ShareGPT sends each turn once the last is answered, so it runs # for a number of requests. # `smallest_tokens` is the corpus's shortest conversation at its pinned revision, input and output # together: AIPerf replays only those that fit the context, so a model serving less has none to # replay. AgentX's shortest carries a coding agent's system prompt; ShareGPT's turns all fit. DATASETS = { "agentx": {"corpus": "ci/inference-corpus.json", "bound": "duration_s", "smallest_tokens": 44048}, "sharegpt": {"corpus": "ci/inference-chat-corpus.json", "bound": "requests", "smallest_tokens": None}, } # AgentX's scenario holds a shorter run to be no submission; a comparison is not one. AGENTX_MINIMUM_S = 900 # Output name -> (AIPerf export metric, statistic). Missing metrics stay null; the raw # export is retained beside them, so a renamed field is visible rather than zero. METRICS = { "output_tok_s": ("output_token_throughput", "avg"), "request_per_s": ("request_throughput", "avg"), "ttft_ms_p50": ("time_to_first_token", "p50"), "ttft_ms_p95": ("time_to_first_token", "p95"), "itl_ms_p50": ("inter_token_latency", "p50"), "latency_ms_p50": ("request_latency", "p50"), "output_tokens_mean": ("output_sequence_length", "avg"), } def tokenizer(fixture): files = fixture["tokenizer_files"] path = downloaded_path(command([ "hf", "download", fixture["tokenizer_repo"], "--revision", fixture["tokenizer_revision"], "--quiet", *files, ], timeout=600, capture_stdout=True)) if any((path / safe_relative(name)).stat().st_size == 0 for name in files): raise ValueError("empty pinned tokenizer asset") return path def request_rate(point, backend): """A rate point's arrivals per second on `backend`, or None for a point that keeps its concurrency in flight. A rate is set per backend, as each runs a different share of what its hardware can serve.""" rates = point.get("request_rate") if rates is None: return None if backend not in rates: raise ValueError(f'{point["id"]} has no request rate for the {backend} backend') return rates[backend] def dataset(point): """The dataset a conversation point replays, or None for a point of generated prompts.""" return DATASETS[point["dataset"]] if "dataset" in point else None def common_args(endpoint, point, coordinate, tokenizer_path, directory): return [ *AIPERF, "--ui", "simple", "--url", endpoint, "--endpoint-type", "chat", "--streaming", # Nothing here reads AIPerf's server metrics or GPU telemetry, and under load their # optional collectors miss heartbeats, which marks the whole run incomplete. "--no-server-metrics", "--no-gpu-telemetry", "--model", coordinate, "--tokenizer", str(tokenizer_path), "--random-seed", "42", "--use-server-token-count", "--concurrency", str(point["concurrency"]), "--artifact-dir", str(directory), ] def conversation_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, context, corpus): args = [*common_args(endpoint, point, coordinate, tokenizer_path, directory), "--public-dataset", corpus["alias"]] if point["dataset"] == "agentx": # The scenario the nightly runs: it sets the trace pacing and ignore_eos itself, and # keeps only the traces whose turns fit a lane. args += ["--scenario", "inferencex-agentx-mvp", "--max-context-length", str(context), "--cache-bust", "first-turn-prefix", "--benchmark-duration", str(point["duration_s"])] return args + (["--unsafe-override"] if point["duration_s"] < AGENTX_MINIMUM_S else []) # Each turn asks for its recorded reply's length and gets all of it, so every arm # generates the same tokens whatever its model would have stopped at. return args + ["--request-count", str(point["requests"]), "--warmup-request-count", str(warmup), "--extra-inputs", "ignore_eos:true"] def profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate=None): args = [ *common_args(endpoint, point, coordinate, tokenizer_path, directory), "--request-count", str(point["requests"]), "--warmup-request-count", str(warmup), "--synthetic-input-tokens-mean", str(point["input_tokens"]), "--synthetic-input-tokens-stddev", "0", "--output-tokens-mean", str(point["output_tokens"]), "--output-tokens-stddev", "0", "--extra-inputs", "ignore_eos:true", ] if rate is not None: # Requests arrive on their own schedule, seeded so every arm sees the same one, and the # concurrency is only a ceiling. Kept in flight instead, requests that finish together # are replaced together, and every later wave queues the way the first one did. args += ["--request-rate", str(rate), "--arrival-pattern", "poisson"] if point["depth"]: # One shared prefix per concurrent request: each conversation re-reads its own # prefix, so the KV pool has to hold concurrency x depth to keep them resident. args += ["--prefix-prompt-length", str(point["depth"]), "--prefix-prompt-pool-size", str(point["concurrency"])] return args def number(value): return float(value) if type(value) in {int, float} else None def measurements(export): count, errors = export["request_count"]["avg"], export["request_error_rate"]["avg"] if (type(count) not in {int, float} or not count > 0 or errors != 0 or export.get("error_summary") != [] or export.get("is_complete") is not True): raise ValueError("AIPerf produced empty, incomplete or failed request evidence") return {name: number((export.get(metric) or {}).get(statistic)) for name, (metric, statistic) in METRICS.items()} def rejection(directory, requests): """What the server failed among the measured requests, from AIPerf's per-request export. AIPerf records an error for a request the server answers with one. A stream that ends on an error event it counts as served and leaves without an output length: that request is cut short here. None when nothing failed, and None unless the export accounts for every measured request, so a load run that broke off is never taken for the server's answer. """ exports = list(directory.rglob("profile_export.jsonl")) if len(exports) != 1: return None # One record a line. A server's own error text sits inside a record, so split on newlines alone. records = [json.loads(line) for line in exports[0].read_text(encoding="utf-8").split("\n") if line.strip()] measured = [record for record in records if (record.get("metadata") or {}).get("benchmark_phase") == "profiling"] failed = Counter(json.dumps(record["error"], sort_keys=True) for record in measured if record.get("error")) cut_short = sum(1 for record in measured if not record.get("error") and "output_sequence_length" not in (record.get("metrics") or {})) if len(measured) != requests or not (failed or cut_short): return None return {"requests": requests, "failed": sum(failed.values()), "cut_short": cut_short, "errors": [{"error_details": json.loads(error), "count": count} for error, count in sorted(failed.items())]} def run_point(endpoint, point, coordinate, tokenizer_path, warmup, directory: Path, *, may_reject, context, rate=None): """One point's metrics, or null metrics and what the server rejected where it may reject. `context` is a lane's, which every turn of a replayed AgentX trace must fit.""" failure, entry = None, dataset(point) if entry is None: args = profile_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, rate) else: corpus = read_json(Path(entry["corpus"])) directory.parent.mkdir(parents=True, exist_ok=True) # The loader resolves the dataset's main branch; the pin holds only if main has not moved. verify_corpus(corpus, directory.parent, f'{point["id"]}-before') args = conversation_args(endpoint, point, coordinate, tokenizer_path, warmup, directory, context, corpus) # AIPerf stages its ZeroMQ event bus under TMPDIR, and the job's own TMPDIR # lives under the workspace, whose path can exceed the 103-byte unix-socket # limit (this Mac's "Application Support" tree) before AIPerf adds its own # nesting. Anchor a short, space-free TMPDIR at /tmp instead. short_tmp = Path(tempfile.mkdtemp(prefix="aiperf-tmp-", dir="/tmp")) try: command(args, timeout=5400, overrides={"TMPDIR": str(short_tmp)}) except subprocess.CalledProcessError as error: # AIPerf exits non-zero, with no summary export, when every measured request failed. failure = error finally: shutil.rmtree(short_tmp, ignore_errors=True) if entry is not None: verify_corpus(corpus, directory.parent, f'{point["id"]}-after') rejected = rejection(directory, point["requests"]) if may_reject else None if rejected is not None: return dict.fromkeys(METRICS), rejected if failure is not None: raise failure # AIPerf 0.13.0 writes the summary at the artifact root and each phase under # phases/, so a recursive search sees three exports; the summary is the file # this point's numbers come from. export = directory / "profile_export_aiperf.json" if not export.is_file(): raise ValueError(f'{point["id"]}: no AIPerf export in {directory}') return measurements(read_json(export)), None