Datasets:
Download scripts/analyze_crossdomain_paper.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 16.9 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/scripts/analyze_crossdomain_paper.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/scripts/analyze_crossdomain_paper.py
-
curl -L -o analyze_crossdomain_paper.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/scripts/analyze_crossdomain_paper.py
16.9 kB
| #!/usr/bin/env python3 | |
| """Replay the 72,000 saved decisions and build descriptive, paired diagnostics. | |
| Inputs are explicit field projections of final responses, not new model calls. | |
| Existing label and group identifiers are treated as opaque keys. No hashes run. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from collections import Counter, defaultdict | |
| import gzip | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from analyze_crossdomain_visual import strict_answer_match | |
| from analyze_visual_judges import number, valid_parsed | |
| MODELS = ["qwen38-flash-next", "gemma4-31b-it", "qwen", "gemma4-26b-a4b-it", "glm", "molmo2-8b"] | |
| CROSS_KEYS = {m: {"qwen": "qwen3.8-27b-fp8", "glm": "GLM-5.3-Flash"}.get(m, m) for m in MODELS} | |
| STATES = {"plotqa": ["FULL", "A_SAME", "A_CHANGED", "U_MISSING", "U_INVALID"], | |
| "clevr": ["FULL", "A_SAME", "A_CHANGED", "U_MISSING"], | |
| "gqa": ["FULL", "A_SAME", "U_MISSING"]} | |
| COMMON = ["FULL", "A_SAME", "U_MISSING"] | |
| METRICS = ["failure", "group_success", "joint_success", "answer_accuracy_strict", | |
| "balanced_failure", "common_state_failure", "common_state_group_success", | |
| "missing_failure", "answerable_failure", "unanswerable_failure"] | |
| def read(path): | |
| return json.loads(Path(path).read_text()) | |
| def rows(path): | |
| with gzip.open(path, "rt") as handle: | |
| return [json.loads(line) for line in handle if line.strip()] | |
| def interval(samples): | |
| return np.quantile(samples, [.025, .975], axis=0).tolist() | |
| def analyze(inputs: Path, expected: Path, draws: int = 10000): | |
| if draws < 10000: | |
| raise ValueError("The manuscript analysis requires at least 10,000 bootstrap draws") | |
| plot_labels = read(inputs / "plotqa/labels.json") | |
| cross_labels = read(inputs / "crossdomain/labels.json") | |
| manifest = [json.loads(line) for line in (inputs / "crossdomain/manifest.jsonl").read_text().splitlines()] | |
| blind = {r["item_id"]: r for r in manifest} | |
| if len(blind) != len(manifest) or len(blind) != 7000: | |
| raise ValueError("Cross-domain manifest must contain 7,000 unique IDs") | |
| plot_manifest = [json.loads(line) for line in (inputs / "plotqa/manifest.jsonl").read_text().splitlines()] | |
| plot_blind = {r["item_id"]: r for r in plot_manifest} | |
| if len(plot_blind) != len(plot_manifest) or len(plot_blind) != 5000: | |
| raise ValueError("PlotQA manifest must contain 5,000 unique IDs") | |
| group_meta = read(inputs / "crossdomain/group-metadata.json") | |
| meta = {r["group_id"]: r for r in group_meta} | |
| if len(meta) != len(group_meta) or len(meta) != 2000: | |
| raise ValueError("Expected 2,000 distinct frozen group metadata records") | |
| label_sets = {"plotqa": plot_labels, | |
| **{s: [r for r in cross_labels if r["source"] == s] for s in ["clevr", "gqa"]}} | |
| old_plot = read(expected / "plotqa-analysis.json")["models"] | |
| old_joint = read(expected / "plotqa-joint.json")["models"] | |
| old_cross = read(expected / "crossdomain-analysis.json")["models"] | |
| outputs = {} | |
| output_rows = 0 | |
| for domain in ["plotqa", "crossdomain"]: | |
| expected_ids = {r["item_id"] for r in (plot_labels if domain == "plotqa" else cross_labels)} | |
| questions = plot_blind if domain == "plotqa" else blind | |
| if expected_ids != set(questions): | |
| raise ValueError("Label IDs and frozen question IDs differ") | |
| outputs[domain] = {} | |
| for model in MODELS: | |
| key = model if domain == "plotqa" else CROSS_KEYS[model] | |
| loaded = rows(inputs / domain / (key + ".jsonl.gz")) | |
| records = {r["item_id"]: r for r in loaded} | |
| if len(records) != len(loaded) or set(records) != expected_ids: | |
| raise ValueError(f"{domain}/{model}: duplicate, missing or unexpected IDs") | |
| for r in loaded: | |
| if r["status"] != "completed" and not ( | |
| r["status"] == "invalid_schema" and r.get("terminal_invalid") is True): | |
| raise ValueError(f"{domain}/{model}: unfinished response") | |
| if r["question"] != questions[r["item_id"]]["question"]: | |
| raise ValueError("Question differs from frozen blind input") | |
| output_rows += len(loaded) | |
| outputs[domain][model] = records | |
| result = {"schema_version": 1, "models": MODELS, "domains": {}, "provenance": {}, | |
| "protocol": {"draws": draws, "seed": 20260915, "unit": "source-question group", | |
| "interval": "descriptive percentile bootstrap; paired within domain; no multiplicity adjustment", | |
| "common_states": COMMON, "inference_calls": 0, | |
| "cross_domain_interpretation": "different questions, states and evidence guarantees; no causal domain effect", | |
| "balanced_failure": "one half answerable failure plus one half unanswerable failure; invalids fail in their truth class", | |
| "new_metrics": "post-hoc descriptive additions; not preregistered", | |
| "source_image_clustering": "one question per source image is the release builder contract; portable labels cannot re-audit original image identities for CLEVR/GQA", | |
| "sha_validation_performed": False}} | |
| total_invalid = 0 | |
| for source, labels in label_sets.items(): | |
| states = STATES[source] | |
| gold = {r["item_id"]: r for r in labels} | |
| if len(gold) != len(labels) or len(labels) != 1000 * len(states): | |
| raise ValueError(f"{source}: invalid number of unique labels") | |
| grouped = defaultdict(dict) | |
| for r in labels: | |
| if r["state"] not in states or type(r["answerable"]) is not bool: | |
| raise ValueError("Malformed state or target") | |
| if r["answerable"] != (not r["state"].startswith("U_")): | |
| raise ValueError("Inconsistent answerability label") | |
| if r["state"] in grouped[r["group_id"]]: | |
| raise ValueError("Repeated group state") | |
| if source != "plotqa": | |
| g = meta[r["group_id"]] | |
| if g["source"] != source or g["question"] != blind[r["item_id"]]["question"]: | |
| raise ValueError("Release group/question join failed") | |
| grouped[r["group_id"]][r["state"]] = r | |
| if len(grouped) != 1000 or any(set(g) != set(states) for g in grouped.values()): | |
| raise ValueError(f"{source}: incomplete group coverage") | |
| group_ids = sorted(grouped) | |
| ordered = [[grouped[g][s] for s in states] for g in group_ids] | |
| positive = np.array([not s.startswith("U_") for s in states]) | |
| common = [states.index(s) for s in COMMON] | |
| vectors = [] | |
| domain = {"groups": 1000, "views": len(labels), "states": states, "models": {}} | |
| if source == "gqa": | |
| location = np.array([grouped[g]["FULL"]["target"] in {"left", "right", "top", "bottom"} for g in group_ids]) | |
| domain["location_sensitivity"] = { | |
| "selection": "FULL canonical target in {left, right, top, bottom}; all sibling states retained", | |
| "location_groups": int(location.sum()), "other_groups": int((~location).sum()), | |
| "location_group_ids": [g for g, selected in zip(group_ids, location) if selected], | |
| "interpretation": "post-hoc vulnerability stratum, not adjudicated label errors; retained complement is not certified clean", | |
| "models": {}, "intervals": "point estimates only"} | |
| if source != "plotqa": | |
| mm = [meta[g] for g in group_ids] | |
| domain["program_steps"] = dict(sorted(Counter(g["dependency_depth"] for g in mm).items())) | |
| domain["program_steps_note"] = "Stored dependency_depth is len(program steps), not tree depth" | |
| domain["answer_types"] = dict(Counter(g["answer_type"] for g in mm)) | |
| for model in MODELS: | |
| records = outputs["plotqa" if source == "plotqa" else "crossdomain"][model] | |
| invalid = np.zeros((1000, len(states)), dtype=bool) | |
| wrong = invalid.copy() | |
| correct_answer = invalid.copy() | |
| for i, gg in enumerate(ordered): | |
| for j, r in enumerate(gg): | |
| prediction = records[r["item_id"]] | |
| if source == "plotqa" and prediction["question"] != records[gg[0]["item_id"]]["question"]: | |
| raise ValueError("PlotQA sibling questions differ") | |
| parsed = valid_parsed(prediction) | |
| invalid[i, j] = parsed is None | |
| wrong[i, j] = parsed is not None and parsed["answerable"] != r["answerable"] | |
| if parsed and parsed["answerable"] and r["answerable"]: | |
| if source == "plotqa": | |
| value, target = number(parsed["answer"]), number(r["target"]) | |
| correct_answer[i, j] = value is not None and target is not None and value == target | |
| else: | |
| correct_answer[i, j] = strict_answer_match(parsed["answer"], r["target"]) | |
| fail = invalid | wrong | |
| success = ~fail.any(axis=1) | |
| joint = success & correct_answer[:, positive].all(axis=1) | |
| if joint.sum() > success.sum(): | |
| raise ValueError("Joint answer success cannot exceed decision success") | |
| pos = fail[:, positive].mean(axis=1) | |
| neg = fail[:, ~positive].mean(axis=1) | |
| matrix = np.column_stack([fail.mean(axis=1), success, joint, | |
| correct_answer[:, positive].mean(axis=1), (pos + neg) / 2, | |
| fail[:, common].mean(axis=1), ~fail[:, common].any(axis=1), | |
| fail[:, states.index("U_MISSING")], pos, neg]) | |
| vectors.append(matrix) | |
| counts = {"failures": int(fail.sum()), "invalid": int(invalid.sum()), | |
| "valid_decision_errors": int(wrong.sum()), "valid": int((~invalid).sum()), | |
| "groups_correct": int(success.sum()), "joint_groups_correct": int(joint.sum()), | |
| "strict_answers_correct": int(correct_answer[:, positive].sum()), | |
| "answerable_views": int(1000 * positive.sum()), | |
| "unanswerable_views": int(1000 * (~positive).sum())} | |
| state_counts = {s: {"failures": int(fail[:, j].sum()), "invalid": int(invalid[:, j].sum()), | |
| "valid_decision_errors": int(wrong[:, j].sum()), "views": 1000} | |
| for j, s in enumerate(states)} | |
| if source == "plotqa": | |
| old = old_plot[model] | |
| checks = [(counts["failures"], old["error_fraction_if_invalid_count_wrong"]["numerator"]), | |
| (counts["invalid"], old["invalid_or_missing"]), | |
| (counts["valid_decision_errors"], old["answerability_errors"]["numerator"]), | |
| (counts["groups_correct"], old["five_view_groups_all_correct"]["numerator"]), | |
| (counts["joint_groups_correct"], old_joint[model]["strict_joint_all_five_groups"]["numerator"])] | |
| for s in states: | |
| checks.append((state_counts[s]["failures"], old["state_counts"][s]["failures_including_invalid"]["numerator"])) | |
| else: | |
| old = old_cross[CROSS_KEYS[model]]["by_source"][source] | |
| checks = [(counts["failures"], old["failures_full_denominator"]["numerator"]), | |
| (counts["invalid"], old["invalid_outputs"]), | |
| (counts["valid_decision_errors"], old["answerability_errors"]["numerator"]), | |
| (counts["groups_correct"], old["groups_all_states_correct"]["numerator"]), | |
| (counts["strict_answers_correct"], old["answer_correct_on_all_answerable_strict_lower_bound"]["numerator"])] | |
| for s in states: | |
| checks.append((state_counts[s]["failures"], old["states"][s]["failures_full_denominator"]["numerator"])) | |
| if any(a != b for a, b in checks): | |
| raise ValueError(f"Saved aggregate mismatch: {source}/{model}: {checks}") | |
| domain["models"][model] = {"counts": counts, "states": state_counts, | |
| "metrics": dict(zip(METRICS, matrix.mean(axis=0).tolist())), | |
| "saved_aggregate_checks": len(checks), | |
| "invalid_item_ids": [r["item_id"] for i, gg in enumerate(ordered) | |
| for j, r in enumerate(gg) if invalid[i, j]]} | |
| if source == "gqa": | |
| domain["location_sensitivity"]["models"][model] = {} | |
| for stratum, mask in [("location", location), ("other", ~location)]: | |
| domain["location_sensitivity"]["models"][model][stratum] = { | |
| "groups": int(mask.sum()), "views": int(mask.sum() * len(states)), | |
| "failures": int(fail[mask].sum()), "groups_correct": int(success[mask].sum()), | |
| "missing_failures": int(fail[mask, states.index("U_MISSING")].sum()), | |
| "invalid": int(invalid[mask].sum())} | |
| total_invalid += counts["invalid"] | |
| if model == "qwen" and source != "plotqa": | |
| backend = {"subsets": {}, "group_composition": dict(Counter( | |
| "mixed" if len({records[r["item_id"]]["saved_backend"] for r in gg}) > 1 | |
| else records[gg[0]["item_id"]]["saved_backend"] for gg in ordered))} | |
| for name in ["bridge", "simflow"]: | |
| mask = np.array([[records[r["item_id"]]["saved_backend"] == name for r in gg] for gg in ordered]) | |
| backend["subsets"][name] = {"views": int(mask.sum()), "failures": int(fail[mask].sum()), | |
| "invalid": int(invalid[mask].sum()), "state_counts": {s: int(mask[:, j].sum()) for j, s in enumerate(states)}} | |
| backend["interpretation"] = "Availability-selected disjoint subsets; not a matched backend comparison" | |
| result["provenance"][source] = backend | |
| values = np.stack(vectors, axis=1) | |
| rng = np.random.default_rng(20260915) | |
| boot = np.empty((draws, len(MODELS), len(METRICS))) | |
| for start in range(0, draws, 100): | |
| end = min(start + 100, draws) | |
| selected = rng.integers(0, 1000, size=(end - start, 1000)) | |
| boot[start:end] = values[selected].mean(axis=1) | |
| for i, model in enumerate(MODELS): | |
| domain["models"][model]["intervals_95"] = {m: interval(boot[:, i, k]) for k, m in enumerate(METRICS)} | |
| contrasts = {} | |
| for i, left in enumerate(MODELS): | |
| for j in range(i + 1, len(MODELS)): | |
| right = MODELS[j] | |
| contrasts[left + "__" + right] = {"left": left, "right": right, | |
| **{metric: {"left_minus_right_pp": float((values[:, i, k] - values[:, j, k]).mean() * 100), | |
| "interval_95_pp": interval((boot[:, i, k] - boot[:, j, k]) * 100)} | |
| for k, metric in enumerate(METRICS)}} | |
| domain["paired_contrasts"] = contrasts | |
| domain["analytic_baselines"] = {"always_answerable_failure": float((~positive).mean()), | |
| "always_unanswerable_failure": float(positive.mean()), "constant_decision_group_success": 0, | |
| "constant_decision_balanced_failure": .5} | |
| result["domains"][source] = domain | |
| result["validation"] = {"status": "passed", "selected_model_responses": output_rows, | |
| "unique_input_views": 12000, "source_question_groups": 3000, "model_domain_cells": 18, | |
| "terminal_invalid_responses": total_invalid, "valid_responses": output_rows - total_invalid, | |
| "missing_or_duplicate_rows": 0, "original_aggregate_counts_reproduced": True, | |
| "all_model_frozen_question_joins": True, | |
| "output_projection_scope": "parsed response fields, not independent raw-output/token validation", | |
| "sha_validation_performed": False} | |
| return result | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--inputs", type=Path, required=True) | |
| parser.add_argument("--expected", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, required=True) | |
| args = parser.parse_args() | |
| result = analyze(args.inputs, args.expected) | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False) + "\n") | |
| print(json.dumps(result["validation"])) | |
| if __name__ == "__main__": | |
| main() | |