ysharma's picture
ysharma HF Staff
v3: vllm nightly, KV-mode fallback, 12k ctx, full server-log dump on failure
d282750 verified
Raw History Blame Contribute Delete
13.3 kB
"""Eval: nvidia/NVIDIA-Nemotron-Labs-Dory1.0-4B-BF16 on 60 MATH-500 problems at 1/2/4 loops.
Serves the model with vLLM (PR #60149) once per loop count, sends the same 60
problems, records accuracy / per-problem latency / generated tokens, pushes
incremental results and plots to ysharma/dory1-4b-math500-loop-eval.
"""
import asyncio
import json
import os
import re
import subprocess
import sys
import time
import urllib.request
MODEL = "nvidia/NVIDIA-Nemotron-Labs-Dory1.0-4B-BF16"
RESULTS_REPO = "ysharma/dory1-4b-math500-loop-eval"
LOOP_COUNTS = [1, 2, 4]
N_PROBLEMS = 60
SAMPLE_SEED = 42
CONCURRENCY = 8
MAX_TOKENS = 11264
MAX_MODEL_LEN = 12288
TEMPERATURE = 1.0
TOP_P = 0.95
REQ_SEED = 1234
PORT = 8000
BASE_URL = f"http://127.0.0.1:{PORT}/v1"
OUT_DIR = "/app/results"
HEALTH_TIMEOUT_S = 900
REQ_TIMEOUT_S = 1500
os.makedirs(OUT_DIR, exist_ok=True)
# ---------- fast assertions ----------
import torch
assert torch.cuda.is_available(), "No CUDA GPU visible — refusing to run on CPU"
print(f"[env] GPU: {torch.cuda.get_device_name(0)}, "
f"{torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB", flush=True)
from datasets import load_dataset
ds = load_dataset("HuggingFaceH4/MATH-500", split="test")
assert len(ds) == 500, f"expected 500 MATH-500 rows, got {len(ds)}"
assert "problem" in ds.column_names and "answer" in ds.column_names
sample = ds.shuffle(seed=SAMPLE_SEED).select(range(N_PROBLEMS))
problems = [{"unique_id": r["unique_id"], "problem": r["problem"], "answer": r["answer"],
"level": r["level"], "subject": r["subject"]} for r in sample]
assert all(p["answer"].strip() for p in problems)
levels = {}
for p in problems:
levels[p["level"]] = levels.get(p["level"], 0) + 1
print(f"[data] {len(problems)} problems (seed {SAMPLE_SEED}), level mix: {levels}", flush=True)
with open(f"{OUT_DIR}/sample_problems.json", "w") as f:
json.dump(problems, f, indent=2)
# ---------- grading ----------
from math_verify import parse as mv_parse, verify as mv_verify
BOXED_RE = re.compile(r"\\boxed\{")
def extract_boxed(text):
"""Return the last \\boxed{...} with balanced braces, or None."""
best = None
for m in BOXED_RE.finditer(text):
i = m.end()
depth = 1
while i < len(text) and depth > 0:
if text[i] == "{":
depth += 1
elif text[i] == "}":
depth -= 1
i += 1
if depth == 0:
best = text[m.end():i - 1]
return best
def grade(pred_text, gold_answer):
"""True/False/None (None = could not grade)."""
try:
gold = mv_parse("$" + gold_answer + "$")
if not gold:
gold = mv_parse(gold_answer)
except Exception:
return None
if not gold:
return None
for cand in (pred_text, extract_boxed(pred_text)):
if not cand:
continue
try:
parsed = mv_parse(cand)
if parsed:
return bool(mv_verify(gold, parsed))
except Exception:
continue
return None
# ---------- server ----------
def server_cmd(n_loops, kv_mode):
overrides = json.dumps({"n_recurrent_loops": n_loops,
"recurrent_kv_cache_mode": kv_mode})
return ["vllm", "serve", MODEL,
"--port", str(PORT),
"--hf-overrides", overrides,
"--max-model-len", str(MAX_MODEL_LEN),
"--max-num-seqs", "16",
"--gpu-memory-utilization", "0.90",
"--reasoning-parser", "nemotron_v3"]
def dump_log_tail(log_path, nbytes=20000):
with open(log_path, "rb") as f:
f.seek(0, 2)
size = f.tell()
f.seek(max(0, size - nbytes))
print(f"[server-log tail {log_path}]\n{f.read().decode(errors='replace')}\n", flush=True)
def start_server(n_loops, log_path):
"""Launch vLLM at n_loops. Try per_loop KV (card's benchmarked mode); if the
engine fails KV profiling, retry once with last_loop (card: accuracy close,
output lengths nearly unchanged) and record which mode was used."""
for kv_mode in ("per_loop", "last_loop"):
cmd = server_cmd(n_loops, kv_mode)
print(f"[server] launching ({kv_mode}): {' '.join(cmd)}", flush=True)
log = open(log_path, "w")
proc = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT)
t0 = time.time()
while time.time() - t0 < HEALTH_TIMEOUT_S:
if proc.poll() is not None:
log.close()
print(f"[server] vLLM exited early at {n_loops} loops, kv_mode={kv_mode}", flush=True)
dump_log_tail(log_path)
if kv_mode == "per_loop":
print("[server] retrying with recurrent_kv_cache_mode=last_loop", flush=True)
break
raise RuntimeError(f"vLLM server failed at {n_loops} loops even with last_loop KV")
try:
with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/health", timeout=5) as r:
if r.status == 200:
print(f"[server] healthy after {time.time()-t0:.0f}s "
f"(n_recurrent_loops={n_loops}, kv_mode={kv_mode})", flush=True)
return proc, log, kv_mode
except Exception:
time.sleep(5)
if time.time() - t0 >= HEALTH_TIMEOUT_S:
proc.kill()
raise RuntimeError(f"vLLM health check timed out after {HEALTH_TIMEOUT_S}s at {n_loops} loops")
raise RuntimeError("unreachable")
# ---------- inference ----------
async def run_batch(problems, n_loops, kv_mode):
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url=BASE_URL, api_key="EMPTY")
sem = asyncio.Semaphore(CONCURRENCY)
async def one(p):
async with sem:
t0 = time.perf_counter()
try:
resp = await asyncio.wait_for(
client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": p["problem"]}],
max_tokens=MAX_TOKENS,
temperature=TEMPERATURE,
top_p=TOP_P,
seed=REQ_SEED,
),
timeout=REQ_TIMEOUT_S)
except Exception as e:
return {"unique_id": p["unique_id"], "level": p["level"],
"loops": n_loops, "kv_mode": kv_mode, "error": f"{type(e).__name__}: {e}",
"latency_s": time.perf_counter() - t0,
"completion_tokens": None, "correct": None,
"finish_reason": "error", "truncated": False}
dt = time.perf_counter() - t0
msg = resp.choices[0]
content = msg.message.content or ""
reasoning = getattr(msg.message, "reasoning_content", None) or ""
n_completion = resp.usage.completion_tokens if resp.usage else None
truncated = msg.finish_reason == "length"
correct = grade(content, p["answer"]) if not truncated else False
if correct is None: # grader failed on content, try reasoning text
correct = grade(reasoning, p["answer"])
return {"unique_id": p["unique_id"], "level": p["level"], "loops": n_loops,
"kv_mode": kv_mode,
"latency_s": round(dt, 2), "completion_tokens": n_completion,
"n_reasoning_chars": len(reasoning), "n_content_chars": len(content),
"finish_reason": msg.finish_reason, "truncated": truncated,
"predicted": extract_boxed(content), "gold": p["answer"],
"correct": correct}
t0 = time.perf_counter()
results = await asyncio.gather(*(one(p) for p in problems))
wall = time.perf_counter() - t0
errors = sum(1 for r in results if r.get("error"))
print(f"[eval] {n_loops} loops: 60 requests done in {wall:.0f}s "
f"({errors} request errors)", flush=True)
return results, wall
def push_to_hub(local_path, path_in_repo):
from huggingface_hub import HfApi
HfApi().upload_file(path_or_fileobj=local_path, path_in_repo=path_in_repo,
repo_id=RESULTS_REPO, repo_type="dataset",
commit_message=f"eval results: {path_in_repo}")
print(f"[push] {path_in_repo} -> {RESULTS_REPO}", flush=True)
# ---------- main ----------
async def main():
all_results = {}
for n_loops in LOOP_COUNTS:
log_path = f"{OUT_DIR}/server_loops{n_loops}.log"
proc, log, kv_mode = start_server(n_loops, log_path)
try:
# 2-problem smoke before the full batch
smoke, _ = await run_batch(problems[:2], n_loops, kv_mode)
if any(r.get("error") for r in smoke):
raise RuntimeError(f"smoke requests failed at {n_loops} loops: {smoke}")
results, wall = await run_batch(problems, n_loops, kv_mode)
all_results[n_loops] = results
with open(f"{OUT_DIR}/results_loops{n_loops}.jsonl", "w") as f:
for r in results:
f.write(json.dumps(r) + "\n")
push_to_hub(f"{OUT_DIR}/results_loops{n_loops}.jsonl", f"results/results_loops{n_loops}.jsonl")
acc = [r["correct"] for r in results if r["correct"] is not None]
toks = [r["completion_tokens"] for r in results if r["completion_tokens"]]
lat = [r["latency_s"] for r in results if not r.get("error")]
print(f"[summary] loops={n_loops}: accuracy={sum(acc)}/{len(acc)}"
f" mean_tokens={sum(toks)/len(toks):.0f}"
f" median_tokens={sorted(toks)[len(toks)//2]}"
f" mean_latency={sum(lat)/len(lat):.1f}s"
f" batch_wall={wall:.0f}s"
f" truncated={sum(1 for r in results if r['truncated'])}", flush=True)
finally:
proc.terminate()
try:
proc.wait(timeout=30)
except subprocess.TimeoutExpired:
proc.kill()
log.close()
time.sleep(10) # let VRAM free before next server
# ---------- aggregate + plots ----------
summary = {}
for n_loops, results in all_results.items():
acc = [r["correct"] for r in results if r["correct"] is not None]
toks = [r["completion_tokens"] for r in results if r["completion_tokens"]]
lat = [r["latency_s"] for r in results if not r.get("error")]
summary[n_loops] = {
"n_graded": len(acc),
"accuracy": sum(acc) / len(acc) if acc else None,
"mean_completion_tokens": sum(toks) / len(toks) if toks else None,
"median_completion_tokens": sorted(toks)[len(toks) // 2] if toks else None,
"mean_latency_s": sum(lat) / len(lat) if lat else None,
"n_truncated": sum(1 for r in results if r["truncated"]),
"n_request_errors": sum(1 for r in results if r.get("error")),
}
print("\n===== SUMMARY (60 MATH-500 problems, Dory1.0-4B BF16) =====", flush=True)
for n in LOOP_COUNTS:
s = summary[n]
print(f"loops={n}: accuracy={s['accuracy']*100:.1f}% "
f"mean_out_tokens={s['mean_completion_tokens']:.0f} "
f"median_out_tokens={s['median_completion_tokens']} "
f"mean_latency={s['mean_latency_s']:.1f}s "
f"truncated={s['n_truncated']} errors={s['n_request_errors']}", flush=True)
if 1 in summary and 4 in summary and summary[1]["mean_completion_tokens"] and summary[4]["mean_completion_tokens"]:
ratio = summary[4]["mean_completion_tokens"] / summary[1]["mean_completion_tokens"]
verdict = "card claim SUPPORTED" if ratio < 1 else "card claim NOT supported on this subset"
print(f"[claim] mean output tokens, 4 loops vs 1 loop: {ratio:.2f}x ({verdict})", flush=True)
with open(f"{OUT_DIR}/summary.json", "w") as f:
json.dump(summary, f, indent=2)
push_to_hub(f"{OUT_DIR}/summary.json", "results/summary.json")
push_to_hub(f"{OUT_DIR}/sample_problems.json", "results/sample_problems.json")
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
xs = [n for n in LOOP_COUNTS if n in summary]
fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
axes[0].plot(xs, [summary[n]["accuracy"] * 100 for n in xs], "o-")
axes[0].set_ylabel("accuracy (%)")
axes[1].plot(xs, [summary[n]["mean_latency_s"] for n in xs], "s-", color="tab:orange")
axes[1].set_ylabel("mean latency per problem (s)")
axes[2].plot(xs, [summary[n]["mean_completion_tokens"] for n in xs], "^-", color="tab:green")
axes[2].set_ylabel("mean output tokens")
for ax in axes:
ax.set_xlabel("recurrent loops")
ax.set_xticks(xs)
fig.suptitle("Dory1.0-4B BF16 — 60 MATH-500 problems (seed 42, temp 1.0, top-p 0.95)")
fig.tight_layout()
fig.savefig(f"{OUT_DIR}/dory_math500_loops.png", dpi=150)
push_to_hub(f"{OUT_DIR}/dory_math500_loops.png", "dory_math500_loops.png")
print("[done] all results pushed", flush=True)
asyncio.run(main())