File size: 8,427 Bytes
a863f79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import json
import random
from collections import defaultdict
from pathlib import Path

SEED = 20261106


def load_rows(path):
    return [json.loads(line) for line in Path(path).open(encoding="utf-8")]


def bootstrap_ci(values, clusters, iters=2000, seed=SEED):
    rng = random.Random(seed)
    groups = defaultdict(list)
    for v, c in zip(values, clusters):
        groups[c].append(v)
    keys = list(groups)
    means = []
    for _ in range(iters):
        picked = [groups[rng.choice(keys)] for _ in keys]
        flat = [x for g in picked for x in g]
        means.append(sum(flat) / len(flat))
    means.sort()
    lo = means[int(0.025 * iters)]
    hi = means[int(0.975 * iters) - 1]
    return {"mean": sum(values) / len(values), "ci95": [lo, hi]}


def ratio(numer, denom):
    return numer / denom if denom else None


def scene_table(rows):
    table = defaultdict(dict)
    for row in rows:
        table[(row["scene_id"], row["state"])][row["condition"]] = row
    return table


def visual_text_response(rows):
    table = scene_table(rows)
    visual = []
    follow = {"Tpos": [], "Tneg": []}
    stratified = {"Tpos": {"correct": [], "wrong": []}, "Tneg": {"correct": [], "wrong": []}}
    for key, cell in table.items():
        base = cell.get("T0")
        if base is None:
            continue
        truth_yes = base["truth"] == "yes"
        base_answer_yes = base["answer"] == "yes"
        visual.append(1 if base_answer_yes == truth_yes else 0)
        for condition, claim_yes in (("Tpos", True), ("Tneg", False)):
            row = cell.get(condition)
            if row is None:
                continue
            if claim_yes == truth_yes:
                continue
            followed = 1 if (row["answer"] == "yes") == claim_yes else 0
            follow[condition].append(followed)
            bucket = "correct" if base_answer_yes == truth_yes else "wrong"
            stratified[condition][bucket].append(followed)

    def mean(values):
        return sum(values) / len(values) if values else None

    v = mean(visual)
    t_pos = mean(follow["Tpos"])
    t_neg = mean(follow["Tneg"])
    interaction = {}
    for condition in ("Tpos", "Tneg"):
        correct = mean(stratified[condition]["correct"])
        wrong = mean(stratified[condition]["wrong"])
        interaction[condition] = {
            "follow_when_visual_correct": correct,
            "follow_when_visual_wrong": wrong,
            "gap": (wrong - correct) if (correct is not None and wrong is not None) else None,
            "n_correct": len(stratified[condition]["correct"]),
            "n_wrong": len(stratified[condition]["wrong"]),
        }
    text = mean(follow["Tpos"] + follow["Tneg"])
    return {
        "V_visual_accuracy_T0": v,
        "T_text_following": text,
        "T_follow_Tpos": t_pos,
        "T_follow_Tneg": t_neg,
        "K_interaction": interaction,
        "R_text_minus_visual": (text - v) if (text is not None and v is not None) else None,
        "n_scenes": len(table),
    }


