File size: 8,417 Bytes
2a8368c | 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 | """Standalone track visualization from a saved checkpoint.
Loads the policy (with all transforms), reads raw samples from the dataset
parquet files directly, runs inference with return_tracks=True, and saves
2x3 grid visualizations. Does NOT use the training data loader.
Usage:
cd /mnt/filesystem-g0/Dual-Dynamics-Models/openpi
HF_LEROBOT_HOME=data PYTHONPATH=src:$PYTHONPATH python scripts/visualize_tracks.py \
--config pi05_realworld_track_joint \
--checkpoint-dir checkpoints/pi05_realworld_track_joint/run1/15000 \
--num-samples 5 \
--output-dir track_viz_output
"""
import argparse
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
import pyarrow.parquet as pq
from PIL import Image
logging.basicConfig(level=logging.INFO, force=True)
logger = logging.getLogger(__name__)
DATA_ROOT = "data/realworld_ee_tracks_rlds"
def load_sample(idx: int):
"""Load a single sample directly from parquet via pyarrow."""
parquet_path = os.path.join(DATA_ROOT, "data/chunk-000", f"episode_{idx:06d}.parquet")
table = pq.read_table(parquet_path)
# Get first row via column access (avoids pandas iloc bug)
def get(col):
return table[col][0].as_py()
# Load images (stored as {'bytes': b'...', 'path': '...'} dicts)
def load_image(col):
import io as _io
val = get(col)
if isinstance(val, dict) and "bytes" in val:
return np.array(Image.open(_io.BytesIO(val["bytes"])).convert("RGB"))
elif isinstance(val, dict) and "path" in val:
return np.array(Image.open(val["path"]).convert("RGB"))
else:
return np.array(Image.open(_io.BytesIO(val)).convert("RGB"))
img_agent = load_image("image")
img_wrist = load_image("wrist_image")
# Track data
agent_mesh = np.array(get("agentview_mesh_vertices_2d")).reshape(7, 2)
wrist_mesh = np.array(get("wrist_mesh_vertices_2d")).reshape(7, 2)
wrist_tracks = np.array(get("wrist_tracks")).reshape(32, 2)
track_targets = np.array(get("track_targets_raw")).reshape(16, 39, 2)
# Task prompt
task_index = int(get("task_index"))
import json
tasks_path = os.path.join(DATA_ROOT, "meta/tasks.jsonl")
with open(tasks_path) as f:
tasks = [json.loads(line) for line in f]
prompt = tasks[task_index]["task"]
# Query points: 78D = [agent_mesh(7x2=14), wrist_mesh(7x2=14), wrist_uniform(25x2=50)]
wrist_uniform = wrist_tracks[:25]
query_points = np.concatenate([
agent_mesh.flatten(),
wrist_mesh.flatten(),
wrist_uniform.flatten(),
])
return {
"img_agent": img_agent,
"img_wrist": img_wrist,
"agent_mesh": agent_mesh,
"wrist_mesh": wrist_mesh,
"wrist_tracks": wrist_tracks,
"query_points": query_points,
"track_targets": track_targets,
"prompt": prompt,
}
def build_policy_input(sample):
"""Build the dict that the policy's infer() expects (pre-transform)."""
return {
"observation/image": sample["img_agent"],
"observation/wrist_image": sample["img_wrist"],
"observation/state": np.zeros(10, dtype=np.float32),
"prompt": sample["prompt"],
"agentview_mesh_vertices_2d": sample["agent_mesh"].astype(np.float32),
"wrist_mesh_vertices_2d": sample["wrist_mesh"].astype(np.float32),
"wrist_tracks": sample["wrist_tracks"].astype(np.float32),
"track_targets_raw": sample["track_targets"].astype(np.float32),
}
def visualize(sample, predicted_tracks, step_name, sample_idx, output_dir):
"""Create 2x3 visualization grid and save."""
img_agent = sample["img_agent"]
img_wrist = sample["img_wrist"]
H, W = img_agent.shape[:2]
# Query points
query_agent = sample["agent_mesh"] # (7, 2)
query_wrist = np.vstack([sample["wrist_mesh"], sample["wrist_tracks"][:25]]) # (32, 2)
# Ground truth: (16, 39, 2)
gt = sample["track_targets"]
gt_agent = gt[:, :7, :] # (16, 7, 2)
gt_wrist = gt[:, 7:, :] # (16, 32, 2)
# Predicted: (16, 78) -> reshape
timesteps = predicted_tracks.shape[0]
pred = predicted_tracks.reshape(timesteps, 39, 2)
pred_agent = pred[:, :7, :] # (16, 7, 2)
pred_wrist = pred[:, 7:, :] # (16, 32, 2)
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.suptitle(f"Track Prediction — ckpt {step_name} — sample {sample_idx}\n\"{sample['prompt']}\"", fontsize=14)
# Row 1: Agentview
axes[0, 0].imshow(img_agent)
axes[0, 0].scatter(query_agent[:, 0] * W, query_agent[:, 1] * H, c="red", s=30)
axes[0, 0].set_title(f"Agentview: Query ({len(query_agent)} pts)")
axes[0, 0].axis("off")
axes[0, 1].imshow(img_agent)
for j in range(pred_agent.shape[1]):
axes[0, 1].plot(pred_agent[:, j, 0] * W, pred_agent[:, j, 1] * H, alpha=0.6, linewidth=2)
axes[0, 1].set_title(f"Agentview: Predicted")
axes[0, 1].axis("off")
axes[0, 2].imshow(img_agent)
for j in range(gt_agent.shape[1]):
axes[0, 2].plot(gt_agent[:, j, 0] * W, gt_agent[:, j, 1] * H, alpha=0.6, linewidth=2)
axes[0, 2].set_title(f"Agentview: Ground Truth")
axes[0, 2].axis("off")
# Row 2: Wrist
axes[1, 0].imshow(img_wrist)
axes[1, 0].scatter(query_wrist[:, 0] * W, query_wrist[:, 1] * H, c="red", s=20)
axes[1, 0].set_title(f"Eyeinhand: Query ({len(query_wrist)} pts)")
axes[1, 0].axis("off")
axes[1, 1].imshow(img_wrist)
for j in range(pred_wrist.shape[1]):
axes[1, 1].plot(pred_wrist[:, j, 0] * W, pred_wrist[:, j, 1] * H, alpha=0.5, linewidth=1.5)
axes[1, 1].set_title(f"Eyeinhand: Predicted")
axes[1, 1].axis("off")
axes[1, 2].imshow(img_wrist)
for j in range(gt_wrist.shape[1]):
axes[1, 2].plot(gt_wrist[:, j, 0] * W, gt_wrist[:, j, 1] * H, alpha=0.5, linewidth=1.5)
axes[1, 2].set_title(f"Eyeinhand: Ground Truth")
axes[1, 2].axis("off")
plt.tight_layout()
save_path = os.path.join(output_dir, f"tracks_ckpt{step_name}_sample{sample_idx}.png")
plt.savefig(save_path, dpi=150, bbox_inches="tight")
plt.close(fig)
logger.info(f"Saved: {save_path}")
def main():
parser = argparse.ArgumentParser(description="Visualize track predictions from a checkpoint")
parser.add_argument("--config", type=str, required=True)
parser.add_argument("--checkpoint-dir", type=str, required=True)
parser.add_argument("--num-samples", type=int, default=5)
parser.add_argument("--output-dir", type=str, default="track_viz_output")
parser.add_argument("--episode-start", type=int, default=0, help="First episode index")
parser.add_argument("--episode-step", type=int, default=20, help="Step between episodes")
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
# Load policy
from openpi.training import config as _config
from openpi.policies import policy_config as _policy_config
config = _config.get_config(args.config)
logger.info(f"Loading policy from {args.checkpoint_dir}")
policy = _policy_config.create_trained_policy(
config, args.checkpoint_dir,
sample_kwargs={"return_tracks": True},
)
logger.info("Policy loaded")
step_name = os.path.basename(args.checkpoint_dir)
for i in range(args.num_samples):
ep_idx = args.episode_start + i * args.episode_step
logger.info(f"Sample {i+1}/{args.num_samples} (episode {ep_idx})")
try:
sample = load_sample(ep_idx)
obs = build_policy_input(sample)
result = policy.infer(obs)
# Extract track predictions
if "track_predictions" in result:
pred_tracks = result["track_predictions"]
elif "actions" in result:
# Tracks might be in actions if no separate head
pred_tracks = result["actions"]
else:
logger.warning(f"No track predictions found in result keys: {list(result.keys())}")
continue
visualize(sample, pred_tracks, step_name, i, args.output_dir)
except Exception as e:
logger.error(f"Error on episode {ep_idx}: {e}")
import traceback
traceback.print_exc()
logger.info(f"Done! Visualizations saved to {args.output_dir}/")
if __name__ == "__main__":
main()
|