MMV-dataset / scripts /materialize_splits.py
czty's picture
Add reproducible video-group-isolated 30/70 splits
31331a5
Raw History Blame Contribute Delete
20.1 kB
#!/usr/bin/env python3
"""Build reproducible, group-isolated 30/70 MMV dataset splits.
The public build intentionally omits Video-MME question-level records because its
official repository forbids redistribution without prior approval. The same
deterministic splitter can materialize those records locally from an authorized
copy with --include-videomme-records.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import shutil
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Callable, Iterable
SEED = "MMV-dataset-v1-2026-09-04"
SOURCES = {
"videomme": {
"url": "https://github.com/MME-Benchmarks/Video-MME",
"revision": "06c2315b892f88578f81d73205d07cf576f292b9",
"license": "custom-academic-no-redistribution",
},
"longvideobench": {
"url": "https://huggingface.co/datasets/longvideobench/LongVideoBench",
"revision": "60d1c89c1919a198b73be39c2babb213b29d6a5c",
"license": "CC-BY-NC-SA-4.0",
},
"egotempo": {
"url": "https://github.com/google-research-datasets/egotempo",
"revision": "7022ba77b4d89f51cf34e499767995ccd5c90c7a",
"license": "CC-BY-4.0",
},
}
def stable_hash(*parts: str) -> str:
return hashlib.sha256("\x1f".join(parts).encode("utf-8")).hexdigest()
def file_sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for block in iter(lambda: f.read(1024 * 1024), b""):
h.update(block)
return h.hexdigest()
def choose_groups_exact(
records: list[dict[str, Any]],
group_key: Callable[[dict[str, Any]], str],
target_rows: int,
namespace: str,
stratify_keys: list[str],
) -> set[str]:
"""Select whole groups with an exact target row count, deterministically.
Groups are first ordered by a seed-derived SHA-256 value. Dynamic programming
then finds the earliest exact subset, providing a reproducible pseudo-random
group sample without introducing row-level leakage.
"""
grouped: dict[str, int] = Counter(group_key(r) for r in records)
ordered = sorted(grouped.items(), key=lambda kv: stable_hash(SEED, namespace, kv[0]))
reachable: dict[int, tuple[int, int] | None] = {0: None}
for idx, (_, size) in enumerate(ordered):
for total in sorted(list(reachable), reverse=True):
nxt = total + size
if nxt <= target_rows and nxt not in reachable:
reachable[nxt] = (total, idx)
if target_rows in reachable:
break
if target_rows not in reachable:
raise RuntimeError(f"cannot select whole {namespace} groups totaling {target_rows} rows")
selected: set[str] = set()
cursor = target_rows
while cursor:
previous, idx = reachable[cursor] # type: ignore[misc]
group_id, size = ordered[idx]
selected.add(group_id)
cursor = previous
assert size > 0
# Improve marginal balance with deterministic, equal-size group swaps. Equal
# sizes preserve the exact row target while allowing multi-question groups to
# remain intact.
grouped_rows: dict[str, list[dict[str, Any]]] = defaultdict(list)
for row in records:
grouped_rows[group_key(row)].append(row)
target_fraction = target_rows / len(records)
totals = {key: Counter(str(r.get(key)) for r in records) for key in stratify_keys}
current = {
key: Counter(str(r.get(key)) for gid in selected for r in grouped_rows[gid])
for key in stratify_keys
}
def contribution(gid: str) -> dict[str, Counter[str]]:
return {key: Counter(str(r.get(key)) for r in grouped_rows[gid]) for key in stratify_keys}
vectors = {gid: contribution(gid) for gid in grouped_rows}
def swap_delta(a: str, b: str) -> float:
delta = 0.0
for key in stratify_keys:
cats = set(vectors[a][key]) | set(vectors[b][key])
for cat in cats:
target = totals[key][cat] * target_fraction
scale = max(1.0, target)
before = (current[key][cat] - target) / scale
after_count = current[key][cat] - vectors[a][key][cat] + vectors[b][key][cat]
after = (after_count - target) / scale
delta += after * after - before * before
return delta
for _ in range(12):
improved = False
train_ids = sorted(selected, key=lambda g: stable_hash(SEED, namespace, "train", g))
val_by_size: dict[int, list[str]] = defaultdict(list)
for gid in grouped_rows:
if gid not in selected:
val_by_size[len(grouped_rows[gid])].append(gid)
for gids in val_by_size.values():
gids.sort(key=lambda g: stable_hash(SEED, namespace, "validation", g))
for a in train_ids:
candidates = val_by_size[len(grouped_rows[a])]
if not candidates:
continue
best = min(candidates, key=lambda b: (swap_delta(a, b), stable_hash(SEED, namespace, a, b)))
if swap_delta(a, best) < -1e-12:
selected.remove(a)
selected.add(best)
for key in stratify_keys:
current[key].subtract(vectors[a][key])
current[key].update(vectors[best][key])
candidates.remove(best)
candidates.append(a)
improved = True
if not improved:
break
return selected
def split_records(
records: list[dict[str, Any]],
group_key: Callable[[dict[str, Any]], str],
target_rows: int,
namespace: str,
stratify_keys: list[str],
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], set[str]]:
selected = choose_groups_exact(records, group_key, target_rows, namespace, stratify_keys)
train = [r for r in records if group_key(r) in selected]
validation = [r for r in records if group_key(r) not in selected]
assert len(train) == target_rows
assert not ({group_key(r) for r in train} & {group_key(r) for r in validation})
return train, validation, selected
def read_json(path: Path) -> Any:
with path.open(encoding="utf-8") as f:
return json.load(f)
def read_videomme(path: Path) -> list[dict[str, Any]]:
try:
import pyarrow.parquet as pq
except ImportError as exc:
raise RuntimeError("pyarrow is required to read the Video-MME parquet") from exc
return pq.read_table(path).to_pylist()
def normalize_lvb(row: dict[str, Any], split: str) -> dict[str, Any]:
choice = int(row["correct_choice"])
candidates = list(row["candidates"])
return {
"benchmark": "LongVideoBench",
"sample_id": str(row["id"]),
"group_id": str(row["video_id"]),
"split": split,
"source_split": "validation",
"question": row["question"],
"question_without_referring_query": row.get("question_wo_referring_query"),
"choices": candidates,
"answer_index": choice,
"answer": candidates[choice],
"question_type": row.get("question_category"),
"topic_category": row.get("topic_category"),
"level": row.get("level"),
"duration_group": row.get("duration_group"),
"duration_seconds": row.get("duration"),
"position": row.get("position"),
"starting_timestamp_for_subtitles": row.get("starting_timestamp_for_subtitles"),
"media_id": str(row["video_id"]),
"media_reference": row.get("video_path"),
"subtitle_reference": row.get("subtitle_path"),
"source_url": SOURCES["longvideobench"]["url"],
"source_revision": SOURCES["longvideobench"]["revision"],
"license": SOURCES["longvideobench"]["license"],
}
def ego_video_uid(clip_id: str) -> str:
return clip_id.split("_", 1)[0]
def normalize_ego(row: dict[str, Any], split: str) -> dict[str, Any]:
clip_id = str(row["clip_id"])
return {
"benchmark": "EgoTempo",
"sample_id": str(row["question_id"]),
"group_id": ego_video_uid(clip_id),
"clip_id": clip_id,
"split": split,
"source_split": "open_ended_qa",
"question": row["question"],
"choices": None,
"answer": row["answer"],
"question_type": row.get("question_type"),
"media_id": ego_video_uid(clip_id),
"media_reference": None,
"source_url": SOURCES["egotempo"]["url"],
"source_revision": SOURCES["egotempo"]["revision"],
"license": SOURCES["egotempo"]["license"],
}
def normalize_videomme(row: dict[str, Any], split: str) -> dict[str, Any]:
return {
"benchmark": "Video-MME",
"sample_id": str(row["question_id"]),
"group_id": str(row["videoID"]),
"video_id": str(row["video_id"]),
"split": split,
"source_split": "test",
"question": row["question"],
"choices": list(row["options"]),
"answer": row["answer"],
"question_type": row.get("task_type"),
"domain": row.get("domain"),
"sub_category": row.get("sub_category"),
"duration_group": row.get("duration"),
"media_id": str(row["videoID"]),
"media_reference": row.get("url"),
"source_url": SOURCES["videomme"]["url"],
"source_revision": SOURCES["videomme"]["revision"],
"license": SOURCES["videomme"]["license"],
}
def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as f:
for row in rows:
f.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
def distribution(rows: list[dict[str, Any]], keys: list[str]) -> dict[str, dict[str, int]]:
result: dict[str, dict[str, int]] = {}
for key in keys:
result[key] = dict(sorted(Counter(str(r.get(key)) for r in rows).items()))
return result
def dataset_audit(
name: str,
raw: list[dict[str, Any]],
train: list[dict[str, Any]],
validation: list[dict[str, Any]],
group_key: Callable[[dict[str, Any]], str],
stratify_keys: list[str],
) -> dict[str, Any]:
train_groups = {group_key(r) for r in train}
validation_groups = {group_key(r) for r in validation}
return {
"benchmark": name,
"total_rows": len(raw),
"train_rows": len(train),
"validation_rows": len(validation),
"train_fraction": len(train) / len(raw),
"total_groups": len(train_groups | validation_groups),
"train_groups": len(train_groups),
"validation_groups": len(validation_groups),
"group_overlap": len(train_groups & validation_groups),
"distributions": {
"all": distribution(raw, stratify_keys),
"train": distribution(train, stratify_keys),
"validation": distribution(validation, stratify_keys),
},
}
README = """---
license: other
task_categories:
- question-answering
- visual-question-answering
language:
- en
configs:
- config_name: unified
data_files:
- split: train
path: data/unified/train.jsonl
- split: validation
path: data/unified/validation.jsonl
- config_name: longvideobench
data_files:
- split: train
path: data/longvideobench/train.jsonl
- split: validation
path: data/longvideobench/validation.jsonl
- config_name: egotempo
data_files:
- split: train
path: data/egotempo/train.jsonl
- split: validation
path: data/egotempo/validation.jsonl
---
# MMV-dataset
Reproducible, video-group-isolated 30/70 research splits derived from three long-video benchmarks. No video, audio, or subtitle media is included.
## Hosted data
| Component | Train | Validation | Grouping unit | License |
|---|---:|---:|---|---|
| LongVideoBench labeled validation set | 401 | 936 | `video_id` | CC BY-NC-SA 4.0 |
| EgoTempo open-ended QA | 150 | 350 | original Ego4D video UID | CC BY 4.0 |
| Unified hosted records | 551 | 1,286 | inherited | mixed; see per-row license |
The LongVideoBench hidden-label test split is not used. Media references are metadata only; obtain media through each upstream project's authorized process.
## Video-MME
Video-MME is part of the split design (810 train / 1,890 validation questions, grouped by 270 / 630 videos), but its official terms prohibit redistribution without prior approval. Consequently, this repository publishes only aggregate audit statistics and the deterministic materialization script—not Video-MME questions, answers, IDs, or media. After obtaining an authorized local copy, run:
```bash
python scripts/materialize_splits.py \\
--longvideobench-val path/to/longvideobench_val_v1.1.json \\
--egotempo-openqa path/to/egotempo_openQA.json \\
--videomme-parquet path/to/test-00000-of-00001.parquet \\
--output-dir local_materialized \\
--include-videomme-records
```
## Reproducibility and leakage control
- Fixed seed: `MMV-dataset-v1-2026-09-04`.
- Splits are made at the video level, never per question.
- The selected whole groups exactly total 30% of question rows for each source.
- `audit/split_report.json` records counts, distributions, and zero group overlap.
- `audit/source_fingerprints.json` pins source revisions and input SHA-256 values.
The hosted JSONL files require no special loader. Local Video-MME materialization
requires Python 3.10+ and `pyarrow` (`pip install -r requirements.txt`).
## Evaluation warning
These are custom research splits. Training on any portion of Video-MME or EgoTempo contaminates those official benchmarks, so scores on their remaining 70% must be reported as **MMV custom held-out scores**, not official full-benchmark or zero-shot leaderboard results.
## Sources and attribution
- [Video-MME](https://github.com/MME-Benchmarks/Video-MME), official custom academic terms.
- [LongVideoBench](https://huggingface.co/datasets/longvideobench/LongVideoBench), CC BY-NC-SA 4.0 annotations. LongVideoBench does not convey rights to linked media.
- [EgoTempo](https://github.com/google-research-datasets/egotempo), CC BY 4.0 annotations. Ego4D media is governed separately.
This adaptation is non-commercial and distributed under the applicable upstream terms. The repository-level `license: other` reflects the mixed licensing; every hosted row carries its component license.
"""
LICENSE_NOTES = """# Component licenses and media rights
- **LongVideoBench annotations:** CC BY-NC-SA 4.0. This adaptation preserves attribution and is offered for non-commercial research under the same share-alike terms. Linked videos and subtitle media are not included and remain subject to their owners' terms.
- **EgoTempo annotations:** CC BY 4.0. Ego4D videos are not included and require separate authorized access.
- **Video-MME:** the official repository states that redistribution in whole or in part requires prior approval. No question-level Video-MME content is hosted here; only a materialization script and aggregate statistics are provided.
Always review the current upstream terms before reuse.
"""
def copy_materializer(destination: Path) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(Path(__file__), destination)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--longvideobench-val", type=Path, required=True)
parser.add_argument("--egotempo-openqa", type=Path, required=True)
parser.add_argument("--videomme-parquet", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--include-videomme-records", action="store_true")
args = parser.parse_args()
out = args.output_dir
out.mkdir(parents=True, exist_ok=True)
lvb = read_json(args.longvideobench_val)
ego_doc = read_json(args.egotempo_openqa)
ego = ego_doc["annotations"] if isinstance(ego_doc, dict) else ego_doc
vmm = read_videomme(args.videomme_parquet)
lvb_strata = ["duration_group", "topic_category", "question_category", "level"]
ego_strata = ["question_type"]
vmm_strata = ["duration", "domain", "sub_category", "task_type"]
lvb_train, lvb_val, _ = split_records(lvb, lambda r: str(r["video_id"]), round(0.3 * len(lvb)), "longvideobench", lvb_strata)
ego_train, ego_val, _ = split_records(ego, lambda r: ego_video_uid(str(r["clip_id"])), round(0.3 * len(ego)), "egotempo", ego_strata)
vmm_train, vmm_val, _ = split_records(vmm, lambda r: str(r["videoID"]), round(0.3 * len(vmm)), "videomme", vmm_strata)
lvb_train_n = [normalize_lvb(r, "train") for r in lvb_train]
lvb_val_n = [normalize_lvb(r, "validation") for r in lvb_val]
ego_train_n = [normalize_ego(r, "train") for r in ego_train]
ego_val_n = [normalize_ego(r, "validation") for r in ego_val]
for rows in (lvb_train_n, lvb_val_n, ego_train_n, ego_val_n):
rows.sort(key=lambda r: (r["benchmark"], r["sample_id"]))
write_jsonl(out / "data/longvideobench/train.jsonl", lvb_train_n)
write_jsonl(out / "data/longvideobench/validation.jsonl", lvb_val_n)
write_jsonl(out / "data/egotempo/train.jsonl", ego_train_n)
write_jsonl(out / "data/egotempo/validation.jsonl", ego_val_n)
write_jsonl(out / "data/unified/train.jsonl", sorted(lvb_train_n + ego_train_n, key=lambda r: (r["benchmark"], r["sample_id"])))
write_jsonl(out / "data/unified/validation.jsonl", sorted(lvb_val_n + ego_val_n, key=lambda r: (r["benchmark"], r["sample_id"])))
if args.include_videomme_records:
write_jsonl(out / "data/videomme/train.jsonl", [normalize_videomme(r, "train") for r in vmm_train])
write_jsonl(out / "data/videomme/validation.jsonl", [normalize_videomme(r, "validation") for r in vmm_val])
report = {
"format_version": 1,
"seed": SEED,
"split_policy": "exact 30/70 by rows, isolated by video group",
"public_build_includes_videomme_records": bool(args.include_videomme_records),
"benchmarks": {
"longvideobench": dataset_audit("LongVideoBench", lvb, lvb_train, lvb_val, lambda r: str(r["video_id"]), lvb_strata),
"egotempo": dataset_audit("EgoTempo", ego, ego_train, ego_val, lambda r: ego_video_uid(str(r["clip_id"])), ego_strata),
"videomme": dataset_audit("Video-MME", vmm, vmm_train, vmm_val, lambda r: str(r["videoID"]), vmm_strata),
},
}
(out / "audit").mkdir(parents=True, exist_ok=True)
(out / "audit/split_report.json").write_text(json.dumps(report, indent=2, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8")
fingerprints = {
"seed": SEED,
"sources": {
"longvideobench": {**SOURCES["longvideobench"], "file": args.longvideobench_val.name, "sha256": file_sha256(args.longvideobench_val)},
"egotempo": {**SOURCES["egotempo"], "file": args.egotempo_openqa.name, "sha256": file_sha256(args.egotempo_openqa)},
"videomme": {**SOURCES["videomme"], "file": args.videomme_parquet.name, "sha256": file_sha256(args.videomme_parquet)},
},
}
(out / "audit/source_fingerprints.json").write_text(json.dumps(fingerprints, indent=2, sort_keys=True) + "\n", encoding="utf-8")
(out / "README.md").write_text(README, encoding="utf-8")
(out / "requirements.txt").write_text("pyarrow>=15\n", encoding="utf-8")
(out / "LICENSES").mkdir(parents=True, exist_ok=True)
(out / "LICENSES/README.md").write_text(LICENSE_NOTES, encoding="utf-8")
copy_materializer(out / "scripts/materialize_splits.py")
checksum_files = sorted(p for p in out.rglob("*") if p.is_file() and p.name != "checksums.sha256")
checksum_text = "".join(f"{file_sha256(p)} {p.relative_to(out).as_posix()}\n" for p in checksum_files)
(out / "audit/checksums.sha256").write_text(checksum_text, encoding="utf-8")
print(json.dumps({"output": str(out), "report": report}, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()