File size: 8,812 Bytes
6461f0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
"""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()