ctrl_baseline / libero_eval /eval_ctrlworld.py
ewykric's picture
Add files using upload-large-folder tool
df5bd17 verified
Raw
History Blame Contribute Delete
8.17 kB
"""
Ctrl-World Evaluation Script
对 val set 全量跑推理,保存预测帧和 GT 帧,供后续指标计算使用。
用法:
cd /mnt/gyc/Ctrl-World
python /mnt/gyc/Latent-Act-WAM/libero_eval/eval_ctrlworld.py \
--ckpt_path /mnt/gyc_wjx/Latent-Act-WAM/ctrl_world_ckpt/libero_svd_finetune/checkpoint-15000.pt \
--output_dir /mnt/gyc_wjx/Latent-Act-WAM/eval_results/checkpoint-15000 \
--batch_size 4 \
--gpu 0
输出结构:
output_dir/
libero_spatial/
episode_0000/
pred.npy # (num_frames, H, W, 3) uint8,预测帧
gt.npy # (num_frames, H, W, 3) uint8,GT 帧(仅 future 部分)
libero_object/
libero_goal/
libero_10/
manifest.json # 每条 episode 的 metadata
"""
import os
import sys
import json
import argparse
import numpy as np
import torch
import einops
from tqdm import tqdm
# 加入 Ctrl-World 路径
sys.path.insert(0, '/mnt/gyc/Ctrl-World')
from models.ctrl_world import CrtlWorld
from models.pipeline_ctrl_world import CtrlWorldDiffusionPipeline
from config_libero import wm_args
from dataset.dataset_droid_exp33 import Dataset_mix
def decode_latents(pipeline, latents, decode_chunk_size=7):
"""将 VAE latent 解码为 RGB 帧 (uint8)"""
bsz, frame_num = 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
out = pipeline.vae.decode(chunk, num_frames=chunk.shape[0]).sample
decoded.append(out)
decoded = torch.cat(decoded, dim=0)
decoded = decoded.reshape(bsz, frame_num, *decoded.shape[1:])
# (B, F, C, H, W) -> (B, F, H, W, C), [0,1], uint8
decoded = ((decoded / 2.0 + 0.5).clamp(0, 1) * 255)
decoded = decoded.detach().cpu().numpy().transpose(0, 1, 3, 4, 2).astype(np.uint8)
return decoded
def run_inference(model, pipeline, batch, args, device):
"""
对一个 batch 跑推理
返回:
pred_frames: (B, num_frames, H, W, 3) uint8 ← 预测的 future 帧
gt_frames: (B, num_frames, H, W, 3) uint8 ← GT 的 future 帧
"""
video_gt = batch['latent'].to(device) # (B, num_history+num_frames, 4, 72, 40)
actions = batch['action'].to(device) # (B, num_history+num_frames, action_dim)
texts = batch['text']
his_latent = video_gt[:, :args.num_history] # (B, num_history, 4, 72, 40)
future_latent = video_gt[:, args.num_history:] # (B, num_frames, 4, 72, 40)
current_latent = future_latent[:, 0] # (B, 4, 72, 40)
with torch.no_grad():
action_latent = model.action_encoder(
actions, texts, model.tokenizer, model.text_encoder, args.frame_level_cond
)
_, pred_latents = CtrlWorldDiffusionPipeline.__call__(
pipeline,
image=current_latent,
text=action_latent,
width=args.width,
height=int(3 * args.height),
num_frames=args.num_frames,
history=his_latent,
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,
mask=None,
output_type='latent',
return_dict=False,
frame_level_cond=args.frame_level_cond,
his_cond_zero=args.his_cond_zero,
)
# rearrange: (B, F, 4, 3*H, W) -> (B*3, F, 4, H, W),取 view[0] 即第一视角
pred_latents = einops.rearrange(
pred_latents, 'b f c (m h) (n w) -> b m n f c h w', m=3, n=1
)[:, 0, 0] # (B, F, 4, H, W)
future_latent_view0 = einops.rearrange(
future_latent, 'b f c (m h) (n w) -> b m n f c h w', m=3, n=1
)[:, 0, 0] # (B, F, 4, H, W)
pred_frames = decode_latents(pipeline, pred_latents, args.decode_chunk_size)
gt_frames = decode_latents(pipeline, future_latent_view0, args.decode_chunk_size)
return pred_frames, gt_frames
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--ckpt_path', type=str, required=True)
parser.add_argument('--output_dir', type=str, required=True)
parser.add_argument('--batch_size', type=int, default=4)
parser.add_argument('--gpu', type=int, default=0)
parser.add_argument('--max_episodes', type=int, default=None,
help='调试用:只跑前 N 条 episode,None = 全量')
parser.add_argument('--datasets', nargs='+', default=None,
help='只跑指定数据集,默认全部。如:--datasets libero_spatial')
cli_args = parser.parse_args()
device = torch.device(f'cuda:{cli_args.gpu}')
os.makedirs(cli_args.output_dir, exist_ok=True)
# 加载配置和模型
args = wm_args()
print(f"Loading model from {cli_args.ckpt_path}...")
model = CrtlWorld(args)
state_dict = torch.load(cli_args.ckpt_path, map_location='cpu')
model.load_state_dict(state_dict, strict=True)
model.to(device)
model.eval()
pipeline = model.pipeline
# 加载 val dataset
val_dataset = Dataset_mix(args, mode='val')
print(f"Val dataset size: {len(val_dataset)} samples")
# 把 samples_all (list of list) 展开成 flat list,附带 dataset 名
dataset_names = args.dataset_names.split('+')
filter_datasets = cli_args.datasets # None = 全部
flat_samples = [] # [(dataset_name, sample_dict), ...]
for ds_idx, (ds_name, ds_samples) in enumerate(zip(dataset_names, val_dataset.samples_all)):
if filter_datasets and ds_name not in filter_datasets:
continue
for s in ds_samples:
flat_samples.append((ds_name, s))
manifest = []
for ds in dataset_names:
os.makedirs(os.path.join(cli_args.output_dir, ds), exist_ok=True)
# 遍历 val set
total = len(flat_samples) if cli_args.max_episodes is None else min(cli_args.max_episodes, len(flat_samples))
print(f"Total samples to eval: {total}")
for idx in tqdm(range(0, total, cli_args.batch_size), desc='Evaluating'):
batch_indices = list(range(idx, min(idx + cli_args.batch_size, total)))
samples = [val_dataset.__getitem__(i) for i in batch_indices]
batch = {
'latent': torch.stack([s['latent'] for s in samples]),
'action': torch.stack([s['action'] for s in samples]),
'text': [s['text'] for s in samples],
}
try:
pred_frames, gt_frames = run_inference(model, pipeline, batch, args, device)
except Exception as e:
print(f"[WARN] batch {idx} failed: {e}")
continue
# 保存每条 episode
for j, sample_idx in enumerate(batch_indices):
dataset_name, sample_meta = flat_samples[sample_idx]
episode_id = sample_meta.get('episode_id', f'{sample_idx:04d}')
frame_ids = sample_meta.get('frame_ids', [0])
save_key = f"episode_{episode_id}_frame{frame_ids[0]}"
ep_dir = os.path.join(cli_args.output_dir, dataset_name, save_key)
os.makedirs(ep_dir, exist_ok=True)
np.save(os.path.join(ep_dir, 'pred.npy'), pred_frames[j])
np.save(os.path.join(ep_dir, 'gt.npy'), gt_frames[j])
manifest.append({
'dataset': dataset_name,
'episode_id': episode_id,
'frame_ids': frame_ids,
'sample_idx': sample_idx,
'pred_path': os.path.join(dataset_name, save_key, 'pred.npy'),
'gt_path': os.path.join(dataset_name, save_key, 'gt.npy'),
'num_frames': pred_frames[j].shape[0],
'text': samples[j]['text'],
})
# 保存 manifest
manifest_path = os.path.join(cli_args.output_dir, 'manifest.json')
with open(manifest_path, 'w') as f:
json.dump(manifest, f, indent=2)
print(f"\nDone! {len(manifest)} episodes saved to {cli_args.output_dir}")
print(f"Manifest: {manifest_path}")
if __name__ == '__main__':
main()