File size: 9,140 Bytes
f15a766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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()