| |
| """ReCamMaster shard runner for the 81-frame contiguous query dataset. |
| |
| Why this is different from `recammaster_pad81_shard.py` |
| -------------------------------------------------------- |
| The pad81 shard works on the original 41-frame TestData and frame-pads to 81. |
| This shard works on `query_datasets_2clips_per_uuid/frames_081/`, where each |
| clip already contains a REAL 81-frame contiguous front.mp4 at 16 fps (5 s), |
| matched by 5 GT view mp4s. |
| |
| Temporal alignment of the camera anchors |
| ---------------------------------------- |
| The pose file referenced from the manifest (`pose_pt`) is the original |
| LongtailTest extraction. Its `T_anchor_front` is 11 anchors at 1 s spacing |
| covering 0..10 s. The new 81-frame clip covers 0..5 s with 21 anchors at |
| 0.25 s spacing. Because the existing `load_clip_geometry` densifies those |
| 11 anchors into a 41-frame trajectory at 0.25 s spacing (frames 0..40 over |
| 0..10 s), the **first 21 entries** of that densified trajectory are exactly |
| the 21 anchors we need for the new 5-second clip. (Small per-frame timestamp |
| jitter is <15 ms = ~6% of the 250 ms anchor spacing, negligible vs vehicle |
| dynamics at typical driving speeds.) |
| |
| Outputs |
| ------- |
| Full 81-frame mp4 (NOT trimmed) to: |
| results/recammaster_query81/<chunk>/<uuid>/<clip_id>/<view>.mp4 |
| This matches the GT layout at: |
| query_datasets_2clips_per_uuid/frames_081/<chunk>/<uuid>/<clip_id>/<view>.mp4 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import sys |
| import time |
| import traceback |
| from pathlib import Path |
|
|
| import numpy as np |
| import torch |
|
|
| EVALWM_ROOT = Path("/scratch/project/prj-02-phai-lab/lulin/longtail/evalWM") |
| RECAM_ROOT = Path("/scratch/project/prj-02-phai-lab/lulin/longtail/ReCamMaster") |
| sys.path.insert(0, str(EVALWM_ROOT / "run_baselines")) |
| sys.path.insert(0, str(EVALWM_ROOT / "run_baselines" / "adapters")) |
| sys.path.insert(0, str(RECAM_ROOT)) |
|
|
| from io_utils import OUTPUT_FPS, load_manifest, shard_view_jobs |
| from recammaster_one import load_source_video, DEFAULT_NEGATIVE_PROMPT |
| from trajectory import load_clip_geometry, SENSOR_FROM_TAG |
|
|
|
|
| SOURCE_FRAMES = 81 |
| NUM_ANCHORS = 21 |
| OUTPUT_FRAMES = 81 |
| BASELINE_NAME = "recammaster_query81" |
| DEFAULT_MANIFEST = EVALWM_ROOT / "run_baselines" / "query_datasets_2clips_per_uuid" / "frames_081" / "manifest.jsonl" |
|
|
|
|
| def build_query81_pose_embedding(geo: dict, view: str) -> torch.Tensor: |
| """(1, 21, 12) pose embedding for the 5-second 81-frame clip. |
| |
| Uses the first 21 frames of the densified 41-frame world_from_view |
| trajectory produced by `load_clip_geometry`, expressed relative to |
| `T_anchor_front[0]` (= identity since world = front_cam_0). |
| """ |
| sensor = SENSOR_FROM_TAG[view] |
| T_view_41 = geo["T_world_from_cam_41_by_sensor"][sensor] |
| T_view_21 = T_view_41[:NUM_ANCHORS] |
| T_front_anchor0 = geo["T_anchor_front_11"][0] |
| inv0 = np.linalg.inv(T_front_anchor0) |
| rel = inv0[None] @ T_view_21 |
| rel_3x4 = rel[:, :3, :].astype(np.float32) |
| rel_flat = rel_3x4.reshape(NUM_ANCHORS, 12) |
| return torch.from_numpy(rel_flat).unsqueeze(0).to(torch.bfloat16) |
|
|
|
|
| def output_path(row: dict, view: str) -> Path: |
| """Match the GT directory-per-clip layout.""" |
| return (EVALWM_ROOT / "results" / BASELINE_NAME |
| / f"chunk_{row['chunk']}" / row["uuid"] / row["clip_id"] / f"{view}.mp4") |
|
|
|
|
| def log_path(row: dict, view: str) -> Path: |
| return (EVALWM_ROOT / "results" / BASELINE_NAME / "_logs" |
| / f"chunk_{row['chunk']}_{row['uuid']}_{row['clip_id']}_{view}.log") |
|
|
|
|
| def parse_args(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--shard-idx", type=int, required=True) |
| ap.add_argument("--num-shards", type=int, default=30) |
| ap.add_argument("--num-steps", type=int, default=50) |
| ap.add_argument("--cfg-scale", type=float, default=5.0) |
| ap.add_argument("--seed", type=int, default=0) |
| ap.add_argument("--height", type=int, default=480) |
| ap.add_argument("--width", type=int, default=832) |
| ap.add_argument("--max-jobs", type=int, default=0) |
| ap.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) |
| return ap.parse_args() |
|
|
|
|
| def main(): |
| args = parse_args() |
| manifest = load_manifest(args.manifest) |
| jobs = shard_view_jobs(manifest, args.shard_idx, args.num_shards) |
| if args.max_jobs > 0: |
| jobs = jobs[: args.max_jobs] |
|
|
| from diffsynth import ModelManager, WanVideoReCamMasterPipeline, save_video |
|
|
| device = "cuda" |
| print(f"[recam_query81] shard={args.shard_idx}/{args.num_shards} jobs={len(jobs)} " |
| f"src_frames={SOURCE_FRAMES} anchors={NUM_ANCHORS} out_frames={OUTPUT_FRAMES}", |
| flush=True) |
|
|
| t_load = time.time() |
| model_manager = ModelManager(torch_dtype=torch.bfloat16, device="cpu") |
| model_manager.load_models([ |
| str(RECAM_ROOT / "models" / "Wan-AI" / "Wan2.1-T2V-1.3B" / "diffusion_pytorch_model.safetensors"), |
| str(RECAM_ROOT / "models" / "Wan-AI" / "Wan2.1-T2V-1.3B" / "models_t5_umt5-xxl-enc-bf16.pth"), |
| str(RECAM_ROOT / "models" / "Wan-AI" / "Wan2.1-T2V-1.3B" / "Wan2.1_VAE.pth"), |
| ]) |
| pipe = WanVideoReCamMasterPipeline.from_model_manager(model_manager, device=device) |
| dim = pipe.dit.blocks[0].self_attn.q.weight.shape[0] |
| for block in pipe.dit.blocks: |
| block.cam_encoder = torch.nn.Linear(12, dim) |
| block.projector = torch.nn.Linear(dim, dim) |
| block.cam_encoder.weight.data.zero_() |
| block.cam_encoder.bias.data.zero_() |
| block.projector.weight = torch.nn.Parameter(torch.eye(dim)) |
| block.projector.bias = torch.nn.Parameter(torch.zeros(dim)) |
| state_dict = torch.load( |
| RECAM_ROOT / "models" / "ReCamMaster" / "checkpoints" / "step20000.ckpt", |
| map_location="cpu", weights_only=False, |
| ) |
| if "state_dict" in state_dict: |
| state_dict = state_dict["state_dict"] |
| pipe.dit.load_state_dict(state_dict, strict=True) |
| pipe.to(device); pipe.to(dtype=torch.bfloat16) |
| print(f"[recam_query81] loaded ckpt in {time.time()-t_load:.1f}s", flush=True) |
|
|
| done = skipped = failed = 0 |
| for i, (row, view) in enumerate(jobs): |
| out_path = output_path(row, view) |
| if out_path.exists() and out_path.stat().st_size > 1000: |
| skipped += 1 |
| print(f" [{i+1}/{len(jobs)}] skip {out_path.relative_to(EVALWM_ROOT)}", flush=True) |
| continue |
| lp = log_path(row, view) |
| lp.parent.mkdir(parents=True, exist_ok=True) |
|
|
| t0 = time.time() |
| try: |
| geo = load_clip_geometry(row) |
| pose_embed = build_query81_pose_embedding(geo, view).to(device) |
| sv = load_source_video(row["front_mp4"], args.height, args.width, |
| num_frames=SOURCE_FRAMES).to(device) |
| source_video = sv.permute(1, 0, 2, 3).unsqueeze(0) |
| assert source_video.shape[2] == SOURCE_FRAMES, source_video.shape |
| assert pose_embed.shape == (1, NUM_ANCHORS, 12), pose_embed.shape |
|
|
| |
| if row.get("text_emb_pt"): |
| te = torch.load(row["text_emb_pt"], map_location="cpu", weights_only=False) |
| prompt = te.get("prompt", "") or "A driving scene viewed from a vehicle-mounted camera." |
| else: |
| prompt = "A driving scene viewed from a vehicle-mounted camera." |
|
|
| video = pipe( |
| prompt=prompt, |
| negative_prompt=DEFAULT_NEGATIVE_PROMPT, |
| source_video=source_video, |
| target_camera=pose_embed, |
| cfg_scale=args.cfg_scale, |
| num_inference_steps=args.num_steps, |
| seed=args.seed, |
| height=args.height, |
| width=args.width, |
| num_frames=SOURCE_FRAMES, |
| tiled=True, |
| ) |
| assert len(video) == SOURCE_FRAMES, f"pipe returned {len(video)} frames, expected {SOURCE_FRAMES}" |
| |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| tmp = out_path.with_suffix(".tmp.mp4") |
| save_video(video, str(tmp), fps=OUTPUT_FPS, quality=5) |
| tmp.rename(out_path) |
| done += 1 |
| print(f" [{i+1}/{len(jobs)}] ok {row['chunk']}/{row['uuid'][:8]}/{row['clip_id']}/{view} " |
| f"{time.time()-t0:.0f}s", flush=True) |
| torch.cuda.empty_cache() |
| except Exception: |
| failed += 1 |
| tb = traceback.format_exc() |
| lp.write_text(tb) |
| print(f" [{i+1}/{len(jobs)}] FAIL {row['chunk']}/{row['uuid'][:8]}/{row['clip_id']}/{view}: " |
| f"{tb.splitlines()[-1]}", flush=True) |
|
|
| print(f"[recam_query81] done done={done} skipped={skipped} failed={failed}", flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|