geudrik/clairic-sm120-work / src_v2 /benchmarks /verify_http_server.py
geudrik's picture
download
raw
9.97 kB
"""Warmed live ASGI HTTP benchmark & value-parity verifier for `create_fastapi_app` (`uvicorn` + `httpx`).
Exercises the full FastAPI serving surface (`/health`, `/v1/extract`, `/systemone`):
1. Verifies both malformed Pydantic schema (`ValidationError`) and unsupported model selector
(`ClairRequestError`) return `HTTP 400`.
2. Warms text AR, multimodal ViT+AR, and `ClairicHead` readout paths over HTTP before timing.
3. Evaluates all 8 `workload_suite` cases over HTTP and checks field value agreement + ground-truth
accuracy against `golden_workload_v2.json`.
4. Runs a warmed concurrent HTTP sweep at `C in (1, 8, 16)` with `N = 32` requests per concurrency level.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import statistics
import sys
import threading
import time
from pathlib import Path
from typing import Any
import httpx
import uvicorn
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, create_fastapi_app
from workload_suite import build_suite, compare_against_golden, evaluate_ground_truth
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_http_on_existing_service(
service: ClairicConcurrentService,
*,
port: int = 8091,
golden_json: Path | None = None,
output_json: Path | None = None,
requests_per_c: int = 32,
config_meta: dict[str, Any] | None = None,
) -> dict[str, Any]:
app = create_fastapi_app(service)
uv_cfg = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning")
server = uvicorn.Server(uv_cfg)
thread = threading.Thread(target=server.run, daemon=True)
thread.start()
base_url = f"http://127.0.0.1:{port}"
suite = build_suite()
try:
limits = httpx.Limits(max_connections=64, max_keepalive_connections=32)
async with httpx.AsyncClient(base_url=base_url, timeout=180.0, limits=limits) as client:
for _ in range(100):
try:
r = await client.get("/health")
if r.status_code == 200:
break
except Exception:
await asyncio.sleep(0.1)
else:
raise RuntimeError("FastAPI HTTP server failed to become healthy")
health_before = (await client.get("/health")).json()
# 1. Verify BOTH Pydantic ValidationError and ClairRequestError return HTTP 400
bad_schema = await client.post(
"/v1/extract", json={"context": "missing state field", "fields": {"a": {"type": "text"}}}
)
assert bad_schema.status_code == 400, f"Expected HTTP 400 on bad schema, got {bad_schema.status_code}"
bad_model_payload = dict(suite[-1]["request"], model="wrong-model")
bad_model = await client.post("/v1/extract", json=bad_model_payload)
assert bad_model.status_code == 400, f"Expected HTTP 400 on bad model, got {bad_model.status_code}"
# 2. Warm all 3 execution paths over HTTP before timing
for idx in (7, 2, 4):
wr = await client.post("/v1/extract", json=suite[idx]["request"])
assert wr.status_code == 200
# 3. Evaluate all 8 cases over HTTP and verify field VALUES (not just keys!)
http_candidates: dict[str, Any] = {}
t_b0 = time.perf_counter()
burst_resps = await asyncio.gather(
*(
client.post("/v1/extract" if idx % 2 == 0 else "/systemone", json=case["request"])
for idx, case in enumerate(suite)
)
)
warm_burst_wall = time.perf_counter() - t_b0
for case, r in zip(suite, burst_resps):
assert r.status_code == 200, f"Case {case['id']} failed HTTP {r.status_code}: {r.text}"
body = r.json()
assert set(body["answers"].keys()) == set(case["request"]["fields"].keys())
http_candidates[case["id"]] = body
gt_all = evaluate_ground_truth(suite, http_candidates, key="expected_all")
golden_cmp = None
if golden_json is not None and golden_json.exists():
golden = json.loads(golden_json.read_text())
golden_cmp = compare_against_golden(golden, http_candidates)
# 4. Warmed concurrent HTTP sweep (C = 1, 8, 16; N = requests_per_c)
http_sweep: dict[str, Any] = {}
for c in (1, 8, 16):
workload = [suite[i % len(suite)] for i in range(requests_per_c)]
sem = asyncio.Semaphore(c)
lats: list[float] = []
async def _http_worker(idx: int, item: dict[str, Any]) -> dict[str, Any]:
route = "/v1/extract" if idx % 2 == 0 else "/systemone"
async with sem:
t0 = time.perf_counter()
resp = await client.post(route, json=item["request"])
lats.append(time.perf_counter() - t0)
assert resp.status_code == 200
return resp.json()
t0 = time.perf_counter()
bodies = await asyncio.gather(*(_http_worker(i, it) for i, it in enumerate(workload)))
wall = time.perf_counter() - t0
s_lat = sorted(lats)
total_fields = sum(len(b["answers"]) for b in bodies)
http_sweep[str(c)] = {
"concurrency": c,
"num_requests": requests_per_c,
"wall_seconds": round(wall, 3),
"requests_per_sec": round(requests_per_c / wall, 4),
"fields_per_sec": round(total_fields / wall, 3),
"latency_p50_sec": round(statistics.median(s_lat), 3),
"latency_p95_sec": round(_percentile_95(s_lat), 3),
"latency_max_sec": round(s_lat[-1], 3),
}
print(
f" [HTTP C={c:2d} (N={requests_per_c})] wall={wall:.2f}s | req/s={requests_per_c/wall:.3f} | "
f"fields/s={total_fields/wall:.2f} | p50={statistics.median(s_lat):.2f}s | p95={_percentile_95(s_lat):.2f}s",
flush=True,
)
health_after = (await client.get("/health")).json()
summary = {
"status": "verified",
"config": config_meta or {},
"validation_error_status_code": bad_schema.status_code,
"unsupported_model_status_code": bad_model.status_code,
"warm_8_case_http_burst_wall_sec": round(warm_burst_wall, 3),
"warm_8_case_http_burst_req_per_sec": round(len(suite) / warm_burst_wall, 4),
"ground_truth_expected_all": gt_all,
"golden_comparison": golden_cmp,
"http_concurrency_sweep": http_sweep,
"health_before": health_before,
"health_after": health_after,
}
if output_json is not None:
output_json.parent.mkdir(parents=True, exist_ok=True)
output_json.write_text(json.dumps(summary, indent=2))
return summary
finally:
server.should_exit = True
thread.join(timeout=5.0)
async def run_http_verification(args: argparse.Namespace) -> None:
service = ClairicConcurrentService.create(
args.model_path,
head_source_path=args.head_source_path,
pool_size=args.pool_size,
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,
)
try:
cfg = {
"model_path": args.model_path,
"head_source_path": args.head_source_path,
"pool_size": args.pool_size,
"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,
}
await run_http_on_existing_service(
service,
port=args.port,
golden_json=Path(args.golden_json) if args.golden_json else None,
output_json=Path(args.output_json) if args.output_json else None,
requests_per_c=args.requests_per_c,
config_meta=cfg,
)
finally:
service.close()
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--model-path", default="/models/nvfp4")
ap.add_argument("--head-source-path", default="/models/clairic")
ap.add_argument("--port", type=int, default=8091)
ap.add_argument("--pool-size", type=int, default=24)
ap.add_argument("--kv-cache-dtype", default="auto")
ap.add_argument("--mem-fraction-static", type=float, default=0.80)
ap.add_argument("--max-mamba-cache-size", type=int, default=180)
ap.add_argument("--max-running-requests", type=int, default=48)
ap.add_argument("--chunked-prefill-size", type=int, default=16384)
ap.add_argument("--requests-per-c", type=int, default=32)
ap.add_argument("--golden-json", default="/work/v2_audit/golden_workload_v2.json")
ap.add_argument("--output-json", default="/work/v2_audit/http_live_verification_v2.json")
asyncio.run(run_http_verification(ap.parse_args()))
if __name__ == "__main__":
main()

Xet Storage Details

Size:
9.97 kB
·
Xet hash:
c317de2bd75a7de9bcf6cee49b82a6c14a1058cbe76714c9b20591779563bd43

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