physics-bench-solid-train / source_metadata /build_hf_hardneg_dataset.py
Yiqi-Liu's picture
Add files using upload-large-folder tool
fc48e53 verified
Raw
History Blame Contribute Delete
19.4 kB
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import hashlib
import json
import random
import shutil
from pathlib import Path
from typing import Any
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
NEGATIVE_COUNT = 5
SOURCE_COLUMNS = ("query_id", "case_id", "raw_text", "parsed_text", "video")
OUTPUT_COLUMNS = ("text", "video", "hard_negative_texts", "hard_negative_videos")
HF_FEATURES = {
"text": {"dtype": "string", "_type": "Value"},
"video": {"dtype": "string", "_type": "Value"},
"hard_negative_texts": {
"feature": {"dtype": "string", "_type": "Value"},
"length": -1,
"_type": "List",
},
"hard_negative_videos": {
"feature": {"dtype": "string", "_type": "Value"},
"length": -1,
"_type": "List",
},
}
OUTPUT_SCHEMA = pa.schema(
[
pa.field("text", pa.string()),
pa.field("video", pa.string()),
pa.field("hard_negative_texts", pa.list_(pa.string())),
pa.field("hard_negative_videos", pa.list_(pa.string())),
],
metadata={
b"huggingface": json.dumps(
{"info": {"features": HF_FEATURES}},
separators=(",", ":"),
).encode()
},
)
def _write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
def _source_files(source_dir: Path) -> list[tuple[str, Path]]:
return sorted(
((path.parent.name, path) for path in source_dir.glob("*/train-*.parquet")),
key=lambda item: item[0],
)
def _read_query_rows(
path: Path,
*,
query_suffix: str,
include_video: bool,
) -> list[dict[str, Any]]:
columns = list(SOURCE_COLUMNS if include_video else SOURCE_COLUMNS[:-1])
table = pq.read_table(path, columns=columns)
filtered = table.filter(pc.ends_with(table["query_id"], pattern=query_suffix))
return sorted(filtered.to_pylist(), key=lambda row: str(row["case_id"]))
def _sample_assignments(
family_rows: dict[str, list[dict[str, Any]]],
*,
seed: int,
) -> dict[str, dict[str, list[str]]]:
rng = random.Random(seed)
assignments: dict[str, dict[str, list[str]]] = {}
for family in sorted(family_rows):
rows = sorted(family_rows[family], key=lambda row: str(row["case_id"]))
family_assignments: dict[str, list[str]] = {}
for row in rows:
case_id = str(row["case_id"])
candidates = [
str(candidate["case_id"])
for candidate in rows
if str(candidate["case_id"]) != case_id
]
family_assignments[case_id] = rng.sample(candidates, NEGATIVE_COUNT)
assignments[family] = family_assignments
return assignments
def _assignment_digest(assignments: dict[str, dict[str, list[str]]]) -> str:
payload = [
{
"family": family,
"case_id": case_id,
"negative_case_ids": assignments[family][case_id],
}
for family in sorted(assignments)
for case_id in sorted(assignments[family])
]
serialized = json.dumps(payload, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(serialized.encode()).hexdigest()
def _video_relpath(family: str, case_id: str) -> str:
return f"videos/{family}/{case_id}.mp4"
def _update_video_digest(digest: Any, relpath: str, data: bytes) -> None:
digest.update(relpath.encode())
digest.update(b"\0")
digest.update(data)
digest.update(b"\n")
def _readme(
*,
repo_id: str,
source_repo: str,
seed: int,
query_suffix: str,
total_rows: int,
metadata_size: int,
video_size: int,
) -> str:
total_size = metadata_size + video_size
return "\n".join(
[
"---",
"dataset_info:",
" features:",
" - name: text",
" dtype: string",
" - name: video",
" dtype: string",
" - name: hard_negative_texts",
" list: string",
" - name: hard_negative_videos",
" list: string",
" splits:",
" - name: train",
f" num_bytes: {total_size}",
f" num_examples: {total_rows}",
f" download_size: {total_size}",
f" dataset_size: {total_size}",
"configs:",
"- config_name: default",
" data_files:",
" - split: train",
" path: metadata.parquet",
"---",
"",
"# Physics Bench Solid With Hard Negatives",
"",
f"Repository: `{repo_id}`",
"",
f"Source dataset: `{source_repo}`",
"",
"This repository follows the path-based layout of "
"`gowitheflowlab/physics-bench-optics-w-hardnegs`.",
"",
f"- rows: {total_rows}",
"- metadata columns: `text`, `video`, `hard_negative_texts`, "
"`hard_negative_videos`",
f"- positive text: query 1 (`{query_suffix}`) from the source case",
f"- hard negatives per row: {NEGATIVE_COUNT}",
"- video paths: repository-relative `videos/<family>/<case_id>.mp4`",
"- list alignment: `hard_negative_texts[i]` and "
"`hard_negative_videos[i]` come from the same case",
"- candidate pool: only the other 99 cases in the positive case's family",
"",
"## Reproducibility",
"",
f"- global seed: {seed}",
"- traversal: family alphabetical order, then case_id order",
f"- sampling: one `random.Random({seed})` stream for all {total_rows} rows",
"- selection: `random.sample(sorted(other_99_case_ids), 5)`",
"",
"## Loading",
"",
"```python",
"from pathlib import Path",
"import pyarrow.parquet as pq",
"from huggingface_hub import snapshot_download",
"",
f'root = Path(snapshot_download("{repo_id}", repo_type="dataset"))',
'rows = pq.read_table(root / "metadata.parquet").to_pylist()',
"row = rows[0]",
'positive_video = root / row["video"]',
'negative_videos = [root / path for path in row["hard_negative_videos"]]',
"```",
"",
"The training metadata intentionally contains only the four retrieval "
"columns. Case IDs and query IDs are retained in "
"`source_metadata/sampling_manifest.json` for auditing.",
"",
]
)
def _validate_output(
*,
out_dir: Path,
metadata_rows: list[dict[str, Any]],
family_rows: dict[str, list[dict[str, Any]]],
expected_total_rows: int,
source_video_hash: str,
) -> dict[str, Any]:
errors: list[str] = []
table = pq.read_table(out_dir / "metadata.parquet")
if tuple(table.column_names) != OUTPUT_COLUMNS:
errors.append(
f"metadata columns are {table.column_names}, expected {OUTPUT_COLUMNS}"
)
written_rows = table.to_pylist()
if len(written_rows) != expected_total_rows:
errors.append(
f"metadata has {len(written_rows)} rows, expected {expected_total_rows}"
)
if written_rows != metadata_rows:
errors.append("metadata changed during parquet serialization")
source_by_path: dict[str, dict[str, Any]] = {}
for family, rows in family_rows.items():
for row in rows:
relpath = _video_relpath(family, str(row["case_id"]))
source_by_path[relpath] = row
seen_positive_paths: set[str] = set()
hard_negative_pairs = 0
cross_family_count = 0
self_negative_count = 0
for row in written_rows:
video = str(row["video"])
source = source_by_path.get(video)
if source is None:
errors.append(f"positive video path is unknown: {video}")
continue
family = Path(video).parts[1]
if video in seen_positive_paths:
errors.append(f"duplicate positive video path: {video}")
seen_positive_paths.add(video)
if str(row["text"]) != str(source["raw_text"]):
errors.append(f"positive text mismatch: {video}")
negative_texts = list(row["hard_negative_texts"])
negative_videos = [str(path) for path in row["hard_negative_videos"]]
if (
len(negative_texts) != NEGATIVE_COUNT
or len(negative_videos) != NEGATIVE_COUNT
):
errors.append(f"{video}: expected five hard negatives")
if len(set(negative_videos)) != NEGATIVE_COUNT:
errors.append(f"{video}: hard-negative videos are not unique")
for negative_text, negative_video in zip(
negative_texts,
negative_videos,
):
hard_negative_pairs += 1
negative_source = source_by_path.get(negative_video)
if negative_source is None:
errors.append(f"{video}: unknown hard-negative path {negative_video}")
continue
if Path(negative_video).parts[1] != family:
cross_family_count += 1
if negative_video == video:
self_negative_count += 1
if str(negative_text) != str(negative_source["raw_text"]):
errors.append(
f"{video}: hard-negative text/path mismatch for {negative_video}"
)
if cross_family_count:
errors.append(f"found {cross_family_count} cross-family hard negatives")
if self_negative_count:
errors.append(f"found {self_negative_count} self hard negatives")
output_digest = hashlib.sha256()
missing_videos: list[str] = []
for relpath in sorted(source_by_path):
path = out_dir / relpath
if not path.is_file() or path.stat().st_size == 0:
missing_videos.append(relpath)
continue
_update_video_digest(output_digest, relpath, path.read_bytes())
output_video_hash = output_digest.hexdigest()
if output_video_hash != source_video_hash:
errors.append("video bytes changed while creating the hard-negative dataset")
return {
"passed": not errors,
"errors": errors[:100],
"metadata_rows": len(written_rows),
"metadata_columns": table.column_names,
"video_files": len(source_by_path) - len(missing_videos),
"missing_videos": missing_videos[:100],
"hard_negative_pairs": hard_negative_pairs,
"cross_family_hard_negatives": cross_family_count,
"self_hard_negatives": self_negative_count,
"source_video_sha256": source_video_hash,
"output_video_sha256": output_video_hash,
"video_bytes_preserved": source_video_hash == output_video_hash,
}
def build_dataset(
*,
source_dir: Path,
out_dir: Path,
repo_id: str,
source_repo: str,
seed: int,
query_suffix: str,
expected_rows_per_family: int,
expected_total_rows: int,
) -> dict[str, Any]:
source_files = _source_files(source_dir)
if not source_files:
raise FileNotFoundError(
f"No source family parquet files found under {source_dir}"
)
family_rows = {
family: _read_query_rows(
path,
query_suffix=query_suffix,
include_video=False,
)
for family, path in source_files
}
bad_counts = {
family: len(rows)
for family, rows in family_rows.items()
if len(rows) != expected_rows_per_family
}
if bad_counts:
raise ValueError(
f"Expected {expected_rows_per_family} query-1 rows per family: {bad_counts}"
)
if sum(map(len, family_rows.values())) != expected_total_rows:
raise ValueError(f"Expected {expected_total_rows} query-1 rows in total")
for family, rows in family_rows.items():
case_ids = [str(row["case_id"]) for row in rows]
if len(case_ids) != len(set(case_ids)):
raise ValueError(f"Duplicate query-1 case IDs in family {family}")
assignments = _sample_assignments(family_rows, seed=seed)
repeated = _sample_assignments(family_rows, seed=seed)
if assignments != repeated:
raise AssertionError("Hard-negative sampling is not reproducible")
if out_dir.exists():
shutil.rmtree(out_dir)
out_dir.mkdir(parents=True)
metadata_rows: list[dict[str, Any]] = []
manifest_rows: list[dict[str, Any]] = []
source_video_digest = hashlib.sha256()
video_size = 0
source_file_map = dict(source_files)
for family in sorted(family_rows):
rows = family_rows[family]
by_case = {str(row["case_id"]): row for row in rows}
rows_with_video = _read_query_rows(
source_file_map[family],
query_suffix=query_suffix,
include_video=True,
)
video_by_case = {
str(row["case_id"]): row["video"] for row in rows_with_video
}
if set(video_by_case) != set(by_case):
raise ValueError(f"Query/video case mismatch in family {family}")
for source_row in rows:
case_id = str(source_row["case_id"])
query_id = str(source_row["query_id"])
if not query_id.endswith(query_suffix):
raise ValueError(f"Unexpected query ID for query 1: {query_id}")
relpath = _video_relpath(family, case_id)
video_value = video_by_case[case_id]
video_bytes = bytes(video_value["bytes"])
if not video_bytes:
raise ValueError(f"Empty source video bytes for {case_id}")
video_path = out_dir / relpath
video_path.parent.mkdir(parents=True, exist_ok=True)
video_path.write_bytes(video_bytes)
video_size += len(video_bytes)
_update_video_digest(source_video_digest, relpath, video_bytes)
negative_case_ids = assignments[family][case_id]
negative_rows = [by_case[negative_id] for negative_id in negative_case_ids]
negative_paths = [
_video_relpath(family, negative_id)
for negative_id in negative_case_ids
]
metadata_rows.append(
{
"text": str(source_row["raw_text"]),
"video": relpath,
"hard_negative_texts": [
str(row["raw_text"]) for row in negative_rows
],
"hard_negative_videos": negative_paths,
}
)
manifest_rows.append(
{
"family": family,
"case_id": case_id,
"query_id": query_id,
"video": relpath,
"negative_case_ids": negative_case_ids,
"negative_query_ids": [
str(row["query_id"]) for row in negative_rows
],
"hard_negative_videos": negative_paths,
}
)
del rows_with_video
del video_by_case
metadata_path = out_dir / "metadata.parquet"
table = pa.Table.from_pylist(metadata_rows, schema=OUTPUT_SCHEMA)
pq.write_table(
table,
metadata_path,
compression="snappy",
row_group_size=100,
write_page_index=True,
)
source_video_hash = source_video_digest.hexdigest()
validation = _validate_output(
out_dir=out_dir,
metadata_rows=metadata_rows,
family_rows=family_rows,
expected_total_rows=expected_total_rows,
source_video_hash=source_video_hash,
)
assignment_hash = _assignment_digest(assignments)
validation.update(
{
"repo_id": repo_id,
"source_repo": source_repo,
"seed": seed,
"query_suffix": query_suffix,
"family_count": len(family_rows),
"rows_per_family": {
family: len(rows) for family, rows in family_rows.items()
},
"assignment_sha256": assignment_hash,
"second_pass_assignment_sha256": _assignment_digest(repeated),
"reproducibility_verified": assignments == repeated,
"single_rng_stream": True,
"traversal_order": "family alphabetical, then case_id",
}
)
_write_json(out_dir / "quality" / "validation.json", validation)
_write_json(
out_dir / "generation_manifest.json",
{
"repo_id": repo_id,
"source_repo": source_repo,
"seed": seed,
"query_suffix": query_suffix,
"algorithm": (
"one random.Random(seed) stream; sorted families; sorted case_id; "
"random.sample(other_99, 5)"
),
"family_count": len(family_rows),
"total_rows": len(metadata_rows),
"assignment_sha256": assignment_hash,
},
)
_write_json(
out_dir / "source_metadata" / "sampling_manifest.json",
manifest_rows,
)
shutil.copy2(
Path(__file__).resolve(),
out_dir / "source_metadata" / Path(__file__).name,
)
(out_dir / ".gitattributes").write_text(
"*.mp4 filter=lfs diff=lfs merge=lfs -text\n",
encoding="utf-8",
)
(out_dir / "README.md").write_text(
_readme(
repo_id=repo_id,
source_repo=source_repo,
seed=seed,
query_suffix=query_suffix,
total_rows=len(metadata_rows),
metadata_size=metadata_path.stat().st_size,
video_size=video_size,
),
encoding="utf-8",
)
if not validation["passed"]:
raise ValueError(f"Validation failed: {validation['errors'][:10]}")
return validation
def main() -> None:
parser = argparse.ArgumentParser(
description="Build a path-based solid hard-negative video dataset."
)
parser.add_argument("--source-dir", type=Path, required=True)
parser.add_argument("--out-dir", type=Path, required=True)
parser.add_argument(
"--repo-id",
default="gowitheflowlab/physics-bench-solid-w-hardnegs",
)
parser.add_argument(
"--source-repo",
default="gowitheflowlab/physics-bench-solid-train-2700",
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--query-suffix", default="__query_1")
parser.add_argument("--expected-rows-per-family", type=int, default=100)
parser.add_argument("--expected-total-rows", type=int, default=2700)
args = parser.parse_args()
result = build_dataset(
source_dir=args.source_dir.resolve(),
out_dir=args.out_dir.resolve(),
repo_id=args.repo_id,
source_repo=args.source_repo,
seed=args.seed,
query_suffix=args.query_suffix,
expected_rows_per_family=args.expected_rows_per_family,
expected_total_rows=args.expected_total_rows,
)
print(json.dumps(result, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()