Datasets:
Download scripts/analyze_visual_judges.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/scripts/analyze_visual_judges.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/scripts/analyze_visual_judges.py
-
curl -L -o analyze_visual_judges.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/scripts/analyze_visual_judges.py
15.1 kB
| #!/usr/bin/env python3 | |
| """Analyze blinded visual-answerability judgments on the fixed five-view groups.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import random | |
| import re | |
| from collections import Counter | |
| from fractions import Fraction | |
| from pathlib import Path | |
| STATES = ["FULL", "A_SAME", "A_CHANGED", "U_MISSING", "U_INVALID"] | |
| def ratio(numerator: int, denominator: int) -> dict: | |
| return { | |
| "numerator": int(numerator), | |
| "denominator": int(denominator), | |
| "value": float(numerator / denominator) if denominator else None, | |
| } | |
| def number(value): | |
| """Conservative numeric parser retained from the original pilot analysis.""" | |
| if value is None: | |
| return None | |
| text = str(value).strip().replace(",", "") | |
| match = re.fullmatch( | |
| r"[$€£]?\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?(?:/\d+)?)\s*(thousand|million|billion|%)?", | |
| text, | |
| re.I, | |
| ) | |
| if not match: | |
| return None | |
| try: | |
| factor = { | |
| "thousand": 1_000, | |
| "million": 1_000_000, | |
| "billion": 1_000_000_000, | |
| }.get((match[2] or "").lower(), 1) | |
| return Fraction(match[1]) * factor | |
| except (ValueError, ZeroDivisionError): | |
| return None | |
| def wilson_interval(successes: int, total: int, z: float = 1.959963984540054) -> list[float] | None: | |
| if not total: | |
| return None | |
| proportion = successes / total | |
| denominator = 1 + z * z / total | |
| center = (proportion + z * z / (2 * total)) / denominator | |
| margin = z * math.sqrt(proportion * (1 - proportion) / total + z * z / (4 * total * total)) / denominator | |
| return [max(0.0, center - margin), min(1.0, center + margin)] | |
| def clustered_interval(group_numerators: list[int], group_denominators: list[int], seed: int = 20260914) -> list[float] | None: | |
| if not group_denominators or not sum(group_denominators): | |
| return None | |
| rng = random.Random(seed) | |
| values = [] | |
| size = len(group_denominators) | |
| for _ in range(10_000): | |
| selected = [rng.randrange(size) for _ in range(size)] | |
| denominator = sum(group_denominators[index] for index in selected) | |
| if denominator: | |
| values.append(sum(group_numerators[index] for index in selected) / denominator) | |
| if not values: | |
| return None | |
| values.sort() | |
| return [values[int(0.025 * (len(values) - 1))], values[int(0.975 * (len(values) - 1))]] | |
| def valid_parsed(row: dict) -> dict | None: | |
| parsed = row.get("parsed") | |
| if row.get("status") != "completed" or not isinstance(parsed, dict): | |
| return None | |
| if type(parsed.get("answerable")) is not bool: | |
| return None | |
| if parsed.get("answer") is not None and not isinstance(parsed.get("answer"), str): | |
| return None | |
| if not isinstance(parsed.get("reason"), str) or not parsed["reason"].strip(): | |
| return None | |
| if not parsed["answerable"] and parsed.get("answer") is not None: | |
| return None | |
| return parsed | |
| def analyze(labels: list[dict], model_rows: dict[str, list[dict]]) -> dict: | |
| if not labels or len({row["item_id"] for row in labels}) != len(labels): | |
| raise ValueError("expected a non-empty set of unique labels") | |
| gold = {row["item_id"]: row for row in labels} | |
| group_ids = sorted({row["group_id"] for row in labels}) | |
| for group_id in group_ids: | |
| group_rows = [row for row in labels if row["group_id"] == group_id] | |
| if len(group_rows) != 5 or {row["state"] for row in group_rows} != set(STATES): | |
| raise ValueError(f"expected one of every state in five-view group {group_id}") | |
| is_full_primary = len(group_ids) == 1000 and len(labels) == 5000 | |
| output = { | |
| "schema_version": 1, | |
| "sample": { | |
| "groups": len(group_ids), | |
| "views": len(labels), | |
| "answerable": sum(bool(row["answerable"]) for row in labels), | |
| "unanswerable": sum(not bool(row["answerable"]) for row in labels), | |
| "state_counts": dict(Counter(row["state"] for row in labels)), | |
| }, | |
| "models": {}, | |
| "pairwise": {}, | |
| "method": { | |
| "primary": "binary answerability agreement with frozen executable-certificate labels", | |
| "invalid_outputs": "answerability error is conditional on a valid judgment; full-denominator failure counts invalid or missing judgments as failures without imputing an answerability decision", | |
| "false_decision_rates": "full-population false-accept/reject fractions are lower bounds when judgments are invalid; conditional rates use only valid judgments in the corresponding truth class", | |
| "group_success": "all five states in a source group must have the correct answerability decision", | |
| "item_interval": "Wilson score 95% interval", | |
| "cluster_interval": "10,000 group bootstrap draws, seed 20260914; all five views resampled together", | |
| "numeric": "strict rational parse and exact equality; units, explanatory strings, and rounding may remain unparsed, so this is a conservative lower bound", | |
| "blinding": "labels are loaded only by this analysis after inference; judge runners received no group, state, target, gold, or sibling-view fields", | |
| }, | |
| "limitations": [ | |
| ( | |
| "This is the complete frozen 1,000-group/5,000-view PlotQA D15 primary split, not a general VLM benchmark." | |
| if is_full_primary else | |
| f"This is a fixed {len(group_ids)}-group/{len(labels)}-view PlotQA D15 evaluation, not a general VLM benchmark." | |
| ), | |
| "Request interfaces and serving stacks are recorded per model and may differ; outcomes are not a pure architecture comparison.", | |
| "Certificate agreement measures answerability behavior on this frozen split and does not establish universal visual reliability.", | |
| ], | |
| } | |
| correctness_masks: dict[str, dict[str, bool]] = {} | |
| predictions: dict[str, dict[str, bool]] = {} | |
| for name, records in model_rows.items(): | |
| rows = {} | |
| for row in records: | |
| item_id = row.get("item_id") | |
| if item_id not in gold: | |
| raise ValueError(f"{name}: unknown item {item_id}") | |
| if item_id in rows: | |
| raise ValueError(f"{name}: duplicate item {item_id}") | |
| rows[item_id] = row | |
| invalid = [] | |
| wrong = [] | |
| false_reject = [] | |
| false_accept = [] | |
| predictions[name] = {} | |
| correctness_masks[name] = {} | |
| numeric_parseable = 0 | |
| numeric_correct = 0 | |
| durations = [] | |
| actual_models = Counter() | |
| image_interfaces = Counter() | |
| attempts = [] | |
| state_metrics = {} | |
| for item_id, label in gold.items(): | |
| row = rows.get(item_id, {}) | |
| parsed = valid_parsed(row) | |
| if parsed is None: | |
| invalid.append(item_id) | |
| correctness_masks[name][item_id] = False | |
| continue | |
| prediction = parsed["answerable"] | |
| predictions[name][item_id] = prediction | |
| correct = prediction == bool(label["answerable"]) | |
| correctness_masks[name][item_id] = correct | |
| if not correct: | |
| wrong.append(item_id) | |
| (false_reject if label["answerable"] else false_accept).append(item_id) | |
| if label["answerable"] and prediction: | |
| parsed_number = number(parsed.get("answer")) | |
| if parsed_number is not None: | |
| numeric_parseable += 1 | |
| if parsed_number == number(label["target"]): | |
| numeric_correct += 1 | |
| if isinstance(row.get("duration_seconds"), (int, float)): | |
| durations.append(float(row["duration_seconds"])) | |
| actual_models[str(row.get("model_actual") or row.get("actual_model") or "(missing)")] += 1 | |
| image_interfaces[str(row.get("image_interface") or "(missing)")] += 1 | |
| attempts.append(int(row.get("attempts") or row.get("attempt") or 1)) | |
| for state in STATES: | |
| ids = [item_id for item_id, label in gold.items() if label["state"] == state] | |
| errors = [item_id for item_id in ids if item_id in wrong] | |
| invalid_ids = [item_id for item_id in ids if item_id in invalid] | |
| state_metrics[state] = { | |
| "total": len(ids), | |
| "valid": len(ids) - len(invalid_ids), | |
| "errors": len(errors), | |
| "answerability_errors_on_valid": ratio(len(errors), len(ids) - len(invalid_ids)), | |
| "failures_including_invalid": ratio(len(errors) + len(invalid_ids), len(ids)), | |
| "error_item_ids": errors, | |
| "invalid_item_ids": invalid_ids, | |
| } | |
| group_error_counts = [] | |
| group_valid_counts = [] | |
| group_failure_counts = [] | |
| group_sizes = [] | |
| correct_groups = [] | |
| wrong_groups = [] | |
| for group_id in group_ids: | |
| ids = [item_id for item_id, label in gold.items() if label["group_id"] == group_id] | |
| valid_ids = [item_id for item_id in ids if item_id in predictions[name]] | |
| errors = sum(not correctness_masks[name][item_id] for item_id in valid_ids) | |
| failures = sum(not correctness_masks[name].get(item_id, False) for item_id in ids) | |
| group_error_counts.append(errors) | |
| group_valid_counts.append(len(valid_ids)) | |
| group_failure_counts.append(failures) | |
| group_sizes.append(len(ids)) | |
| (correct_groups if failures == 0 else wrong_groups).append(group_id) | |
| valid_count = len(labels) - len(invalid) | |
| error_count = len(wrong) | |
| valid_answerable = sum(bool(gold[item_id]["answerable"]) for item_id in predictions[name]) | |
| valid_unanswerable = valid_count - valid_answerable | |
| output["models"][name] = { | |
| "attempted_items": len(rows), | |
| "valid_judgments": valid_count, | |
| "invalid_or_missing": len(invalid), | |
| "answerability_errors": ratio(error_count, valid_count), | |
| "answerability_error_wilson_95": wilson_interval(error_count, valid_count), | |
| "answerability_error_group_bootstrap_95": clustered_interval(group_error_counts, group_valid_counts), | |
| "error_fraction_if_invalid_count_wrong": ratio(error_count + len(invalid), len(labels)), | |
| "failure_group_bootstrap_95": clustered_interval(group_failure_counts, group_sizes), | |
| "answerability_error_bounds_full_denominator": [ | |
| error_count / len(labels), (error_count + len(invalid)) / len(labels) | |
| ], | |
| "false_reject_answerable": ratio(len(false_reject), sum(row["answerable"] for row in labels)), | |
| "false_accept_unanswerable": ratio(len(false_accept), sum(not row["answerable"] for row in labels)), | |
| "false_reject_on_valid_answerable": ratio(len(false_reject), valid_answerable), | |
| "false_accept_on_valid_unanswerable": ratio(len(false_accept), valid_unanswerable), | |
| "five_view_groups_all_correct": ratio(len(correct_groups), len(group_ids)), | |
| "answer_correct_on_all_answerable_strict_lower_bound": ratio(numeric_correct, sum(row["answerable"] for row in labels)), | |
| "numeric_parseable_on_answerable": ratio(numeric_parseable, sum(row["answerable"] for row in labels)), | |
| "numeric_correct_among_parseable": ratio(numeric_correct, numeric_parseable), | |
| "state_counts": state_metrics, | |
| "wrong_item_ids": wrong, | |
| "wrong_items": [{ | |
| "item_id": item_id, | |
| "group_id": gold[item_id]["group_id"], | |
| "state": gold[item_id]["state"], | |
| "question": rows[item_id].get("question"), | |
| "predicted_answerable": rows[item_id]["parsed"]["answerable"], | |
| "predicted_answer": rows[item_id]["parsed"].get("answer"), | |
| "reason": rows[item_id]["parsed"].get("reason"), | |
| } for item_id in wrong], | |
| "wrong_group_ids": wrong_groups, | |
| "invalid_item_ids": invalid, | |
| "actual_model_counts": dict(actual_models), | |
| "image_interface_counts": dict(image_interfaces), | |
| "retried_items": sum(value > 1 for value in attempts), | |
| "maximum_attempt_number": max(attempts, default=None), | |
| "mean_seconds_per_completed_item": sum(durations) / len(durations) if durations else None, | |
| "total_seconds_summed_across_requests": sum(durations), | |
| } | |
| names = list(model_rows) | |
| for left_index, left in enumerate(names): | |
| for right in names[left_index + 1 :]: | |
| both = sorted(set(predictions[left]) & set(predictions[right])) | |
| disagreement = [item_id for item_id in both if predictions[left][item_id] != predictions[right][item_id]] | |
| both_wrong = [item_id for item_id in both if not correctness_masks[left][item_id] and not correctness_masks[right][item_id]] | |
| left_only_wrong = [item_id for item_id in both if not correctness_masks[left][item_id] and correctness_masks[right][item_id]] | |
| right_only_wrong = [item_id for item_id in both if correctness_masks[left][item_id] and not correctness_masks[right][item_id]] | |
| output["pairwise"][f"{left}__{right}"] = { | |
| "models": [left, right], | |
| "both_valid": len(both), | |
| "answerability_disagreement": ratio(len(disagreement), len(both)), | |
| "both_wrong": len(both_wrong), | |
| "left_only_wrong": len(left_only_wrong), | |
| "right_only_wrong": len(right_only_wrong), | |
| "disagreement_item_ids": disagreement, | |
| "both_wrong_item_ids": both_wrong, | |
| } | |
| return output | |
| def load_jsonl(path: Path) -> list[dict]: | |
| return [json.loads(line) for line in path.read_text().splitlines() if line.strip()] | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--labels", type=Path, required=True) | |
| parser.add_argument("--model", action="append", required=True, help="name=results.jsonl") | |
| parser.add_argument("--output", type=Path, required=True) | |
| args = parser.parse_args() | |
| rows = {} | |
| for value in args.model: | |
| name, filename = value.split("=", 1) | |
| if name in rows: | |
| raise ValueError(f"duplicate model name: {name}") | |
| rows[name] = load_jsonl(Path(filename)) | |
| result = analyze(json.loads(args.labels.read_text()), rows) | |
| 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({name: { | |
| "errors": row["answerability_errors"], | |
| "groups_all_correct": row["five_view_groups_all_correct"], | |
| "strict_numeric_lower_bound": row["answer_correct_on_all_answerable_strict_lower_bound"], | |
| } for name, row in result["models"].items()})) | |
| if __name__ == "__main__": | |
| main() | |