Datasets:
File size: 8,812 Bytes
e1ced61 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | #!/usr/bin/env python3
"""Offline integrity, HF loading, cohort, image, and source-label validation."""
from __future__ import annotations
import argparse
import io
import json
import os
import sys
from collections import Counter, defaultdict
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from hf_release_common import (
STATES,
digest,
file_digest,
read_json,
read_rows,
safe_path,
write_json,
)
def verify_proof(row):
from explicit_learning.certificates.bounded_plot import verify_bounded_plot
result = verify_bounded_plot(row)
if not result["ok"]:
raise ValueError("Invalid chart proof " + str(result))
return row["group_id"]
def verify(dataset, workers, pre_seal=False):
sys.path.insert(0, str(dataset / "src"))
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["HF_DATASETS_OFFLINE"] = "1"
from datasets import Image as HFImage
from datasets import load_dataset
from PIL import Image
from explicit_learning.certificates.build import program_from_dict
from explicit_learning.executors.clevr import ClevrExecutor
from explicit_learning.executors.plot import PlotExecutor
if not pre_seal:
manifest = read_json(dataset / "MANIFEST.json")
actual = {
str(path.relative_to(dataset))
for path in dataset.rglob("*")
if path.is_file() and "__pycache__" not in path.parts and path.name != "MANIFEST.json"
}
if actual != set(manifest["files"]):
raise ValueError("Frozen file set changed")
for relative, item in manifest["files"].items():
path = safe_path(dataset, relative)
if path.stat().st_size != item["bytes"] or file_digest(path) != item["sha256"]:
raise ValueError("Frozen file changed: " + relative)
labels = read_rows(dataset / "metadata/views.jsonl.gz")
by_id = {row["item_id"]: row for row in labels}
if len(labels) != len(by_id) or Counter(row["source"] for row in labels) != {
"plotqa": 5000,
"clevr": 4000,
"gqa": 3000,
}:
raise ValueError("Wrong cohort")
groups = defaultdict(list)
image_ids = defaultdict(set)
for row in labels:
groups[row["group_id"]].append(row)
image_ids[row["source"]].add(row["source_image_id"])
if len(groups) != 3000 or any(len(ids) != 1000 for ids in image_ids.values()):
raise ValueError("Group/source-image uniqueness differs")
for rows in groups.values():
if len(rows) != len(STATES[rows[0]["source"]]) or {row["state"] for row in rows} != set(
STATES[rows[0]["source"]]
):
raise ValueError("Incomplete state group")
if len({row["question_sha256"] for row in rows}) != 1:
raise ValueError("Sibling questions differ")
seen, image_checks = set(), 0
for source in STATES:
# Exercise the README's actual config discovery, not just a Parquet reader.
data = load_dataset(str(dataset), name=source, split="test").cast_column(
"image", HFImage(decode=False)
)
if len(data) != {"plotqa": 5000, "clevr": 4000, "gqa": 3000}[source]:
raise ValueError("HF configuration row count differs")
for row in data:
if row["item_id"] in seen:
raise ValueError("Repeated HF item")
seen.add(row["item_id"])
if {key: value for key, value in row.items() if key != "image"} != by_id[
row["item_id"]
]:
raise ValueError("HF metadata differs from scoring metadata")
if source == "gqa":
if row["image"] is not None or row["question"] is not None:
raise ValueError("GQA upstream media/text present in the upload candidate")
continue
blob = row["image"]["bytes"]
if digest(blob) != row["image_sha256"]:
raise ValueError("Image bytes changed in Parquet")
with Image.open(io.BytesIO(blob)) as image:
image.load()
if image.size != (row["width"], row["height"]):
raise ValueError("Image dimensions changed")
image_checks += 1
if seen != set(by_id):
raise ValueError("HF and scoring IDs differ")
proofs = read_rows(dataset / "evidence/plotqa/bounded-witness-proofs.jsonl.gz")
plot_groups = {gid: rows for gid, rows in groups.items() if rows[0]["source"] == "plotqa"}
if len(proofs) != len({proof["group_id"] for proof in proofs}) or {
proof["group_id"] for proof in proofs
} != set(plot_groups):
raise ValueError("Proof cohort differs")
import base64
for proof in proofs:
rows = plot_groups[proof["group_id"]]
if any(
proof["source_native_id"] != row["source_question_id"]
or proof["question"] != row["question"]
for row in rows
):
raise ValueError("Proof question/source join failed")
missing = next(row for row in rows if row["state"] == "U_MISSING")
if (
digest(base64.b64decode(proof["observed_png_base64"], validate=True))
!= missing["image_sha256"]
):
raise ValueError("Proof observation is not the evaluated image")
with ProcessPoolExecutor(max_workers=workers) as pool:
checked = list(pool.map(verify_proof, proofs, chunksize=5))
semantic_checks = Counter()
for source, executor in (("plotqa", PlotExecutor()), ("clevr", ClevrExecutor())):
for row in read_rows(dataset / f"evidence/{source}/views.jsonl.gz"):
label = by_id[row["item_id"]]
program = program_from_dict(row["program"])
result = executor.execute(program, world=row["world_after"])
if label["answerable"]:
if result.status != "UNIQUE" or str(result.answer_canonical) != label["target"]:
raise ValueError("Supported source-program target differs: " + row["item_id"])
elif (
result.status
!= {"U_MISSING": "MISSING_INFORMATION", "U_INVALID": "INVALID_REFERENT"}[
row["state"]
]
):
raise ValueError("Unanswerable source-program failure category differs")
if source == "clevr" and row["state"] == "U_MISSING":
a, b = [
executor.execute(program, world=row[key])
for key in ("completion_a", "completion_b")
]
if (
a.status != "UNIQUE"
or b.status != "UNIQUE"
or a.answer_canonical == b.answer_canonical
):
raise ValueError("CLEVR symbolic alternatives fail")
semantic_checks[source] += 1
recipes = read_rows(dataset / "evidence/gqa/reconstruction.jsonl.gz")
if len(recipes) != 3000 or {row["item_id"] for row in recipes} != {
row["item_id"] for row in labels if row["source"] == "gqa"
}:
raise ValueError("GQA reconstruction coverage differs")
if sum(row["gqa_location_stratum"] for row in recipes) != 376 * 3:
raise ValueError("GQA sensitivity stratum changed")
return {
"status": "passed",
"hf_configs": list(STATES),
"unique_views": len(seen),
"source_groups": len(groups),
"embedded_images_decoded_and_hashed": image_checks,
"proofs_verified": len(checked),
"proof_observations_match_evaluated_images": len(proofs),
"source_program_checks": dict(semantic_checks),
"gqa_recipes": len(recipes),
"gqa_location_groups": 376,
"gqa_hydration": "separate reconstruction-validation.json",
"file_manifest_verified": not pre_seal,
"network_calls": 0,
"publication_performed": False,
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset", type=Path, default=Path(__file__).resolve().parents[1])
parser.add_argument("--workers", type=int, default=8)
parser.add_argument(
"--pre-seal",
action="store_true",
help="Maintainer validation before creating MANIFEST.json",
)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
if args.workers < 1:
parser.error("workers must be positive")
if args.output.resolve().is_relative_to(args.dataset.resolve()):
parser.error("Write validation outside the frozen dataset directory")
report = verify(args.dataset.resolve(), args.workers, args.pre_seal)
write_json(args.output, report)
print(json.dumps(report))
|