Download Ctrl-World-Graph/scripts/eval_graph_video.py from EndeavourDD/gnn_wm2: direct link, hf CLI and curl.
- Browser
- Download file 9.14 kB
-
https://huggingface.co/datasets/EndeavourDD/gnn_wm2/resolve/main/Ctrl-World-Graph/scripts/eval_graph_video.py
- Command line
-
hf download hf://datasets/EndeavourDD/gnn_wm2/Ctrl-World-Graph/scripts/eval_graph_video.py
-
curl -L -o eval_graph_video.py https://huggingface.co/datasets/EndeavourDD/gnn_wm2/resolve/main/Ctrl-World-Graph/scripts/eval_graph_video.py
9.14 kB
| import argparse | |
| import json | |
| import sys | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import torch | |
| from torch.utils.data import DataLoader | |
| 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.models.ctrl_world_graph import CtrlWorldGraph | |
| from graphwm.original_ctrl_world import import_original_modules | |
| from scripts.train_wm_graph import build_datasets | |
| def write_video(path: Path, frames: np.ndarray, fps: int = 5): | |
| try: | |
| import mediapy as media | |
| media.write_video(str(path), frames, fps=fps) | |
| return | |
| except Exception: | |
| import imageio.v2 as imageio | |
| imageio.mimwrite(str(path), frames, fps=fps, macro_block_size=None) | |
| def decode_latents_to_video(pipeline, latents: torch.Tensor, decode_chunk_size: int): | |
| bsz, num_frames = latents.shape[:2] | |
| flat = latents.flatten(0, 1) | |
| decoded = [] | |
| for i in range(0, flat.shape[0], decode_chunk_size): | |
| chunk = flat[i:i + decode_chunk_size] / pipeline.vae.config.scaling_factor | |
| sample = pipeline.vae.decode(chunk, num_frames=chunk.shape[0]).sample | |
| decoded.append(sample) | |
| video = torch.cat(decoded, dim=0).reshape(bsz, num_frames, -1, flat.shape[-2] * 8, flat.shape[-1] * 8) | |
| video = ((video / 2.0 + 0.5).clamp(0, 1) * 255).byte() | |
| return video.permute(0, 1, 3, 4, 2).cpu().numpy() | |
| def latest_checkpoint(ckpt_dir: Path) -> Path: | |
| checkpoints = sorted( | |
| ckpt_dir.glob('checkpoint-*.pt'), | |
| key=lambda p: int(p.stem.split('-')[-1]), | |
| ) | |
| if not checkpoints: | |
| raise FileNotFoundError(f'No checkpoints found in {ckpt_dir}') | |
| return checkpoints[-1] | |
| def psnr(pred: np.ndarray, target: np.ndarray) -> tuple[float, list[float]]: | |
| pred_f = pred.astype(np.float32) / 255.0 | |
| target_f = target.astype(np.float32) / 255.0 | |
| mse = ((pred_f - target_f) ** 2).mean(axis=(1, 2, 3)) | |
| per_frame = [ | |
| float('inf') if value == 0.0 else float(10.0 * np.log10(1.0 / value)) | |
| for value in mse | |
| ] | |
| finite = [v for v in per_frame if np.isfinite(v)] | |
| mean = float(np.mean(finite)) if finite else float('inf') | |
| return mean, per_frame | |
| def run_one_sample( | |
| *, | |
| sample_index: int, | |
| val_ds, | |
| model: CtrlWorldGraph, | |
| pipeline_cls, | |
| args: GraphWMArgs, | |
| out_root: Path, | |
| write_videos: bool, | |
| ) -> dict[str, Any]: | |
| sample = val_ds[sample_index] | |
| batch = collate_graph_wm([sample]) | |
| device = next(model.parameters()).device | |
| batch['rgb'] = batch['rgb'].to(device) | |
| batch['graph_seq'] = [g.to(device) for g in batch['graph_seq']] | |
| with torch.no_grad(): | |
| latents = model.encode_rgb_to_latents(batch['rgb']) | |
| graph_hidden = model.encode_graph_condition(batch).to(device=device, dtype=model.unet.dtype) | |
| current_latent = latents[:, args.num_history] | |
| history = latents[:, :args.num_history] if args.num_history > 0 else None | |
| _, pred_latents = pipeline_cls.__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, | |
| ) | |
| pred_video = decode_latents_to_video(model.pipeline, pred_latents, args.decode_chunk_size)[0] | |
| gt_video = (batch['rgb'][0, args.num_history:].permute(0, 2, 3, 1).clamp(0, 1) * 255).byte().cpu().numpy() | |
| mean_psnr, per_frame_psnr = psnr(pred_video, gt_video) | |
| ckpt_name = Path(args.ckpt_path).stem | |
| out_dir = out_root / ckpt_name / f'val{sample_index:04d}' | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| metrics = { | |
| 'ckpt_path': args.ckpt_path, | |
| 'sample_index': sample_index, | |
| 'frame_ids': batch['frame_ids'][0].tolist(), | |
| 'gt_future_frame_ids': batch['frame_ids'][0, args.num_history:].tolist(), | |
| 'num_history': args.num_history, | |
| 'num_frames': args.num_frames, | |
| 'frame_interval': args.hanoi_frame_interval, | |
| 'source_fps': 30, | |
| 'sample_fps': args.fps, | |
| 'psnr_mean': mean_psnr, | |
| 'psnr_per_frame': per_frame_psnr, | |
| } | |
| if write_videos: | |
| compare_video = np.concatenate([gt_video, pred_video], axis=2) | |
| pred_path = out_dir / 'pred.mp4' | |
| gt_path = out_dir / 'gt_future.mp4' | |
| compare_path = out_dir / 'compare_gt_left_pred_right.mp4' | |
| write_video(pred_path, pred_video, fps=args.fps) | |
| write_video(gt_path, gt_video, fps=args.fps) | |
| write_video(compare_path, compare_video, fps=args.fps) | |
| metrics.update({ | |
| 'pred_path': str(pred_path), | |
| 'gt_path': str(gt_path), | |
| 'compare_path': str(compare_path), | |
| }) | |
| metrics_path = out_dir / 'metrics.json' | |
| metrics_path.write_text(json.dumps(metrics, indent=2), encoding='utf-8') | |
| return metrics | |
| def main(): | |
| parser = argparse.ArgumentParser(description='Run graph-conditioned video eval and compute PSNR.') | |
| parser.add_argument('--ckpt-path', type=Path, default=None) | |
| parser.add_argument('--sample-index', type=int, default=0) | |
| parser.add_argument('--num-samples', type=int, default=1) | |
| parser.add_argument('--save-videos-limit', type=int, default=None) | |
| parser.add_argument('--out-dir', type=Path, default=Path('/workspace/Ctrl-World-Graph/eval_videos')) | |
| 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) | |
| args.eval_batch_size = 1 | |
| args.num_workers = 0 | |
| _, val_ds = build_datasets(args) | |
| if val_ds is None or len(val_ds) == 0: | |
| raise ValueError('Validation dataset is empty.') | |
| if cli.sample_index < 0 or cli.sample_index >= len(val_ds): | |
| raise IndexError(f'sample-index {cli.sample_index} outside val dataset length {len(val_ds)}') | |
| end_index = min(len(val_ds), cli.sample_index + cli.num_samples) | |
| 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'] | |
| ckpt_name = Path(args.ckpt_path).stem | |
| aggregate_dir = cli.out_dir / ckpt_name | |
| aggregate_dir.mkdir(parents=True, exist_ok=True) | |
| results = [] | |
| print(f'evaluating val samples [{cli.sample_index}, {end_index}) on {device}') | |
| for offset, sample_index in enumerate(range(cli.sample_index, end_index)): | |
| write_videos = cli.save_videos_limit is None or offset < cli.save_videos_limit | |
| metrics = run_one_sample( | |
| sample_index=sample_index, | |
| val_ds=val_ds, | |
| model=model, | |
| pipeline_cls=CtrlWorldDiffusionPipeline, | |
| args=args, | |
| out_root=cli.out_dir, | |
| write_videos=write_videos, | |
| ) | |
| results.append(metrics) | |
| print( | |
| f"sample={sample_index} psnr_mean={metrics['psnr_mean']:.4f} " | |
| f"frames={metrics['gt_future_frame_ids']}" | |
| ) | |
| psnr_values = [m['psnr_mean'] for m in results if np.isfinite(m['psnr_mean'])] | |
| per_frame_values = np.array([m['psnr_per_frame'] for m in results], dtype=np.float32) | |
| aggregate = { | |
| 'ckpt_path': args.ckpt_path, | |
| 'start_index': cli.sample_index, | |
| 'end_index': end_index, | |
| 'num_samples': len(results), | |
| 'val_dataset_len': len(val_ds), | |
| 'psnr_mean': float(np.mean(psnr_values)) if psnr_values else float('inf'), | |
| 'psnr_std': float(np.std(psnr_values)) if psnr_values else 0.0, | |
| 'psnr_min': float(np.min(psnr_values)) if psnr_values else float('inf'), | |
| 'psnr_max': float(np.max(psnr_values)) if psnr_values else float('inf'), | |
| 'psnr_per_future_frame_mean': per_frame_values.mean(axis=0).tolist() if len(results) else [], | |
| 'samples': results, | |
| } | |
| aggregate_path = aggregate_dir / f'val_psnr_{cli.sample_index:04d}_{end_index - 1:04d}.json' | |
| aggregate_path.write_text(json.dumps(aggregate, indent=2), encoding='utf-8') | |
| print('saved_aggregate=', aggregate_path) | |
| print('aggregate_psnr_mean=', aggregate['psnr_mean']) | |
| print('aggregate_psnr_std=', aggregate['psnr_std']) | |
| if __name__ == '__main__': | |
| main() | |