def family_breakdown(rows):
    out = {}
    for family in sorted({row["family"] for row in rows}):
        subset = [row for row in rows if row["family"] == family]
        out[family] = visual_text_response(subset)
    return out


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--pred", required=True)
    parser.add_argument("--out", required=True)
    args = parser.parse_args()
    rows = load_rows(args.pred)
    by_model = defaultdict(list)
    for row in rows:
        by_model[row["model"]].append(row)
    report = {"schema": "n_full.synth_report.v1", "models": {}, "conditions": ["T0", "Tpos", "Tneg", "Tabs", "Tunk"]}
    for model, subset in by_model.items():
        cells = defaultdict(list)
        for row in subset:
            cells[(row["condition"], row["state"])].append(row)
        model_report = {"conditions": {}, "endpoints": {}}
        for condition in report["conditions"]:
            values = []
            for state in ("a", "b"):
                for row in cells[(condition, state)]:
                    values.append(1 if row["answer"] == "yes" else 0)
            model_report["conditions"][condition] = {
                "n": len(values),
                "yes_rate": sum(values) / len(values) if values else None,
            }
        truth_rows = [r for r in subset if r["condition"] == "T0"]
        acc = []
        for row in truth_rows:
            pred = 1 if row["answer"] == "yes" else 0
            acc.append(1 if pred == row["truth"] else 0)
        clusters = [row["scene_id"] for row in truth_rows]
        model_report["accuracy_T0"] = bootstrap_ci(acc, clusters)

        def answer(row):
            return 1 if row["answer"] == "yes" else 0

        def claim(row, condition):
            if condition == "Tpos":
                return 1
            if condition == "Tneg":
                return 0
            return None

        for condition in ("Tpos", "Tneg"):
            targeted = [r for r in subset if r["condition"] == condition]
            fca_num = [r for r in targeted if r["truth"] != claim(r, condition)]
            fca_vals = [1 if answer(r) == claim(r, condition) else 0 for r in fca_num]
            model_report["endpoints"][f"fca_{condition}"] = bootstrap_ci(
                fca_vals, [r["scene_id"] for r in fca_num]
            )
        for condition in ("Tpos", "Tneg"):
            targeted = {r["scene_id"] + r["state"]: r for r in subset if r["condition"] == condition}
            base = {r["scene_id"] + r["state"]: r for r in subset if r["condition"] == "T0"}
            nums, clusters2 = [], []
            for key, row in targeted.items():
                if key not in base:
                    continue
                if claim(row, condition) == row["truth"]:
                    continue
                if answer(row) != row["truth"] and answer(base[key]) == row["truth"]:
                    nums.append(1)
                else:
                    nums.append(0)
                clusters2.append(row["scene_id"])
            model_report["endpoints"][f"induced_error_{condition}"] = bootstrap_ci(nums, clusters2)
        for condition in ("Tpos", "Tneg"):
            targeted = {r["scene_id"] + r["state"]: r for r in subset if r["condition"] == condition}
            base = {r["scene_id"] + r["state"]: r for r in subset if r["condition"] == "T0"}
            nums, clusters2 = [], []
            for key, row in targeted.items():
                if key not in base:
                    continue
                if claim(row, condition) != row["truth"]:
                    continue
                gain = answer(row) - answer(base[key])
                nums.append(gain)
                clusters2.append(row["scene_id"])
            model_report["endpoints"][f"teu_{condition}_vs_T0"] = bootstrap_ci(nums, clusters2)
        flips = []
        for scene_state in {(r["scene_id"], r["state"]) for r in subset}:
            subset_pair = {
                r["condition"]: r
                for r in subset
                if (r["scene_id"], r["state"]) == scene_state
            }
            if "T0" not in subset_pair:
                continue
            base = answer(subset_pair["T0"])
            for condition in ("Tpos", "Tneg", "Tabs", "Tunk"):
                row = subset_pair.get(condition)
                if row is None:
                    continue
                if base == 0 and answer(row) == 1:
                    flips.append((condition, 1))
                else:
                    flips.append((condition, 0))
        for condition in ("Tpos", "Tneg", "Tabs", "Tunk"):
            vals = [v for c, v in flips if c == condition]
            model_report["endpoints"][f"pfc_no_to_yes_{condition}"] = {
                "mean": sum(vals) / len(vals) if vals else None,
                "n": len(vals),
            }
        model_report["n_rows"] = len(subset)
        model_report["vtr"] = visual_text_response(subset)
        model_report["by_family"] = family_breakdown(subset)
        report["models"][model] = model_report
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"written": str(out), "models": list(report["models"])}, ensure_ascii=False))


if __name__ == "__main__":
    main()