Datasets:
Download scripts/build_dataset.py from xiaoyuanwang/ifbench-audit: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/datasets/xiaoyuanwang/ifbench-audit/resolve/main/scripts/build_dataset.py
- Command line
-
hf download hf://datasets/xiaoyuanwang/ifbench-audit/scripts/build_dataset.py
-
curl -L -o build_dataset.py https://huggingface.co/datasets/xiaoyuanwang/ifbench-audit/resolve/main/scripts/build_dataset.py
11 kB
| # Copyright 2026 Xiaoyuan Wang | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """Build this dataset from the IFBench audit repository and check it against the audit's scores. | |
| Usage: python -I scripts/build_dataset.py <ifbench-audit checkout at a31c684> <output dir> | |
| Writes data/*.jsonl and data/panel_verdicts.jsonl.gz, then recomputes both blinded rounds' error | |
| rates and inter-reviewer kappa from the written rows and compares them with the audit's | |
| results/blind_audit/round*/score_frozen.json. | |
| """ | |
| from __future__ import annotations | |
| import gzip | |
| import json | |
| import re | |
| import sys | |
| from pathlib import Path | |
| SOURCE_COMMIT = "a31c6841dae2632dafda740bd51496843d9e5f38" | |
| STATUS = {"✗": "defective", "fixed": "fixed"} | |
| ROUNDS = {1: "round1", 2: "round2"} | |
| def read_jsonl(path: Path) -> list[dict]: | |
| with open(path, encoding="utf-8") as f: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def write_jsonl(path: Path, rows: list[dict]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| opener = gzip.open if path.suffix == ".gz" else open | |
| with opener(path, "wt", encoding="utf-8", newline="\n") as f: | |
| for row in rows: | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| def section(text: str, heading: str) -> str: | |
| start = text.index(f"\n## {heading}\n") | |
| end = text.find("\n## ", start + 1) | |
| return text[start : end if end != -1 else len(text)] | |
| def table_rows(block: str, prefix: str, n_cells: int) -> list[list[str]]: | |
| rows = [] | |
| for line in block.splitlines(): | |
| if line.startswith(f"| {prefix}"): | |
| cells = [c.strip() for c in line.strip().strip("|").split("|")] | |
| assert len(cells) == n_cells, (line, len(cells)) | |
| rows.append(cells) | |
| return rows | |
| def bullets(block: str, pattern: str) -> list[tuple[str, str]]: | |
| items, current = [], None | |
| for line in block.splitlines(): | |
| match = re.match(pattern, line) | |
| if match: | |
| current = [match.group(1), match.group(2).strip()] | |
| items.append(current) | |
| elif current is not None and line.startswith(" ") and line.strip(): | |
| current[1] += " " + line.strip() | |
| elif not line.strip() or line.startswith("- ") or line.startswith("#"): | |
| current = None | |
| return [(i, t) for i, t in items] | |
| def decision_dependent(block: str) -> set[str]: | |
| """Expand the report's list of findings that rest on a decision, e.g. "F5, F33–F36 and F42".""" | |
| flat = re.sub(r"\s+", " ", block) | |
| listed = re.search(r"rest on a decision rather than on the instruction text alone: ([^.]*?), whose", flat).group(1) | |
| ids = set() | |
| for start, end in re.findall(r"F(\d+)(?:–F(\d+))?", listed): | |
| ids.update(f"F{n}" for n in range(int(start), int(end or start) + 1)) | |
| return ids | |
| def findings(report: str) -> list[dict]: | |
| rows = [] | |
| block = section(report, "Findings") | |
| on_decision = decision_dependent(block) | |
| assert len(on_decision) == 9, on_decision | |
| for fid, instruction, defect, counterexample, marin, upstream in table_rows(block, "F", 6): | |
| match = re.fullmatch(r"(.+) \((\d+)\)", instruction) | |
| assert match, instruction | |
| assert marin in STATUS and upstream in STATUS, (fid, marin, upstream) | |
| rows.append({ | |
| "id": fid, | |
| "kind": "checker", | |
| "instruction_ids": [s.strip() for s in match.group(1).split(",")], | |
| "n_test_constraints": int(match.group(2)), | |
| "defect": defect, | |
| "counterexample": counterexample, | |
| "decisions": sorted(set(re.findall(r"\bD-[a-z-]+[a-z]", defect + " " + counterexample))), | |
| "rests_on_decision": fid in on_decision, | |
| "marin_status": STATUS[marin], | |
| "upstream_status": STATUS[upstream], | |
| }) | |
| for gid, text in bullets(section(report, "Protocol findings"), r"^- (G\d+): (.*)$"): | |
| rows.append({ | |
| "id": gid, | |
| "kind": "protocol", | |
| "instruction_ids": [], | |
| "n_test_constraints": None, | |
| "defect": text, | |
| "counterexample": None, | |
| "decisions": [], | |
| "rests_on_decision": False, | |
| "marin_status": None, | |
| "upstream_status": None, | |
| }) | |
| return rows | |
| def decisions(report: str) -> list[dict]: | |
| block = section(report, "Interpretation decisions") | |
| rows = [ | |
| {"id": did, "question": question, "official_reading": official, "proposal": proposal} | |
| for did, question, official, proposal in table_rows(block, "D-", 4) | |
| ] | |
| open_part = block.split("Three more questions have no proposal yet.")[1] | |
| for did, text in bullets(open_part, r"^- (D-[a-z-]+|Output surface): (.*)$"): | |
| rows.append({"id": did, "question": text, "official_reading": None, "proposal": None}) | |
| return rows | |
| def fixtures(repo: Path) -> list[dict]: | |
| rows = [] | |
| for fx in read_jsonl(repo / "fixtures/ifbench_fixtures.jsonl"): | |
| rows.append({ | |
| "id": fx["id"], | |
| "family": fx["family"], | |
| "name": fx["name"], | |
| "instruction_id": fx["instruction_id"], | |
| "kwargs_json": json.dumps(fx["kwargs"], ensure_ascii=False, sort_keys=True), | |
| "response": fx["response"], | |
| "expected": fx["expected"], | |
| "finding": fx["finding"], | |
| "decision": fx["decision"], | |
| "note": fx["note"], | |
| "content_sha256": fx["content_sha256"], | |
| }) | |
| return rows | |
| def blind_review(repo: Path) -> tuple[list[dict], list[dict]]: | |
| rows, strata = [], [] | |
| for number, name in ROUNDS.items(): | |
| base = repo / "results/blind_audit" / name | |
| key = {k["case_id"]: k for k in read_jsonl(base / "key.jsonl")} | |
| cases = {c["case_id"]: c for c in read_jsonl(base / "cases/all_cases.jsonl")} | |
| reviews = {"a": {}, "b": {}} | |
| for path in sorted((base / "reviews").glob("review_*.jsonl")): | |
| reviewer = path.name[len("review_")].lower() | |
| for review in read_jsonl(path): | |
| assert review["case_id"] not in reviews[reviewer], (path, review["case_id"]) | |
| reviews[reviewer][review["case_id"]] = review | |
| assert set(key) == set(cases) == set(reviews["a"]) == set(reviews["b"]), name | |
| for case_id in sorted(key): | |
| k, c, a, b = key[case_id], cases[case_id], reviews["a"][case_id], reviews["b"][case_id] | |
| assert c["instruction_id"] == k["instruction_id"], case_id | |
| panel = k["source"] == "panel" | |
| row = { | |
| "case_id": case_id, | |
| "round": number, | |
| "source": k["source"], | |
| "stratum": k["stratum"] if panel else "fixture", | |
| "config": k.get("config"), | |
| "prompt_key": k.get("key"), | |
| "fixture_name": None if panel else k["name"], | |
| "fixture_expected": None if panel else k["expected"], | |
| "finding": None if panel else k["finding"], | |
| "decision": None if panel else k["decision"], | |
| "instruction_id": k["instruction_id"], | |
| "instruction": c["instruction"], | |
| "prompt": c["prompt"], | |
| "response": c["response"], | |
| "marin_strict": k.get("marin_strict"), | |
| "fixes_only": k.get("fixes_only"), | |
| "proposed": k.get("proposed"), | |
| } | |
| for tag, review in (("a", a), ("b", b)): | |
| for field in ("verdict", "lean", "confidence", "reason"): | |
| row[f"reviewer_{tag}_{field}"] = review[field] | |
| row["consensus"] = a["lean"] if a["lean"] == b["lean"] else None | |
| rows.append(row) | |
| score = json.loads((base / "score_frozen.json").read_text(encoding="utf-8")) | |
| sampled = {s: sum(1 for k in key.values() if k["source"] == "panel" and k["stratum"] == s) for s in score["population"]} | |
| for stratum, population in score["population"].items(): | |
| strata.append({"round": number, "stratum": stratum, "population": population, "sampled": sampled[stratum]}) | |
| strata.append({"round": number, "stratum": "fixture", "population": None, | |
| "sampled": sum(1 for k in key.values() if k["source"] == "fixture")}) | |
| return rows, strata | |
| def panel_verdicts(repo: Path) -> list[dict]: | |
| rows = [] | |
| with gzip.open(repo / "results/panel/analysis.samples.jsonl.gz", "rt", encoding="utf-8") as f: | |
| for line in f: | |
| sample = json.loads(line) | |
| assert sample.pop("semantic") is None | |
| sample["prompt_key"] = sample.pop("key") | |
| rows.append(sample) | |
| return rows | |
| def kappa(pairs: list[tuple[str, str]]) -> float: | |
| n = len(pairs) | |
| observed = sum(x == y for x, y in pairs) / n | |
| labels = {x for pair in pairs for x in pair} | |
| expected = sum((sum(x == l for x, _ in pairs) / n) * (sum(y == l for _, y in pairs) / n) for l in labels) | |
| return (observed - expected) / (1 - expected) | |
| def check(rows: list[dict], strata: list[dict], repo: Path) -> None: | |
| graders = ("marin_strict", "fixes_only", "proposed") | |
| for number, name in ROUNDS.items(): | |
| score = json.loads((repo / "results/blind_audit" / name / "score_frozen.json").read_text(encoding="utf-8")) | |
| cases = [r for r in rows if r["round"] == number] | |
| k = kappa([(r["reviewer_a_lean"], r["reviewer_b_lean"]) for r in cases]) | |
| assert abs(k - score["kappa"]) < 1e-12, (name, k, score["kappa"]) | |
| population = {s["stratum"]: s["population"] for s in strata if s["round"] == number and s["population"]} | |
| total = sum(population.values()) | |
| for grader in graders: | |
| rate = 0.0 | |
| for stratum, size in population.items(): | |
| decided = [r for r in cases if r["stratum"] == stratum and r["consensus"] is not None] | |
| wrong = sum(1 for r in decided if (r["consensus"] == "pass") != r[grader]) | |
| rate += size * wrong / len(decided) | |
| rate /= total | |
| assert abs(rate - score["error_rates"][grader][0]) < 1e-12, (name, grader, rate) | |
| print(f"{name} {grader}: error rate {100 * rate:.1f}% matches score_frozen.json") | |
| print(f"{name}: {len(cases)} cases, kappa {k:.2f} matches") | |
| def main(repo_arg: str, out_arg: str) -> None: | |
| repo, out = Path(repo_arg), Path(out_arg) | |
| report = (repo / "reports/AUDIT.md").read_text(encoding="utf-8") | |
| review_rows, strata = blind_review(repo) | |
| tables = { | |
| "fixtures.jsonl": fixtures(repo), | |
| "findings.jsonl": findings(report), | |
| "decisions.jsonl": decisions(report), | |
| "blind_review.jsonl": review_rows, | |
| "blind_review_strata.jsonl": strata, | |
| "panel_verdicts.jsonl.gz": panel_verdicts(repo), | |
| } | |
| for filename, rows in tables.items(): | |
| write_jsonl(out / "data" / filename, rows) | |
| print(f"data/{filename}: {len(rows)} rows") | |
| check(review_rows, strata, repo) | |
| if __name__ == "__main__": | |
| main(*sys.argv[1:]) | |