Nanthasit's picture
Fix validator bench path
3d2aed7 verified
Raw
History Blame Contribute Delete
5.06 kB
"""Validate every non-GPU part of the job script against real rows, locally.
The meta-lesson from the earlier fast-fails: anything that isn't the GPU itself
gets proven here first. Checks:
1. renderer runs on every v7 + bench row without raising, and emits sane ChatML
2. the bench-exclusion filter reproduces the builder's arithmetic
3. the eval scorer is an oracle-pass: gold output must score 100% in every
category, otherwise the metric is broken before the model ever runs
4. token-length distribution vs MAX_LEN (silent truncation check)
"""
import json, re, sys, collections, importlib.util, pathlib
# Lift the pure functions out of the job script verbatim — no torch, no training
# body — so what is validated here is exactly the code that will run on the GPU.
src = pathlib.Path("job-0.5b-v7.py").read_text()
start = src.index("def _text(c):")
end = src.index("# ── Data: v7 minus")
ns = {"json": json, "hashlib": __import__("hashlib")}
exec(compile(src[start:end], "job-pure", "exec"), ns)
render_chatml = ns["render_chatml"]
fingerprint = ns["fingerprint"]
_TC = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", re.DOTALL)
def _pred(t):
o = []
for mm in _TC.findall(t):
try: o.append(json.loads(mm).get("name"))
except Exception: pass
return [n for n in o if n]
def load(p):
return [json.loads(l) for l in open(p) if l.strip()]
train = load("v7/data/train.jsonl")
bench = load("bench/data/test.jsonl")
excl = json.load(open("bench/train_exclude_fingerprints.json"))
EXCLUDE, HELD = set(excl["fingerprints"]), set(excl["held_out_tools"])
fail = 0
# ── 1. renderer ──────────────────────────────────────────────────────────
bad, empty = 0, 0
lens = []
for ds, name in ((train, "v7 train"), (bench, "bench")):
for i, ex in enumerate(ds):
try:
t = render_chatml(ex["messages"], ex.get("tools") or None)
except Exception as e:
bad += 1
if bad <= 3: print(f" RENDER FAIL {name}[{i}]: {type(e).__name__}: {e}")
continue
if not t or len(t) < 20:
empty += 1
lens.append(len(t))
if "<|im_start|>" not in t or "<|im_end|>" not in t:
bad += 1
print(f"1. renderer: {len(lens)} rows rendered, {bad} failures, {empty} suspiciously short")
fail += bad + empty
# ── 2. exclusion filter reproduces the builder ───────────────────────────
def keep(ex):
if fingerprint(ex["messages"]) in EXCLUDE:
return False
names = {(t.get("function") or {}).get("name") or t.get("name") for t in (ex.get("tools") or [])}
return not (names & HELD)
kept = [ex for ex in train if keep(ex)]
bench_fps = {r["fingerprint"] for r in bench}
leaked = sum(1 for ex in kept if fingerprint(ex["messages"]) in bench_fps)
tool_leak = sum(1 for ex in kept
if {(t.get("function") or {}).get("name") or t.get("name")
for t in (ex.get("tools") or [])} & HELD)
print(f"2. filter: {len(train)} -> {len(kept)} kept; bench rows leaked into train: {leaked}; "
f"held-out tool schemas visible: {tool_leak}")
fail += leaked + tool_leak
# ── 3. oracle pass on the eval scorer ────────────────────────────────────
buckets = collections.defaultdict(lambda: [0, 0])
for ex in bench:
msgs, cat, gold = ex["messages"], ex["category"], ex["gold_tools"]
idx = next((i for i, m in enumerate(msgs) if m.get("role") == "assistant"), None)
if idx is None:
continue
# the oracle emits exactly what the reference assistant turn contains
body = ns["_assistant_body"](msgs[idx])
pred = _pred(body)
if cat.startswith("irrelevance"):
ok = len(pred) == 0
elif cat == "simple":
ok = bool(gold) and gold[0] in pred
else:
ok = set(gold).issubset(set(pred))
buckets[cat][0] += int(ok); buckets[cat][1] += 1
print("3. oracle scorer (gold output must score 100%):")
for c in ("simple", "parallel", "irrelevance_tools", "irrelevance_no_tools"):
p, t = buckets[c]
flag = "" if p == t else " <-- BROKEN"
print(f" {c:<22}{p:>4}/{t:<4} {100*p/t if t else 0:5.1f}%{flag}")
fail += (t - p)
# ── 4. truncation ────────────────────────────────────────────────────────
# rough char->token ratio for Qwen on this data is ~3.4 chars/token
approx = sorted(l / 3.4 for l in lens)
over = sum(1 for a in approx if a > 1536)
p50, p95, p99 = (approx[int(len(approx) * q)] for q in (0.5, 0.95, 0.99))
print(f"4. length: ~p50={p50:.0f} p95={p95:.0f} p99={p99:.0f} tokens; "
f"{over} rows ({100*over/len(approx):.1f}%) exceed MAX_LEN=1536")
print("\nRESULT:", "PASS" if fail == 0 else f"FAIL ({fail} problems)")
sys.exit(1 if fail else 0)