File size: 6,998 Bytes
67e2a29 | 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 | #!/usr/bin/env python3
"""Build a v2 of a *-w-hardnegs dataset that keeps the v1 positive/negative pairing
byte-for-byte and only rewrites `text` / `hard_negative_texts` using the eval-aligned
raw query generator of the corresponding domain.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import sys
from collections import Counter
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
FLUID_ROOT = Path("/mnt/iusers01/fatpou01/compsci01/r90629yl/src/Physics_bench/physics_bench_fluid")
SOLID_ROOT = Path("/mnt/iusers01/fatpou01/compsci01/r90629yl/src/Physics_bench/physics_bench_solid")
OPTICS_ROOT = Path("/mnt/iusers01/fatpou01/compsci01/r90629yl/src/Physics_bench/physics_bench_optics")
DYNAMICS_ROOT = Path("/mnt/iusers01/fatpou01/compsci01/r90629yl/src/Physics_bench/physics_bench_dynamics")
def _load_module(path: Path, name: str):
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def make_text_fn(domain: str):
if domain == "optics":
sys.path.insert(0, str(OPTICS_ROOT / "src"))
from physics_bench_optics import dataset as ds
def fn(case):
return ds._parsed_query_text(case, ds._case_tokens(case))
return fn, ds.QUERY_VERSION
if domain == "fluid":
exp = _load_module(FLUID_ROOT / "scripts" / "export_hf_fluid_test_format.py", "fluid_export")
return exp._eval_parsed_query_text, exp.EVAL_QUERY_VERSION
if domain == "solid":
sys.path.insert(0, str(SOLID_ROOT / "src"))
from physics_bench_solid import release_pipeline as rp
return rp._eval_parsed_query_text, rp.EVAL_QUERY_VERSION
if domain == "dynamics":
sys.path.insert(0, str(DYNAMICS_ROOT / "src"))
from physics_bench_dynamics import parsed_query as pqm
return pqm.generate_template_text, pqm.PARSED_QUERY_VERSION
raise ValueError(domain)
def disambiguate(domain: str, texts: dict, cases: dict) -> dict:
if domain == "dynamics":
sys.path.insert(0, str(DYNAMICS_ROOT / "src"))
from physics_bench_dynamics import parsed_query as pqm
return pqm.disambiguate_texts(texts, cases)
if domain == "optics":
sys.path.insert(0, str(OPTICS_ROOT / "src"))
from physics_bench_optics import dataset as ds
case_vals = {cid: ds._case_tokens(cases[cid]) for cid in texts}
return ds.disambiguate_parsed_texts(texts, case_vals)
return texts
def case_id_from_path(path: str) -> str:
return path.split("/")[-1].rsplit(".", 1)[0]
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--domain", required=True, choices=["optics", "fluid", "solid", "dynamics"])
ap.add_argument("--v1-metadata", required=True, help="metadata.parquet downloaded from the v1 repo")
ap.add_argument("--train-cases", required=True, help="train cases.jsonl / release_cases.jsonl")
ap.add_argument("--out-dir", required=True)
ap.add_argument("--benchmark-cases", default=None,
help="optional benchmark cases file; asserts train params differ (solid safety check)")
args = ap.parse_args()
text_fn, version = make_text_fn(args.domain)
cases: dict[str, dict] = {}
with open(args.train_cases) as fh:
for line in fh:
c = json.loads(line)
cases[str(c["case_id"])] = c
if args.benchmark_cases:
bench: dict[str, dict] = {}
with open(args.benchmark_cases) as fh:
for line in fh:
c = json.loads(line)
bench[str(c["case_id"])] = c
shared = sorted(set(cases) & set(bench))
identical = [c for c in shared if cases[c].get("params") == bench[c].get("params")]
print(f"[safety] case_id shared with benchmark: {len(shared)}; identical params: {len(identical)}")
if identical:
raise ValueError(f"train metadata appears to be the benchmark set, e.g. {identical[:3]}")
table = pq.read_table(args.v1_metadata)
rows = table.to_pylist()
referenced: list[str] = []
for r in rows:
referenced.append(case_id_from_path(r["video"]))
referenced.extend(case_id_from_path(v) for v in r["hard_negative_videos"])
missing = sorted({c for c in referenced if c not in cases})
if missing:
raise ValueError(f"{len(missing)} referenced case_ids missing from train metadata, e.g. {missing[:3]}")
texts: dict[str, str] = {cid: text_fn(cases[cid]) for cid in sorted(set(referenced))}
texts = disambiguate(args.domain, texts, cases)
new_text = [texts[case_id_from_path(r["video"])] for r in rows]
new_negs = [[texts[case_id_from_path(v)] for v in r["hard_negative_videos"]] for r in rows]
dupes = {k: v for k, v in Counter(new_text).items() if v > 1}
if dupes:
raise ValueError(f"positive texts not unique: {len(dupes)} collisions")
names = table.schema.names
out_table = table.set_column(names.index("text"), table.schema.field(names.index("text")),
pa.array(new_text, type=pa.string()))
out_table = out_table.set_column(names.index("hard_negative_texts"),
out_table.schema.field(names.index("hard_negative_texts")),
pa.array(new_negs, type=out_table.schema.field(names.index("hard_negative_texts")).type))
# pairing must be untouched
assert out_table.column("video").to_pylist() == table.column("video").to_pylist()
assert out_table.column("hard_negative_videos").to_pylist() == table.column("hard_negative_videos").to_pylist()
pair_repr = json.dumps(
[[r["video"], r["hard_negative_videos"]] for r in rows], separators=(",", ":"), sort_keys=False
)
pairing_sha = hashlib.sha256(pair_repr.encode()).hexdigest()
out = Path(args.out_dir)
out.mkdir(parents=True, exist_ok=True)
pq.write_table(out_table, out / "metadata.parquet", compression="snappy", write_page_index=True)
summary = {
"domain": args.domain,
"text_version": version,
"text_style": "eval-aligned raw structured query",
"rows": len(rows),
"distinct_cases": len(texts),
"negatives_per_case": len(rows[0]["hard_negative_videos"]),
"pairing_identical_to_v1": True,
"pairing_sha256": pairing_sha,
"unique_positive_texts": len(set(new_text)),
"v1_metadata": args.v1_metadata,
"train_cases": args.train_cases,
}
(out / "v2_manifest.json").write_text(json.dumps(summary, indent=2))
sample = {"positive": new_text[0], "negatives": new_negs[0][:2],
"video": rows[0]["video"], "negative_videos": rows[0]["hard_negative_videos"][:2]}
(out / "sample.json").write_text(json.dumps(sample, indent=2))
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
|