DOVE-Bench / scripts /compare_models.py
XinNUS's picture
DOVE v1: 180 groups, 530 intervals, 1,223 human-verified probes
92186b3 verified
Raw History Blame Contribute Delete
9.71 kB
#!/usr/bin/env python3
"""Paired group-bootstrap comparisons for DOVE temporal-probe evaluation.
The independent resampling unit is one source-video/query group (``gid``),
never an individual clip or probe. All clips and probes within the group are
resampled together, preserving the dependence induced by same-video hard
distractors and shared visual context.
"""
from __future__ import annotations
import argparse
import json
import random
from collections import defaultdict
from pathlib import Path
from typing import Any
METRICS = (
"temp_cov",
"clip_complete",
"order",
"state",
"outcome",
"tec",
"not_mentioned_rate",
)
LOWER_IS_BETTER = {"not_mentioned_rate"}
def load_jsonl(path: Path) -> list[dict[str, Any]]:
with path.open(encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def parse_model(value: str) -> tuple[str, Path]:
if "=" not in value:
raise argparse.ArgumentTypeError("model must be NAME=JUDGMENTS.jsonl")
name, path = value.split("=", 1)
if not name or not path:
raise argparse.ArgumentTypeError("model must be NAME=JUDGMENTS.jsonl")
return name, Path(path)
def mean(values: list[float]) -> float:
if not values:
raise ValueError("cannot take mean of empty values")
return sum(values) / len(values)
def percentile(values: list[float], probability: float) -> float:
position = probability * (len(values) - 1)
lower = int(position)
upper = min(lower + 1, len(values) - 1)
fraction = position - lower
return values[lower] * (1.0 - fraction) + values[upper] * fraction
def load_samples(
probes_path: Path, judgments_path: Path
) -> dict[int, dict[str, list[float]]]:
probes = {row["probe_id"]: row for row in load_jsonl(probes_path)}
judgments = {
row["probe_id"]: row
for row in load_jsonl(judgments_path)
if row.get("ok", True) and row.get("probe_id") in probes
}
missing = set(probes) - set(judgments)
if missing:
raise ValueError(f"{judgments_path}: missing {len(missing)} scored probes")
per_group: dict[int, dict[str, list[float]]] = defaultdict(
lambda: defaultdict(list)
)
per_clip: dict[tuple[int, str], list[float]] = defaultdict(list)
for probe_id, probe in probes.items():
judgment = judgments[probe_id]
gid = int(probe["gid"])
correct = float(
judgment.get("state") == "answered"
and judgment.get("selected_index") == probe["answer_index"]
)
not_mentioned = float(judgment.get("state") in {"not_mentioned", "ambiguous"})
per_group[gid]["temp_cov"].append(correct)
per_group[gid][probe["axis"]].append(correct)
per_group[gid]["not_mentioned_rate"].append(not_mentioned)
per_clip[(gid, probe["qid"])].append(correct)
for (gid, _), values in per_clip.items():
per_group[gid]["clip_complete"].append(float(all(values)))
missing_axes = (set(METRICS) - {"tec"}) - {
metric for values in per_group.values() for metric in values
}
if missing_axes:
raise ValueError(f"missing metrics: {sorted(missing_axes)}")
return {gid: dict(values) for gid, values in per_group.items()}
def paired_differences(
reference: dict[int, dict[str, list[float]]],
candidate: dict[int, dict[str, list[float]]],
metric: str,
) -> dict[int, list[float]]:
if set(reference) != set(candidate):
raise ValueError("models do not cover identical groups")
differences: dict[int, list[float]] = {}
for gid in sorted(reference):
# A group need not contain every evidence axis. For an axis-specific
# statistic, resample only the groups that actually contain paired
# probes for that axis rather than treating an absent axis as a zero.
if metric not in reference[gid] or metric not in candidate[gid]:
continue
a = reference[gid][metric]
b = candidate[gid][metric]
if len(a) != len(b):
raise ValueError(f"gid {gid}: mismatched {metric} samples")
differences[gid] = [x - y for x, y in zip(a, b)]
if not differences:
raise ValueError(f"no paired values for {metric}")
return differences
def tec_score(
samples: dict[int, dict[str, list[float]]], gids: list[int]
) -> float:
"""Macro-average the three axes after resampling complete groups.
This preserves the paper's TEC definition (macro-average of corpus-level
Order, State, and Outcome coverage), unlike averaging a per-probe score.
"""
axis_scores = []
for axis in ("order", "state", "outcome"):
values = [
value
for gid in gids
if axis in samples[gid]
for value in samples[gid][axis]
]
axis_scores.append(mean(values))
return mean(axis_scores)
def bootstrap_tec(
reference: dict[int, dict[str, list[float]]],
candidate: dict[int, dict[str, list[float]]],
rng: random.Random,
iterations: int,
) -> dict[str, Any]:
gids = sorted(set(reference) & set(candidate))
if set(reference) != set(candidate):
raise ValueError("models do not cover identical groups")
observed = tec_score(reference, gids) - tec_score(candidate, gids)
draws = []
for _ in range(iterations):
sampled_gids = [rng.choice(gids) for _ in gids]
draws.append(tec_score(reference, sampled_gids) - tec_score(candidate, sampled_gids))
draws.sort()
nonpositive = sum(value <= 0.0 for value in draws) / iterations
nonnegative = sum(value >= 0.0 for value in draws) / iterations
return {
"difference_reference_minus_candidate": observed,
"ci95_low": percentile(draws, 0.025),
"ci95_high": percentile(draws, 0.975),
"bootstrap_p_two_sided": min(1.0, 2.0 * min(nonpositive, nonnegative)),
"groups": len(gids),
"paired_values": sum(
len(values)
for gid in gids
for axis, values in reference[gid].items()
if axis in {"order", "state", "outcome"}
),
}
def bootstrap(
differences: dict[int, list[float]], rng: random.Random, iterations: int
) -> dict[str, Any]:
gids = sorted(differences)
observed = mean([value for gid in gids for value in differences[gid]])
draws = []
for _ in range(iterations):
sampled_gids = [rng.choice(gids) for _ in gids]
draws.append(mean([value for gid in sampled_gids for value in differences[gid]]))
draws.sort()
nonpositive = sum(value <= 0.0 for value in draws) / iterations
nonnegative = sum(value >= 0.0 for value in draws) / iterations
return {
"difference_reference_minus_candidate": observed,
"ci95_low": percentile(draws, 0.025),
"ci95_high": percentile(draws, 0.975),
"bootstrap_p_two_sided": min(1.0, 2.0 * min(nonpositive, nonnegative)),
"groups": len(gids),
"paired_values": sum(len(values) for values in differences.values()),
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--probes", type=Path, required=True)
parser.add_argument("--model", action="append", type=parse_model, required=True)
parser.add_argument("--reference", required=True)
parser.add_argument("--iterations", type=int, default=20000)
parser.add_argument("--seed", type=int, default=20260903)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
if args.iterations < 1000:
parser.error("--iterations must be at least 1000")
samples: dict[str, dict[int, dict[str, list[float]]]] = {}
paths: dict[str, str] = {}
for name, path in args.model:
if name in samples:
parser.error(f"duplicate model name: {name}")
samples[name] = load_samples(args.probes, path)
paths[name] = str(path)
if args.reference not in samples:
parser.error("reference must be one of --model names")
comparisons: dict[str, dict[str, Any]] = {}
for name, candidate in samples.items():
if name == args.reference:
continue
key = f"{args.reference}_vs_{name}"
comparisons[key] = {}
for metric in METRICS:
if metric == "tec":
result = bootstrap_tec(
samples[args.reference],
candidate,
random.Random(f"{args.seed}:{key}:{metric}"),
args.iterations,
)
else:
result = bootstrap(
paired_differences(samples[args.reference], candidate, metric),
random.Random(f"{args.seed}:{key}:{metric}"),
args.iterations,
)
result["higher_is_better"] = metric not in LOWER_IS_BETTER
comparisons[key][metric] = result
report = {
"schema_version": "dove-v2-group-bootstrap-v1",
"probes": str(args.probes),
"judgments": paths,
"reference": args.reference,
"bootstrap": {
"unit": "source_video_query_group",
"paired": True,
"iterations": args.iterations,
"seed": args.seed,
"ci": "percentile_95",
},
"comparisons": comparisons,
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
if __name__ == "__main__":
main()