File size: 7,932 Bytes
7f316b2 | 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 | """
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()
|