Download validate.py from saxenan3/mncri: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/datasets/saxenan3/mncri/resolve/main/validate.py
- Command line
-
hf download hf://datasets/saxenan3/mncri/validate.py
-
curl -L -o validate.py https://huggingface.co/datasets/saxenan3/mncri/resolve/main/validate.py
11.9 kB
| """Independently verify the canonical items and the published Parquet payloads.""" | |
| import argparse | |
| from collections import Counter | |
| from hashlib import sha256 | |
| from io import BytesIO | |
| import json | |
| from pathlib import Path | |
| import re | |
| import subprocess | |
| import wave | |
| import pyarrow.parquet as pq | |
| from PIL import Image | |
| from corpus import (expression_text, greedy_cost, path_costs, run_updates, shortest_path, | |
| text_for_edge, transitions, update_text) | |
| def check(condition, reason): | |
| if not condition: | |
| raise ValueError(reason) | |
| def replace_at(rows, index, replacement): | |
| return [*rows[:index], replacement, *rows[index + 1:]] | |
| def substitute_backwards(initial, updates, target): | |
| factor, offset = 1, 0 | |
| for destination, source, multiplier, constant in reversed(updates): | |
| if destination == target: | |
| target = source | |
| offset += factor * constant | |
| factor *= multiplier | |
| return factor * initial[target] + offset | |
| def validate_item(item): | |
| facts = item["facts"] | |
| speech = item["speech"] | |
| cf = item["counterfactual"] | |
| index = cf["fact_index"] | |
| family = item["family"] | |
| check(0 <= index < len(facts) == len(speech), "Fact and speech alignment") | |
| check(facts[index] != cf["fact"] and speech[index] != cf["speech"], "Ineffective media edit") | |
| check(cf["gold"] != item["gold"], "Unchanged counterfactual answer") | |
| if family == "shortpath": | |
| graph = item["graph"] | |
| nodes, edges, source, target = [graph[key] for key in ("nodes", "edges", "source", "target")] | |
| check(len(nodes) == item["rung"] and len(edges) == len(facts), "Incorrect route size") | |
| parsed = [] | |
| for fact, spoken in zip(facts, speech): | |
| match = re.fullmatch(r"([A-Z]) - ([A-Z])\s+\|\s+(\d+)", fact) | |
| check(bool(match), "Route fact syntax") | |
| a, b, w = match.groups() | |
| parsed.append([a, b, int(w)]) | |
| check(spoken == f"The edge between {a} and {b} has cost {w}.", "Route speech differs") | |
| check(parsed == edges, "Graph differs from visible edge list") | |
| paths = path_costs(nodes, edges, source, target) | |
| check(paths[0][0] == item["gold"] == shortest_path(nodes, edges, source, target), "Disagreeing route solvers") | |
| check(len(paths[0][1]) >= 3 and paths[0][0] < paths[1][0], "Invalid optimum") | |
| check(greedy_cost(nodes, edges, source, target) != item["gold"], "Greedy shortcut") | |
| edited = replace_at(edges, index, cf["replacement"]) | |
| check(shortest_path(nodes, edited, source, target) == cf["gold"], "Wrong edited route cost") | |
| check((cf["fact"], cf["speech"]) == text_for_edge(cf["replacement"]), "Wrong rendered edge edit") | |
| elif family == "config_patch": | |
| program = item["program"] | |
| initial, updates, target = [program[key] for key in ("initial", "updates", "target")] | |
| check(len(updates) == 13 and len(facts) == 14, "Incorrect register update load") | |
| match = re.fullmatch(r"All registers start at 0 except ([A-Z]) = (\d+)\.", facts[0]) | |
| check(bool(match), "Initial state syntax") | |
| active, initial_value = match.groups() | |
| check(initial[active] == int(initial_value) and sum(v != 0 for v in initial.values()) == 1, "Initial state mismatch") | |
| check(speech[0] == f"Every register starts at zero except register {active}, which starts at {initial_value}.", | |
| "Spoken initial state differs") | |
| parsed = [] | |
| for fact, spoken in zip(facts[1:], speech[1:]): | |
| match = re.fullmatch(r"([A-Z]) = (2 × )?([A-Z]) ([+-]) (\d+)", fact) | |
| check(bool(match), "Update syntax") | |
| dst, factor, src, sign, amount = match.groups() | |
| value = int(amount) if sign == "+" else -int(amount) | |
| parsed.append([dst, src, 2 if factor else 1, value]) | |
| multiplier = "twice " if factor else "" | |
| operation = "plus" if value > 0 else "minus" | |
| check(spoken == f"Set register {dst} to {multiplier}register {src} {operation} {amount}.", "Update speech differs") | |
| check(parsed == updates, "Program differs from visual facts") | |
| gold, _ = run_updates(initial, updates, target) | |
| check(gold == item["gold"] == substitute_backwards(initial, updates, target), "Disagreeing register solvers") | |
| influences = [] | |
| for offset, op in enumerate(updates): | |
| changed = [*op[:3], op[3] + 1] | |
| variant, _ = run_updates(initial, replace_at(updates, offset, changed), target) | |
| if variant != gold: | |
| influences.append(offset + 1) | |
| needed = item["solution"]["required_fact_indices"] | |
| check(influences == needed and len(needed) == item["rung"], "Controlled dependency count failed") | |
| edited = replace_at(updates, index - 1, cf["replacement"]) | |
| check(run_updates(initial, edited, target)[0] == cf["gold"] == substitute_backwards(initial, edited, target), | |
| "Wrong edited register value") | |
| check((cf["fact"], cf["speech"]) == update_text(cf["replacement"]), "Wrong rendered register edit") | |
| group, alt = (item["layouts"][name] for name in ("grouped_av", "alternating_av")) | |
| check(all(len(mask) == len(facts) and set(mask) == {0, 1} for mask in (group, alt)), "Invalid modality mask") | |
| check(sum(group) == sum(alt) and transitions(group) == transitions(alt), "Unmatched timeline") | |
| check(all(group[i] == alt[i] for i in range(len(facts)) if i not in needed), "Distractor channel differs") | |
| ga, aa = [[mask[i] for i in needed] for mask in (group, alt)] | |
| check(sum(ga) == sum(aa) and ga[0] == aa[0] and ga[-1] == aa[-1], "Required sources unbalanced") | |
| check(len(set(ga)) == len(set(aa)) == 2 and transitions(ga) < transitions(aa) == len(aa) - 1, | |
| "Invalid difference in dependency crossings") | |
| elif family == "modes": | |
| expressions = item["expressions"] | |
| results = [] | |
| for (a, b, op), fact, spoken in zip(expressions, facts, speech): | |
| check(fact == f"{a} {op} {b}", "Expression differs from visual fact") | |
| operator = "plus" if op == "+" else "minus" | |
| check(spoken == f"{a} {operator} {b}.", "Expression speech differs") | |
| results.append(a + b if op == "+" else a - b) | |
| top = Counter(results).most_common() | |
| check(len(results) == item["rung"] == len(facts), "Incorrect parallel load") | |
| check(top[0][1] > top[1][1] and top[0][0] == item["gold"], "Mode is missing or ambiguous") | |
| a, b, op = cf["replacement"] | |
| replacement = a + b if op == "+" else a - b | |
| edited = Counter(replace_at(results, index, replacement)).most_common() | |
| check(edited[0][1] > edited[1][1] and edited[0][0] == cf["gold"], "Wrong edited mode") | |
| check((cf["fact"], cf["speech"]) == expression_text(cf["replacement"]), "Wrong rendered expression edit") | |
| else: | |
| raise ValueError(f"Unknown task family {family}") | |
| def validate_png(data): | |
| with Image.open(BytesIO(data)) as image: | |
| check(image.format == "PNG" and min(image.size) >= 360, "Invalid still image") | |
| image.verify() | |
| def validate_wav(data): | |
| with wave.open(BytesIO(data)) as recording: | |
| check(recording.getnchannels() == 1, "Expected mono WAV") | |
| check(recording.getframerate() >= 16000 and recording.getsampwidth() == 2, "Unexpected audio encoding") | |
| check(recording.getnframes() > recording.getframerate(), "Missing speech") | |
| check(any(recording.readframes(recording.getnframes())), "Silent recording") | |
| def validate_mp4(data, has_speech, decode=False): | |
| check(data[4:8] == b"ftyp" and b"avc1" in data, "Expected H.264 MP4") | |
| check((b"mp4a" in data) == has_speech, "Unexpected MP4 audio track") | |
| check(b"moov" in data and data.find(b"moov") < data.find(b"mdat"), "MP4 lacks fast start") | |
| if decode: | |
| from imageio_ffmpeg import get_ffmpeg_exe | |
| subprocess.run( | |
| [get_ffmpeg_exe(), "-v", "error", "-xerror", "-i", "pipe:0", "-f", "null", "-"], | |
| input=data, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, | |
| ) | |
| def verify_release(manifest_file, data_files, decode_all=False): | |
| items = {} | |
| for line in manifest_file.read_text(encoding="utf-8").splitlines(): | |
| item = json.loads(line) | |
| check(item["item_id"] not in items, "Duplicate manifest item identifier") | |
| validate_item(item) | |
| items[item["item_id"]] = item | |
| check(bool(items), "No benchmark items") | |
| seen = set() | |
| groups = Counter() | |
| fingerprints = set() | |
| decoded_cells = 0 | |
| for file in data_files: | |
| parquet = pq.ParquetFile(file) | |
| metadata = json.loads(parquet.schema_arrow.metadata[b"huggingface"]) | |
| features = metadata["info"]["features"] | |
| for col, expected in (("image", "Image"), ("audio", "Audio"), ("video", "Video"), | |
| ("av_grouped", "Video"), ("av_alternating", "Video")): | |
| check(features[col]["_type"] == expected, f"Wrong Viewer type for {col}") | |
| for batch in parquet.iter_batches(batch_size=8): | |
| for row in batch.to_pylist(): | |
| item = items[row["item_id"]] | |
| check(row["item_id"] not in seen, "Split or shard overlap") | |
| seen.add(row["item_id"]) | |
| for key in ("split", "family", "rung", "question", "gold"): | |
| check(row[key] == item[key], f"Wrong stored field {key}") | |
| check(row["text"] == "\n".join(item["facts"]), "Text representation differs from canonical facts") | |
| fingerprint = sha256(f"{row['question']}\n{row['text']}".encode()).hexdigest() | |
| check(fingerprint not in fingerprints, "Duplicate problem across splits") | |
| fingerprints.add(fingerprint) | |
| groups[(row["split"], row["family"], row["rung"])] += 1 | |
| validate_png(row["image"]["bytes"]) | |
| validate_wav(row["audio"]["bytes"]) | |
| validate_mp4(row["video"]["bytes"], False, decode_all) | |
| for col, layout in (("av_grouped", "grouped_av"), ("av_alternating", "alternating_av")): | |
| expected = row["family"] == "config_patch" | |
| check((row[col] is not None) == expected, f"Unexpected {col} availability") | |
| if expected: | |
| validate_mp4(row[col]["bytes"], True, decode_all) | |
| check(json.loads(row["layout_" + col]) == item["layouts"][layout], "Paired layout metadata mismatch") | |
| else: | |
| check(row["layout_" + col] is None, "Unexpected layout metadata") | |
| if decode_all: | |
| decoded_cells += 3 if row["family"] == "config_patch" else 1 | |
| check(seen == set(items), "Release is missing manifest items") | |
| counts = Counter((split, family) for split, family, _ in groups) | |
| check(len(counts) == 6, "Missing task family or split") | |
| return { | |
| "rows": len(seen), | |
| "paired_items": sum(n for (_, family, _), n in groups.items() if family == "config_patch"), | |
| "rows_by_split_family_rung": {f"{s}/{f}/{r}": n for (s, f, r), n in sorted(groups.items())}, | |
| "full_mp4_decodes": decoded_cells, | |
| "parquet_sha256": {file.name: sha256(file.read_bytes()).hexdigest() for file in data_files}, | |
| } | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("manifest", type=Path) | |
| parser.add_argument("parquet", type=Path, nargs="+") | |
| parser.add_argument("--decode-all", action="store_true") | |
| parser.add_argument("--output", type=Path) | |
| args = parser.parse_args() | |
| report = json.dumps(verify_release(args.manifest, args.parquet, args.decode_all), indent=2) | |
| if args.output: | |
| args.output.write_text(report + "\n", encoding="utf-8") | |
| print(report) | |