Launch80's picture
Quality-eval reference: BF16 logits, v1.0 arm, eval set, calibration set, scripts
e8eb104 verified
Raw History Blame Contribute Delete
3.25 kB
#!/usr/bin/env python3
"""Teacher-forced top-k logprobs for every window of eval-set.json from any vLLM OpenAI server.
uv run --with numpy python logprobs.py --base http://127.0.0.1:8002 --model <id> \
--set eval-set.json --out arm.npz [--topk 64] [--sets kld,ppl-wiki,ppl-code] [--workers 4]
Server needs `--max-logprobs 64` and speculation OFF (prompt_logprobs is NaN under MTP on the
B65 stack). Per set, writes:
<set>.target float32 [W, L-1] logprob of the true next token (positions 1..L-1)
<set>.ids int32 [W, L-1, k] top-k token ids
<set>.lp float16 [W, L-1, k] their logprobs
"""
import argparse, json, math, time, urllib.request
from concurrent.futures import ThreadPoolExecutor
import numpy as np
ap = argparse.ArgumentParser()
ap.add_argument("--base", required=True); ap.add_argument("--model", required=True)
ap.add_argument("--set", required=True); ap.add_argument("--out", required=True)
ap.add_argument("--topk", type=int, default=64); ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--sets", default="kld,ppl-wiki,ppl-code")
ap.add_argument("--api-key", default="local")
a = ap.parse_args()
es = json.load(open(a.set))
def score(ids):
body = {"model": a.model, "prompt": ids, "max_tokens": 1, "temperature": 0,
"prompt_logprobs": a.topk, "add_special_tokens": False}
for attempt in range(5):
try:
req = urllib.request.Request(a.base.rstrip("/") + "/v1/completions", json.dumps(body).encode(),
{"Content-Type": "application/json", "Authorization": f"Bearer {a.api_key}"})
pl = json.load(urllib.request.urlopen(req, timeout=1800))["choices"][0]["prompt_logprobs"]
break
except Exception as ex:
if attempt == 4:
raise
print(f" retry {attempt + 1}: {ex}", flush=True); time.sleep(10)
L = len(ids)
tgt = np.empty(L - 1, np.float32); tid = np.zeros((L - 1, a.topk), np.int32)
tlp = np.full((L - 1, a.topk), -np.inf, np.float16)
for p in range(1, L):
d = pl[p] # {token_id: {"logprob": x, "rank": r, ...}}; includes the true token
tgt[p - 1] = d[str(ids[p])]["logprob"]
top = sorted(((int(t), v["logprob"]) for t, v in d.items() if v.get("rank", 0) <= a.topk),
key=lambda x: -x[1])[:a.topk]
for j, (t, lp) in enumerate(top):
tid[p - 1, j] = t; tlp[p - 1, j] = lp
if not np.isfinite(tgt).all():
raise SystemExit("non-finite prompt logprobs: is speculation on?")
return tgt, tid, tlp
out = {}
for s in a.sets.split(","):
W = es[s]; t0 = time.time()
with ThreadPoolExecutor(a.workers) as ex:
res = list(ex.map(score, W))
out[f"{s}.target"] = np.stack([r[0] for r in res]); out[f"{s}.ids"] = np.stack([r[1] for r in res])
out[f"{s}.lp"] = np.stack([r[2] for r in res])
nll = -out[f"{s}.target"].mean()
print(f"{s}: {len(W)} windows, ppl {math.exp(nll):.4f}, {time.time() - t0:.0f}s", flush=True)
np.savez_compressed(a.out, **out, meta=json.dumps({"model": a.model, "topk": a.topk,
"eval_set_sha256": es["meta"]["sha256_ids"]}))
print("wrote", a.out)