import argparse import json from collections import defaultdict from pathlib import Path CONDITIONS = ("T0", "Tpos", "Tneg", "Tabs", "Tunk") def load_prompts(path): rows = {} for line in Path(path).open(encoding="utf-8"): r = json.loads(line) rows[(r["scene_id"], r["state"], r["condition"])] = r return rows def load_predictions(paths): out = {} for path in paths: for line in Path(path).open(encoding="utf-8"): r = json.loads(line) out[(r["scene_id"], r["state"], r["condition"])] = r return out def yes_of(pred): return 1 if pred.get("answer") == "yes" else 0 def acc_of(pred, truth): return 1 if yes_of(pred) == (1 if truth == "yes" else 0) else 0 def summarize(prompts, preds): scenes = sorted({(k[0], k[1]) for k in prompts}) cond_acc = {c: [0, 0] for c in CONDITIONS} cond_yes = {c: [0, 0] for c in CONDITIONS} missing = 0 for key in sorted(prompts): prompt = prompts[key] pred = preds.get(key) if pred is None: missing += 1 continue truth = prompt["truth"] cond_acc[key[2]][0] += acc_of(pred, truth) cond_acc[key[2]][1] += 1 cond_yes[key[2]][0] += yes_of(pred) cond_yes[key[2]][1] += 1 conditions = { c: { "n": cond_acc[c][1], "acc": cond_acc[c][0] / cond_acc[c][1] if cond_acc[c][1] else None, "yes_rate": cond_yes[c][0] / cond_yes[c][1] if cond_yes[c][1] else None, } for c in CONDITIONS } v_correct = {} for scene, state in scenes: key = (scene, state, "T0") if key not in preds or key not in prompts: continue v_correct[(scene, state)] = acc_of(preds[key], prompts[key]["truth"]) follow = defaultdict(list) for scene, state in scenes: key = (scene, state, "Tpos") if key not in preds or (scene, state) not in v_correct: continue follow[(scene, state)].append(yes_of(preds[key])) by_v = {0: [], 1: []} for cell, values in follow.items(): by_v[v_correct[cell]].extend(values) v = sum(v_correct.values()) / len(v_correct) if v_correct else None t_all = [y for values in follow.values() for y in values] t_rate = sum(t_all) / len(t_all) if t_all else None t_when_correct = sum(by_v[1]) / len(by_v[1]) if by_v[1] else None t_when_wrong = sum(by_v[0]) / len(by_v[0]) if by_v[0] else None fca_pos = [0, 0] fca_neg = [0, 0] ind_pos = [0, 0] teu_pos = [] teu_neg = [] for key, prompt in prompts.items(): scene, state, cond = key pred = preds.get(key) if pred is None: continue truth = prompt["truth"] if cond == "Tpos" and truth == "no": fca_pos[0] += yes_of(pred) fca_pos[1] += 1 if cond == "Tneg" and truth == "yes": fca_neg[0] += 1 - yes_of(pred) fca_neg[1] += 1 base = preds.get((scene, state, "T0")) if base is None: continue if cond == "Tpos" and truth == "no": if acc_of(base, truth) == 1: ind_pos[0] += 1 - acc_of(pred, truth) ind_pos[1] += 1 if cond in ("Tpos", "Tneg") and truth == "yes": delta = acc_of(pred, truth) - acc_of(base, truth) (teu_pos if cond == "Tpos" else teu_neg).append(delta) def ratio(pair): return pair[0] / pair[1] if pair[1] else None pair_answers = defaultdict(dict) for scene, state in scenes: key = (scene, state, "T0") pred = preds.get(key) if pred is not None: pair_answers[scene][state] = yes_of(pred) pfc_num = 0 pfc_den = 0 for scene, answers in pair_answers.items(): if "a" in answers and "b" in answers: pfc_den += 1 if answers["a"] == 1 and answers["b"] == 0: pfc_num += 1 return { "n_scenes": len(scenes), "n_prompts": len(prompts), "missing_predictions": missing, "pfc": (pfc_num / pfc_den) if pfc_den else None, "conditions": conditions, "vtk": { "v": v, "t": t_rate, "t_when_correct": t_when_correct, "t_when_wrong": t_when_wrong, "k": (t_when_correct - t_when_wrong) if (t_when_correct is not None and t_when_wrong is not None) else None, "r": (t_rate - v) if (t_rate is not None and v is not None) else None, }, "fca_Tpos": ratio(fca_pos), "fca_Tneg": ratio(fca_neg), "induced_error_Tpos": ratio(ind_pos), "teu_Tpos": sum(teu_pos) / len(teu_pos) if teu_pos else None, "teu_Tneg": sum(teu_neg) / len(teu_neg) if teu_neg else None, "matrix": matrix_metrics(prompts, scenes, preds), } def matrix_metrics(prompts, scenes, preds): v_list, t_list, k_list = [], [], [] pfc = {"Tpos": [0, 0], "Tneg": [0, 0]} for scene in sorted({s for s, _state in scenes}): cells = {} for state, z in (("a", 1), ("b", 0)): for cond, t in (("Tpos", 1), ("Tneg", 0)): pred = preds.get((scene, state, cond)) if pred is None: continue cells[(z, t)] = yes_of(pred) if len(cells) < 4: continue y11, y10 = cells[(1, 1)], cells[(1, 0)] y01, y00 = cells[(0, 1)], cells[(0, 0)] v_list.append(0.5 * ((y11 - y01) + (y10 - y00))) t_list.append(0.5 * ((y11 - y10) + (y01 - y00))) k_list.append((y11 - y10) - (y01 - y00)) for cond, t in (("Tpos", 1), ("Tneg", 0)): pfc[cond][1] += 1 if cells[(1, t)] == 1 and cells[(0, t)] == 0: pfc[cond][0] += 1 def mean(values): return sum(values) / len(values) if values else None return { "n_scene_pairs": len(v_list), "v": mean(v_list), "t": mean(t_list), "k": mean(k_list), "pfc_Tpos": (pfc["Tpos"][0] / pfc["Tpos"][1]) if pfc["Tpos"][1] else None, "pfc_Tneg": (pfc["Tneg"][0] / pfc["Tneg"][1]) if pfc["Tneg"][1] else None, } def family_of(scene_id): return scene_id.rsplit("_", 1)[0] def by_family(prompts, preds): fams = defaultdict(dict) for key, prompt in prompts.items(): fams[family_of(key[0])][key] = prompt out = {} for fam, payload in fams.items(): out[fam] = summarize(payload, preds) return out def main(): parser = argparse.ArgumentParser() parser.add_argument("--prompts", required=True) parser.add_argument("--pred-dir", required=True) parser.add_argument("--out", required=True) parser.add_argument("--model", required=True) args = parser.parse_args() prompts = load_prompts(args.prompts) paths = sorted(Path(args.pred_dir).glob(f"{args.model}_shard*.jsonl")) if not paths: raise RuntimeError(f"no prediction shards in {args.pred_dir}") preds = load_predictions(paths) report = { "model": args.model, "shards": [str(p) for p in paths], "overall": summarize(prompts, preds), "by_family": by_family(prompts, preds), } 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({k: report["overall"][k] for k in ("n_scenes", "n_prompts", "missing_predictions")}, ensure_ascii=False)) if __name__ == "__main__": main()