File size: 8,675 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
"""Analyze the frozen CLEVR/GQA views without assuming five-state groups."""
import argparse
import json
import unicodedata
from collections import Counter, defaultdict
from fractions import Fraction
from pathlib import Path

import numpy as np
from analyze_visual_judges import ratio, valid_parsed

STATES = {"clevr": {"FULL", "A_SAME", "A_CHANGED", "U_MISSING"},
          "gqa": {"FULL", "A_SAME", "U_MISSING"}}


def strict_answer_match(answer, target):
    if answer is None or target is None:
        return False
    try:
        return Fraction(str(answer).strip()) == Fraction(str(target).strip())
    except (ValueError, ZeroDivisionError):
        pass
    normalize = lambda value: " ".join(unicodedata.normalize("NFKC", str(value)).lower().split())
    return normalize(answer) == normalize(target)


def validate_inputs(labels, items):
    gold = {r["item_id"]: r for r in labels}
    blind = {r["item_id"]: r for r in items}
    expected = {f"cross-{i:05d}" for i in range(7000)}
    if len(labels) != 7000 or len(items) != 7000 or set(gold) != expected or set(blind) != expected:
        raise ValueError("expected the same 7,000 distinct frozen input IDs")
    groups = defaultdict(list)
    for row in labels:
        groups[(row["source"], row["group_id"])].append(row)
        if type(row["answerable"]) is not bool or row["answerable"] != (not row["state"].startswith("U_")):
            raise ValueError("inconsistent frozen answerability label")
    if Counter(source for source, _ in groups) != {"clevr": 1000, "gqa": 1000}:
        raise ValueError("expected 1,000 groups from each source")
    for (source, _), rows in groups.items():
        if len(rows) != len(STATES[source]) or {r["state"] for r in rows} != STATES[source]:
            raise ValueError("source-specific state coverage mismatch")
    return gold, blind


def group_interval(numerators, denominators, draws=10000):
    if not draws or not sum(denominators):
        return None
    rng = np.random.default_rng(20260915)
    n, d = np.asarray(numerators), np.asarray(denominators)
    values = []
    for start in range(0, draws, 250):
        indices = rng.integers(0, len(n), size=(min(250, draws-start), len(n)))
        sums = d[indices].sum(axis=1)
        valid = sums > 0
        values.extend((n[indices].sum(axis=1)[valid] / sums[valid]).tolist())
    return [float(x) for x in np.quantile(values, [.025, .975])] if values else None


def summarize(labels, records, draws=10000):
    groups = defaultdict(list)
    state_metrics = {}
    wrong, invalid, rejected, accepted = [], [], [], []
    answer_correct = 0
    for row in labels:
        item_id = row["item_id"]
        parsed = valid_parsed(records[item_id])
        bad_output = parsed is None
        error = not bad_output and parsed["answerable"] != row["answerable"]
        groups[(row["source"], row["group_id"])].append((int(error), int(bad_output)))
        if bad_output:
            invalid.append(item_id)
        elif error:
            wrong.append(item_id)
            (rejected if row["answerable"] else accepted).append(item_id)
        if parsed and row["answerable"] and parsed["answerable"]:
            answer_correct += strict_answer_match(parsed["answer"], row["target"])
    for state in sorted({r["state"] for r in labels}):
        ids = {r["item_id"] for r in labels if r["state"] == state}
        n_bad = len(ids & set(invalid))
        n_wrong = len(ids & set(wrong))
        state_metrics[state] = dict(total=len(ids), invalid=n_bad,
            errors_on_valid=ratio(n_wrong, len(ids)-n_bad),
            failures_full_denominator=ratio(n_wrong+n_bad, len(ids)))
    group_errors = [sum(x[0] for x in rows) for rows in groups.values()]
    group_bad = [sum(x[1] for x in rows) for rows in groups.values()]
    group_sizes = [len(rows) for rows in groups.values()]
    answerable = sum(r["answerable"] for r in labels)
    valid_answerable = sum(r["answerable"] and r["item_id"] not in set(invalid) for r in labels)
    valid_unanswerable = len(labels)-len(invalid)-valid_answerable
    return dict(views=len(labels), groups=len(groups), valid_judgments=len(labels)-len(invalid),
        invalid_outputs=len(invalid), answerability_errors=ratio(len(wrong),len(labels)-len(invalid)),
        failures_full_denominator=ratio(len(wrong)+len(invalid),len(labels)),
        answerability_error_group_bootstrap_95=group_interval(group_errors,
            [n-b for n,b in zip(group_sizes,group_bad)],draws),
        failure_group_bootstrap_95=group_interval(
            [e+b for e,b in zip(group_errors,group_bad)],group_sizes,draws),
        false_reject_on_valid_answerable=ratio(len(rejected),valid_answerable),
        false_accept_on_valid_unanswerable=ratio(len(accepted),valid_unanswerable),
        groups_all_states_correct=ratio(sum(e+b==0 for e,b in zip(group_errors,group_bad)),len(groups)),
        answer_correct_on_all_answerable_strict_lower_bound=ratio(answer_correct,answerable),
        states=state_metrics, wrong_item_ids=wrong, invalid_item_ids=invalid)


