"""Model preflight: serve one model on given GPUs, run 10 representative prompts, check template/parsing, measure latency, throughput, GPU memory. Usage: python preflight.py MODEL_ID GPUS(comma) PORT""" import json, os, re, subprocess, sys, time, asyncio sys.path.insert(0, "src") from pathlib import Path import httpx from llmroute.seqroute import serve as S from llmroute.seqroute.client import run_jobs, read_ids mid, gpus, port = sys.argv[1], [int(x) for x in sys.argv[2].split(",")], int(sys.argv[3]) spec = {m["id"]: m for m in json.load(open("/mnt/localssd/seqroute1m/scripts/models_spec.json"))}[mid] out_dir = Path("/mnt/localssd/seqroute1m/manifests/preflight"); out_dir.mkdir(parents=True, exist_ok=True) PROMPTS = [ ("math", "Solve the following math problem. Think step by step, then give the final answer on the last line in the form 'Final answer: \\boxed{ANSWER}'.\n\nJanet has 3 boxes with 12 apples each and gives away 7 apples. How many apples are left?", r"\\boxed\{29\}"), ("mc", "Answer the following multiple-choice question. Think step by step, then finish with a final line of the form 'Final answer: X' where X is the letter of the correct option.\n\nWhich planet is known as the Red Planet?\n\nA. Venus\nB. Mars\nC. Jupiter\nD. Mercury", r"Final answer:\s*\**\(?B"), ("code", "Write a Python function for the task below. Reply with the complete code in a single ```python code block, followed by nothing else.\n\nWrite a function add(a, b) that returns the sum of two numbers.", r"```python"), ("summ", "Summarize the following document accurately and concisely in at most 30 words.\n\n=== DOCUMENT ===\nThe city council voted 7-2 on Tuesday to approve a new bike lane network spanning 40 kilometres. Construction begins in March and is expected to cost 12 million dollars, funded partly by a state grant.\n\n=== SUMMARY ===\n", r"bike|lane"), ("json", 'Extract the fields as JSON with keys "name" and "age" only.\n\nText: Maria Lopez, who is 34, works as an engineer.\n\nJSON:', r'"name"'), ("translation", "Translate the following English text into German. Output only the German translation.\n\nThe weather is nice today.", r"Wetter"), ("instruction", "Write one sentence about the ocean. Your answer must be entirely in lowercase letters.", r"ocean"), ("logic", "All bloops are razzies and all razzies are lazzies. Are all bloops definitely lazzies? Think briefly, then end with 'Final answer: Yes' or 'Final answer: No'.", r"Final answer:\s*\**Yes"), ("class", "Classify the sentiment of the review as positive or negative. Reply with one word.\n\nReview: I loved this movie, it was fantastic.", r"(?i)positive"), ("long", "List three prime numbers greater than 10, separated by commas, and nothing else.", r"\d"), ] res = dict(model=mid, gpus=gpus, spec=spec, started=time.strftime("%F %T")) S.PIDS = Path(f"/mnt/localssd/seqroute1m/logs/servers_{mid}.pids") gcount = len(gpus) cmd = [S.VLLM, "serve", str(S.MODELS / mid), "--served-model-name", mid, "--port", str(port), "--seed", "0", "--trust-remote-code", "--max-model-len", str(spec["max_model_len"]), "--gpu-memory-utilization", "0.92", "--max-num-seqs", "128", "--enable-prefix-caching", "--tensor-parallel-size", str(spec["tp"]), *spec["serve_args"]] log = open(f"/mnt/localssd/seqroute1m/logs/preflight_serve_{mid}.log", "w") t0 = time.time() p = subprocess.Popen(cmd, env=dict(S.ENV, CUDA_VISIBLE_DEVICES=",".join(map(str, gpus))), stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, start_new_session=True) try: ok = False while time.time() - t0 < 1500: if p.poll() is not None: break try: if httpx.get(f"http://127.0.0.1:{port}/v1/models", timeout=3).status_code == 200: ok = True; break except Exception: pass time.sleep(5) res["server_ready"] = ok; res["startup_s"] = time.time() - t0 if not ok: res["error"] = "server did not start; see log" else: mem = subprocess.run(["nvidia-smi", "--query-gpu=index,memory.used", "--format=csv,noheader,nounits"], capture_output=True, text=True).stdout res["gpu_mem_mib"] = {l.split(",")[0].strip(): int(l.split(",")[1]) for l in mem.strip().splitlines() if int(l.split(",")[0]) in gpus} tmpf = Path(f"/mnt/localssd/seqroute1m/manifests/preflight/{mid}_smoke.jsonl"); tmpf.unlink(missing_ok=True) params = dict(temperature=spec["temperature"], top_p=spec["top_p"], chat_template_kwargs=spec["chat_template_kwargs"], system=spec.get("system")) budget = 8192 if spec["reasoning"] else 1024 jobs = [dict(id=f"{n}", prompt=pr, max_tokens=budget, seed=i) for i, (n, pr, rx) in enumerate(PROMPTS)] t1 = time.time(); st = run_jobs(jobs, tmpf, mid, [port], params, per_server=1, every=100); res["latency_c1_total_s"] = time.time() - t1 recs = {json.loads(l)["id"]: json.loads(l) for l in open(tmpf)} checks = {} for n, pr, rx in PROMPTS: r = recs.get(n) if r is None: checks[n] = "missing"; continue final = r["text"].split("")[-1] if "" in r["text"] else r["text"] checks[n] = dict(nonempty=bool(final.strip()), regex_ok=bool(re.search(rx, final, re.S)), finish=r["finish_reason"], tokens=r["completion_tokens"], has_reasoning_field=bool(r.get("reasoning")), has_lp=("mean_lp" in r), sample=final.strip()[:160]) res["checks"] = checks # throughput at concurrency 64 on repeated mixed prompts tmp2 = Path(f"/mnt/localssd/seqroute1m/manifests/preflight/{mid}_bench.jsonl"); tmp2.unlink(missing_ok=True) bj = [dict(id=f"b{i}", prompt=PROMPTS[i % len(PROMPTS)][1] + f"\n\n(Variant {i})", max_tokens=min(budget, 1024), seed=i) for i in range(128)] t2 = time.time(); run_jobs(bj, tmp2, mid, [port], params, per_server=64, every=1000); wall = time.time() - t2 rows = [json.loads(l) for l in open(tmp2)] assert rows, 'bench produced no rows: ' + (open(str(tmp2)+'.errors').read()[:500] if Path(str(tmp2)+'.errors').exists() else '') res["bench"] = dict(n=len(rows), wall_s=wall, completion_tokens=sum(r["completion_tokens"] for r in rows), prompt_tokens=sum(r["prompt_tokens"] for r in rows), gpus=gcount, tok_per_s_per_replica=sum(r["completion_tokens"] for r in rows) / wall, mean_latency_s=sum(r["latency_s"] for r in rows) / len(rows)) finally: import signal try: os.killpg(os.getpgid(p.pid), signal.SIGTERM) except Exception: pass res["finished"] = time.strftime("%F %T") json.dump(res, open(out_dir / f"{mid}.json", "w"), indent=1) print(mid, "ready" if res.get("server_ready") else "FAILED", {k: v["regex_ok"] if isinstance(v, dict) else v for k, v in res.get("checks", {}).items()}, flush=True)