"""Compute Metrics between model scores and human-labeled scores. Ground truth is loaded from the point-wise sampled file, where each item exposes top-level fields ``if_score`` / ``vq_score`` / ``wc_score`` keyed by ``video_name``. """ import argparse import json from pathlib import Path SCRIPT_DIR = Path(__file__).resolve().parent PROJECT_ROOT = SCRIPT_DIR.parent DEFAULT_RESULTS_DIR = PROJECT_ROOT / "results" DEFAULT_GT_FILE = PROJECT_ROOT / "data" / "firm-video-bench.json" MODEL_FILES = { "gemini-3.1-pro": "gemini31pro_scores.json", "gpt5": "gpt5_scores.json", "seed-2.0-lite": "seed20lite_scores.json", "qwen3vl-8b": "qwen3vl8b_scores.json", "qwen3vl-30b": "qwen3vl30ba3b_scores.json", "qwen3vl-235b": "qwen3vl235ba22b_scores.json", "internvl3-8b": "internvl3-8b_scores.json", "internvl3-38b": "internvl3-38b_scores.json", "firm-video-8b-qwen3vl": "firm-video-qwen3vl_scores.json", "firm-video-8b-internvl3": "firm-video-internvl3_scores.json" } # model dimension -> ground-truth key in GT_FILE DIM_MAP = { "instruction_following": "if_score", "visual_quality": "vq_score", "world_consistency": "wc_score", } def load(path): with open(path, "r", encoding="utf-8") as f: return json.load(f) def load_gt(path): """Return dict: video_name -> {if_score, vq_score, wc_score}.""" gt = {} for item in load(path): key = item.get("video_name") if not key: continue gt[key] = {k: item.get(k) for k in DIM_MAP.values()} return gt def _std(abs_errors): """绝对误差 |pred - human| 的样本标准差(围绕 MAE 的波动,ddof=1)。""" m = len(abs_errors) if m <= 1: return None mean_err = sum(abs_errors) / m return (sum((e - mean_err) ** 2 for e in abs_errors) / (m - 1)) ** 0.5 def _accuracy(abs_errors): """预测与 human GT 完全相等的比例。""" if not abs_errors: return None return sum(1 for e in abs_errors if e == 0) / len(abs_errors) def _relaxed_accuracy(abs_errors): """预测与 human GT 相差不超过 1 的比例。""" if not abs_errors: return None return sum(1 for e in abs_errors if e <= 1) / len(abs_errors) def _rankdata(values): """返回带 ties 平均秩(1-based)的秩数组。""" order = sorted(range(len(values)), key=lambda i: values[i]) ranks = [0.0] * len(values) i = 0 while i < len(values): j = i while j + 1 < len(values) and values[order[j + 1]] == values[order[i]]: j += 1 avg_rank = (i + j) / 2.0 + 1.0 for k in range(i, j + 1): ranks[order[k]] = avg_rank i = j + 1 return ranks def _spearman(pairs): """Spearman 秩相关系数(对秩做 Pearson,含 ties 处理)。pairs: [(pred, human)]。""" n = len(pairs) if n < 2: return None xs = [p for p, _ in pairs] ys = [h for _, h in pairs] rx = _rankdata(xs) ry = _rankdata(ys) mean_rx = sum(rx) / n mean_ry = sum(ry) / n cov = sum((a - mean_rx) * (b - mean_ry) for a, b in zip(rx, ry)) var_x = sum((a - mean_rx) ** 2 for a in rx) var_y = sum((b - mean_ry) ** 2 for b in ry) denom = (var_x * var_y) ** 0.5 if denom == 0: return None return cov / denom def compute_mae(items, gt): """Return per-dimension (MAE, std, N), overall (MAE, std) and extra metrics. extra 部分返回 per-dimension 的 (accuracy, relaxed_accuracy, spearman), overall 仅返回 (accuracy, relaxed_accuracy)。 """ diffs = {dim: [] for dim in DIM_MAP} pairs = {dim: [] for dim in DIM_MAP} missing = 0 for item in items: key = item.get("video_name") human_scores = gt.get(key) if human_scores is None: missing += 1 continue dims = { d["dimension"]: d.get("score") for d in item.get("scoring", {}).get("dimensions", []) } for model_dim, gt_key in DIM_MAP.items(): human = human_scores.get(gt_key) pred = dims.get(model_dim) if human is None or pred is None: missing += 1 continue try: pv = float(pred) hv = float(human) except (TypeError, ValueError): missing += 1 continue diffs[model_dim].append(abs(pv - hv)) pairs[model_dim].append((pv, hv)) per_dim = { dim: (sum(v) / len(v) if v else None, _std(v), len(v)) for dim, v in diffs.items() } all_diffs = [x for v in diffs.values() for x in v] overall = sum(all_diffs) / len(all_diffs) if all_diffs else None overall_std = _std(all_diffs) per_dim_extra = { dim: (_accuracy(diffs[dim]), _relaxed_accuracy(diffs[dim]), _spearman(pairs[dim])) for dim in DIM_MAP } overall_extra = ( _accuracy(all_diffs), _relaxed_accuracy(all_diffs), ) return per_dim, overall, overall_std, per_dim_extra, overall_extra, missing, len(items) def parse_args(): parser = argparse.ArgumentParser( description="Compute metrics between model scores and human-labeled scores." ) parser.add_argument( "--gt_file", type=str, default=str(DEFAULT_GT_FILE), help="Ground-truth JSON file with if_score/vq_score/wc_score fields.", ) parser.add_argument( "--results_dir", type=str, default=str(DEFAULT_RESULTS_DIR), help="Directory containing model score JSON files.", ) return parser.parse_args() def main(): args = parse_args() gt_file = Path(args.gt_file).expanduser() results_dir = Path(args.results_dir).expanduser() if not gt_file.exists(): print(f"GT file not found: {gt_file}") return gt = load_gt(gt_file) print(f"Loaded {len(gt)} GT entries from {gt_file}") fmt = lambda x: f"{x:.4f}" if x is not None else " N/A " header = ( f"{'Model':<12} {'N':>4} " f"{'IF':>10} {'IF_std':>10} " f"{'PQ':>10} {'PQ_std':>10} " f"{'WC':>10} {'WC_std':>10} " f"{'Overall':>10} {'Ovr_std':>10} {'missing':>8}" ) print(header) print("-" * len(header)) # 收集每个模型的额外指标 extra_rows = [] for name, fname in MODEL_FILES.items(): path = results_dir / fname if not path.exists(): print(f"{name}: file not found: {path}") continue items = load(path) (per_dim, overall, overall_std, per_dim_extra, overall_extra, missing, n) = compute_mae(items, gt) if_mae, if_std, _ = per_dim["instruction_following"] vq_mae, vq_std, _ = per_dim["visual_quality"] wc_mae, wc_std, _ = per_dim["world_consistency"] print( f"{name:<12} {n:>4} " f"{fmt(if_mae):>10} {fmt(if_std):>10} " f"{fmt(vq_mae):>10} {fmt(vq_std):>10} " f"{fmt(wc_mae):>10} {fmt(wc_std):>10} " f"{fmt(overall):>10} {fmt(overall_std):>10} {missing:>8}" ) extra_rows.append((name, per_dim_extra, overall_extra)) # ---- 额外指标:accuracy / relaxed accuracy / spearman ---- if extra_rows: print("\n== Extra metrics: Accuracy(=) / Relaxed(|d|<=1) / Spearman ==") extra_header = ( f"{'Model':<12} " f"{'IF_acc':>8} {'IF_racc':>8} {'IF_spr':>8} " f"{'PQ_acc':>8} {'PQ_racc':>8} {'PQ_spr':>8} " f"{'WC_acc':>8} {'WC_racc':>8} {'WC_spr':>8} " f"{'Ovr_acc':>8} {'Ovr_racc':>8}" ) print(extra_header) print("-" * len(extra_header)) for name, per_dim_extra, overall_extra in extra_rows: if_acc, if_racc, if_spr = per_dim_extra["instruction_following"] vq_acc, vq_racc, vq_spr = per_dim_extra["visual_quality"] wc_acc, wc_racc, wc_spr = per_dim_extra["world_consistency"] ovr_acc, ovr_racc = overall_extra print( f"{name:<12} " f"{fmt(if_acc):>8} {fmt(if_racc):>8} {fmt(if_spr):>8} " f"{fmt(vq_acc):>8} {fmt(vq_racc):>8} {fmt(vq_spr):>8} " f"{fmt(wc_acc):>8} {fmt(wc_racc):>8} {fmt(wc_spr):>8} " f"{fmt(ovr_acc):>8} {fmt(ovr_racc):>8}" ) print("\nDimension mapping: instruction_following<->if_score, " "perceptual quality (PQ; input: visual_quality<->vq_score), " "world_coherence<->wc_score") print("std = 模型打分绝对误差|pred - human|的样本标准差(ddof=1)") print("acc = 完全相等准确率; racc = 相差<=1准确率; spr = Spearman秩相关系数") if __name__ == "__main__": main()