ChihHsuan-Yang's picture
Document the confidence scale and null handling; correct the fallback-row statement; note AUPRC tie sensitivity
5c5c8b4 verified
Raw
History Blame Contribute Delete
22 kB
#!/usr/bin/env python3
"""Validate a downloaded copy of the Cost-Aware Protocol Routing dataset.
Usage
-----
python validate.py # validate the directory this file is in
python validate.py --dir PATH # validate another directory
python validate.py --skip-checksums
Exits 0 if every check passes, 1 on a validation failure, 2 on a usage error.
Requires ONLY the Python standard library -- no pandas, no numpy, nothing to
install. It is meant to be the first thing you run after `hf download`.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import os
import sys
EXPECTED_RELEASE_VERSION = "1.0.0"
EXPECTED_SCHEMA_VERSION = "emnlp-protocol-routing-dataset-v1.0.0"
PROTOCOLS = ["baseline_llm", "single_agent", "per", "broadcast"]
ORACLE_LABELS = PROTOCOLS + ["none"]
REQUIRED_FILES = [
"README.md", "LICENSE", "NOTICE", "CITATION.cff",
"registry/experiments.csv", "registry/benchmarks.csv", "registry/models.csv",
"registry/protocols.csv", "registry/schema.json",
"registry/release_manifest.json", "registry/checksums.sha256",
"data/matched_labels.csv", "data/problems.csv", "data/labels_for_scoring.csv",
"data/probe_inputs.jsonl",
"data/splits/six_setting_splits.csv", "data/splits/primary_omnimath_splits.csv",
"data/router/six_setting_test_predictions.csv", "data/router/six_setting_metrics.csv",
"data/confidence/six_setting_confidence_metrics.csv",
"data/confidence/primary_omnimath_confidence_predictions.csv",
"data/confidence/postanswer_confidence_predictions.csv",
"data/confidence/failure_and_protocol_value_targets.csv",
"data/costs/omnimath_per_protocol_costs.csv",
"registry/example_id_crosswalk.csv",
"docs/confidence_probe_prompt.txt", "docs/primary_confidence_probe_prompt.txt",
"TODO.md", "validate.py",
"data/aggregate/matched_protocol_coverage.csv",
"data/aggregate/oracle_label_distribution.csv",
"data/aggregate/main_routing_heldout.csv",
"docs/schema.md", "docs/provenance.md", "docs/license_audit.md",
"docs/reconstruction.md", "docs/anonymization_report.md",
]
# Optional artifacts: absent by design, listed so their absence is explicit.
OPTIONAL_ARTIFACTS = {
"data/problem_text.csv":
"upstream problem text (withheld for licensing; see docs/reconstruction.md)",
"data/baseline_final_answers.csv":
"Baseline final-answer text (NOT released; probe is not re-runnable without it)",
"data/traces/":
"raw protocol traces / model generations (out of scope for this table-first release)",
"data/costs/other_settings_per_protocol_costs.csv":
"per-problem costs for the other 9 settings (UNRESOLVED -- must not be "
"back-filled from an incompatible token convention; see TODO.md)",
}
EXPECTED_ROWS = {
"data/matched_labels.csv": 15088,
"data/problems.csv": 6803,
"data/labels_for_scoring.csv": 12928,
"data/probe_inputs.jsonl": 12928,
"data/splits/six_setting_splits.csv": 12928,
"data/splits/primary_omnimath_splits.csv": 4181,
"data/router/six_setting_test_predictions.csv": 5832,
"data/confidence/primary_omnimath_confidence_predictions.csv": 839,
"data/confidence/postanswer_confidence_predictions.csv": 12928,
"registry/example_id_crosswalk.csv": 12928,
"data/costs/omnimath_per_protocol_costs.csv": 4155,
}
EXPECTED_SETTINGS = {
"omnimath2__competition_math_4181__gpt_oss_120b": 4181,
"omnimath2__competition_math_4181__gemma_4_31b": 4181,
"labbench__text_no_tool__gpt_oss_120b_text_no_tool": 1542,
"labbench__text_no_tool__gemma_4_31b_text_no_tool": 1542,
"labbench__llm_strict__gpt_oss_120b": 741,
"labbench__llm_strict__gemma_4_31b": 741,
"scibench__text_only__gpt_oss_120b": 565,
"scibench__text_only__gemma_4_31b": 565,
"jeebench__text_only__gpt_oss_120b": 515,
"jeebench__text_only__gemma_4_31b": 515,
}
EXPECTED_BENCHMARKS = {"omnimath2": 4181, "labbench": 1542, "scibench": 565, "jeebench": 515}
EXPECTED_MODELS = {"gpt_oss_120b": 5, "gemma_4_31b": 5}
# Files that must never contain outcome/label columns.
FEATURE_FILES = [
"data/problems.csv", "data/probe_inputs.jsonl",
"data/splits/six_setting_splits.csv", "data/splits/primary_omnimath_splits.csv",
"data/confidence/primary_omnimath_confidence_predictions.csv",
"data/confidence/postanswer_confidence_predictions.csv",
"data/costs/omnimath_per_protocol_costs.csv",
]
FORBIDDEN_IN_FEATURES = {
"oracle_label", "baseline_correct", "single_correct", "per_correct",
"broadcast_correct", "any_protocol_solved", "answer", "gold", "gold_answer",
"problem_text", "question", "reference_solution", "options",
"baseline_final_answer", "baseline_final_passed", "cheapest_successful_protocol",
}
# Infrastructure that download tools and version control create alongside the
# release. Not release content, so never expected in checksums.sha256. Matched by
# PATH COMPONENT, so any depth is covered (e.g. .cache/huggingface/download/*.lock).
IGNORED_DIR_COMPONENTS = {".cache", ".git", "__pycache__", ".ipynb_checkpoints"}
IGNORED_BASENAMES = {".gitattributes", ".gitignore", ".DS_Store", ".gitmodules", "Thumbs.db"}
MAX_LISTED_OFFENDERS = 10
FAILS: list[str] = []
WARNS: list[str] = []
def is_infrastructure(rel_path: str) -> bool:
"""True for tool-created files that are not part of the release payload."""
parts = rel_path.replace(os.sep, "/").split("/")
if any(part in IGNORED_DIR_COMPONENTS for part in parts[:-1]):
return True
return parts[-1] in IGNORED_BASENAMES
def abbreviate(items: "list[str]", limit: int = MAX_LISTED_OFFENDERS) -> str:
"""Render a list without letting it swamp the output."""
shown = ", ".join(items[:limit])
if len(items) > limit:
shown += f", ... and {len(items) - limit} more"
return shown
def ok(label: str, passed: bool, detail: str = "", fail_detail: str = "") -> bool:
"""Report one check.
`detail` is a factual measurement and prints either way. `fail_detail`
explains what went wrong and prints ONLY on failure -- a check must never
print a reason that contradicts its own verdict.
"""
shown = detail if passed else (fail_detail or detail)
print(f" [{'PASS' if passed else 'FAIL'}] {label}" + (f" -- {shown}" if shown else ""))
if not passed:
FAILS.append(f"{label}: {shown}" if shown else label)
return passed
def head(title: str) -> None:
print(f"\n{title}\n{'-' * len(title)}")
def sha256(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def read_csv(path: str) -> "list[dict[str, str]]":
"""Read a CSV into a list of dicts using only the stdlib.
Empty cells come back as the empty string, never as a float NaN. Callers
that care about missing values must test for "" explicitly -- absence must
not be allowed to read as a value.
"""
with open(path, newline="", encoding="utf-8") as fh:
return list(csv.DictReader(fh))
def header(path: str) -> "list[str]":
with open(path, newline="", encoding="utf-8") as fh:
return next(csv.reader(fh), [])
def count_distinct(rows, key_col, group_col):
"""{group value: number of distinct key_col values}."""
acc = {}
for r in rows:
acc.setdefault(r[group_col], set()).add(r[key_col])
return {k: len(v) for k, v in acc.items()}
def count_rows(rows, group_col):
acc = {}
for r in rows:
acc[r[group_col]] = acc.get(r[group_col], 0) + 1
return acc
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--dir", default=os.path.dirname(os.path.abspath(__file__)))
ap.add_argument("--skip-checksums", action="store_true")
args = ap.parse_args()
root = os.path.abspath(args.dir)
print("=" * 72)
print("Cost-Aware Protocol Routing -- dataset validation")
print("=" * 72)
print(f"Directory: {root}")
# ---- versions -------------------------------------------------------
head("Versions")
mpath = os.path.join(root, "registry/release_manifest.json")
if not os.path.exists(mpath):
ok("registry/release_manifest.json present", False, "missing")
print("\nCannot continue without the manifest.")
return 1
man = json.load(open(mpath))
rv, sv = man.get("dataset_version"), man.get("schema_version")
print(f" release version : {rv}")
print(f" schema version : {sv}")
print(f" generated (UTC) : {man.get('generated_utc')}")
ok("release version matches", rv == EXPECTED_RELEASE_VERSION, f"got {rv}")
ok("schema version matches", sv == EXPECTED_SCHEMA_VERSION, f"got {sv}")
# ---- expected files -------------------------------------------------
head("Expected files")
missing = [f for f in REQUIRED_FILES if not os.path.exists(os.path.join(root, f))]
ok(f"all {len(REQUIRED_FILES)} required files present", not missing,
f"missing: {missing}" if missing else "")
if missing:
print("\nCannot continue with required files missing.")
return 1
# ---- row counts -----------------------------------------------------
head("Row counts")
for rel, exp in EXPECTED_ROWS.items():
p = os.path.join(root, rel)
n = sum(1 for _ in open(p)) if rel.endswith(".jsonl") else sum(1 for _ in open(p)) - 1
ok(f"{rel} == {exp} rows", n == exp, f"got {n}")
m = read_csv(os.path.join(root, "data/matched_labels.csv"))
# ---- coverage -------------------------------------------------------
head("Benchmark coverage")
got_b = count_distinct(m, "problem_id", "benchmark_id")
for b, exp in EXPECTED_BENCHMARKS.items():
ok(f"{b}: {exp} distinct problems", got_b.get(b) == exp, f"got {got_b.get(b)}")
ok("no unexpected benchmark", set(got_b) == set(EXPECTED_BENCHMARKS),
f"unexpected: {sorted(set(got_b) - set(EXPECTED_BENCHMARKS))}")
ok("MaScQA absent (excluded: NonCommercial, not in paper)", "mascqa" not in got_b)
head("Model coverage")
got_m = count_distinct(m, "setting_id", "model")
for mod, exp in EXPECTED_MODELS.items():
ok(f"{mod}: {exp} settings", got_m.get(mod) == exp, f"got {got_m.get(mod)}")
ok("no unexpected solver", set(got_m) == set(EXPECTED_MODELS),
f"unexpected: {sorted(set(got_m) - set(EXPECTED_MODELS))}")
all_settings = {r["setting_id"] for r in m}
ok("Gemma-3-27B scope check absent",
not any("gemma3_27b" in s_ for s_ in all_settings))
head("Setting coverage")
got_s = count_rows(m, "setting_id")
ok("exactly 10 settings", len(got_s) == 10, f"got {len(got_s)}")
for s_, exp in EXPECTED_SETTINGS.items():
ok(f"{s_} == {exp}", got_s.get(s_) == exp, f"got {got_s.get(s_)}")
head("Protocol coverage")
cols = [f"{x}_correct" for x in ["baseline", "single", "per", "broadcast"]]
mcols = header(os.path.join(root, "data/matched_labels.csv"))
ok("all four protocol columns present", all(c in mcols for c in cols),
f"missing: {[c for c in cols if c not in mcols]}")
# Empty string means a missing cell. Absence must not read as a value.
blanks = sum(1 for r in m for c in cols if r[c].strip() == "")
ok("no null protocol outcomes", blanks == 0, f"{blanks} blank cells")
bad = sum(1 for r in m for c in cols if r[c].strip() not in ("0", "1"))
ok("protocol outcomes are strictly 0/1", bad == 0, f"{bad} out of range")
got_lab = {r["oracle_label"] for r in m}
ok("oracle_label uses the documented vocabulary", got_lab <= set(ORACLE_LABELS),
f"unexpected: {sorted(got_lab - set(ORACLE_LABELS))}")
head("Oracle recomputation (Baseline -> Single -> PER -> Broadcast -> None)")
mism = inv = 0
seen = set()
dupes = 0
for r in m:
flags = [r["baseline_correct"], r["single_correct"], r["per_correct"], r["broadcast_correct"]]
rec = "none"
for proto, flag in zip(PROTOCOLS, flags):
if flag == "1":
rec = proto
break
if rec != r["oracle_label"]:
mism += 1
if (r["oracle_label"] == "none") != (r["any_protocol_solved"] == "0"):
inv += 1
k = (r["setting_id"], r["problem_id"])
if k in seen:
dupes += 1
seen.add(k)
ok("oracle recomputation agrees on every row", mism == 0, f"{mism} mismatches")
ok("oracle_label=='none' iff any_protocol_solved==0", inv == 0, f"{inv} violations")
ok("(setting_id, problem_id) unique", dupes == 0, f"{dupes} duplicates")
head("Split integrity")
for rel in ["data/splits/primary_omnimath_splits.csv",
"data/splits/six_setting_splits.csv"]:
rows = read_csv(os.path.join(root, rel))
groups = {}
for r in rows:
g = r.get("setting_id", "(all)")
groups.setdefault(g, {}).setdefault(r["split"], set()).add(r["problem_id"])
bad_n = 0
for _, st in groups.items():
tr, dv, te = st.get("train", set()), st.get("dev", set()), st.get("test", set())
if (tr & dv) or (tr & te) or (dv & te):
bad_n += 1
ok(f"{rel}: train/dev/test pairwise disjoint", bad_n == 0, f"{bad_n} groups overlap")
head("Leakage guard (feature files must carry no outcomes)")
for rel in FEATURE_FILES:
p_ = os.path.join(root, rel)
if rel.endswith(".jsonl"):
with open(p_, encoding="utf-8") as fh:
cs = set(json.loads(fh.readline()).keys())
else:
cs = set(header(p_))
hits = sorted(cs & FORBIDDEN_IN_FEATURES)
ok(f"{rel} carries no outcome/answer column", not hits, f"found {hits}")
head("Confidence probes (two distinct instruments)")
post = read_csv(os.path.join(root, "data/confidence/postanswer_confidence_predictions.csv"))
pre = read_csv(os.path.join(root, "data/confidence/primary_omnimath_confidence_predictions.csv"))
post_types = {r["probe_type"] for r in post}
pre_types = {r["probe_type"] for r in pre}
ok("post-answer file is uniformly probe_type=post_answer_pre_collaboration",
post_types == {"post_answer_pre_collaboration"}, f"got {sorted(post_types)}")
ok("pre-answer file is uniformly probe_type=pre_answer_q1",
pre_types == {"pre_answer_q1"}, f"got {sorted(pre_types)}")
post_eids = [r["example_id"] for r in post]
ok("post-answer example_id is unique", len(set(post_eids)) == len(post_eids),
f"{len(post_eids) - len(set(post_eids))} duplicates")
# Scale and null semantics: a "probability"-named column on a 0-100 scale is
# the kind of thing a reader gets silently wrong, so assert it rather than
# only document it.
post_conf = [float(r["confidence"]) for r in post if r["confidence"].strip() != ""]
post_hi = max(post_conf) if post_conf else 0.0
ok("post-answer `confidence` is on the documented 0-100 scale", post_hi > 1.0,
detail=f"range {min(post_conf)}-{post_hi} over {len(post_conf)} parsed rows",
fail_detail=f"max is {post_hi}: the column looks like a 0-1 probability, "
f"not the documented 0-100 scale")
ok("post-answer `confidence` is blank exactly where parse_ok is false",
sum(1 for r in post if r["confidence"].strip() == "")
== sum(1 for r in post if r["parse_ok"].strip().lower() == "false"))
pre_vals = [float(r["confidence_probability"]) for r in pre
if r["confidence_probability"].strip() != ""]
pre_hi = max(pre_vals) if pre_vals else 0.0
ok("pre-answer `confidence_probability` is on the documented 0-100 scale",
pre_hi > 1.0,
detail=f"range {min(pre_vals)}-{pre_hi} over {len(pre_vals)} parsed rows",
fail_detail=f"max is {pre_hi}: the column looks like a 0-1 probability, "
f"not the documented 0-100 scale")
fb = [r for r in pre if r["used_fallback"].strip().lower() == "true"]
fb_with_value = sum(1 for r in fb if r["confidence_probability"].strip() != "")
ok("pre-answer fallback rows carry NO confidence value (documented as null)",
fb_with_value == 0, f"{fb_with_value} of {len(fb)} fallback rows have a value")
print(f" {len(fb)} fallback rows are null; treat a null as ESCALATE "
f"(see docs/schema.md -- other readings give 73.76% or 60.76% "
f"against the published 78.0%)")
xw = read_csv(os.path.join(root, "registry/example_id_crosswalk.csv"))
xw_keys = {(r["setting_id"], r["example_id"], r["problem_id"]) for r in xw}
resolved = sum(1 for r in post
if (r["setting_id"], r["example_id"], r["problem_id"]) in xw_keys)
ok("crosswalk resolves every post-answer example_id", resolved == len(post),
f"{resolved}/{len(post)}")
matched_keys = {(r["setting_id"], r["problem_id"]) for r in m}
joined = sum(1 for r in post
if (r["setting_id"], r["example_id"], r["problem_id"]) in xw_keys
and (r["setting_id"], r["problem_id"]) in matched_keys)
ok("post-answer predictions join to matched outcomes via the crosswalk",
joined == len(post), f"{joined}/{len(post)}")
head("Cost layer (one setting only)")
costs = read_csv(os.path.join(root, "data/costs/omnimath_per_protocol_costs.csv"))
cset = {r["setting_id"] for r in costs}
ok("costs cover exactly one setting",
cset == {"omnimath2__competition_math_4181__gpt_oss_120b"}, f"got {sorted(cset)}")
cids = [r["problem_id"] for r in costs]
ok("cost problem_id is unique", len(set(cids)) == len(cids),
f"{len(cids) - len(set(cids))} duplicates")
om = {r["problem_id"] for r in m
if r["setting_id"] == "omnimath2__competition_math_4181__gpt_oss_120b"}
ok("every cost row resolves to a released problem", set(cids) <= om,
f"{len(set(cids) - om)} unresolved")
ok("26 of 4181 problems omitted (duplicate-text groups; see TODO.md)",
len(om - set(cids)) == 26, f"{len(om - set(cids))} omitted")
tokcols = [f"{x}_total_tokens" for x in ["baseline", "single", "per", "broadcast"]]
blank = sum(1 for r in costs for c in tokcols if r[c].strip() == "")
ok("no blank token totals", blank == 0, f"{blank} blanks")
mean_base = sum(int(r["baseline_total_tokens"]) for r in costs) / len(costs)
print(f" mean Baseline tokens over the {len(costs)} emitted rows: {mean_base:,.1f}")
print(" (the paper's figure over all 4,181 problems is 18,385.4 -- the gap is the")
print(" 26 omitted rows, not a disagreement. See docs/schema.md.)")
ok("mean Baseline tokens is the documented 18,432.0",
abs(mean_base - 18432.0) < 0.05, f"got {mean_base:.1f}")
# ---- checksums ------------------------------------------------------
head("Checksums")
cpath = os.path.join(root, "registry/checksums.sha256")
expected = {}
for line in open(cpath):
line = line.strip()
if not line or line.startswith("#"):
continue
digest, rel = line.split(None, 1)
expected[rel.strip()] = digest
print(f" {len(expected)} entries in registry/checksums.sha256")
if args.skip_checksums:
print(" (skipped by --skip-checksums)")
else:
bad, absent = [], []
for rel, digest in sorted(expected.items()):
p = os.path.join(root, rel)
if not os.path.exists(p):
absent.append(rel)
elif sha256(p) != digest:
bad.append(rel)
ok("every checksummed file is present", not absent, f"missing: {absent}")
ok("every checksum matches", not bad, f"mismatched: {bad}")
on_disk = set()
skipped_infra = 0
for dp, _, fs in os.walk(root):
for fn in fs:
r = os.path.relpath(os.path.join(dp, fn), root)
if r == "registry/checksums.sha256":
continue
if is_infrastructure(r):
skipped_infra += 1
continue
on_disk.add(r)
if skipped_infra:
print(f" ({skipped_infra} tool-created file(s) ignored: download cache, "
f"version-control and OS metadata)")
extra = sorted(on_disk - set(expected))
if extra:
# An unexpected extra file is not corruption, so this stays a warning.
WARNS.append(f"{len(extra)} file(s) present but not checksummed: "
f"{abbreviate(extra)}")
print(f" [WARN] {len(extra)} file(s) not in checksums.sha256: "
f"{abbreviate(extra)}")
# ---- optional artifacts --------------------------------------------
head("Optional artifacts (absent by design)")
for rel, why in OPTIONAL_ARTIFACTS.items():
present = os.path.exists(os.path.join(root, rel.rstrip("/")))
print(f" [{'present' if present else 'ABSENT '}] {rel} -- {why}")
print("\n NOTE: Baseline final-answer text is NOT in this release. The post-answer")
print(" confidence probe consumed it, so the probe CANNOT be re-run from this")
print(" release alone. data/probe_inputs.jsonl is an identifier manifest, not a")
print(" runnable prompt set. See docs/reconstruction.md and TODO.md.")
# ---- result ---------------------------------------------------------
print("\n" + "=" * 72)
if FAILS:
print(f"RESULT: FAILED -- {len(FAILS)} check(s) did not pass")
for f in FAILS:
print(f" - {f}")
print("=" * 72)
return 1
print("RESULT: PASSED -- all checks succeeded")
if WARNS:
print(f"({len(WARNS)} warning(s))")
for w in WARNS:
print(f" ! {w}")
print("=" * 72)
return 0
if __name__ == "__main__":
sys.exit(main())