""" Example inference script for the LiberoActionConverter. Demonstrates the full workflow: 1. Load the trained MLP adapter 2. Given an initial EE state (from sim or observation) 3. Convert a sequence of delta actions into absolute EE states 4. These states can then be fed to Ctrl-World as conditioning Usage: cd /mnt/filesystem-g0/Dual-Dynamics-Models/Ctrl-World conda activate atm_ati_vdm python scripts/inference_converter_example.py # Test on specific suite: python scripts/inference_converter_example.py --suite libero_goal_no_noops # Test on specific episode: python scripts/inference_converter_example.py --episode 5 """ import argparse import glob import os import sys import numpy as np os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from models.libero_action_converter import LiberoActionConverter def load_rlds_episode(rlds_dir, suite, episode_idx=0): """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 in {suite}") def run_inference_16step(converter, states_7d, actions, start): """Run converter for 16 steps from a starting frame. This is what you'd do at inference time: - You have the current EE state (from sim or observation) - Policy outputs 16 delta actions (action chunk) - Convert to 16 absolute EE states for world model conditioning """ initial_state = states_7d[start] action_chunk = actions[start : start + 16] predicted_states = converter.trajectory(initial_state, action_chunk) return predicted_states # (17, 7) including initial def evaluate_episode(converter, states_7d, actions, stride=16): """Evaluate converter accuracy over an entire episode in 16-step windows.""" T = len(states_7d) results = [] for start in range(0, T - 17, stride): predicted = run_inference_16step(converter, states_7d, actions, start) actual = states_7d[start : start + 17] pos_errors = np.linalg.norm(predicted[:, :3] - actual[:, :3], axis=1) ori_errors = np.linalg.norm(predicted[:, 3:6] - actual[:, 3:6], axis=1) results.append({ "start": start, "pos_err_per_step": pos_errors, "ori_err_per_step": ori_errors, "pos_err_16": pos_errors[16], "ori_err_16": ori_errors[16], }) return results def main(): parser = argparse.ArgumentParser(description="Test LiberoActionConverter inference") parser.add_argument("--adapter", default="models/converter_weights/libero_action_adapter.pt") 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=0) parser.add_argument("--device", default="cuda:0") parser.add_argument("--save_dir", default="scripts/adapter_samples") args = parser.parse_args() # 1. Load converter print(f"Loading adapter from {args.adapter}") converter = LiberoActionConverter(device=args.device) converter.load_adapter(args.adapter, device=args.device) print(f" Adapter loaded: {converter.has_adapter}") # 2. Load episode print(f"\nLoading episode {args.episode} from {args.suite}") states_7d, actions, task_text = load_rlds_episode(args.rlds_dir, args.suite, args.episode) T = len(states_7d) print(f" Task: {task_text}") print(f" Episode length: {T} steps") print(f" Initial EE state: {states_7d[0]}") # 3. Run inference on every 16-frame window print(f"\nRunning 16-step inference windows (stride=16)...") results = evaluate_episode(converter, states_7d, actions, stride=16) n_windows = len(results) print(f" {n_windows} windows evaluated") # 4. Print per-window results print(f"\n{'Window':>6} {'Start':>6} {'Pos@16':>10} {'Ori@16':>10}") print("-" * 40) for r in results: print(f"{results.index(r):6d} {r['start']:6d} {r['pos_err_16']*1000:8.1f}mm {r['ori_err_16']*1000:8.1f}mrad") # 5. Summary pos_16 = np.array([r["pos_err_16"] for r in results]) ori_16 = np.array([r["ori_err_16"] for r in results]) print(f"\n{'='*50}") print(f"SUMMARY ({n_windows} windows of 16 steps)") print(f" Position: mean={pos_16.mean()*1000:.1f}mm max={pos_16.max()*1000:.1f}mm") print(f" Orientation: mean={ori_16.mean()*1000:.1f}mrad max={ori_16.max()*1000:.1f}mrad") print(f"{'='*50}") # 6. Plot try: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 2, figsize=(14, 10)) # Top left: position error over time per window for r in results: axes[0, 0].plot(r["pos_err_per_step"] * 1000, alpha=0.4, linewidth=1) axes[0, 0].set_xlabel("Step within window") axes[0, 0].set_ylabel("Position error (mm)") axes[0, 0].set_title("Position error per step (all windows)") # Top right: orientation error over time per window for r in results: axes[0, 1].plot(r["ori_err_per_step"] * 1000, alpha=0.4, linewidth=1) axes[0, 1].set_xlabel("Step within window") axes[0, 1].set_ylabel("Orientation error (mrad)") axes[0, 1].set_title("Orientation error per step (all windows)") # Bottom left: full trajectory comparison (position) full_pred = converter.trajectory(states_7d[0], actions[:T-1]) for dim, name in enumerate(["x", "y", "z"]): axes[1, 0].plot(states_7d[:, dim], label=f"GT {name}", linewidth=1.5) axes[1, 0].plot(full_pred[:T, dim], "--", label=f"Pred {name}", linewidth=1) axes[1, 0].set_xlabel("Step") axes[1, 0].set_ylabel("Position (m)") axes[1, 0].set_title("Full episode trajectory") axes[1, 0].legend(fontsize=8, ncol=2) # Bottom right: bar chart of 16-step errors per window x = np.arange(n_windows) axes[1, 1].bar(x - 0.15, pos_16 * 1000, 0.3, label="Pos (mm)", color="steelblue") axes[1, 1].bar(x + 0.15, ori_16 * 1000, 0.3, label="Ori (mrad)", color="coral") axes[1, 1].set_xlabel("Window index") axes[1, 1].set_ylabel("Error at step 16") axes[1, 1].set_title("16-step error per window") axes[1, 1].legend() fig.suptitle(f"Converter Inference: {task_text[:60]}\nEpisode {args.episode}, {T} steps, {n_windows} windows", fontsize=12, fontweight="bold") plt.tight_layout() os.makedirs(args.save_dir, exist_ok=True) save_path = os.path.join(args.save_dir, f"converter_inference_{args.suite.replace('_no_noops', '')}_ep{args.episode}.png") plt.savefig(save_path, dpi=150, bbox_inches="tight") print(f"\nPlot saved to {save_path}") except Exception as e: print(f"\nPlotting failed: {e}") if __name__ == "__main__": main()