Backup bacp/video_pipeline.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374"""End-to-end BACP counterfactual video generation via Wan 2.2-Fun-5B-Control."""
from __future__ import annotations
from fractions import Fraction
import hashlib
import json
import math
from pathlib import Path
import subprocess
import sys
from typing import Any
import av
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import torch
import torch.nn.functional as F
PALETTE = np.array(
[
[230, 25, 75],
[60, 180, 75],
[255, 225, 25],
[0, 130, 200],
[245, 130, 48],
[145, 30, 180],
[70, 240, 240],
[240, 50, 230],
[170, 110, 40],
[128, 128, 0],
],
dtype=np.uint8,
)
def shift_sigma(x: np.ndarray) -> np.ndarray:
return 3.0 * x / (1.0 + 2.0 * x)
def color_mask(labels: np.ndarray, palette: np.ndarray = PALETTE) -> np.ndarray:
lut = np.concatenate([np.zeros((1, 3), dtype=np.uint8), palette], axis=0)
return lut[labels]
def resize_frames(arr: np.ndarray, size: int = 256, is_rgb: bool = True) -> np.ndarray:
filt = Image.Resampling.BOX if is_rgb else Image.Resampling.NEAREST
return np.stack([np.asarray(Image.fromarray(f).resize((size, size), filt)) for f in arr])
def read_mp4(path: str | Path) -> np.ndarray:
with av.open(str(path)) as container:
frames = [f.to_ndarray(format="rgb24") for f in container.decode(video=0)]
return np.stack(frames, axis=0)
def write_mp4(path: str | Path, frames: np.ndarray, fps: int = 24, crf: int = 16) -> Path:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
h, w = int(frames.shape[1]), int(frames.shape[2])
tmp = path.with_suffix(".tmp.mp4")
with av.open(str(tmp), "w") as container:
stream = container.add_stream("libx264", rate=fps)
stream.width = w
stream.height = h
stream.pix_fmt = "yuv420p"
stream.options = {"crf": str(crf), "preset": "fast"}
for frame in frames:
vf = av.VideoFrame.from_ndarray(np.ascontiguousarray(frame, dtype=np.uint8), format="rgb24")
for packet in stream.encode(vf):
container.mux(packet)
for packet in stream.encode():
container.mux(packet)
tmp.replace(path)
return path
def project_3d_to_pixels(
pts_xyz: np.ndarray,
cam_pos: np.ndarray,
cam_rot: np.ndarray,
fx_512: float,
img_size: int = 256,
) -> tuple[np.ndarray, np.ndarray]:
"""Project world XYZ (..., 3) -> pixel (u, v) in [0, img_size] and camera depth."""
scale = img_size / 512.0
fx = fx_512 * scale
cx = cy = img_size / 2.0
pc = (np.asarray(pts_xyz, dtype=np.float64) - cam_pos) @ cam_rot
depth = np.maximum(-pc[..., 2], 1e-4)
u = cx + fx * pc[..., 0] / depth
v = cy - fx * pc[..., 1] / depth
return np.stack([u, v], axis=-1), depth
def _warp_binary_mask(
mask_hw: np.ndarray,
center_xy: tuple[float, float],
scale: float,
shift_xy: tuple[float, float],
) -> np.ndarray:
"""Nearest-neighbor inverse warp of a single [H, W] bool mask about center_xy."""
H, W = mask_hw.shape
ys, xs = torch.meshgrid(
torch.arange(H, dtype=torch.float32),
torch.arange(W, dtype=torch.float32),
indexing="ij",
)
cx, cy = float(center_xy[0]), float(center_xy[1])
sx, sy = float(shift_xy[0]), float(shift_xy[1])
sc = max(float(scale), 0.15)
src_x = (xs - cx - sx) / sc + cx
src_y = (ys - cy - sy) / sc + cy
grid = torch.stack(
[(src_x + 0.5) / W * 2.0 - 1.0, (src_y + 0.5) / H * 2.0 - 1.0],
dim=-1,
).unsqueeze(0)
inp = torch.from_numpy(mask_hw.astype(np.float32))[None, None]
out = F.grid_sample(inp, grid, mode="nearest", padding_mode="zeros", align_corners=False)
return (out[0, 0] > 0.5).numpy()
def warp_trajectories_to_masks(
obs_labels_256: np.ndarray,
xyz_48: np.ndarray,
cam_pos: np.ndarray,
cam_rot: np.ndarray,
fx_512: float,
cut: int,
slot_to_seg_id: list[int] | None = None,
) -> np.ndarray:
"""Project a 48-frame 3D trajectory into 256x256 categorical masks for Wan 2.2 control.
Preserves exact observed prefix segmentation labels for frames 0..cut, and depth-sorts
warped object silhouettes (far -> near) for forecast frames cut+1..47.
"""
T, n, _ = xyz_48.shape
H, W = obs_labels_256.shape[1], obs_labels_256.shape[2]
assert H == W == 256
seg_ids = slot_to_seg_id if slot_to_seg_id is not None else [i + 1 for i in range(n)]
uv, depth = project_3d_to_pixels(xyz_48, cam_pos, cam_rot, fx_512, img_size=256)
# Choose the sharpest/largest prefix frame template per object slot
ref_masks: list[np.ndarray | None] = []
ref_frame: list[int] = []
ref_uv: list[tuple[float, float]] = []
ref_depth: list[float] = []
for i in range(n):
sid = int(seg_ids[i])
prefix_m = obs_labels_256[: cut + 1] == sid
areas = prefix_m.sum(axis=(1, 2))
if areas.max() == 0:
ref_masks.append(None)
ref_frame.append(cut)
ref_uv.append((float(uv[cut, i, 0]), float(uv[cut, i, 1])))
ref_depth.append(float(depth[cut, i]))
else:
t_best = int(np.flatnonzero(areas == areas.max())[-1])
ref_masks.append(prefix_m[t_best])
ref_frame.append(t_best)
ref_uv.append((float(uv[t_best, i, 0]), float(uv[t_best, i, 1])))
ref_depth.append(float(depth[t_best, i]))
out = np.zeros((T, H, W), dtype=np.uint8)
out[: cut + 1] = obs_labels_256[: cut + 1]
for t in range(cut + 1, T):
# Depth-sort far -> near so nearer objects occlude farther objects cleanly
order = np.argsort(-depth[t])
canvas = np.zeros((H, W), dtype=np.uint8)
for i in order:
rm = ref_masks[i]
if rm is None:
continue
sid = int(seg_ids[i])
sc = float(np.clip(ref_depth[i] / max(float(depth[t, i]), 1e-4), 0.35, 2.5))
dx = float(uv[t, i, 0] - ref_uv[i][0])
dy = float(uv[t, i, 1] - ref_uv[i][1])
warped = _warp_binary_mask(rm, ref_uv[i], sc, (dx, dy))
canvas[warped] = sid
out[t] = canvas
return out
class Wan22CounterfactualRenderer:
"""Wrapper around the pinned Wan 2.2-Fun-5B-Control + trained JAIS terminal.pt adapter."""
def __init__(self, cache_root: Path):
self.cache_root = Path(cache_root)
self.cache_root.mkdir(parents=True, exist_ok=True)
self.native = None
self.tr = None
self.vae = None
self.emb = None
self.trainable = None
def setup(self) -> None:
from huggingface_hub import hf_hub_download, snapshot_download
code_dir = self.cache_root / "wan22_src"
code_dir.mkdir(parents=True, exist_ok=True)
nat_path = hf_hub_download(
"pineapplechoco/jais-physical-graph-cache",
"wan22_fun5b_control_7200_20261127/training/source/wan22_native.py",
repo_type="dataset",
)
(code_dir / "wan22_native.py").write_bytes(Path(nat_path).read_bytes())
if str(code_dir) not in sys.path:
sys.path.insert(0, str(code_dir))
import wan22_native as native
self.native = native
# Ensure pinned VideoX-Fun checkout
videox_dir = self.cache_root / "VideoX-Fun"
if not (videox_dir / "videox_fun").is_dir():
subprocess.run(
["git", "clone", "--no-checkout", "https://github.com/aigc-apps/VideoX-Fun.git", str(videox_dir)],
check=True,
)
subprocess.run(["git", "-C", str(videox_dir), "fetch", "--depth", "1", "origin", native.CODE], check=True)
subprocess.run(["git", "-C", str(videox_dir), "checkout", native.CODE], check=True)
# Download pinned Wan2.2-Fun-5B-Control weights (only needed files)
base_dir = Path(
snapshot_download(
native.MODEL,
revision=native.REV,
allow_patterns=[
"config.json",
"diffusion_pytorch_model.safetensors",
"Wan2.2_VAE.pth",
"models_t5_umt5-xxl-enc-bf16.pth",
"google/umt5-xxl/*",
],
)
)
# Build native 5B transformer + VAE + prompt embedding + LoRA/PatchDelta adapters
self.tr, self.vae, self.emb, self.trainable = native.build(base_dir, videox_dir, self.cache_root)
# Load the trained 7,200-step JAIS terminal LoRA + control patch checkpoint
ckpt_path = hf_hub_download(
"pineapplechoco/jais-physical-graph-cache",
"wan22_fun5b_control_7200_20261127/training/model/terminal.pt",
repo_type="dataset",
)
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=True)
state = ckpt["state"] if isinstance(ckpt, dict) and "state" in ckpt else ckpt
if set(state.keys()) != set(self.trainable.keys()):
# Handle nested keys like 'trainable' or 'model'
for k in ("trainable", "model", "weights"):
if isinstance(ckpt, dict) and k in ckpt and set(ckpt[k].keys()) == set(self.trainable.keys()):
state = ckpt[k]
break
assert set(state.keys()) == set(self.trainable.keys()), (
f"Checkpoint keys mismatch: {len(state)} vs {len(self.trainable)}"
)
with torch.no_grad():
for name, param in self.trainable.items():
param.copy_(state[name].to(device=param.device, dtype=param.dtype))
self.tr.eval()
@torch.no_grad()
def render(
self,
prefix_rgb_256: np.ndarray,
control_labels_256: np.ndarray,
seed: int,
steps: int = 30,
) -> tuple[np.ndarray, dict[str, Any]]:
"""Render a 48-frame 256x256 counterfactual RGB video conditioned on prefix RGB & control masks."""
assert self.tr is not None and self.vae is not None
native = self.native
src, vis = native.source(self.vae, prefix_rgb_256)
pose = native.encode(self.vae, native.frames(color_mask(control_labels_256)))
noise = torch.randn(pose.shape, device="cuda", generator=torch.Generator("cuda").manual_seed(int(seed)))
ab = native.forward(self.tr, self.emb, noise, src, vis, torch.zeros_like(pose), 1.0)
z = noise
grid = shift_sigma(np.linspace(1.0, 0.0, steps + 1))
ablation_rms = 0.0
for i, (cur, nxt) in enumerate(zip(grid[:-1], grid[1:])):
v = native.forward(self.tr, self.emb, z, src, vis, pose, float(cur))
if i == 0:
ablation_rms = float((v - ab).square().mean().sqrt())
z = z + (float(nxt) - float(cur)) * v
z[:, :, :1] = src[:, :, :1]
video = native.decode(self.vae, z)
meta = {
"seed": int(seed),
"steps": int(steps),
"mask_ablation_rms": ablation_rms,
"raw_mask_sha256": hashlib.sha256(np.ascontiguousarray(control_labels_256).tobytes()).hexdigest(),
}
return video, meta
def compose_labeled_grid(
panels: list[tuple[str, np.ndarray, tuple[int, int, int]]],
cut: int,
banner_h: int = 34,
) -> np.ndarray:
"""Compose N 256x256 48-frame videos side-by-side with crisp header labels and cutoff indicator."""
T, H, W, _ = panels[0][1].shape
N = len(panels)
pad = 4
total_w = N * W + (N - 1) * pad
total_h = H + banner_h
out = np.full((T, total_h, total_w, 3), 24, dtype=np.uint8)
font = ImageFont.load_default()
# Pre-render static header strip once
header = Image.new("RGB", (total_w, banner_h), (24, 24, 28))
draw = ImageDraw.Draw(header)
for idx, (title, _, color) in enumerate(panels):
x0 = idx * (W + pad)
draw.rectangle([x0, 0, x0 + W - 1, 5], fill=color)
draw.text((x0 + 6, 10), title, fill=(245, 245, 245), font=font)
header_arr = np.asarray(header, dtype=np.uint8)
for t in range(T):
out[t, :banner_h] = header_arr
for idx, (_, frames, color) in enumerate(panels):
x0 = idx * (W + pad)
frame = frames[t].copy()
# Draw subtle thin border: blue during observed prefix (t<=cut), accent after edit
bcol = (70, 140, 230) if t <= cut else color
frame[:2, :] = bcol
frame[-2:, :] = bcol
frame[:, :2] = bcol
frame[:, -2:] = bcol
out[t, banner_h:, x0 : x0 + W] = frame
return out
def save_keyframe_filmstrip(
panels: list[tuple[str, np.ndarray, tuple[int, int, int]]],
frame_indices: list[int],
out_path: str | Path,
title: str,
) -> Path:
"""Save a crisp publication-ready multi-row keyframe filmstrip PNG."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
n_rows = len(panels)
n_cols = len(frame_indices)
fig, axes = plt.subplots(n_rows, n_cols, figsize=(2.35 * n_cols, 2.35 * n_rows), dpi=160)
if n_rows == 1:
axes = axes[None, :]
for r, (label, frames, color) in enumerate(panels):
for c, fidx in enumerate(frame_indices):
ax = axes[r, c]
ax.imshow(frames[fidx])
ax.set_xticks([])
ax.set_yticks([])
for sp in ax.spines.values():
sp.set_edgecolor(tuple(v / 255.0 for v in color))
sp.set_linewidth(1.8)
if r == 0:
ax.set_title(f"Frame {fidx}", fontsize=10, fontweight="bold")
if c == 0:
ax.set_ylabel(label, fontsize=9, fontweight="bold", rotation=90, labelpad=6)
fig.suptitle(title, fontsize=12, fontweight="bold", y=0.995)
fig.tight_layout(rect=[0, 0, 1, 0.96])
out_path = Path(out_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(out_path, bbox_inches="tight")
plt.close(fig)
return out_pathbacp_20261130/code/bacp/video_pipeline.pyAdded+374