geudrik/clairic-sm120-work / src_v2 /benchmarks /bench_sglang_engine.py
geudrik's picture
download
raw
17.5 kB
"""Multi-Repeat Accuracy, Held-Out Validation & Concurrency Benchmark Harness for `ClairicConcurrentService`."""
from __future__ import annotations
import argparse
import asyncio
import json
import os
import statistics
import subprocess
import sys
import time
from pathlib import Path
from typing import Any
BENCH_DIR = Path(__file__).resolve().parent
REPO_ROOT = BENCH_DIR.parent
for p in (str(REPO_ROOT), str(BENCH_DIR)):
if p not in sys.path:
sys.path.insert(0, p)
from clairic_sm120.engine import ClairicConcurrentService
from heldout_suite import build_heldout_suite
from workload_suite import build_suite, compare_against_golden, evaluate_ground_truth
def query_gpu_used_mib() -> float:
try:
out = subprocess.check_output(
["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"],
text=True,
).strip()
return float(out.splitlines()[0])
except Exception:
return 0.0
def _percentile_95(sorted_vals: list[float]) -> float:
if not sorted_vals:
return 0.0
return sorted_vals[min(len(sorted_vals) - 1, int(0.95 * len(sorted_vals)))]
async def run_concurrency_level(
service: ClairicConcurrentService,
suite: list[dict[str, Any]],
concurrency: int,
total_requests: int,
) -> dict[str, Any]:
workload = [suite[i % len(suite)] for i in range(total_requests)]
limiter = asyncio.Semaphore(concurrency)
latencies: list[float] = []
async def worker(req_item: dict[str, Any]) -> dict[str, Any]:
async with limiter:
t0 = time.perf_counter()
resp = await service.predict_async(req_item["request"])
latencies.append(time.perf_counter() - t0)
return resp
t_start = time.perf_counter()
responses = await asyncio.gather(*(worker(item) for item in workload))
wall = time.perf_counter() - t_start
total_fields = sum(len(r["answers"]) for r in responses)
total_in_tok = sum(r["usage"]["input_tokens"] for r in responses)
total_out_tok = sum(r["usage"]["output_tokens"] for r in responses)
sorted_lat = sorted(latencies)
p50 = statistics.median(sorted_lat)
p95 = _percentile_95(sorted_lat)
return {
"concurrency": concurrency,
"num_requests": total_requests,
"wall_seconds": round(wall, 3),
"requests_per_sec": round(total_requests / wall, 4),
"fields_per_sec": round(total_fields / wall, 3),
"effective_input_tok_per_sec": round(total_in_tok / wall, 1),
"output_tok_per_sec": round(total_out_tok / wall, 2),
"latency_p50_sec": round(p50, 3),
"latency_p95_sec": round(p95, 3),
"latency_max_sec": round(sorted_lat[-1], 3),
}
async def evaluate_single_suite(
service: ClairicConcurrentService,
suite: list[dict[str, Any]],
golden_path: Path | None,
) -> tuple[dict[str, Any], dict[str, Any]]:
candidate_responses: dict[str, Any] = {}
per_case_metrics: list[dict[str, Any]] = []
for case in suite:
cid = case["id"]
t0 = time.perf_counter()
resp = await service.predict_async(case["request"])
dt = time.perf_counter() - t0
candidate_responses[cid] = resp
per_case_metrics.append(
{
"id": cid,
"category": case["category"],
"latency_sec": round(dt, 3),
"num_fields": len(resp["answers"]),
"truncated": bool(resp.get("truncated", False)),
"usage": resp["usage"],
}
)
gt_v1 = evaluate_ground_truth(suite, candidate_responses, key="expected")
gt_all = evaluate_ground_truth(suite, candidate_responses, key="expected_all")
golden_cmp = None
if golden_path is not None and golden_path.exists():
golden = json.loads(golden_path.read_text())
golden_cmp = compare_against_golden(golden, candidate_responses)
return candidate_responses, {
"per_case_single_request": per_case_metrics,
"ground_truth_expected": gt_v1,
"ground_truth_expected_all": gt_all,
"golden_comparison": golden_cmp,
}
def _aggregate_repeats(runs: list[dict[str, Any]], concurrencies: list[str]) -> dict[str, Any]:
agg_c: dict[str, Any] = {}
for ck in concurrencies:
sub = [r["concurrency_sweep"][ck] for r in runs if ck in r["concurrency_sweep"]]
if not sub:
continue
req_s = [x["requests_per_sec"] for x in sub]
fld_s = [x["fields_per_sec"] for x in sub]
in_s = [x["effective_input_tok_per_sec"] for x in sub]
out_s = [x["output_tok_per_sec"] for x in sub]
p50s = [x["latency_p50_sec"] for x in sub]
p95s = [x["latency_p95_sec"] for x in sub]
maxs = [x["latency_max_sec"] for x in sub]
agg_c[ck] = {
"concurrency": int(ck),
"num_requests_per_repeat": sub[0]["num_requests"],
"repeats": len(sub),
"requests_per_sec_median": round(statistics.median(req_s), 4),
"requests_per_sec_min": round(min(req_s), 4),
"requests_per_sec_max": round(max(req_s), 4),
"fields_per_sec_median": round(statistics.median(fld_s), 3),
"fields_per_sec_min": round(min(fld_s), 3),
"fields_per_sec_max": round(max(fld_s), 3),
"effective_input_tok_per_sec_median": round(statistics.median(in_s), 1),
"output_tok_per_sec_median": round(statistics.median(out_s), 2),
"latency_p50_sec_median": round(statistics.median(p50s), 3),
"latency_p50_sec_min": round(min(p50s), 3),
"latency_p50_sec_max": round(max(p50s), 3),
"latency_p95_sec_median": round(statistics.median(p95s), 3),
"latency_p95_sec_min": round(min(p95s), 3),
"latency_p95_sec_max": round(max(p95s), 3),
"latency_max_sec_median": round(statistics.median(maxs), 3),
}
def _agg_parity(suite_key: str) -> dict[str, Any] | None:
cmps = [
r[suite_key]["golden_comparison"]
for r in runs
if r.get(suite_key) and r[suite_key].get("golden_comparison") is not None
]
if not cmps:
return None
matches = [c["matching_fields"] for c in cmps]
mean_confs = [c["mean_abs_confidence_diff"] for c in cmps]
max_confs = [c["max_abs_confidence_diff"] for c in cmps]
return {
"repeats": len(cmps),
"total_fields": cmps[0]["total_fields"],
"matching_fields_median": statistics.median(matches),
"matching_fields_min": min(matches),
"matching_fields_max": max(matches),
"mean_abs_confidence_diff_median": round(statistics.median(mean_confs), 6),
"max_abs_confidence_diff_max": round(max(max_confs), 6),
}
return {
"concurrency_summary": agg_c,
"selection_parity_summary": _agg_parity("selection_suite"),
"heldout_parity_summary": _agg_parity("heldout_suite"),
}
async def run_benchmark_on_service(
service: ClairicConcurrentService,
args: argparse.Namespace,
*,
load_sec: float,
gpu_mib_after_load: float,
) -> dict[str, Any]:
workload = build_suite()
heldout = build_heldout_suite() if args.heldout_golden_json else None
print("Warming up text AR, multimodal ViT+AR, and ClairicHead paths...", flush=True)
await service.predict_async(workload[7]["request"]) # compact AR
await service.predict_async(workload[2]["request"]) # multimodal ViT + AR
await service.predict_async(workload[4]["request"]) # ClairicHead typed readout
concurrencies = [int(x) for x in args.concurrencies.split(",") if x.strip()]
concurrencies = [c for c in concurrencies if not args.max_concurrency_bench or c <= args.max_concurrency_bench]
repeats_data: list[dict[str, Any]] = []
first_workload_resps: dict[str, Any] = {}
first_heldout_resps: dict[str, Any] = {}
for rep in range(1, args.repeats + 1):
print(f"--- [{args.label}] Repeat {rep}/{args.repeats} ---", flush=True)
# Reset engine warmup cache between repeats so intra-request warmup runs identically per repeat
service.engine._warmed_prefixes.clear()
service.engine._warmup_locks.clear()
w_resps, w_eval = await evaluate_single_suite(
service,
workload,
Path(args.golden_json) if args.golden_json else None,
)
if rep == 1:
first_workload_resps = w_resps
if w_eval["golden_comparison"]:
gc = w_eval["golden_comparison"]
print(
f" [Selection 8-case] match={gc['matching_fields']}/{gc['total_fields']} | "
f"GT47={w_eval['ground_truth_expected_all']['passed']}/{w_eval['ground_truth_expected_all']['total']} | "
f"mean_conf={gc['mean_abs_confidence_diff']:.4f} | max_conf={gc['max_abs_confidence_diff']:.4f} | "
f"est_rel={gc['mean_estimate_rel_diff']:.4f}",
flush=True,
)
h_eval = None
if heldout is not None:
h_resps, h_eval = await evaluate_single_suite(
service,
heldout,
Path(args.heldout_golden_json) if args.heldout_golden_json else None,
)
if rep == 1:
first_heldout_resps = h_resps
if h_eval["golden_comparison"]:
hgc = h_eval["golden_comparison"]
print(
f" [Held-out 12-case] match={hgc['matching_fields']}/{hgc['total_fields']} | "
f"GT={h_eval['ground_truth_expected_all']['passed']}/{h_eval['ground_truth_expected_all']['total']} | "
f"mean_conf={hgc['mean_abs_confidence_diff']:.4f} | max_conf={hgc['max_abs_confidence_diff']:.4f} | "
f"est_rel={hgc['mean_estimate_rel_diff']:.4f}",
flush=True,
)
c_results: dict[str, Any] = {}
for c in concurrencies:
n_req = max(args.requests_per_c, c)
res = await run_concurrency_level(service, workload, concurrency=c, total_requests=n_req)
c_results[str(c)] = res
print(
f" [{args.label} rep={rep} C={c:2d} (N={n_req:2d})] wall={res['wall_seconds']:6.2f}s | "
f"req/s={res['requests_per_sec']:.3f} | fields/s={res['fields_per_sec']:.2f} | "
f"p50={res['latency_p50_sec']:.2f}s | p95={res['latency_p95_sec']:.2f}s | max={res['latency_max_sec']:.2f}s",
flush=True,
)
repeats_data.append(
{
"repeat": rep,
"selection_suite": w_eval,
"heldout_suite": h_eval,
"concurrency_sweep": c_results,
}
)
peak_gpu_mib = query_gpu_used_mib()
out_path = Path(args.output_json).resolve()
out_path.parent.mkdir(parents=True, exist_ok=True)
# Archive full candidate responses from repeat 1 alongside the summary report
w_resp_path = out_path.parent / f"responses_{args.label}_workload.json"
w_resp_path.write_text(json.dumps(first_workload_resps, indent=2))
h_resp_path = None
if first_heldout_resps:
h_resp_path = out_path.parent / f"responses_{args.label}_heldout.json"
h_resp_path.write_text(json.dumps(first_heldout_resps, indent=2))
eng = service.engine
agg = _aggregate_repeats(repeats_data, [str(c) for c in concurrencies])
first = repeats_data[0]
report = {
"label": args.label,
"config": {
"model_path": str(args.model_path),
"head_source_path": str(args.head_source_path),
"pool_size": args.pool_size,
"dtype": args.dtype,
"quantization": args.quantization,
"kv_cache_dtype": args.kv_cache_dtype,
"mem_fraction_static": args.mem_fraction_static,
"max_mamba_cache_size": args.max_mamba_cache_size,
"max_running_requests": args.max_running_requests,
"chunked_prefill_size": args.chunked_prefill_size,
"disable_radix_cache": args.disable_radix_cache,
"disable_prefill_cuda_graph": args.disable_prefill_cuda_graph,
"prefix_warmup_enabled": eng.enable_prefix_warmup,
"fused_sampler_enabled": os.environ.get("CLAIRIC_FUSED_SAMPLER", "1") == "1",
"speculative_algorithm": args.speculative_algorithm,
"speculative_num_steps": args.speculative_num_steps,
"speculative_eagle_topk": args.speculative_eagle_topk,
"speculative_num_draft_tokens": args.speculative_num_draft_tokens,
"repeats": args.repeats,
"requests_per_concurrency_level": args.requests_per_c,
"load_seconds": round(load_sec, 2),
"gpu_gib_after_load": round(gpu_mib_after_load / 1024.0, 2),
"gpu_gib_after_bench": round(peak_gpu_mib / 1024.0, 2),
"prefix_warmup_runs": eng.warmup_runs,
"prefix_warmup_dedup_key_hits": eng.warmup_hits,
"read_typed_calls": eng.read_typed_calls,
"read_typed_compact_bytes_min": eng.read_typed_compact_bytes_min,
"read_typed_compact_bytes_max": eng.read_typed_compact_bytes_max,
"archived_workload_responses": w_resp_path.name,
"archived_heldout_responses": h_resp_path.name if h_resp_path else None,
},
"summary": agg,
"selection_suite_rep1": first["selection_suite"],
"heldout_suite_rep1": first["heldout_suite"],
"concurrency_sweep_rep1": first["concurrency_sweep"],
"all_repeats": repeats_data,
}
out_path.write_text(json.dumps(report, indent=2))
print(f"Saved report to {out_path}", flush=True)
return report
async def async_main(args: argparse.Namespace) -> None:
os.environ["CLAIRIC_FUSED_SAMPLER"] = "0" if args.disable_fused_sampler else "1"
print(f"=== Loading ClairicConcurrentService [{args.label}] from {args.model_path} ===", flush=True)
t_load0 = time.perf_counter()
service = ClairicConcurrentService.create(
args.model_path,
head_source_path=args.head_source_path,
pool_size=args.pool_size,
dtype=args.dtype,
quantization=args.quantization,
kv_cache_dtype=args.kv_cache_dtype,
mem_fraction_static=args.mem_fraction_static,
max_mamba_cache_size=None if args.disable_radix_cache and args.max_mamba_cache_size < 0 else args.max_mamba_cache_size,
max_running_requests=args.max_running_requests,
chunked_prefill_size=args.chunked_prefill_size,
disable_radix_cache=args.disable_radix_cache,
disable_prefill_cuda_graph=args.disable_prefill_cuda_graph,
speculative_algorithm=args.speculative_algorithm,
speculative_num_steps=args.speculative_num_steps,
speculative_eagle_topk=args.speculative_eagle_topk,
speculative_num_draft_tokens=args.speculative_num_draft_tokens,
enable_prefix_warmup=not (args.disable_prefix_warmup or args.disable_radix_cache),
)
load_sec = time.perf_counter() - t_load0
gpu_mib_after_load = query_gpu_used_mib()
print(f"Loaded in {load_sec:.1f}s | GPU memory used = {gpu_mib_after_load/1024:.2f} GiB", flush=True)
try:
await run_benchmark_on_service(
service,
args,
load_sec=load_sec,
gpu_mib_after_load=gpu_mib_after_load,
)
finally:
service.close()
def build_arg_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser()
p.add_argument("--label", required=True)
p.add_argument("--model-path", default="/models/clairic")
p.add_argument("--head-source-path", default="/models/clairic")
p.add_argument("--golden-json", default="/work/v2_audit/golden_workload_v2.json")
p.add_argument("--heldout-golden-json", default="/work/v2_audit/golden_heldout_v2.json")
p.add_argument("--output-json", required=True)
p.add_argument("--pool-size", type=int, default=24)
p.add_argument("--dtype", default="bfloat16")
p.add_argument("--quantization", default=None)
p.add_argument("--kv-cache-dtype", default="auto")
p.add_argument("--mem-fraction-static", type=float, default=0.80)
p.add_argument("--max-mamba-cache-size", type=int, default=180)
p.add_argument("--max-running-requests", type=int, default=48)
p.add_argument("--chunked-prefill-size", type=int, default=16384)
p.add_argument("--disable-radix-cache", action="store_true")
p.add_argument("--disable-prefill-cuda-graph", action="store_true")
p.add_argument("--disable-prefix-warmup", action="store_true")
p.add_argument("--disable-fused-sampler", action="store_true")
p.add_argument("--speculative-algorithm", default=None)
p.add_argument("--speculative-num-steps", type=int, default=None)
p.add_argument("--speculative-eagle-topk", type=int, default=None)
p.add_argument("--speculative-num-draft-tokens", type=int, default=None)
p.add_argument("--concurrencies", default="1,4,8,16,32")
p.add_argument("--requests-per-c", type=int, default=32)
p.add_argument("--repeats", type=int, default=1)
p.add_argument("--max-concurrency-bench", type=int, default=32)
return p
if __name__ == "__main__":
asyncio.run(async_main(build_arg_parser().parse_args()))

Xet Storage Details

Size:
17.5 kB
·
Xet hash:
02ba114226ab2310d484d577ec2bd787834fbb54f3d886061257c83ae0876935

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.