Download eval_wan_ctrlworld_valset.py from ewykric/ctrl_baseline: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/datasets/ewykric/ctrl_baseline/resolve/main/eval_wan_ctrlworld_valset.py
- Command line
-
hf download hf://datasets/ewykric/ctrl_baseline/eval_wan_ctrlworld_valset.py
-
curl -L -o eval_wan_ctrlworld_valset.py https://huggingface.co/datasets/ewykric/ctrl_baseline/resolve/main/eval_wan_ctrlworld_valset.py
14.5 kB
| #!/usr/bin/env python3 | |
| # Copyright 2026 The RLinf Authors. | |
| # | |
| # Licensed under the Apache License, Version 2.0 (the "License"); | |
| # you may not use this file except in compliance with the License. | |
| # You may obtain a copy of the License at | |
| # | |
| # https://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| # See the License for the specific language governing permissions and | |
| # limitations under the License. | |
| """Distributed val-set rollout and metric evaluation for RLinf Wan AC world model.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import sys | |
| from copy import deepcopy | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import torch | |
| def _ensure_repo_imports() -> None: | |
| repo_root = Path(__file__).resolve().parents[2] | |
| wan_pkg_root = repo_root / ".venv" / "wan" | |
| metrics_root = repo_root.parent / "video_metrics" | |
| for path in (repo_root, wan_pkg_root, metrics_root): | |
| path_str = str(path) | |
| if path.exists() and path_str not in sys.path: | |
| sys.path.insert(0, path_str) | |
| _ensure_repo_imports() | |
| from calculate_fvd import calculate_fvd | |
| from calculate_lpips import calculate_lpips | |
| from calculate_psnr import calculate_psnr | |
| from calculate_ssim import calculate_ssim | |
| from infer_wan_ctrlworld import ( | |
| build_comparison_frames, | |
| build_wan_pipeline, | |
| load_annotation, | |
| load_video_frames, | |
| resolve_video_path, | |
| run_window_rollout, | |
| save_video, | |
| ) | |
| def parse_args() -> argparse.Namespace: | |
| repo_root = Path(__file__).resolve().parents[2] | |
| default_dataset_root = repo_root / "libero_ctrlworld2" / "libero_spatial" | |
| default_annotation_dir = default_dataset_root / "annotation" / "val" | |
| default_wm_model_ckpt = ( | |
| repo_root | |
| / "logs" | |
| / "wan_ctrlworld2_train_resume_from_3499" | |
| / "best_val_loss.safetensors" | |
| ) | |
| default_wm_vae_ckpt = repo_root / "RLinf-Wan-LIBERO-Spatial" / "Wan2.2_VAE.pth" | |
| default_output_dir = repo_root / "logs" / "wan_ctrlworld2_eval_best_val_17f" | |
| parser = argparse.ArgumentParser( | |
| description="Distributed rollout and metric evaluation on libero_ctrlworld2 val set." | |
| ) | |
| parser.add_argument("--wm-model-ckpt", type=Path, default=default_wm_model_ckpt) | |
| parser.add_argument("--wm-vae-ckpt", type=Path, default=default_wm_vae_ckpt) | |
| parser.add_argument("--annotation-dir", type=Path, default=default_annotation_dir) | |
| parser.add_argument("--dataset-root", type=Path, default=default_dataset_root) | |
| parser.add_argument("--output-dir", type=Path, default=default_output_dir) | |
| parser.add_argument("--device", type=str, default="cuda") | |
| parser.add_argument("--seed", type=int, default=0) | |
| parser.add_argument("--rollout-length", type=int, default=17) | |
| parser.add_argument("--num-inference-steps", type=int, default=5) | |
| parser.add_argument("--num-gpus", type=int, default=8) | |
| parser.add_argument("--chunk-size", type=int, default=8) | |
| parser.add_argument("--condition-frames", type=int, default=5) | |
| parser.add_argument("--fps", type=float, default=None) | |
| return parser.parse_args() | |
| def validate_args(args: argparse.Namespace) -> None: | |
| required_paths = [ | |
| args.wm_model_ckpt, | |
| args.wm_vae_ckpt, | |
| args.annotation_dir, | |
| args.dataset_root, | |
| ] | |
| for path in required_paths: | |
| if not path.exists(): | |
| raise FileNotFoundError(f"Required path does not exist: {path}") | |
| if args.rollout_length < 2: | |
| raise ValueError(f"rollout_length must be >= 2, got {args.rollout_length}") | |
| if args.chunk_size != 8: | |
| raise ValueError(f"Expected chunk_size=8, got {args.chunk_size}") | |
| if args.condition_frames != 5: | |
| raise ValueError(f"Expected condition_frames=5, got {args.condition_frames}") | |
| def get_rank_info(args: argparse.Namespace) -> tuple[bool, int, int, int, str]: | |
| world_size = int(os.environ.get("WORLD_SIZE", "1")) | |
| rank = int(os.environ.get("RANK", "0")) | |
| local_rank = int(os.environ.get("LOCAL_RANK", "0")) | |
| distributed = world_size > 1 | |
| if distributed and world_size != args.num_gpus: | |
| raise ValueError( | |
| f"torchrun WORLD_SIZE={world_size} does not match --num-gpus={args.num_gpus}" | |
| ) | |
| if not distributed and args.num_gpus != 1 and args.device.startswith("cuda"): | |
| print( | |
| f"Running in single-process mode even though --num-gpus={args.num_gpus}; " | |
| "continuing with one process." | |
| ) | |
| if args.device.startswith("cuda"): | |
| device = f"cuda:{local_rank}" | |
| torch.cuda.set_device(local_rank) | |
| else: | |
| device = args.device | |
| if distributed and not torch.distributed.is_initialized(): | |
| backend = "nccl" if device.startswith("cuda") else "gloo" | |
| torch.distributed.init_process_group(backend=backend) | |
| return distributed, rank, local_rank, world_size, device | |
| def sample_seed(global_seed: int, sample_id: str) -> int: | |
| digest = hashlib.sha256(f"{global_seed}:{sample_id}".encode("utf-8")).hexdigest() | |
| return int(digest[:8], 16) | |
| def choose_start_frame_index( | |
| *, total_frames: int, rollout_length: int, seed_value: int | |
| ) -> int: | |
| max_start = total_frames - rollout_length | |
| if max_start < 0: | |
| raise ValueError( | |
| f"Video length {total_frames} is shorter than rollout_length {rollout_length}" | |
| ) | |
| rng = np.random.default_rng(seed_value) | |
| return int(rng.integers(0, max_start + 1)) | |
| def frames_to_video_tensor(frames: list[np.ndarray]) -> torch.Tensor: | |
| array = np.stack(frames, axis=0).astype(np.float32) / 255.0 | |
| return torch.from_numpy(array).permute(0, 3, 1, 2).unsqueeze(0).contiguous() | |
| def compute_per_video_metrics( | |
| gt_frames: list[np.ndarray], | |
| pred_frames: list[np.ndarray], | |
| device: str, | |
| ) -> dict[str, float]: | |
| gt_tensor = frames_to_video_tensor(gt_frames) | |
| pred_tensor = frames_to_video_tensor(pred_frames) | |
| psnr = float(calculate_psnr(gt_tensor, pred_tensor)["value_mean"]) | |
| ssim = float(calculate_ssim(gt_tensor, pred_tensor)["value_mean"]) | |
| lpips = float(calculate_lpips(gt_tensor, pred_tensor, torch.device(device))["value_mean"]) | |
| return { | |
| "psnr": psnr, | |
| "ssim": ssim, | |
| "lpips": lpips, | |
| } | |
| def gather_saved_video_tensors( | |
| video_paths: list[Path], rollout_length: int | |
| ) -> torch.Tensor: | |
| videos = [] | |
| for video_path in video_paths: | |
| frames, _ = load_video_frames(video_path, image_size=(256, 256)) | |
| if len(frames) != rollout_length: | |
| raise ValueError( | |
| f"Expected {rollout_length} frames in {video_path}, got {len(frames)}" | |
| ) | |
| video_tensor = frames_to_video_tensor(frames).squeeze(0) | |
| videos.append(video_tensor) | |
| return torch.stack(videos, dim=0) | |
| def write_json(path: Path, payload: dict[str, Any]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", encoding="utf-8") as f: | |
| json.dump(payload, f, indent=2, ensure_ascii=False) | |
| def evaluate_sample( | |
| *, | |
| annotation_path: Path, | |
| pipe, | |
| args: argparse.Namespace, | |
| device: str, | |
| rank: int, | |
| ) -> dict[str, Any]: | |
| sample_id = annotation_path.stem | |
| annotation = load_annotation(annotation_path) | |
| video_path = resolve_video_path(args.dataset_root, annotation) | |
| gt_frames, source_fps = load_video_frames(video_path, image_size=(256, 256)) | |
| fps = float(args.fps if args.fps is not None else source_fps) | |
| if len(gt_frames) != int(annotation["video_length"]): | |
| raise ValueError( | |
| f"Decoded frame count {len(gt_frames)} does not match annotation video_length " | |
| f"{annotation['video_length']} for {annotation_path}" | |
| ) | |
| joints = np.asarray(annotation["joints"], dtype=np.float32) | |
| if joints.ndim != 2 or joints.shape[1] != 7: | |
| raise ValueError(f"Expected joints shape [T, 7], got {joints.shape} for {annotation_path}") | |
| per_sample_seed = sample_seed(args.seed, sample_id) | |
| start_frame_index = choose_start_frame_index( | |
| total_frames=len(gt_frames), | |
| rollout_length=args.rollout_length, | |
| seed_value=per_sample_seed, | |
| ) | |
| rollout_args = deepcopy(args) | |
| rollout_args.device = device | |
| rollout_args.seed = per_sample_seed | |
| rollout_args.action_offset = 0 | |
| gt_clip, pred_clip, chunk_infos, action_start_index = run_window_rollout( | |
| args=rollout_args, | |
| gt_frames=gt_frames, | |
| joints=joints, | |
| pipe=pipe, | |
| start_frame_index=start_frame_index, | |
| rollout_length=args.rollout_length, | |
| ) | |
| comparison_frames = build_comparison_frames(gt_clip, pred_clip) | |
| pred_path = args.output_dir / "pred_videos" / f"{sample_id}.mp4" | |
| gt_path = args.output_dir / "gt_videos" / f"{sample_id}.mp4" | |
| comparison_path = args.output_dir / "comparisons" / f"{sample_id}.mp4" | |
| meta_path = args.output_dir / "meta" / f"{sample_id}.json" | |
| save_video(pred_path, pred_clip, fps=fps) | |
| save_video(gt_path, gt_clip, fps=fps) | |
| save_video(comparison_path, comparison_frames, fps=fps) | |
| metrics = compute_per_video_metrics(gt_clip, pred_clip, device=device) | |
| payload = { | |
| "sample_id": sample_id, | |
| "annotation_json": str(annotation_path.resolve()), | |
| "video_path": str(video_path.resolve()), | |
| "start_frame_index": start_frame_index, | |
| "rollout_length": args.rollout_length, | |
| "action_start_index": action_start_index, | |
| "wm_model_ckpt": str(args.wm_model_ckpt.resolve()), | |
| "wm_vae_ckpt": str(args.wm_vae_ckpt.resolve()), | |
| "seed": per_sample_seed, | |
| "global_seed": args.seed, | |
| "gpu_rank": rank, | |
| "num_inference_steps": args.num_inference_steps, | |
| "fps": fps, | |
| "chunks": chunk_infos, | |
| **metrics, | |
| } | |
| write_json(meta_path, payload) | |
| return payload | |
| def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", encoding="utf-8") as f: | |
| for row in rows: | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| def main() -> None: | |
| args = parse_args() | |
| validate_args(args) | |
| distributed, rank, _local_rank, world_size, device = get_rank_info(args) | |
| annotation_paths = sorted(args.annotation_dir.glob("*.json")) | |
| if not annotation_paths: | |
| raise FileNotFoundError(f"No json files found in {args.annotation_dir}") | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| for dirname in ("pred_videos", "gt_videos", "comparisons", "meta", "shards"): | |
| (args.output_dir / dirname).mkdir(parents=True, exist_ok=True) | |
| if distributed: | |
| torch.distributed.barrier() | |
| pipe = build_wan_pipeline(args.wm_model_ckpt, args.wm_vae_ckpt, device) | |
| assigned_paths = [ | |
| path for idx, path in enumerate(annotation_paths) if idx % world_size == rank | |
| ] | |
| shard_rows: list[dict[str, Any]] = [] | |
| for annotation_path in assigned_paths: | |
| result = evaluate_sample( | |
| annotation_path=annotation_path, | |
| pipe=pipe, | |
| args=args, | |
| device=device, | |
| rank=rank, | |
| ) | |
| shard_rows.append(result) | |
| print( | |
| f"[rank {rank}] finished {annotation_path.stem}: " | |
| f"start={result['start_frame_index']} psnr={result['psnr']:.4f} " | |
| f"ssim={result['ssim']:.4f} lpips={result['lpips']:.4f}" | |
| ) | |
| shard_jsonl = args.output_dir / "shards" / f"per_video_metrics_rank{rank}.jsonl" | |
| write_jsonl(shard_jsonl, shard_rows) | |
| write_json( | |
| args.output_dir / "shards" / f"summary_rank{rank}.json", | |
| { | |
| "rank": rank, | |
| "world_size": world_size, | |
| "num_processed": len(shard_rows), | |
| "sample_ids": [row["sample_id"] for row in shard_rows], | |
| }, | |
| ) | |
| if distributed: | |
| torch.distributed.barrier() | |
| if rank == 0: | |
| merged_rows: list[dict[str, Any]] = [] | |
| for shard_rank in range(world_size): | |
| shard_path = args.output_dir / "shards" / f"per_video_metrics_rank{shard_rank}.jsonl" | |
| if not shard_path.exists(): | |
| raise FileNotFoundError(f"Missing shard metrics file: {shard_path}") | |
| with shard_path.open("r", encoding="utf-8") as f: | |
| for line in f: | |
| line = line.strip() | |
| if line: | |
| merged_rows.append(json.loads(line)) | |
| merged_rows.sort(key=lambda row: row["sample_id"]) | |
| write_jsonl(args.output_dir / "per_video_metrics.jsonl", merged_rows) | |
| pred_paths = [ | |
| args.output_dir / "pred_videos" / f"{row['sample_id']}.mp4" | |
| for row in merged_rows | |
| ] | |
| gt_paths = [ | |
| args.output_dir / "gt_videos" / f"{row['sample_id']}.mp4" | |
| for row in merged_rows | |
| ] | |
| videos_gt = gather_saved_video_tensors(gt_paths, args.rollout_length) | |
| videos_pred = gather_saved_video_tensors(pred_paths, args.rollout_length) | |
| fvd = float( | |
| calculate_fvd( | |
| videos_gt, | |
| videos_pred, | |
| device=torch.device(device), | |
| method="styleganv", | |
| )["value"] | |
| ) | |
| metrics = { | |
| "num_videos": len(merged_rows), | |
| "rollout_length": args.rollout_length, | |
| "psnr_mean": float(np.mean([row["psnr"] for row in merged_rows])), | |
| "ssim_mean": float(np.mean([row["ssim"] for row in merged_rows])), | |
| "lpips_mean": float(np.mean([row["lpips"] for row in merged_rows])), | |
| "fvd": fvd, | |
| } | |
| summary = { | |
| "annotation_dir": str(args.annotation_dir.resolve()), | |
| "dataset_root": str(args.dataset_root.resolve()), | |
| "wm_model_ckpt": str(args.wm_model_ckpt.resolve()), | |
| "wm_vae_ckpt": str(args.wm_vae_ckpt.resolve()), | |
| "seed": args.seed, | |
| "num_gpus": world_size, | |
| "metrics": metrics, | |
| } | |
| write_json(args.output_dir / "metrics.json", metrics) | |
| write_json(args.output_dir / "summary.json", summary) | |
| print(json.dumps(metrics, indent=2, ensure_ascii=False)) | |
| if distributed: | |
| torch.distributed.barrier() | |
| torch.distributed.destroy_process_group() | |
| if __name__ == "__main__": | |
| main() | |