openpi-realworld / Ctrl-World /scripts /inference_world_model.py
Howard Ji
Add missing Ctrl-World configs, normalization stats (all domains), converter weights, preprocessing scripts
06ce2b2
Raw
History Blame Contribute Delete
13.7 kB
"""
Full inference script: Delta Actions → Converter → Ctrl-World → Predicted Video
This demonstrates the complete inference pipeline:
1. Load Ctrl-World model (from checkpoint)
2. Load the action converter (MLP adapter)
3. Given initial observation (latent + EE state) and delta actions:
a. Convert delta actions → absolute EE states (via converter)
b. Normalize states using dataset statistics
c. Feed to world model → generate predicted future frames
d. Decode latents → video
4. Save predicted video (and optionally compare with ground truth)
Usage:
cd /mnt/filesystem-g0/Dual-Dynamics-Models/Ctrl-World
conda activate atm_ati_vdm
# Basic inference with ground truth actions:
CUDA_VISIBLE_DEVICES=0 python scripts/inference_world_model.py \
--ckpt model_ckpt/libero_ctrlworld/checkpoint-20000.pt
# Specific episode:
CUDA_VISIBLE_DEVICES=0 python scripts/inference_world_model.py \
--ckpt model_ckpt/libero_ctrlworld/checkpoint-20000.pt \
--suite libero_goal_no_noops --episode 5
# Use converter (delta actions → states) instead of ground truth states:
CUDA_VISIBLE_DEVICES=0 python scripts/inference_world_model.py \
--ckpt model_ckpt/libero_ctrlworld/checkpoint-20000.pt \
--use_converter
"""
import argparse
import glob
import json
import os
import sys
import cv2
import einops
import mediapy
import numpy as np
import torch
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config_libero import wm_args
from models.ctrl_world import CrtlWorld
from models.pipeline_ctrl_world import CtrlWorldDiffusionPipeline
from models.libero_action_converter import LiberoActionConverter
def load_rlds_episode(rlds_dir, suite, episode_idx):
"""Load a single episode from RLDS TFRecords."""
import tensorflow as tf
tf.config.set_visible_devices([], "GPU")
tfrecords = sorted(glob.glob(os.path.join(rlds_dir, suite, "1.0.0", "*.tfrecord*")))
idx = 0
for tfr in tfrecords:
for rec in tf.data.TFRecordDataset(tfr):
if idx == episode_idx:
ex = tf.train.SequenceExample()
ex.ParseFromString(rec.numpy())
s8 = np.array(ex.context.feature["steps/observation/state"].float_list.value, dtype=np.float32).reshape(-1, 8)
a7 = np.array(ex.context.feature["steps/action"].float_list.value, dtype=np.float32).reshape(-1, 7)
lang = ex.context.feature["steps/language_instruction"].bytes_list.value[0].decode()
T = min(s8.shape[0], a7.shape[0])
s7 = np.column_stack([s8[:T, :6], s8[:T, 6] - s8[:T, 7]])
return s7, a7[:T], lang
idx += 1
raise ValueError(f"Episode {episode_idx} not found")
def load_episode_latents(dataset_dir, episode_id):
"""Load preprocessed latent videos for an episode."""
for split in ["train", "val"]:
latent_dir = os.path.join(dataset_dir, "latent_videos", split, episode_id)
if os.path.exists(latent_dir):
view0 = torch.load(os.path.join(latent_dir, "0.pt"), map_location="cpu")
view1 = torch.load(os.path.join(latent_dir, "1.pt"), map_location="cpu")
view2 = torch.load(os.path.join(latent_dir, "2.pt"), map_location="cpu")
T = view0.shape[0]
stacked = torch.zeros(T, 4, 72, 40)
stacked[:, :, 0:24] = view0
stacked[:, :, 24:48] = view1
stacked[:, :, 48:72] = view2
return stacked
raise FileNotFoundError(f"Latents not found for {episode_id}")
def normalize_states(states_7d, stat_path):
"""Normalize 7D states to [-1, 1] using dataset statistics."""
with open(stat_path) as f:
stat = json.load(f)
p01 = np.array(stat["state_01"])
p99 = np.array(stat["state_99"])
normalized = 2 * (states_7d - p01) / (p99 - p01 + 1e-8) - 1
return np.clip(normalized, -1, 1)
def decode_latents(latents, pipeline, decode_chunk_size=7):
"""Decode (B, F, 4, H, W) latents → (B, F, H*8, W*8, 3) 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
decoded.append(pipeline.vae.decode(chunk, num_frames=chunk.shape[0]).sample)
video = torch.cat(decoded, dim=0)
video = video.reshape(bsz, frame_num, *video.shape[1:])
video = ((video / 2.0 + 0.5).clamp(0, 1) * 255)
return video.to(torch.float32).detach().cpu().numpy().transpose(0, 1, 3, 4, 2).astype(np.uint8)
def run_world_model_inference(
model, pipeline, latents, states_norm, text, args, device,
start_frame=0,
):
"""Run Ctrl-World inference for 16 frames from start_frame.
Args:
model: CrtlWorld model
pipeline: SVD pipeline (for decoding)
latents: (T, 4, 72, 40) full episode stacked latents
states_norm: (T, 7) normalized absolute EE states
text: task instruction string
args: wm_args config
device: torch device
start_frame: which frame to start from
Returns:
pred_frames: (16, H, W, 3) predicted agentview frames
gt_frames: (17, H, W, 3) ground truth agentview frames
"""
num_history = args.num_history # 1
num_frames = args.num_frames # 16
# Extract window: [history, current, future...]
his_idx = max(0, start_frame - 1)
window_end = min(start_frame + num_frames + 1, latents.shape[0])
window_latents = latents[his_idx:window_end].unsqueeze(0).to(device) # (1, <=17, 4, 72, 40)
# Pad if needed
actual_len = window_latents.shape[1]
if actual_len < num_history + num_frames:
pad = torch.zeros(1, num_history + num_frames - actual_len, 4, 72, 40, device=device)
window_latents = torch.cat([window_latents, pad], dim=1)
his_latent = window_latents[:, :num_history]
future_latent = window_latents[:, num_history:]
current_latent = future_latent[:, 0]
# Build action conditioning
state_start = max(0, start_frame - num_history)
state_end = min(start_frame + num_frames, states_norm.shape[0])
action_window = states_norm[state_start:state_end]
# Pad to num_history + num_frames
if len(action_window) < num_history + num_frames:
pad = np.tile(action_window[-1:], (num_history + num_frames - len(action_window), 1))
action_window = np.concatenate([action_window, pad])
action_window = action_window[:num_history + num_frames]
actions = torch.from_numpy(action_window).float().unsqueeze(0).to(device) # (1, 17, 7)
# Encode actions + text
with torch.no_grad():
action_latent = model.action_encoder(
actions, [text], model.tokenizer, model.text_encoder,
frame_level_cond=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,
)
# Split views and decode agentview only
pred_split = einops.rearrange(pred_latents, "b f c (m h) (n w) -> (b m n) f c h w", m=3, n=1)
gt_full = torch.cat([his_latent, future_latent], dim=1)
gt_split = einops.rearrange(gt_full, "b f c (m h) (n w) -> (b m n) f c h w", m=3, n=1)
# View 0 = agentview
pred_agent = pred_split[0:1] # (1, 16, 4, 24, 40)
gt_agent = gt_split[0:1] # (1, 17, 4, 24, 40)
pred_frames = decode_latents(pred_agent, pipeline)[0] # (16, 192, 320, 3)
gt_frames = decode_latents(gt_agent, pipeline)[0] # (17, 192, 320, 3)
return pred_frames, gt_frames
def main():
parser = argparse.ArgumentParser(description="Ctrl-World + Converter full inference")
parser.add_argument("--ckpt", default="model_ckpt/libero_ctrlworld/checkpoint-20000.pt")
parser.add_argument("--svd_path", default="checkpoints/svd")
parser.add_argument("--clip_path", default="checkpoints/clip-vit-base-patch32")
parser.add_argument("--adapter", default="models/converter_weights/libero_action_adapter.pt")
parser.add_argument("--stat_path", default="dataset_meta_info/libero/stat.json")
parser.add_argument("--dataset_dir", default="dataset_example/libero")
parser.add_argument("--rlds_dir", default="raw_data/modified_libero_rlds")
parser.add_argument("--suite", default="libero_spatial_no_noops")
parser.add_argument("--episode", type=int, default=3)
parser.add_argument("--start_frame", type=int, default=20)
parser.add_argument("--use_converter", action="store_true",
help="Use converter to derive states from delta actions (instead of GT states)")
parser.add_argument("--output_dir", default="scripts/adapter_samples")
args_cli = parser.parse_args()
device = torch.device("cuda:0")
# 1. Load Ctrl-World model
print("Loading Ctrl-World model...")
args = wm_args()
args.svd_model_path = args_cli.svd_path
args.clip_model_path = args_cli.clip_path
model = CrtlWorld(args)
print(f" Loading checkpoint: {args_cli.ckpt}")
state_dict = torch.load(args_cli.ckpt, map_location="cpu")
model.load_state_dict(state_dict, strict=True)
model.to(device)
model.eval()
pipeline = model.pipeline
# 2. Load converter
print("Loading action converter...")
converter = LiberoActionConverter(device=str(device))
converter.load_adapter(args_cli.adapter, device=str(device))
print(f" Converter loaded: {converter.has_adapter}")
# 3. Load episode data
suite_short = args_cli.suite.replace("_no_noops", "")
print(f"\nLoading episode {args_cli.episode} from {args_cli.suite}")
states_7d, actions, task_text = load_rlds_episode(args_cli.rlds_dir, args_cli.suite, args_cli.episode)
T = len(states_7d)
print(f" Task: {task_text}")
print(f" Episode length: {T} steps")
# 4. Load preprocessed latents
episode_id = f"{suite_short}_{args_cli.episode:04d}"
print(f" Loading latents for {episode_id}")
latents = load_episode_latents(args_cli.dataset_dir, episode_id)
print(f" Latent shape: {latents.shape}")
# 5. Get absolute EE states (GT or converter-derived)
if args_cli.use_converter:
print("\n Using CONVERTER to derive states from delta actions")
initial_state = states_7d[0]
converted = converter.trajectory(initial_state, actions[:T-1])
ee_states = converted[:T]
else:
print("\n Using GROUND TRUTH absolute states")
ee_states = states_7d
# 6. Normalize states
states_norm = normalize_states(ee_states, args_cli.stat_path).astype(np.float32)
# 7. Run world model inference for every 16-frame window
print(f"\nRunning world model inference...")
all_pred = []
all_gt = []
starts = list(range(1, min(T - 17, 80), 16))
for start in starts:
print(f" Window start={start}")
pred_frames, gt_frames = run_world_model_inference(
model, pipeline, latents, states_norm, task_text, args, device,
start_frame=start,
)
all_pred.append(pred_frames)
all_gt.append(gt_frames[1:]) # skip history frame
# 8. Save comparison video
os.makedirs(args_cli.output_dir, exist_ok=True)
mode = "converter" if args_cli.use_converter else "gt_states"
for i, (pred, gt) in enumerate(zip(all_pred, all_gt)):
n_frames = min(pred.shape[0], gt.shape[0])
comparison = np.concatenate([gt[:n_frames], pred[:n_frames]], axis=1) # stack vertically
out_path = os.path.join(args_cli.output_dir,
f"wm_inference_{suite_short}_ep{args_cli.episode}_{mode}_win{i}.mp4")
mediapy.write_video(out_path, comparison, fps=4)
# 9. Save a summary grid image
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
n_windows = len(all_pred)
fig, axes = plt.subplots(n_windows, 5, figsize=(20, 4 * n_windows))
if n_windows == 1:
axes = axes[np.newaxis, :]
for row, (pred, gt) in enumerate(zip(all_pred, all_gt)):
for col, t in enumerate([0, 3, 7, 11, 15]):
if t < pred.shape[0] and t < gt.shape[0] - 1:
combined = np.concatenate([gt[t + 1], pred[t]], axis=0)
axes[row, col].imshow(combined)
axes[row, col].set_title(f"Win {row} t={t}\nGT(top) Pred(bot)", fontsize=9)
axes[row, col].axis("off")
fig.suptitle(f"Ctrl-World Inference: {task_text[:60]}\nMode: {mode} | Checkpoint: {os.path.basename(args_cli.ckpt)}",
fontsize=13, fontweight="bold")
plt.tight_layout()
summary_path = os.path.join(args_cli.output_dir,
f"wm_inference_{suite_short}_ep{args_cli.episode}_{mode}_summary.png")
plt.savefig(summary_path, dpi=150, bbox_inches="tight")
print(f"\nSaved summary: {summary_path}")
print(f"Saved {n_windows} comparison videos to {args_cli.output_dir}/")
if __name__ == "__main__":
main()