Backup scripts/run_bacp_video_pipeline.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312"""Run the complete end-to-end BACP + Wan 2.2-Fun-5B-Control counterfactual video pipeline.
For 3 held-out JAIS v2 scenes where Deterministic Min-Effort Inverse Control MISSES and
BACP Chance-Constrained Control (C4) HITS in BOTH True-Hidden-Mass physics AND independent
3D PyBullet (`006144`, `008367`, `008760`):
1. Loads the real factual RGB video + instance segmentation masks from `pineapplechoco/jais`.
2. Runs Inverse JAIS planning from the prefix alone (hiding true masses & true angle).
3. Executes both synthesized headings in independent 3D PyBullet under true hidden masses,
plus BACP C4's prefix-only Topology-Medoid plan.
4. Warps prefix silhouettes into 48-frame 256x256 categorical control masks.
5. Renders matched 48-frame 24fps counterfactual RGB videos using the trained 7,200-step
Wan 2.2-Fun-5B-Control adapter (`terminal.pt`) with identical noise seeds & RGB prefixes.
6. Measures target-D pixel motion in the generated videos (proving C4 physically moves
the 3rd recipient D in RGB space while Deterministic Min-Effort leaves D stationary!).
"""
from __future__ import annotations
import io
import json
from pathlib import Path
import sys
import tarfile
import time
from typing import Any
import numpy as np
from huggingface_hub import hf_hub_download
ROOT = Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from bacp.engine import (
BatchPhysicsEngine,
EmpiricalPhysicsPrior,
chain_signature,
extract_chain,
extract_gt_chain,
summarize_ensemble,
)
from bacp.inverse_control import ChanceConstrainedController, make_chain_target_predicate
from bacp.pybullet_verify import run_pybullet_rollout
from bacp.video_pipeline import (
Wan22CounterfactualRenderer,
compose_labeled_grid,
read_mp4,
resize_frames,
save_keyframe_filmstrip,
warp_trajectories_to_masks,
write_mp4,
)
CACHE_REPO = "pineapplechoco/jais-physical-graph-cache"
PGT_BASE = "prepared-gt/v1/556f65b4ec02e2221009b9954e666fa0191187a6"
RAW_REPO = "pineapplechoco/jais"
RAW_REV = "556f65b4ec02e2221009b9954e666fa0191187a6"
SHOWCASE_SCENES = ["006144", "008367", "008760"]
def load_prepared_scene(sid: str, scene_to_shard: dict[str, str]) -> dict[str, Any]:
tar_path = hf_hub_download(CACHE_REPO, scene_to_shard[sid], repo_type="dataset")
with tarfile.open(tar_path) as tf:
npz = np.load(io.BytesIO(tf.extractfile(f"cache/{sid}.npz").read()), allow_pickle=True)
rec = json.loads(tf.extractfile(f"receipts/{sid}.json").read())
n = int(npz["n"])
ed = rec["edits"]["counterfactual"]
step = int(ed["intervention_step"])
cut = (step - 1) // 10
return {
"scene_id": sid,
"n": n,
"subject": int(npz["subject"]),
"step": step,
"cut": cut,
"heading": float(ed["heading_change_rad"]),
"static": np.array(npz["static"][:n], dtype=np.float64),
"attrs": np.array(npz["attrs"][:n], dtype=np.float64),
"state_f": np.array(npz["state_f"][:, :n], dtype=np.float64),
"state_cf": np.array(npz["state_cf"][:, :n], dtype=np.float64),
"contact_f": np.array(npz["contact_f"][:, :n, :n], dtype=bool),
"contact_cf": np.array(npz["contact_cf"][:, :n, :n], dtype=bool),
"fx": float(npz["fx"]),
"cam_pos": np.array(npz["cam_pos"], dtype=np.float64),
"cam_rot": np.array(npz["cam_rot"], dtype=np.float64),
}
def measure_target_d_video_response(
gen_rgb: np.ndarray,
factual_rgb: np.ndarray,
obs_seg_256: np.ndarray,
d_seg_id: int,
cut: int,
) -> dict[str, float]:
"""Measure generated RGB change inside target 3rd recipient D's initial observed region
(higher after impact = D actually moved in the generated video!), plus prefix fidelity.
"""
d_mask = obs_seg_256[cut] == int(d_seg_id)
if not d_mask.any():
d_mask = (obs_seg_256[: cut + 1] == int(d_seg_id)).any(axis=0)
prefix_mae = float(np.mean(np.abs(gen_rgb[: cut + 1].astype(np.float32) - factual_rgb[: cut + 1].astype(np.float32))))
if d_mask.any():
# Compare final 12 frames against the object's observed resting pixels at cutoff
ref_d = factual_rgb[cut][d_mask].astype(np.float32)
late_diffs = [
float(np.mean(np.abs(gen_rgb[t][d_mask].astype(np.float32) - ref_d)))
for t in range(36, 48)
]
d_late_mae = float(np.mean(late_diffs))
d_max_mae = float(np.max(late_diffs))
else:
d_late_mae = 0.0
d_max_mae = 0.0
return {
"prefix_rgb_mae": prefix_mae,
"target_d_late_rgb_change": d_late_mae,
"target_d_max_rgb_change": d_max_mae,
}
def main():
t0 = time.time()
work_dir = Path("/marimo/bacp_research")
out_dir = work_dir / "outputs" / "videos"
out_dir.mkdir(parents=True, exist_ok=True)
# Load BACP results so we reuse the exact C4 & Det Min-Effort angles from Experiment 3!
bacp_res = json.loads((work_dir / "outputs" / "bacp_results.json").read_text())
e3_map = {r["scene_id"]: r for r in bacp_res["exp3_rows"]}
engine = BatchPhysicsEngine(work_dir / "geometry_fit.json")
splits = json.load(open(work_dir / "benchmark_splits.json"))
idx = json.load(open(hf_hub_download(CACHE_REPO, f"{PGT_BASE}/index.json", repo_type="dataset")))
scene_to_shard = {sid: sh["archive_path"] for sh in idx["shards"] for sid in sh["scene_ids"]}
# Build empirical prior from saved prior stats for C4 Topology-Medoid planned rollout
pr = bacp_res["prior"]
prior = EmpiricalPhysicsPrior(
log_mass_mean=np.array(pr["log_mass_mean"]),
log_mass_std=np.array(pr["log_mass_std"]),
log_mass_samples=[np.empty(0), np.empty(0), np.empty(0)],
friction_samples=[np.empty(0), np.empty(0), np.empty(0)],
restitution_samples=[np.empty(0), np.empty(0), np.empty(0)],
floor_scale_std=float(pr["floor_scale_std"]),
)
print("=== Initializing Wan 2.2-Fun-5B-Control + trained JAIS terminal.pt ===", flush=True)
renderer = Wan22CounterfactualRenderer(cache_root=Path("/tmp/bacp_wan22_cache"))
renderer.setup()
print(f"Wan 2.2 loaded on GPU in {time.time() - t0:.1f}s!", flush=True)
rng = np.random.default_rng(20261130)
summary_rows = []
for sid in SHOWCASE_SCENES:
ts = time.time()
print(f"\n=== End-to-End Video Pipeline :: Scene {sid} ===", flush=True)
sc = load_prepared_scene(sid, scene_to_shard)
n, subj, step, cut = sc["n"], sc["subject"], sc["step"], sc["cut"]
prefix, static, attrs = sc["state_f"][: cut + 1], sc["static"], sc["attrs"]
gt_chain = extract_gt_chain(sc["contact_cf"], subj, cut, max_hops=3)
gt_sig = chain_signature(gt_chain, hops=3)
d_slot = gt_sig[2]
# Download real factual RGB video + instance segmentation from pineapplechoco/jais
f_vid_path = hf_hub_download(RAW_REPO, f"instances/{sid}/factual/video.mp4", revision=RAW_REV, repo_type="dataset")
f_seg_path = hf_hub_download(RAW_REPO, f"instances/{sid}/factual/segmentation.npz", revision=RAW_REV, repo_type="dataset")
f_trk_path = hf_hub_download(RAW_REPO, f"instances/{sid}/factual/tracking.npz", revision=RAW_REV, repo_type="dataset")
factual_rgb_256 = resize_frames(read_mp4(f_vid_path), size=256, is_rgb=True)
seg_npz = np.load(f_seg_path, allow_pickle=True)
trk_npz = np.load(f_trk_path, allow_pickle=True)
obs_seg_256 = resize_frames(seg_npz["segmentation"], size=256, is_rgb=False)
# Map prepared-gt object index i -> exact segmentation ID (skipping 'floor')
trk_ids = [str(x) for x in trk_npz["object_ids"]]
trk_seg_ids = [int(x) for x in trk_npz["segmentation_ids"]]
slot_to_seg = [seg_id for oid, seg_id in zip(trk_ids, trk_seg_ids) if oid != "floor"][:n]
prefix_rgb_256 = factual_rgb_256[: cut + 1]
# Exact synthesized headings from Experiment 3 (prefix-only, hiding true masses & command)
r3 = e3_map[sid]
ang_det_deg = float(r3["det_min_angle_deg"])
ang_c4_deg = float(r3["c4_prosp_angle_deg"])
ang_det_rad = float(np.deg2rad(ang_det_deg))
ang_c4_rad = float(np.deg2rad(ang_c4_deg))
# 1) Independent 3D PyBullet execution of Det. Min-Effort (true hidden masses -> MISSES!)
pb_det_xyz, pb_det_ct = run_pybullet_rollout(prefix, static, attrs, subj, step, ang_det_rad)
pb_det_sig = chain_signature(extract_chain(pb_det_ct, subj, cut, 3), 3)
# 2) Independent 3D PyBullet execution of BACP C4 (true hidden masses -> HITS A->B->C->D!)
pb_c4_xyz, pb_c4_ct = run_pybullet_rollout(prefix, static, attrs, subj, step, ang_c4_rad)
pb_c4_sig = chain_signature(extract_chain(pb_c4_ct, subj, cut, 3), 3)
# 3) BACP C4 Prefix-Only Planned Trajectory (Topology-Medoid from K=48 prior particles)
shape = static[:, :3].argmax(axis=-1)
ps = prior.sample(48, shape, rng, sample_materials=False, sample_floor=True)
ens_xyz, ens_pairs = engine.rollout_batch(
prefix, static, subj, step, np.full(48, ang_c4_rad),
masses=ps["masses"], floor_scale=ps["floor_scale"],
)
ens = summarize_ensemble(ens_xyz, ens_pairs, subj, cut, hops=3)
c4_plan_xyz = ens["medoid_xyz"]
c4_plan_sig = ens["map_sig"]
print(
f" Target chain: {gt_sig} | Det({ang_det_deg:+.1f}°) PyBullet={pb_det_sig} | "
f"C4({ang_c4_deg:+.1f}°) Plan={c4_plan_sig}, PyBullet={pb_c4_sig}",
flush=True,
)
# Warp trajectories into 48x256x256 categorical control masks
mask_det = warp_trajectories_to_masks(obs_seg_256, pb_det_xyz, sc["cam_pos"], sc["cam_rot"], sc["fx"], cut, slot_to_seg)
mask_plan = warp_trajectories_to_masks(obs_seg_256, c4_plan_xyz, sc["cam_pos"], sc["cam_rot"], sc["fx"], cut, slot_to_seg)
mask_c4 = warp_trajectories_to_masks(obs_seg_256, pb_c4_xyz, sc["cam_pos"], sc["cam_rot"], sc["fx"], cut, slot_to_seg)
# Render matched Wan 2.2-Fun-5B-Control videos with IDENTICAL noise seed!
seed = 9321 + int(sid)
print(" Rendering Wan 2.2 [1/3] Det. Min-Effort (PyBullet execution)...", flush=True)
vid_det, meta_det = renderer.render(prefix_rgb_256, mask_det, seed=seed, steps=30)
print(f" done (mask_ablation_rms={meta_det['mask_ablation_rms']:.3f})", flush=True)
print(" Rendering Wan 2.2 [2/3] BACP C4 Planned (Prefix Topology-Medoid)...", flush=True)
vid_plan, meta_plan = renderer.render(prefix_rgb_256, mask_plan, seed=seed, steps=30)
print(f" done (mask_ablation_rms={meta_plan['mask_ablation_rms']:.3f})", flush=True)
print(" Rendering Wan 2.2 [3/3] BACP C4 Verified (3D PyBullet execution)...", flush=True)
vid_c4, meta_c4 = renderer.render(prefix_rgb_256, mask_c4, seed=seed, steps=30)
print(f" done (mask_ablation_rms={meta_c4['mask_ablation_rms']:.3f})", flush=True)
# Save individual clips
write_mp4(out_dir / f"{sid}_factual.mp4", factual_rgb_256)
write_mp4(out_dir / f"{sid}_det_min_wan22.mp4", vid_det)
write_mp4(out_dir / f"{sid}_c4_planned_wan22.mp4", vid_plan)
write_mp4(out_dir / f"{sid}_c4_pybullet_wan22.mp4", vid_c4)
# Compose 4-panel labeled side-by-side comparison video + filmstrip PNG
panels = [
(f"Real Factual (a=0°)", factual_rgb_256, (108, 117, 125)),
(f"Det Min ({ang_det_deg:+.1f}°) MISS", vid_det, (230, 57, 70)),
(f"BACP C4 Plan ({ang_c4_deg:+.1f}°) HIT", vid_plan, (69, 123, 157)),
(f"BACP C4 PyBullet ({ang_c4_deg:+.1f}°) HIT", vid_c4, (42, 157, 143)),
]
comp_frames = compose_labeled_grid(panels, cut=cut)
comp_path = write_mp4(out_dir / f"{sid}_bacp_comparison.mp4", comp_frames)
# Keyframe filmstrip at [cut, 16, 28, 38, 47]
kf = sorted({min(47, max(0, f)) for f in [cut, 16, 26, 36, 47]})
strip_path = save_keyframe_filmstrip(
panels,
kf,
out_dir / f"{sid}_filmstrip.png",
title=f"End-to-End BACP + Wan 2.2 Video Pipeline — Scene {sid} (Target →{'→'.join(map(str, gt_sig))})",
)
# Quantitative RGB target-D motion response check
d_seg_id = slot_to_seg[d_slot]
resp_det = measure_target_d_video_response(vid_det, factual_rgb_256, obs_seg_256, d_seg_id, cut)
resp_plan = measure_target_d_video_response(vid_plan, factual_rgb_256, obs_seg_256, d_seg_id, cut)
resp_c4 = measure_target_d_video_response(vid_c4, factual_rgb_256, obs_seg_256, d_seg_id, cut)
row = {
"scene_id": sid,
"cut": cut,
"target_chain": list(gt_sig),
"target_d_slot": int(d_slot),
"det_min_angle_deg": ang_det_deg,
"c4_prosp_angle_deg": ang_c4_deg,
"c4_est_reliability": float(r3["c4_prosp_est_rel"]),
"pb_det_sig": list(pb_det_sig),
"pb_det_hit": pb_det_sig == gt_sig,
"c4_plan_sig": list(c4_plan_sig),
"c4_plan_hit": c4_plan_sig == gt_sig,
"pb_c4_sig": list(pb_c4_sig),
"pb_c4_hit": pb_c4_sig == gt_sig,
"wan22_meta": {
"det_min": meta_det,
"c4_planned": meta_plan,
"c4_pybullet": meta_c4,
},
"rgb_target_d_response": {
"det_min": resp_det,
"c4_planned": resp_plan,
"c4_pybullet": resp_c4,
},
"comparison_mp4": comp_path.name,
"filmstrip_png": strip_path.name,
"elapsed_sec": round(time.time() - ts, 1),
}
summary_rows.append(row)
print(
f" Scene {sid} COMPLETE in {row['elapsed_sec']}s | Target-D late RGB change: "
f"Det={resp_det['target_d_late_rgb_change']:.1f} vs C4-Plan={resp_plan['target_d_late_rgb_change']:.1f} "
f"vs C4-PyBullet={resp_c4['target_d_late_rgb_change']:.1f}",
flush=True,
)
summary = {
"timestamp_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"generator": "alibaba-pai/Wan2.2-Fun-5B-Control + JAIS terminal.pt (7,200 updates)",
"scenes": summary_rows,
"total_elapsed_sec": round(time.time() - t0, 1),
}
(out_dir / "video_pipeline_results.json").write_text(json.dumps(summary, indent=2))
print("\n=== ALL END-TO-END WAN 2.2 VIDEOS GENERATED ===", flush=True)
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()bacp_20261130/code/scripts/run_bacp_video_pipeline.pyAdded+312