| import argparse |
| import json |
| import sys |
| from pathlib import Path |
|
|
| import numpy as np |
| import torch |
|
|
| ROOT = Path(__file__).resolve().parents[1] |
| if str(ROOT) not in sys.path: |
| sys.path.insert(0, str(ROOT)) |
|
|
| from graphwm.config_graph import GraphWMArgs |
| from graphwm.cli_graph import add_graph_model_args, apply_graph_model_args, load_graph_model_config_sidecar |
| from graphwm.dataset.collate_graph_wm import collate_graph_wm |
| from graphwm.dataset.dataset_graph_wm import _load_rgb_frame |
| from graphwm.models.ctrl_world_graph import CtrlWorldGraph |
| from graphwm.original_ctrl_world import import_original_modules |
| from scripts.eval_graph_video import decode_latents_to_video, latest_checkpoint, psnr, write_video |
| from scripts.train_wm_graph import build_datasets |
|
|
|
|
| def _episode_frame_ids(episode_dir: Path, graph_dir_name: str) -> list[int]: |
| rgb_dir = episode_dir / "side" / "rgb" |
| graph_dir = episode_dir / graph_dir_name |
| rgb_ids = {int(p.stem.split("_")[-1]) for p in rgb_dir.glob("frame_*.png")} |
| graph_ids = {int(p.stem.split("_")[-1]) for p in graph_dir.glob("frame_*.pt")} |
| return sorted(rgb_ids & graph_ids) |
|
|
|
|
| def _make_graph_batch( |
| episode_dir: Path, |
| graph_dir_name: str, |
| frame_ids: list[int], |
| ) -> dict: |
| graph_seq = [ |
| torch.load( |
| episode_dir / graph_dir_name / f"frame_{frame_id:06d}.pt", |
| map_location="cpu", |
| weights_only=False, |
| ) |
| for frame_id in frame_ids |
| ] |
| return collate_graph_wm([{ |
| "graph_seq": graph_seq, |
| "frame_ids": torch.tensor(frame_ids, dtype=torch.long), |
| "text": "", |
| "meta": {"episode_dir": str(episode_dir)}, |
| }]) |
|
|
|
|
| def _load_rgb_batch( |
| episode_dir: Path, |
| frame_ids: list[int], |
| resize_hw: tuple[int, int], |
| ) -> torch.Tensor: |
| frames = [ |
| _load_rgb_frame(episode_dir / "side" / "rgb" / f"frame_{frame_id:06d}.png", resize_hw) |
| for frame_id in frame_ids |
| ] |
| return torch.stack(frames, dim=0).unsqueeze(0) |
|
|
|
|
| def _episode_from_val_dataset(val_ds, sample_index: int) -> Path: |
| if hasattr(val_ds, "dataset") and hasattr(val_ds, "indices"): |
| base_index = val_ds.indices[sample_index] |
| return val_ds.dataset.samples[base_index][0] |
| if hasattr(val_ds, "samples"): |
| return val_ds.samples[sample_index][0] |
| raise TypeError(f"Cannot infer episode dir from val dataset type {type(val_ds)!r}.") |
|
|
|
|
| def _spaced_window(frame_ids: list[int], current_offset: int, before: int, after: int, interval: int) -> list[int]: |
| history = [ |
| frame_ids[current_offset - i * interval] |
| for i in range(before, 0, -1) |
| ] |
| future = [ |
| frame_ids[current_offset + i * interval] |
| for i in range(after) |
| ] |
| return history + future |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Graph-conditioned episode rollout.") |
| parser.add_argument("--ckpt-path", type=Path, default=None) |
| parser.add_argument("--out-dir", type=Path, default=Path("/workspace/Ctrl-World-Graph/eval_videos")) |
| parser.add_argument("--episode-dir", type=Path, default=None) |
| parser.add_argument("--val-sample-index", type=int, default=0) |
| parser.add_argument("--start-frame-offset", type=int, default=0) |
| parser.add_argument("--max-output-frames", type=int, default=80) |
| parser.add_argument("--save-fps", type=int, default=None) |
| parser.add_argument( |
| "--frame-interval", |
| type=int, |
| default=None, |
| help="Override hanoi_frame_interval. Use 1 for pre-downsampled 5fps data " |
| "(hanoi_0420_balanced_5fps); leave unset to use the config default (6 for 30fps data).", |
| ) |
| parser.add_argument("--graph-mode", choices=["gt"], default="gt") |
| parser.add_argument( |
| "--rollout-mode", |
| choices=["ar", "teacher_forced"], |
| default="ar", |
| help="ar feeds generated frames back as history; teacher_forced uses GT history/current for every chunk.", |
| ) |
| add_graph_model_args(parser) |
| cli = parser.parse_args() |
|
|
| args = GraphWMArgs() |
| args.ckpt_path = str(cli.ckpt_path or latest_checkpoint(Path(args.output_dir))) |
| load_graph_model_config_sidecar(args, args.ckpt_path) |
| apply_graph_model_args(args, cli) |
| if cli.frame_interval is not None: |
| args.hanoi_frame_interval = cli.frame_interval |
| args.eval_batch_size = 1 |
| args.num_workers = 0 |
|
|
| _, val_ds = build_datasets(args) |
| if cli.episode_dir is not None: |
| episode_dir = cli.episode_dir |
| else: |
| episode_dir = _episode_from_val_dataset(val_ds, cli.val_sample_index) |
|
|
| all_frame_ids = _episode_frame_ids(episode_dir, args.hanoi_graph_dir_name) |
| frame_interval = args.hanoi_frame_interval |
| current_offset = cli.start_frame_offset + args.num_history * frame_interval |
| if current_offset >= len(all_frame_ids): |
| raise ValueError(f"current_offset={current_offset} exceeds episode length={len(all_frame_ids)}") |
|
|
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| model = CtrlWorldGraph(args).to(device) |
| state_dict = torch.load(args.ckpt_path, map_location="cpu") |
| model.load_state_dict(state_dict, strict=False) |
| model.eval() |
|
|
| original = import_original_modules(args.ctrl_world_root) |
| CtrlWorldDiffusionPipeline = original["CtrlWorldDiffusionPipeline"] |
|
|
| resize_hw = (args.height, args.width) |
| initial_frame_ids = [ |
| all_frame_ids[cli.start_frame_offset + i * frame_interval] |
| for i in range(args.num_history + 1) |
| ] |
| if len(initial_frame_ids) != args.num_history + 1: |
| raise ValueError(f"Need {args.num_history + 1} initial frames, got {len(initial_frame_ids)}") |
|
|
| with torch.no_grad(): |
| initial_rgb = _load_rgb_batch(episode_dir, initial_frame_ids, resize_hw).to(device) |
| timeline_latents = [latent.detach().clone() for latent in model.encode_rgb_to_latents(initial_rgb)[0]] |
|
|
| timeline_frame_ids = list(initial_frame_ids) |
| chunk_records = [] |
| new_frames_per_chunk = args.num_frames - 1 |
| max_episode_offset = len(all_frame_ids) - 1 - new_frames_per_chunk * frame_interval |
|
|
| with torch.no_grad(): |
| while ( |
| len(timeline_frame_ids) < cli.max_output_frames |
| and current_offset <= max_episode_offset |
| ): |
| graph_frame_ids = _spaced_window( |
| all_frame_ids, |
| current_offset, |
| before=args.num_history, |
| after=args.num_frames, |
| interval=frame_interval, |
| ) |
| graph_batch = _make_graph_batch(episode_dir, args.hanoi_graph_dir_name, graph_frame_ids) |
| graph_batch["graph_seq"] = [g.to(device) for g in graph_batch["graph_seq"]] |
| graph_hidden = model.encode_graph_condition(graph_batch).to(device=device, dtype=model.unet.dtype) |
|
|
| if cli.rollout_mode == "teacher_forced": |
| context_frame_ids = _spaced_window( |
| all_frame_ids, |
| current_offset, |
| before=args.num_history, |
| after=1, |
| interval=frame_interval, |
| ) |
| context_rgb = _load_rgb_batch(episode_dir, context_frame_ids, resize_hw).to(device) |
| context_latents = model.encode_rgb_to_latents(context_rgb)[0] |
| history = context_latents[:args.num_history].unsqueeze(0) |
| current_latent = context_latents[args.num_history].unsqueeze(0) |
| else: |
| history = torch.stack(timeline_latents[-(args.num_history + 1):-1], dim=0).unsqueeze(0) |
| current_latent = timeline_latents[-1].unsqueeze(0) |
|
|
| _, pred_latents = CtrlWorldDiffusionPipeline.__call__( |
| model.pipeline, |
| image=current_latent, |
| text=graph_hidden, |
| width=args.width, |
| height=args.height, |
| num_frames=args.num_frames, |
| history=history, |
| num_inference_steps=args.num_inference_steps, |
| decode_chunk_size=args.decode_chunk_size, |
| max_guidance_scale=args.guidance_scale, |
| fps=args.fps, |
| motion_bucket_id=args.motion_bucket_id, |
| output_type="latent", |
| return_dict=False, |
| frame_level_cond=args.frame_level_cond, |
| his_cond_zero=args.his_cond_zero, |
| ) |
|
|
| append_count = min(new_frames_per_chunk, cli.max_output_frames - len(timeline_frame_ids)) |
| for latent in pred_latents[0, 1:1 + append_count]: |
| timeline_latents.append(latent.detach().clone()) |
| appended_frame_ids = [ |
| all_frame_ids[current_offset + i * frame_interval] |
| for i in range(1, append_count + 1) |
| ] |
| timeline_frame_ids.extend(appended_frame_ids) |
| chunk_records.append({ |
| "current_frame_id": all_frame_ids[current_offset], |
| "graph_frame_ids": graph_frame_ids, |
| "appended_frame_ids": appended_frame_ids, |
| "history_source": "gt" if cli.rollout_mode == "teacher_forced" else "generated", |
| }) |
| current_offset += new_frames_per_chunk * frame_interval |
|
|
| rollout_latents = torch.stack(timeline_latents, dim=0).unsqueeze(0) |
| pred_video = decode_latents_to_video(model.pipeline, rollout_latents, args.decode_chunk_size)[0] |
| gt_rgb = _load_rgb_batch(episode_dir, timeline_frame_ids, resize_hw)[0] |
| gt_video = (gt_rgb.permute(0, 2, 3, 1).clamp(0, 1) * 255).byte().cpu().numpy() |
| compare_video = np.concatenate([gt_video, pred_video], axis=2) |
|
|
| generated_start = args.num_history + 1 |
| mean_psnr, per_frame_psnr = psnr(pred_video[generated_start:], gt_video[generated_start:]) |
|
|
| ckpt_name = Path(args.ckpt_path).stem |
| episode_name = f"{episode_dir.parent.name}_{episode_dir.name}" |
| out_dir = ( |
| cli.out_dir |
| / ckpt_name |
| / f"rollout_{cli.rollout_mode}_{episode_name}_start{cli.start_frame_offset:04d}_n{len(timeline_frame_ids):04d}" |
| ) |
| out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| save_fps = cli.save_fps or args.fps |
| pred_path = out_dir / "pred_rollout.mp4" |
| gt_path = out_dir / "gt_rollout.mp4" |
| compare_path = out_dir / "compare_gt_left_pred_right.mp4" |
| metrics_path = out_dir / "metrics.json" |
| write_video(pred_path, pred_video, fps=save_fps) |
| write_video(gt_path, gt_video, fps=save_fps) |
| write_video(compare_path, compare_video, fps=save_fps) |
|
|
| metrics = { |
| "ckpt_path": args.ckpt_path, |
| "episode_dir": str(episode_dir), |
| "graph_mode": cli.graph_mode, |
| "rollout_mode": cli.rollout_mode, |
| "num_history": args.num_history, |
| "num_frames": args.num_frames, |
| "frame_interval": frame_interval, |
| "source_fps": 30, |
| "new_frames_per_chunk": new_frames_per_chunk, |
| "model_condition_fps": args.fps, |
| "save_fps": save_fps, |
| "frame_ids": timeline_frame_ids, |
| "generated_frame_ids": timeline_frame_ids[generated_start:], |
| "psnr_mean_generated": mean_psnr, |
| "psnr_per_generated_frame": per_frame_psnr, |
| "chunks": chunk_records, |
| "pred_path": str(pred_path), |
| "gt_path": str(gt_path), |
| "compare_path": str(compare_path), |
| } |
| metrics_path.write_text(json.dumps(metrics, indent=2), encoding="utf-8") |
| print("saved_pred=", pred_path) |
| print("saved_gt=", gt_path) |
| print("saved_compare=", compare_path) |
| print("saved_metrics=", metrics_path) |
| print("num_output_frames=", len(timeline_frame_ids)) |
| print("psnr_mean_generated=", mean_psnr) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|