File size: 6,095 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
#!/usr/bin/env python3
"""Score new predictions with the paper's exact answer/abstention rules, offline."""

from __future__ import annotations

import argparse
import json
from collections import defaultdict
from pathlib import Path

from analyze_crossdomain_visual import strict_answer_match
from analyze_visual_judges import number, valid_parsed
from hf_release_common import STATES, read_rows, write_json


def score(labels, predictions):
    gold = {row["item_id"]: row for row in labels}
    records = {row["item_id"]: row for row in predictions}
    if not gold or len(gold) != len(labels):
        raise ValueError("Empty or duplicate gold IDs")
    if len(records) != len(predictions):
        raise ValueError("Duplicate prediction IDs")
    if records.keys() != gold.keys():
        raise ValueError(
            f"Prediction coverage differs: {len(gold.keys() - records.keys())} missing, {len(records.keys() - gold.keys())} unexpected"
        )
    output = {}
    for source in sorted({row["source"] for row in labels}):
        selected = [row for row in labels if row["source"] == source]
        groups = defaultdict(list)
        state_counts = {
            state: {"failures": 0, "invalid": 0, "valid_decision_errors": 0, "views": 0}
            for state in STATES[source]
        }
        counts = {
            "failures": 0,
            "invalid": 0,
            "valid_decision_errors": 0,
            "valid": 0,
            "groups_correct": 0,
            "joint_groups_correct": 0,
            "strict_answers_correct": 0,
            "answerable_views": 0,
            "unanswerable_views": 0,
        }
        for label in selected:
            record = dict(records[label["item_id"]])
            if "status" not in record:
                record = {
                    "status": "completed",
                    "parsed": {key: record.get(key) for key in ("answerable", "answer", "reason")},
                }
            elif record["status"] not in {"completed", "invalid_schema"}:
                raise ValueError(
                    "Unfinished prediction status; submit a terminal output for every item"
                )
            if record["status"] == "invalid_schema" and record.get("terminal_invalid") is not True:
                raise ValueError("invalid_schema must explicitly set terminal_invalid=true")
            parsed = valid_parsed(record)
            invalid = parsed is None
            wrong = not invalid and parsed["answerable"] != label["answerable"]
            correct = False
            if parsed and parsed["answerable"] and label["answerable"]:
                if source == "plotqa":
                    answer, target = number(parsed["answer"]), number(label["target"])
                    correct = answer is not None and target is not None and answer == target
                else:
                    correct = strict_answer_match(parsed["answer"], label["target"])
            fail = invalid or wrong
            state = state_counts[label["state"]]
            for values in (state, counts):
                values["invalid"] += int(invalid)
                values["valid_decision_errors"] += int(wrong)
                values["failures"] += int(fail)
            state["views"] += 1
            counts["valid"] += int(not invalid)
            counts["strict_answers_correct"] += int(correct)
            counts["answerable_views"] += int(label["answerable"])
            counts["unanswerable_views"] += int(not label["answerable"])
            groups[label["group_id"]].append(
                (label["state"], fail, correct or not label["answerable"])
            )
        for rows in groups.values():
            if len(rows) != len(STATES[source]) or {row[0] for row in rows} != set(STATES[source]):
                raise ValueError("Missing or repeated sibling state")
            success = all(not row[1] for row in rows)
            counts["groups_correct"] += int(success)
            counts["joint_groups_correct"] += int(success and all(row[2] for row in rows))
        answerable_failures = sum(
            row["failures"] for state, row in state_counts.items() if not state.startswith("U_")
        )
        unanswerable_failures = counts["failures"] - answerable_failures
        output[source] = {
            "counts": counts,
            "states": state_counts,
            "groups": len(groups),
            "views": len(selected),
            "metrics": {
                "decision_accuracy": 1 - counts["failures"] / len(selected),
                "group_decision_success": counts["groups_correct"] / len(groups),
                "joint_success": counts["joint_groups_correct"] / len(groups),
                "supported_answer_accuracy": counts["strict_answers_correct"]
                / counts["answerable_views"],
                "balanced_failure": (
                    answerable_failures / counts["answerable_views"]
                    + unanswerable_failures / counts["unanswerable_views"]
                )
                / 2,
            },
        }
    return {
        "status": "passed",
        "prediction_rows": len(predictions),
        "by_source": output,
        "scoring": "exact chart rational equality; strict normalized scene answers; invalid outputs fail; all siblings required",
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset", type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument("--predictions", type=Path, required=True)
    parser.add_argument("--sources", nargs="+", choices=list(STATES), default=list(STATES))
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    labels = [
        row
        for row in read_rows(args.dataset / "metadata/views.jsonl.gz")
        if row["source"] in args.sources
    ]
    result = score(labels, read_rows(args.predictions))
    write_json(args.output, result)
    print(json.dumps({"status": result["status"], "rows": result["prediction_rows"]}))


if __name__ == "__main__":
    main()