CMBench_NewRecipe / prepare_requests.py
Aoraku's picture
CMBench handoff: 40 remaining videos, prompts, annotations, scripts
a8d795a verified
Raw
History Blame Contribute Delete
6.76 kB
#!/usr/bin/env python
"""Build the generation requests for a CMBench batch on any machine.
Every path is taken from the environment or the command line, and the per-method
hyper-parameters are read from `method_configs.json` in this bundle rather than
from another experiment directory, so nothing here depends on the machine the
batch was first run on.
The prompt contract is the part most easily got wrong, so it is explicit:
* the continuation prompt is the question's `generation_prompt`;
* the context is encoded with one plain description per 10s clip, scheduled at
chunk 0, 10, 20, 30, 40, 50 (10 chunks per clip at chunk_size 4);
* `context_prompt_mode` is "case", which passes that schedule through
untouched. "scene" would overwrite it with a single curated prompt and the
clipwise setting would silently not happen.
"""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
BUNDLE = Path(__file__).resolve().parent
CHUNKS_PER_CLIP = 10
def env_path(name: str, default: str) -> Path:
return Path(os.environ.get(name, default)).expanduser()
def load_prompts(source: Path) -> tuple[dict, dict, dict]:
payload = json.loads(source.read_text(encoding="utf-8"))
generation, clips, bundle_of = {}, {}, {}
for video in payload["videos"]:
bundle = video["bundle_id"]
ordered = sorted(video["clips"], key=lambda c: int(c["clip_id"]))
clips[bundle] = [c["clip_prompt"] for c in ordered]
for question in video["questions"]:
generation[question["case_id"]] = question["generation_prompt"]
bundle_of[question["case_id"]] = bundle
return generation, clips, bundle_of
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--output-root", type=Path, required=True,
help="where generated runs should be written")
parser.add_argument("--seeds", nargs="+", type=int, default=[42, 1234, 3407])
parser.add_argument("--methods", nargs="+", default=None)
parser.add_argument("--cases", nargs="+", default=None,
help="default: every case that has an annotation")
parser.add_argument("--exclude-priority", action="store_true",
help="skip the ten videos already run, leaving the 40")
parser.add_argument("--prompts", type=Path,
default=BUNDLE / "prompts/metadata_clip_and_gen.json")
parser.add_argument("--metadata", type=Path,
default=BUNDLE / "benchmark/metadata/benchmark_cases.jsonl")
parser.add_argument("--cases-root", type=Path,
default=env_path("CMBENCH_CASES_ROOT",
str(BUNDLE / "context_videos")))
parser.add_argument("--head-map", type=Path,
default=env_path("CMBENCH_HEAD_MAP", ""),
help="required by ours_fkv and forcingkv")
args = parser.parse_args()
configs = json.loads((BUNDLE / "method_configs.json").read_text())
methods = args.methods or list(configs["methods"])
generation, clips, bundle_of = load_prompts(args.prompts)
rows = [json.loads(l) for l in args.metadata.open()]
annotated = {r["case_id"]: r for r in rows}
priority = set(configs["priority_cases"])
cases = args.cases or sorted(annotated)
if args.exclude_priority:
cases = [c for c in cases if c not in priority]
written = 0
args.out.parent.mkdir(parents=True, exist_ok=True)
with args.out.open("w", encoding="utf-8") as handle:
for method in methods:
spec = configs["methods"][method]
for seed in args.seeds:
profile = f"{method}_seed{seed}"
for case in cases:
row = annotated[case]
bundle = bundle_of[case]
prompt = generation[case]
record = {
"case_id": case,
"scene_id": bundle,
"clip_file": str(args.cases_root / f"{bundle}.mp4"),
"memory_level": row["memory_level"],
"object_subtype": row["object_subtype"],
"background_motion": row["background_motion"],
"target_label": row["target_label"],
"target_aliases": row["target_aliases"],
"discard": False,
"camera_condition": "tail_motion",
"prompt_adapter": "strict",
"anchor_selection": "none",
"generation_kv_policy": "method-native",
"height": 480,
"width": 832,
"chunk_size": 4,
"sampling_shift": 5.0,
"num_output_latent_frames":
configs["output_frames"][row["object_subtype"]]["latent"],
"num_output_pixel_frames":
configs["output_frames"][row["object_subtype"]]["pixel"],
"method": method,
"seed": int(seed),
"profile_name": profile,
"output_root": str(args.output_root / profile),
"request_id": f"{profile}::{case}",
"prompt": prompt,
"prompt_en_strict": prompt,
"prompt_schedule": [{"start_chunk": 0,
"prompt": prompt}],
"context_prompt_mode": "case",
"context_prompt_schedule": [
{"start_chunk": i * CHUNKS_PER_CLIP,
"prompt": text}
for i, text in enumerate(clips[bundle])
],
}
record.update(spec["knobs"])
if spec.get("needs_head_map"):
if not str(args.head_map):
raise SystemExit(
f"{method} needs --head-map "
"(or CMBENCH_HEAD_MAP)"
)
record["head_map_file"] = str(args.head_map)
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
written += 1
print(f"{written} requests -> {args.out}")
print(f" methods: {methods}")
print(f" seeds : {args.seeds}")
print(f" cases : {len(cases)}")
if __name__ == "__main__":
main()