#!/usr/bin/env python3 """Append completed evaluation benchmarks to an existing MMV-dataset build.""" from __future__ import annotations import argparse import hashlib import json import shutil from collections import Counter, defaultdict from pathlib import Path from typing import Any, Iterable try: from build_mmv_dataset import split_records except ImportError: from materialize_splits import split_records SEED = "MMV-dataset-v1-2026-09-04" def stable_hash(namespace: str, item_id: str) -> str: return hashlib.sha256(f"{SEED}\x1f{namespace}\x1f{item_id}".encode()).hexdigest() def 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 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 read_jsonl(path: Path) -> list[dict[str, Any]]: return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] def stratified_rows( rows: list[dict[str, Any]], category_key: str, id_key: str, target: int, namespace: str ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: by_category: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in rows: by_category[str(row.get(category_key))].append(row) raw_quotas = {cat: len(group) * target / len(rows) for cat, group in by_category.items()} quotas = {cat: int(q) for cat, q in raw_quotas.items()} remainder = target - sum(quotas.values()) order = sorted(by_category, key=lambda cat: (-(raw_quotas[cat] - quotas[cat]), stable_hash(namespace, cat))) for cat in order[:remainder]: quotas[cat] += 1 selected: set[str] = set() for cat, group in by_category.items(): ranked = sorted(group, key=lambda row: stable_hash(namespace, str(row[id_key]))) selected.update(str(row[id_key]) for row in ranked[: quotas[cat]]) train = [row for row in rows if str(row[id_key]) in selected] validation = [row for row in rows if str(row[id_key]) not in selected] assert len(train) == target and len(train) + len(validation) == len(rows) return train, validation def flatten_m3(doc: dict[str, Any]) -> list[dict[str, Any]]: rows = [] for video_id, video in doc.items(): for qa in video["qa_list"]: rows.append({"video_id": video_id, "video_path": video.get("video_path"), **qa}) return rows def normalize_m3(row: dict[str, Any], split: str) -> dict[str, Any]: return { "benchmark": "M3-Bench-robot", "sample_id": str(row["question_id"]), "group_id": str(row["video_id"]), "split": split, "source_split": "robot", "question": row["question"], "choices": None, "answer": row["answer"], "rationale": row.get("reasoning"), "question_type": row.get("type"), "gold_timestamp": row.get("timestamp"), "query_cutoff_clip": row.get("before_clip"), "media_id": str(row["video_id"]), "media_reference": row.get("video_path"), "source_url": "https://huggingface.co/datasets/ByteDance-Seed/M3-Bench", "source_revision": "2672152eee36b25ccb38fdbc3b72135347adbb63", "license": "CC-BY-NC-SA-4.0", } def normalize_egolife(row: dict[str, Any], split: str) -> dict[str, Any]: choices = {key: row[f"choice_{key.lower()}"] for key in "ABCD"} answer = str(row["answer"]) return { "benchmark": "EgoLifeQA", "sample_id": str(row["ID"]), "group_id": "A1_JAKE", "split": split, "source_split": "EgoLifeQA_A1_JAKE", "question": row["question"], "question_zh": row.get("question_chinese"), "choices": choices, "answer": answer, "answer_text": choices[answer], "rationale": row.get("reason"), "rationale_zh": row.get("reason_chinese"), "question_type": row.get("type"), "need_audio": row.get("need_audio"), "query_time": row.get("query_time"), "target_time": row.get("target_time"), "media_id": "A1_JAKE", "media_reference": None, "source_url": "https://huggingface.co/datasets/lmms-lab/EgoLife", "source_revision": "143fb319be7aa5ae210c936bf4f0f3a86092afb0", "license": "MIT-dataset-card-metadata", } def normalize_egomem(row: dict[str, Any], split: str) -> dict[str, Any]: return { "benchmark": "EgoMemReason", "sample_id": str(row["example_id"]), "public_id": row.get("p_id"), "group_id": str(row.get("identity")), "split": split, "source_split": "public_test_without_labels", "question": row["question"], "choices": row.get("options"), "answer": None, "label_status": "private_official_answer_key; not suitable for supervised training", "question_type": row.get("query_type"), "query_time": row.get("query_time"), "media_id": str(row.get("identity")), "media_reference": None, "source_url": "https://huggingface.co/datasets/Ted412/EgoMemReason", "source_revision": "7e581505b9dce0e85193a27ae689ff899d0bc507", "license": "CC-BY-NC-4.0", } def counts(rows: list[dict[str, Any]], key: str) -> dict[str, int]: return dict(sorted(Counter(str(r.get(key)) for r in rows).items())) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--base-build", type=Path, required=True) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--m3-robot-full", type=Path, required=True) parser.add_argument("--egolifeqa", type=Path, required=True) parser.add_argument("--egomemreason", type=Path, required=True) args = parser.parse_args() shutil.copytree(args.base_build, args.output_dir, dirs_exist_ok=True) m3 = flatten_m3(json.loads(args.m3_robot_full.read_text(encoding="utf-8"))) egolife = json.loads(args.egolifeqa.read_text(encoding="utf-8")) egomem = read_jsonl(args.egomemreason) assert len(m3) == 1276 and len({r["question_id"] for r in m3}) == 1276 assert len(egolife) == 500 and len({r["ID"] for r in egolife}) == 500 assert len(egomem) == 500 and len({r["example_id"] for r in egomem}) == 500 m3_types = sorted({t for row in m3 for t in row.get("type", [])}) for row in m3: row["room_category"] = str(row["video_id"]).rsplit("_", 1)[0] row["type_combination"] = " | ".join(sorted(row.get("type", []))) for question_type in m3_types: row[f"has_type::{question_type}"] = question_type in row.get("type", []) m3_strata = ["room_category", "type_combination"] + [f"has_type::{t}" for t in m3_types] m3_train, m3_val, _ = split_records( m3, lambda row: str(row["video_id"]), round(0.3 * len(m3)), "m3_robot", m3_strata ) ego_train, ego_val = stratified_rows(egolife, "type", "ID", 150, "egolifeqa") mem_train, mem_val = stratified_rows(egomem, "query_type", "example_id", 150, "egomemreason") m3_train_n = sorted((normalize_m3(r, "train") for r in m3_train), key=lambda r: r["sample_id"]) m3_val_n = sorted((normalize_m3(r, "validation") for r in m3_val), key=lambda r: r["sample_id"]) ego_train_n = sorted((normalize_egolife(r, "train") for r in ego_train), key=lambda r: r["sample_id"]) ego_val_n = sorted((normalize_egolife(r, "validation") for r in ego_val), key=lambda r: r["sample_id"]) mem_train_n = sorted((normalize_egomem(r, "unlabeled_train") for r in mem_train), key=lambda r: r["sample_id"]) mem_val_n = sorted((normalize_egomem(r, "unlabeled_validation") for r in mem_val), key=lambda r: r["sample_id"]) out = args.output_dir write_jsonl(out / "data/m3_robot/train.jsonl", m3_train_n) write_jsonl(out / "data/m3_robot/validation.jsonl", m3_val_n) write_jsonl(out / "data/egolifeqa/train.jsonl", ego_train_n) write_jsonl(out / "data/egolifeqa/validation.jsonl", ego_val_n) write_jsonl(out / "data/egomemreason/unlabeled_train.jsonl", mem_train_n) write_jsonl(out / "data/egomemreason/unlabeled_validation.jsonl", mem_val_n) old_train = read_jsonl(out / "data/unified/train.jsonl") old_val = read_jsonl(out / "data/unified/validation.jsonl") write_jsonl(out / "data/unified/train.jsonl", sorted(old_train + m3_train_n + ego_train_n, key=lambda r: (r["benchmark"], r["sample_id"]))) write_jsonl(out / "data/unified/validation.jsonl", sorted(old_val + m3_val_n + ego_val_n, key=lambda r: (r["benchmark"], r["sample_id"]))) write_jsonl(out / "data/unified/unlabeled_train.jsonl", mem_train_n) write_jsonl(out / "data/unified/unlabeled_validation.jsonl", mem_val_n) report = { "format_version": 1, "seed": SEED, "m3_robot": { "policy": "complete M3-Bench-robot, exact 30/70 by rows and isolated by video", "rows": len(m3), "train_rows": len(m3_train_n), "validation_rows": len(m3_val_n), "train_videos": len({r["group_id"] for r in m3_train_n}), "validation_videos": len({r["group_id"] for r in m3_val_n}), "video_overlap": len({r["group_id"] for r in m3_train_n} & {r["group_id"] for r in m3_val_n}), "train_question_types": dict(sorted(Counter(t for r in m3_train_n for t in r["question_type"]).items())), "validation_question_types": dict(sorted(Counter(t for r in m3_val_n for t in r["question_type"]).items())), "supervised": True, }, "egolifeqa": { "policy": "deterministic question-level 30/70 stratified by question type", "rows": 500, "train_rows": len(ego_train_n), "validation_rows": len(ego_val_n), "train_types": counts(ego_train_n, "question_type"), "validation_types": counts(ego_val_n, "question_type"), "sample_id_overlap": len({r["sample_id"] for r in ego_train_n} & {r["sample_id"] for r in ego_val_n}), "media_group_overlap": 1, "media_isolation_note": "impossible: all 500 questions use the single A1_JAKE week-long recording", "supervised": True, }, "egomemreason": { "policy": "deterministic question-level 30/70 stratified by query type", "rows": 500, "unlabeled_train_rows": len(mem_train_n), "unlabeled_validation_rows": len(mem_val_n), "train_types": counts(mem_train_n, "question_type"), "validation_types": counts(mem_val_n, "question_type"), "sample_id_overlap": len({r["sample_id"] for r in mem_train_n} & {r["sample_id"] for r in mem_val_n}), "media_group_overlap": 1, "media_isolation_note": "impossible: all 500 questions use the single A1_JAKE week-long recording", "supervised": False, "label_note": "official answers are private; no pseudo-labels were created", }, "unified": { "supervised_train_rows": len(old_train) + len(m3_train_n) + len(ego_train_n), "supervised_validation_rows": len(old_val) + len(m3_val_n) + len(ego_val_n), "unlabeled_train_rows": len(mem_train_n), "unlabeled_validation_rows": len(mem_val_n), }, } (out / "audit/completed_benchmarks_report.json").write_text(json.dumps(report, indent=2, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8") fingerprints_path = out / "audit/source_fingerprints.json" fingerprints = json.loads(fingerprints_path.read_text(encoding="utf-8")) fingerprints["sources"].update({ "m3_robot": {"file": args.m3_robot_full.name, "sha256": sha256(args.m3_robot_full), "source_revision": "0e3e41939bd8a0b66d756e7b7eb8d5fe9992da5c", "dataset_revision": "2672152eee36b25ccb38fdbc3b72135347adbb63", "license": "CC-BY-NC-SA-4.0"}, "egolifeqa": {"file": args.egolifeqa.name, "sha256": sha256(args.egolifeqa), "source_revision": "143fb319be7aa5ae210c936bf4f0f3a86092afb0", "license": "MIT-dataset-card-metadata"}, "egomemreason": {"file": args.egomemreason.name, "sha256": sha256(args.egomemreason), "source_revision": "7e581505b9dce0e85193a27ae689ff899d0bc507", "license": "CC-BY-NC-4.0", "labels": "private/not included"}, }) fingerprints_path.write_text(json.dumps(fingerprints, indent=2, sort_keys=True) + "\n", encoding="utf-8") shutil.copy2(Path(__file__), out / "scripts/extend_completed_benchmarks.py") readme = (out / "README.md").read_text(encoding="utf-8") readme = readme.replace( "Reproducible, video-group-isolated 30/70 research splits derived from three long-video benchmarks.", "Reproducible research splits and full-training subsets derived from long-video benchmarks.", ) readme = readme.replace( "| Unified hosted records | 551 | 1,286 | inherited | mixed; see per-row license |", "| Unified supervised records | 1,084 | 2,529 | inherited | mixed; see per-row license |", ) readme = readme.replace( "- Splits are made at the video level, never per question.\n- The selected whole groups exactly total 30% of question rows for each source.", "- Video-MME, LongVideoBench, and EgoTempo are split at the video level.\n- Those selected whole groups exactly total 30% of question rows for each source.\n- Completed benchmark additions follow the explicitly documented exceptions below.", ) readme = readme.replace( "- config_name: longvideobench\n", "- config_name: m3_robot\n data_files:\n - split: train\n path: data/m3_robot/train.jsonl\n - split: validation\n path: data/m3_robot/validation.jsonl\n- config_name: egolifeqa\n data_files:\n - split: train\n path: data/egolifeqa/train.jsonl\n - split: validation\n path: data/egolifeqa/validation.jsonl\n- config_name: egomemreason_unlabeled\n data_files:\n - split: train\n path: data/egomemreason/unlabeled_train.jsonl\n - split: validation\n path: data/egomemreason/unlabeled_validation.jsonl\n- config_name: longvideobench\n", ) readme = readme.replace( " - split: validation\n path: data/unified/validation.jsonl\n", " - split: validation\n path: data/unified/validation.jsonl\n - split: unlabeled_train\n path: data/unified/unlabeled_train.jsonl\n - split: unlabeled_validation\n path: data/unified/unlabeled_validation.jsonl\n", 1, ) addition = """ ## Completed benchmark additions | Component | Train | Validation | Label status | Split policy | |---|---:|---:|---|---| | M3-Bench-robot (complete) | 383 | 893 | public | video-level, type-balanced 30/70 | | EgoLifeQA-500 | 150 | 350 | public | question-level, type-stratified 30/70 | | EgoMemReason-500 | 150 | 350 | **private / unavailable** | unlabeled question-level, type-stratified 30/70 | The unified supervised splits now contain **1,084 train** and **2,529 validation** rows. EgoMemReason is exposed only through `unlabeled_train` and `unlabeled_validation`; it is not silently mixed into supervised data and no model-generated pseudo-labels are presented as truth. M3 uses the complete 1,276-question, 100-video M3-Bench-robot annotation set. The 383/893 split is made by video, so no robot video appears in both partitions. EgoLifeQA and EgoMemReason both use the single A1_JAKE week-long recording. Their question IDs are disjoint across 30/70 splits, but media-level isolation is mathematically impossible. Treat their held-out scores as question-held-out diagnostics, not unseen-video generalization. EgoMemReason official labels remain private and official benchmark use is contaminated once its public questions are used for training. """ marker = "\n## Evaluation warning\n" readme = readme.replace(marker, addition + marker) readme = readme.replace( "Training on any portion of Video-MME or EgoTempo contaminates those official benchmarks", "Training on any portion of Video-MME, EgoTempo, M3-Bench, EgoLifeQA, or EgoMemReason contaminates those official benchmarks", ) readme = readme.replace( "- [EgoTempo](https://github.com/google-research-datasets/egotempo), CC BY 4.0 annotations. Ego4D media is governed separately.\n", "- [EgoTempo](https://github.com/google-research-datasets/egotempo), CC BY 4.0 annotations. Ego4D media is governed separately.\n- [M3-Bench](https://huggingface.co/datasets/ByteDance-Seed/M3-Bench), CC BY-NC-SA 4.0 annotations.\n- [EgoLife](https://huggingface.co/datasets/lmms-lab/EgoLife), source card declares MIT; media terms apply separately.\n- [EgoMemReason](https://huggingface.co/datasets/Ted412/EgoMemReason), CC BY-NC 4.0 public questions; answers are private.\n", ) (out / "README.md").write_text(readme, encoding="utf-8") license_notes = (out / "LICENSES/README.md").read_text(encoding="utf-8") license_notes += "\n- **M3-Bench annotations:** CC BY-NC-SA 4.0; the M3-Bench-robot split is redistributed under the same non-commercial share-alike terms.\n- **EgoLifeQA annotations:** source dataset card declares MIT; media is not included and upstream media terms apply separately.\n- **EgoMemReason public annotations:** CC BY-NC 4.0; the private answer key is not included.\n" (out / "LICENSES/README.md").write_text(license_notes, encoding="utf-8") checksum_files = sorted(p for p in out.rglob("*") if p.is_file() and p.name != "checksums.sha256") (out / "audit/checksums.sha256").write_text("".join(f"{sha256(p)} {p.relative_to(out).as_posix()}\n" for p in checksum_files), encoding="utf-8") print(json.dumps(report, indent=2, ensure_ascii=False)) if __name__ == "__main__": main()