def analyze(labels, items, model_rows, draws=10000):
    gold, blind = validate_inputs(labels, items)
    models = {}
    for name, rows in model_rows.items():
        records = {}
        for row in rows:
            item_id = row.get("item_id")
            if item_id not in gold or item_id in records:
                raise ValueError(f"{name}: unknown or duplicate output ID")
            if row.get("question") != blind[item_id]["question"]:
                raise ValueError(f"{name}: output question differs from frozen input")
            if row.get("status") != "completed" and not (
                    row.get("status") == "invalid_schema" and row.get("terminal_invalid") is True):
                raise ValueError(f"{name}: unfinished request {item_id}")
            records[item_id] = row
        if set(records) != set(gold):
            raise ValueError(f"{name}: incomplete output coverage")
        model = dict(actual_model_counts=dict(Counter(r.get("model_actual") or r.get("actual_model") for r in rows)),
                     overall=summarize(labels, records, draws), by_source={})
        for source in STATES:
            model["by_source"][source] = summarize(
                [r for r in labels if r["source"] == source], records, draws)
        models[name] = model
    return dict(schema_version=1, sample=dict(views=7000, groups=2000,
        source_views=dict(Counter(r["source"] for r in labels))), models=models,
        method=dict(primary="agreement with frozen source-derived answerability labels",
        output_failures="invalid outputs count as failures on the full denominator and are excluded from conditional decision-error rates",
        group_success="all available states in each CLEVR four-view or GQA three-view group must be correct",
        intervals="10,000 group-level bootstrap draws, seed 20260915; source-specific intervals keep sibling views together",
        answers="strict rational equality for numeric answers; otherwise Unicode normalization, case and whitespace normalization followed by exact match",
        new_mask_controls_included=False),
        limitations=["GQA labels derive from scene annotations and do not establish that every visual clue in the photograph is exhausted.",
                     "Existing CLEVR/GQA validation views were reused; no new matched-mask control was performed.",
                     "Serving stacks differ between bridge APIs and Simflow vLLM."])


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--labels", type=Path, required=True)
    parser.add_argument("--manifest", type=Path, required=True)
    parser.add_argument("--model", action="append", required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    read_rows = lambda p: [json.loads(line) for line in Path(p).read_text().splitlines() if line.strip()]
    rows = {}
    for entry in args.model:
        name, filename = entry.split("=",1)
        if name in rows:
            raise ValueError("duplicate model key")
        rows[name] = read_rows(filename)
    result = analyze(json.loads(args.labels.read_text()), read_rows(args.manifest), 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:{s:{"errors":v["answerability_errors"],
        "groups_correct":v["groups_all_states_correct"]} for s,v in m["by_source"].items()}
        for name,m in result["models"].items()}))


if __name__ == "__main__":
    main()