bot commited on
Commit ·
9ad6280
1
Parent(s): 0f1e257
Restore all project files from original repo
Browse files- build_index.py +316 -0
- compute_stats.py +98 -0
- eval_kitchen.py +263 -0
- eval_sim.py +171 -0
- filtered_index.json +0 -0
- infer_so101.py +223 -0
- norm_stats.json +38 -0
- so100_dataset.py +325 -0
build_index.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Build a filtered training index from community_dataset_v3 on disk.
|
| 4 |
+
|
| 5 |
+
Applies:
|
| 6 |
+
- Robot type filter (so100/so101 variants only)
|
| 7 |
+
- Schema filter (2 cameras, 6-DOF, 30fps)
|
| 8 |
+
- Episode length filter (5s-60s)
|
| 9 |
+
- Per-task cap (default 200)
|
| 10 |
+
- Per-contributor cap (default 200)
|
| 11 |
+
- Excludes datasets with file count mismatches
|
| 12 |
+
|
| 13 |
+
Outputs filtered_index.json with all info needed to train.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import glob
|
| 18 |
+
import json
|
| 19 |
+
import random
|
| 20 |
+
from collections import defaultdict
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import av
|
| 24 |
+
import pandas as pd
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_video_duration(video_path: Path) -> float:
|
| 28 |
+
"""Get video duration in seconds by reading container metadata (fast, no decoding)."""
|
| 29 |
+
try:
|
| 30 |
+
container = av.open(str(video_path))
|
| 31 |
+
stream = container.streams.video[0]
|
| 32 |
+
duration = float(stream.duration * stream.time_base)
|
| 33 |
+
container.close()
|
| 34 |
+
return duration
|
| 35 |
+
except Exception:
|
| 36 |
+
return 0.0
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_dataset_meta(dataset_root: Path) -> dict | None:
|
| 40 |
+
"""Load and validate a single dataset's metadata."""
|
| 41 |
+
info_path = dataset_root / "meta" / "info.json"
|
| 42 |
+
if not info_path.exists():
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
info = json.load(open(info_path))
|
| 46 |
+
|
| 47 |
+
# Robot type filter
|
| 48 |
+
robot = info.get("robot_type", "")
|
| 49 |
+
if robot not in ("so100", "so101", "so100_follower", "so101_follower"):
|
| 50 |
+
return None
|
| 51 |
+
|
| 52 |
+
# Schema filter: exactly the 2-camera, 6-DOF schema
|
| 53 |
+
features = info.get("features", {})
|
| 54 |
+
expected_keys = {
|
| 55 |
+
"action", "episode_index", "frame_index", "index",
|
| 56 |
+
"observation.images.image", "observation.images.image2",
|
| 57 |
+
"observation.state", "task_index", "timestamp",
|
| 58 |
+
}
|
| 59 |
+
if set(features.keys()) != expected_keys:
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
# Dimension check
|
| 63 |
+
if features.get("action", {}).get("shape") != [6]:
|
| 64 |
+
return None
|
| 65 |
+
if features.get("observation.state", {}).get("shape") != [6]:
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
# FPS check
|
| 69 |
+
if info.get("fps") != 30:
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
# Resolution check
|
| 73 |
+
for cam_key in ("observation.images.image", "observation.images.image2"):
|
| 74 |
+
shape = features.get(cam_key, {}).get("shape", [])
|
| 75 |
+
if len(shape) < 2 or shape[0] != 480 or shape[1] != 640:
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
# Load tasks
|
| 79 |
+
tasks_path = dataset_root / "meta" / "tasks.jsonl"
|
| 80 |
+
tasks = {}
|
| 81 |
+
if tasks_path.exists():
|
| 82 |
+
for line in open(tasks_path):
|
| 83 |
+
line = line.strip()
|
| 84 |
+
if line:
|
| 85 |
+
t = json.loads(line)
|
| 86 |
+
tasks[t["task_index"]] = t["task"]
|
| 87 |
+
|
| 88 |
+
# Integrity check: video and parquet file counts
|
| 89 |
+
total_eps = info.get("total_episodes", 0)
|
| 90 |
+
vids = glob.glob(str(dataset_root / "videos" / "**" / "*.mp4"), recursive=True)
|
| 91 |
+
parquets = glob.glob(str(dataset_root / "data" / "**" / "*.parquet"), recursive=True)
|
| 92 |
+
expected_vids = total_eps * 2 # 2 cameras
|
| 93 |
+
if len(vids) != expected_vids or len(parquets) != total_eps:
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
# Load episode metadata if available
|
| 97 |
+
episodes = []
|
| 98 |
+
ep_jsonl = dataset_root / "meta" / "episodes.jsonl"
|
| 99 |
+
if ep_jsonl.exists():
|
| 100 |
+
for line in open(ep_jsonl):
|
| 101 |
+
line = line.strip()
|
| 102 |
+
if line:
|
| 103 |
+
episodes.append(json.loads(line))
|
| 104 |
+
|
| 105 |
+
return {
|
| 106 |
+
"robot_type": robot,
|
| 107 |
+
"total_episodes": total_eps,
|
| 108 |
+
"total_frames": info.get("total_frames", 0),
|
| 109 |
+
"fps": info["fps"],
|
| 110 |
+
"tasks": tasks,
|
| 111 |
+
"episodes": episodes,
|
| 112 |
+
"features": {k: v.get("shape") for k, v in features.items()},
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def build_index(
|
| 117 |
+
data_root: Path,
|
| 118 |
+
max_per_task: int = 200,
|
| 119 |
+
max_per_contributor: int = 200,
|
| 120 |
+
min_episode_frames: int = 150,
|
| 121 |
+
max_episode_frames: int = 1800,
|
| 122 |
+
seed: int = 42,
|
| 123 |
+
) -> dict:
|
| 124 |
+
"""Build filtered training index."""
|
| 125 |
+
rng = random.Random(seed)
|
| 126 |
+
|
| 127 |
+
# Discover all contributor/dataset pairs
|
| 128 |
+
contributors = sorted([
|
| 129 |
+
d for d in data_root.iterdir()
|
| 130 |
+
if d.is_dir() and not d.name.startswith(".")
|
| 131 |
+
])
|
| 132 |
+
|
| 133 |
+
# Phase 1: Load all valid datasets
|
| 134 |
+
all_episodes = [] # (contributor, dataset_name, episode_idx, task, num_frames)
|
| 135 |
+
datasets_passed = 0
|
| 136 |
+
datasets_rejected = 0
|
| 137 |
+
skipped_missing = 0
|
| 138 |
+
skipped_video_mismatch = 0
|
| 139 |
+
|
| 140 |
+
for contrib_dir in contributors:
|
| 141 |
+
if not contrib_dir.is_dir():
|
| 142 |
+
continue
|
| 143 |
+
contributor = contrib_dir.name
|
| 144 |
+
|
| 145 |
+
for ds_dir in sorted(contrib_dir.iterdir()):
|
| 146 |
+
if not ds_dir.is_dir():
|
| 147 |
+
continue
|
| 148 |
+
|
| 149 |
+
meta = load_dataset_meta(ds_dir)
|
| 150 |
+
if meta is None:
|
| 151 |
+
datasets_rejected += 1
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
datasets_passed += 1
|
| 155 |
+
dataset_name = f"{contributor}/{ds_dir.name}"
|
| 156 |
+
|
| 157 |
+
# Default task if none specified
|
| 158 |
+
if not meta["tasks"]:
|
| 159 |
+
meta["tasks"] = {0: "(no task)"}
|
| 160 |
+
|
| 161 |
+
# Build episode list by reading actual parquet files
|
| 162 |
+
# Trust the parquet row count, not metadata
|
| 163 |
+
for ep_idx in range(meta["total_episodes"]):
|
| 164 |
+
parquet_path = ds_dir / f"data/chunk-000/episode_{ep_idx:06d}.parquet"
|
| 165 |
+
if not parquet_path.exists():
|
| 166 |
+
skipped_missing += 1
|
| 167 |
+
continue
|
| 168 |
+
|
| 169 |
+
# Read actual row count and timestamps from parquet
|
| 170 |
+
pf_full = pd.read_parquet(parquet_path, columns=["frame_index", "timestamp"])
|
| 171 |
+
actual_length = len(pf_full)
|
| 172 |
+
|
| 173 |
+
if actual_length < min_episode_frames or actual_length > max_episode_frames:
|
| 174 |
+
continue
|
| 175 |
+
|
| 176 |
+
# Also verify both video files exist
|
| 177 |
+
vid1 = ds_dir / f"videos/chunk-000/observation.images.image/episode_{ep_idx:06d}.mp4"
|
| 178 |
+
vid2 = ds_dir / f"videos/chunk-000/observation.images.image2/episode_{ep_idx:06d}.mp4"
|
| 179 |
+
if not vid1.exists() or not vid2.exists():
|
| 180 |
+
skipped_missing += 1
|
| 181 |
+
continue
|
| 182 |
+
|
| 183 |
+
# Verify video duration covers all parquet timestamps
|
| 184 |
+
# The last frame's timestamp must be within the video duration
|
| 185 |
+
last_timestamp = float(pf_full["timestamp"].iloc[-1])
|
| 186 |
+
vid1_duration = get_video_duration(vid1)
|
| 187 |
+
vid2_duration = get_video_duration(vid2)
|
| 188 |
+
min_vid_duration = min(vid1_duration, vid2_duration)
|
| 189 |
+
if min_vid_duration > 0 and last_timestamp > min_vid_duration:
|
| 190 |
+
# Video is shorter than parquet claims — truncate to what the video covers
|
| 191 |
+
# Find the last frame index where timestamp <= video duration
|
| 192 |
+
valid_mask = pf_full["timestamp"] <= min_vid_duration
|
| 193 |
+
actual_length = int(valid_mask.sum())
|
| 194 |
+
if actual_length < min_episode_frames:
|
| 195 |
+
skipped_video_mismatch += 1
|
| 196 |
+
continue
|
| 197 |
+
|
| 198 |
+
# Get task from episodes.jsonl if available, else default
|
| 199 |
+
task_idx = 0
|
| 200 |
+
if meta["episodes"]:
|
| 201 |
+
for ep_meta in meta["episodes"]:
|
| 202 |
+
if ep_meta.get("episode_index") == ep_idx:
|
| 203 |
+
task_idx = ep_meta.get("task_index", 0)
|
| 204 |
+
break
|
| 205 |
+
|
| 206 |
+
task = meta["tasks"].get(task_idx, "(no task)")
|
| 207 |
+
all_episodes.append((contributor, dataset_name, ep_idx, task, actual_length))
|
| 208 |
+
|
| 209 |
+
print(f"Datasets: {datasets_passed} passed, {datasets_rejected} rejected")
|
| 210 |
+
print(f"Episodes verified: {len(all_episodes)}, skipped missing: {skipped_missing}, skipped video mismatch: {skipped_video_mismatch}")
|
| 211 |
+
print(f"Episodes before caps: {len(all_episodes)}")
|
| 212 |
+
|
| 213 |
+
# Phase 2: Apply per-task cap
|
| 214 |
+
task_buckets = defaultdict(list)
|
| 215 |
+
for ep in all_episodes:
|
| 216 |
+
task_buckets[ep[3]].append(ep)
|
| 217 |
+
|
| 218 |
+
after_task_cap = []
|
| 219 |
+
tasks_capped = 0
|
| 220 |
+
for task, eps in task_buckets.items():
|
| 221 |
+
rng.shuffle(eps)
|
| 222 |
+
if len(eps) > max_per_task:
|
| 223 |
+
tasks_capped += 1
|
| 224 |
+
after_task_cap.extend(eps[:max_per_task])
|
| 225 |
+
|
| 226 |
+
print(f"Episodes after per-task cap ({max_per_task}): {len(after_task_cap)} ({tasks_capped} tasks capped)")
|
| 227 |
+
|
| 228 |
+
# Phase 3: Apply per-contributor cap
|
| 229 |
+
contrib_buckets = defaultdict(list)
|
| 230 |
+
for ep in after_task_cap:
|
| 231 |
+
contrib_buckets[ep[0]].append(ep)
|
| 232 |
+
|
| 233 |
+
final_episodes = []
|
| 234 |
+
contribs_capped = 0
|
| 235 |
+
for contributor, eps in contrib_buckets.items():
|
| 236 |
+
rng.shuffle(eps)
|
| 237 |
+
if len(eps) > max_per_contributor:
|
| 238 |
+
contribs_capped += 1
|
| 239 |
+
final_episodes.extend(eps[:max_per_contributor])
|
| 240 |
+
|
| 241 |
+
print(f"Episodes after per-contributor cap ({max_per_contributor}): {len(final_episodes)} ({contribs_capped} contributors capped)")
|
| 242 |
+
|
| 243 |
+
# Phase 4: Build the index
|
| 244 |
+
# Sort for determinism
|
| 245 |
+
final_episodes.sort(key=lambda x: (x[1], x[2]))
|
| 246 |
+
|
| 247 |
+
# Collect unique tasks
|
| 248 |
+
unique_tasks = sorted(set(ep[3] for ep in final_episodes))
|
| 249 |
+
task_to_idx = {t: i for i, t in enumerate(unique_tasks)}
|
| 250 |
+
|
| 251 |
+
# Collect unique datasets used
|
| 252 |
+
datasets_used = sorted(set(ep[1] for ep in final_episodes))
|
| 253 |
+
|
| 254 |
+
# Build episode entries
|
| 255 |
+
entries = []
|
| 256 |
+
total_frames = 0
|
| 257 |
+
for contributor, dataset_name, ep_idx, task, num_frames in final_episodes:
|
| 258 |
+
entries.append({
|
| 259 |
+
"dataset": dataset_name,
|
| 260 |
+
"episode_index": ep_idx,
|
| 261 |
+
"task": task,
|
| 262 |
+
"task_index": task_to_idx[task],
|
| 263 |
+
"num_frames": num_frames,
|
| 264 |
+
})
|
| 265 |
+
total_frames += num_frames
|
| 266 |
+
|
| 267 |
+
index = {
|
| 268 |
+
"source_repo": "HuggingFaceVLA/community_dataset_v3",
|
| 269 |
+
"filters": {
|
| 270 |
+
"max_per_task": max_per_task,
|
| 271 |
+
"max_per_contributor": max_per_contributor,
|
| 272 |
+
"min_episode_frames": min_episode_frames,
|
| 273 |
+
"max_episode_frames": max_episode_frames,
|
| 274 |
+
"seed": seed,
|
| 275 |
+
},
|
| 276 |
+
"summary": {
|
| 277 |
+
"datasets": len(datasets_used),
|
| 278 |
+
"episodes": len(entries),
|
| 279 |
+
"unique_tasks": len(unique_tasks),
|
| 280 |
+
"total_frames": total_frames,
|
| 281 |
+
"est_hours": total_frames / 30 / 3600,
|
| 282 |
+
},
|
| 283 |
+
"tasks": unique_tasks,
|
| 284 |
+
"datasets_used": datasets_used,
|
| 285 |
+
"episodes": entries,
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
return index
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
if __name__ == "__main__":
|
| 292 |
+
parser = argparse.ArgumentParser()
|
| 293 |
+
parser.add_argument("--data-root", type=Path, default=Path.home() / "lap" / "community_dataset_v3")
|
| 294 |
+
parser.add_argument("--output", type=Path, default=Path(__file__).parent / "filtered_index.json")
|
| 295 |
+
parser.add_argument("--max-per-task", type=int, default=200)
|
| 296 |
+
parser.add_argument("--max-per-contributor", type=int, default=200)
|
| 297 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 298 |
+
args = parser.parse_args()
|
| 299 |
+
|
| 300 |
+
index = build_index(
|
| 301 |
+
args.data_root,
|
| 302 |
+
max_per_task=args.max_per_task,
|
| 303 |
+
max_per_contributor=args.max_per_contributor,
|
| 304 |
+
seed=args.seed,
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 308 |
+
with open(args.output, "w") as f:
|
| 309 |
+
json.dump(index, f, indent=2)
|
| 310 |
+
|
| 311 |
+
print(f"\nSaved to {args.output}")
|
| 312 |
+
print(f" Datasets: {index['summary']['datasets']}")
|
| 313 |
+
print(f" Episodes: {index['summary']['episodes']}")
|
| 314 |
+
print(f" Tasks: {index['summary']['unique_tasks']}")
|
| 315 |
+
print(f" Frames: {index['summary']['total_frames']:,}")
|
| 316 |
+
print(f" Est. hours: {index['summary']['est_hours']:.1f}")
|
compute_stats.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Compute normalization statistics (mean/std) for state and action across the filtered dataset.
|
| 4 |
+
Only reads parquet files — no video decoding, so it's fast.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import json
|
| 9 |
+
import time
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import pandas as pd
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def compute_stats(data_root: Path, index_path: Path) -> dict:
|
| 17 |
+
with open(index_path) as f:
|
| 18 |
+
index = json.load(f)
|
| 19 |
+
|
| 20 |
+
# Collect all unique (dataset, episode) pairs
|
| 21 |
+
episode_set = set()
|
| 22 |
+
for ep in index["episodes"]:
|
| 23 |
+
episode_set.add((ep["dataset"], ep["episode_index"]))
|
| 24 |
+
|
| 25 |
+
print(f"Computing stats from {len(episode_set)} episodes...")
|
| 26 |
+
|
| 27 |
+
# Online mean/variance computation (Welford's algorithm)
|
| 28 |
+
state_sum = np.zeros(6, dtype=np.float64)
|
| 29 |
+
state_sq_sum = np.zeros(6, dtype=np.float64)
|
| 30 |
+
action_sum = np.zeros(6, dtype=np.float64)
|
| 31 |
+
action_sq_sum = np.zeros(6, dtype=np.float64)
|
| 32 |
+
n_state = 0
|
| 33 |
+
n_action = 0
|
| 34 |
+
|
| 35 |
+
start = time.time()
|
| 36 |
+
for i, (dataset, ep_idx) in enumerate(sorted(episode_set)):
|
| 37 |
+
parquet_path = data_root / dataset / f"data/chunk-000/episode_{ep_idx:06d}.parquet"
|
| 38 |
+
if not parquet_path.exists():
|
| 39 |
+
continue
|
| 40 |
+
|
| 41 |
+
df = pd.read_parquet(parquet_path)
|
| 42 |
+
|
| 43 |
+
states = np.stack(df["observation.state"].values).astype(np.float64)
|
| 44 |
+
actions = np.stack(df["action"].values).astype(np.float64)
|
| 45 |
+
|
| 46 |
+
state_sum += states.sum(axis=0)
|
| 47 |
+
state_sq_sum += (states ** 2).sum(axis=0)
|
| 48 |
+
n_state += len(states)
|
| 49 |
+
|
| 50 |
+
action_sum += actions.sum(axis=0)
|
| 51 |
+
action_sq_sum += (actions ** 2).sum(axis=0)
|
| 52 |
+
n_action += len(actions)
|
| 53 |
+
|
| 54 |
+
if (i + 1) % 1000 == 0:
|
| 55 |
+
elapsed = time.time() - start
|
| 56 |
+
rate = (i + 1) / elapsed
|
| 57 |
+
eta = (len(episode_set) - i - 1) / rate
|
| 58 |
+
print(f" [{i+1}/{len(episode_set)}] {rate:.0f} eps/s, ETA: {eta:.0f}s")
|
| 59 |
+
|
| 60 |
+
state_mean = state_sum / n_state
|
| 61 |
+
state_std = np.sqrt(state_sq_sum / n_state - state_mean ** 2)
|
| 62 |
+
|
| 63 |
+
action_mean = action_sum / n_action
|
| 64 |
+
action_std = np.sqrt(action_sq_sum / n_action - action_mean ** 2)
|
| 65 |
+
|
| 66 |
+
elapsed = time.time() - start
|
| 67 |
+
print(f"Done in {elapsed:.1f}s ({n_state:,} state frames, {n_action:,} action frames)")
|
| 68 |
+
|
| 69 |
+
print(f"\nState mean: {state_mean}")
|
| 70 |
+
print(f"State std: {state_std}")
|
| 71 |
+
print(f"Action mean: {action_mean}")
|
| 72 |
+
print(f"Action std: {action_std}")
|
| 73 |
+
|
| 74 |
+
stats = {
|
| 75 |
+
"observation.state": {
|
| 76 |
+
"mean": state_mean.tolist(),
|
| 77 |
+
"std": state_std.tolist(),
|
| 78 |
+
},
|
| 79 |
+
"action": {
|
| 80 |
+
"mean": action_mean.tolist(),
|
| 81 |
+
"std": action_std.tolist(),
|
| 82 |
+
},
|
| 83 |
+
}
|
| 84 |
+
return stats
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
parser = argparse.ArgumentParser()
|
| 89 |
+
parser.add_argument("--data-root", type=Path, default=Path.home() / "lap" / "community_dataset_v3")
|
| 90 |
+
parser.add_argument("--index", type=Path, default=Path(__file__).parent / "filtered_index.json")
|
| 91 |
+
parser.add_argument("--output", type=Path, default=Path(__file__).parent / "norm_stats.json")
|
| 92 |
+
args = parser.parse_args()
|
| 93 |
+
|
| 94 |
+
stats = compute_stats(args.data_root, args.index)
|
| 95 |
+
|
| 96 |
+
with open(args.output, "w") as f:
|
| 97 |
+
json.dump(stats, f, indent=2)
|
| 98 |
+
print(f"\nSaved to {args.output}")
|
eval_kitchen.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Evaluate Pi0.5 checkpoints in the RoboCasa kitchen sim.
|
| 4 |
+
Compares base model vs finetuned model side by side.
|
| 5 |
+
|
| 6 |
+
Runs on CPU only (GPU is used by training).
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python eval_kitchen.py --checkpoint /mnt/hdd/pi05-training/full_run/checkpoints/004000/pretrained_model
|
| 10 |
+
python eval_kitchen.py --checkpoint lerobot/pi05_base # base model comparison
|
| 11 |
+
python eval_kitchen.py --compare # run both and save side-by-side
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
# EGL rendering for headless MuJoCo
|
| 21 |
+
os.environ["MUJOCO_GL"] = "egl"
|
| 22 |
+
|
| 23 |
+
import imageio
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 28 |
+
sys.path.insert(0, str(Path.home() / "lerobot" / "src"))
|
| 29 |
+
sys.path.insert(0, "/mnt/hdd/pi05-training/robocasa_test")
|
| 30 |
+
|
| 31 |
+
from so100_kitchen_env import SO100KitchenEnv
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def load_policy(checkpoint_path, device="cuda"):
|
| 35 |
+
"""Load Pi0.5 policy."""
|
| 36 |
+
from lerobot.policies.pi05.modeling_pi05 import PI05Policy
|
| 37 |
+
print(f"Loading policy from {checkpoint_path} ({device})...")
|
| 38 |
+
policy = PI05Policy.from_pretrained(str(checkpoint_path))
|
| 39 |
+
policy = policy.to(device)
|
| 40 |
+
policy.eval()
|
| 41 |
+
return policy
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def build_batch(env_obs, camera_image, task, stats, device="cuda"):
|
| 45 |
+
"""Convert kitchen env observation to Pi0.5 batch format."""
|
| 46 |
+
import torchvision.transforms.functional as TF
|
| 47 |
+
|
| 48 |
+
# Image: (H, W, 3) uint8 -> (1, 3, 224, 224) float32
|
| 49 |
+
image = torch.from_numpy(camera_image).permute(2, 0, 1).float() / 255.0
|
| 50 |
+
image = image.unsqueeze(0)
|
| 51 |
+
image_224 = TF.resize(image, [224, 224], antialias=True)
|
| 52 |
+
|
| 53 |
+
# ImageNet normalization
|
| 54 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
|
| 55 |
+
std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
|
| 56 |
+
image_224 = (image_224 - mean) / std
|
| 57 |
+
|
| 58 |
+
# State: joint positions in radians -> degrees (LeRobot scale), then normalize
|
| 59 |
+
joint_pos = env_obs["joint_pos"]
|
| 60 |
+
state_degrees = np.degrees(joint_pos)
|
| 61 |
+
state = torch.tensor(state_degrees, dtype=torch.float32).unsqueeze(0)
|
| 62 |
+
|
| 63 |
+
state_mean = torch.tensor(stats["observation.state"]["mean"], dtype=torch.float32)
|
| 64 |
+
state_std = torch.tensor(stats["observation.state"]["std"], dtype=torch.float32)
|
| 65 |
+
state = (state - state_mean) / (state_std + 1e-8)
|
| 66 |
+
|
| 67 |
+
# Pad to 32 dims
|
| 68 |
+
state_padded = torch.zeros(1, 32)
|
| 69 |
+
state_padded[:, :6] = state
|
| 70 |
+
|
| 71 |
+
# Tokenize
|
| 72 |
+
from transformers import AutoTokenizer
|
| 73 |
+
tokenizer = AutoTokenizer.from_pretrained("google/paligemma-3b-pt-224")
|
| 74 |
+
|
| 75 |
+
state_discrete = ((state[0].clamp(-1, 1) + 1) / 2 * 255).int()
|
| 76 |
+
state_str = " ".join(str(v.item()) for v in state_discrete)
|
| 77 |
+
prompt = f"Task: {task}, State: {state_str};\nAction: "
|
| 78 |
+
|
| 79 |
+
tokens = tokenizer(
|
| 80 |
+
prompt, padding="max_length", max_length=200,
|
| 81 |
+
truncation=True, return_tensors="pt",
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
return {
|
| 85 |
+
"observation.images.base_0_rgb": image_224.to(device),
|
| 86 |
+
"observation.images.left_wrist_0_rgb": image_224.to(device),
|
| 87 |
+
"observation.state": state_padded.to(device),
|
| 88 |
+
"observation.language.tokens": tokens["input_ids"].to(device),
|
| 89 |
+
"observation.language.attention_mask": tokens["attention_mask"].bool().to(device),
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def decode_actions(raw_actions, stats):
|
| 94 |
+
"""Convert model output to joint angle radians."""
|
| 95 |
+
actions = raw_actions[0, :, :6].cpu().numpy()
|
| 96 |
+
action_mean = np.array(stats["action"]["mean"])
|
| 97 |
+
action_std = np.array(stats["action"]["std"])
|
| 98 |
+
actions = actions * action_std + action_mean
|
| 99 |
+
return np.radians(actions)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def run_episode(policy, env, task, stats, num_steps=200, camera="robot_workspace", show_live=True):
|
| 103 |
+
"""Run one episode, return frames and joint trajectories."""
|
| 104 |
+
obs = env.reset()
|
| 105 |
+
frames = []
|
| 106 |
+
joint_history = []
|
| 107 |
+
chunk_actions = None
|
| 108 |
+
chunk_idx = 0
|
| 109 |
+
|
| 110 |
+
for step in range(num_steps):
|
| 111 |
+
if chunk_actions is None or chunk_idx >= len(chunk_actions):
|
| 112 |
+
camera_image = env.render(camera)
|
| 113 |
+
with torch.no_grad():
|
| 114 |
+
batch = build_batch(obs, camera_image, task, stats, device=next(policy.parameters()).device)
|
| 115 |
+
action = policy.select_action(batch)
|
| 116 |
+
chunk_actions = decode_actions(action.unsqueeze(0), stats)
|
| 117 |
+
chunk_idx = 0
|
| 118 |
+
|
| 119 |
+
action = chunk_actions[chunk_idx]
|
| 120 |
+
chunk_idx += 1
|
| 121 |
+
|
| 122 |
+
obs, reward, done, info = env.step(action)
|
| 123 |
+
frame = env.render(camera)
|
| 124 |
+
frames.append(frame)
|
| 125 |
+
joint_history.append(obs["joint_pos"].copy())
|
| 126 |
+
|
| 127 |
+
# Live display via cv2 (static camera)
|
| 128 |
+
if show_live:
|
| 129 |
+
try:
|
| 130 |
+
import cv2
|
| 131 |
+
cv2.imshow("SO-100 Kitchen Sim", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
| 132 |
+
if cv2.waitKey(1) & 0xFF == ord('q'):
|
| 133 |
+
print("Quit by user")
|
| 134 |
+
break
|
| 135 |
+
except Exception:
|
| 136 |
+
pass
|
| 137 |
+
|
| 138 |
+
if step % 25 == 0:
|
| 139 |
+
pos = obs["joint_pos"]
|
| 140 |
+
print(f" step {step:>3}: joints=[{pos[0]:.2f} {pos[1]:.2f} {pos[2]:.2f} {pos[3]:.2f} {pos[4]:.2f} {pos[5]:.3f}]")
|
| 141 |
+
|
| 142 |
+
return frames, np.array(joint_history)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def main():
|
| 146 |
+
parser = argparse.ArgumentParser()
|
| 147 |
+
parser.add_argument("--checkpoint", type=str, default=None)
|
| 148 |
+
parser.add_argument("--task", type=str, default="pick up the mug and place it on the plate")
|
| 149 |
+
parser.add_argument("--steps", type=int, default=200)
|
| 150 |
+
parser.add_argument("--output-dir", type=str, default="/mnt/hdd/pi05-training/eval_kitchen")
|
| 151 |
+
parser.add_argument("--compare", action="store_true", help="Run base vs finetuned comparison")
|
| 152 |
+
parser.add_argument("--viewer", action="store_true", help="Use MuJoCo interactive viewer (mouse orbit/pan/zoom)")
|
| 153 |
+
parser.add_argument("--finetuned-checkpoint", type=str,
|
| 154 |
+
default="/mnt/hdd/pi05-training/full_run/checkpoints/004000/pretrained_model")
|
| 155 |
+
args = parser.parse_args()
|
| 156 |
+
|
| 157 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 158 |
+
|
| 159 |
+
with open(Path(__file__).parent / "norm_stats.json") as f:
|
| 160 |
+
stats = json.load(f)
|
| 161 |
+
|
| 162 |
+
env = SO100KitchenEnv()
|
| 163 |
+
|
| 164 |
+
if args.viewer:
|
| 165 |
+
# Interactive MuJoCo viewer with mouse controls
|
| 166 |
+
import mujoco.viewer
|
| 167 |
+
import time as _time
|
| 168 |
+
policy = load_policy(args.checkpoint or "lerobot/pi05_base")
|
| 169 |
+
obs = env.reset()
|
| 170 |
+
chunk_actions = None
|
| 171 |
+
chunk_idx = 0
|
| 172 |
+
device = next(policy.parameters()).device
|
| 173 |
+
|
| 174 |
+
print(f"Launching interactive viewer. Task: '{args.task}'")
|
| 175 |
+
print("Mouse: Left=rotate, Right=pan, Scroll=zoom")
|
| 176 |
+
print("Close window to exit.")
|
| 177 |
+
|
| 178 |
+
viewer = mujoco.viewer.launch_passive(env.model, env.data)
|
| 179 |
+
step = 0
|
| 180 |
+
while viewer.is_running():
|
| 181 |
+
# Get action from policy
|
| 182 |
+
if chunk_actions is None or chunk_idx >= len(chunk_actions):
|
| 183 |
+
camera_image = env.render("overview")
|
| 184 |
+
with torch.no_grad():
|
| 185 |
+
batch = build_batch(obs, camera_image, args.task, stats, device=device)
|
| 186 |
+
action = policy.select_action(batch)
|
| 187 |
+
chunk_actions = decode_actions(action.unsqueeze(0), stats)
|
| 188 |
+
chunk_idx = 0
|
| 189 |
+
|
| 190 |
+
act = chunk_actions[chunk_idx]
|
| 191 |
+
chunk_idx += 1
|
| 192 |
+
|
| 193 |
+
# Apply action to actuators
|
| 194 |
+
from so100_kitchen_env import JOINT_NAMES
|
| 195 |
+
for i, name in enumerate(JOINT_NAMES):
|
| 196 |
+
aid = env.actuator_ids.get(name)
|
| 197 |
+
if aid is not None:
|
| 198 |
+
env.data.ctrl[aid] = act[i]
|
| 199 |
+
|
| 200 |
+
# Step physics
|
| 201 |
+
mujoco.mj_step(env.model, env.data)
|
| 202 |
+
viewer.sync()
|
| 203 |
+
|
| 204 |
+
# Update obs
|
| 205 |
+
joint_pos = np.array([env.data.qpos[env.model.jnt_qposadr[env.joint_ids[n]]] for n in JOINT_NAMES])
|
| 206 |
+
obs = {"joint_pos": joint_pos}
|
| 207 |
+
|
| 208 |
+
step += 1
|
| 209 |
+
if step % 50 == 0:
|
| 210 |
+
print(f" step {step}: joints=[{' '.join(f'{j:.2f}' for j in joint_pos)}]")
|
| 211 |
+
|
| 212 |
+
_time.sleep(0.02) # ~50Hz
|
| 213 |
+
|
| 214 |
+
viewer.close()
|
| 215 |
+
|
| 216 |
+
elif args.compare:
|
| 217 |
+
# Run both base and finetuned
|
| 218 |
+
print("=== BASE MODEL ===")
|
| 219 |
+
base_policy = load_policy("lerobot/pi05_base")
|
| 220 |
+
base_frames, base_joints = run_episode(base_policy, env, args.task, stats, args.steps)
|
| 221 |
+
del base_policy
|
| 222 |
+
|
| 223 |
+
print("\n=== FINETUNED MODEL ===")
|
| 224 |
+
ft_policy = load_policy(args.finetuned_checkpoint)
|
| 225 |
+
ft_frames, ft_joints = run_episode(ft_policy, env, args.task, stats, args.steps)
|
| 226 |
+
del ft_policy
|
| 227 |
+
|
| 228 |
+
# Save videos
|
| 229 |
+
imageio.mimsave(f"{args.output_dir}/base_model.mp4", base_frames, fps=25)
|
| 230 |
+
imageio.mimsave(f"{args.output_dir}/finetuned_model.mp4", ft_frames, fps=25)
|
| 231 |
+
|
| 232 |
+
# Save side-by-side frames at key timesteps
|
| 233 |
+
for t in [0, 50, 100, 150, 199]:
|
| 234 |
+
if t < len(base_frames) and t < len(ft_frames):
|
| 235 |
+
combined = np.concatenate([base_frames[t], ft_frames[t]], axis=1)
|
| 236 |
+
imageio.imwrite(f"{args.output_dir}/compare_step_{t:03d}.png", combined)
|
| 237 |
+
|
| 238 |
+
# Print joint trajectory summary
|
| 239 |
+
print("\n=== COMPARISON ===")
|
| 240 |
+
print(f"Base model - joint range: {base_joints.min(axis=0)} to {base_joints.max(axis=0)}")
|
| 241 |
+
print(f"Finetuned - joint range: {ft_joints.min(axis=0)} to {ft_joints.max(axis=0)}")
|
| 242 |
+
print(f"Base model - total motion: {np.abs(np.diff(base_joints, axis=0)).sum():.2f} rad")
|
| 243 |
+
print(f"Finetuned - total motion: {np.abs(np.diff(ft_joints, axis=0)).sum():.2f} rad")
|
| 244 |
+
|
| 245 |
+
print(f"\nSaved to {args.output_dir}/")
|
| 246 |
+
|
| 247 |
+
elif args.checkpoint:
|
| 248 |
+
policy = load_policy(args.checkpoint)
|
| 249 |
+
frames, joints = run_episode(policy, env, args.task, stats, args.steps)
|
| 250 |
+
|
| 251 |
+
name = Path(args.checkpoint).parent.name if "checkpoint" in args.checkpoint else "model"
|
| 252 |
+
imageio.mimsave(f"{args.output_dir}/{name}.mp4", frames, fps=25)
|
| 253 |
+
|
| 254 |
+
for t in [0, len(frames)//2, len(frames)-1]:
|
| 255 |
+
imageio.imwrite(f"{args.output_dir}/{name}_step_{t:03d}.png", frames[t])
|
| 256 |
+
|
| 257 |
+
print(f"Saved {len(frames)} frames to {args.output_dir}/")
|
| 258 |
+
else:
|
| 259 |
+
print("Specify --checkpoint or --compare")
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
if __name__ == "__main__":
|
| 263 |
+
main()
|
eval_sim.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Evaluate a Pi0.5 checkpoint in the SO-100 MuJoCo sim.
|
| 4 |
+
Renders a video of the model controlling the arm.
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
python eval_sim.py --checkpoint outputs/scale_up_1k/checkpoints/000500/pretrained_model
|
| 8 |
+
python eval_sim.py --checkpoint lerobot/pi05_base # test base model
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import imageio
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 20 |
+
sys.path.insert(0, str(Path.home() / "lerobot" / "src"))
|
| 21 |
+
|
| 22 |
+
from gym_so100.env import SO100Env
|
| 23 |
+
from gym_so100.constants import normalize_lerobot_to_gym_so100
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load_policy(checkpoint_path, device="cuda"):
|
| 27 |
+
"""Load Pi0.5 policy from checkpoint."""
|
| 28 |
+
from lerobot.policies.pi05.modeling_pi05 import PI05Policy
|
| 29 |
+
|
| 30 |
+
print(f"Loading policy from {checkpoint_path}...")
|
| 31 |
+
policy = PI05Policy.from_pretrained(str(checkpoint_path))
|
| 32 |
+
policy = policy.to(device)
|
| 33 |
+
policy.eval()
|
| 34 |
+
return policy
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def build_batch(obs, task, stats, device="cuda"):
|
| 38 |
+
"""Convert sim observation to Pi0.5 batch format."""
|
| 39 |
+
# Image: sim gives (H, W, 3) uint8 -> (1, 3, H, W) float32 [0,1]
|
| 40 |
+
image = torch.from_numpy(obs["pixels"]).permute(2, 0, 1).float() / 255.0
|
| 41 |
+
image = image.unsqueeze(0) # add batch dim
|
| 42 |
+
|
| 43 |
+
# Resize to 224x224
|
| 44 |
+
import torchvision.transforms.functional as TF
|
| 45 |
+
image_224 = TF.resize(image, [224, 224], antialias=True)
|
| 46 |
+
|
| 47 |
+
# ImageNet normalization
|
| 48 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
|
| 49 |
+
std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
|
| 50 |
+
image_224 = (image_224 - mean) / std
|
| 51 |
+
|
| 52 |
+
# State: sim gives radians, convert to degrees (LeRobot scale)
|
| 53 |
+
agent_pos = obs["agent_pos"].copy()
|
| 54 |
+
agent_pos_degrees = np.degrees(agent_pos)
|
| 55 |
+
state = torch.tensor(agent_pos_degrees, dtype=torch.float32).unsqueeze(0)
|
| 56 |
+
|
| 57 |
+
# Normalize state with our stats
|
| 58 |
+
state_mean = torch.tensor(stats["observation.state"]["mean"], dtype=torch.float32)
|
| 59 |
+
state_std = torch.tensor(stats["observation.state"]["std"], dtype=torch.float32)
|
| 60 |
+
state = (state - state_mean) / (state_std + 1e-8)
|
| 61 |
+
|
| 62 |
+
# Pad state to 32 dims
|
| 63 |
+
state_padded = torch.zeros(1, 32)
|
| 64 |
+
state_padded[:, :6] = state
|
| 65 |
+
|
| 66 |
+
# Tokenize task
|
| 67 |
+
from transformers import AutoTokenizer
|
| 68 |
+
tokenizer = AutoTokenizer.from_pretrained("google/paligemma-3b-pt-224")
|
| 69 |
+
|
| 70 |
+
# Discretize state for prompt (Pi0.5 format)
|
| 71 |
+
state_discrete = ((state[0].clamp(-1, 1) + 1) / 2 * 255).int()
|
| 72 |
+
state_str = " ".join(str(v.item()) for v in state_discrete)
|
| 73 |
+
prompt = f"Task: {task}, State: {state_str};\nAction: "
|
| 74 |
+
|
| 75 |
+
tokens = tokenizer(
|
| 76 |
+
prompt,
|
| 77 |
+
padding="max_length",
|
| 78 |
+
max_length=200,
|
| 79 |
+
truncation=True,
|
| 80 |
+
return_tensors="pt",
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
batch = {
|
| 84 |
+
"observation.images.base_0_rgb": image_224.to(device),
|
| 85 |
+
"observation.images.left_wrist_0_rgb": image_224.to(device),
|
| 86 |
+
"observation.state": state_padded.to(device),
|
| 87 |
+
"observation.language.tokens": tokens["input_ids"].to(device),
|
| 88 |
+
"observation.language.attention_mask": tokens["attention_mask"].bool().to(device),
|
| 89 |
+
}
|
| 90 |
+
return batch
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def decode_actions(raw_actions, stats):
|
| 94 |
+
"""Convert model output actions back to LeRobot scale, then to sim radians."""
|
| 95 |
+
actions = raw_actions[0, :, :6].cpu().numpy() # (chunk_size, 6)
|
| 96 |
+
|
| 97 |
+
# Unnormalize from MEAN_STD
|
| 98 |
+
action_mean = np.array(stats["action"]["mean"])
|
| 99 |
+
action_std = np.array(stats["action"]["std"])
|
| 100 |
+
actions = actions * action_std + action_mean
|
| 101 |
+
|
| 102 |
+
# Now in LeRobot degree-scale. Convert to radians for sim.
|
| 103 |
+
actions_rad = np.radians(actions)
|
| 104 |
+
return actions_rad
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main():
|
| 108 |
+
parser = argparse.ArgumentParser()
|
| 109 |
+
parser.add_argument("--checkpoint", type=str, required=True)
|
| 110 |
+
parser.add_argument("--task", type=str, default="pick up the cube and place it in the bin")
|
| 111 |
+
parser.add_argument("--steps", type=int, default=200)
|
| 112 |
+
parser.add_argument("--output", type=str, default="sim_eval.mp4")
|
| 113 |
+
parser.add_argument("--device", type=str, default="cuda")
|
| 114 |
+
args = parser.parse_args()
|
| 115 |
+
|
| 116 |
+
import json
|
| 117 |
+
with open(Path(__file__).parent / "norm_stats.json") as f:
|
| 118 |
+
stats = json.load(f)
|
| 119 |
+
|
| 120 |
+
# Load policy
|
| 121 |
+
policy = load_policy(args.checkpoint, args.device)
|
| 122 |
+
|
| 123 |
+
# Create sim
|
| 124 |
+
env = SO100Env(task="so100_cube_to_bin", obs_type="so100_pixels_agent_pos")
|
| 125 |
+
obs, info = env.reset()
|
| 126 |
+
|
| 127 |
+
frames = []
|
| 128 |
+
print(f"Running {args.steps} sim steps with task: '{args.task}'")
|
| 129 |
+
|
| 130 |
+
chunk_actions = None
|
| 131 |
+
chunk_idx = 0
|
| 132 |
+
|
| 133 |
+
for step in range(args.steps):
|
| 134 |
+
# Get new action chunk from policy every N steps
|
| 135 |
+
if chunk_actions is None or chunk_idx >= len(chunk_actions):
|
| 136 |
+
with torch.no_grad():
|
| 137 |
+
batch = build_batch(obs, args.task, stats, args.device)
|
| 138 |
+
action = policy.select_action(batch)
|
| 139 |
+
chunk_actions = decode_actions(action.unsqueeze(0), stats)
|
| 140 |
+
chunk_idx = 0
|
| 141 |
+
|
| 142 |
+
# Apply one action from the chunk
|
| 143 |
+
action = chunk_actions[chunk_idx]
|
| 144 |
+
chunk_idx += 1
|
| 145 |
+
|
| 146 |
+
# Normalize radians to sim's [-1, 1] action space
|
| 147 |
+
joint_mins = np.array([-1.92, -3.32, -0.174, -1.66, -2.79, -0.174])
|
| 148 |
+
joint_maxs = np.array([1.92, 0.174, 3.14, 1.66, 2.79, 1.75])
|
| 149 |
+
sim_action = 2.0 * (action - joint_mins) / (joint_maxs - joint_mins) - 1.0
|
| 150 |
+
sim_action = np.clip(sim_action, -1.0, 1.0)
|
| 151 |
+
|
| 152 |
+
obs, reward, terminated, truncated, info = env.step(sim_action.astype(np.float32))
|
| 153 |
+
|
| 154 |
+
frame = env.render()
|
| 155 |
+
frames.append(frame)
|
| 156 |
+
|
| 157 |
+
if step % 20 == 0:
|
| 158 |
+
pos = obs["agent_pos"]
|
| 159 |
+
print(f" step {step:>3}: pos=[{pos[0]:.2f} {pos[1]:.2f} {pos[2]:.2f} {pos[3]:.2f} {pos[4]:.2f} {pos[5]:.3f}] reward={reward:.3f}")
|
| 160 |
+
|
| 161 |
+
if terminated or truncated:
|
| 162 |
+
print(f"Episode ended at step {step}")
|
| 163 |
+
break
|
| 164 |
+
|
| 165 |
+
# Save video
|
| 166 |
+
imageio.mimsave(args.output, frames, fps=25)
|
| 167 |
+
print(f"Saved {len(frames)} frames to {args.output}")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
main()
|
filtered_index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
infer_so101.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Run Pi0.5 inference on SO-101.
|
| 4 |
+
|
| 5 |
+
Uses LeRobot's FeetechMotorsBus with calibration for correct normalization,
|
| 6 |
+
but bypasses lerobot_record's problematic control loop.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python infer_so101.py --task "pick up the blue football"
|
| 10 |
+
"""
|
| 11 |
+
import argparse
|
| 12 |
+
import json
|
| 13 |
+
import logging
|
| 14 |
+
import sys
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import cv2
|
| 19 |
+
import numpy as np
|
| 20 |
+
import scservo_sdk as scs
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 24 |
+
sys.path.insert(0, str(Path.home() / "lerobot" / "src"))
|
| 25 |
+
|
| 26 |
+
logging.basicConfig(level=logging.WARNING, format='%(asctime)s %(message)s', datefmt='%H:%M:%S')
|
| 27 |
+
log = logging.getLogger()
|
| 28 |
+
|
| 29 |
+
MOTOR_NAMES = ["shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper"]
|
| 30 |
+
MOTOR_IDS = [1, 2, 3, 4, 5, 6]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def main():
|
| 34 |
+
parser = argparse.ArgumentParser()
|
| 35 |
+
parser.add_argument("--task", type=str, required=True)
|
| 36 |
+
parser.add_argument("--checkpoint", type=str,
|
| 37 |
+
default="/mnt/hdd/pi05-training/full_run/checkpoints/015000/pretrained_model")
|
| 38 |
+
parser.add_argument("--port", type=str, default="/dev/ttyACM0")
|
| 39 |
+
parser.add_argument("--cam-front", type=int, default=2)
|
| 40 |
+
parser.add_argument("--cam-wrist", type=int, default=0)
|
| 41 |
+
parser.add_argument("--max-steps", type=int, default=0, help="0 = run until Ctrl+C")
|
| 42 |
+
args = parser.parse_args()
|
| 43 |
+
|
| 44 |
+
# --- Connect motors using LeRobot's bus (for calibration/normalization) ---
|
| 45 |
+
from lerobot.motors.feetech.feetech import FeetechMotorsBus
|
| 46 |
+
from lerobot.motors import Motor, MotorNormMode, MotorCalibration
|
| 47 |
+
|
| 48 |
+
bus = FeetechMotorsBus(
|
| 49 |
+
port=args.port,
|
| 50 |
+
motors={
|
| 51 |
+
'shoulder_pan': Motor(1, 'sts3215', MotorNormMode.RANGE_M100_100),
|
| 52 |
+
'shoulder_lift': Motor(2, 'sts3215', MotorNormMode.RANGE_M100_100),
|
| 53 |
+
'elbow_flex': Motor(3, 'sts3215', MotorNormMode.RANGE_M100_100),
|
| 54 |
+
'wrist_flex': Motor(4, 'sts3215', MotorNormMode.RANGE_M100_100),
|
| 55 |
+
'wrist_roll': Motor(5, 'sts3215', MotorNormMode.RANGE_M100_100),
|
| 56 |
+
'gripper': Motor(6, 'sts3215', MotorNormMode.RANGE_0_100),
|
| 57 |
+
},
|
| 58 |
+
)
|
| 59 |
+
bus.connect()
|
| 60 |
+
|
| 61 |
+
# Load calibration
|
| 62 |
+
cal_path = Path.home() / ".cache/huggingface/lerobot/calibration/robots/so_follower/my_so101.json"
|
| 63 |
+
cal = json.load(open(cal_path))
|
| 64 |
+
cal_dict = {name: MotorCalibration(**vals) for name, vals in cal.items()}
|
| 65 |
+
bus.write_calibration(cal_dict)
|
| 66 |
+
log.warning("Bus connected with calibration")
|
| 67 |
+
|
| 68 |
+
# Configure motors the same way LeRobot does in so_follower.configure()
|
| 69 |
+
# This uses torque_disabled() context which disables torque, configures, re-enables
|
| 70 |
+
with bus.torque_disabled():
|
| 71 |
+
bus.configure_motors()
|
| 72 |
+
for motor in bus.motors:
|
| 73 |
+
bus.write("Operating_Mode", motor, 0) # Position mode
|
| 74 |
+
bus.write("P_Coefficient", motor, 16)
|
| 75 |
+
bus.write("I_Coefficient", motor, 0)
|
| 76 |
+
bus.write("D_Coefficient", motor, 32)
|
| 77 |
+
bus.write("Goal_Velocity", motor, 600) # Slow velocity limit
|
| 78 |
+
bus.write("Acceleration", motor, 50) # Gentle acceleration
|
| 79 |
+
if motor == "gripper":
|
| 80 |
+
bus.write("Max_Torque_Limit", motor, 500)
|
| 81 |
+
bus.write("Protection_Current", motor, 250)
|
| 82 |
+
bus.write("Overload_Torque", motor, 25)
|
| 83 |
+
# torque_disabled() re-enables torque on exit
|
| 84 |
+
# Velocity and acceleration limits prevent snapping
|
| 85 |
+
log.warning("Motors configured and torque enabled (velocity/accel limited)")
|
| 86 |
+
|
| 87 |
+
# --- Open cameras ---
|
| 88 |
+
cap_front = cv2.VideoCapture(args.cam_front)
|
| 89 |
+
cap_wrist = cv2.VideoCapture(args.cam_wrist)
|
| 90 |
+
for cap in [cap_front, cap_wrist]:
|
| 91 |
+
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
|
| 92 |
+
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
|
| 93 |
+
log.warning("Cameras open")
|
| 94 |
+
|
| 95 |
+
# --- Load policy + preprocessor + postprocessor ---
|
| 96 |
+
from lerobot.policies.factory import make_pre_post_processors
|
| 97 |
+
from lerobot.policies.utils import prepare_observation_for_inference, make_robot_action
|
| 98 |
+
from lerobot.configs.policies import PreTrainedConfig
|
| 99 |
+
from lerobot.processor.rename_processor import rename_stats
|
| 100 |
+
from lerobot.policies.pi05.modeling_pi05 import PI05Policy
|
| 101 |
+
|
| 102 |
+
log.warning("Loading Pi0.5...")
|
| 103 |
+
policy_cfg = PreTrainedConfig.from_pretrained(args.checkpoint)
|
| 104 |
+
policy_cfg.pretrained_path = Path(args.checkpoint)
|
| 105 |
+
|
| 106 |
+
policy = PI05Policy.from_pretrained(args.checkpoint)
|
| 107 |
+
policy = policy.to("cuda")
|
| 108 |
+
policy.eval()
|
| 109 |
+
policy.reset()
|
| 110 |
+
|
| 111 |
+
# Build stats from checkpoint's saved preprocessor
|
| 112 |
+
rename_map = {
|
| 113 |
+
"observation.images.front": "observation.images.base_0_rgb",
|
| 114 |
+
"observation.images.wrist": "observation.images.left_wrist_0_rgb",
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
preprocessor, postprocessor = make_pre_post_processors(
|
| 118 |
+
policy_cfg=policy_cfg,
|
| 119 |
+
pretrained_path=policy_cfg.pretrained_path,
|
| 120 |
+
preprocessor_overrides={
|
| 121 |
+
"device_processor": {"device": "cuda"},
|
| 122 |
+
"rename_observations_processor": {"rename_map": rename_map},
|
| 123 |
+
},
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
action_names = [f"{name}.pos" for name in MOTOR_NAMES]
|
| 127 |
+
ds_features = {"action": {"names": action_names}}
|
| 128 |
+
|
| 129 |
+
# --- Set up live camera display ---
|
| 130 |
+
try:
|
| 131 |
+
import rerun as rr
|
| 132 |
+
rr.init("so101_inference", spawn=True)
|
| 133 |
+
use_rerun = True
|
| 134 |
+
log.warning("Rerun viewer launched — live camera feed")
|
| 135 |
+
except ImportError:
|
| 136 |
+
use_rerun = False
|
| 137 |
+
log.warning("Rerun not available, no live view")
|
| 138 |
+
|
| 139 |
+
log.warning(f"Running: '{args.task}' — Ctrl+C to stop")
|
| 140 |
+
|
| 141 |
+
step = 0
|
| 142 |
+
try:
|
| 143 |
+
while args.max_steps == 0 or step < args.max_steps:
|
| 144 |
+
t0 = time.perf_counter()
|
| 145 |
+
|
| 146 |
+
# 1. Read motor positions (calibrated/normalized by bus)
|
| 147 |
+
try:
|
| 148 |
+
pos_dict = bus.sync_read("Present_Position", num_retry=5)
|
| 149 |
+
except ConnectionError:
|
| 150 |
+
bus.port_handler.is_using = False
|
| 151 |
+
bus.port_handler.ser.reset_input_buffer()
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
# Build observation dict
|
| 155 |
+
state_array = np.array([pos_dict[name] for name in MOTOR_NAMES], dtype=np.float32)
|
| 156 |
+
|
| 157 |
+
# 2. Capture camera images
|
| 158 |
+
ret_f, frame_front = cap_front.read()
|
| 159 |
+
ret_w, frame_wrist = cap_wrist.read()
|
| 160 |
+
if not ret_f or not ret_w:
|
| 161 |
+
continue
|
| 162 |
+
|
| 163 |
+
# Live display
|
| 164 |
+
if use_rerun:
|
| 165 |
+
rr.set_time_sequence("step", step)
|
| 166 |
+
rr.log("camera/front", rr.Image(frame_front))
|
| 167 |
+
rr.log("camera/wrist", rr.Image(frame_wrist))
|
| 168 |
+
rr.log("state", rr.BarChart([pos_dict[n] for n in MOTOR_NAMES]))
|
| 169 |
+
|
| 170 |
+
observation = {
|
| 171 |
+
"observation.images.front": frame_front,
|
| 172 |
+
"observation.images.wrist": frame_wrist,
|
| 173 |
+
"observation.state": state_array,
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
# 3. Inference
|
| 177 |
+
with torch.inference_mode():
|
| 178 |
+
obs = prepare_observation_for_inference(
|
| 179 |
+
observation, torch.device("cuda"), args.task, "so101_follower"
|
| 180 |
+
)
|
| 181 |
+
obs = preprocessor(obs)
|
| 182 |
+
action = policy.select_action(obs)
|
| 183 |
+
action = postprocessor(action)
|
| 184 |
+
|
| 185 |
+
# 4. Convert to motor commands
|
| 186 |
+
robot_action = make_robot_action(action, ds_features)
|
| 187 |
+
|
| 188 |
+
# 5. Send to motors (calibrated/normalized by bus)
|
| 189 |
+
goal_pos = {name: robot_action[f"{name}.pos"] for name in MOTOR_NAMES}
|
| 190 |
+
try:
|
| 191 |
+
bus.sync_write("Goal_Position", goal_pos)
|
| 192 |
+
except ConnectionError:
|
| 193 |
+
bus.port_handler.is_using = False
|
| 194 |
+
bus.port_handler.ser.reset_input_buffer()
|
| 195 |
+
|
| 196 |
+
dt = time.perf_counter() - t0
|
| 197 |
+
step += 1
|
| 198 |
+
|
| 199 |
+
if step % 10 == 0:
|
| 200 |
+
pos_str = " ".join(f"{pos_dict[n]:>7.1f}" for n in MOTOR_NAMES)
|
| 201 |
+
act_str = " ".join(f"{robot_action[f'{n}.pos']:>7.1f}" for n in MOTOR_NAMES)
|
| 202 |
+
log.warning(f"step {step:>4} | state=[{pos_str}] | action=[{act_str}] | {dt*1000:.0f}ms")
|
| 203 |
+
|
| 204 |
+
except KeyboardInterrupt:
|
| 205 |
+
log.warning("Stopped by user")
|
| 206 |
+
finally:
|
| 207 |
+
log.warning("Disabling torque...")
|
| 208 |
+
try:
|
| 209 |
+
bus.disable_torque()
|
| 210 |
+
except Exception:
|
| 211 |
+
for mid in MOTOR_IDS:
|
| 212 |
+
try:
|
| 213 |
+
bus.packet_handler.write1ByteTxRx(bus.port_handler, mid, 40, 0)
|
| 214 |
+
except Exception:
|
| 215 |
+
pass
|
| 216 |
+
bus.disconnect()
|
| 217 |
+
cap_front.release()
|
| 218 |
+
cap_wrist.release()
|
| 219 |
+
log.warning("Done")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
if __name__ == "__main__":
|
| 223 |
+
main()
|
norm_stats.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"observation.state": {
|
| 3 |
+
"mean": [
|
| 4 |
+
3.2129562341482223,
|
| 5 |
+
81.25934383631572,
|
| 6 |
+
97.87567545165706,
|
| 7 |
+
58.2558965428857,
|
| 8 |
+
-3.869688922486154,
|
| 9 |
+
13.552276313577162
|
| 10 |
+
],
|
| 11 |
+
"std": [
|
| 12 |
+
26.932913188864053,
|
| 13 |
+
85.10186432539234,
|
| 14 |
+
60.096302230313775,
|
| 15 |
+
32.18041942119004,
|
| 16 |
+
64.69174273514702,
|
| 17 |
+
17.38995233769721
|
| 18 |
+
]
|
| 19 |
+
},
|
| 20 |
+
"action": {
|
| 21 |
+
"mean": [
|
| 22 |
+
3.2667901525244267,
|
| 23 |
+
82.01517467950833,
|
| 24 |
+
96.44080348317482,
|
| 25 |
+
58.19181662702153,
|
| 26 |
+
-3.898391972920288,
|
| 27 |
+
11.117041393936647
|
| 28 |
+
],
|
| 29 |
+
"std": [
|
| 30 |
+
27.026112586762707,
|
| 31 |
+
85.80857081004108,
|
| 32 |
+
60.86058528648729,
|
| 33 |
+
32.566689386004555,
|
| 34 |
+
64.99547212544971,
|
| 35 |
+
17.279498490768535
|
| 36 |
+
]
|
| 37 |
+
}
|
| 38 |
+
}
|
so100_dataset.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Custom PyTorch Dataset that reads directly from community_dataset_v3 v2.1 files on disk.
|
| 4 |
+
No merging, no conversion, no copying. Just reads parquets + decodes video frames.
|
| 5 |
+
|
| 6 |
+
Returns raw (unnormalized) data in the format LeRobotDataset returns — the existing
|
| 7 |
+
Pi0.5 preprocessor handles normalization, padding, tokenization, and device placement.
|
| 8 |
+
|
| 9 |
+
Provides a .meta adapter so lerobot_train.py can use it as a drop-in replacement.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import pandas as pd
|
| 17 |
+
import torch
|
| 18 |
+
from torch.utils.data import Dataset
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class _DatasetMeta:
|
| 22 |
+
"""
|
| 23 |
+
Lightweight adapter that provides the .meta interface lerobot_train.py expects.
|
| 24 |
+
Wraps our filtered index + precomputed stats.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, index: dict, stats: dict, data_root: Path):
|
| 28 |
+
self.repo_id = "SO100Dataset/local"
|
| 29 |
+
self.root = data_root
|
| 30 |
+
|
| 31 |
+
# Stats: training script expects dict[str, dict[str, torch.Tensor]]
|
| 32 |
+
self.stats = {}
|
| 33 |
+
for key, s in stats.items():
|
| 34 |
+
self.stats[key] = {
|
| 35 |
+
"mean": torch.tensor(s["mean"], dtype=torch.float32),
|
| 36 |
+
"std": torch.tensor(s["std"], dtype=torch.float32),
|
| 37 |
+
# Preprocessor may also look for min/max/quantiles.
|
| 38 |
+
# Approximate them from mean/std for MEAN_STD normalization.
|
| 39 |
+
"min": torch.tensor(s["mean"], dtype=torch.float32) - 3 * torch.tensor(s["std"], dtype=torch.float32),
|
| 40 |
+
"max": torch.tensor(s["mean"], dtype=torch.float32) + 3 * torch.tensor(s["std"], dtype=torch.float32),
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# Tasks
|
| 44 |
+
self.tasks = pd.DataFrame(
|
| 45 |
+
{"task_index": range(len(index["tasks"]))},
|
| 46 |
+
index=index["tasks"],
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Features
|
| 50 |
+
self._features = {
|
| 51 |
+
"observation.images.image": {
|
| 52 |
+
"dtype": "video",
|
| 53 |
+
"shape": [3, 480, 640],
|
| 54 |
+
"names": ["channels", "height", "width"],
|
| 55 |
+
},
|
| 56 |
+
"observation.images.image2": {
|
| 57 |
+
"dtype": "video",
|
| 58 |
+
"shape": [3, 480, 640],
|
| 59 |
+
"names": ["channels", "height", "width"],
|
| 60 |
+
},
|
| 61 |
+
"observation.state": {
|
| 62 |
+
"dtype": "float32",
|
| 63 |
+
"shape": [6],
|
| 64 |
+
},
|
| 65 |
+
"action": {
|
| 66 |
+
"dtype": "float32",
|
| 67 |
+
"shape": [6],
|
| 68 |
+
},
|
| 69 |
+
"timestamp": {"dtype": "float32", "shape": []},
|
| 70 |
+
"frame_index": {"dtype": "int64", "shape": []},
|
| 71 |
+
"episode_index": {"dtype": "int64", "shape": []},
|
| 72 |
+
"index": {"dtype": "int64", "shape": []},
|
| 73 |
+
"task_index": {"dtype": "int64", "shape": []},
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
self.info = {
|
| 77 |
+
"fps": 30,
|
| 78 |
+
"robot_type": "so100",
|
| 79 |
+
"total_episodes": index["summary"]["episodes"],
|
| 80 |
+
"total_frames": index["summary"]["total_frames"],
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def fps(self):
|
| 85 |
+
return 30
|
| 86 |
+
|
| 87 |
+
@property
|
| 88 |
+
def features(self):
|
| 89 |
+
return self._features
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def camera_keys(self):
|
| 93 |
+
return ["observation.images.image", "observation.images.image2"]
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def video_keys(self):
|
| 97 |
+
return ["observation.images.image", "observation.images.image2"]
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def image_keys(self):
|
| 101 |
+
return []
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def total_episodes(self):
|
| 105 |
+
return self.info["total_episodes"]
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def total_frames(self):
|
| 109 |
+
return self.info["total_frames"]
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def robot_type(self):
|
| 113 |
+
return "so100"
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class SO100Dataset(Dataset):
|
| 117 |
+
"""
|
| 118 |
+
Loads filtered SO-100/101 episodes from community_dataset_v3 on disk.
|
| 119 |
+
|
| 120 |
+
Each sample is one frame with an action chunk of the next `chunk_size` steps.
|
| 121 |
+
Returns raw unnormalized data — the Pi0.5 preprocessor handles normalization.
|
| 122 |
+
|
| 123 |
+
Provides .meta property compatible with lerobot_train.py.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def __init__(
|
| 127 |
+
self,
|
| 128 |
+
data_root: str | Path,
|
| 129 |
+
index_path: str | Path,
|
| 130 |
+
stats_path: str | Path | None = None,
|
| 131 |
+
video_backend: str = "pyav",
|
| 132 |
+
chunk_size: int = 50,
|
| 133 |
+
image_transforms=None,
|
| 134 |
+
):
|
| 135 |
+
self.data_root = Path(data_root)
|
| 136 |
+
self.video_backend = video_backend
|
| 137 |
+
self.chunk_size = chunk_size
|
| 138 |
+
self.image_transforms = image_transforms
|
| 139 |
+
self.fps = 30
|
| 140 |
+
|
| 141 |
+
# Load index
|
| 142 |
+
with open(index_path) as f:
|
| 143 |
+
self._index = json.load(f)
|
| 144 |
+
|
| 145 |
+
self.tasks = self._index["tasks"]
|
| 146 |
+
|
| 147 |
+
# Load stats
|
| 148 |
+
raw_stats = {}
|
| 149 |
+
if stats_path and Path(stats_path).exists():
|
| 150 |
+
with open(stats_path) as f:
|
| 151 |
+
raw_stats = json.load(f)
|
| 152 |
+
|
| 153 |
+
# Create meta adapter
|
| 154 |
+
self.meta = _DatasetMeta(self._index, raw_stats, self.data_root)
|
| 155 |
+
|
| 156 |
+
# Build flat frame-level index
|
| 157 |
+
self._frame_index = []
|
| 158 |
+
self._episode_offsets = []
|
| 159 |
+
|
| 160 |
+
for ep in self._index["episodes"]:
|
| 161 |
+
dataset_path = self.data_root / ep["dataset"]
|
| 162 |
+
ep_idx = ep["episode_index"]
|
| 163 |
+
task = ep["task"]
|
| 164 |
+
task_idx = ep["task_index"]
|
| 165 |
+
num_frames = ep["num_frames"]
|
| 166 |
+
|
| 167 |
+
# Only include frames where a full action chunk fits
|
| 168 |
+
valid_frames = max(0, num_frames - self.chunk_size)
|
| 169 |
+
if valid_frames == 0:
|
| 170 |
+
continue
|
| 171 |
+
|
| 172 |
+
start = len(self._frame_index)
|
| 173 |
+
self._episode_offsets.append(start)
|
| 174 |
+
|
| 175 |
+
for frame_idx in range(valid_frames):
|
| 176 |
+
self._frame_index.append((
|
| 177 |
+
dataset_path, ep_idx, frame_idx,
|
| 178 |
+
num_frames, task, task_idx,
|
| 179 |
+
))
|
| 180 |
+
|
| 181 |
+
# Parquet cache
|
| 182 |
+
self._parquet_cache = {}
|
| 183 |
+
self._cache_max = 200
|
| 184 |
+
|
| 185 |
+
def __len__(self):
|
| 186 |
+
return len(self._frame_index)
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def num_episodes(self):
|
| 190 |
+
return len(self._episode_offsets)
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def num_frames(self):
|
| 194 |
+
return len(self._frame_index)
|
| 195 |
+
|
| 196 |
+
@property
|
| 197 |
+
def episodes(self):
|
| 198 |
+
return None # Use all episodes (no further filtering)
|
| 199 |
+
|
| 200 |
+
@property
|
| 201 |
+
def features(self):
|
| 202 |
+
return self.meta.features
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def video(self):
|
| 206 |
+
return True
|
| 207 |
+
|
| 208 |
+
@property
|
| 209 |
+
def camera_keys(self):
|
| 210 |
+
return self.meta.camera_keys
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def video_frame_keys(self):
|
| 214 |
+
return self.meta.camera_keys
|
| 215 |
+
|
| 216 |
+
def _load_parquet(self, dataset_path: Path, episode_index: int) -> pd.DataFrame:
|
| 217 |
+
"""Load and cache a parquet file."""
|
| 218 |
+
key = (str(dataset_path), episode_index)
|
| 219 |
+
if key in self._parquet_cache:
|
| 220 |
+
return self._parquet_cache[key]
|
| 221 |
+
|
| 222 |
+
parquet_path = dataset_path / f"data/chunk-000/episode_{episode_index:06d}.parquet"
|
| 223 |
+
df = pd.read_parquet(parquet_path)
|
| 224 |
+
|
| 225 |
+
if len(self._parquet_cache) >= self._cache_max:
|
| 226 |
+
oldest_key = next(iter(self._parquet_cache))
|
| 227 |
+
del self._parquet_cache[oldest_key]
|
| 228 |
+
|
| 229 |
+
self._parquet_cache[key] = df
|
| 230 |
+
return df
|
| 231 |
+
|
| 232 |
+
def _decode_video_frame(self, video_path: Path, timestamp: float) -> torch.Tensor:
|
| 233 |
+
"""Decode a single frame from an MP4 at the given timestamp. Returns (C, H, W) float32 [0,1]."""
|
| 234 |
+
if self.video_backend == "torchcodec":
|
| 235 |
+
from torchcodec.decoders import VideoDecoder
|
| 236 |
+
decoder = VideoDecoder(str(video_path))
|
| 237 |
+
frame = decoder.get_frame_played_at(timestamp)
|
| 238 |
+
return frame.data.float() / 255.0
|
| 239 |
+
else:
|
| 240 |
+
import av
|
| 241 |
+
container = av.open(str(video_path))
|
| 242 |
+
stream = container.streams.video[0]
|
| 243 |
+
target_pts = int(timestamp / float(stream.time_base))
|
| 244 |
+
container.seek(target_pts, stream=stream)
|
| 245 |
+
for frame in container.decode(video=0):
|
| 246 |
+
arr = frame.to_ndarray(format="rgb24")
|
| 247 |
+
tensor = torch.from_numpy(arr).permute(2, 0, 1).float() / 255.0
|
| 248 |
+
container.close()
|
| 249 |
+
return tensor
|
| 250 |
+
container.close()
|
| 251 |
+
raise RuntimeError(f"Could not decode frame at t={timestamp} from {video_path}")
|
| 252 |
+
|
| 253 |
+
def __getitem__(self, idx: int) -> dict:
|
| 254 |
+
# Retry with a different sample if this one has corrupt/mismatched video
|
| 255 |
+
for _attempt in range(5):
|
| 256 |
+
try:
|
| 257 |
+
return self._get_sample(idx)
|
| 258 |
+
except (IndexError, RuntimeError, OSError) as e:
|
| 259 |
+
# Video duration doesn't match parquet timestamps, or file is corrupt.
|
| 260 |
+
# Pick a random different index and try again.
|
| 261 |
+
import random
|
| 262 |
+
idx = random.randint(0, len(self._frame_index) - 1)
|
| 263 |
+
# If all retries fail, raise
|
| 264 |
+
return self._get_sample(idx)
|
| 265 |
+
|
| 266 |
+
def _get_sample(self, idx: int) -> dict:
|
| 267 |
+
dataset_path, ep_idx, frame_idx, num_frames, task, task_idx = self._frame_index[idx]
|
| 268 |
+
|
| 269 |
+
df = self._load_parquet(dataset_path, ep_idx)
|
| 270 |
+
|
| 271 |
+
# Current frame
|
| 272 |
+
row = df.iloc[frame_idx]
|
| 273 |
+
state = torch.tensor(row["observation.state"], dtype=torch.float32)
|
| 274 |
+
timestamp = float(row["timestamp"])
|
| 275 |
+
|
| 276 |
+
# Action chunk: next chunk_size actions starting from current frame
|
| 277 |
+
action_end = min(frame_idx + self.chunk_size, len(df))
|
| 278 |
+
action_rows = df.iloc[frame_idx:action_end]
|
| 279 |
+
actions = torch.tensor(
|
| 280 |
+
np.stack(action_rows["action"].values),
|
| 281 |
+
dtype=torch.float32,
|
| 282 |
+
)
|
| 283 |
+
# Pad with last action if near episode end
|
| 284 |
+
if actions.shape[0] < self.chunk_size:
|
| 285 |
+
pad = actions[-1:].expand(self.chunk_size - actions.shape[0], -1)
|
| 286 |
+
actions = torch.cat([actions, pad], dim=0)
|
| 287 |
+
|
| 288 |
+
# Decode video frames
|
| 289 |
+
video_dir = dataset_path / "videos" / "chunk-000"
|
| 290 |
+
ep_str = f"episode_{ep_idx:06d}.mp4"
|
| 291 |
+
|
| 292 |
+
image1 = self._decode_video_frame(
|
| 293 |
+
video_dir / "observation.images.image" / ep_str, timestamp
|
| 294 |
+
)
|
| 295 |
+
image2 = self._decode_video_frame(
|
| 296 |
+
video_dir / "observation.images.image2" / ep_str, timestamp
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
if self.image_transforms is not None:
|
| 300 |
+
image1 = self.image_transforms(image1)
|
| 301 |
+
image2 = self.image_transforms(image2)
|
| 302 |
+
|
| 303 |
+
return {
|
| 304 |
+
"observation.images.image": image1, # (3, 480, 640) float32 [0,1]
|
| 305 |
+
"observation.images.image2": image2, # (3, 480, 640) float32 [0,1]
|
| 306 |
+
"observation.state": state, # (6,) float32, raw values
|
| 307 |
+
"action": actions, # (50, 6) float32, raw values
|
| 308 |
+
"task": task, # str
|
| 309 |
+
"task_index": torch.tensor(task_idx),
|
| 310 |
+
"timestamp": torch.tensor(timestamp),
|
| 311 |
+
"frame_index": torch.tensor(frame_idx),
|
| 312 |
+
"episode_index": torch.tensor(ep_idx),
|
| 313 |
+
"index": torch.tensor(idx),
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
def __repr__(self):
|
| 317 |
+
return (
|
| 318 |
+
f"SO100Dataset(\n"
|
| 319 |
+
f" data_root='{self.data_root}',\n"
|
| 320 |
+
f" episodes={self.num_episodes},\n"
|
| 321 |
+
f" frames={self.num_frames:,},\n"
|
| 322 |
+
f" tasks={len(self.tasks)},\n"
|
| 323 |
+
f" video_backend='{self.video_backend}',\n"
|
| 324 |
+
f")"
|
| 325 |
+
)
|