Datasets:
File size: 15,124 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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | #!/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()
|