Instructions to use AlexWortega/tinyvla with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- LeRobot
How to use AlexWortega/tinyvla with LeRobot:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Upload tinyvla2/src/tinyvla/data/hub_stream.py with huggingface_hub
Browse files
tinyvla2/src/tinyvla/data/hub_stream.py
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stream training samples straight from HF hub LeRobot v2.x repos. No disk.
|
| 2 |
+
|
| 3 |
+
Why this works: v2.0/v2.1 stores ONE parquet + ONE mp4 per camera PER EPISODE
|
| 4 |
+
(2-10 MB each). A DataLoader worker samples a (dataset, episode) pair by weight,
|
| 5 |
+
HTTP-GETs the files into memory, decodes the episode SEQUENTIALLY (the cheap
|
| 6 |
+
direction — no seeks at all), yields every stride-th frame as a full training
|
| 7 |
+
sample, then moves to the next episode. A downstream shuffle buffer breaks the
|
| 8 |
+
intra-episode correlation. Nothing ever touches disk, so the 1.3 TB
|
| 9 |
+
materialization step disappears entirely.
|
| 10 |
+
|
| 11 |
+
Bandwidth math (nvidia/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim): source h264
|
| 12 |
+
is ~10 KB/frame over all cams; at 400 samples/s consumption and stride 2-3 the
|
| 13 |
+
stream needs ~10-25 MB/s and ~4 HTTP requests/s — trivial for the HF CDN.
|
| 14 |
+
|
| 15 |
+
Emits the exact CanonicalSource/ShardSource schema, so it drops into the
|
| 16 |
+
training loop unchanged.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import io
|
| 22 |
+
import json
|
| 23 |
+
import random
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from torch.utils.data import IterableDataset, get_worker_info
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _resolve(repo_id: str, path: str) -> str:
|
| 32 |
+
return f"https://huggingface.co/datasets/{repo_id}/resolve/main/{path}"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _pad(x: torch.Tensor, dim: int, what: str) -> torch.Tensor:
|
| 36 |
+
d = x.shape[-1]
|
| 37 |
+
if d > dim:
|
| 38 |
+
raise ValueError(f"{what} has {d} dims > max {dim}; raise the cap, never truncate")
|
| 39 |
+
return F.pad(x, (0, dim - d)) if d < dim else x
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class HubEpisodeStream(IterableDataset):
|
| 43 |
+
"""Infinite weighted mixture over LeRobot v2.x datasets, streamed from HF.
|
| 44 |
+
|
| 45 |
+
spec per dataset:
|
| 46 |
+
repo_id HF dataset repo
|
| 47 |
+
prefix subdir for nested repos ("" for root-level)
|
| 48 |
+
weight mixture sampling weight
|
| 49 |
+
embodiment_id
|
| 50 |
+
hz target rate (stride = round(fps/hz))
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
specs: list[dict],
|
| 56 |
+
token: str | None = None,
|
| 57 |
+
chunk: int = 50,
|
| 58 |
+
image_size: int = 256,
|
| 59 |
+
max_state_dim: int = 64,
|
| 60 |
+
max_action_dim: int = 64,
|
| 61 |
+
shuffle_buffer: int = 4096,
|
| 62 |
+
seed: int = 42,
|
| 63 |
+
rank: int = 0,
|
| 64 |
+
world_size: int = 1,
|
| 65 |
+
n_support: int = 0,
|
| 66 |
+
morph_descriptors: dict | None = None, # morph_key -> (16,) tensor
|
| 67 |
+
robot_prompts: dict | None = None, # morph_key -> str
|
| 68 |
+
support_cache_datasets: int = 8,
|
| 69 |
+
support_cache_size: int = 48,
|
| 70 |
+
):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.specs = specs
|
| 73 |
+
self.n_support = n_support
|
| 74 |
+
self.morph_descriptors = morph_descriptors or {}
|
| 75 |
+
self.robot_prompts = robot_prompts or {}
|
| 76 |
+
self.support_cache_datasets = support_cache_datasets
|
| 77 |
+
self.support_cache_size = support_cache_size
|
| 78 |
+
self.token = token
|
| 79 |
+
self.chunk = chunk
|
| 80 |
+
self.image_size = image_size
|
| 81 |
+
self.max_state_dim = max_state_dim
|
| 82 |
+
self.max_action_dim = max_action_dim
|
| 83 |
+
self.shuffle_buffer = shuffle_buffer
|
| 84 |
+
self.seed = seed
|
| 85 |
+
self.rank, self.world_size = rank, world_size
|
| 86 |
+
self.epoch = 0
|
| 87 |
+
self._session = None # per-process requests.Session (created lazily post-fork)
|
| 88 |
+
self._meta: dict[int, dict] = {}
|
| 89 |
+
|
| 90 |
+
# ------------------------------------------------------------------- http
|
| 91 |
+
|
| 92 |
+
def _http(self):
|
| 93 |
+
if self._session is None:
|
| 94 |
+
import requests
|
| 95 |
+
|
| 96 |
+
s = requests.Session()
|
| 97 |
+
if self.token:
|
| 98 |
+
s.headers["Authorization"] = f"Bearer {self.token}"
|
| 99 |
+
a = requests.adapters.HTTPAdapter(pool_connections=8, pool_maxsize=8, max_retries=3)
|
| 100 |
+
s.mount("https://", a)
|
| 101 |
+
self._session = s
|
| 102 |
+
return self._session
|
| 103 |
+
|
| 104 |
+
def _fetch(self, repo_id: str, path: str) -> bytes:
|
| 105 |
+
r = self._http().get(_resolve(repo_id, path), timeout=120)
|
| 106 |
+
r.raise_for_status()
|
| 107 |
+
return r.content
|
| 108 |
+
|
| 109 |
+
# ------------------------------------------------------------------- meta
|
| 110 |
+
|
| 111 |
+
def _load_meta(self, si: int) -> dict:
|
| 112 |
+
"""info.json + episodes list + normalization stats, once per worker."""
|
| 113 |
+
if si in self._meta:
|
| 114 |
+
return self._meta[si]
|
| 115 |
+
spec = self.specs[si]
|
| 116 |
+
rid, pfx = spec["repo_id"], spec.get("prefix", "")
|
| 117 |
+
p = f"{pfx}/" if pfx else ""
|
| 118 |
+
info = json.loads(self._fetch(rid, p + "meta/info.json"))
|
| 119 |
+
fps = float(info["fps"])
|
| 120 |
+
stride = max(1, int(round(fps / spec.get("hz", 10.0))))
|
| 121 |
+
|
| 122 |
+
episodes = []
|
| 123 |
+
for line in self._fetch(rid, p + "meta/episodes.jsonl").decode().splitlines():
|
| 124 |
+
if line.strip():
|
| 125 |
+
e = json.loads(line)
|
| 126 |
+
episodes.append((e["episode_index"], e.get("length", 0),
|
| 127 |
+
(e.get("tasks") or [""])[0] if isinstance(e.get("tasks"), list) else ""))
|
| 128 |
+
|
| 129 |
+
stats = self._load_stats(rid, p, info)
|
| 130 |
+
cam0, cam1 = self._pick_cams(info["features"])
|
| 131 |
+
meta = dict(info=info, fps=fps, stride=stride, episodes=episodes, stats=stats,
|
| 132 |
+
cams=(cam0, cam1), chunks_size=info.get("chunks_size", 1000),
|
| 133 |
+
state_dim=info["features"]["observation.state"]["shape"][0],
|
| 134 |
+
action_dim=info["features"]["action"]["shape"][0])
|
| 135 |
+
self._meta[si] = meta
|
| 136 |
+
return meta
|
| 137 |
+
|
| 138 |
+
def _load_stats(self, rid: str, p: str, info: dict) -> dict:
|
| 139 |
+
"""v2.0: meta/stats.json. v2.1: aggregate meta/episodes_stats.jsonl.
|
| 140 |
+
Repos with neither (e.g. GR00T-Tuned-Tasks): estimate from a sample of
|
| 141 |
+
episode parquets — cheap (no video), and far better than skipping the
|
| 142 |
+
dataset forever with a warning per attempt."""
|
| 143 |
+
try:
|
| 144 |
+
raw = json.loads(self._fetch(rid, p + "meta/stats.json"))
|
| 145 |
+
return {k: (np.asarray(raw[k]["mean"], np.float32).reshape(-1),
|
| 146 |
+
np.asarray(raw[k]["std"], np.float32).reshape(-1))
|
| 147 |
+
for k in ("observation.state", "action")}
|
| 148 |
+
except Exception:
|
| 149 |
+
pass
|
| 150 |
+
try:
|
| 151 |
+
return self._stats_from_jsonl(rid, p)
|
| 152 |
+
except Exception:
|
| 153 |
+
return self._stats_from_episodes(rid, p, info)
|
| 154 |
+
|
| 155 |
+
def _stats_from_episodes(self, rid: str, p: str, info: dict, n_eps: int = 16) -> dict:
|
| 156 |
+
import pyarrow.parquet as pqt
|
| 157 |
+
|
| 158 |
+
chunks_size = info.get("chunks_size", 1000)
|
| 159 |
+
total = info["total_episodes"]
|
| 160 |
+
idxs = np.linspace(0, total - 1, min(n_eps, total)).astype(int)
|
| 161 |
+
st, ac = [], []
|
| 162 |
+
for ep in idxs:
|
| 163 |
+
t = pqt.read_table(io.BytesIO(self._fetch(rid, p + info["data_path"].format(
|
| 164 |
+
episode_chunk=int(ep) // chunks_size, episode_index=int(ep)))),
|
| 165 |
+
columns=["observation.state", "action"])
|
| 166 |
+
st.append(np.stack([np.asarray(x, np.float32)
|
| 167 |
+
for x in t["observation.state"].to_numpy(zero_copy_only=False)]))
|
| 168 |
+
ac.append(np.stack([np.asarray(x, np.float32)
|
| 169 |
+
for x in t["action"].to_numpy(zero_copy_only=False)]))
|
| 170 |
+
st, ac = np.concatenate(st), np.concatenate(ac)
|
| 171 |
+
return {"observation.state": (st.mean(0), np.maximum(st.std(0), 1e-6)),
|
| 172 |
+
"action": (ac.mean(0), np.maximum(ac.std(0), 1e-6))}
|
| 173 |
+
|
| 174 |
+
def _stats_from_jsonl(self, rid: str, p: str) -> dict:
|
| 175 |
+
acc = {k: [0.0, 0.0, 0] for k in ("observation.state", "action")} # sum, sumsq, n
|
| 176 |
+
for line in self._fetch(rid, p + "meta/episodes_stats.jsonl").decode().splitlines():
|
| 177 |
+
if not line.strip():
|
| 178 |
+
continue
|
| 179 |
+
st = json.loads(line)["stats"]
|
| 180 |
+
for k in acc:
|
| 181 |
+
m = np.asarray(st[k]["mean"], np.float32).reshape(-1)
|
| 182 |
+
s = np.asarray(st[k]["std"], np.float32).reshape(-1)
|
| 183 |
+
n = int(np.asarray(st[k]["count"]).reshape(-1)[0])
|
| 184 |
+
acc[k][0] = acc[k][0] + m * n
|
| 185 |
+
acc[k][1] = acc[k][1] + (s ** 2 + m ** 2) * n
|
| 186 |
+
acc[k][2] += n
|
| 187 |
+
out = {}
|
| 188 |
+
for k, (sm, sq, n) in acc.items():
|
| 189 |
+
mean = sm / n
|
| 190 |
+
out[k] = (mean.astype(np.float32),
|
| 191 |
+
np.sqrt(np.maximum(sq / n - mean ** 2, 1e-12)).astype(np.float32))
|
| 192 |
+
return out
|
| 193 |
+
|
| 194 |
+
@staticmethod
|
| 195 |
+
def _pick_cams(features: dict):
|
| 196 |
+
import re
|
| 197 |
+
|
| 198 |
+
PRIMARY = re.compile(r"ego_view|top|front|base|main|scene|image_0$|images\.image$|image2$")
|
| 199 |
+
WRIST = re.compile(r"wrist|gripper|hand|image_1$")
|
| 200 |
+
keys = sorted(k for k, v in features.items() if v.get("dtype") == "video")
|
| 201 |
+
cam0 = next((k for k in keys if PRIMARY.search(k)), keys[0])
|
| 202 |
+
cam1 = next((k for k in keys if k != cam0 and WRIST.search(k)), None)
|
| 203 |
+
if cam1 is None and len(keys) > 1:
|
| 204 |
+
cam1 = next(k for k in keys if k != cam0)
|
| 205 |
+
return cam0, cam1
|
| 206 |
+
|
| 207 |
+
# ---------------------------------------------------------------- episode
|
| 208 |
+
|
| 209 |
+
def _decode_video(self, blob: bytes, stride: int) -> list[torch.Tensor]:
|
| 210 |
+
import av
|
| 211 |
+
|
| 212 |
+
out = []
|
| 213 |
+
with av.open(io.BytesIO(blob)) as c:
|
| 214 |
+
st = c.streams.video[0]
|
| 215 |
+
st.thread_type = "AUTO"
|
| 216 |
+
i = 0
|
| 217 |
+
for fr in c.decode(st):
|
| 218 |
+
if i % stride == 0:
|
| 219 |
+
a = fr.to_rgb().to_ndarray()
|
| 220 |
+
x = torch.from_numpy(np.ascontiguousarray(a)).permute(2, 0, 1).float().div_(255.0)
|
| 221 |
+
if x.shape[-2:] != (self.image_size, self.image_size):
|
| 222 |
+
x = F.interpolate(x[None], size=(self.image_size, self.image_size),
|
| 223 |
+
mode="bilinear", align_corners=False)[0]
|
| 224 |
+
out.append(x)
|
| 225 |
+
i += 1
|
| 226 |
+
return out
|
| 227 |
+
|
| 228 |
+
def _stream_episode(self, si: int, ep_idx: int, task: str):
|
| 229 |
+
spec = self.specs[si]
|
| 230 |
+
meta = self._load_meta(si)
|
| 231 |
+
rid, pfx = spec["repo_id"], spec.get("prefix", "")
|
| 232 |
+
p = f"{pfx}/" if pfx else ""
|
| 233 |
+
info, stride = meta["info"], meta["stride"]
|
| 234 |
+
ch = ep_idx // meta["chunks_size"]
|
| 235 |
+
|
| 236 |
+
t = __import__("pyarrow.parquet", fromlist=["read_table"]).read_table(
|
| 237 |
+
io.BytesIO(self._fetch(rid, p + info["data_path"].format(
|
| 238 |
+
episode_chunk=ch, episode_index=ep_idx))))
|
| 239 |
+
keep = np.arange(0, t.num_rows, stride)
|
| 240 |
+
cols = {c: t[c].to_numpy(zero_copy_only=False) for c in ("observation.state", "action")}
|
| 241 |
+
sm, ss = meta["stats"]["observation.state"]
|
| 242 |
+
am, as_ = meta["stats"]["action"]
|
| 243 |
+
state = (np.stack([np.asarray(x, np.float32) for x in cols["observation.state"][keep]]) - sm) / np.maximum(ss, 1e-6)
|
| 244 |
+
action = (np.stack([np.asarray(x, np.float32) for x in cols["action"][keep]]) - am) / np.maximum(as_, 1e-6)
|
| 245 |
+
|
| 246 |
+
cams = {}
|
| 247 |
+
for slot, key in zip(("cam0", "cam1"), meta["cams"]):
|
| 248 |
+
if key is None:
|
| 249 |
+
cams[slot] = None
|
| 250 |
+
continue
|
| 251 |
+
blob = self._fetch(rid, p + info["video_path"].format(
|
| 252 |
+
episode_chunk=ch, video_key=key, episode_index=ep_idx))
|
| 253 |
+
frames = self._decode_video(blob, stride)
|
| 254 |
+
if len(frames) + 1 < len(keep): # video may run a frame or two long, never short
|
| 255 |
+
raise RuntimeError(f"{rid}/{pfx} ep{ep_idx} {key}: {len(frames)} frames vs {len(keep)} rows")
|
| 256 |
+
cams[slot] = frames[: len(keep)]
|
| 257 |
+
|
| 258 |
+
m = min(len(keep), *(len(v) for v in cams.values() if v is not None))
|
| 259 |
+
state_t = torch.from_numpy(state[:m])
|
| 260 |
+
action_t = torch.from_numpy(action[:m])
|
| 261 |
+
ad = meta["action_dim"]
|
| 262 |
+
dim_mask = torch.zeros(self.max_action_dim, dtype=torch.bool)
|
| 263 |
+
dim_mask[:ad] = True
|
| 264 |
+
cam_mask = torch.tensor([True, cams["cam1"] is not None])
|
| 265 |
+
zero_img = None
|
| 266 |
+
|
| 267 |
+
for j in range(m):
|
| 268 |
+
avail = m - j
|
| 269 |
+
if avail >= self.chunk:
|
| 270 |
+
chunk_a = action_t[j : j + self.chunk]
|
| 271 |
+
is_pad = torch.zeros(self.chunk, dtype=torch.bool)
|
| 272 |
+
else:
|
| 273 |
+
chunk_a = torch.cat([action_t[j:], action_t[-1:].expand(self.chunk - avail, -1)])
|
| 274 |
+
is_pad = torch.zeros(self.chunk, dtype=torch.bool)
|
| 275 |
+
is_pad[avail:] = True
|
| 276 |
+
if cams["cam1"] is None and zero_img is None:
|
| 277 |
+
zero_img = torch.zeros_like(cams["cam0"][j])
|
| 278 |
+
out = {
|
| 279 |
+
"observation.images.cam0": cams["cam0"][j],
|
| 280 |
+
"observation.images.cam1": cams["cam1"][j] if cams["cam1"] is not None else zero_img,
|
| 281 |
+
"camera_mask": cam_mask,
|
| 282 |
+
"observation.state": _pad(state_t[j], self.max_state_dim, "state"),
|
| 283 |
+
"action": _pad(chunk_a, self.max_action_dim, "action"),
|
| 284 |
+
"action_dim_mask": dim_mask,
|
| 285 |
+
"action_is_pad": is_pad,
|
| 286 |
+
"embodiment_id": torch.tensor(spec.get("embodiment_id", si), dtype=torch.long),
|
| 287 |
+
"task": task,
|
| 288 |
+
}
|
| 289 |
+
mkey = spec.get("morph_key")
|
| 290 |
+
if mkey and mkey in self.morph_descriptors:
|
| 291 |
+
out["morphology"] = self.morph_descriptors[mkey]
|
| 292 |
+
if mkey:
|
| 293 |
+
out["morph_text"] = self.robot_prompts.get(mkey, "")
|
| 294 |
+
yield out
|
| 295 |
+
|
| 296 |
+
# ------------------------------------------------------------------- iter
|
| 297 |
+
|
| 298 |
+
def __iter__(self):
|
| 299 |
+
wi = get_worker_info()
|
| 300 |
+
wid, nw = (wi.id, wi.num_workers) if wi is not None else (0, 1)
|
| 301 |
+
gid = self.rank * nw + wid
|
| 302 |
+
rng = random.Random(self.seed * 7919 + self.epoch * 104729 + gid)
|
| 303 |
+
weights = [s["weight"] for s in self.specs]
|
| 304 |
+
|
| 305 |
+
buf: list[dict] = []
|
| 306 |
+
# in-context demo support: per-dataset ring of (img, action_chunk, ep) from
|
| 307 |
+
# PREVIOUS episodes of the same dataset. LRU over datasets bounds memory.
|
| 308 |
+
from collections import OrderedDict, deque
|
| 309 |
+
|
| 310 |
+
sup_cache: OrderedDict[int, deque] = OrderedDict()
|
| 311 |
+
|
| 312 |
+
def attach_support(item, si, ep_idx):
|
| 313 |
+
if self.n_support <= 0:
|
| 314 |
+
return item
|
| 315 |
+
pool = list(sup_cache.get(si, ()))
|
| 316 |
+
other = [e for e in pool if e[2] != ep_idx] or pool
|
| 317 |
+
imgs, acts = [], []
|
| 318 |
+
for _ in range(self.n_support):
|
| 319 |
+
if other:
|
| 320 |
+
e = other[rng.randrange(len(other))]
|
| 321 |
+
imgs.append(e[0]); acts.append(e[1])
|
| 322 |
+
else: # bootstrap: first episode of this dataset — fall back to self
|
| 323 |
+
imgs.append(item["observation.images.cam0"]); acts.append(item["action"])
|
| 324 |
+
item["support_images"] = torch.stack(imgs)
|
| 325 |
+
item["support_actions"] = torch.stack(acts)
|
| 326 |
+
return item
|
| 327 |
+
|
| 328 |
+
while True: # infinite stream; the training loop counts steps, not epochs
|
| 329 |
+
si = rng.choices(range(len(self.specs)), weights=weights, k=1)[0]
|
| 330 |
+
try:
|
| 331 |
+
meta = self._load_meta(si)
|
| 332 |
+
ep_idx, _, task = meta["episodes"][rng.randrange(len(meta["episodes"]))]
|
| 333 |
+
n_seen = 0
|
| 334 |
+
for item in self._stream_episode(si, ep_idx, task):
|
| 335 |
+
if self.n_support > 0:
|
| 336 |
+
n_seen += 1
|
| 337 |
+
if n_seen % 17 == 0: # редкая подвыборка эпизода в кэш демо
|
| 338 |
+
d = sup_cache.setdefault(si, deque(maxlen=self.support_cache_size))
|
| 339 |
+
d.append((item["observation.images.cam0"], item["action"], ep_idx))
|
| 340 |
+
sup_cache.move_to_end(si)
|
| 341 |
+
while len(sup_cache) > self.support_cache_datasets:
|
| 342 |
+
sup_cache.popitem(last=False)
|
| 343 |
+
item = attach_support(item, si, ep_idx)
|
| 344 |
+
if len(buf) < self.shuffle_buffer:
|
| 345 |
+
buf.append(item)
|
| 346 |
+
continue
|
| 347 |
+
k = rng.randrange(len(buf))
|
| 348 |
+
buf[k], item = item, buf[k]
|
| 349 |
+
yield item
|
| 350 |
+
except Exception as e: # network hiccup / bad episode: log and resample
|
| 351 |
+
import logging
|
| 352 |
+
|
| 353 |
+
logging.warning(f"stream: skipping {self.specs[si]['repo_id']} ep after {type(e).__name__}: {e}")
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# ---------------------------------------------------------------------------
|
| 357 |
+
# Evaluation access (added for scripts/eval_physical_ai.py)
|
| 358 |
+
#
|
| 359 |
+
# HubEpisodeStream.__iter__ is an infinite weighted stream, which is right for
|
| 360 |
+
# training and useless for a bounded eval. _stream_episode IS finite, so the only
|
| 361 |
+
# thing missing is (a) picking specific frames instead of every frame, and (b)
|
| 362 |
+
# reading raw parquet without touching video for the ABS/DELTA calibration pass.
|
| 363 |
+
#
|
| 364 |
+
# Everything that decides what a sample LOOKS like — stride, camera choice,
|
| 365 |
+
# z-scoring, resize, chunk padding — is inherited unchanged. Any reimplementation
|
| 366 |
+
# would silently diverge: _pick_cams' PRIMARY regex matches none of r1_pro's video
|
| 367 |
+
# keys, so its cam0 is the head camera only because it sorts first alphabetically.
|
| 368 |
+
# ---------------------------------------------------------------------------
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class EvalEpisodeStream(HubEpisodeStream):
|
| 372 |
+
"""Random access into single episodes, with training-identical preprocessing."""
|
| 373 |
+
|
| 374 |
+
def episode_list(self, si: int):
|
| 375 |
+
"""(episode_index, length, task) triples for dataset `si`."""
|
| 376 |
+
return self._load_meta(si)["episodes"]
|
| 377 |
+
|
| 378 |
+
def episode_raw(self, si: int):
|
| 379 |
+
"""RAW (un-normalized) strided state/action for one episode — parquet only.
|
| 380 |
+
|
| 381 |
+
Used by the calibration pass to decide, per action dim, whether the action
|
| 382 |
+
is an absolute target (matches some state dim) or a delta. Must be raw:
|
| 383 |
+
the z-score hides the identity `action[3:6] == state[6:9]` that r1_pro has.
|
| 384 |
+
"""
|
| 385 |
+
import pyarrow.parquet as pq
|
| 386 |
+
|
| 387 |
+
meta = self._load_meta(si)
|
| 388 |
+
spec = self.specs[si]
|
| 389 |
+
rid, pfx = spec["repo_id"], spec.get("prefix", "")
|
| 390 |
+
p = f"{pfx}/" if pfx else ""
|
| 391 |
+
ep_idx = meta["episodes"][0][0]
|
| 392 |
+
ch = ep_idx // meta["chunks_size"]
|
| 393 |
+
t = pq.read_table(io.BytesIO(self._fetch(rid, p + meta["info"]["data_path"].format(
|
| 394 |
+
episode_chunk=ch, episode_index=ep_idx))))
|
| 395 |
+
keep = np.arange(0, t.num_rows, meta["stride"])
|
| 396 |
+
s = np.stack([np.asarray(x, np.float32) for x in t["observation.state"].to_numpy(zero_copy_only=False)[keep]])
|
| 397 |
+
a = np.stack([np.asarray(x, np.float32) for x in t["action"].to_numpy(zero_copy_only=False)[keep]])
|
| 398 |
+
return s, a, meta
|
| 399 |
+
|
| 400 |
+
def _decode_capped(self, blob: bytes, stride: int, n_needed: int) -> list[torch.Tensor]:
|
| 401 |
+
"""_decode_video, but stops once n_needed strided frames are collected.
|
| 402 |
+
|
| 403 |
+
Frame-for-frame identical to the full decode's prefix (same container, same
|
| 404 |
+
stride, same order), so samples taken from it are bit-identical. Only used
|
| 405 |
+
to avoid walking all ~26k frames of an r1_pro episode.
|
| 406 |
+
"""
|
| 407 |
+
import av
|
| 408 |
+
|
| 409 |
+
out = []
|
| 410 |
+
with av.open(io.BytesIO(blob)) as c:
|
| 411 |
+
st = c.streams.video[0]
|
| 412 |
+
st.thread_type = "AUTO"
|
| 413 |
+
i = 0
|
| 414 |
+
for fr in c.decode(st):
|
| 415 |
+
if i % stride == 0:
|
| 416 |
+
a = fr.to_rgb().to_ndarray()
|
| 417 |
+
x = torch.from_numpy(np.ascontiguousarray(a)).permute(2, 0, 1).float().div_(255.0)
|
| 418 |
+
if x.shape[-2:] != (self.image_size, self.image_size):
|
| 419 |
+
x = F.interpolate(x[None], size=(self.image_size, self.image_size),
|
| 420 |
+
mode="bilinear", align_corners=False)[0]
|
| 421 |
+
out.append(x)
|
| 422 |
+
if len(out) >= n_needed:
|
| 423 |
+
break
|
| 424 |
+
i += 1
|
| 425 |
+
return out
|
| 426 |
+
|
| 427 |
+
def episode_samples(self, si: int, ep_idx: int, task: str, starts):
|
| 428 |
+
"""Samples at the given strided start indices. Mirrors _stream_episode."""
|
| 429 |
+
spec = self.specs[si]
|
| 430 |
+
meta = self._load_meta(si)
|
| 431 |
+
rid, pfx = spec["repo_id"], spec.get("prefix", "")
|
| 432 |
+
p = f"{pfx}/" if pfx else ""
|
| 433 |
+
info, stride = meta["info"], meta["stride"]
|
| 434 |
+
ch = ep_idx // meta["chunks_size"]
|
| 435 |
+
|
| 436 |
+
import pyarrow.parquet as pq
|
| 437 |
+
|
| 438 |
+
t = pq.read_table(io.BytesIO(self._fetch(rid, p + info["data_path"].format(
|
| 439 |
+
episode_chunk=ch, episode_index=ep_idx))))
|
| 440 |
+
keep = np.arange(0, t.num_rows, stride)
|
| 441 |
+
sm, ss = meta["stats"]["observation.state"]
|
| 442 |
+
am, as_ = meta["stats"]["action"]
|
| 443 |
+
state = (np.stack([np.asarray(x, np.float32) for x in
|
| 444 |
+
t["observation.state"].to_numpy(zero_copy_only=False)[keep]]) - sm) / np.maximum(ss, 1e-6)
|
| 445 |
+
action = (np.stack([np.asarray(x, np.float32) for x in
|
| 446 |
+
t["action"].to_numpy(zero_copy_only=False)[keep]]) - am) / np.maximum(as_, 1e-6)
|
| 447 |
+
|
| 448 |
+
starts = [int(s) for s in starts]
|
| 449 |
+
n_needed = max(starts) + self.chunk + 1
|
| 450 |
+
cams = {}
|
| 451 |
+
for slot, key in zip(("cam0", "cam1"), meta["cams"]):
|
| 452 |
+
if key is None:
|
| 453 |
+
cams[slot] = None
|
| 454 |
+
continue
|
| 455 |
+
blob = self._fetch(rid, p + info["video_path"].format(
|
| 456 |
+
episode_chunk=ch, video_key=key, episode_index=ep_idx))
|
| 457 |
+
cams[slot] = self._decode_capped(blob, stride, n_needed)
|
| 458 |
+
|
| 459 |
+
m = min(len(keep), *(len(v) for v in cams.values() if v is not None))
|
| 460 |
+
state_t = torch.from_numpy(state[:m])
|
| 461 |
+
action_t = torch.from_numpy(action[:m])
|
| 462 |
+
ad = meta["action_dim"]
|
| 463 |
+
dim_mask = torch.zeros(self.max_action_dim, dtype=torch.bool)
|
| 464 |
+
dim_mask[:ad] = True
|
| 465 |
+
cam_mask = torch.tensor([True, cams["cam1"] is not None])
|
| 466 |
+
zero_img = None
|
| 467 |
+
|
| 468 |
+
out = []
|
| 469 |
+
for j in starts:
|
| 470 |
+
if j + self.chunk > m:
|
| 471 |
+
continue # never evaluate a padded chunk
|
| 472 |
+
chunk_a = action_t[j : j + self.chunk]
|
| 473 |
+
if cams["cam1"] is None and zero_img is None:
|
| 474 |
+
zero_img = torch.zeros_like(cams["cam0"][j])
|
| 475 |
+
out.append({
|
| 476 |
+
"observation.images.cam0": cams["cam0"][j],
|
| 477 |
+
"observation.images.cam1": cams["cam1"][j] if cams["cam1"] is not None else zero_img,
|
| 478 |
+
"camera_mask": cam_mask,
|
| 479 |
+
"observation.state": _pad(state_t[j], self.max_state_dim, "state"),
|
| 480 |
+
"action": _pad(chunk_a, self.max_action_dim, "action"),
|
| 481 |
+
"action_dim_mask": dim_mask,
|
| 482 |
+
"action_is_pad": torch.zeros(self.chunk, dtype=torch.bool),
|
| 483 |
+
"embodiment_id": torch.tensor(spec.get("embodiment_id", si), dtype=torch.long),
|
| 484 |
+
"task": task,
|
| 485 |
+
"state_raw_row": j,
|
| 486 |
+
})
|
| 487 |
+
return out
|