MI4ToolCalling / validate.py
XijieGong's picture
Paper dataset release
4b59c40
Raw History Blame Contribute Delete
6.74 kB
#!/usr/bin/env python3
"""Validate the released dataset bundle using Python's standard library."""
from __future__ import annotations
import argparse
import hashlib
import json
from collections import Counter
from pathlib import Path
MODELS = ("qwen3_4b", "qwen3_8b", "qwen3_14b", "qwen35_4b", "qwen35_9b",
"mistral_3p2_24b", "granite_3p3_8b")
def rows(path: Path) -> list[dict]:
with path.open(encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def file_at(root: Path, relative: str) -> Path:
path = Path(relative)
if path.is_absolute() or ".." in path.parts:
raise ValueError(f"Invalid input path: {relative}")
target = root / path
if not target.is_file():
raise FileNotFoundError(target)
return target
def digest(path: Path, *, native_ids: bool = False) -> str:
data = path.read_bytes()
if native_ids:
ids = json.loads(data)["input_ids"]
data = json.dumps(ids, separators=(",", ":"), ensure_ascii=True).encode("ascii")
return hashlib.sha256(data).hexdigest()
def pairs(root: Path, records: list[dict]) -> None:
for row in records:
for side in ("clean", "corrupt"):
path = file_at(root, row[f"{side}_relpath"])
if digest(path, native_ids=path.suffix == ".json") != row[f"{side}_prompt_sha256"]:
raise ValueError(f"Prompt hash mismatch: {path}")
def validate(root: Path) -> None:
for model in MODELS:
directory = root / model / "pair"
manifest = "pairs.jsonl" if model == "qwen3_8b" else "manifest.jsonl"
records = rows(directory / manifest)
if Counter(row["split"] for row in records) != {"train": 300, "heldout": 200}:
raise ValueError(f"{model}: expected 300 training and 200 held-out pairs")
if len({row["sample_id"] for row in records}) != 500:
raise ValueError(f"{model}: invalid pair identifiers")
expected_files = {row[f"{side}_relpath"] for row in records for side in ("clean", "corrupt")}
actual_files = {path.relative_to(directory).as_posix()
for split in ("train", "heldout") for side in ("clean", "corrupt")
for path in (directory / split / side).iterdir()
if path.is_file() and path.suffix in {".txt", ".json"}}
if actual_files != expected_files:
raise ValueError(f"{model}: unexpected paired prompt files; download into an empty dataset directory")
pairs(directory, records)
free = root / model / "verb_free"
filename = "implicit_intent.jsonl" if model == "mistral_3p2_24b" else "requests.jsonl"
requests = rows(free / filename)
key = "input_ids" if model == "mistral_3p2_24b" else "prompt"
if len(requests) != 600 or any(not row.get(key) for row in requests):
raise ValueError(f"{model}: invalid verb-free inputs")
for side in ("call", "text"):
if len(rows(root / model / "tau2_bench" / f"native-{side}-200.jsonl")) != 200:
raise ValueError(f"{model}: invalid tau2 {side} inputs")
source = "qwen3_8b" if model in {"qwen3_4b", "qwen3_14b"} else model
for domain in ("retrieval", "operations", "communication"):
directory = root / source / "multi_domain" / domain
records = rows(directory / "selected_pairs.jsonl")
expected = {"train": 400, "test": 100} if source == "qwen3_8b" else {"test": 100}
if Counter(row.get("split", "test") for row in records) != expected:
raise ValueError(f"{source}/{domain}: invalid input split")
for row in records:
for side in ("clean", "corrupt"):
if not row.get(f"{side}_prompt"):
file_at(directory, row[f"{side}_relpath"])
cohort = rows(root / model / "controls/early_signal/pairs.jsonl")
count = 200 if model == "qwen3_8b" else 240 if model == "granite_3p3_8b" else 300
if len(cohort) != count or [row["order"] for row in cohort] != list(range(count)):
raise ValueError(f"{model}: invalid early-signal cohort")
pairs(root, cohort)
controlled = root / "qwen3_8b/controlled"
metadata = json.loads((controlled / "dataset.json").read_text())
for relative, expected in metadata["frozen_files_sha256"].items():
if digest(file_at(controlled, relative)) != expected:
raise ValueError(f"Controlled manifest hash mismatch: {relative}")
for split, count in (("train", 1200), ("test", 300)):
manifests = [rows(controlled / split / side / "manifest.jsonl") for side in ("clean", "corrupt")]
names = [[row.get("output_filename") or row.get("filename") for row in records] for records in manifests]
if len(names[0]) != count or names[0] != names[1]:
raise ValueError(f"Controlled {split}: invalid paired manifest")
for side in ("clean", "corrupt"):
for filename in names[0]:
file_at(controlled / split / side, filename)
manifest = json.loads((root / "qwen3_8b/manifest.json").read_text())["pair"]
for name, field in (("pairs.jsonl", "pairs_jsonl_sha256"), ("balance.csv", "balance_csv_sha256")):
if digest(root / "qwen3_8b/pair" / name) != manifest[field]:
raise ValueError(f"Qwen3-8B manifest hash mismatch: {name}")
controls = root / "qwen3_8b/controls"
cohort = rows(controls / "layer_comparison/pairs.jsonl")
if Counter(row["split"] for row in cohort) != {"train": 200, "heldout": 300}:
raise ValueError("Invalid layer-comparison cohort")
pairs(root, cohort)
requests = rows(controls / "tool_affordance/requests.jsonl")
expected = {(verb, tool) for verb in ("Write", "Review") for tool in ("write_file", "submit_review")}
by_sample: dict[str, set[tuple[str, str]]] = {}
for row in requests:
if hashlib.sha256(row["prompt"].encode()).hexdigest() != row["prompt_sha256"]:
raise ValueError("Tool-affordance prompt hash mismatch")
by_sample.setdefault(row["sample_id"], set()).add((row["request_verb"], row["tool_name"]))
if len(requests) != 400 or len(by_sample) != 100 or any(value != expected for value in by_sample.values()):
raise ValueError("Invalid tool-affordance input conditions")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", nargs="?", type=Path, default=Path(__file__).resolve().parent)
args = parser.parse_args()
validate(args.directory.expanduser().resolve())
print("Dataset inputs verified.")
if __name__ == "__main__":
main()