Sync bacp_20261130/finetune_wan22_disocc.py (fd16a59)
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589"""Real-RGB Disocclusion-Weighted Fine-Tuning of Wan 2.2-Fun-5B-Control for BACP.
Fixes the vacated-floor ghosting and muddy proxy-appearance artifacts of the Nov 27`terminal.pt` checkpoint (which was trained solely on synthetic copy-paste `prefix_proxy`targets with zero gradient on vacated-floor pixels).
Key upgrades (strictly zero-leakage: trained ONLY on `catalog['train']` scenes): 1. Real 48-frame Blender RGB supervision (both factual & counterfactual branches) from `pineapplechoco/jais` (`train` split only). 2. Explicit 4-region Disocclusion-Weighted Flow-Matching loss: - 0.35 Vacated Floor (foreground at t<=cut, background at t>cut -> kills ghosts!) - 0.35 Foreground Objects (sharp object edges, 3D lighting & shadows) - 0.15 Stable Visible Floor (prevents background drift) - 0.15 Global Uniform Anchor (maintains global exposure & coherence) 3. Mix of canonical and permuted mask palettes + realistic cutoff distribution matching JAIS (`cut` in 1..5). 4. Strict held-out evaluation before vs. after on: - 8 unseen `val` scenes (including `001936`, measuring exact region RGB MAE and `001936` Frame-29 vacated-ball-spot MAE). - All 3 BACP C4 `test` showcase scenes (`006144`, `008367`, `008760`), re-rendering the 4-panel comparison MP4s + Before-vs-After filmstrips."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutorimport copyimport jsonimport mathfrom pathlib import Pathimport randomimport sysimport timefrom typing import Any
import numpy as npimport torchfrom huggingface_hub import hf_hub_download
ROOT = Path(__file__).resolve().parent.parentif 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.pybullet_verify import run_pybullet_rolloutfrom bacp.video_pipeline import ( PALETTE, Wan22CounterfactualRenderer, color_mask, compose_labeled_grid, read_mp4, resize_frames, save_keyframe_filmstrip, shift_sigma, warp_trajectories_to_masks, write_mp4,)from scripts.run_bacp_video_pipeline import ( CACHE_REPO, PGT_BASE, RAW_REPO, RAW_REV, SHOWCASE_SCENES, load_prepared_scene, measure_target_d_video_response,)
VAL_BENCHMARK_SCENES = ["001936", "000007", "000015", "000024", "000033", "000044", "000051", "000063"]
def _load_raw_branch(sid: str, branch: str) -> tuple[np.ndarray, np.ndarray, list[int]]: """Download and decode a real 48x256x256 RGB video + remapped categorical mask (1..K).""" vid_p = hf_hub_download(RAW_REPO, f"instances/{sid}/{branch}/video.mp4", revision=RAW_REV, repo_type="dataset") seg_p = hf_hub_download(RAW_REPO, f"instances/{sid}/{branch}/segmentation.npz", revision=RAW_REV, repo_type="dataset") trk_p = hf_hub_download(RAW_REPO, f"instances/{sid}/{branch}/tracking.npz", revision=RAW_REV, repo_type="dataset")
rgb_256 = resize_frames(read_mp4(vid_p), size=256, is_rgb=True) seg_raw = np.load(seg_p, allow_pickle=True)["segmentation"] seg_256 = resize_frames(seg_raw, size=256, is_rgb=False) trk = np.load(trk_p, allow_pickle=True) names = [str(x) for x in trk["object_ids"]] sids = [int(x) for x in trk["segmentation_ids"]] slot_ids = [s for nm, s in zip(names, sids) if nm != "floor"]
# Map raw segmentation IDs to canonical 1..len(slot_ids) (floor = 0) mx = max(int(seg_256.max()), max(slot_ids)) if slot_ids else int(seg_256.max()) lut = np.zeros(mx + 1, dtype=np.uint8) for idx_i, seg_id in enumerate(slot_ids, start=1): lut[seg_id] = idx_i labels = lut[seg_256] return rgb_256, labels, slot_ids
def _pool_mask_to_latent(mask_48_256: np.ndarray) -> np.ndarray: """Pool a (48, 256, 256) float mask into Wan 2.2's (13, 16, 16) latent grid.""" # Pad frame 47 -> 49 frames to match Wan 2.2 VAE temporal framing (1 + 12*4 = 49) padded = np.concatenate([mask_48_256, mask_48_256[-1:]], axis=0) # (49, 256, 256) # Temporal: frame 0 -> latent 0; frames 1..48 -> 12 groups of 4 t_lat = np.zeros((13, 256, 256), dtype=np.float32) t_lat[0] = padded[0] t_lat[1:] = padded[1:].reshape(12, 4, 256, 256).mean(axis=1) # Spatial: 256x256 -> 16x16 (16x16 patch average) pooled = t_lat.reshape(13, 16, 16, 16, 16).mean(axis=(2, 4)) return pooled
def _build_region_weights(labels_48: np.ndarray, cut: int) -> np.ndarray: """Build 4-channel normalized latent region weights (4, 13, 16, 16) for disocclusion training.
Channels: 0: Vacated floor (foreground at any t<=cut, background at t>cut) 1: Foreground objects (labels > 0 at t>cut) 2: Stable visible floor (background at all t<=cut, background at t>cut) 3: Global uniform anchor (all tokens for latent t >= 1) """ n_pref = cut + 1 fg_pref = (labels_48[:n_pref] > 0).any(axis=0) # (256, 256) after = np.zeros((48, 1, 1), dtype=bool) after[n_pref:] = True
is_fg = (labels_48 > 0) & after is_bg = (labels_48 == 0) & after is_vacated = is_bg & fg_pref[None, :, :] is_stable_floor = is_bg & (~fg_pref[None, :, :])
w0 = _pool_mask_to_latent(is_vacated.astype(np.float32)) w1 = _pool_mask_to_latent(is_fg.astype(np.float32)) w2 = _pool_mask_to_latent(is_stable_floor.astype(np.float32)) w3 = np.ones((13, 16, 16), dtype=np.float32)
regs = np.stack([w0, w1, w2, w3], axis=0) # (4, 13, 16, 16) regs[:, 0] = 0.0 # Latent frame 0 is clamped to observed frame 0 for c in range(4): s = float(regs[c].sum()) if s > 1e-8: regs[c] /= s else: regs[c] = regs[3] / max(float(regs[3].sum()), 1e-8) return regs
def _evaluate_video_regions( gen_rgb: np.ndarray, gt_rgb: np.ndarray, gt_labels: np.ndarray, cut: int,) -> dict[str, float]: """Compute exact per-region RGB MAE (0-255 scale) over post-cutoff frames t > cut.""" n_pref = cut + 1 diff = np.abs(gen_rgb[n_pref:].astype(np.float32) - gt_rgb[n_pref:].astype(np.float32)).mean(axis=-1) # (T', H, W) prefix_mae = float(np.abs(gen_rgb[:n_pref].astype(np.float32) - gt_rgb[:n_pref].astype(np.float32)).mean())
pref_fg = (gt_labels[:n_pref] > 0).any(axis=0) # (H, W) post_lbl = gt_labels[n_pref:] # (T', H, W) post_bg = post_lbl == 0 post_fg = post_lbl > 0
# Identify moving vs stationary objects (IoU < 0.85 across post frames) n_obj = int(gt_labels.max()) moved_mask = np.zeros_like(post_fg) static_mask = np.zeros_like(post_fg) for oid in range(1, n_obj + 1): m0 = gt_labels[cut] == oid mt = post_lbl == oid if not mt.any(): continue inter = (mt & m0[None]).sum(axis=(1, 2)) union = np.maximum((mt | m0[None]).sum(axis=(1, 2)), 1) min_iou = float((inter / union).min()) if min_iou < 0.85: moved_mask |= mt else: static_mask |= mt
vacated = post_bg & pref_fg[None] stable_floor = post_bg & (~pref_fg[None])
def _mean(m: np.ndarray) -> float: return float(diff[m].mean()) if m.any() else float("nan")
mse = float(((gen_rgb[n_pref:].astype(np.float32) - gt_rgb[n_pref:].astype(np.float32)) ** 2).mean()) psnr = float(20.0 * math.log10(255.0 / max(math.sqrt(mse), 1e-6)))
return { "prefix_mae": prefix_mae, "whole_frame_mae": float(diff.mean()), "psnr_db": psnr, "stable_floor_mae": _mean(stable_floor), "vacated_floor_mae": _mean(vacated), "static_obj_mae": _mean(static_mask), "moved_obj_mae": _mean(moved_mask), }
def _scene_001936_ball_spot_mae(gen_rgb: np.ndarray, gt_rgb: np.ndarray) -> float: """Exact Nov 29 benchmark metric: Frame 29 MAE inside circle (x=79, y=109, r=8).""" yy, xx = np.ogrid[:256, :256] spot = (xx - 79) ** 2 + (yy - 109) ** 2 <= 8 ** 2 d = np.abs(gen_rgb[29].astype(np.float32) - gt_rgb[29].astype(np.float32)).mean(axis=-1) return float(d[spot].mean())
def main() -> None: t_start = time.time() work_dir = Path("/marimo/bacp_research") ft_dir = work_dir / "outputs" / "wan22_disocc_ft" ft_dir.mkdir(parents=True, exist_ok=True) vid_dir = work_dir / "outputs" / "videos_disocc" vid_dir.mkdir(parents=True, exist_ok=True)
splits = json.load(open(work_dir / "benchmark_splits.json")) train_pool = list(splits["catalog"]["train"]) val_pool = list(splits["catalog"]["val"]) test_pool = set(splits["catalog"]["test"])
# Pick 8 held-out val scenes (starting with 001936) strictly outside train val_scenes = ["001936"] + [s for s in val_pool if s != "001936"][:7] assert not (set(val_scenes) & set(train_pool)), "Leakage detected in val_scenes!" assert not (set(SHOWCASE_SCENES) & set(train_pool)), "Leakage detected in showcase scenes!"
# Select 280 diverse training scenes strictly from catalog['train'] rng = np.random.default_rng(20261130) n_train_scenes = 280 train_scenes = [train_pool[i] for i in rng.choice(len(train_pool), size=n_train_scenes, replace=False)]
print(f"=== [1/5] Downloading {n_train_scenes} real 48-frame train scenes (counterfactual + factual) ===", flush=True) t0 = time.time() raw_items: list[tuple[str, str, np.ndarray, np.ndarray]] = []
def _fetch_train(sid: str): out = [] for br in ("counterfactual", "factual"): try: rgb, lbl, _ = _load_raw_branch(sid, br) if rgb.shape == (48, 256, 256, 3) and lbl.shape == (48, 256, 256) and int(lbl.max()) >= 1: out.append((sid, br, rgb, lbl)) except Exception: pass return out
with ThreadPoolExecutor(max_workers=12) as ex: for res in ex.map(_fetch_train, train_scenes): raw_items.extend(res) print(f"Downloaded & decoded {len(raw_items)} real 48-frame Blender videos in {time.time() - t0:.1f}s!", flush=True)
# Also download held-out val benchmark scenes (counterfactual branch) print(f"=== [2/5] Loading {len(val_scenes)} held-out val benchmark scenes ===", flush=True) idx_pgt = 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_pgt["shards"] for sid in sh["scene_ids"]}
val_data = [] for sid in val_scenes: rgb, lbl, _ = _load_raw_branch(sid, "counterfactual") cut = 4 if sid in scene_to_shard: sc_meta = load_prepared_scene(sid, scene_to_shard) cut = int(sc_meta["cut"]) val_data.append({"scene_id": sid, "rgb": rgb, "labels": lbl, "cut": cut}) print(f"Val scenes ready: {[(v['scene_id'], v['cut']) for v in val_data]}", flush=True)
# Load Wan 2.2-Fun-5B-Control + Nov 27 terminal.pt print("=== [3/5] Loading Wan 2.2-Fun-5B-Control + Nov 27 terminal.pt ===", flush=True) renderer = Wan22CounterfactualRenderer(cache_root=Path("/tmp/bacp_wan22_cache")) renderer.setup() native = renderer.native tr, vae, emb, params = renderer.tr, renderer.vae, renderer.emb, renderer.trainable
# Evaluate BASELINE terminal.pt on the 8 held-out val scenes BEFORE fine-tuning! print("=== Evaluating BASELINE terminal.pt on 8 held-out val scenes ===", flush=True) baseline_val_rows = [] baseline_001936_vid = None for item in val_data: sid, gt_rgb, gt_lbl, cut = item["scene_id"], item["rgb"], item["labels"], item["cut"] seed = 9321 + int(sid) gen, meta = renderer.render(gt_rgb[: cut + 1], gt_lbl, seed=seed, steps=30) metrics = _evaluate_video_regions(gen, gt_rgb, gt_lbl, cut) metrics["scene_id"] = sid metrics["cut"] = cut metrics["mask_ablation_rms"] = meta["mask_ablation_rms"] if sid == "001936": metrics["spot_frame29_mae"] = _scene_001936_ball_spot_mae(gen, gt_rgb) baseline_001936_vid = gen.copy() baseline_val_rows.append(metrics) def _agg(rows): keys = ["prefix_mae", "whole_frame_mae", "psnr_db", "stable_floor_mae", "vacated_floor_mae", "static_obj_mae", "moved_obj_mae", "mask_ablation_rms"] out = {} for k in keys: vals = [r[k] for r in rows if k in r and math.isfinite(r[k])] out[k] = float(np.mean(vals)) if vals else float("nan") for r in rows: if r["scene_id"] == "001936": out["scene_001936_spot_frame29_mae"] = r["spot_frame29_mae"] return out
base_summary = _agg(baseline_val_rows) print("BASELINE terminal.pt val summary:", json.dumps(base_summary, indent=2), flush=True)
# Pre-encode all training clips with Wan 2.2 VAE once (keeps training blazing fast!) print(f"=== [4/5] Pre-encoding {len(raw_items)} real 48-frame videos into VAE latents ===", flush=True) t_enc = time.time() encoded_bank: list[dict[str, torch.Tensor]] = [] cut_choices = [1, 2, 3, 4, 5] with torch.no_grad(): for i, (sid, br, rgb_256, lbl_256) in enumerate(raw_items): cut = int(cut_choices[i % len(cut_choices)]) n_pref = cut + 1 # 40% canonical PALETTE order (matching BACP inference), 60% permuted palette (generalization) if i % 5 < 2: pal = PALETTE else: pal = PALETTE[rng.permutation(len(PALETTE))] src_z, vis = native.source(vae, rgb_256[:n_pref]) ctrl_z = native.encode(vae, native.frames(color_mask(lbl_256, pal))) tgt_z = native.encode(vae, native.frames(rgb_256)) reg_w = torch.from_numpy(_build_region_weights(lbl_256, cut)) encoded_bank.append({ "src": src_z.cpu(), "vis": vis.cpu(), "ctrl": ctrl_z.cpu(), "tgt": tgt_z.cpu(), "weights": reg_w, }) if (i + 1) % 100 == 0 or (i + 1) == len(raw_items): print(f" encoded {i + 1}/{len(raw_items)} ({time.time() - t_enc:.1f}s)", flush=True) del raw_items
# Fine-tune LoRA + PatchDelta with Disocclusion-Weighted Flow-Matching Loss n_steps = 900 batch_size = 2 reg_coeffs = torch.tensor([0.35, 0.35, 0.15, 0.15], device="cuda", dtype=torch.float32)
lora_params = [p for k, p in params.items() if "lora_" in k] patch_params = [params["patch_embedding.additional.weight"]] opt = torch.optim.AdamW( [ {"params": lora_params, "lr": 8e-5}, {"params": patch_params, "lr": 1.6e-4}, ], weight_decay=1e-4, ) sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=n_steps, eta_min=8e-6)
# Track EMA weights for smoother, artifact-free video synthesis ema_state = {k: v.detach().float().clone() for k, v in params.items()} ema_decay = 0.992
# RTX PRO 6000 has 102 GB VRAM -> disable gradient checkpointing for ~2x speedup! tr.gradient_checkpointing = False tr.train()
print(f"=== Fine-tuning Wan 2.2 for {n_steps} steps (batch_size={batch_size}, real RGB + disocclusion loss) ===", flush=True) t_tr = time.time() loss_history = [] order_rng = np.random.default_rng(42026)
for step_i in range(1, n_steps + 1): opt.zero_grad(set_to_none=True) step_loss = 0.0 step_parts = np.zeros(4, dtype=np.float64)
for b_idx in range(batch_size): ex = encoded_bank[int(order_rng.integers(0, len(encoded_bank)))] x = ex["tgt"].cuda().float() src = ex["src"].cuda() vis = ex["vis"].cuda() ctrl = ex["ctrl"].cuda() w = ex["weights"].cuda()
# Logit-normal shifted sigma schedule matching Wan 2.2 Flow Matching u = float(1.0 / (1.0 + math.exp(-float(order_rng.standard_normal())))) sigma = float(shift_sigma(np.array([u]))[0]) noise = torch.randn_like(x) noisy = (1.0 - sigma) * x + sigma * noise
v_pred = native.forward(tr, emb, noisy, src, vis, ctrl, sigma) per_tok = (v_pred - (noise - x)).square().mean(dim=(0, 1)) # (13, 16, 16) parts = (w * per_tok.unsqueeze(0)).sum(dim=(1, 2, 3)) # (4,) loss = (parts * reg_coeffs).sum() / batch_size loss.backward() step_loss += float(loss.detach()) step_parts += parts.detach().cpu().numpy() / batch_size
grad_norm = float(torch.nn.utils.clip_grad_norm_(list(params.values()), 1.0)) opt.step() sched.step()
with torch.no_grad(): for k, p in params.items(): ema_state[k].mul_(ema_decay).add_(p.detach().float(), alpha=1.0 - ema_decay)
loss_history.append({ "step": step_i, "loss": step_loss, "vacated_loss": float(step_parts[0]), "fg_loss": float(step_parts[1]), "floor_loss": float(step_parts[2]), "global_loss": float(step_parts[3]), "grad_norm": grad_norm, })
if step_i == 1 or step_i % 50 == 0 or step_i == n_steps: recent = loss_history[-50:] avg_l = float(np.mean([r["loss"] for r in recent])) avg_vac = float(np.mean([r["vacated_loss"] for r in recent])) avg_fg = float(np.mean([r["fg_loss"] for r in recent])) rate = step_i / max(time.time() - t_tr, 1e-6) print( f" step {step_i:4d}/{n_steps} | loss={avg_l:.4f} (vacated={avg_vac:.4f}, fg={avg_fg:.4f}) " f"| lr={sched.get_last_lr()[0]:.2e} | {rate:.2f} steps/s", flush=True, )
# Swap in EMA weights for clean inference & save checkpoint with torch.no_grad(): for k, p in params.items(): p.copy_(ema_state[k].to(device=p.device, dtype=p.dtype)) tr.eval()
ckpt_out = ft_dir / "bacp_wan22_disocc_ema.pt" torch.save( { "kind": "bacp_wan22_disocc_ema", "base_checkpoint": "wan22_fun5b_control_7200_20261127/training/model/terminal.pt", "n_train_videos": len(encoded_bank), "n_steps": n_steps, "batch_size": batch_size, "region_weights": [0.35, 0.35, 0.15, 0.15], "state": {k: v.detach().cpu() for k, v in params.items()}, }, ckpt_out, ) print(f"Saved fine-tuned EMA checkpoint to {ckpt_out}", flush=True)
# Evaluate FINE-TUNED model on the exact same 8 held-out val scenes! print("=== [5/5] Evaluating FINE-TUNED bacp_wan22_disocc_ema on 8 held-out val scenes ===", flush=True) ft_val_rows = [] ft_001936_vid = None gt_001936_vid = None cut_001936 = 4 for item in val_data: sid, gt_rgb, gt_lbl, cut = item["scene_id"], item["rgb"], item["labels"], item["cut"] seed = 9321 + int(sid) gen, meta = renderer.render(gt_rgb[: cut + 1], gt_lbl, seed=seed, steps=30) metrics = _evaluate_video_regions(gen, gt_rgb, gt_lbl, cut) metrics["scene_id"] = sid metrics["cut"] = cut metrics["mask_ablation_rms"] = meta["mask_ablation_rms"] if sid == "001936": metrics["spot_frame29_mae"] = _scene_001936_ball_spot_mae(gen, gt_rgb) ft_001936_vid = gen.copy() gt_001936_vid = gt_rgb.copy() cut_001936 = cut ft_val_rows.append(metrics)
ft_summary = _agg(ft_val_rows) print("FINE-TUNED bacp_wan22_disocc_ema val summary:", json.dumps(ft_summary, indent=2), flush=True)
# Save 001936 Before-vs-After comparison MP4 & filmstrip! if baseline_001936_vid is not None and ft_001936_vid is not None and gt_001936_vid is not None: p001936 = [ ("Real Blender GT", gt_001936_vid, (108, 117, 125)), ("Old terminal.pt (Proxy FT)", baseline_001936_vid, (230, 57, 70)), ("New Disocc Real-RGB FT", ft_001936_vid, (42, 157, 143)), ] write_mp4(vid_dir / "001936_before_after_comparison.mp4", compose_labeled_grid(p001936, cut=cut_001936)) save_keyframe_filmstrip( p001936, [cut_001936, 12, 22, 29, 44], vid_dir / "001936_before_after_filmstrip.png", title=( f"Scene 001936 Disocclusion Benchmark — Old terminal.pt " f"(spot MAE {base_summary['scene_001936_spot_frame29_mae']:.2f}) vs. " f"New Real-RGB Disocc FT (spot MAE {ft_summary['scene_001936_spot_frame29_mae']:.2f})" ), )
# Re-render all 3 BACP C4 showcase test scenes (006144, 008367, 008760) with the new checkpoint! print("=== Re-rendering 3 BACP C4 showcase test scenes with fine-tuned Wan 2.2 ===", flush=True) 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") 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"]), )
showcase_rows = [] rng_sc = np.random.default_rng(20261130) for sid in SHOWCASE_SCENES: 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_sig = chain_signature(extract_gt_chain(sc["contact_cf"], subj, cut, max_hops=3), hops=3) d_slot = gt_sig[2]
factual_rgb_256, obs_seg_256, slot_to_seg = _load_raw_branch(sid, "factual") slot_to_seg_norm = list(range(1, n + 1)) prefix_rgb_256 = factual_rgb_256[: cut + 1]
r3 = e3_map[sid] ang_det_deg = float(r3["det_min_angle_deg"]) ang_c4_deg = float(r3["c4_prosp_angle_deg"]) pb_det_xyz, pb_det_ct = run_pybullet_rollout(prefix, static, attrs, subj, step, float(np.deg2rad(ang_det_deg))) pb_c4_xyz, pb_c4_ct = run_pybullet_rollout(prefix, static, attrs, subj, step, float(np.deg2rad(ang_c4_deg)))
shape = static[:, :3].argmax(axis=-1) ps = prior.sample(48, shape, rng_sc, sample_materials=False, sample_floor=True) ens_xyz, ens_pairs = engine.rollout_batch( prefix, static, subj, step, np.full(48, float(np.deg2rad(ang_c4_deg))), 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"]
mask_det = warp_trajectories_to_masks(obs_seg_256, pb_det_xyz, sc["cam_pos"], sc["cam_rot"], sc["fx"], cut, slot_to_seg_norm) mask_plan = warp_trajectories_to_masks(obs_seg_256, c4_plan_xyz, sc["cam_pos"], sc["cam_rot"], sc["fx"], cut, slot_to_seg_norm) mask_c4 = warp_trajectories_to_masks(obs_seg_256, pb_c4_xyz, sc["cam_pos"], sc["cam_rot"], sc["fx"], cut, slot_to_seg_norm)
seed = 9321 + int(sid) vid_det, meta_det = renderer.render(prefix_rgb_256, mask_det, seed=seed, steps=30) vid_plan, meta_plan = renderer.render(prefix_rgb_256, mask_plan, seed=seed, steps=30) vid_c4, meta_c4 = renderer.render(prefix_rgb_256, mask_c4, seed=seed, steps=30)
panels = [ ("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)), ] write_mp4(vid_dir / f"{sid}_bacp_comparison_disocc.mp4", compose_labeled_grid(panels, cut=cut)) kf = sorted({min(47, max(0, f)) for f in [cut, 16, 26, 36, 47]}) save_keyframe_filmstrip( panels, kf, vid_dir / f"{sid}_filmstrip_disocc.png", title=f"Disocclusion-FT Wan 2.2 + BACP — Scene {sid} (Target →{'→'.join(map(str, gt_sig))})", ) showcase_rows.append({ "scene_id": sid, "cut": cut, "target_chain": list(gt_sig), "det_min_angle_deg": ang_det_deg, "c4_prosp_angle_deg": ang_c4_deg, "wan22_meta": {"det_min": meta_det, "c4_planned": meta_plan, "c4_pybullet": meta_c4}, "rgb_response": { "det_min": measure_target_d_video_response(vid_det, factual_rgb_256, obs_seg_256, d_slot + 1, cut), "c4_planned": measure_target_d_video_response(vid_plan, factual_rgb_256, obs_seg_256, d_slot + 1, cut), "c4_pybullet": measure_target_d_video_response(vid_c4, factual_rgb_256, obs_seg_256, d_slot + 1, cut), }, "comparison_mp4": f"{sid}_bacp_comparison_disocc.mp4", "filmstrip_png": f"{sid}_filmstrip_disocc.png", }) print(f" Rendered {sid} (mask_ablation_rms={meta_c4['mask_ablation_rms']:.3f})", flush=True)
summary_payload = { "timestamp_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "total_elapsed_sec": round(time.time() - t_start, 1), "n_train_videos": len(encoded_bank), "n_steps": n_steps, "batch_size": batch_size, "baseline_val_summary": base_summary, "finetuned_val_summary": ft_summary, "baseline_val_rows": baseline_val_rows, "finetuned_val_rows": ft_val_rows, "showcase_scenes": showcase_rows, "final_train_loss_50": float(np.mean([r["loss"] for r in loss_history[-50:]])), "initial_train_loss_50": float(np.mean([r["loss"] for r in loss_history[:50]])), } (ft_dir / "disocc_ft_results.json").write_text(json.dumps(summary_payload, indent=2)) print(f"\n=== ALL DONE in {time.time() - t_start:.1f}s! ===", flush=True) print("BEFORE (terminal.pt) vs AFTER (bacp_wan22_disocc_ema):", flush=True) for k in ["vacated_floor_mae", "stable_floor_mae", "moved_obj_mae", "static_obj_mae", "whole_frame_mae", "psnr_db", "scene_001936_spot_frame29_mae"]: print(f" {k:30s}: {base_summary.get(k, float('nan')):.3f} -> {ft_summary.get(k, float('nan')):.3f}", flush=True)
if __name__ == "__main__": main()bacp_20261130/finetune_wan22_disocc.pyAdded+589