| """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) |
| |
| def get(col): |
| return table[col][0].as_py() |
|
|
| |
| 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") |
|
|
| |
| 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_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"] |
|
|
| |
| 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_agent = sample["agent_mesh"] |
| query_wrist = np.vstack([sample["wrist_mesh"], sample["wrist_tracks"][:25]]) |
|
|
| |
| gt = sample["track_targets"] |
| gt_agent = gt[:, :7, :] |
| gt_wrist = gt[:, 7:, :] |
|
|
| |
| timesteps = predicted_tracks.shape[0] |
| pred = predicted_tracks.reshape(timesteps, 39, 2) |
| pred_agent = pred[:, :7, :] |
| pred_wrist = pred[:, 7:, :] |
|
|
| 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) |
|
|
| |
| 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") |
|
|
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| if "track_predictions" in result: |
| pred_tracks = result["track_predictions"] |
| elif "actions" in result: |
| |
| 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() |
|
|