Upload hf_gpu_runner.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456"""Self-contained HF Jobs vLLM runner for Pareto benchmarking open models & v3 LoRA.
Launches local `vllm serve` (with optional `--enable-lora` so Stage-1 uses LoRA and Stage-2uses base weights with zero reload), runs a 10-doc concurrency=1 p50/p95 latency probe, then runsconcurrency=N batched requests across frozen HackApertus OOF (n=200), InvoiceBenchmark (n=200),and optional HackApertus test anchors. Uploads JSONL outputs + telemetry JSON back to HF staging."""
from __future__ import annotations
import argparseimport asyncioimport jsonimport osimport reimport subprocessimport sysimport timeimport urllib.requestfrom pathlib import Pathfrom typing import Any
from huggingface_hub import HfApi, snapshot_download
# Reuse balanced JSON parser & stats cleanlydef extract_json_obj(raw: str) -> dict[str, Any] | None: if not raw: return None text = raw.strip() for suf in ("<|inner_suffix|>", "</think>", "<channel|>"): if suf in text: _, _, text = text.partition(suf) text = text.strip() m = re.search(r"\{", text) if not m: return None body = text[m.start() :] for cand in (body, re.sub(r'([,{])\s*([A-Za-z_][A-Za-z0-9_]*)\s*":', r'\1"\2":', body)): try: obj = json.loads(cand) if isinstance(obj, dict): return obj except json.JSONDecodeError: pass cand = re.sub(r'([,{])\s*([A-Za-z_][A-Za-z0-9_]*)\s*":', r'\1"\2":', body) depth = 0 in_str = False esc = False for i, ch in enumerate(cand): if in_str: if esc: esc = False elif ch == "\\": esc = True elif ch == '"': in_str = False continue if ch == '"': in_str = True elif ch == "{": depth += 1 elif ch == "}": depth -= 1 if depth == 0: try: obj = json.loads(cand[: i + 1]) return obj if isinstance(obj, dict) else None except json.JSONDecodeError: return None return None
def percentile(vals: list[float], pct: float) -> float: if not vals: return 0.0 s = sorted(vals) idx = (len(s) - 1) * (pct / 100.0) lo = int(idx) hi = min(len(s) - 1, lo + 1) frac = idx - lo return s[lo] * (1.0 - frac) + s[hi] * frac
def wait_for_vllm(url: str, proc: subprocess.Popen[bytes], timeout_s: int = 1500) -> float: t0 = time.perf_counter() while time.perf_counter() - t0 < timeout_s: if proc.poll() is not None: raise RuntimeError(f"vLLM server exited early with code {proc.returncode}") try: with urllib.request.urlopen(f"{url}/models", timeout=3) as r: if r.status == 200: return time.perf_counter() - t0 except Exception: time.sleep(2.0) raise TimeoutError(f"vLLM server did not become ready within {timeout_s}s")
async def run_openai_batch( *, base_url: str, model_name: str, items: list[tuple[str, list[dict[str, str]], int]], out_jsonl: Path, concurrency: int = 8, probe_serial_n: int = 10, disable_thinking: bool = True,) -> dict[str, Any]: from openai import AsyncOpenAI
client = AsyncOpenAI(base_url=base_url, api_key="local-vllm", timeout=300.0) out_jsonl.parent.mkdir(parents=True, exist_ok=True) rows: list[dict[str, Any]] = [] use_thinking_kw = disable_thinking
async def one_call(did: str, msgs: list[dict[str, str]], max_toks: int) -> dict[str, Any]: nonlocal use_thinking_kw t0 = time.perf_counter() kw: dict[str, Any] = { "model": model_name, "messages": msgs, "temperature": 0.0, "max_tokens": max_toks, } if use_thinking_kw: kw["extra_body"] = {"chat_template_kwargs": {"enable_thinking": False}} try: resp = await client.chat.completions.create(**kw) except Exception as exc: if use_thinking_kw and "enable_thinking" in str(exc): use_thinking_kw = False kw.pop("extra_body", None) resp = await client.chat.completions.create(**kw) else: return { "doc_id": did, "raw_text": "", "parsed": None, "prompt_tokens": 0, "completion_tokens": 0, "latency_s": round(time.perf_counter() - t0, 4), "error": str(exc)[:240], } lat = time.perf_counter() - t0 raw = (resp.choices[0].message.content or "").strip() u = resp.usage return { "doc_id": did, "raw_text": raw, "parsed": extract_json_obj(raw), "prompt_tokens": int(getattr(u, "prompt_tokens", 0) or 0), "completion_tokens": int(getattr(u, "completion_tokens", 0) or 0), "latency_s": round(lat, 4), "error": None, }
# 1. Warmup + Serial p50/p95 probe (concurrency=1) serial_n = min(probe_serial_n, len(items)) if items: await one_call(*items[0]) # warmup 1 doc so JIT/prefix cache warm serial_lats: list[float] = [] for item in items[:serial_n]: r = await one_call(*item) rows.append(r) serial_lats.append(r["latency_s"])
# 2. Steady-state batched run on remainder (or full wall measurement over all items cleanly) sem = asyncio.Semaphore(concurrency) rem = items[serial_n:] t_batch0 = time.perf_counter()
async def sem_call(item: tuple[str, list[dict[str, str]], int]) -> dict[str, Any]: async with sem: return await one_call(*item)
if rem: rem_rows = await asyncio.gather(*(sem_call(it) for it in rem)) rows.extend(rem_rows) batch_wall_s = time.perf_counter() - t_batch0
# Also measure total warm throughput across all docs if serial_n < len(items) out_jsonl.write_text( "\n".join(json.dumps(r, ensure_ascii=False) for r in rows) + "\n", encoding="utf-8" ) return { "docs": len(rows), "serial_probe_n": serial_n, "p50_serial_s": round(percentile(serial_lats, 50), 3), "p95_serial_s": round(percentile(serial_lats, 95), 3), "batch_docs": len(rem), "batch_wall_s": round(batch_wall_s, 3), "batch_sec_per_doc": round(batch_wall_s / len(rem), 4) if rem else round(sum(serial_lats) / max(1, serial_n), 4), "parse_rate": round(sum(1 for r in rows if r["parsed"] is not None) / max(1, len(rows)), 4), "prompt_tokens": sum(r["prompt_tokens"] for r in rows), "completion_tokens": sum(r["completion_tokens"] for r in rows), }
async def run_all(args: argparse.Namespace) -> None: staging_dir = Path( snapshot_download(repo_id=args.staging_repo, repo_type="dataset", token=os.environ.get("HF_TOKEN")) ) out_dir = Path(args.out_dir) out_dir.mkdir(parents=True, exist_ok=True)
adapter_dir = None if args.adapter_id: adapter_dir = snapshot_download( repo_id=args.adapter_id, revision=args.adapter_rev or None, token=os.environ.get("HF_TOKEN"), )
cmd = [ sys.executable, "-m", "vllm.entrypoints.openai.api_server", "--model", args.model_id, "--tensor-parallel-size", str(args.tp), "--enable-prefix-caching", "--max-model-len", str(args.max_model_len), "--gpu-memory-utilization", str(args.gpu_mem), "--port", "8000", ] if args.revision: cmd.extend(["--revision", args.revision]) if adapter_dir: cmd.extend(["--enable-lora", "--max-lora-rank", "16", "--lora-modules", f"v3={adapter_dir}"]) if args.trust_remote_code: cmd.append("--trust-remote-code")
log_f = (out_dir / "vllm_server.log").open("wb") t_start = time.perf_counter() proc = subprocess.Popen(cmd, stdout=log_f, stderr=subprocess.STDOUT) telemetry: dict[str, Any] = { "tag": args.tag, "model_id": args.model_id, "adapter_id": args.adapter_id, "gpu_flavor": args.gpu_flavor, "hourly_rate_usd": args.hourly_rate, "tp": args.tp, "concurrency": args.concurrency, "tasks": {}, } try: load_s = wait_for_vllm("http://127.0.0.1:8000/v1", proc) telemetry["vllm_load_s"] = round(load_s, 2) print(f"[{args.tag}] vLLM ready in {load_s:.1f}s", flush=True)
base_url = "http://127.0.0.1:8000/v1" s1_model = "v3" if adapter_dir else args.model_id s2_model = args.model_id # Stage 2 VAT ALWAYS uses base model
sys_prompts = json.loads((staging_dir / "prompts_bundle.json").read_text(encoding="utf-8")) tasks = [t.strip() for t in args.tasks.split(",") if t.strip()]
def prep_oof_text(pages: list[str]) -> str: joined = "\n\n".join(f"--- PAGE {i + 1} ---\n{t}" for i, t in enumerate(pages)) if len(joined) > 24000: head = int(24000 * 0.42) tail = 24000 - head - 40 joined = joined[:head] + "\n\n...[MIDDLE_LINE_ITEMS_TRUNCATED]...\n\n" + joined[-tail:] return joined
if "oof" in tasks: oof_docs = [ json.loads(ln) for ln in (staging_dir / "oof_200_bundle.jsonl").read_text(encoding="utf-8").splitlines() if ln.strip() ][: args.limit] text_key = "pages_text_vlm" if args.use_vlm_text else "pages_text_novlm" s1_items = [ ( d["id"], [ {"role": "system", "content": sys_prompts["hack_s1"]}, {"role": "user", "content": f"Invoice ID: {d['id']}\n\n{prep_oof_text(d[text_key])}"}, ], 400, ) for d in oof_docs ] s2_items = [ ( d["id"], [ {"role": "system", "content": sys_prompts["hack_s2"]}, {"role": "user", "content": f"Invoice ID: {d['id']}\n\n{prep_oof_text(d[text_key])}"}, ], 220, ) for d in oof_docs ] telemetry["tasks"]["oof_s1"] = await run_openai_batch( base_url=base_url, model_name=s1_model, items=s1_items, out_jsonl=out_dir / f"{args.tag}_oof_s1.jsonl", concurrency=args.concurrency, ) telemetry["tasks"]["oof_s2"] = await run_openai_batch( base_url=base_url, model_name=s2_model, items=s2_items, out_jsonl=out_dir / f"{args.tag}_oof_s2.jsonl", concurrency=args.concurrency, )
if "ib" in tasks: ib_docs = [ json.loads(ln) for ln in (staging_dir / "ib_200_bundle.jsonl").read_text(encoding="utf-8").splitlines() if ln.strip() ][: args.limit] ib_items = [ ( d["id"], [ {"role": "system", "content": sys_prompts["ib_sys"]}, { "role": "user", "content": sys_prompts["ib_cond_b"].replace( "{invoice_text}", "\n\n".join(d["pdf_pages_text"]) ), }, ], 1200, ) for d in ib_docs ] telemetry["tasks"]["ib_cond_b"] = await run_openai_batch( base_url=base_url, model_name=s1_model, items=ib_items, out_jsonl=out_dir / f"{args.tag}_ib_b.jsonl", concurrency=args.concurrency, ) if args.include_native_v3: nat_items = [ ( d["id"], [ {"role": "system", "content": sys_prompts["hack_s1"]}, { "role": "user", "content": f"Invoice ID: {d['id']}\n\n" + "\n\n".join(f"--- PAGE {i + 1} ---\n{t}" for i, t in enumerate(d["pdf_pages_text"])), }, ], 400, ) for d in ib_docs ] telemetry["tasks"]["ib_native_v3"] = await run_openai_batch( base_url=base_url, model_name=s1_model, items=nat_items, out_jsonl=out_dir / f"{args.tag}_ib_native.jsonl", concurrency=args.concurrency, )
if "test" in tasks: t_docs = [ json.loads(ln) for ln in (staging_dir / "test_200_bundle.jsonl").read_text(encoding="utf-8").splitlines() if ln.strip() ][: args.limit] text_key = "pages_text_vlm" if args.use_vlm_text else "pages_text_novlm" ts1 = [ ( d["id"], [ {"role": "system", "content": sys_prompts["hack_s1"]}, {"role": "user", "content": f"Invoice ID: {d['id']}\n\n{prep_oof_text(d[text_key])}"}, ], 400, ) for d in t_docs ] ts2 = [ ( d["id"], [ {"role": "system", "content": sys_prompts["hack_s2"]}, {"role": "user", "content": f"Invoice ID: {d['id']}\n\n{prep_oof_text(d[text_key])}"}, ], 220, ) for d in t_docs ] telemetry["tasks"]["test_s1"] = await run_openai_batch( base_url=base_url, model_name=s1_model, items=ts1, out_jsonl=out_dir / f"{args.tag}_test_s1.jsonl", concurrency=args.concurrency, ) telemetry["tasks"]["test_s2"] = await run_openai_batch( base_url=base_url, model_name=s2_model, items=ts2, out_jsonl=out_dir / f"{args.tag}_test_s2.jsonl", concurrency=args.concurrency, ) finally: proc.terminate() try: proc.wait(timeout=15) except subprocess.TimeoutExpired: proc.kill() log_f.close()
telemetry["total_wall_s"] = round(time.perf_counter() - t_start, 2) (out_dir / f"{args.tag}_telemetry.json").write_text(json.dumps(telemetry, indent=2), encoding="utf-8")
api = HfApi(token=os.environ["HF_TOKEN"]) for p in sorted(out_dir.glob(f"{args.tag}_*")): api.upload_file( path_or_fileobj=str(p), path_in_repo=f"results/{args.tag}/{p.name}", repo_id=args.staging_repo, repo_type="dataset", ) print(f"[{args.tag}] UPLOADED ALL RESULTS cleanly", flush=True)
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--staging-repo", default="RishyanthReddy/basel-pareto-eval-staging") ap.add_argument("--tag", required=True) ap.add_argument("--model-id", required=True) ap.add_argument("--revision", default="") ap.add_argument("--adapter-id", default="") ap.add_argument("--adapter-rev", default="") ap.add_argument("--gpu-flavor", default="rtx-pro-6000") ap.add_argument("--hourly-rate", type=float, default=2.75) ap.add_argument("--tp", type=int, default=1) ap.add_argument("--concurrency", type=int, default=8) ap.add_argument("--max-model-len", type=int, default=12288) ap.add_argument("--gpu-mem", type=float, default=0.90) ap.add_argument("--tasks", default="oof,ib") ap.add_argument("--limit", type=int, default=None) ap.add_argument("--use-vlm-text", action="store_true") ap.add_argument("--include-native-v3", action="store_true") ap.add_argument("--trust-remote-code", action="store_true") ap.add_argument("--out-dir", default="/tmp/bench_out") args = ap.parse_args() asyncio.run(run_all(args))
if __name__ == "__main__": main()hf_gpu_runner.pyAdded+456