physics-bench-fluid-train / source_metadata /build_hf_hardneg_dataset.py
Yiqi-Liu's picture
Add files using upload-large-folder tool
4746a8e verified
Raw
History Blame Contribute Delete
19.5 kB
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import hashlib
import json
import random
import shutil
from collections import defaultdict
from pathlib import Path
from typing import Any
import pyarrow as pa
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 _read_jsonl(path: Path) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
with path.open(encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if line:
rows.append(json.loads(line))
return rows
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 _full_query_row(row: dict[str, Any]) -> bool:
query_id = str(row.get("query_id", ""))
return "__full__" in query_id or query_id.endswith("__full__00")
def _read_source_full_rows(source_dir: Path, case_to_family: dict[str, str]) -> dict[str, list[dict[str, Any]]]:
family_rows: dict[str, list[dict[str, Any]]] = defaultdict(list)
seen_cases: set[str] = set()
for _scenario, path in _source_files(source_dir):
table = pq.read_table(path)
if tuple(table.column_names) != SOURCE_COLUMNS:
raise ValueError(f"Unexpected source columns in {path}: {table.column_names}")
for row in table.to_pylist():
if not _full_query_row(row):
continue
case_id = str(row["case_id"])
if case_id in seen_cases:
raise ValueError(f"Duplicate full-query row for case {case_id}")
family = case_to_family.get(case_id)
if family is None:
raise KeyError(f"No high-level family mapping for case {case_id}")
row = dict(row)
row["family"] = family
family_rows[family].append(row)
seen_cases.add(case_id)
return {family: sorted(rows, key=lambda row: str(row["case_id"])) for family, rows in sorted(family_rows.items())}
def _case_family_map(cases_jsonl: Path) -> dict[str, str]:
rows = _read_jsonl(cases_jsonl)
out: dict[str, str] = {}
for row in rows:
case_id = str(row["case_id"])
family = str(row["family"])
if case_id in out:
raise ValueError(f"Duplicate case_id in cases.jsonl: {case_id}")
out[case_id] = family
return out
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 = sorted(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])
]
return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
def _video_relpath(family: str, case_id: str) -> str:
return f"videos/{family}/{case_id}.mp4"
def _video_bytes(row: dict[str, Any]) -> bytes:
video_value = row.get("video")
if not isinstance(video_value, dict) or video_value.get("bytes") is None:
raise ValueError(f"Source row for {row.get('case_id')} does not contain embedded video bytes")
return bytes(video_value["bytes"])
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 _feature_yaml(indent: str = " ") -> list[str]:
return [
f"{indent}- name: text",
f"{indent} dtype: string",
f"{indent}- name: video",
f"{indent} dtype: string",
f"{indent}- name: hard_negative_texts",
f"{indent} list: string",
f"{indent}- name: hard_negative_videos",
f"{indent} list: string",
]
def _readme(
*,
repo_id: str,
source_repo: str,
seed: int,
total_rows: int,
metadata_size: int,
video_size: int,
family_count: int,
) -> str:
total_size = metadata_size + video_size
lines = [
"---",
"dataset_info:",
" features:",
*_feature_yaml(" "),
" 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 Fluid With Hard Negatives",
"",
f"Repository: `{repo_id}`",
"",
f"Source dataset: `{source_repo}`",
"",
"This repository uses a path-based VideoFolder-style layout for direct positive and hard-negative loading.",
"",
f"- rows: {total_rows}",
"- metadata columns: `text`, `video`, `hard_negative_texts`, `hard_negative_videos`",
"- positive text: query 1 (`__full__00`) from the source row",
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 high-level fluid 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)`",
f"- high-level fluid families: {family_count}",
"",
"## 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 requested columns. Case IDs, query IDs, and sampled assignments are retained in `source_metadata/sampling_manifest.json` for auditing.",
"",
]
return "\n".join(lines)
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]] = {}
source_by_case: dict[str, tuple[str, dict[str, Any]]] = {}
for family, rows in family_rows.items():
for row in rows:
case_id = str(row["case_id"])
source_by_path[_video_relpath(family, case_id)] = row
source_by_case[case_id] = (family, row)
output_digest = hashlib.sha256()
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}")
neg_texts = list(row["hard_negative_texts"])
neg_videos = [str(path) for path in row["hard_negative_videos"]]
if len(neg_texts) != NEGATIVE_COUNT or len(neg_videos) != NEGATIVE_COUNT:
errors.append(f"{video}: expected five hard negatives")
if len(set(neg_videos)) != NEGATIVE_COUNT:
errors.append(f"{video}: hard-negative videos are not unique")
for neg_text, neg_video in zip(neg_texts, neg_videos):
hard_negative_pairs += 1
neg_source = source_by_path.get(neg_video)
if neg_source is None:
errors.append(f"{video}: unknown hard-negative path {neg_video}")
continue
if Path(neg_video).parts[1] != family:
cross_family_count += 1
if neg_video == video:
self_negative_count += 1
if str(neg_text) != str(neg_source["raw_text"]):
errors.append(f"{video}: hard-negative text/path mismatch for {neg_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")
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 VideoFolder")
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,
cases_jsonl: Path,
out_dir: Path,
repo_id: str,
source_repo: str,
seed: int,
expected_rows_per_family: int,
expected_total_rows: int,
) -> dict[str, Any]:
if out_dir.exists() and any(out_dir.iterdir()):
raise FileExistsError(f"Output directory is not empty: {out_dir}")
case_to_family = _case_family_map(cases_jsonl)
family_rows = _read_source_full_rows(source_dir, case_to_family)
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} rows per high-level family: {bad_counts}")
if sum(map(len, family_rows.values())) != expected_total_rows:
raise ValueError(f"Expected {expected_total_rows} rows in total")
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")
out_dir.mkdir(parents=True, exist_ok=True)
metadata_rows: list[dict[str, Any]] = []
manifest_rows: list[dict[str, Any]] = []
source_video_digest = hashlib.sha256()
video_size = 0
for family in sorted(family_rows):
rows = family_rows[family]
by_case = {str(row["case_id"]): row for row in rows}
for source_row in rows:
case_id = str(source_row["case_id"])
query_id = str(source_row["query_id"])
relpath = _video_relpath(family, case_id)
video_bytes = _video_bytes(source_row)
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,
}
)
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,
)
validation.update(
{
"repo_id": repo_id,
"source_repo": source_repo,
"seed": seed,
"family_count": len(family_rows),
"rows_per_family": {family: len(rows) for family, rows in family_rows.items()},
"assignment_sha256": _assignment_digest(assignments),
"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,
"algorithm": "one random.Random(seed) stream; sorted high-level families; sorted case_id; random.sample(sorted(other_99_case_ids), 5)",
"family_count": len(family_rows),
"total_rows": len(metadata_rows),
"assignment_sha256": _assignment_digest(assignments),
},
)
_write_json(out_dir / "source_metadata" / "sampling_manifest.json", manifest_rows)
_write_json(out_dir / "source_metadata" / "family_case_counts.json", {family: len(rows) for family, rows in family_rows.items()})
shutil.copy2(cases_jsonl, out_dir / "source_metadata" / "cases.jsonl")
shutil.copy2(Path(__file__).resolve(), out_dir / "source_metadata" / "build_hf_hardneg_dataset.py")
(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,
total_rows=len(metadata_rows),
metadata_size=metadata_path.stat().st_size,
video_size=video_size,
family_count=len(family_rows),
),
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 path-based fluid hard-negative VideoFolder data.")
parser.add_argument("--source-dir", type=Path, required=True, help="Previewable HF source layout with scenario/train-*.parquet files.")
parser.add_argument("--cases-jsonl", type=Path, required=True, help="cases.jsonl containing high-level family for each case.")
parser.add_argument("--out-dir", type=Path, required=True)
parser.add_argument("--repo-id", default="gowitheflowlab/physics-bench-fluid-w-hardnegs")
parser.add_argument("--source-repo", default="gowitheflowlab/physics-bench-fluid-train-700")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--expected-rows-per-family", type=int, default=100)
parser.add_argument("--expected-total-rows", type=int, default=700)
args = parser.parse_args()
result = build_dataset(
source_dir=args.source_dir.resolve(),
cases_jsonl=args.cases_jsonl.resolve(),
out_dir=args.out_dir.resolve(),
repo_id=args.repo_id,
source_repo=args.source_repo,
seed=args.seed,
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()