sungguk's picture
Release visual answerability benchmark v1.0.0
e1ced61 verified
Raw
History Blame Contribute Delete
27.8 kB
"""``explicit-data`` — ingest, decontamination, rendering, and group assembly.
Implemented subcommands:
freeze-eval Freeze the evaluation registry write-once before any training
ingest (``docs/02`` §3). Refuses to overwrite a frozen registry.
ingest Normalize one training source to ``normalized/<source>/<split>``.
Hard-refuses MathVista (training-prohibited) and skips BBox DocVQA
when its dual approval gate is not cleared.
fingerprint Compute exact/pHash/MinHash fingerprints into a SQLite index
(``docs/02`` §5.1). Operates on normalized items.jsonl files or,
for eval, the registry's companion items file.
decontaminate Match train fingerprints against the eval index and
automatically reject exact and near duplicates.
scan-plotqa-prefix
Verify and summarize the pinned PlotQA source prefixes.
build-certified-release
Build the fixed C1 five-state train/evaluation release.
replay-certificates
Independently replay every persisted view certificate.
The remaining subcommands are documented but not yet implemented: they exit 2
(never a silent success, per the runbook).
"""
from __future__ import annotations
import argparse
import json
import sys
from collections.abc import Callable, Mapping
from pathlib import Path
from typing import Any
from .. import contamination, ingest
from ..atomic_io import read_jsonl
from ..config import (
ConfigError,
ExperimentConfig,
ResourcesManifest,
load_config_pair,
load_resources,
)
from ..ingest import base as ingest_base
from ..ingest.base import IngestError
from ..logging_setup import get_logger
from ..paths import data_root, repo_root
from ..resources import load_approval
from ._stub import dispatch
_PROG = "explicit-data"
logger = get_logger("data")
_SUBCOMMANDS = {
"freeze-eval": "Freeze the evaluation registry before any training ingest (P2).",
"ingest": "Normalize a source dataset to the common item schema (P2).",
"fingerprint": "Compute exact/pHash/MinHash fingerprints into SQLite (P3).",
"decontaminate": "Reject/near-duplicate match train vs eval (P3).",
"scan-plotqa-prefix": "Compile and count executable D15 PlotQA prefix rows.",
"build-certified-release": "Build the fixed PlotQA C1 train/eval release.",
"replay-certificates": "Replay every persisted certificate in one split.",
"build-evi-core-release": "Build PlotQA+GQA+CLEVR EVI core v2.",
"replay-evi-core-release": "Replay every certificate in EVI core v2.",
"validate-evi-core-release": "Schema/admission-check EVI core v2.",
"validate-full": "Teacher/verifier blind validation of FULL problems (P4/P7).",
"propose-dependencies": "Teacher dependency/region proposal (P5).",
"localize": "OCR/SAM/CV region localization (P5).",
"render": "Deterministic intervention rendering (P6).",
"blind-relabel": "Teacher/verifier blind re-solve of transformed views (P7).",
"reconcile": "Reconcile solver labels into states (P7).",
"build-groups": "Assemble intervention groups (P7).",
"validate-groups": "Validate groups against schema + invariants (P7).",
"manifest": "Build a dataset manifest (P7).",
"sample-candidates": "Sample dry-run candidates (P6).",
"build-pilot": "Build the accepted 2K pilot (P6).",
"produce-silver": "Produce silver train at scale (P7).",
}
def _add_config_args(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--resources",
type=Path,
default=repo_root() / "configs" / "resources.yaml",
)
parser.add_argument(
"--experiment",
type=Path,
default=repo_root() / "configs" / "experiment.yaml",
)
def _utc_now() -> str:
from datetime import UTC, datetime
return datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
class _Handled(Exception):
"""Internal control-flow signal that a nonzero exit has already been printed."""
def __init__(self, code: int) -> None:
super().__init__()
self.code = code
def _load_pair(
args: argparse.Namespace,
) -> tuple[ResourcesManifest, ExperimentConfig]:
try:
return load_config_pair(args.resources, args.experiment)
except (ConfigError, FileNotFoundError) as exc:
print(f"{_PROG}: config load failed: {exc}", file=sys.stderr)
raise _Handled(1) from exc
# --- freeze-eval -----------------------------------------------------------
def cmd_freeze_eval(argv: list[str]) -> int:
parser = argparse.ArgumentParser(prog=f"{_PROG} freeze-eval")
_add_config_args(parser)
parser.add_argument(
"--rows-dir",
type=Path,
required=True,
help="directory holding <source>.<split>.jsonl native-row files.",
)
parser.add_argument(
"--image-root",
type=Path,
default=None,
help="root directory for native image refs (visual eval sources).",
)
parser.add_argument(
"--output",
type=Path,
default=None,
help="registry output (default <data_root>/registry/evaluation_items.v1.jsonl).",
)
parser.add_argument(
"--force", action="store_true", help="overwrite an existing frozen registry."
)
parser.add_argument(
"--resume",
action="store_true",
help="verify an existing registry matches the computed freeze (idempotent).",
)
args = parser.parse_args(argv)
try:
resources, experiment = _load_pair(args)
except _Handled as exc:
return exc.code
plan = ingest.eval_freeze_plan(experiment)
resolved_plan = [
ingest.EvalSourceSpec(
name=spec.name,
config=spec.config,
split=spec.split if spec.from_gold else ingest.default_split_for(spec.name, resources),
from_gold=spec.from_gold,
)
for spec in plan
]
output = args.output or (data_root() / "registry" / "evaluation_items.v1.jsonl")
try:
frozen = ingest.freeze_eval(
resolved_plan,
resources,
rows_dir=args.rows_dir,
image_root=args.image_root,
output_path=output,
force=args.force,
resume=args.resume,
)
except ingest.RegistryFrozenError as exc:
print(f"{_PROG} freeze-eval: {exc}", file=sys.stderr)
return 1
except ingest.IngestError as exc:
print(f"{_PROG} freeze-eval: {exc}", file=sys.stderr)
return 1
print(
json.dumps(
{
"registry_path": str(frozen.path),
"registry_sha256": frozen.sha256,
"row_count": frozen.row_count,
"sources": [s.name for s in resolved_plan],
},
sort_keys=True,
)
)
return 0
# --- ingest ----------------------------------------------------------------
def cmd_ingest(argv: list[str]) -> int:
parser = argparse.ArgumentParser(prog=f"{_PROG} ingest")
src_group = parser.add_mutually_exclusive_group(required=True)
src_group.add_argument(
"--source",
help="structured source name (plotqa/geometry3k); reads from raw/<source>.",
)
src_group.add_argument("--resource", help="HF dataset resource logical name.")
parser.add_argument("--split", required=True, help="source split to ingest.")
parser.add_argument(
"--rows",
type=Path,
default=None,
help="native-row JSONL file for this source/split (HF --resource path).",
)
parser.add_argument(
"--image-root",
type=Path,
default=None,
help="root directory for native image refs (HF --resource path).",
)
parser.add_argument(
"--raw-dir",
type=Path,
default=None,
help="materialized raw dir for a structured --source (default <data_root>/raw/<source>).",
)
parser.add_argument(
"--config",
default="default",
help="source config name (MMMU: subject).",
)
parser.add_argument("--approval", type=Path, default=None, help="resource_approval.json path.")
parser.add_argument(
"--resources",
type=Path,
default=repo_root() / "configs" / "resources.yaml",
)
parser.add_argument(
"--eval-registry",
type=Path,
default=None,
help="frozen evaluation registry path (required for train ingest).",
)
parser.add_argument(
"--no-require-eval-registry",
action="store_true",
help="allow train ingest before the eval registry is frozen (testing only).",
)
parser.add_argument(
"--output",
type=Path,
default=None,
help="output dir (default <data_root>/normalized/<name>/<split>).",
)
parser.add_argument(
"--config-sha256",
default="",
help="canonical config hash to record in the ingest manifest.",
)
args = parser.parse_args(argv)
try:
resources = load_resources(args.resources)
except (ConfigError, FileNotFoundError) as exc:
print(f"{_PROG} ingest: resources load failed: {exc}", file=sys.stderr)
return 1
# Structured-source path (PlotQA/Geometry3K C1): reads from a materialized
# raw dir; --rows/--image-root do not apply.
if args.source is not None:
return _ingest_structured(args, resources)
return _ingest_dataset(args, resources)
def _ingest_structured(args: argparse.Namespace, resources: Any) -> int:
name = args.source
assert name is not None
if name not in resources.structured_sources:
print(f"{_PROG} ingest: unknown structured source {name!r}", file=sys.stderr)
return 1
cfg = resources.structured_sources[name]
revision = cfg.get("revision", "")
raw_dir = args.raw_dir or (data_root() / "raw" / name)
output = args.output or (data_root() / "normalized" / name / args.split)
expected_sha256 = cfg.get("expected_sha256") or None
try:
result = ingest.ingest_structured_source(
name,
args.split,
raw_dir,
output,
revision=revision,
source_config=cfg,
expected_sha256=expected_sha256,
eval_registry_path=args.eval_registry,
require_eval_registry=not args.no_require_eval_registry,
config_sha256=args.config_sha256,
created_at=_utc_now(),
)
except ingest.IngestError as exc:
print(f"{_PROG} ingest: {exc}", file=sys.stderr)
return 1
print(
json.dumps(
{
"source": result.source,
"split": result.split,
"written": result.written,
"dropped": result.dropped,
"output": str(result.output_path),
},
sort_keys=True,
)
)
return 0
def _ingest_dataset(args: argparse.Namespace, resources: Any) -> int:
if args.resource not in resources.datasets:
print(f"{_PROG} ingest: unknown resource {args.resource!r}", file=sys.stderr)
return 1
revision = resources.datasets[args.resource].revision
approval = load_approval(args.approval)
if args.rows is None or not args.rows.exists():
print(f"{_PROG} ingest: rows file not found: {args.rows}", file=sys.stderr)
return 1
rows = ingest.read_native_rows(args.rows)
resolver = ingest_base.DirectoryImageResolver(args.image_root) if args.image_root else None
if resolver is None and args.resource != "bbox_docvqa_train":
print(
f"{_PROG} ingest: --image-root is required for source {args.resource!r}",
file=sys.stderr,
)
return 1
output = args.output or (data_root() / "normalized" / args.resource / args.split)
try:
result = ingest.ingest_source(
args.resource,
args.split,
rows,
resolver, # type: ignore[arg-type]
output,
revision=revision,
config=args.config,
approval=approval,
eval_registry_path=args.eval_registry,
require_eval_registry=not args.no_require_eval_registry,
config_sha256=args.config_sha256,
created_at=_utc_now(),
)
except ingest.IngestError as exc:
print(f"{_PROG} ingest: {exc}", file=sys.stderr)
return 1
print(
json.dumps(
{
"source": result.source,
"split": result.split,
"written": result.written,
"dropped": result.dropped,
"output": str(result.output_path),
},
sort_keys=True,
)
)
return 0
# --- fingerprint -----------------------------------------------------------
def _collect_input_files(args: argparse.Namespace) -> list[Path]:
if args.input is not None:
path = Path(args.input)
if path.is_dir():
return sorted(path.rglob("items.jsonl"))
# A single items.jsonl (or a registry path whose companion is read later).
return [path] if path.is_file() else []
return sorted(Path(args.input_root).rglob("items.jsonl"))
def _is_registry_row(row: Mapping[str, Any]) -> bool:
"""A frozen registry row carries ``native_id`` but no ``question`` text."""
return "question" not in row and "native_id" in row
def _pick_image_base(file_path: Path, rows: list[dict[str, Any]]) -> Path | None:
"""Auto-detect the image root for a file's rows, or None if text-only."""
for row in rows:
paths = row.get("image_paths") or []
if paths:
first = paths[0]
for candidate in (file_path.parent, file_path.parent / "eval_images"):
if (candidate / first).exists():
return candidate
raise IngestError(f"cannot resolve image {first!r} for {file_path}; pass --image-base")
return None
def _make_resolver(base_dir: Path) -> Callable[[str], Path]:
def resolve(ref: str) -> Path:
path = base_dir / ref
if not path.exists():
raise IngestError(f"image not found: {path}")
return path
return resolve
def cmd_fingerprint(argv: list[str]) -> int:
parser = argparse.ArgumentParser(prog=f"{_PROG} fingerprint")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--input", type=Path, help="items.jsonl file or directory.")
group.add_argument("--input-root", type=Path, help="root to glob items.jsonl under.")
parser.add_argument(
"--image-base", type=Path, default=None, help="image root (auto-detected if omitted)."
)
parser.add_argument("--db", type=Path, required=True, help="SQLite index output.")
args = parser.parse_args(argv)
files = _collect_input_files(args)
if not files:
print(f"{_PROG} fingerprint: no items.jsonl found", file=sys.stderr)
return 1
fingerprints: list[contamination.Fingerprints] = []
sources: set[str] = set()
for file_path in files:
rows = [dict(r) for r in read_jsonl(file_path)]
# A frozen registry has no text/pixels; use its companion items file when present.
if rows and _is_registry_row(rows[0]):
companion = file_path.with_name(file_path.stem + ".items.jsonl")
if companion.exists():
rows = [dict(r) for r in read_jsonl(companion)]
file_path = companion
else:
print(
f"{_PROG} fingerprint: {file_path} is a registry without a companion "
"items file; text/pHash fingerprints unavailable",
file=sys.stderr,
)
base_dir = (
args.image_base if args.image_base is not None else _pick_image_base(file_path, rows)
)
resolve_image = _make_resolver(base_dir) if base_dir is not None else None
try:
for row in rows:
fp = contamination.fingerprint_row(row, resolve_image=resolve_image)
fingerprints.append(fp)
sources.add(fp.source)
except IngestError as exc:
print(f"{_PROG} fingerprint: {exc}", file=sys.stderr)
return 1
count = contamination.index.write_fingerprints(args.db, fingerprints)
print(
json.dumps(
{"db": str(args.db), "row_count": count, "sources": sorted(sources)}, sort_keys=True
)
)
return 0
# --- decontaminate ---------------------------------------------------------
def cmd_decontaminate(argv: list[str]) -> int:
parser = argparse.ArgumentParser(prog=f"{_PROG} decontaminate")
parser.add_argument("--train-db", type=Path, required=True)
parser.add_argument("--eval-db", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True, help="train allowlist JSONL.")
parser.add_argument(
"--near-duplicate-rejects",
"--review-queue",
dest="near_duplicate_rejects",
type=Path,
required=True,
help="immutable auto-rejected near-duplicate JSONL (legacy alias: --review-queue).",
)
args = parser.parse_args(argv)
for label, path in (("train-db", args.train_db), ("eval-db", args.eval_db)):
if not path.exists():
print(f"{_PROG} decontaminate: {label} not found: {path}", file=sys.stderr)
return 1
summary = contamination.match.decontaminate_dbs(
str(args.train_db),
str(args.eval_db),
allowlist_path=str(args.output),
review_path=str(args.near_duplicate_rejects),
)
# The full rejected list is available in the summary; print counts only.
printable = {k: v for k, v in summary.items() if k != "rejected"}
print(json.dumps(printable, sort_keys=True))
return 0
# --- fixed PlotQA C1 release ----------------------------------------------
def cmd_scan_plotqa_prefix(argv: list[str]) -> int:
from ..datasets.plotqa_prefix import collect_plotqa_candidates
parser = argparse.ArgumentParser(prog=f"{_PROG} scan-plotqa-prefix")
parser.add_argument("--annotations", type=Path, required=True)
parser.add_argument("--qa", type=Path, required=True)
args = parser.parse_args(argv)
try:
result = collect_plotqa_candidates(args.annotations, args.qa)
except (OSError, ValueError) as exc:
print(f"{_PROG} scan-plotqa-prefix: {exc}", file=sys.stderr)
return 1
print(
json.dumps(
{
"accepted_candidates": len(result.candidates),
"complete_annotation_items": result.complete_annotation_items,
"complete_qa_items": result.complete_qa_items,
"d15_items": result.d15_items,
"rejection_counts": result.rejection_counts,
},
sort_keys=True,
)
)
return 0
def cmd_build_certified_release(argv: list[str]) -> int:
from ..datasets.release import (
ReleaseError,
build_plotqa_release,
load_release_config,
)
parser = argparse.ArgumentParser(prog=f"{_PROG} build-certified-release")
parser.add_argument("--annotations", type=Path, required=True)
parser.add_argument("--qa", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument(
"--release-config",
type=Path,
default=repo_root() / "configs" / "release.plotqa-prefix.json",
)
parser.add_argument(
"--code-commit",
required=True,
help="clean 40-hex commit containing the exact generator implementation.",
)
parser.add_argument(
"--workers",
type=int,
default=8,
help="Ordered generation worker processes (default: 8; output bytes are invariant).",
)
args = parser.parse_args(argv)
try:
config = load_release_config(args.release_config)
summary = build_plotqa_release(
annotations_prefix=args.annotations,
qa_prefix=args.qa,
output_dir=args.output,
pipeline_code_commit=args.code_commit,
config=config,
workers=args.workers,
)
except (OSError, ValueError, ReleaseError) as exc:
print(f"{_PROG} build-certified-release: {exc}", file=sys.stderr)
return 1
print(json.dumps(summary.__dict__, sort_keys=True))
return 0
def cmd_replay_certificates(argv: list[str]) -> int:
from ..certificates.replay import replay_dataset
parser = argparse.ArgumentParser(prog=f"{_PROG} replay-certificates")
parser.add_argument("--dataset", type=Path, required=True)
parser.add_argument("--report", type=Path, default=None)
parser.add_argument(
"--workers",
type=int,
default=8,
help="Ordered certificate-replay worker processes (default: 8).",
)
args = parser.parse_args(argv)
try:
results = replay_dataset(args.dataset, workers=args.workers)
except (OSError, ValueError) as exc:
print(f"{_PROG} replay-certificates: {exc}", file=sys.stderr)
return 1
failures = [
{"view_dir": row.view_dir, "errors": list(row.errors)} for row in results if not row.ok
]
report = {
"dataset": str(args.dataset),
"view_count": len(results),
"passed": len(results) - len(failures),
"failed": len(failures),
"failures": failures,
}
if args.report is not None:
from ..atomic_io import atomic_write_json
atomic_write_json(args.report, report)
print(json.dumps({key: value for key, value in report.items() if key != "failures"}))
return 1 if failures else 0
# --- multi-domain EVI core release ----------------------------------------
def cmd_build_evi_core_release(argv: list[str]) -> int:
from ..datasets.evi_core_release import (
EviCoreReleaseError,
build_evi_core_release,
load_evi_core_release_config,
)
parser = argparse.ArgumentParser(prog=f"{_PROG} build-evi-core-release")
parser.add_argument("--plotqa-release", type=Path, required=True)
parser.add_argument("--gqa-train-questions", type=Path, required=True)
parser.add_argument("--gqa-train-scene-graphs", type=Path, required=True)
parser.add_argument("--gqa-val-questions", type=Path, required=True)
parser.add_argument("--gqa-val-scene-graphs", type=Path, required=True)
parser.add_argument("--gqa-image-cache", type=Path, required=True)
parser.add_argument("--clevr-train-questions", type=Path, required=True)
parser.add_argument("--clevr-train-scenes", type=Path, required=True)
parser.add_argument("--clevr-val-questions", type=Path, required=True)
parser.add_argument("--clevr-val-scenes", type=Path, required=True)
parser.add_argument("--clevr-blender-executable", type=Path, required=True)
parser.add_argument("--clevr-dataset-gen-root", type=Path, required=True)
parser.add_argument("--clevr-blender-runtime-library-dir", type=Path, default=None)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument(
"--release-config",
type=Path,
default=repo_root() / "configs" / "release.evi-core-v2.json",
)
parser.add_argument("--code-commit", required=True)
parser.add_argument("--workers", type=int, default=8)
parser.add_argument("--download-workers", type=int, default=24)
args = parser.parse_args(argv)
try:
summary = build_evi_core_release(
plotqa_release=args.plotqa_release,
gqa_train_questions=args.gqa_train_questions,
gqa_train_scene_graphs=args.gqa_train_scene_graphs,
gqa_val_questions=args.gqa_val_questions,
gqa_val_scene_graphs=args.gqa_val_scene_graphs,
gqa_image_cache=args.gqa_image_cache,
clevr_train_questions=args.clevr_train_questions,
clevr_train_scenes=args.clevr_train_scenes,
clevr_val_questions=args.clevr_val_questions,
clevr_val_scenes=args.clevr_val_scenes,
clevr_blender_executable=args.clevr_blender_executable,
clevr_dataset_gen_root=args.clevr_dataset_gen_root,
clevr_blender_runtime_library_dir=args.clevr_blender_runtime_library_dir,
output_dir=args.output,
pipeline_code_commit=args.code_commit,
config=load_evi_core_release_config(args.release_config),
workers=args.workers,
download_workers=args.download_workers,
)
except (OSError, ValueError, EviCoreReleaseError) as exc:
print(f"{_PROG} build-evi-core-release: {exc}", file=sys.stderr)
return 1
print(json.dumps(summary.__dict__, sort_keys=True))
return 0
def cmd_replay_evi_core_release(argv: list[str]) -> int:
from ..datasets.evi_core_release import replay_evi_core_release
parser = argparse.ArgumentParser(prog=f"{_PROG} replay-evi-core-release")
parser.add_argument("--release", type=Path, required=True)
parser.add_argument("--workers", type=int, default=8)
parser.add_argument("--report", type=Path, default=None)
args = parser.parse_args(argv)
try:
results = replay_evi_core_release(args.release, workers=args.workers)
except (OSError, ValueError) as exc:
print(f"{_PROG} replay-evi-core-release: {exc}", file=sys.stderr)
return 1
failures = [
{"view_dir": row.view_dir, "errors": list(row.errors)} for row in results if not row.ok
]
report = {
"release": str(args.release),
"view_count": len(results),
"passed": len(results) - len(failures),
"failed": len(failures),
"failures": failures,
}
if args.report is not None:
from ..atomic_io import atomic_write_json
atomic_write_json(args.report, report)
print(json.dumps({key: value for key, value in report.items() if key != "failures"}))
return 1 if failures else 0
def cmd_validate_evi_core_release(argv: list[str]) -> int:
from ..datasets.evi_core_release import (
EviCoreReleaseError,
validate_evi_core_release,
)
parser = argparse.ArgumentParser(prog=f"{_PROG} validate-evi-core-release")
parser.add_argument("--release", type=Path, required=True)
args = parser.parse_args(argv)
try:
counts = validate_evi_core_release(args.release)
except (EviCoreReleaseError, OSError, ValueError) as exc:
print(f"{_PROG} validate-evi-core-release: {exc}", file=sys.stderr)
return 1
print(
json.dumps(
{
"release": str(args.release),
"group_counts": counts,
"validation_mode": "structural_no_content_hash_replay",
},
sort_keys=True,
)
)
return 0
_IMPLEMENTATIONS = {
"freeze-eval": cmd_freeze_eval,
"ingest": cmd_ingest,
"fingerprint": cmd_fingerprint,
"decontaminate": cmd_decontaminate,
"scan-plotqa-prefix": cmd_scan_plotqa_prefix,
"build-certified-release": cmd_build_certified_release,
"replay-certificates": cmd_replay_certificates,
"build-evi-core-release": cmd_build_evi_core_release,
"replay-evi-core-release": cmd_replay_evi_core_release,
"validate-evi-core-release": cmd_validate_evi_core_release,
}
def main(argv: list[str] | None = None) -> int:
if argv is None:
argv = sys.argv[1:]
return dispatch(_PROG, argv, _SUBCOMMANDS, _IMPLEMENTATIONS)
if __name__ == "__main__":
raise SystemExit(main())