File size: 7,788 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
#!/usr/bin/env python3
"""Connect archived chart witnesses to the frozen evaluation, without inference."""
import argparse
from collections import defaultdict
import gzip
import json
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

from analyze_visual_judges import number, valid_parsed
from analyze_crossdomain_paper import MODELS, STATES
from build_crossdomain_paper_assets import NAMES


def build(inputs, analysis_path, output, proofs=None):
    output.mkdir(parents=True, exist_ok=True)
    saved = json.loads(analysis_path.read_text())["domains"]["plotqa"]["models"]
    labels = json.loads((inputs / "plotqa/labels.json").read_text())
    manifest = {r["item_id"]: r for r in map(json.loads, (inputs / "plotqa/manifest.jsonl").read_text().splitlines())}
    groups = defaultdict(dict)
    for row in labels:
        assert row["state"] not in groups[row["group_id"]]
        groups[row["group_id"]][row["state"]] = row
    assert len(labels) == len(manifest) == 5000 and len(groups) == 1000
    assert all(set(g) == set(STATES["plotqa"]) for g in groups.values())
    join = {"status": "not repeated; archived witness join required separately"}
    if proofs is not None:
        seen = set()
        with gzip.open(proofs, "rt") as handle:
            for proof in map(json.loads, handle):
                gid = proof["group_id"]
                assert gid not in seen and gid in groups
                seen.add(gid)
                for row in groups[gid].values():
                    assert proof["question"] == manifest[row["item_id"]]["question"]
                    assert proof["source_native_id"] == row["source_native_id"]
        assert seen == set(groups)
        join = {"status": "passed", "unique_witness_groups": len(seen),
                "evaluated_groups": len(groups), "question_and_source_joins": len(labels),
                "checks": "exact group IDs, source native IDs, and question strings; no digest validation",
                "scope": "identity join only; semantic and pixel replay reported separately"}
        (output / "witness-cohort-join.json").write_text(json.dumps(join, indent=2) + "\n")

    result = {"status": "passed", "inference_calls": 0,
              "analysis": "post-hoc disjoint group decomposition on existing chart responses",
              "groups": 1000, "views_per_configuration": 5000, "models": {}}
    table = [r"\begin{tabular}{@{}lrrrrr@{}}", r"\toprule",
             r"Configuration & $J_5\uparrow$ & $B_5\uparrow$ & $E_A\downarrow$ & $E_M\downarrow$ & $E_I\downarrow$ \\",
             r"\midrule"]
    partitions = []
    for model in MODELS:
        with gzip.open(inputs / "plotqa" / (model + ".jsonl.gz"), "rt") as handle:
            rows = list(map(json.loads, handle))
        records = {r["item_id"]: r for r in rows}
        assert len(rows) == len(records) == 5000 and set(records) == set(manifest)
        counts = np.zeros(4, dtype=int)
        ids = [[], [], [], []]
        for gid, group in sorted(groups.items()):
            failed, answers = {}, []
            for state, label in group.items():
                rec = records[label["item_id"]]
                assert rec["question"] == manifest[label["item_id"]]["question"]
                parsed = valid_parsed(rec)
                failed[state] = parsed is None or parsed["answerable"] != label["answerable"]
                if label["answerable"]:
                    value = number(parsed["answer"]) if parsed and parsed["answerable"] else None
                    target = number(label["target"])
                    answers.append(value is not None and target is not None and value == target)
            if failed["U_MISSING"]:
                category = 2
            elif any(failed.values()):
                category = 3
            elif all(answers):
                category = 0
            else:
                category = 1
            counts[category] += 1
            ids[category].append(gid)
        old = saved[model]
        assert counts.sum() == 1000
        assert counts[0] == old["counts"]["joint_groups_correct"]
        assert counts[0] + counts[1] == old["counts"]["groups_correct"]
        assert counts[2] == old["states"]["U_MISSING"]["failures"]
        assert counts[2] + counts[3] == 1000 - old["counts"]["groups_correct"]
        partitions.append(counts)
        names = ["all_decisions_and_supported_answers_correct", "all_decisions_correct_answer_mismatch",
                 "missing_information_decision_failed", "other_decision_failed_missing_correct"]
        result["models"][model] = {"counts": dict(zip(names, counts.tolist())),
                                   "group_ids": dict(zip(names, ids)),
                                   "missing_state_invalid": old["states"]["U_MISSING"]["invalid"]}
        values = [old["counts"]["joint_groups_correct"] / 10,
                  old["counts"]["groups_correct"] / 10,
                  100 * old["metrics"]["answerable_failure"],
                  old["states"]["U_MISSING"]["failures"] / 10,
                  old["states"]["U_INVALID"]["failures"] / 10]
        table.append(NAMES[model] + " & " + " & ".join(f"{v:.2f}" for v in values) + r" \\")
    table.extend([r"\bottomrule", r"\end{tabular}"])
    (output / "chart_table.tex").write_text("\n".join(table) + "\n")
    (output / "chart-diagnostics.json").write_text(json.dumps(result, indent=2) + "\n")

    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11.5, "pdf.fonttype": 42})
    fig, ax = plt.subplots(figsize=(7.3, 3.5))
    colors = ["#216b87", "#83b9c5", "#b85030", "#ddd4c8"]
    legend = ["Decisions + answers correct", "Decisions correct; answer mismatch",
              "Missing-information decision fails", "Other decision fails; M correct"]
    values = np.array(partitions)
    left = np.zeros(6)
    for j, color in enumerate(colors):
        bars = ax.barh(np.arange(6), values[:, j], left=left, height=.64, color=color,
                       edgecolor="white", linewidth=.65, label=legend[j])
        for bar, count in zip(bars, values[:, j]):
            if count >= 30:
                ax.text(bar.get_x()+bar.get_width()/2, bar.get_y()+bar.get_height()/2,
                        str(count), ha="center", va="center", fontsize=9.5 if count < 45 else 11.5,
                        color="white" if j in (0, 2) else "#172b35")
        left += values[:, j]
    ax.set_yticks(np.arange(6), [NAMES[m] for m in MODELS])
    ax.invert_yaxis()
    ax.set_xlim(0, 1000)
    ax.set_xticks(np.arange(0, 1001, 200))
    ax.set_xlabel("Chart question groups (1,000 per configuration)", fontsize=11.5)
    ax.spines[["top", "right", "left"]].set_visible(False)
    ax.tick_params(axis="y", length=0)
    ax.grid(axis="x", color="#e4e7eb", linewidth=.6)
    ax.set_axisbelow(True)
    ax.legend(loc="lower left", bbox_to_anchor=(-.30, 1.015), ncol=2,
              frameon=False, fontsize=11.0, columnspacing=1.0, handlelength=1.3)
    fig.subplots_adjust(left=.25, right=.99, top=.80, bottom=.16)
    for ext in ("pdf", "png"):
        fig.savefig(output / ("chart_diagnosis." + ext), dpi=220, bbox_inches="tight", pad_inches=.06)
    plt.close(fig)
    return {"status": "passed", "models": len(MODELS), "responses_checked": 30000,
            "disjoint_partitions": 6, "witness_join": join, "inference_calls": 0}


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--inputs", type=Path, required=True)
    p.add_argument("--analysis", type=Path, required=True)
    p.add_argument("--output", type=Path, required=True)
    p.add_argument("--proofs", type=Path)
    a = p.parse_args()
    print(json.dumps(build(a.inputs, a.analysis, a.output, a.proofs)))