#!/usr/bin/env python3 """MR-Bench-H v2.0.1 scorer (Python standard library + numpy only). Predictions: JSONL (optionally .gz), one object per (item, view). Required: "uid". The prediction is read from the first available of "polarity" -1 / 0 / 1 (0 = neutral: always wrong, reported as invalid) "score" real number (e.g. a regression output on the source's label scale) -> its sign "pred" alias of "score" "answer" free text, parsed like the MLLM protocol: first of positive / negative / neutral Optional: "view" (default "full"), "model" (default: the file name), "seed". Items without a prediction count as wrong and invalid (coverage is printed). python tools/evaluate.py --pred my_model.jsonl # core tier, all sources python tools/evaluate.py --pred run_s1.jsonl run_s2.jsonl run_s3.jsonl --average # mean/std over runs python tools/evaluate.py --pred preds.jsonl --sources mosi sims simsv2 --by source language --json out.json Metrics (per model x view): accuracy on category L (language shortcut), V (non-verbal shortcut) and control items, Acc-conflict on L+V, ShortErr = fraction of LS items answered with the fixed misleading text polarity, distractor_error_all = former pooled L+V distractor error. On NS, text following is not an error. ShortErr-L / ShortErr-V are retained aliases for category distractor rates. Invalid answers are not text following. """ import argparse import gzip import json import math import os import re import sys from collections import OrderedDict, defaultdict import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) PROTOCOL = ("MR-Bench-H v2.0.1: 900 human-reviewed items (620 LS / 280 NS). " "MLLM protocol: zero-shot, greedy decoding (max 6 new tokens), binary prompt in README.md; answers parsed with the " "first match of positive|negative; answers without a binary label count as wrong. Fusion models: " "sign of the neutral-centered regression output; the paper uses all seven sources, pooled per seed, then three-seed mean/std " "(--average, population std with ddof=0). JSON metric names L/V correspond to LS/NS.") VIEW_ORDER = ["full", "muted+transcript", "transcript", "nonverbal", "audio", "muted"] METRICS = ["acc_L", "acc_V", "acc_control", "acc_conflict", "shorterr", "shorterr_L", "shorterr_V", "distractor_error_all", "invalid", "invalid_L", "invalid_V"] def _open(path): return gzip.open(path, "rt", encoding="utf-8") if path.endswith(".gz") else open(path, encoding="utf-8") def load_items(path, sources=None, validated_only=False, panel_only=False): """panel_only: keep the items that passed the model-independent text-reader panel (stage 2b), i.e. the benchmark set.""" items = OrderedDict() with _open(path) as f: for line in f: r = json.loads(line) if sources and r["source"] not in sources: continue if panel_only and not ((r.get("stage2") or {}).get("panel") or {}).get("pass"): continue if r["uid"] in items: raise ValueError(f"Duplicate item UID: {r['uid']}") items[r["uid"]] = r if validated_only: done = {r["source"] for r in items.values() if r.get("validated") is not None} if not done: sys.exit("--validated_only: no human validation has been merged into this items file yet") # kept L/V items + the controls of the sources whose validation has been merged items = OrderedDict((u, r) for u, r in items.items() if r.get("validated") is True or (r["category"] == "control" and r["source"] in done)) return items def parse_answer(text): if not isinstance(text, str): return None m = re.search(r"\b(positive|negative)\b", text.strip().lower()) return {"positive": 1, "negative": -1}[m.group(1)] if m else None def to_polarity(r, band=0.0): if r.get("polarity") is not None: p = r["polarity"] return int(p) if not isinstance(p, bool) and p in (-1, 0, 1) else None for k in ("score", "pred"): if r.get(k) is not None: try: x = float(r[k]) except (TypeError, ValueError): return None if isinstance(r[k], bool) or not math.isfinite(x): return None return 0 if abs(x) <= band else (1 if x > 0 else -1) if "answer" in r: return parse_answer(r["answer"]) return None def load_predictions(path, band=0.0, views=None, models=None): """-> {(model, view): {uid: polarity}}; duplicate predictions are rejected.""" name = os.path.basename(path) for ext in (".gz", ".jsonl", ".json"): name = name[: -len(ext)] if name.endswith(ext) else name groups = defaultdict(dict) with _open(path) as f: for line in f: if not line.strip(): continue r = json.loads(line) key = (r.get("model", name), r.get("view", "full")) if (views and key[1] not in views) or (models and key[0] not in models): continue if r["uid"] in groups[key]: raise ValueError(f"Duplicate prediction for {r['uid']}, model/view {key}; put each seed in a separate file") groups[key][r["uid"]] = to_polarity(r, band) if not groups and not views and not models: groups[(name, "full")] = {} return groups def score(items, preds): """items: {uid: item}; preds: {uid: polarity or None}. Returns a dict of metrics (fractions) and counts.""" acc = defaultdict(list) short = defaultdict(list) invalid, covered = [], 0 invalid_by_category = defaultdict(list) for uid, it in items.items(): p = preds.get(uid) covered += uid in preds c = it["category"] acc[c].append(p == it["label_polarity"]) if c in ("L", "V"): acc["conflict"].append(p == it["label_polarity"]) short[c].append(p == it["distractor_polarity"]) short["all"].append(p == it["distractor_polarity"]) invalid.append(p not in (-1, 1)) invalid_by_category[c].append(p not in (-1, 1)) m = lambda v: float(np.mean(v)) if len(v) else None return {"n": len(items), "n_L": len(acc["L"]), "n_V": len(acc["V"]), "n_control": len(acc["control"]), "coverage": covered / len(items) if items else None, "acc_L": m(acc["L"]), "acc_V": m(acc["V"]), "acc_control": m(acc["control"]), "acc_conflict": m(acc["conflict"]), "shorterr": m(short["L"]), "shorterr_L": m(short["L"]), "shorterr_V": m(short["V"]), "distractor_error_all": m(short["all"]), "invalid": m(invalid), "invalid_L": m(invalid_by_category["L"]), "invalid_V": m(invalid_by_category["V"])} def breakdown(items, preds, by): """Metrics of every subset of the items sharing the same value of field `by` (source, language, ...).""" sub = defaultdict(OrderedDict) for uid, it in items.items(): sub[it[by]][uid] = it return OrderedDict((k, score(v, preds)) for k, v in sub.items()) def evaluate_files(items, files, band=0.0, views=None, models=None, by=()): """-> list of result dicts, one per (file, model, view).""" out = [] for f in files: for (model, view), preds in load_predictions(f, band, views, models).items(): res = {"file": f, "model": model, "view": view, "overall": score(items, preds)} for b in by: res[b] = breakdown(items, preds, b) out.append(res) return out def average(results): """Mean and population std of per-seed pooled metrics sharing (model, view).""" groups = OrderedDict() for r in results: groups.setdefault((r["model"], r["view"]), []).append(r) out = [] for (model, view), rs in groups.items(): if len(rs) != 3 or len({os.path.realpath(r["file"]) for r in rs}) != 3: raise ValueError("The paper protocol requires three distinct seed files per model/view; combine sources within each seed and use matching model/view names") def agg(dicts): count_keys = ("n", "n_L", "n_V", "n_control") if any(any(d[k] != dicts[0][k] for k in count_keys) for d in dicts): raise ValueError("Seed results must use the same evaluation population") o = {k: dicts[0][k] for k in count_keys} o["runs"] = len(dicts) for k in METRICS + ["coverage"]: v = [d[k] for d in dicts if d[k] is not None] o[k] = float(np.mean(v)) if v else None o[k + "_std"] = float(np.std(v)) if v else None return o a = {"file": [r["file"] for r in rs], "model": model, "view": view, "aggregation": "per_seed_mean_std", "std_ddof": 0, "overall": agg([r["overall"] for r in rs])} for b in rs[0]: if b in ("file", "model", "view", "overall"): continue keys = rs[0][b].keys() a[b] = OrderedDict((k, agg([r[b][k] for r in rs if k in r[b]])) for k in keys) out.append(a) return out def pct(x, std=None): if x is None: return "-" return f"{100 * x:.1f}" + (f" ± {100 * std:.1f}" if std is not None else "") def view_rank(v): return VIEW_ORDER.index(v) if v in VIEW_ORDER else len(VIEW_ORDER) def print_tables(results, by=(), show_std=False): cols = [("acc_L", "Acc-LS"), ("acc_V", "Acc-NS"), ("acc_control", "Acc-ctrl"), ("acc_conflict", "Acc-all"), ("shorterr", "ShortErr-LS"), ("distractor_error_all", "DistrErr-all"), ("shorterr_V", "DistrErr-NS"), ("invalid_L", "Invalid-LS"), ("invalid", "invalid")] results = sorted(results, key=lambda r: (r["model"], view_rank(r["view"]))) print("| model | view | n | coverage | " + " | ".join(c[1] for c in cols) + " |") print("|---|---|---|---|" + "---|" * len(cols)) for r in results: o = r["overall"] cells = [pct(o[k], o.get(k + "_std") if show_std else None) for k, _ in cols] print(f"| {r['model']} | {r['view']} | {o['n']} | {pct(o['coverage'])} | " + " | ".join(cells) + " |") short_cols = [("acc_L", "Acc-LS"), ("acc_V", "Acc-NS"), ("acc_control", "Acc-ctrl"), ("shorterr", "ShortErr")] for b in by: print(f"\n**by {b}**\n") print(f"| model | view | {b} | n | " + " | ".join(c[1] for c in short_cols) + " |") print("|---|---|---|---|" + "---|" * len(short_cols)) for r in results: for k, o in r[b].items(): cells = [pct(o[c], o.get(c + "_std") if show_std else None) for c, _ in short_cols] print(f"| {r['model']} | {r['view']} | {k} | {o['n']} | " + " | ".join(cells) + " |") def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--pred", nargs="+", required=True, help="prediction JSONL file(s), .gz allowed") ap.add_argument("--items", default=None, help="default: ../data/test.jsonl (900 validated items)") ap.add_argument("--sources", nargs="*", default=None, help="restrict to these sources (e.g. mosi sims simsv2)") ap.add_argument("--views", nargs="*", default=None) ap.add_argument("--models", nargs="*", default=None) ap.add_argument("--validated_only", action="store_true", help="only human-validated items (+ controls)") ap.add_argument("--all_candidates", action="store_true", help="score every candidate instead of the benchmark set (items passing the text-reader panel)") ap.add_argument("--neutral_band", type=float, default=0.0, help="|score| <= band -> neutral (wrong)") ap.add_argument("--by", nargs="*", default=["source", "language"], help="breakdowns (item fields)") ap.add_argument("--average", action="store_true", help="paper protocol: mean ± population std over exactly three distinct seed files sharing model/view; pool all sources into one file per seed") ap.add_argument("--json", default=None, help="write all metrics (fractions) to this file") args = ap.parse_args() if not math.isfinite(args.neutral_band) or args.neutral_band < 0: ap.error("--neutral_band must be finite and non-negative") items_path = args.items or os.path.join(HERE, "..", "data", "test.jsonl") items = load_items(items_path, args.sources, args.validated_only, panel_only=not args.all_candidates) if not items: sys.exit("no items selected") results = evaluate_files(items, args.pred, args.neutral_band, args.views, args.models, args.by) if args.average: results = average(results) print(f"items: {os.path.relpath(items_path)} ({len(items)} items" + (f", sources {' '.join(args.sources)}" if args.sources else "") + ")\n") print_tables(results, args.by, show_std=args.average) print(f"\n{PROTOCOL}") if args.json: json.dump(results, open(args.json, "w", encoding="utf-8"), indent=1) print(f"metrics -> {args.json}") if __name__ == "__main__": main()