Delete patch_lerobot_for_smolvla.py
Browse files- patch_lerobot_for_smolvla.py +0 -298
patch_lerobot_for_smolvla.py
DELETED
|
@@ -1,298 +0,0 @@
|
|
| 1 |
-
"""Patch an existing LeRobot v3 dataset to be usable for SmolVLA.
|
| 2 |
-
|
| 3 |
-
This script is intended for the common situation where a dataset was converted for ACT
|
| 4 |
-
but is missing SmolVLA-required language fields and/or uses an incompatible definition
|
| 5 |
-
for observation.state.
|
| 6 |
-
|
| 7 |
-
What it does:
|
| 8 |
-
- Creates a patched copy of the dataset (optionally symlinking videos to avoid duplication)
|
| 9 |
-
- Sets observation.state to the previous target (scheme-2): state[t] = action[t-1] within each episode
|
| 10 |
-
(state[0] is set to action[0] as a boundary condition)
|
| 11 |
-
- Adds SmolVLA language inputs:
|
| 12 |
-
- observation.language.tokens
|
| 13 |
-
- observation.language.attention_mask
|
| 14 |
-
computed from each episode's metadata.json "task" string using a Transformers tokenizer.
|
| 15 |
-
- Updates meta/info.json features and meta/stats.json.
|
| 16 |
-
- Updates meta/tasks.parquet (task strings live in the dataframe index) and meta/episodes parquet "tasks".
|
| 17 |
-
|
| 18 |
-
Usage example:
|
| 19 |
-
python backend/scripts/patch_lerobot_for_smolvla.py \
|
| 20 |
-
--dataset-dir backend/datasets/pick_up_objects \
|
| 21 |
-
--raw-dir backend/data/pick_up_objects \
|
| 22 |
-
--output-dir backend/datasets/pick_up_objects_smolvla \
|
| 23 |
-
--vlm-model-name HuggingFaceTB/SmolVLM2-500M-Video-Instruct \
|
| 24 |
-
--tokenizer-max-length 48
|
| 25 |
-
|
| 26 |
-
Notes:
|
| 27 |
-
- This does NOT re-encode videos.
|
| 28 |
-
- Requires "transformers" to be installed in the current environment.
|
| 29 |
-
"""
|
| 30 |
-
|
| 31 |
-
from __future__ import annotations
|
| 32 |
-
|
| 33 |
-
import argparse
|
| 34 |
-
import json
|
| 35 |
-
import shutil
|
| 36 |
-
from pathlib import Path
|
| 37 |
-
|
| 38 |
-
import numpy as np
|
| 39 |
-
import pandas as pd
|
| 40 |
-
|
| 41 |
-
try:
|
| 42 |
-
from transformers import AutoTokenizer
|
| 43 |
-
|
| 44 |
-
_TRANSFORMERS_AVAILABLE = True
|
| 45 |
-
except Exception:
|
| 46 |
-
_TRANSFORMERS_AVAILABLE = False
|
| 47 |
-
|
| 48 |
-
try:
|
| 49 |
-
from lerobot.datasets.compute_stats import DEFAULT_QUANTILES, get_feature_stats
|
| 50 |
-
|
| 51 |
-
_LEROBOT_STATS_AVAILABLE = True
|
| 52 |
-
except Exception:
|
| 53 |
-
_LEROBOT_STATS_AVAILABLE = False
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
STATE_KEY = "observation.state"
|
| 57 |
-
ACTION_KEY = "action"
|
| 58 |
-
LANG_TOKENS_KEY = "observation.language.tokens"
|
| 59 |
-
LANG_MASK_KEY = "observation.language.attention_mask"
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def _iter_episode_dirs(raw_dir: Path) -> list[Path]:
|
| 63 |
-
eps = [p for p in raw_dir.iterdir() if p.is_dir() and p.name.startswith("episode_")]
|
| 64 |
-
eps.sort(key=lambda p: int(p.name.split("_")[1]))
|
| 65 |
-
return eps
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def _collect_tasks_from_raw(raw_dir: Path) -> list[str]:
|
| 69 |
-
tasks: list[str] = []
|
| 70 |
-
for ep_dir in _iter_episode_dirs(raw_dir):
|
| 71 |
-
meta_path = ep_dir / "metadata.json"
|
| 72 |
-
if not meta_path.exists():
|
| 73 |
-
continue
|
| 74 |
-
meta = json.loads(meta_path.read_text())
|
| 75 |
-
task = meta.get("task")
|
| 76 |
-
if isinstance(task, str) and task.strip():
|
| 77 |
-
tasks.append(task.strip())
|
| 78 |
-
# preserve order but unique
|
| 79 |
-
seen = set()
|
| 80 |
-
uniq: list[str] = []
|
| 81 |
-
for t in tasks:
|
| 82 |
-
if t not in seen:
|
| 83 |
-
seen.add(t)
|
| 84 |
-
uniq.append(t)
|
| 85 |
-
return uniq
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def _normalize_task_text(task: str) -> str:
|
| 89 |
-
# Keep it minimal and stable: convert snake_case to words.
|
| 90 |
-
return task.replace("_", " ").strip()
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def _encode_tasks(tasks: list[str], vlm_model_name: str, tokenizer_max_length: int) -> dict[str, tuple[list[int], list[int]]]:
|
| 94 |
-
if not _TRANSFORMERS_AVAILABLE:
|
| 95 |
-
raise RuntimeError(
|
| 96 |
-
"transformers is required to generate language tokens. Install it with `pip install transformers`."
|
| 97 |
-
)
|
| 98 |
-
|
| 99 |
-
tokenizer = AutoTokenizer.from_pretrained(vlm_model_name, use_fast=True)
|
| 100 |
-
encoded: dict[str, tuple[list[int], list[int]]] = {}
|
| 101 |
-
for task in tasks:
|
| 102 |
-
text = _normalize_task_text(task)
|
| 103 |
-
out = tokenizer(
|
| 104 |
-
text,
|
| 105 |
-
padding="max_length",
|
| 106 |
-
truncation=True,
|
| 107 |
-
max_length=tokenizer_max_length,
|
| 108 |
-
return_attention_mask=True,
|
| 109 |
-
return_tensors=None,
|
| 110 |
-
)
|
| 111 |
-
input_ids = list(map(int, out["input_ids"]))
|
| 112 |
-
attn = list(map(int, out["attention_mask"]))
|
| 113 |
-
if len(input_ids) != tokenizer_max_length or len(attn) != tokenizer_max_length:
|
| 114 |
-
raise ValueError("Tokenizer output length mismatch; expected fixed max_length")
|
| 115 |
-
encoded[task] = (input_ids, attn)
|
| 116 |
-
|
| 117 |
-
return encoded
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
def _compute_stats(states: np.ndarray, actions: np.ndarray, existing_stats: dict) -> dict:
|
| 121 |
-
# Recompute state/action stats; preserve image stats unchanged.
|
| 122 |
-
stats = dict(existing_stats) if isinstance(existing_stats, dict) else {}
|
| 123 |
-
|
| 124 |
-
if _LEROBOT_STATS_AVAILABLE:
|
| 125 |
-
state_stats = get_feature_stats(states, axis=0, keepdims=False, quantile_list=DEFAULT_QUANTILES)
|
| 126 |
-
action_stats = get_feature_stats(actions, axis=0, keepdims=False, quantile_list=DEFAULT_QUANTILES)
|
| 127 |
-
stats[STATE_KEY] = {k: v.tolist() for k, v in state_stats.items()}
|
| 128 |
-
stats[ACTION_KEY] = {k: v.tolist() for k, v in action_stats.items()}
|
| 129 |
-
else:
|
| 130 |
-
stats[STATE_KEY] = {
|
| 131 |
-
"min": states.min(axis=0).tolist(),
|
| 132 |
-
"max": states.max(axis=0).tolist(),
|
| 133 |
-
"mean": states.mean(axis=0).tolist(),
|
| 134 |
-
"std": states.std(axis=0).tolist(),
|
| 135 |
-
}
|
| 136 |
-
stats[ACTION_KEY] = {
|
| 137 |
-
"min": actions.min(axis=0).tolist(),
|
| 138 |
-
"max": actions.max(axis=0).tolist(),
|
| 139 |
-
"mean": actions.mean(axis=0).tolist(),
|
| 140 |
-
"std": actions.std(axis=0).tolist(),
|
| 141 |
-
}
|
| 142 |
-
|
| 143 |
-
return stats
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
def patch_dataset(
|
| 147 |
-
dataset_dir: Path,
|
| 148 |
-
raw_dir: Path,
|
| 149 |
-
output_dir: Path,
|
| 150 |
-
vlm_model_name: str,
|
| 151 |
-
tokenizer_max_length: int,
|
| 152 |
-
symlink_videos: bool,
|
| 153 |
-
) -> None:
|
| 154 |
-
if not dataset_dir.exists():
|
| 155 |
-
raise FileNotFoundError(f"dataset_dir not found: {dataset_dir}")
|
| 156 |
-
if not raw_dir.exists():
|
| 157 |
-
raise FileNotFoundError(f"raw_dir not found: {raw_dir}")
|
| 158 |
-
|
| 159 |
-
tasks = _collect_tasks_from_raw(raw_dir)
|
| 160 |
-
if not tasks:
|
| 161 |
-
raise ValueError(f"No tasks found in raw metadata under {raw_dir}")
|
| 162 |
-
if len(tasks) != 1:
|
| 163 |
-
# The existing converter currently writes a single task_index=0 for all frames.
|
| 164 |
-
# If you truly have multiple tasks, you should re-convert with a corrected mapping.
|
| 165 |
-
raise ValueError(
|
| 166 |
-
f"Found {len(tasks)} unique tasks in raw data ({tasks}), but this dataset appears single-task. "
|
| 167 |
-
"Re-run conversion with multi-task support if needed."
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
task = tasks[0]
|
| 171 |
-
encoded = _encode_tasks([task], vlm_model_name, tokenizer_max_length)
|
| 172 |
-
tok, mask = encoded[task]
|
| 173 |
-
|
| 174 |
-
if output_dir.exists():
|
| 175 |
-
shutil.rmtree(output_dir)
|
| 176 |
-
output_dir.mkdir(parents=True, exist_ok=True)
|
| 177 |
-
|
| 178 |
-
# Copy data/meta; reuse videos via symlink if requested.
|
| 179 |
-
shutil.copytree(dataset_dir / "data", output_dir / "data")
|
| 180 |
-
shutil.copytree(dataset_dir / "meta", output_dir / "meta")
|
| 181 |
-
|
| 182 |
-
src_videos = dataset_dir / "videos"
|
| 183 |
-
if src_videos.exists():
|
| 184 |
-
if symlink_videos:
|
| 185 |
-
(output_dir / "videos").symlink_to(src_videos, target_is_directory=True)
|
| 186 |
-
else:
|
| 187 |
-
shutil.copytree(src_videos, output_dir / "videos")
|
| 188 |
-
|
| 189 |
-
# Patch tasks.parquet (task string is the index).
|
| 190 |
-
tasks_df = pd.DataFrame({"task_index": [0]}, index=[task])
|
| 191 |
-
tasks_df.to_parquet(output_dir / "meta" / "tasks.parquet", index=True)
|
| 192 |
-
|
| 193 |
-
# Patch episodes parquet (update tasks list entry).
|
| 194 |
-
episodes_paths = sorted((output_dir / "meta" / "episodes").glob("chunk-*/*.parquet"))
|
| 195 |
-
if not episodes_paths:
|
| 196 |
-
raise FileNotFoundError("No episodes parquet found under meta/episodes")
|
| 197 |
-
for ep_path in episodes_paths:
|
| 198 |
-
edf = pd.read_parquet(ep_path)
|
| 199 |
-
if "tasks" in edf.columns:
|
| 200 |
-
edf["tasks"] = [[task] for _ in range(len(edf))]
|
| 201 |
-
if "task_index" in edf.columns:
|
| 202 |
-
edf["task_index"] = 0
|
| 203 |
-
edf.to_parquet(ep_path, index=False)
|
| 204 |
-
|
| 205 |
-
# Patch data parquet(s).
|
| 206 |
-
data_paths = sorted((output_dir / "data").glob("chunk-*/*.parquet"))
|
| 207 |
-
if not data_paths:
|
| 208 |
-
raise FileNotFoundError("No data parquet found under data/")
|
| 209 |
-
|
| 210 |
-
all_states = []
|
| 211 |
-
all_actions = []
|
| 212 |
-
|
| 213 |
-
for dp in data_paths:
|
| 214 |
-
df = pd.read_parquet(dp)
|
| 215 |
-
required = {STATE_KEY, ACTION_KEY, "episode_index", "frame_index", "task_index"}
|
| 216 |
-
missing = required - set(df.columns)
|
| 217 |
-
if missing:
|
| 218 |
-
raise ValueError(f"Missing required columns in {dp}: {sorted(missing)}")
|
| 219 |
-
|
| 220 |
-
df = df.sort_values(["episode_index", "frame_index"]).reset_index(drop=False)
|
| 221 |
-
# Shift state within each episode: state[t] = action[t-1]
|
| 222 |
-
action_arr = np.stack(df[ACTION_KEY].to_numpy())
|
| 223 |
-
ep_idx = df["episode_index"].to_numpy()
|
| 224 |
-
|
| 225 |
-
state_arr = np.empty_like(action_arr)
|
| 226 |
-
# process per episode
|
| 227 |
-
start = 0
|
| 228 |
-
while start < len(df):
|
| 229 |
-
curr_ep = ep_idx[start]
|
| 230 |
-
end = start
|
| 231 |
-
while end < len(df) and ep_idx[end] == curr_ep:
|
| 232 |
-
end += 1
|
| 233 |
-
a = action_arr[start:end]
|
| 234 |
-
s = np.vstack([a[0:1], a[:-1]])
|
| 235 |
-
state_arr[start:end] = s
|
| 236 |
-
start = end
|
| 237 |
-
|
| 238 |
-
# Add language columns (same for all rows; single-task)
|
| 239 |
-
df[STATE_KEY] = [row.tolist() for row in state_arr]
|
| 240 |
-
df[LANG_TOKENS_KEY] = [tok for _ in range(len(df))]
|
| 241 |
-
df[LANG_MASK_KEY] = [mask for _ in range(len(df))]
|
| 242 |
-
|
| 243 |
-
# Restore original row order (by the previous dataframe index).
|
| 244 |
-
df = df.sort_values("index").drop(columns=["index"]).reset_index(drop=True)
|
| 245 |
-
|
| 246 |
-
dp.parent.mkdir(parents=True, exist_ok=True)
|
| 247 |
-
df.to_parquet(dp, index=False)
|
| 248 |
-
|
| 249 |
-
all_states.append(state_arr)
|
| 250 |
-
all_actions.append(action_arr)
|
| 251 |
-
|
| 252 |
-
# Update info.json features.
|
| 253 |
-
info_path = output_dir / "meta" / "info.json"
|
| 254 |
-
info = json.loads(info_path.read_text())
|
| 255 |
-
features = info.get("features", {})
|
| 256 |
-
features[LANG_TOKENS_KEY] = {"dtype": "int64", "shape": [tokenizer_max_length], "names": None}
|
| 257 |
-
features[LANG_MASK_KEY] = {"dtype": "int64", "shape": [tokenizer_max_length], "names": None}
|
| 258 |
-
info["features"] = features
|
| 259 |
-
info["total_tasks"] = 1
|
| 260 |
-
info_path.write_text(json.dumps(info, indent=2))
|
| 261 |
-
|
| 262 |
-
# Update stats.json.
|
| 263 |
-
stats_path = output_dir / "meta" / "stats.json"
|
| 264 |
-
existing_stats = json.loads(stats_path.read_text()) if stats_path.exists() else {}
|
| 265 |
-
|
| 266 |
-
states = np.concatenate(all_states, axis=0)
|
| 267 |
-
actions = np.concatenate(all_actions, axis=0)
|
| 268 |
-
stats = _compute_stats(states, actions, existing_stats)
|
| 269 |
-
stats_path.write_text(json.dumps(stats, indent=2))
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
def main() -> None:
|
| 273 |
-
parser = argparse.ArgumentParser(description="Patch a LeRobot dataset for SmolVLA")
|
| 274 |
-
parser.add_argument("--dataset-dir", type=str, required=True)
|
| 275 |
-
parser.add_argument("--raw-dir", type=str, required=True)
|
| 276 |
-
parser.add_argument("--output-dir", type=str, required=True)
|
| 277 |
-
parser.add_argument(
|
| 278 |
-
"--vlm-model-name",
|
| 279 |
-
type=str,
|
| 280 |
-
default="HuggingFaceTB/SmolVLM2-500M-Video-Instruct",
|
| 281 |
-
)
|
| 282 |
-
parser.add_argument("--tokenizer-max-length", type=int, default=48)
|
| 283 |
-
parser.add_argument("--no-symlink-videos", action="store_true")
|
| 284 |
-
|
| 285 |
-
args = parser.parse_args()
|
| 286 |
-
|
| 287 |
-
patch_dataset(
|
| 288 |
-
dataset_dir=Path(args.dataset_dir),
|
| 289 |
-
raw_dir=Path(args.raw_dir),
|
| 290 |
-
output_dir=Path(args.output_dir),
|
| 291 |
-
vlm_model_name=args.vlm_model_name,
|
| 292 |
-
tokenizer_max_length=args.tokenizer_max_length,
|
| 293 |
-
symlink_videos=not args.no_symlink_videos,
|
| 294 |
-
)
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
if __name__ == "__main__":
|
| 298 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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