Datasets:
File size: 9,706 Bytes
92186b3 | 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 263 264 265 | #!/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()
|