Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. Β See raw diff
- README.md +34 -8
- app.py +414 -0
- examples/lab_scene_alt.jpg +0 -0
- examples/lab_scene_view.jpg +0 -0
- labsim_transforms.py +178 -0
- labvla_schema.json +20 -0
- requirements.txt +13 -0
- src/__init__.py +1 -0
- src/adapters/__init__.py +3 -0
- src/adapters/_scan_cache.py +130 -0
- src/adapters/base.py +82 -0
- src/adapters/lerobot_base.py +1101 -0
- src/adapters/lerobot_v21.py +710 -0
- src/adapters/lerobot_v30.py +942 -0
- src/adapters/registry.py +92 -0
- src/adapters/vqa_adapter.py +183 -0
- src/config/__init__.py +1 -0
- src/config/default.py +68 -0
- src/config/policies.py +234 -0
- src/config/types.py +42 -0
- src/dataset/__init__.py +1 -0
- src/dataset/adapters/__init__.py +0 -0
- src/dataset/adapters/robointer_token_budget.py +115 -0
- src/dataset/adapters/robointer_vqa_adapter.py +544 -0
- src/dataset/pi0_mixture.py +249 -0
- src/dataset/transforms.py +325 -0
- src/dataset/utils.py +1283 -0
- src/dataset/video_utils.py +34 -0
- src/optim/__init__.py +15 -0
- src/optim/ema.py +191 -0
- src/optim/optimizers.py +367 -0
- src/optim/schedulers.py +176 -0
- src/policies/LabVLA/__init__.py +0 -0
- src/policies/LabVLA/configuration_labvla.py +656 -0
- src/policies/LabVLA/dit_action_head.py +338 -0
- src/policies/LabVLA/ki/__init__.py +13 -0
- src/policies/LabVLA/ki/fast_tokenizer.py +10 -0
- src/policies/LabVLA/ki/ki_head.py +107 -0
- src/policies/LabVLA/modeling_labvla.py +0 -0
- src/policies/LabVLA/transform_labvla.py +14 -0
- src/policies/__init__.py +19 -0
- src/policies/pretrained.py +272 -0
- src/policies/utils.py +132 -0
- src/schema/__init__.py +82 -0
- src/schema/annotation_loss.py +169 -0
- src/schema/arm_layout.py +262 -0
- src/schema/blueprint.py +291 -0
- src/schema/camera_mapping.py +219 -0
- src/schema/dataset_schema.py +213 -0
- src/schema/discovery.py +307 -0
README.md
CHANGED
|
@@ -1,13 +1,39 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 6.
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: LabVLA
|
| 3 |
+
emoji: π§ͺ
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.15.1
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
short_description: VLA model for scientific laboratory robotics
|
| 10 |
+
python_version: "3.12"
|
| 11 |
+
startup_duration_timeout: 1h
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# LabVLA: Vision-Language-Action Model for Scientific Laboratories
|
| 15 |
+
|
| 16 |
+
LabVLA is the first VLA foundation model designed specifically for scientific laboratory environments.
|
| 17 |
+
It combines a **Qwen3-VL-4B** vision-language backbone with a **DiT flow-matching action expert** trained
|
| 18 |
+
with the Ο0.5 recipe: FAST action-token pre-training β flow-matching post-training with knowledge isolation.
|
| 19 |
+
|
| 20 |
+
This demo lets you provide a laboratory camera view and a natural language instruction, and the model
|
| 21 |
+
predicts a chunk of 50 future robot actions (7 arm joint angles + 1 gripper width per step) for a Franka
|
| 22 |
+
Panda manipulator.
|
| 23 |
+
|
| 24 |
+
## Model
|
| 25 |
+
|
| 26 |
+
- **Model**: [zjunlp/LabVLA-5B-Base](https://huggingface.co/zjunlp/LabVLA-5B-Base)
|
| 27 |
+
- **Paper**: [LabVLA: Grounding Vision-Language-Action Models in Scientific Laboratories](https://huggingface.co/papers/2606.13578)
|
| 28 |
+
- **GitHub**: [zjunlp/LabVLA](https://github.com/zjunlp/LabVLA)
|
| 29 |
+
|
| 30 |
+
## Inputs
|
| 31 |
+
|
| 32 |
+
- **Camera View**: An image of the laboratory workspace
|
| 33 |
+
- **Task Instruction**: Natural language instruction (e.g., "Pick up the beaker")
|
| 34 |
+
- **Robot State**: 7 arm joint angles + 1 gripper width (Franka Panda 7-DOF)
|
| 35 |
+
|
| 36 |
+
## Outputs
|
| 37 |
+
|
| 38 |
+
- **Action Trajectory**: 50-step predicted action chunk visualized as per-joint trajectory plots
|
| 39 |
+
- **Action Details**: JSON with the raw action values and timing information
|
app.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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before torch / any CUDA-touching import
|
| 7 |
+
import sys
|
| 8 |
+
import json
|
| 9 |
+
import time
|
| 10 |
+
import tempfile
|
| 11 |
+
import logging
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
from PIL import Image
|
| 17 |
+
|
| 18 |
+
# Add the Space repo root to sys.path so `src` and `deployment` modules are importable
|
| 19 |
+
SPACE_ROOT = Path(__file__).resolve().parent
|
| 20 |
+
if str(SPACE_ROOT) not in sys.path:
|
| 21 |
+
sys.path.insert(0, str(SPACE_ROOT))
|
| 22 |
+
|
| 23 |
+
# Also add the LabVLA repo root for deployment imports
|
| 24 |
+
LABVLA_ROOT = str(SPACE_ROOT)
|
| 25 |
+
os.environ.setdefault("LABVLA_ROOT", LABVLA_ROOT)
|
| 26 |
+
|
| 27 |
+
import gradio as gr
|
| 28 |
+
|
| 29 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
MODEL_ID = "zjunlp/LabVLA-5B-Base"
|
| 33 |
+
|
| 34 |
+
# ---- Download model checkpoint ----
|
| 35 |
+
from huggingface_hub import snapshot_download
|
| 36 |
+
|
| 37 |
+
logger.info(f"Downloading model from {MODEL_ID}...")
|
| 38 |
+
_model_dir = snapshot_download(
|
| 39 |
+
repo_id=MODEL_ID,
|
| 40 |
+
repo_type="model",
|
| 41 |
+
local_dir=str(SPACE_ROOT / "model_cache"),
|
| 42 |
+
)
|
| 43 |
+
# The checkpoint files are at the root of the repo
|
| 44 |
+
PRETRAINED_PATH = str(SPACE_ROOT / "model_cache")
|
| 45 |
+
logger.info(f"Model downloaded to {PRETRAINED_PATH}")
|
| 46 |
+
|
| 47 |
+
# ---- Load the LabVLA policy ----
|
| 48 |
+
from deployment.labsim_transforms import parse_image_to_uint8_hwc
|
| 49 |
+
from src.policies.LabVLA.configuration_labvla import LabVLAConfig
|
| 50 |
+
from src.policies.LabVLA.modeling_labvla import LabVLAPolicy
|
| 51 |
+
|
| 52 |
+
# Load config from the checkpoint
|
| 53 |
+
config_path = Path(PRETRAINED_PATH) / "config.json"
|
| 54 |
+
with open(config_path) as f:
|
| 55 |
+
saved_config = json.load(f)
|
| 56 |
+
|
| 57 |
+
# Build LabVLAConfig from saved config, with deploy overrides
|
| 58 |
+
allowed_fields = set(LabVLAConfig.__dataclass_fields__.keys())
|
| 59 |
+
saved_fwd = {k: v for k, v in saved_config.items() if k in allowed_fields}
|
| 60 |
+
|
| 61 |
+
# Normalize tuple fields
|
| 62 |
+
if "image_resolution" in saved_fwd and isinstance(saved_fwd["image_resolution"], list):
|
| 63 |
+
saved_fwd["image_resolution"] = tuple(saved_fwd["image_resolution"])
|
| 64 |
+
if "optimizer_betas" in saved_fwd and isinstance(saved_fwd["optimizer_betas"], list):
|
| 65 |
+
saved_fwd["optimizer_betas"] = tuple(saved_fwd["optimizer_betas"])
|
| 66 |
+
|
| 67 |
+
# Drop str-fallback fields that can't be properly deserialized
|
| 68 |
+
for field_name in ("input_features", "output_features"):
|
| 69 |
+
if field_name in saved_fwd and isinstance(saved_fwd[field_name], str):
|
| 70 |
+
saved_fwd.pop(field_name)
|
| 71 |
+
|
| 72 |
+
# Deploy overrides: no GC, no compile, use the checkpoint's bundled VLM
|
| 73 |
+
saved_fwd["vlm_pretrained_path"] = PRETRAINED_PATH
|
| 74 |
+
saved_fwd["freeze_vision_encoder"] = False
|
| 75 |
+
saved_fwd["gradient_checkpointing"] = False
|
| 76 |
+
saved_fwd["compile_model"] = False
|
| 77 |
+
|
| 78 |
+
# Use SDPA instead of flash_attention_2 for ZeroGPU compatibility
|
| 79 |
+
saved_fwd["attn_implementation"] = "sdpa"
|
| 80 |
+
|
| 81 |
+
config = LabVLAConfig(**saved_fwd)
|
| 82 |
+
|
| 83 |
+
# Load the policy
|
| 84 |
+
logger.info("Loading LabVLA policy...")
|
| 85 |
+
policy = LabVLAPolicy.from_pretrained(
|
| 86 |
+
pretrained_name_or_path=PRETRAINED_PATH,
|
| 87 |
+
config=config,
|
| 88 |
+
strict=True,
|
| 89 |
+
)
|
| 90 |
+
policy.to("cuda")
|
| 91 |
+
policy.eval()
|
| 92 |
+
logger.info("LabVLA policy loaded successfully!")
|
| 93 |
+
|
| 94 |
+
# Load VLM processor for image/token processing
|
| 95 |
+
from transformers import Qwen3VLProcessor
|
| 96 |
+
vlm_processor = Qwen3VLProcessor.from_pretrained(PRETRAINED_PATH)
|
| 97 |
+
vision_start_token_id = vlm_processor.vision_start_token_id
|
| 98 |
+
vision_end_token_id = vlm_processor.vision_end_token_id
|
| 99 |
+
image_token_id = vlm_processor.image_token_id
|
| 100 |
+
|
| 101 |
+
# Image processing constants
|
| 102 |
+
SPATIAL_MERGE_SIZE = 2
|
| 103 |
+
h, w = config.image_resolution
|
| 104 |
+
image_size = (h, w)
|
| 105 |
+
dummy_img = torch.zeros(h, w, 3)
|
| 106 |
+
dummy_out = vlm_processor.image_processor([dummy_img], do_rescale=False, return_tensors="pt")
|
| 107 |
+
_fixed_grid_thw = dummy_out["image_grid_thw"]
|
| 108 |
+
num_patches = int(_fixed_grid_thw[0, 0] * _fixed_grid_thw[0, 1] * _fixed_grid_thw[0, 2])
|
| 109 |
+
num_image_tokens = num_patches // (SPATIAL_MERGE_SIZE ** 2)
|
| 110 |
+
|
| 111 |
+
# Load schema
|
| 112 |
+
schema_path = SPACE_ROOT / "labvla_schema.json"
|
| 113 |
+
with open(schema_path) as f:
|
| 114 |
+
schema = json.load(f)
|
| 115 |
+
|
| 116 |
+
# Schema-derived dimensions
|
| 117 |
+
state_dim = sum(schema["state_dims"])
|
| 118 |
+
action_dim = sum(schema["action_dims"])
|
| 119 |
+
delta_mask = np.array(schema["delta_mask"], dtype=bool)
|
| 120 |
+
max_state_dim = config.max_state_dim
|
| 121 |
+
max_action_dim = config.max_action_dim
|
| 122 |
+
chunk_size = config.chunk_size
|
| 123 |
+
|
| 124 |
+
logger.info(
|
| 125 |
+
f"Schema loaded: state_dim={state_dim}, action_dim={action_dim}, "
|
| 126 |
+
f"chunk_size={chunk_size}, image_size={image_size}, "
|
| 127 |
+
f"num_image_tokens={num_image_tokens}"
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def resize_with_pad(image_tensor, target_h, target_w):
|
| 132 |
+
"""Resize keeping aspect ratio + zero-pad to target size."""
|
| 133 |
+
from src.transforms.utils import resize_with_pad as _train_resize_with_pad
|
| 134 |
+
return _train_resize_with_pad(image_tensor, target_h, target_w, "bilinear")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def process_image(image_hwc):
|
| 138 |
+
"""Convert HWC uint8 image to Qwen3-VL pixel_values."""
|
| 139 |
+
target_h, target_w = image_size
|
| 140 |
+
img_tensor = torch.from_numpy(image_hwc.copy()).float() / 255.0
|
| 141 |
+
img_tensor = img_tensor.permute(2, 0, 1)
|
| 142 |
+
img_tensor = resize_with_pad(img_tensor, target_h, target_w)
|
| 143 |
+
img_inputs = vlm_processor.image_processor([img_tensor], do_rescale=False, return_tensors="pt")
|
| 144 |
+
pixel_values = img_inputs["pixel_values"]
|
| 145 |
+
image_grid_thw = img_inputs["image_grid_thw"]
|
| 146 |
+
return pixel_values, image_grid_thw
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def build_batch(images, prompt, state):
|
| 150 |
+
"""Build input batch from camera images, prompt, and state."""
|
| 151 |
+
all_pixel_values = []
|
| 152 |
+
all_image_grid_thw = []
|
| 153 |
+
input_ids = []
|
| 154 |
+
attention_mask = []
|
| 155 |
+
|
| 156 |
+
# Pre-process first valid image for placeholder
|
| 157 |
+
first_valid_idx = next((i for i, img in enumerate(images) if img is not None), None)
|
| 158 |
+
if first_valid_idx is None:
|
| 159 |
+
raise ValueError("No valid images provided")
|
| 160 |
+
|
| 161 |
+
placeholder_pv, placeholder_grid = process_image(images[first_valid_idx])
|
| 162 |
+
|
| 163 |
+
for i, img in enumerate(images):
|
| 164 |
+
if img is not None:
|
| 165 |
+
pv, grid = process_image(img)
|
| 166 |
+
all_pixel_values.append(pv)
|
| 167 |
+
all_image_grid_thw.append(grid)
|
| 168 |
+
vision_ids = (
|
| 169 |
+
[vision_start_token_id]
|
| 170 |
+
+ [image_token_id] * num_image_tokens
|
| 171 |
+
+ [vision_end_token_id]
|
| 172 |
+
)
|
| 173 |
+
input_ids += vision_ids
|
| 174 |
+
attention_mask += [1] * len(vision_ids)
|
| 175 |
+
else:
|
| 176 |
+
all_pixel_values.append(placeholder_pv)
|
| 177 |
+
all_image_grid_thw.append(placeholder_grid)
|
| 178 |
+
vision_ids = (
|
| 179 |
+
[vision_start_token_id]
|
| 180 |
+
+ [image_token_id] * num_image_tokens
|
| 181 |
+
+ [vision_end_token_id]
|
| 182 |
+
)
|
| 183 |
+
input_ids += vision_ids
|
| 184 |
+
attention_mask += [0] * len(vision_ids)
|
| 185 |
+
|
| 186 |
+
# Tokenize language instruction
|
| 187 |
+
lang_inputs = vlm_processor.tokenizer(
|
| 188 |
+
prompt,
|
| 189 |
+
max_length=config.tokenizer_max_length,
|
| 190 |
+
padding="max_length",
|
| 191 |
+
truncation=True,
|
| 192 |
+
)
|
| 193 |
+
input_ids += lang_inputs.input_ids
|
| 194 |
+
attention_mask += lang_inputs.attention_mask
|
| 195 |
+
|
| 196 |
+
pixel_values = torch.cat(all_pixel_values, dim=0)
|
| 197 |
+
image_grid_thw = torch.cat(all_image_grid_thw, dim=0)
|
| 198 |
+
|
| 199 |
+
# Pad state to max_state_dim
|
| 200 |
+
state_padded = np.zeros(max_state_dim, dtype=np.float32)
|
| 201 |
+
state_padded[:min(len(state), max_state_dim)] = state[:max_state_dim]
|
| 202 |
+
state_tensor = torch.from_numpy(state_padded).to(dtype=torch.bfloat16)
|
| 203 |
+
|
| 204 |
+
batch = {
|
| 205 |
+
"observation.pixel_values": pixel_values.unsqueeze(0).to("cuda"),
|
| 206 |
+
"observation.image_grid_thw": image_grid_thw.to("cuda"),
|
| 207 |
+
"observation.input_ids": torch.tensor(input_ids, dtype=torch.long).unsqueeze(0).to("cuda"),
|
| 208 |
+
"observation.attention_mask": torch.tensor(attention_mask, dtype=torch.long).unsqueeze(0).to("cuda"),
|
| 209 |
+
"observation.state": state_tensor.unsqueeze(0).to("cuda"),
|
| 210 |
+
}
|
| 211 |
+
return batch
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@spaces.GPU(duration=120)
|
| 215 |
+
def predict_actions(
|
| 216 |
+
camera_1: Image.Image,
|
| 217 |
+
instruction: str,
|
| 218 |
+
state_j1: float, state_j2: float, state_j3: float,
|
| 219 |
+
state_j4: float, state_j5: float, state_j6: float,
|
| 220 |
+
state_j7: float, gripper: float,
|
| 221 |
+
):
|
| 222 |
+
"""Predict a robot action chunk from laboratory camera views and a language instruction.
|
| 223 |
+
|
| 224 |
+
LabVLA is a Vision-Language-Action model that takes camera images, a natural
|
| 225 |
+
language instruction, and the current robot state (7 joint angles + 1 gripper
|
| 226 |
+
width) as input, and predicts a chunk of 50 future action steps.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
camera_1: Camera view of the laboratory workspace.
|
| 230 |
+
instruction: Natural language task instruction (e.g. "Pick up the beaker").
|
| 231 |
+
state_j1..j7: Franka Panda 7-DOF arm joint angles (radians).
|
| 232 |
+
gripper: Gripper width in meters (0.0 = closed, 0.04 = fully open).
|
| 233 |
+
|
| 234 |
+
Returns:
|
| 235 |
+
A matplotlib figure visualizing the predicted action trajectory,
|
| 236 |
+
and a JSON string with the raw action values.
|
| 237 |
+
"""
|
| 238 |
+
if not instruction or not instruction.strip():
|
| 239 |
+
return None, '{"error": "Please provide a task instruction."}'
|
| 240 |
+
|
| 241 |
+
# Convert PIL image to numpy
|
| 242 |
+
img1 = np.array(camera_1.convert("RGB"))
|
| 243 |
+
img1 = parse_image_to_uint8_hwc(img1)
|
| 244 |
+
|
| 245 |
+
# Use the same image for all 3 cameras (the model supports 3 camera views;
|
| 246 |
+
# with only 1, slots 2/3 are masked out)
|
| 247 |
+
images = [img1, None, None]
|
| 248 |
+
|
| 249 |
+
# Build state vector
|
| 250 |
+
state = np.array([state_j1, state_j2, state_j3, state_j4,
|
| 251 |
+
state_j5, state_j6, state_j7, gripper], dtype=np.float32)
|
| 252 |
+
|
| 253 |
+
start_time = time.perf_counter()
|
| 254 |
+
|
| 255 |
+
# Build batch
|
| 256 |
+
batch = build_batch(images, instruction, state)
|
| 257 |
+
|
| 258 |
+
# Run inference
|
| 259 |
+
with torch.no_grad():
|
| 260 |
+
action_chunk = policy.predict_action_chunk(batch)
|
| 261 |
+
|
| 262 |
+
if isinstance(action_chunk, torch.Tensor):
|
| 263 |
+
actions = action_chunk.detach().float().cpu().numpy()
|
| 264 |
+
else:
|
| 265 |
+
actions = np.asarray(action_chunk)
|
| 266 |
+
|
| 267 |
+
if actions.ndim == 3:
|
| 268 |
+
actions = actions[0]
|
| 269 |
+
|
| 270 |
+
# Truncate to action_dim
|
| 271 |
+
actions = actions[:, :action_dim]
|
| 272 |
+
|
| 273 |
+
# Delta -> absolute for arm dims
|
| 274 |
+
arm_mask = delta_mask[:actions.shape[-1]]
|
| 275 |
+
arm_idxs = np.where(arm_mask)[0]
|
| 276 |
+
if arm_idxs.size > 0:
|
| 277 |
+
n_arm = len(arm_mask)
|
| 278 |
+
state_for_add = state[:n_arm]
|
| 279 |
+
if state_for_add.shape[0] < n_arm:
|
| 280 |
+
state_for_add = np.concatenate([
|
| 281 |
+
state_for_add,
|
| 282 |
+
np.zeros(n_arm - state_for_add.shape[0], dtype=state_for_add.dtype),
|
| 283 |
+
])
|
| 284 |
+
state_delta = state_for_add[arm_mask]
|
| 285 |
+
actions[:, arm_mask] = actions[:, arm_mask] + state_delta[np.newaxis, :]
|
| 286 |
+
|
| 287 |
+
infer_time = time.perf_counter() - start_time
|
| 288 |
+
|
| 289 |
+
# Create visualization
|
| 290 |
+
import matplotlib
|
| 291 |
+
matplotlib.use("Agg")
|
| 292 |
+
import matplotlib.pyplot as plt
|
| 293 |
+
|
| 294 |
+
fig, axes = plt.subplots(2, 4, figsize=(16, 8))
|
| 295 |
+
fig.suptitle(
|
| 296 |
+
f"LabVLA Predicted Action Chunk ({chunk_size} steps, {infer_time:.2f}s)\n"
|
| 297 |
+
f"Instruction: \"{instruction}\"",
|
| 298 |
+
fontsize=12, fontweight="bold",
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
labels = ["J1", "J2", "J3", "J4", "J5", "J6", "J7", "Gripper"]
|
| 302 |
+
for i in range(8):
|
| 303 |
+
ax = axes[i // 4, i % 4]
|
| 304 |
+
ax.plot(actions[:, i], linewidth=2, color="#4C72B0")
|
| 305 |
+
ax.set_title(labels[i], fontsize=11, fontweight="bold")
|
| 306 |
+
ax.set_xlabel("Step")
|
| 307 |
+
ax.set_ylabel("Value" if i < 7 else "Width (m)")
|
| 308 |
+
ax.grid(True, alpha=0.3)
|
| 309 |
+
ax.axhline(y=state[i], color="r", linestyle="--", alpha=0.5, label="Current state")
|
| 310 |
+
if i == 0:
|
| 311 |
+
ax.legend(fontsize=8)
|
| 312 |
+
|
| 313 |
+
plt.tight_layout()
|
| 314 |
+
|
| 315 |
+
# Save figure
|
| 316 |
+
fig_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
|
| 317 |
+
fig.savefig(fig_path, dpi=150, bbox_inches="tight")
|
| 318 |
+
plt.close(fig)
|
| 319 |
+
|
| 320 |
+
# Prepare JSON output
|
| 321 |
+
actions_list = actions.tolist()
|
| 322 |
+
result = {
|
| 323 |
+
"instruction": instruction,
|
| 324 |
+
"state_input": state.tolist(),
|
| 325 |
+
"action_chunk_shape": list(actions.shape),
|
| 326 |
+
"num_steps": int(actions.shape[0]),
|
| 327 |
+
"action_dim": int(actions.shape[1]),
|
| 328 |
+
"inference_time_s": round(infer_time, 3),
|
| 329 |
+
"first_action": actions_list[0] if len(actions_list) > 0 else None,
|
| 330 |
+
"last_action": actions_list[-1] if len(actions_list) > 0 else None,
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
return fig_path, json.dumps(result, indent=2)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
# ---- Gradio UI ----
|
| 337 |
+
|
| 338 |
+
CSS = """
|
| 339 |
+
#col-container { max-width: 1200px; margin: 0 auto; }
|
| 340 |
+
.dark .gradio-container { color: var(--body-text-color); }
|
| 341 |
+
"""
|
| 342 |
+
|
| 343 |
+
with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo:
|
| 344 |
+
gr.Markdown("""
|
| 345 |
+
# π§ͺ LabVLA: Vision-Language-Action Model for Scientific Laboratories
|
| 346 |
+
|
| 347 |
+
LabVLA is the first VLA foundation model designed specifically for scientific laboratory environments.
|
| 348 |
+
It combines a **Qwen3-VL-4B** vision-language backbone with a **DiT flow-matching action expert** to
|
| 349 |
+
predict robotic action trajectories from laboratory camera views and language instructions.
|
| 350 |
+
|
| 351 |
+
π [Paper](https://huggingface.co/papers/2606.13578) β’
|
| 352 |
+
π» [GitHub](https://github.com/zjunlp/LabVLA) β’
|
| 353 |
+
π€ [Model](https://huggingface.co/zjunlp/LabVLA-5B-Base)
|
| 354 |
+
""")
|
| 355 |
+
|
| 356 |
+
with gr.Column(elem_id="col-container"):
|
| 357 |
+
with gr.Row():
|
| 358 |
+
with gr.Column(scale=1):
|
| 359 |
+
camera_1 = gr.Image(
|
| 360 |
+
label="Camera View (Laboratory Workspace)",
|
| 361 |
+
type="pil",
|
| 362 |
+
height=280,
|
| 363 |
+
)
|
| 364 |
+
instruction = gr.Textbox(
|
| 365 |
+
label="Task Instruction",
|
| 366 |
+
placeholder="e.g. Pick up the beaker and pour it into the flask",
|
| 367 |
+
value="Pick up the beaker",
|
| 368 |
+
lines=2,
|
| 369 |
+
)
|
| 370 |
+
with gr.Accordion("Robot State (Franka Panda 7-DOF + Gripper)", open=False):
|
| 371 |
+
with gr.Row():
|
| 372 |
+
state_j1 = gr.Slider(-6.28, 6.28, value=0.0, step=0.01, label="Joint 1 (rad)")
|
| 373 |
+
state_j2 = gr.Slider(-6.28, 6.28, value=0.0, step=0.01, label="Joint 2 (rad)")
|
| 374 |
+
with gr.Row():
|
| 375 |
+
state_j3 = gr.Slider(-6.28, 6.28, value=0.0, step=0.01, label="Joint 3 (rad)")
|
| 376 |
+
state_j4 = gr.Slider(-6.28, 6.28, value=0.0, step=0.01, label="Joint 4 (rad)")
|
| 377 |
+
with gr.Row():
|
| 378 |
+
state_j5 = gr.Slider(-6.28, 6.28, value=0.0, step=0.01, label="Joint 5 (rad)")
|
| 379 |
+
state_j6 = gr.Slider(-6.28, 6.28, value=0.0, step=0.01, label="Joint 6 (rad)")
|
| 380 |
+
with gr.Row():
|
| 381 |
+
state_j7 = gr.Slider(-6.28, 6.28, value=0.0, step=0.01, label="Joint 7 (rad)")
|
| 382 |
+
gripper = gr.Slider(0.0, 0.04, value=0.04, step=0.001, label="Gripper Width (m)")
|
| 383 |
+
|
| 384 |
+
run_btn = gr.Button("Predict Actions", variant="primary", size="lg")
|
| 385 |
+
|
| 386 |
+
with gr.Column(scale=1):
|
| 387 |
+
output_plot = gr.Image(label="Predicted Action Trajectory (50 steps)")
|
| 388 |
+
output_json = gr.Textbox(label="Action Details (JSON)", lines=12, max_lines=20)
|
| 389 |
+
|
| 390 |
+
gr.Examples(
|
| 391 |
+
examples=[
|
| 392 |
+
["examples/lab_scene_view.jpg", "Pick up the beaker and pour it into the flask"],
|
| 393 |
+
["examples/lab_scene_view.jpg", "Transfer the solution from the test tube to the beaker"],
|
| 394 |
+
["examples/lab_scene_alt.jpg", "Press the button on the instrument"],
|
| 395 |
+
],
|
| 396 |
+
inputs=[camera_1, instruction],
|
| 397 |
+
outputs=[output_plot, output_json],
|
| 398 |
+
fn=predict_actions,
|
| 399 |
+
cache_examples=True,
|
| 400 |
+
cache_mode="lazy",
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
run_btn.click(
|
| 404 |
+
fn=predict_actions,
|
| 405 |
+
inputs=[
|
| 406 |
+
camera_1, instruction,
|
| 407 |
+
state_j1, state_j2, state_j3, state_j4,
|
| 408 |
+
state_j5, state_j6, state_j7, gripper,
|
| 409 |
+
],
|
| 410 |
+
outputs=[output_plot, output_json],
|
| 411 |
+
api_name="predict",
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
demo.launch(mcp_server=True)
|
examples/lab_scene_alt.jpg
ADDED
|
examples/lab_scene_view.jpg
ADDED
|
labsim_transforms.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LabUtopia <-> LeRobot data transforms.
|
| 3 |
+
|
| 4 |
+
Handles converting LabUtopia observation format (camera_1_rgb, camera_2_rgb, camera_3_rgb,
|
| 5 |
+
state, prompt) into the LeRobot model input format, and converting model action outputs
|
| 6 |
+
back into the format LabUtopia expects.
|
| 7 |
+
|
| 8 |
+
This module is analogous to openpi's labsim_policy.py (LabSimInputs / LabSimOutputs).
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def parse_image_to_uint8_hwc(image: np.ndarray) -> np.ndarray:
|
| 21 |
+
"""
|
| 22 |
+
Parse an image to uint8 (H, W, C) format.
|
| 23 |
+
|
| 24 |
+
LabUtopia sends images as uint8 (H, W, C), but we handle edge cases:
|
| 25 |
+
- float images in [0, 1] -> convert to uint8
|
| 26 |
+
- (C, H, W) layout -> transpose to (H, W, C)
|
| 27 |
+
"""
|
| 28 |
+
image = np.asarray(image)
|
| 29 |
+
if np.issubdtype(image.dtype, np.floating):
|
| 30 |
+
image = (255 * np.clip(image, 0.0, 1.0)).astype(np.uint8)
|
| 31 |
+
# If shape is (C, H, W) with C in {1, 3, 4}, transpose
|
| 32 |
+
if image.ndim == 3 and image.shape[0] in (1, 3, 4) and image.shape[2] not in (1, 3, 4):
|
| 33 |
+
image = np.transpose(image, (1, 2, 0))
|
| 34 |
+
return image
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def image_hwc_uint8_to_chw_float32(image: np.ndarray, normalize: bool = True) -> torch.Tensor:
|
| 38 |
+
"""
|
| 39 |
+
Convert (H, W, C) uint8 image to (C, H, W) float32 tensor.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
image: uint8 image in (H, W, C) format
|
| 43 |
+
normalize: if True, output [0, 1] range (matches training data from video_utils);
|
| 44 |
+
if False, output [0, 255] range (for models with own image_to_float
|
| 45 |
+
step in their preprocessor, e.g. XVLA has xvla_image_to_float)
|
| 46 |
+
"""
|
| 47 |
+
image = np.asarray(image, dtype=np.float32)
|
| 48 |
+
if normalize:
|
| 49 |
+
image = image / 255.0 # -> [0, 1] to match training data format
|
| 50 |
+
if image.ndim == 3 and image.shape[2] in (1, 3, 4):
|
| 51 |
+
image = np.transpose(image, (2, 0, 1)) # (H,W,C) -> (C,H,W)
|
| 52 |
+
return torch.from_numpy(image)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def resize_image_tensor(image_tensor: torch.Tensor, target_h: int, target_w: int) -> torch.Tensor:
|
| 56 |
+
"""
|
| 57 |
+
Resize a (C, H, W) or (1, C, H, W) tensor to (target_h, target_w).
|
| 58 |
+
Returns (C, H, W) tensor.
|
| 59 |
+
"""
|
| 60 |
+
if image_tensor.ndim == 3:
|
| 61 |
+
image_tensor = image_tensor.unsqueeze(0)
|
| 62 |
+
resized = torch.nn.functional.interpolate(
|
| 63 |
+
image_tensor.float(), size=(target_h, target_w), mode="bilinear", align_corners=False
|
| 64 |
+
)
|
| 65 |
+
return resized.squeeze(0)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class LabUtopiaInputTransform:
|
| 69 |
+
"""
|
| 70 |
+
Transform LabUtopia observation dict into a LeRobot preprocessor-ready batch dict.
|
| 71 |
+
|
| 72 |
+
LabUtopia RemoteInferenceEngine sends:
|
| 73 |
+
- camera_1_rgb: (H, W, C) uint8 ndarray
|
| 74 |
+
- camera_2_rgb: (H, W, C) uint8 ndarray
|
| 75 |
+
- camera_3_rgb: (H, W, C) uint8 ndarray (arm camera, optional)
|
| 76 |
+
- state: (8,) float array (7 joints + 1 gripper)
|
| 77 |
+
- prompt / language_instruction: str
|
| 78 |
+
|
| 79 |
+
The LeRobot preprocessor pipeline expects a flat dict with keys like:
|
| 80 |
+
- observation.images.camera_1_rgb: (C, H, W) float tensor in [0, 255]
|
| 81 |
+
- observation.images.camera_2_rgb: (C, H, W) float tensor in [0, 255]
|
| 82 |
+
- observation.state: (state_dim,) float tensor
|
| 83 |
+
- task: str
|
| 84 |
+
|
| 85 |
+
The preprocessor's RenameObservationsProcessorStep will rename these keys to
|
| 86 |
+
match the model's feature names (e.g., camera_1_rgb -> image, camera_2_rgb -> image2).
|
| 87 |
+
Then AddBatchDimension, Tokenizer, ImageToFloat, ImageNetNormalize, Device, Normalizer
|
| 88 |
+
steps handle the rest.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
image_features: Dict[str, Tuple[int, ...]],
|
| 94 |
+
camera_to_obs_key: Dict[str, str],
|
| 95 |
+
state_dim: int = 8,
|
| 96 |
+
normalize_images: bool = True,
|
| 97 |
+
):
|
| 98 |
+
"""
|
| 99 |
+
Args:
|
| 100 |
+
image_features: dict mapping LeRobot feature names to (C, H, W) shapes.
|
| 101 |
+
e.g. {"observation.images.image": (3, 256, 256), ...}
|
| 102 |
+
camera_to_obs_key: dict mapping LabUtopia camera names to the ORIGINAL
|
| 103 |
+
observation key (before rename), e.g.
|
| 104 |
+
{"camera_1_rgb": "observation.images.camera_1_rgb", ...}
|
| 105 |
+
state_dim: dimension of the state vector.
|
| 106 |
+
normalize_images: if True, normalize images to [0, 1] (for most models);
|
| 107 |
+
if False, keep [0, 255] (for models like XVLA whose preprocessor
|
| 108 |
+
has its own image_to_float step that divides by 255).
|
| 109 |
+
"""
|
| 110 |
+
self.image_features = image_features
|
| 111 |
+
self.camera_to_obs_key = camera_to_obs_key
|
| 112 |
+
self.state_dim = state_dim
|
| 113 |
+
self.normalize_images = normalize_images
|
| 114 |
+
# Derive a single target (H, W) from image_features when every visual
|
| 115 |
+
# feature declares the same spatial size. If shapes are missing or
|
| 116 |
+
# inconsistent, leave _target_hw = None and skip resizing rather than
|
| 117 |
+
# guessing one ambiguously.
|
| 118 |
+
self._target_hw: Optional[Tuple[int, int]] = None
|
| 119 |
+
hw_set = set()
|
| 120 |
+
for shape in (image_features or {}).values():
|
| 121 |
+
if isinstance(shape, (tuple, list)) and len(shape) == 3:
|
| 122 |
+
hw_set.add((int(shape[1]), int(shape[2])))
|
| 123 |
+
if len(hw_set) == 1:
|
| 124 |
+
self._target_hw = next(iter(hw_set))
|
| 125 |
+
|
| 126 |
+
def __call__(self, obs: Dict[str, Any]) -> Dict[str, Any]:
|
| 127 |
+
"""
|
| 128 |
+
Convert a raw LabUtopia observation to a LeRobot preprocessor input batch.
|
| 129 |
+
|
| 130 |
+
Returns a dict with keys like "observation.images.camera_1_rgb",
|
| 131 |
+
"observation.state", "task" β ready to be fed into the preprocessor pipeline.
|
| 132 |
+
|
| 133 |
+
Images are resized to the target (H, W) from `image_features` (when
|
| 134 |
+
uniform) and the state vector is padded/truncated to `state_dim`. Both
|
| 135 |
+
are no-ops when the inputs already match the trained resolution / width.
|
| 136 |
+
"""
|
| 137 |
+
batch = {}
|
| 138 |
+
|
| 139 |
+
# ---- State (pad/truncate/validate to state_dim) ----
|
| 140 |
+
state = np.asarray(obs.get("state", np.zeros(self.state_dim)), dtype=np.float32)
|
| 141 |
+
state = np.atleast_1d(state).reshape(-1)
|
| 142 |
+
if state.shape[0] != self.state_dim:
|
| 143 |
+
logger.warning(
|
| 144 |
+
"LabUtopiaInputTransform: state dim %d != expected state_dim %d; "
|
| 145 |
+
"padding/truncating to match the trained contract.",
|
| 146 |
+
state.shape[0], self.state_dim,
|
| 147 |
+
)
|
| 148 |
+
fitted = np.zeros(self.state_dim, dtype=np.float32)
|
| 149 |
+
n = min(state.shape[0], self.state_dim)
|
| 150 |
+
fitted[:n] = state[:n]
|
| 151 |
+
state = fitted
|
| 152 |
+
batch["observation.state"] = torch.from_numpy(state).float()
|
| 153 |
+
|
| 154 |
+
# ---- Images (resize to image_features target H,W when known) ----
|
| 155 |
+
for lab_cam_name, obs_key in self.camera_to_obs_key.items():
|
| 156 |
+
if lab_cam_name in obs:
|
| 157 |
+
img_hwc = parse_image_to_uint8_hwc(obs[lab_cam_name])
|
| 158 |
+
# Convert to (C, H, W) float in [0, 255] range
|
| 159 |
+
img_tensor = image_hwc_uint8_to_chw_float32(img_hwc, normalize=self.normalize_images)
|
| 160 |
+
if self._target_hw is not None and tuple(img_tensor.shape[-2:]) != self._target_hw:
|
| 161 |
+
img_tensor = resize_image_tensor(
|
| 162 |
+
img_tensor, self._target_hw[0], self._target_hw[1]
|
| 163 |
+
)
|
| 164 |
+
batch[obs_key] = img_tensor
|
| 165 |
+
|
| 166 |
+
# ---- Language instruction / prompt ----
|
| 167 |
+
prompt = obs.get("prompt", obs.get("language_instruction", ""))
|
| 168 |
+
if isinstance(prompt, (np.ndarray, np.generic)):
|
| 169 |
+
prompt = str(prompt.item()) if hasattr(prompt, 'item') else str(prompt)
|
| 170 |
+
# Always write "task" to batch to avoid KeyError in TokenizerProcessorStep.
|
| 171 |
+
# If prompt is empty, use an empty string as placeholder.
|
| 172 |
+
batch["task"] = prompt if prompt else ""
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
return batch
|
| 177 |
+
|
| 178 |
+
|
labvla_schema.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_id": "labutopia_franka8",
|
| 3 |
+
"source": "manifest",
|
| 4 |
+
"source_path": "labvla_schema.json",
|
| 5 |
+
"robot_type": "franka",
|
| 6 |
+
"state_keys": ["observation.state"],
|
| 7 |
+
"action_keys": ["action"],
|
| 8 |
+
"state_dims": [8],
|
| 9 |
+
"action_dims": [8],
|
| 10 |
+
"delta_mask": [true, true, true, true, true, true, true, false],
|
| 11 |
+
"gripper_action_dims": [7],
|
| 12 |
+
"image_mapping": {
|
| 13 |
+
"camera_1_rgb": "observation.images.image0",
|
| 14 |
+
"camera_2_rgb": "observation.images.image1",
|
| 15 |
+
"camera_3_rgb": "observation.images.image2"
|
| 16 |
+
},
|
| 17 |
+
"arm_layout": {
|
| 18 |
+
"gripper_binarize_threshold": 0.5
|
| 19 |
+
}
|
| 20 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
torchvision
|
| 3 |
+
transformers>=4.57.0
|
| 4 |
+
accelerate
|
| 5 |
+
safetensors
|
| 6 |
+
sentencepiece
|
| 7 |
+
einops
|
| 8 |
+
numpy
|
| 9 |
+
pillow
|
| 10 |
+
matplotlib
|
| 11 |
+
liger_kernel
|
| 12 |
+
packaging
|
| 13 |
+
https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/flash_attn-2.8.3-cp312-cp312-linux_x86_64.whl
|
src/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""LabVLA library root. Subpackages are imported as src.<name> from the repo root."""
|
src/adapters/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dataset format adapters
|
| 2 |
+
from .registry import create_adapter # noqa: F401
|
| 3 |
+
from .base import BaseAdapter, DatasetMeta # noqa: F401
|
src/adapters/_scan_cache.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Disk-persistent scan-cache infrastructure shared by the v2.1 and v3.0
|
| 2 |
+
adapters.
|
| 3 |
+
|
| 4 |
+
``lerobot_v21`` re-exports the names defined here for any out-of-tree caller.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Optional
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
_SCAN_CACHE_FILE = ".labvla_scan_cache.json"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _shard_fingerprint(data_root: Optional[Path]) -> dict:
|
| 19 |
+
"""Summarize the data/ shard parquet files by count + total size + max mtime.
|
| 20 |
+
|
| 21 |
+
A cheap content fingerprint so the scan cache invalidates on in-place shard
|
| 22 |
+
repair/replacement that keeps the episode list unchanged (keying only on
|
| 23 |
+
episodes.jsonl mtime missed those). O(num_shards) ``stat()`` calls, no
|
| 24 |
+
parquet open. Returns zeros when ``data_root`` is absent (degrades to the
|
| 25 |
+
previous episode-list-only behavior).
|
| 26 |
+
"""
|
| 27 |
+
if data_root is None:
|
| 28 |
+
return {"shard_count": 0, "shard_total_size": 0, "shard_max_mtime": 0.0}
|
| 29 |
+
count = 0
|
| 30 |
+
total_size = 0
|
| 31 |
+
max_mtime = 0.0
|
| 32 |
+
if data_root.is_dir():
|
| 33 |
+
for p in data_root.rglob("*.parquet"):
|
| 34 |
+
try:
|
| 35 |
+
st = p.stat()
|
| 36 |
+
except OSError:
|
| 37 |
+
continue
|
| 38 |
+
count += 1
|
| 39 |
+
total_size += int(st.st_size)
|
| 40 |
+
if st.st_mtime > max_mtime:
|
| 41 |
+
max_mtime = st.st_mtime
|
| 42 |
+
return {
|
| 43 |
+
"shard_count": count,
|
| 44 |
+
"shard_total_size": total_size,
|
| 45 |
+
"shard_max_mtime": max_mtime,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _scan_cache_key(
|
| 50 |
+
meta_root: Path,
|
| 51 |
+
schema_id: str,
|
| 52 |
+
chunks_size: int,
|
| 53 |
+
data_root: Optional[Path] = None,
|
| 54 |
+
) -> dict:
|
| 55 |
+
"""Fingerprint used to invalidate the cached scan.
|
| 56 |
+
|
| 57 |
+
Invalidated when any of these change from the stored key:
|
| 58 |
+
- schema_id: a different schema filters different episodes
|
| 59 |
+
- chunks_size: repartitioning changes chunk_ok semantics
|
| 60 |
+
- episodes_jsonl_mtime: the canonical "episode list changed" signal
|
| 61 |
+
- shard_*: count/total-size/max-mtime of data/**/*.parquet, so the cache
|
| 62 |
+
also invalidates when shard CONTENTS change even though the episode list
|
| 63 |
+
is identical (v3 has no episodes.jsonl and relies entirely on this).
|
| 64 |
+
"""
|
| 65 |
+
ep_jsonl = meta_root / "episodes.jsonl"
|
| 66 |
+
from src.utils import env_flags as _env_flags
|
| 67 |
+
return {
|
| 68 |
+
"schema_id": str(schema_id),
|
| 69 |
+
"chunks_size": int(chunks_size),
|
| 70 |
+
# These env gates change which episodes/shards the integrity filter
|
| 71 |
+
# accepts; flipping them must invalidate the cache. Read via the
|
| 72 |
+
# env_flags registry (not raw os.environ) so an unset flag and an
|
| 73 |
+
# explicit "=0" resolve to the same default rather than colliding with
|
| 74 |
+
# opposite scan behavior.
|
| 75 |
+
"allow_truncate": _env_flags.get("LABVLA_ALLOW_TRUNCATE") == "1",
|
| 76 |
+
"v21_validate_per_file": str(_env_flags.get("LABVLA_V21_VALIDATE_PER_FILE")),
|
| 77 |
+
"episodes_jsonl_mtime": (
|
| 78 |
+
ep_jsonl.stat().st_mtime if ep_jsonl.exists() else 0.0
|
| 79 |
+
),
|
| 80 |
+
**_shard_fingerprint(data_root),
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _load_scan_cache(meta_root: Path, expected_key: dict) -> Optional[tuple[dict, set]]:
|
| 85 |
+
"""Return (chunk_ok_map, existing_episodes) if cache is valid, else None.
|
| 86 |
+
|
| 87 |
+
Cache file is `meta/.labvla_scan_cache.json`; hidden to avoid cluttering.
|
| 88 |
+
Bypass by setting env `LABVLA_SCAN_CACHE=0`.
|
| 89 |
+
"""
|
| 90 |
+
from src.utils import env_flags as _env_flags
|
| 91 |
+
if _env_flags.get("LABVLA_SCAN_CACHE") == "0":
|
| 92 |
+
return None
|
| 93 |
+
cache_path = meta_root / _SCAN_CACHE_FILE
|
| 94 |
+
if not cache_path.exists():
|
| 95 |
+
return None
|
| 96 |
+
try:
|
| 97 |
+
cached = json.loads(cache_path.read_text())
|
| 98 |
+
except Exception:
|
| 99 |
+
return None
|
| 100 |
+
# MA2: expected_key may contain list[tuple] (declared_dims); the cached key
|
| 101 |
+
# round-tripped through JSON is list[list]. Compare canonical JSON so tuples
|
| 102 |
+
# and lists match instead of always reporting a (false) cache miss.
|
| 103 |
+
if json.dumps(cached.get("key"), sort_keys=True) != json.dumps(expected_key, sort_keys=True):
|
| 104 |
+
return None
|
| 105 |
+
# json keys are strings β restore int dict
|
| 106 |
+
chunk_ok = {int(k): bool(v) for k, v in cached.get("chunk_ok", {}).items()}
|
| 107 |
+
existing = set(int(x) for x in cached.get("existing_episodes", []))
|
| 108 |
+
return chunk_ok, existing
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _save_scan_cache(
|
| 112 |
+
meta_root: Path,
|
| 113 |
+
key: dict,
|
| 114 |
+
chunk_ok: dict[int, bool],
|
| 115 |
+
existing_episodes: set[int],
|
| 116 |
+
) -> None:
|
| 117 |
+
"""Atomically write scan result. Failure is non-fatal (just log)."""
|
| 118 |
+
cache_path = meta_root / _SCAN_CACHE_FILE
|
| 119 |
+
tmp_path = cache_path.with_suffix(cache_path.suffix + ".tmp")
|
| 120 |
+
payload = {
|
| 121 |
+
"key": key,
|
| 122 |
+
"chunk_ok": {str(k): bool(v) for k, v in chunk_ok.items()},
|
| 123 |
+
"existing_episodes": sorted(int(x) for x in existing_episodes),
|
| 124 |
+
}
|
| 125 |
+
try:
|
| 126 |
+
tmp_path.write_text(json.dumps(payload))
|
| 127 |
+
import os
|
| 128 |
+
os.replace(tmp_path, cache_path)
|
| 129 |
+
except Exception as e:
|
| 130 |
+
logger.warning("[scan-cache] failed to write scan cache at %s: %s", cache_path, e)
|
src/adapters/base.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Base adapter interface.
|
| 3 |
+
|
| 4 |
+
All dataset adapters must provide:
|
| 5 |
+
- meta: DatasetMeta (robot_type, stats, fps, features, ...)
|
| 6 |
+
- __getitem__(idx) β dict with raw column-name keys
|
| 7 |
+
- __len__() β total frames
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from dataclasses import dataclass, field
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any, Optional, TYPE_CHECKING
|
| 13 |
+
|
| 14 |
+
import torch.utils.data
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from src.schema import DatasetSchema
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class DatasetMeta:
|
| 22 |
+
"""Minimal metadata interface that the Transform chain needs."""
|
| 23 |
+
robot_type: str
|
| 24 |
+
stats: dict[str, dict] | None # per-key normalization stats
|
| 25 |
+
fps: int
|
| 26 |
+
total_episodes: int
|
| 27 |
+
total_frames: int
|
| 28 |
+
features: dict[str, Any]
|
| 29 |
+
video_keys: list[str] = field(default_factory=list)
|
| 30 |
+
camera_keys: list[str] = field(default_factory=list)
|
| 31 |
+
# Optional only for the brief pre-discovery window inside adapter __init__;
|
| 32 |
+
# once the adapter returns, schema MUST be non-None. Use require_schema().
|
| 33 |
+
schema: Optional["DatasetSchema"] = None
|
| 34 |
+
# MultiLeRobotDataset expects `meta.episodes["dataset_from_index"/"to_index"]`
|
| 35 |
+
# to build combined frame indices across multi-repo concatenation.
|
| 36 |
+
episodes: dict = field(default_factory=lambda: {
|
| 37 |
+
"dataset_from_index": [],
|
| 38 |
+
"dataset_to_index": [],
|
| 39 |
+
})
|
| 40 |
+
|
| 41 |
+
def require_schema(self) -> "DatasetSchema":
|
| 42 |
+
"""Return ``self.schema`` or raise if it is still ``None``.
|
| 43 |
+
|
| 44 |
+
Code paths after adapter construction should use this accessor rather
|
| 45 |
+
than carrying a ``None`` schema forward: a missing schema means
|
| 46 |
+
hydrate_all has no state/action keys, no delta mask, and no image
|
| 47 |
+
mapping β silently training on raw features with zero normalization.
|
| 48 |
+
"""
|
| 49 |
+
if self.schema is None:
|
| 50 |
+
from src.schema.errors import SchemaDiscoveryError
|
| 51 |
+
|
| 52 |
+
raise SchemaDiscoveryError(
|
| 53 |
+
"DatasetMeta.schema is None after adapter construction. "
|
| 54 |
+
"Every adapter __init__ must populate meta.schema via "
|
| 55 |
+
"schema.discover_schema(root, robot_type=...). If this meta "
|
| 56 |
+
"was constructed manually (tests, ablations), attach a "
|
| 57 |
+
"DatasetSchema before handing it to the transform/dataset "
|
| 58 |
+
"pipeline."
|
| 59 |
+
)
|
| 60 |
+
return self.schema
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class BaseAdapter(torch.utils.data.Dataset):
|
| 64 |
+
"""Abstract base for all dataset format adapters."""
|
| 65 |
+
|
| 66 |
+
meta: DatasetMeta
|
| 67 |
+
repo_id: str
|
| 68 |
+
root: Path
|
| 69 |
+
|
| 70 |
+
def __getitem__(self, idx: int) -> dict:
|
| 71 |
+
raise NotImplementedError
|
| 72 |
+
|
| 73 |
+
def __len__(self) -> int:
|
| 74 |
+
return self.meta.total_frames
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def num_episodes(self) -> int:
|
| 78 |
+
return self.meta.total_episodes
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def num_frames(self) -> int:
|
| 82 |
+
return self.meta.total_frames
|
src/adapters/lerobot_base.py
ADDED
|
@@ -0,0 +1,1101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared base class for LeRobot v21 / v30 adapters.
|
| 2 |
+
|
| 3 |
+
Factors common per-frame transformation logic into ``LeRobotAdapterBase``.
|
| 4 |
+
Subclasses plug in two format-specific methods:
|
| 5 |
+
|
| 6 |
+
* ``_load_ep_parquet(ep_idx) -> pd.DataFrame``
|
| 7 |
+
Return a flat, per-episode DataFrame. v21 reads one parquet per
|
| 8 |
+
episode; v30 slices a shard using the episodes meta.
|
| 9 |
+
* ``_read_video_frame(ep_idx, vkey, frame) -> torch.Tensor``
|
| 10 |
+
Return one RGB frame as a ``(3, H, W) float32`` tensor in [0, 1].
|
| 11 |
+
|
| 12 |
+
Kept separate from ``base.py`` (a minimal abstract boundary) so other
|
| 13 |
+
adapter families (e.g. raw HDF5) can speak the same ``BaseAdapter``
|
| 14 |
+
interface without inheriting LeRobot plumbing.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import io
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
import threading
|
| 22 |
+
from abc import abstractmethod
|
| 23 |
+
from collections import OrderedDict
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Optional
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import pandas as pd
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
from .base import BaseAdapter
|
| 32 |
+
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _ep_starts_lens(episodes: list[dict]) -> tuple[np.ndarray, np.ndarray]:
|
| 37 |
+
"""Parallel arrays: ep_starts[i] = global frame idx of ep i frame 0;
|
| 38 |
+
ep_lens[i] = length of ep i. Used for O(log N) globalβ(ep, local) lookup.
|
| 39 |
+
|
| 40 |
+
Shared indexing math used by both format adapters.
|
| 41 |
+
"""
|
| 42 |
+
lens = np.array([int(e["length"]) for e in episodes], dtype=np.int64)
|
| 43 |
+
starts = np.concatenate([[0], np.cumsum(lens)[:-1]])
|
| 44 |
+
return starts, lens
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _is_missing_scalar_value(value) -> bool:
|
| 48 |
+
"""True if ``value`` is a pandas/NumPy missing scalar (NaN/NaT/None).
|
| 49 |
+
|
| 50 |
+
Used by task resolution to distinguish a real instruction string from a
|
| 51 |
+
NaN-filled cell (heterogeneous v3 shards leave absent columns as NaN).
|
| 52 |
+
Guarded so array-like inputs (which would make ``pd.isna`` return an
|
| 53 |
+
array) never raise here.
|
| 54 |
+
"""
|
| 55 |
+
try:
|
| 56 |
+
result = pd.isna(value)
|
| 57 |
+
except (TypeError, ValueError):
|
| 58 |
+
return False
|
| 59 |
+
return bool(result) if isinstance(result, (bool, np.bool_)) else False
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# Process-wide PyAV container cache shared across ALL LeRobot adapters (v2.1
|
| 63 |
+
# and v3.0). Per-adapter caches summed to 60+ adapters Γ 64 slots = 3840
|
| 64 |
+
# decoders/worker in the 4ds mixture and OOM'd the host; one process-wide LRU
|
| 65 |
+
# (cap=LABVLA_VIDEO_CACHE_MAX, default 128) self-tunes via LRU eviction, with
|
| 66 |
+
# keys namespaced by ``id(adapter)`` so adapters cannot collide. Also fixes the
|
| 67 |
+
# v21 O(av.open per frame) bottleneck: consecutive frames in one chunk reuse a
|
| 68 |
+
# single cached container. Each DataLoader worker fork gets its own empty cache.
|
| 69 |
+
|
| 70 |
+
from src.utils import env_flags as _env_flags # registered LABVLA_* flags
|
| 71 |
+
|
| 72 |
+
_VIDEO_CONTAINER_CACHE_MAX = int(_env_flags.get("LABVLA_VIDEO_CACHE_MAX"))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class _SharedVideoContainerCache:
|
| 76 |
+
"""Process-wide LRU of opened ``av.Container`` instances.
|
| 77 |
+
|
| 78 |
+
Shared by both ``LeRobotV21Adapter`` and ``LeRobotV30Adapter``. Replaces
|
| 79 |
+
per-adapter ``OrderedDict[(vkey,...) -> (container, stream)]`` with a
|
| 80 |
+
single shared ``OrderedDict[(adapter_id, *cache_key) -> ...]`` LRU.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(self, max_size: int):
|
| 84 |
+
self._cache: "OrderedDict[tuple, tuple]" = OrderedDict()
|
| 85 |
+
self._max = max(1, int(max_size))
|
| 86 |
+
# Precautionary: DataLoader workers run __getitem__ single-threaded.
|
| 87 |
+
self._lock = threading.Lock()
|
| 88 |
+
|
| 89 |
+
def get(self, key: tuple):
|
| 90 |
+
with self._lock:
|
| 91 |
+
entry = self._cache.get(key)
|
| 92 |
+
if entry is not None:
|
| 93 |
+
self._cache.move_to_end(key)
|
| 94 |
+
return entry
|
| 95 |
+
|
| 96 |
+
def put(self, key: tuple, value: tuple) -> None:
|
| 97 |
+
"""Insert; evict LRU and close its container if over cap."""
|
| 98 |
+
to_close = []
|
| 99 |
+
with self._lock:
|
| 100 |
+
self._cache[key] = value
|
| 101 |
+
while len(self._cache) > self._max:
|
| 102 |
+
_evicted_key, evicted = self._cache.popitem(last=False)
|
| 103 |
+
_old_container = evicted[0] if evicted else None
|
| 104 |
+
if _old_container is not None:
|
| 105 |
+
to_close.append(_old_container)
|
| 106 |
+
for container in to_close:
|
| 107 |
+
try:
|
| 108 |
+
container.close()
|
| 109 |
+
except Exception:
|
| 110 |
+
pass
|
| 111 |
+
|
| 112 |
+
def pop(self, key: tuple):
|
| 113 |
+
with self._lock:
|
| 114 |
+
return self._cache.pop(key, None)
|
| 115 |
+
|
| 116 |
+
def drop_owner(self, owner_id: int) -> None:
|
| 117 |
+
"""Close all entries owned by ``owner_id`` (called from adapter teardown)."""
|
| 118 |
+
to_close = []
|
| 119 |
+
with self._lock:
|
| 120 |
+
stale_keys = [k for k in self._cache.keys() if k and k[0] == owner_id]
|
| 121 |
+
for k in stale_keys:
|
| 122 |
+
entry = self._cache.pop(k, None)
|
| 123 |
+
if entry is not None:
|
| 124 |
+
to_close.append(entry[0])
|
| 125 |
+
for container in to_close:
|
| 126 |
+
try:
|
| 127 |
+
container.close()
|
| 128 |
+
except Exception:
|
| 129 |
+
pass
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# Lazy module-level singleton (one per worker process via fork).
|
| 133 |
+
_SHARED_VIDEO_CACHE: "_SharedVideoContainerCache | None" = None
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _get_shared_video_cache() -> _SharedVideoContainerCache:
|
| 137 |
+
global _SHARED_VIDEO_CACHE
|
| 138 |
+
if _SHARED_VIDEO_CACHE is None:
|
| 139 |
+
_SHARED_VIDEO_CACHE = _SharedVideoContainerCache(_VIDEO_CONTAINER_CACHE_MAX)
|
| 140 |
+
return _SHARED_VIDEO_CACHE
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
_PAD_NARROW_WARNED: set = set()
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class LeRobotAdapterBase(BaseAdapter):
|
| 147 |
+
"""Shared transformation pipeline for LeRobot v21 / v30 adapters.
|
| 148 |
+
|
| 149 |
+
Concrete subclasses own ``__init__`` (version-specific meta parsing)
|
| 150 |
+
and override the two abstract I/O hooks below. Everything else β row
|
| 151 |
+
β tensor conversion, schema-driven padding, task resolution,
|
| 152 |
+
delta_timestamp expansion, video-frame dispatch, and the CRIT-05
|
| 153 |
+
``_is_pad`` postcondition β is provided here.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
# Canonical column-name aliases. v2.1 ships two pluralizations of the
|
| 157 |
+
# state/action columns; normalize to the canonical (v3.0) names so
|
| 158 |
+
# downstream transforms see a consistent key set. {canonical: raw_alias};
|
| 159 |
+
# when canonical is missing AND alias is present, alias is copied under
|
| 160 |
+
# canonical. A class constant so subclasses can override/extend.
|
| 161 |
+
CANONICAL_ALT_KEYS: dict[str, str] = {
|
| 162 |
+
"observation.state": "state",
|
| 163 |
+
"action": "actions",
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
# Virtual action columns derived from the following frame's observation.
|
| 167 |
+
#
|
| 168 |
+
# robointer_droid stores the gripper command as
|
| 169 |
+
# `other_information.action_gripper_velocity`, but training should predict
|
| 170 |
+
# the next absolute gripper pose. Rather than rewriting 130k+ parquet files,
|
| 171 |
+
# expose a schema-visible synthetic key whose value at frame t is read from
|
| 172 |
+
# the source observation at frame t+1. Samples that would need T+1 are
|
| 173 |
+
# marked padded and contribute no action loss.
|
| 174 |
+
NEXT_FRAME_ACTION_SOURCES: dict[str, str] = {
|
| 175 |
+
"other_information.action_gripper_position":
|
| 176 |
+
"other_information.observation_gripper_position",
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
# PNG-in-parquet support. Subclasses populate from info.json features whose
|
| 180 |
+
# ``dtype == "image"`` (PNG bytes in a parquet struct column, e.g.
|
| 181 |
+
# LabUtopia/Level3_open). Empty default: mp4-only datasets fall through to
|
| 182 |
+
# ``_read_video_frame``. When populated, these columns are projected at read
|
| 183 |
+
# time and decoded inline by ``_decode_image_cell`` per row.
|
| 184 |
+
_image_keys: tuple[str, ...] = ()
|
| 185 |
+
|
| 186 |
+
@staticmethod
|
| 187 |
+
def _decode_image_cell(val) -> torch.Tensor:
|
| 188 |
+
"""Decode a parquet image cell to ``(C, H, W) float32`` in ``[0, 1]``.
|
| 189 |
+
|
| 190 |
+
HuggingFace ``datasets`` Image feature stores cells as a struct
|
| 191 |
+
``{"bytes": <encoded image bytes>, "path": <str|None>}``; the bytes
|
| 192 |
+
are typically PNG (LabUtopia/Level3_open) but JPG also decodes via
|
| 193 |
+
Pillow. This helper handles those two shapes plus a few defensive
|
| 194 |
+
fallbacks (raw bytes, np.ndarray HWC uint8, pre-decoded torch.Tensor).
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
val: a parquet image cell from the per-frame DataFrame row.
|
| 198 |
+
|
| 199 |
+
Returns:
|
| 200 |
+
``torch.Tensor`` of shape ``(C, H, W)``, dtype ``float32``,
|
| 201 |
+
range ``[0, 1]``. Always a freshly-allocated tensor β callers
|
| 202 |
+
may mutate without affecting the cache.
|
| 203 |
+
"""
|
| 204 |
+
from PIL import Image # local import: PIL is heavy & only needed here
|
| 205 |
+
|
| 206 |
+
if isinstance(val, dict): # HF Image feature: {"bytes": ..., "path": ...}
|
| 207 |
+
b = val.get("bytes")
|
| 208 |
+
if b is None:
|
| 209 |
+
raise ValueError(
|
| 210 |
+
"image cell dict missing 'bytes' key (HF Image feature "
|
| 211 |
+
"with only 'path' is unsupported β adapter cannot read "
|
| 212 |
+
"external files mid-batch)"
|
| 213 |
+
)
|
| 214 |
+
elif isinstance(val, (bytes, bytearray)):
|
| 215 |
+
b = bytes(val)
|
| 216 |
+
elif isinstance(val, np.ndarray):
|
| 217 |
+
arr = val
|
| 218 |
+
if arr.ndim == 3 and arr.shape[-1] == 3: # HWC uint8 / float
|
| 219 |
+
arr = arr.transpose(2, 0, 1)
|
| 220 |
+
t = torch.from_numpy(np.ascontiguousarray(arr).copy())
|
| 221 |
+
return t.float() / 255.0 if t.dtype == torch.uint8 else t.float()
|
| 222 |
+
elif isinstance(val, torch.Tensor):
|
| 223 |
+
return val.float() / 255.0 if val.dtype == torch.uint8 else val.float()
|
| 224 |
+
else:
|
| 225 |
+
raise TypeError(f"unsupported image cell type: {type(val)!r}")
|
| 226 |
+
|
| 227 |
+
img = Image.open(io.BytesIO(b)).convert("RGB")
|
| 228 |
+
arr = np.asarray(img) # H, W, 3 uint8
|
| 229 |
+
# `.copy()` β writable buffer, avoids the read-only-buffer UserWarning.
|
| 230 |
+
return (
|
| 231 |
+
torch.from_numpy(arr.copy()).permute(2, 0, 1).contiguous().float()
|
| 232 |
+
/ 255.0
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
# ---- format-specific hooks (must be overridden) -----------------------
|
| 236 |
+
|
| 237 |
+
@abstractmethod
|
| 238 |
+
def _load_ep_parquet(self, ep_idx: int) -> pd.DataFrame:
|
| 239 |
+
"""Return a flat DataFrame holding every frame of episode ``ep_idx``."""
|
| 240 |
+
raise NotImplementedError
|
| 241 |
+
|
| 242 |
+
@abstractmethod
|
| 243 |
+
def _read_video_frame(
|
| 244 |
+
self, ep_idx: int, vkey: str, frame: int
|
| 245 |
+
) -> torch.Tensor:
|
| 246 |
+
"""Return the ``(3, H, W) float32`` RGB frame at ``frame`` index."""
|
| 247 |
+
raise NotImplementedError
|
| 248 |
+
|
| 249 |
+
# ---- flat-idx helpers (subclass must set _ep_starts/_episodes/meta) ----
|
| 250 |
+
|
| 251 |
+
def __len__(self) -> int:
|
| 252 |
+
return int(self._ep_lens.sum())
|
| 253 |
+
|
| 254 |
+
def _validate_delta_timestamps_frame_aligned(self) -> None:
|
| 255 |
+
"""Enforce that every delta-timestamp offset is an integer multiple of
|
| 256 |
+
1/fps (1e-4s tolerance). Arbitrary float offsets would be silently
|
| 257 |
+
snapped to the nearest frame at read time, changing the temporal
|
| 258 |
+
sampling semantics."""
|
| 259 |
+
dts = getattr(self, "delta_timestamps", None) or {}
|
| 260 |
+
fps = float(getattr(self.meta, "fps", 0) or 0)
|
| 261 |
+
if not dts or fps <= 0:
|
| 262 |
+
return
|
| 263 |
+
bad = []
|
| 264 |
+
for key, offsets in dts.items():
|
| 265 |
+
for dt in offsets:
|
| 266 |
+
frames = float(dt) * fps
|
| 267 |
+
if abs(frames - round(frames)) > 1e-4 * fps:
|
| 268 |
+
bad.append((key, float(dt)))
|
| 269 |
+
if bad:
|
| 270 |
+
raise ValueError(
|
| 271 |
+
f"delta_timestamps contain non-frame-aligned offsets for "
|
| 272 |
+
f"fps={fps}: {bad[:6]} β each offset must be an integer "
|
| 273 |
+
f"multiple of 1/fps={1.0 / fps:.6f}s (M15: silent rounding "
|
| 274 |
+
f"changes the temporal sampling semantics)."
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
def _validate_delta_timestamps_vs_episode_lens(self) -> None:
|
| 278 |
+
"""Warn once per repo if the longest ``delta_timestamps`` offset clips
|
| 279 |
+
past the tail of many episodes.
|
| 280 |
+
|
| 281 |
+
``__getitem__`` clips ``idxs`` to ``[0, T-1]`` and records ``_is_pad``,
|
| 282 |
+
so training does not crash. But when ``max(deltas) * fps`` is a large
|
| 283 |
+
fraction of the SHORTEST episode, every sample from those episodes is
|
| 284 |
+
mostly-padded β MSE effectively trains on the last frame repeated K
|
| 285 |
+
times. Surface this at init. Warn (not hard-fail) above an 80%
|
| 286 |
+
worst-case clipped-frame ratio; clip semantics are preserved.
|
| 287 |
+
"""
|
| 288 |
+
if not self.delta_timestamps or not len(self._ep_lens):
|
| 289 |
+
return
|
| 290 |
+
try:
|
| 291 |
+
max_delta = max(
|
| 292 |
+
(max(v) for v in self.delta_timestamps.values() if len(v) > 0),
|
| 293 |
+
default=0.0,
|
| 294 |
+
)
|
| 295 |
+
except (TypeError, ValueError):
|
| 296 |
+
return
|
| 297 |
+
if max_delta <= 0:
|
| 298 |
+
return
|
| 299 |
+
|
| 300 |
+
fps = float(getattr(self.meta, "fps", 0.0) or 0.0)
|
| 301 |
+
if fps <= 0:
|
| 302 |
+
return
|
| 303 |
+
|
| 304 |
+
max_offset_frames = int(round(max_delta * fps))
|
| 305 |
+
min_ep_len = int(self._ep_lens.min())
|
| 306 |
+
if min_ep_len <= 0:
|
| 307 |
+
return
|
| 308 |
+
|
| 309 |
+
if max_offset_frames > int(0.80 * min_ep_len):
|
| 310 |
+
from src.utils.logging_utils import warn_once
|
| 311 |
+
|
| 312 |
+
repo_id = getattr(self, "repo_id", "<unknown>")
|
| 313 |
+
warn_once(
|
| 314 |
+
logger,
|
| 315 |
+
("delta_ts_exceeds_ep_len", repo_id, max_offset_frames, min_ep_len),
|
| 316 |
+
"[adapter] %s: delta_timestamps max offset (%d frames @ fps=%.1f) "
|
| 317 |
+
"exceeds 80%% of shortest episode length (%d frames). Samples "
|
| 318 |
+
"drawn from short episodes will be heavily padded β training "
|
| 319 |
+
"MSE may silently degrade. Consider shortening action_horizon "
|
| 320 |
+
"or filtering episodes with min_len > max_offset.",
|
| 321 |
+
repo_id, max_offset_frames, fps, min_ep_len,
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
def _flat_to_ep(self, flat_idx: int) -> tuple[int, int]:
|
| 325 |
+
if flat_idx < 0 or flat_idx >= self.meta.total_frames:
|
| 326 |
+
raise IndexError(
|
| 327 |
+
f"flat_idx {flat_idx} out of [0, {self.meta.total_frames})"
|
| 328 |
+
)
|
| 329 |
+
ep_i = int(np.searchsorted(self._ep_starts, flat_idx, side="right") - 1)
|
| 330 |
+
ep_idx = int(self._episodes[ep_i]["episode_index"])
|
| 331 |
+
return ep_idx, int(flat_idx - self._ep_starts[ep_i])
|
| 332 |
+
|
| 333 |
+
# ---- next-frame virtual action helpers --------------------------------
|
| 334 |
+
|
| 335 |
+
@classmethod
|
| 336 |
+
def _next_frame_action_source(cls, key: str) -> Optional[str]:
|
| 337 |
+
return cls.NEXT_FRAME_ACTION_SOURCES.get(str(key))
|
| 338 |
+
|
| 339 |
+
@classmethod
|
| 340 |
+
def _required_parquet_key(cls, key: str) -> str:
|
| 341 |
+
"""Map a schema key to the physical parquet column it requires."""
|
| 342 |
+
return cls._next_frame_action_source(key) or str(key)
|
| 343 |
+
|
| 344 |
+
# ---- virtual state column helpers --------------------------------------
|
| 345 |
+
|
| 346 |
+
@staticmethod
|
| 347 |
+
def _virtual_state_source(schema, key: str) -> Optional[str]:
|
| 348 |
+
"""Physical source column for a schema-declared virtual state key.
|
| 349 |
+
|
| 350 |
+
Returns None when ``key`` is not virtual (or no schema). Virtual keys
|
| 351 |
+
carry the mandatory ``"virtual."`` prefix and are declared in
|
| 352 |
+
``schema.virtual_state_sources`` β see DatasetSchema for the contract.
|
| 353 |
+
"""
|
| 354 |
+
if schema is None:
|
| 355 |
+
return None
|
| 356 |
+
vss = getattr(schema, "virtual_state_sources", None) or {}
|
| 357 |
+
return vss.get(str(key))
|
| 358 |
+
|
| 359 |
+
@classmethod
|
| 360 |
+
def _resolve_physical_column(cls, schema, key: str) -> str:
|
| 361 |
+
"""Schema key β the physical parquet column that backs it.
|
| 362 |
+
|
| 363 |
+
Resolution order: virtual-state mapping, then next-frame action
|
| 364 |
+
mapping (NEXT_FRAME_ACTION_SOURCES), else identity. Column
|
| 365 |
+
existence filters and read projections must use THIS (not
|
| 366 |
+
``_required_parquet_key``) so shards are never dropped for "missing"
|
| 367 |
+
a column that only exists virtually.
|
| 368 |
+
"""
|
| 369 |
+
return (
|
| 370 |
+
cls._virtual_state_source(schema, key)
|
| 371 |
+
or cls._required_parquet_key(key)
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
@classmethod
|
| 375 |
+
def _schema_uses_next_frame_actions(cls, schema) -> bool:
|
| 376 |
+
if schema is None:
|
| 377 |
+
return False
|
| 378 |
+
return any(
|
| 379 |
+
cls._next_frame_action_source(k) is not None
|
| 380 |
+
for k in getattr(schema, "action_keys", ())
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
@staticmethod
|
| 384 |
+
def _field_offset(key: str, keys, dims) -> tuple[int, int] | None:
|
| 385 |
+
offset = 0
|
| 386 |
+
for k, d in zip(keys, dims):
|
| 387 |
+
d = int(d)
|
| 388 |
+
if str(k) == str(key):
|
| 389 |
+
return offset, d
|
| 390 |
+
offset += d
|
| 391 |
+
return None
|
| 392 |
+
|
| 393 |
+
@staticmethod
|
| 394 |
+
def _has_sized_stats(value) -> bool:
|
| 395 |
+
if value is None or isinstance(value, (str, bytes)):
|
| 396 |
+
return False
|
| 397 |
+
try:
|
| 398 |
+
len(value)
|
| 399 |
+
except TypeError:
|
| 400 |
+
return False
|
| 401 |
+
return True
|
| 402 |
+
|
| 403 |
+
@classmethod
|
| 404 |
+
def patch_stats_for_next_frame_actions(cls, stats: dict, schema) -> dict:
|
| 405 |
+
"""Patch canonical action stats for synthetic next-frame action keys.
|
| 406 |
+
|
| 407 |
+
`data_process stats` was computed from the physical parquet columns.
|
| 408 |
+
For robointer_droid that means canonical `stats["action"][7]` still
|
| 409 |
+
describes the old velocity command. Once the schema action key becomes
|
| 410 |
+
`other_information.action_gripper_position`, normalization must use the
|
| 411 |
+
source observation-position distribution instead. We copy the matching
|
| 412 |
+
slice from `stats["observation.state"]` into both `action` and
|
| 413 |
+
`action_abs`; arm stats are left unchanged.
|
| 414 |
+
"""
|
| 415 |
+
if not stats or schema is None:
|
| 416 |
+
return stats
|
| 417 |
+
|
| 418 |
+
action_keys = tuple(getattr(schema, "action_keys", ()) or ())
|
| 419 |
+
state_keys = tuple(getattr(schema, "state_keys", ()) or ())
|
| 420 |
+
action_dims = tuple(getattr(schema, "action_dims", ()) or ())
|
| 421 |
+
state_dims = tuple(getattr(schema, "state_dims", ()) or ())
|
| 422 |
+
|
| 423 |
+
patched = dict(stats)
|
| 424 |
+
for action_key in action_keys:
|
| 425 |
+
source_key = cls._next_frame_action_source(action_key)
|
| 426 |
+
if source_key is None:
|
| 427 |
+
continue
|
| 428 |
+
|
| 429 |
+
action_loc = cls._field_offset(action_key, action_keys, action_dims)
|
| 430 |
+
source_loc = cls._field_offset(source_key, state_keys, state_dims)
|
| 431 |
+
if action_loc is None or source_loc is None:
|
| 432 |
+
logger.warning(
|
| 433 |
+
"[adapter] cannot patch stats for derived action %r from %r: "
|
| 434 |
+
"schema offsets not found",
|
| 435 |
+
action_key, source_key,
|
| 436 |
+
)
|
| 437 |
+
continue
|
| 438 |
+
action_offset, action_dim = action_loc
|
| 439 |
+
source_offset, source_dim = source_loc
|
| 440 |
+
if action_dim != source_dim:
|
| 441 |
+
logger.warning(
|
| 442 |
+
"[adapter] cannot patch stats for derived action %r from %r: "
|
| 443 |
+
"dim mismatch action_dim=%d source_dim=%d",
|
| 444 |
+
action_key, source_key, action_dim, source_dim,
|
| 445 |
+
)
|
| 446 |
+
continue
|
| 447 |
+
|
| 448 |
+
state_stats = patched.get("observation.state")
|
| 449 |
+
if not isinstance(state_stats, dict):
|
| 450 |
+
logger.warning(
|
| 451 |
+
"[adapter] cannot patch stats for derived action %r: "
|
| 452 |
+
"stats['observation.state'] missing",
|
| 453 |
+
action_key,
|
| 454 |
+
)
|
| 455 |
+
continue
|
| 456 |
+
|
| 457 |
+
for action_stats_key in ("action", "action_abs"):
|
| 458 |
+
action_stats = patched.get(action_stats_key)
|
| 459 |
+
if not isinstance(action_stats, dict):
|
| 460 |
+
continue
|
| 461 |
+
action_stats = dict(action_stats)
|
| 462 |
+
for stat_name, action_value in list(action_stats.items()):
|
| 463 |
+
if stat_name == "count" or not cls._has_sized_stats(action_value):
|
| 464 |
+
continue
|
| 465 |
+
source_value = state_stats.get(stat_name)
|
| 466 |
+
if not cls._has_sized_stats(source_value):
|
| 467 |
+
continue
|
| 468 |
+
if (
|
| 469 |
+
len(action_value) < action_offset + action_dim
|
| 470 |
+
or len(source_value) < source_offset + source_dim
|
| 471 |
+
):
|
| 472 |
+
logger.warning(
|
| 473 |
+
"[adapter] cannot patch stats[%r][%r] for derived "
|
| 474 |
+
"action %r: action_len=%d source_len=%d",
|
| 475 |
+
action_stats_key, stat_name, action_key,
|
| 476 |
+
len(action_value), len(source_value),
|
| 477 |
+
)
|
| 478 |
+
continue
|
| 479 |
+
arr = np.asarray(action_value).copy()
|
| 480 |
+
src = np.asarray(source_value)[
|
| 481 |
+
source_offset:source_offset + source_dim
|
| 482 |
+
]
|
| 483 |
+
arr[action_offset:action_offset + action_dim] = src
|
| 484 |
+
action_stats[stat_name] = arr
|
| 485 |
+
patched[action_stats_key] = action_stats
|
| 486 |
+
|
| 487 |
+
return patched
|
| 488 |
+
|
| 489 |
+
def _drop_terminal_samples_for_next_frame_actions(self, schema) -> None:
|
| 490 |
+
"""Exclude each episode's terminal frame when next-frame labels exist.
|
| 491 |
+
|
| 492 |
+
The terminal frame has no t+1 observation, so it cannot produce a valid
|
| 493 |
+
next-frame gripper action. We keep the physical episode parquet intact
|
| 494 |
+
(so frame T-2 can still read T-1 as its label) but shrink the sampling
|
| 495 |
+
index by one frame per episode. Very short episodes are dropped.
|
| 496 |
+
"""
|
| 497 |
+
if not self._schema_uses_next_frame_actions(schema):
|
| 498 |
+
return
|
| 499 |
+
|
| 500 |
+
before_eps = len(self._episodes)
|
| 501 |
+
before_frames = int(self._ep_lens.sum()) if len(self._ep_lens) else 0
|
| 502 |
+
kept: list[dict] = []
|
| 503 |
+
for ep in self._episodes:
|
| 504 |
+
length = int(ep.get("length", 0))
|
| 505 |
+
if length <= 1:
|
| 506 |
+
continue
|
| 507 |
+
ep_view = dict(ep)
|
| 508 |
+
ep_view["length"] = length - 1
|
| 509 |
+
kept.append(ep_view)
|
| 510 |
+
|
| 511 |
+
self._episodes = kept
|
| 512 |
+
self._ep_lens = np.array(
|
| 513 |
+
[int(e["length"]) for e in self._episodes], dtype=np.int64
|
| 514 |
+
)
|
| 515 |
+
self._ep_starts = (
|
| 516 |
+
np.concatenate([[0], np.cumsum(self._ep_lens)[:-1]])
|
| 517 |
+
if len(self._ep_lens)
|
| 518 |
+
else np.array([], dtype=np.int64)
|
| 519 |
+
)
|
| 520 |
+
after_frames = int(self._ep_lens.sum()) if len(self._ep_lens) else 0
|
| 521 |
+
logger.info(
|
| 522 |
+
"[adapter] next-frame action schema=%s: dropped terminal samples "
|
| 523 |
+
"for %d episodes (%d -> %d trainable frames; dropped episodes=%d)",
|
| 524 |
+
getattr(schema, "schema_id", None),
|
| 525 |
+
len(self._episodes),
|
| 526 |
+
before_frames,
|
| 527 |
+
after_frames,
|
| 528 |
+
before_eps - len(self._episodes),
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
def _resolve_df_key(self, key: str, df: pd.DataFrame) -> Optional[str]:
|
| 532 |
+
if key in df.columns:
|
| 533 |
+
return key
|
| 534 |
+
if key == "action" and "actions" in df.columns:
|
| 535 |
+
return "actions"
|
| 536 |
+
if key == "observation.state" and "state" in df.columns:
|
| 537 |
+
return "state"
|
| 538 |
+
return None
|
| 539 |
+
|
| 540 |
+
def _materialize_next_frame_actions(
|
| 541 |
+
self,
|
| 542 |
+
out: dict,
|
| 543 |
+
df: pd.DataFrame,
|
| 544 |
+
frame_in_ep: int,
|
| 545 |
+
) -> None:
|
| 546 |
+
sch = self.meta.schema
|
| 547 |
+
if sch is None:
|
| 548 |
+
return
|
| 549 |
+
T = len(df)
|
| 550 |
+
for action_key in getattr(sch, "action_keys", ()):
|
| 551 |
+
source_key = self._next_frame_action_source(action_key)
|
| 552 |
+
if source_key is None:
|
| 553 |
+
continue
|
| 554 |
+
src_key = self._resolve_df_key(source_key, df)
|
| 555 |
+
target = self._schema_key_target_dim(action_key)
|
| 556 |
+
valid = src_key is not None and frame_in_ep + 1 < T
|
| 557 |
+
if valid:
|
| 558 |
+
arr = np.atleast_1d(
|
| 559 |
+
np.asarray(df[src_key].iloc[frame_in_ep + 1], dtype=np.float32)
|
| 560 |
+
)
|
| 561 |
+
else:
|
| 562 |
+
arr = np.zeros((target or 1,), dtype=np.float32)
|
| 563 |
+
if target is not None:
|
| 564 |
+
arr = self._pad_row(arr, target)
|
| 565 |
+
if not arr.flags.writeable:
|
| 566 |
+
arr = np.array(arr, copy=True)
|
| 567 |
+
out[action_key] = torch.as_tensor(arr)
|
| 568 |
+
out[f"{action_key}_is_pad"] = torch.as_tensor(
|
| 569 |
+
[not valid], dtype=torch.bool
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
def _materialize_virtual_state(
|
| 573 |
+
self,
|
| 574 |
+
out: dict,
|
| 575 |
+
df: pd.DataFrame,
|
| 576 |
+
frame_in_ep: int,
|
| 577 |
+
) -> None:
|
| 578 |
+
"""Copy physical source columns into schema-declared virtual state keys.
|
| 579 |
+
|
| 580 |
+
A virtual state key ("virtual.<name>") never exists in parquet; the
|
| 581 |
+
schema's ``virtual_state_sources`` maps it to the physical column
|
| 582 |
+
whose SAME-FRAME value it mirrors, so no ``_is_pad`` companion is
|
| 583 |
+
needed (the source frame always exists). Padding to the declared
|
| 584 |
+
state dim mirrors the physical-column path in ``__getitem__``.
|
| 585 |
+
|
| 586 |
+
Fails loud when the source column is missing: episode/shard filtering
|
| 587 |
+
at init already required the resolved physical column, so a miss here
|
| 588 |
+
means meta/data drift β silently zero-filling would reintroduce the
|
| 589 |
+
garbage-state failure mode this mechanism exists to fix.
|
| 590 |
+
"""
|
| 591 |
+
sch = self.meta.schema
|
| 592 |
+
vss = (
|
| 593 |
+
getattr(sch, "virtual_state_sources", None) or {}
|
| 594 |
+
) if sch is not None else {}
|
| 595 |
+
if not vss:
|
| 596 |
+
return
|
| 597 |
+
for vkey, source_key in vss.items():
|
| 598 |
+
src_key = self._resolve_df_key(str(source_key), df)
|
| 599 |
+
if src_key is None:
|
| 600 |
+
raise KeyError(
|
| 601 |
+
f"virtual state key {vkey!r}: physical source column "
|
| 602 |
+
f"{source_key!r} not found in episode parquet (repo="
|
| 603 |
+
f"{getattr(self, 'repo_id', '<unknown>')!r}). The schema "
|
| 604 |
+
f"declares a virtual_state_sources binding this episode's "
|
| 605 |
+
f"data does not satisfy β init-time column filtering and "
|
| 606 |
+
f"the loaded data have drifted."
|
| 607 |
+
)
|
| 608 |
+
arr = np.atleast_1d(
|
| 609 |
+
np.asarray(df[src_key].iloc[frame_in_ep], dtype=np.float32)
|
| 610 |
+
)
|
| 611 |
+
target = self._schema_key_target_dim(str(vkey))
|
| 612 |
+
if target is not None:
|
| 613 |
+
arr = self._pad_row(arr, target)
|
| 614 |
+
if not arr.flags.writeable:
|
| 615 |
+
arr = np.array(arr, copy=True)
|
| 616 |
+
out[str(vkey)] = torch.as_tensor(arr)
|
| 617 |
+
|
| 618 |
+
# ---- row-cell / per-key padding helpers (hoisted from v21) ------------
|
| 619 |
+
|
| 620 |
+
@staticmethod
|
| 621 |
+
def _cell_to_tensor(val):
|
| 622 |
+
if isinstance(val, np.ndarray):
|
| 623 |
+
# pyarrow-backed views are read-only AND contiguous, so
|
| 624 |
+
# ascontiguousarray is a no-op; np.array(copy=True) forces a fresh
|
| 625 |
+
# writable buffer (one small memcpy/row) to avoid the UserWarning.
|
| 626 |
+
if not val.flags.writeable:
|
| 627 |
+
val = np.array(val, copy=True)
|
| 628 |
+
return torch.as_tensor(val)
|
| 629 |
+
if isinstance(val, (list, tuple)):
|
| 630 |
+
return torch.as_tensor(np.asarray(val))
|
| 631 |
+
if isinstance(val, (int, np.integer)):
|
| 632 |
+
return torch.tensor(int(val), dtype=torch.int64)
|
| 633 |
+
if isinstance(val, (float, np.floating)):
|
| 634 |
+
return torch.tensor(float(val), dtype=torch.float32)
|
| 635 |
+
if isinstance(val, (bool, np.bool_)):
|
| 636 |
+
return torch.tensor(bool(val))
|
| 637 |
+
return val # bytes/dict/str left as-is
|
| 638 |
+
|
| 639 |
+
def _schema_target_dim(self, kind: str) -> Optional[int]:
|
| 640 |
+
"""Legacy canonical-key target dim. Kept for callers that assume
|
| 641 |
+
a single (state_dim, action_dim) pair exists. Multi-key schemas
|
| 642 |
+
must use ``_schema_key_target_dim`` for per-column lookup.
|
| 643 |
+
"""
|
| 644 |
+
sch = self.meta.schema
|
| 645 |
+
if sch is None:
|
| 646 |
+
return None
|
| 647 |
+
if kind == "state":
|
| 648 |
+
keys, dims = sch.state_keys, sch.state_dims
|
| 649 |
+
else:
|
| 650 |
+
keys, dims = sch.action_keys, sch.action_dims
|
| 651 |
+
if len(keys) == 1 and len(dims) == 1:
|
| 652 |
+
return int(dims[0])
|
| 653 |
+
return None
|
| 654 |
+
|
| 655 |
+
def _schema_key_target_dim(self, col: str) -> Optional[int]:
|
| 656 |
+
"""Per-schema-key target dim lookup by raw column name.
|
| 657 |
+
|
| 658 |
+
For multi-key schemas (e.g. robocoin: ``action`` +
|
| 659 |
+
``gripper_open_scale_action`` with dims ``(30, 2)``) each column
|
| 660 |
+
must be padded/truncated INDEPENDENTLY to its declared dim before
|
| 661 |
+
concat β otherwise variable-dim source robots (49-dim
|
| 662 |
+
``observation.state`` in one of the bimanual episodes) let the
|
| 663 |
+
cat'd vector explode past the schema's ``delta_mask`` length and
|
| 664 |
+
crash ``DeltaActionTransformFn``'s broadcast. Returns None for
|
| 665 |
+
columns not declared in the schema (``task_index``, ``timestamp``,
|
| 666 |
+
etc.).
|
| 667 |
+
"""
|
| 668 |
+
sch = self.meta.schema
|
| 669 |
+
if sch is None:
|
| 670 |
+
return None
|
| 671 |
+
for k, d in zip(sch.state_keys, sch.state_dims):
|
| 672 |
+
if col == k:
|
| 673 |
+
return int(d)
|
| 674 |
+
for k, d in zip(sch.action_keys, sch.action_dims):
|
| 675 |
+
if col == k:
|
| 676 |
+
return int(d)
|
| 677 |
+
return None
|
| 678 |
+
|
| 679 |
+
# Per-(repo, cur, target) dedupe set for the LABVLA_ALLOW_TRUNCATE
|
| 680 |
+
# escape-hatch warning. Keyed on repo_id so multi-repo mixes reveal WHICH
|
| 681 |
+
# repo is being truncated (OXE packed-canonical is safe; others may mask a
|
| 682 |
+
# real data bug). Emits once per unique mismatch across all ranks/workers.
|
| 683 |
+
_truncate_warned: set = set()
|
| 684 |
+
|
| 685 |
+
@classmethod
|
| 686 |
+
def _emit_truncate_warning_once_cls(
|
| 687 |
+
cls, cur: int, target_dim: int, repo_id: str
|
| 688 |
+
) -> None:
|
| 689 |
+
key = (repo_id, cur, target_dim)
|
| 690 |
+
if key in cls._truncate_warned:
|
| 691 |
+
return
|
| 692 |
+
cls._truncate_warned.add(key)
|
| 693 |
+
logger.warning(
|
| 694 |
+
"LABVLA_ALLOW_TRUNCATE=1: repo=%r truncating last-dim from %d to %d. "
|
| 695 |
+
"This bypasses the P0-03 guard and is unsafe for joint/action data. "
|
| 696 |
+
"If you only intended this for a specific repo (e.g. oxe-auge_clean_v2's "
|
| 697 |
+
"packed-canonical observation.state), check whether other repos in "
|
| 698 |
+
"this run are silently affected too.",
|
| 699 |
+
repo_id, cur, target_dim,
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
def _pad_row(self, arr: np.ndarray, target_dim: int) -> np.ndarray:
|
| 703 |
+
"""Zero-pad last dim up to ``target_dim``; refuse to silently truncate.
|
| 704 |
+
|
| 705 |
+
Truncating when ``cur > target_dim`` would silently drop real
|
| 706 |
+
joint/action dims (dual-arm or gripper state), so this raises; data
|
| 707 |
+
wider than the schema declares is a schema bug to fix at the source.
|
| 708 |
+
``LABVLA_ALLOW_TRUNCATE=1`` opts back into the legacy truncation.
|
| 709 |
+
"""
|
| 710 |
+
cur = arr.shape[-1]
|
| 711 |
+
if cur == target_dim:
|
| 712 |
+
return arr
|
| 713 |
+
if cur > target_dim:
|
| 714 |
+
if _env_flags.get("LABVLA_ALLOW_TRUNCATE") == "1":
|
| 715 |
+
_repo = str(getattr(self, "repo_id", "<unknown>"))
|
| 716 |
+
self._emit_truncate_warning_once_cls(cur, target_dim, _repo)
|
| 717 |
+
return arr[..., :target_dim]
|
| 718 |
+
raise ValueError(
|
| 719 |
+
f"_pad_row: source last-dim={cur} > schema target_dim={target_dim}; "
|
| 720 |
+
"refusing silent truncation. Either widen the schema's "
|
| 721 |
+
"state_dims/action_dims or set LABVLA_ALLOW_TRUNCATE=1 to "
|
| 722 |
+
"retain the legacy truncating behavior (not recommended)."
|
| 723 |
+
)
|
| 724 |
+
key = (str(getattr(self, "repo_id", "?")), int(cur), int(target_dim))
|
| 725 |
+
if key not in _PAD_NARROW_WARNED:
|
| 726 |
+
_PAD_NARROW_WARNED.add(key)
|
| 727 |
+
logger.warning(
|
| 728 |
+
"[adapter] %s: row width %d < declared dim %d β zero-padding. "
|
| 729 |
+
"A narrower-than-declared row usually means corrupt data or a "
|
| 730 |
+
"mis-declared schema dim; the padded zeros train as real "
|
| 731 |
+
"values. (warned once per (repo, width, dim))",
|
| 732 |
+
key[0], cur, target_dim,
|
| 733 |
+
)
|
| 734 |
+
pad_shape = list(arr.shape)
|
| 735 |
+
pad_shape[-1] = target_dim - cur
|
| 736 |
+
return np.concatenate(
|
| 737 |
+
[arr, np.zeros(pad_shape, dtype=arr.dtype)], axis=-1
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
# ---- shared __getitem__ pipeline --------------------------------------
|
| 741 |
+
|
| 742 |
+
def __getitem__(self, flat_idx: int) -> dict:
|
| 743 |
+
ep_idx, frame_in_ep = self._flat_to_ep(flat_idx)
|
| 744 |
+
df = self._load_ep_parquet(ep_idx)
|
| 745 |
+
|
| 746 |
+
# Schema-driven target dims for per-row padding (multi-robot merges).
|
| 747 |
+
state_target = self._schema_target_dim("state")
|
| 748 |
+
action_target = self._schema_target_dim("action")
|
| 749 |
+
|
| 750 |
+
out: dict = {}
|
| 751 |
+
image_keys_set = set(self._image_keys)
|
| 752 |
+
# Write image cells under the CANONICAL prefixed key
|
| 753 |
+
# (``observation.images.<x>``) regardless of the parquet column name
|
| 754 |
+
# (v3.0 uses prefixed feature names, v2.1 unprefixed like
|
| 755 |
+
# ``camera_1_rgb``) so adapter writes and the downstream
|
| 756 |
+
# RemapImageKeyTransformFn stay on the same canonical shape.
|
| 757 |
+
from src.schema.camera_mapping import expand_camera_source as _expand_src
|
| 758 |
+
_canonical_image_key = {col: _expand_src(col) for col in image_keys_set}
|
| 759 |
+
for col in df.columns:
|
| 760 |
+
# PNG-in-parquet (dtype=image) columns are decoded inline here;
|
| 761 |
+
# dtype=video columns go through the mp4 path below. Without this
|
| 762 |
+
# branch the image cell is skipped and the video loop falls through
|
| 763 |
+
# to _zero_frame, training the model on all-black frames.
|
| 764 |
+
if col in image_keys_set:
|
| 765 |
+
val = df[col].iloc[frame_in_ep]
|
| 766 |
+
frame_t = self._decode_image_cell(val)
|
| 767 |
+
# dtype=image cameras must receive the SAME seeded augmentation
|
| 768 |
+
# as the mp4 decode path (_read_video_frame). Skipping
|
| 769 |
+
# image_transforms here would leave PNG/JPEG-in-parquet datasets
|
| 770 |
+
# (all LabUtopia Level3 finetune tasks,
|
| 771 |
+
# verified dtype="image" on disk) trained with ZERO augmentation
|
| 772 |
+
# while --image_augmentation=true claimed otherwise.
|
| 773 |
+
_img_tf = getattr(self, "image_transforms", None)
|
| 774 |
+
if _img_tf is not None:
|
| 775 |
+
_apply_seeded = getattr(_img_tf, "apply_with_seed", None)
|
| 776 |
+
if callable(_apply_seeded):
|
| 777 |
+
frame_t = _apply_seeded(
|
| 778 |
+
frame_t,
|
| 779 |
+
seed_parts=(self.repo_id, ep_idx, col, frame_in_ep),
|
| 780 |
+
)
|
| 781 |
+
else:
|
| 782 |
+
frame_t = _img_tf(frame_t)
|
| 783 |
+
out[_canonical_image_key[col]] = frame_t
|
| 784 |
+
continue
|
| 785 |
+
if col in self.meta.video_keys:
|
| 786 |
+
continue
|
| 787 |
+
val = df[col].iloc[frame_in_ep]
|
| 788 |
+
# Per-schema-key padding: multi-key schemas (robocoin) pad each key
|
| 789 |
+
# to its declared schema.state_dims[i]/action_dims[i] before cat.
|
| 790 |
+
key_target = self._schema_key_target_dim(col)
|
| 791 |
+
# Same source_*_keys guard as the chunked path below: if a
|
| 792 |
+
# downstream canonical transform owns the raw-N -> canonical-8
|
| 793 |
+
# mapping, don't pre-truncate here.
|
| 794 |
+
sch_here = self.meta.schema
|
| 795 |
+
if sch_here is not None and key_target is not None:
|
| 796 |
+
act_set = set(getattr(sch_here, "action_keys", ()) or ()) | {"action", "actions"}
|
| 797 |
+
st_set = set(getattr(sch_here, "state_keys", ()) or ()) | {"observation.state", "state"}
|
| 798 |
+
if col in act_set and getattr(sch_here, "source_action_keys", ()):
|
| 799 |
+
key_target = None
|
| 800 |
+
elif col in st_set and getattr(sch_here, "source_state_keys", ()):
|
| 801 |
+
key_target = None
|
| 802 |
+
if key_target is not None and isinstance(val, (np.ndarray, list)):
|
| 803 |
+
arr = np.atleast_1d(np.asarray(val, dtype=np.float32))
|
| 804 |
+
arr = self._pad_row(arr, key_target)
|
| 805 |
+
# Force a writable copy (see _cell_to_tensor).
|
| 806 |
+
if not arr.flags.writeable:
|
| 807 |
+
arr = np.array(arr, copy=True)
|
| 808 |
+
out[col] = torch.as_tensor(arr)
|
| 809 |
+
continue
|
| 810 |
+
out[col] = self._cell_to_tensor(val)
|
| 811 |
+
|
| 812 |
+
# Normalize v2.1 pluralization quirks; keep both legacy and canonical
|
| 813 |
+
# keys when they diverge. CANONICAL_ALT_KEYS is overridable by subclasses.
|
| 814 |
+
for canonical, alias in self.CANONICAL_ALT_KEYS.items():
|
| 815 |
+
if canonical not in out and alias in out:
|
| 816 |
+
out[canonical] = out[alias]
|
| 817 |
+
|
| 818 |
+
# Synthetic next-frame action columns are not stored in parquet. Expose
|
| 819 |
+
# them under their schema action key so non-chunked paths still receive
|
| 820 |
+
# a valid tensor + `_is_pad`; the chunking loop below overwrites this
|
| 821 |
+
# with a (K, D) horizon tensor when delta_timestamps are configured.
|
| 822 |
+
self._materialize_next_frame_actions(out, df, frame_in_ep)
|
| 823 |
+
|
| 824 |
+
# Virtual state keys are same-frame copies of a physical column;
|
| 825 |
+
# materialize them right after the synthetic action keys so
|
| 826 |
+
# every downstream consumer (Delta/Normalize/Compose) sees them like
|
| 827 |
+
# any physical state column.
|
| 828 |
+
self._materialize_virtual_state(out, df, frame_in_ep)
|
| 829 |
+
|
| 830 |
+
# Resolve the language instruction string for the VLM processor.
|
| 831 |
+
# Priority: task -> task_index -> natural_language_instruction (some v3
|
| 832 |
+
# OXE sub-repos ship only the last). Warn-loud once if still empty so
|
| 833 |
+
# empty-instruction training surfaces instead of passing silently.
|
| 834 |
+
_existing_task = out.get("task")
|
| 835 |
+
_blank_task = (
|
| 836 |
+
isinstance(_existing_task, str) and not _existing_task.strip()
|
| 837 |
+
)
|
| 838 |
+
if "task" not in out or _blank_task:
|
| 839 |
+
# An existing-but-blank task cell must not block the task_index /
|
| 840 |
+
# natural_language_instruction fallback, or the sample would train
|
| 841 |
+
# on an empty instruction even when a recoverable source exists on
|
| 842 |
+
# the same row.
|
| 843 |
+
resolved_task = ""
|
| 844 |
+
if "task_index" in df.columns and not getattr(
|
| 845 |
+
self, "_task_index_unreliable", False
|
| 846 |
+
):
|
| 847 |
+
ti = int(df["task_index"].iloc[frame_in_ep])
|
| 848 |
+
resolved_task = self._tasks_by_idx.get(ti, "")
|
| 849 |
+
elif "task_index" in df.columns and not getattr(
|
| 850 |
+
self, "_warned_task_index_unreliable", False
|
| 851 |
+
):
|
| 852 |
+
# info.json["task_index_remapped"]: per-frame indices point into
|
| 853 |
+
# per-SOURCE task tables, not the merged global one.
|
| 854 |
+
logging.getLogger(__name__).warning(
|
| 855 |
+
"[H17] %s: skipping task_index fallback (merged product "
|
| 856 |
+
"re-indexed tasks.parquet; falling through to "
|
| 857 |
+
"natural_language_instruction). Warned once.",
|
| 858 |
+
getattr(self, "repo_id", "?"),
|
| 859 |
+
)
|
| 860 |
+
self._warned_task_index_unreliable = True
|
| 861 |
+
if not resolved_task and "natural_language_instruction" in df.columns:
|
| 862 |
+
nli = df["natural_language_instruction"].iloc[frame_in_ep]
|
| 863 |
+
if nli is not None and not _is_missing_scalar_value(nli):
|
| 864 |
+
resolved_task = str(nli)
|
| 865 |
+
out["task"] = resolved_task
|
| 866 |
+
|
| 867 |
+
# Warn-loud (once per repo) if the final instruction is empty: the
|
| 868 |
+
# sample carries real images but no language supervision.
|
| 869 |
+
_final_task = out.get("task")
|
| 870 |
+
if _final_task is None or (
|
| 871 |
+
isinstance(_final_task, str) and _final_task == ""
|
| 872 |
+
):
|
| 873 |
+
from src.utils.logging_utils import warn_once
|
| 874 |
+
|
| 875 |
+
repo_id = getattr(self, "repo_id", "<unknown>")
|
| 876 |
+
warn_once(
|
| 877 |
+
logger,
|
| 878 |
+
("empty_task_instruction", repo_id),
|
| 879 |
+
"[adapter] %s: resolved an EMPTY task/instruction string "
|
| 880 |
+
"(task -> task_index -> natural_language_instruction all "
|
| 881 |
+
"missing/empty). These samples train on an empty language "
|
| 882 |
+
"instruction. Check that the dataset has `task`, a usable "
|
| 883 |
+
"`task_index` (+ tasks.jsonl/tasks.parquet), or a "
|
| 884 |
+
"`natural_language_instruction` column.",
|
| 885 |
+
repo_id,
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
# delta_timestamps: caller wants K future frames of a key (e.g.
|
| 889 |
+
# actions). Expand canonical "action"/"observation.state" specs to the
|
| 890 |
+
# schema's actual action_keys/state_keys so schemas like
|
| 891 |
+
# robointer_droid (e.g. other_information.action_joint_position) chunk.
|
| 892 |
+
dt_items: list[tuple[str, list[float]]] = []
|
| 893 |
+
sch = self.meta.schema
|
| 894 |
+
for key, deltas in self.delta_timestamps.items():
|
| 895 |
+
dt_items.append((key, deltas))
|
| 896 |
+
# Expand to every schema action_key, INCLUDING "action"/"actions":
|
| 897 |
+
# single-key schemas (labutopia action_keys=("actions",)) need the
|
| 898 |
+
# phase-2 loop to overwrite the single-frame value with a (K, D)
|
| 899 |
+
# chunk, else DeltaActionTransformFn fails to broadcast against
|
| 900 |
+
# (1, D) state. Dedup since the top-level loop already added it.
|
| 901 |
+
if key in ("action", "actions") and sch is not None:
|
| 902 |
+
action_expand_keys = (
|
| 903 |
+
tuple(getattr(sch, "source_action_keys", ()) or ())
|
| 904 |
+
or tuple(getattr(sch, "action_keys", ()) or ())
|
| 905 |
+
)
|
| 906 |
+
for ak in action_expand_keys:
|
| 907 |
+
if ak != key:
|
| 908 |
+
dt_items.append((ak, deltas))
|
| 909 |
+
# NOTE: state is intentionally NOT expanded β
|
| 910 |
+
# DeltaActionTransformFn asserts state.ndim == 1 (single frame
|
| 911 |
+
# per sample).
|
| 912 |
+
|
| 913 |
+
for key, deltas in dt_items:
|
| 914 |
+
next_frame_source = self._next_frame_action_source(key)
|
| 915 |
+
lookup_key = next_frame_source or key
|
| 916 |
+
src_key = self._resolve_df_key(lookup_key, df)
|
| 917 |
+
if src_key is None:
|
| 918 |
+
continue
|
| 919 |
+
T = len(df)
|
| 920 |
+
source_shift = 1 if next_frame_source is not None else 0
|
| 921 |
+
idxs = [
|
| 922 |
+
frame_in_ep + source_shift + int(round(dt * self.meta.fps))
|
| 923 |
+
for dt in deltas
|
| 924 |
+
]
|
| 925 |
+
clipped = np.clip(idxs, 0, T - 1)
|
| 926 |
+
is_pad = np.array(
|
| 927 |
+
[i != c for i, c in zip(idxs, clipped)], dtype=bool
|
| 928 |
+
)
|
| 929 |
+
rows = [
|
| 930 |
+
np.atleast_1d(np.asarray(df[src_key].iloc[int(c)])) for c in clipped
|
| 931 |
+
]
|
| 932 |
+
# Review L4: a column with per-row varying widths (e.g. the raw
|
| 933 |
+
# heterogeneous observation.state of a merged multi-source repo)
|
| 934 |
+
# would make np.stack raise an opaque broadcast error mid-training.
|
| 935 |
+
# Fail loud with an actionable message instead.
|
| 936 |
+
_widths = {int(r.shape[-1]) for r in rows}
|
| 937 |
+
if len(_widths) > 1:
|
| 938 |
+
raise ValueError(
|
| 939 |
+
f"[adapter] {getattr(self, 'repo_id', '<unknown>')!r}: "
|
| 940 |
+
f"column {src_key!r} has per-row varying widths "
|
| 941 |
+
f"{sorted(_widths)} within one chunk window β cannot "
|
| 942 |
+
f"stack into a (T, D) tensor. This column is not a usable "
|
| 943 |
+
f"chunk source; bind the schema key to a homogeneous "
|
| 944 |
+
f"physical column (or a virtual_state_sources copy of "
|
| 945 |
+
f"one) instead."
|
| 946 |
+
)
|
| 947 |
+
col_vals = np.stack(rows).astype(np.float32)
|
| 948 |
+
# Per-key schema target dim (multi-key schemas like robocoin pad
|
| 949 |
+
# each column to its own declared dim before cat).
|
| 950 |
+
target = self._schema_key_target_dim(key)
|
| 951 |
+
# If the schema declares source_*_keys, a downstream transform owns
|
| 952 |
+
# the raw-N -> canonical-8 mapping, so the adapter MUST NOT
|
| 953 |
+
# pre-truncate here: doing so drops the real gripper (e.g.
|
| 954 |
+
# UR/Festo raw 11, Rizon4 raw 12 β first 8 dims) and
|
| 955 |
+
# replaces it with a mirror joint. Must run REGARDLESS of whether
|
| 956 |
+
# the canonical key matched, since the data column is the raw source.
|
| 957 |
+
if sch is not None and target is not None:
|
| 958 |
+
action_keys_set = set(getattr(sch, "action_keys", ()) or ()) | {"action", "actions"}
|
| 959 |
+
state_keys_set = set(getattr(sch, "state_keys", ()) or ()) | {"observation.state", "state"}
|
| 960 |
+
if key in action_keys_set and getattr(sch, "source_action_keys", ()):
|
| 961 |
+
target = None
|
| 962 |
+
elif key in state_keys_set and getattr(sch, "source_state_keys", ()):
|
| 963 |
+
target = None
|
| 964 |
+
if target is None:
|
| 965 |
+
# Fall back to canonical single-key path.
|
| 966 |
+
target = action_target if key in ("action", "actions") else (
|
| 967 |
+
state_target if key in ("observation.state", "state") else None)
|
| 968 |
+
if sch is not None:
|
| 969 |
+
if key in ("action", "actions") and getattr(sch, "source_action_keys", ()):
|
| 970 |
+
target = None
|
| 971 |
+
elif key in ("observation.state", "state") and getattr(sch, "source_state_keys", ()):
|
| 972 |
+
target = None
|
| 973 |
+
if target is not None:
|
| 974 |
+
col_vals = self._pad_row(col_vals, target)
|
| 975 |
+
out[key] = torch.as_tensor(col_vals)
|
| 976 |
+
out[f"{key}_is_pad"] = torch.as_tensor(is_pad)
|
| 977 |
+
|
| 978 |
+
# Video frame reads β only cameras the schema actually uses. Iterating
|
| 979 |
+
# info.json cameras that don't exist on disk or aren't in image_mapping
|
| 980 |
+
# wastes a full mp4 decode + NFS stat per extra camera, which dominates
|
| 981 |
+
# data loading under multi-rank contention.
|
| 982 |
+
sch = self.meta.schema
|
| 983 |
+
target_cams = (list(sch.image_mapping.keys())
|
| 984 |
+
if sch is not None and getattr(sch, "image_mapping", None)
|
| 985 |
+
else self.meta.video_keys)
|
| 986 |
+
# Track cameras whose read fell back to a black _zero_frame; otherwise
|
| 987 |
+
# RemapImageKeyTransformFn marks the slot mask=True and the attention
|
| 988 |
+
# layer treats the fallback as a real observation.
|
| 989 |
+
for vkey in target_cams:
|
| 990 |
+
# dtype=image cameras were already decoded from parquet above; skip
|
| 991 |
+
# the mp4 fallback to avoid clobbering the real frame and doing
|
| 992 |
+
# wasted stat()s. image_mapping order yields vkey canonical-prefixed.
|
| 993 |
+
if vkey in out:
|
| 994 |
+
continue
|
| 995 |
+
self._last_read_was_zero_frame = False
|
| 996 |
+
frame_t = self._read_video_frame(ep_idx, vkey, frame_in_ep)
|
| 997 |
+
out[vkey] = frame_t
|
| 998 |
+
if self._last_read_was_zero_frame:
|
| 999 |
+
out[f"{vkey}_invalid"] = True
|
| 1000 |
+
|
| 1001 |
+
# Defensive fill: guarantee every schema action_key has a matching
|
| 1002 |
+
# `{key}_is_pad`. The dt_items loop skips keys absent from
|
| 1003 |
+
# delta_timestamps (inference/ablation), which otherwise leaves
|
| 1004 |
+
# `action_is_pad` absent and forces pad-masked MSE to unmasked mean on
|
| 1005 |
+
# ~9% of padded trailing frames. Fill zeros (no pad) where missing.
|
| 1006 |
+
if sch is not None:
|
| 1007 |
+
for ak in getattr(sch, "action_keys", ()):
|
| 1008 |
+
if ak in out and f"{ak}_is_pad" not in out:
|
| 1009 |
+
val = out[ak]
|
| 1010 |
+
chunk_len = int(val.shape[0]) if val.ndim >= 1 else 1
|
| 1011 |
+
out[f"{ak}_is_pad"] = torch.zeros(chunk_len, dtype=torch.bool)
|
| 1012 |
+
|
| 1013 |
+
return out
|
| 1014 |
+
|
| 1015 |
+
# ---- zero-frame fallback (shared) -------------------------------------
|
| 1016 |
+
|
| 1017 |
+
_last_read_was_zero_frame: bool = False
|
| 1018 |
+
|
| 1019 |
+
# Fixed slot order for the fork-shared fallback counter. The local Counter
|
| 1020 |
+
# below only ever accumulates inside DataLoader WORKER processes (fork
|
| 1021 |
+
# copies), so with num_workers > 0 the main process's save-time
|
| 1022 |
+
# `video_fallback_summary` would read an always-empty Counter and the
|
| 1023 |
+
# "silent I/O rot" diagnostic would never fire. A multiprocessing.Array
|
| 1024 |
+
# created in the main process BEFORE workers fork is shared memory, so
|
| 1025 |
+
# worker increments are visible to the main process.
|
| 1026 |
+
_ZERO_FRAME_REASON_SLOTS: tuple[str, ...] = (
|
| 1027 |
+
"missing_file",
|
| 1028 |
+
"decode_error",
|
| 1029 |
+
"index_overshoot",
|
| 1030 |
+
"frame_overshoot",
|
| 1031 |
+
"missing_episode",
|
| 1032 |
+
"schema_camera_missing",
|
| 1033 |
+
"video_metadata_missing",
|
| 1034 |
+
"other",
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
def _init_zero_frame_shared(self) -> None:
|
| 1038 |
+
"""Create the fork-shared fallback counter. Call from subclass __init__
|
| 1039 |
+
(main process, before any DataLoader worker forks). Best-effort: on
|
| 1040 |
+
platforms without usable shared memory the local Counter still works
|
| 1041 |
+
for num_workers=0."""
|
| 1042 |
+
try:
|
| 1043 |
+
import multiprocessing as _mp
|
| 1044 |
+
self._zero_frame_shared = _mp.Array("l", len(self._ZERO_FRAME_REASON_SLOTS))
|
| 1045 |
+
except Exception:
|
| 1046 |
+
self._zero_frame_shared = None
|
| 1047 |
+
|
| 1048 |
+
def _zero_frame(
|
| 1049 |
+
self, h: int = 480, w: int = 640, reason: str = "missing_file"
|
| 1050 |
+
) -> torch.Tensor:
|
| 1051 |
+
"""Return a cached black frame for missing-video fallback.
|
| 1052 |
+
|
| 1053 |
+
Never runs image_transforms on the cached zero tensor: the random
|
| 1054 |
+
jitter would destroy the 'this camera is invalid' semantic and cache
|
| 1055 |
+
one random outcome forever (same tensor returned for every sample).
|
| 1056 |
+
"""
|
| 1057 |
+
# Count reasons per failure mode so silent I/O rot is discoverable.
|
| 1058 |
+
if not hasattr(self, "_zero_frame_reasons"):
|
| 1059 |
+
import collections as _collections
|
| 1060 |
+
self._zero_frame_reasons = _collections.Counter()
|
| 1061 |
+
self._zero_frame_reasons[reason] += 1
|
| 1062 |
+
# Also bump the fork-shared slot so the MAIN process's save-time
|
| 1063 |
+
# summary sees worker-side fallbacks.
|
| 1064 |
+
shared = getattr(self, "_zero_frame_shared", None)
|
| 1065 |
+
if shared is not None:
|
| 1066 |
+
slots = self._ZERO_FRAME_REASON_SLOTS
|
| 1067 |
+
idx = slots.index(reason) if reason in slots else len(slots) - 1
|
| 1068 |
+
try:
|
| 1069 |
+
with shared.get_lock():
|
| 1070 |
+
shared[idx] += 1
|
| 1071 |
+
except Exception:
|
| 1072 |
+
pass
|
| 1073 |
+
self._last_read_was_zero_frame = True
|
| 1074 |
+
return torch.zeros(3, h, w, dtype=torch.float32)
|
| 1075 |
+
|
| 1076 |
+
def video_fallback_summary(self) -> dict:
|
| 1077 |
+
"""Snapshot of how many times each fallback reason fired in this
|
| 1078 |
+
adapter's lifetime, so callers can log silent I/O rot ("why did MSE
|
| 1079 |
+
never drop on that repo").
|
| 1080 |
+
|
| 1081 |
+
Prefer the fork-shared counter (includes DataLoader-worker increments);
|
| 1082 |
+
fall back to the process-local Counter (num_workers=0 or shared-memory
|
| 1083 |
+
init failure).
|
| 1084 |
+
"""
|
| 1085 |
+
shared = getattr(self, "_zero_frame_shared", None)
|
| 1086 |
+
if shared is not None:
|
| 1087 |
+
try:
|
| 1088 |
+
with shared.get_lock():
|
| 1089 |
+
vals = list(shared)
|
| 1090 |
+
out = {
|
| 1091 |
+
reason: int(v)
|
| 1092 |
+
for reason, v in zip(self._ZERO_FRAME_REASON_SLOTS, vals)
|
| 1093 |
+
if int(v) > 0
|
| 1094 |
+
}
|
| 1095 |
+
if out:
|
| 1096 |
+
return out
|
| 1097 |
+
except Exception:
|
| 1098 |
+
pass
|
| 1099 |
+
if not hasattr(self, "_zero_frame_reasons"):
|
| 1100 |
+
return {}
|
| 1101 |
+
return dict(self._zero_frame_reasons)
|
src/adapters/lerobot_v21.py
ADDED
|
@@ -0,0 +1,710 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LeRobot v2.1 dataset adapter.
|
| 2 |
+
|
| 3 |
+
v2.1 layout:
|
| 4 |
+
<root>/meta/info.json (codebase_version="v2.1")
|
| 5 |
+
<root>/meta/episodes.jsonl (one episode per line: {episode_index, length, tasks})
|
| 6 |
+
<root>/meta/tasks.jsonl
|
| 7 |
+
<root>/meta/stats.json (absolute-value per-feature stats)
|
| 8 |
+
<root>/data/chunk-XXX/episode_NNNNNN.parquet (one parquet per episode)
|
| 9 |
+
<root>/videos/chunk-XXX/<cam_key>/episode_NNNNNN.mp4
|
| 10 |
+
|
| 11 |
+
Interface satisfies `BaseAdapter` β train.py's `TransformedAdapterDataset`
|
| 12 |
+
only needs `adapter[idx]`, `len(adapter)`, and `adapter.meta`. No
|
| 13 |
+
HuggingFace lerobot dependency; this adapter reads parquet/mp4 directly.
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import logging
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
from fractions import Fraction
|
| 22 |
+
from functools import lru_cache
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Optional
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pandas as pd
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
from .base import DatasetMeta
|
| 31 |
+
from .lerobot_base import LeRobotAdapterBase, _get_shared_video_cache
|
| 32 |
+
from src.utils.storage_retry import (
|
| 33 |
+
read_parquet_with_storage_retry,
|
| 34 |
+
run_with_storage_retry,
|
| 35 |
+
storage_path_exists,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _read_episodes_jsonl(meta_root: Path) -> list[dict]:
|
| 42 |
+
out = []
|
| 43 |
+
with open(meta_root / "episodes.jsonl") as f:
|
| 44 |
+
for line in f:
|
| 45 |
+
line = line.strip()
|
| 46 |
+
if line:
|
| 47 |
+
out.append(json.loads(line))
|
| 48 |
+
out.sort(key=lambda e: e["episode_index"])
|
| 49 |
+
return out
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Scan-cache infrastructure lives in adapters/_scan_cache.py and _ep_starts_lens
|
| 53 |
+
# in lerobot_base (shared indexing math); re-exported here for out-of-tree callers.
|
| 54 |
+
from ._scan_cache import ( # noqa: F401
|
| 55 |
+
_SCAN_CACHE_FILE,
|
| 56 |
+
_load_scan_cache,
|
| 57 |
+
_save_scan_cache,
|
| 58 |
+
_scan_cache_key,
|
| 59 |
+
_shard_fingerprint,
|
| 60 |
+
)
|
| 61 |
+
from .lerobot_base import _ep_starts_lens # noqa: F401
|
| 62 |
+
|
| 63 |
+
# Episode index extracted from a v2.1 per-episode filename
|
| 64 |
+
# ("episode_000123.parquet" β 123). Any digit width accepted.
|
| 65 |
+
_EP_NUM_RE = re.compile(r"episode_(\d+)")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _parquet_ok_v21(
|
| 69 |
+
p: Path,
|
| 70 |
+
*,
|
| 71 |
+
needed: list,
|
| 72 |
+
alt: dict,
|
| 73 |
+
declared_dim: dict,
|
| 74 |
+
ep_len_by_idx: dict,
|
| 75 |
+
repo_id: str,
|
| 76 |
+
warn_key_root: str,
|
| 77 |
+
allow_truncate: bool = False,
|
| 78 |
+
) -> bool:
|
| 79 |
+
"""Schema-satisfies check for a sample parquet.
|
| 80 |
+
|
| 81 |
+
(a) every schema key must be present (or its v2.1 alt variant);
|
| 82 |
+
(b) any key with a per-episode list dim must not EXCEED the
|
| 83 |
+
schema's declared dim. Source-robot episodes whose native
|
| 84 |
+
state/action exceeds the declared envelope (e.g. a 49-dim
|
| 85 |
+
observation.state when schema says 30) are skipped rather
|
| 86 |
+
than truncated β truncation would lose actual joint info.
|
| 87 |
+
Shorter is OK; Phase-1 zero-pads up to declared dim.
|
| 88 |
+
(c) the parquet's row count must equal the episodes.jsonl `length`
|
| 89 |
+
for this episode β a longer meta length means an IndexError
|
| 90 |
+
mid-training; a shorter one means silently unsampled tail
|
| 91 |
+
frames. Either way the episode is dropped with a warning.
|
| 92 |
+
"""
|
| 93 |
+
import pyarrow.parquet as _pq
|
| 94 |
+
try:
|
| 95 |
+
table = _pq.read_table(str(p))
|
| 96 |
+
except Exception:
|
| 97 |
+
return False
|
| 98 |
+
_m = _EP_NUM_RE.search(p.name)
|
| 99 |
+
if _m is not None:
|
| 100 |
+
expected_len = ep_len_by_idx.get(int(_m.group(1)))
|
| 101 |
+
if expected_len is not None and expected_len != len(table):
|
| 102 |
+
from src.utils.logging_utils import warn_once
|
| 103 |
+
warn_once(
|
| 104 |
+
logger,
|
| 105 |
+
("v21_row_len_mismatch", warn_key_root),
|
| 106 |
+
"[v21-adapter] %s: episode_%06d parquet has %d "
|
| 107 |
+
"rows but episodes.jsonl declares length=%d β "
|
| 108 |
+
"dropping episode (meta/data inconsistency; "
|
| 109 |
+
"further mismatches in this repo are dropped "
|
| 110 |
+
"with the same policy, warned once).",
|
| 111 |
+
repo_id, int(_m.group(1)),
|
| 112 |
+
len(table), expected_len,
|
| 113 |
+
)
|
| 114 |
+
return False
|
| 115 |
+
cols = set(table.schema.names)
|
| 116 |
+
for k in needed:
|
| 117 |
+
key_in_parquet = k if k in cols else alt.get(k)
|
| 118 |
+
if key_in_parquet is None or key_in_parquet not in cols:
|
| 119 |
+
return False
|
| 120 |
+
# Overflow check only for keys with a declared dim.
|
| 121 |
+
decl = declared_dim.get(k)
|
| 122 |
+
if decl is None or len(table) == 0:
|
| 123 |
+
continue
|
| 124 |
+
raw = table[key_in_parquet][0].as_py()
|
| 125 |
+
if isinstance(raw, (list, tuple)) and len(raw) > decl and not allow_truncate:
|
| 126 |
+
# v30 honors LABVLA_ALLOW_TRUNCATE here (keep the shard, truncate at
|
| 127 |
+
# read time); on v2.1 the over-wide episode is dropped instead.
|
| 128 |
+
return False
|
| 129 |
+
return True
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class LeRobotV21Adapter(LeRobotAdapterBase):
|
| 134 |
+
"""Adapter for LeRobot v2.1 datasets (one parquet + one mp4 per episode)."""
|
| 135 |
+
|
| 136 |
+
def __init__(
|
| 137 |
+
self,
|
| 138 |
+
repo_id: str,
|
| 139 |
+
root: str | Path,
|
| 140 |
+
delta_timestamps: dict | None = None,
|
| 141 |
+
image_transforms=None,
|
| 142 |
+
external_stats: dict | None = None,
|
| 143 |
+
override_schema=None,
|
| 144 |
+
video_backend: str = "pyav",
|
| 145 |
+
episode_filter: list[int] | tuple[int, ...] | None = None,
|
| 146 |
+
):
|
| 147 |
+
"""
|
| 148 |
+
Args:
|
| 149 |
+
episode_filter: optional set of episode_index values to keep; all
|
| 150 |
+
others are excluded. Used by the task-uniform sampler to build
|
| 151 |
+
per-task views of one repo β the adapter then reports
|
| 152 |
+
num_episodes/num_frames/sample() as if it held only those.
|
| 153 |
+
|
| 154 |
+
__init__ is a thin orchestrator over the four phase methods below.
|
| 155 |
+
"""
|
| 156 |
+
self._resolve_root(
|
| 157 |
+
repo_id, root, delta_timestamps, image_transforms, video_backend
|
| 158 |
+
)
|
| 159 |
+
stats, schema = self._load_meta_and_stats(external_stats, override_schema)
|
| 160 |
+
|
| 161 |
+
# Filter episodes whose parquet lacks schema-required state/action keys
|
| 162 |
+
# (e.g. robocoin chunks missing gripper_open_scale_* would crash
|
| 163 |
+
# downstream). Stats compute applies the same filter to stay aligned.
|
| 164 |
+
if schema is not None:
|
| 165 |
+
self._filter_episodes_by_schema(schema)
|
| 166 |
+
|
| 167 |
+
# Task-uniform support: restrict to a user-supplied episode subset,
|
| 168 |
+
# applied AFTER schema/parquet filters (view = filter β© schema-valid).
|
| 169 |
+
if episode_filter is not None:
|
| 170 |
+
allowed = {int(i) for i in episode_filter}
|
| 171 |
+
before = len(self._episodes)
|
| 172 |
+
self._episodes = [
|
| 173 |
+
ep for ep in self._episodes
|
| 174 |
+
if int(ep.get("episode_index", -1)) in allowed
|
| 175 |
+
]
|
| 176 |
+
self._ep_starts, self._ep_lens = _ep_starts_lens(self._episodes)
|
| 177 |
+
logger.info(
|
| 178 |
+
"[v21-adapter] %s: episode_filter kept %d/%d episodes",
|
| 179 |
+
repo_id, len(self._episodes), before,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
self._drop_terminal_samples_for_next_frame_actions(schema)
|
| 183 |
+
|
| 184 |
+
self._finalize_meta_and_caches(stats, schema)
|
| 185 |
+
|
| 186 |
+
# ---- __init__ phase methods --------------------------------------------
|
| 187 |
+
|
| 188 |
+
def _resolve_root(
|
| 189 |
+
self,
|
| 190 |
+
repo_id: str,
|
| 191 |
+
root: str | Path,
|
| 192 |
+
delta_timestamps: dict | None,
|
| 193 |
+
image_transforms,
|
| 194 |
+
video_backend: str,
|
| 195 |
+
) -> None:
|
| 196 |
+
"""Phase 1: root resolution, info.json version gate, episodes index."""
|
| 197 |
+
self.repo_id = repo_id
|
| 198 |
+
# Caller can pass either <parent>/<repo_id> or <root> directly.
|
| 199 |
+
root_p = Path(root)
|
| 200 |
+
if root_p.name != Path(repo_id).name and (root_p / repo_id).exists():
|
| 201 |
+
root_p = root_p / repo_id
|
| 202 |
+
self.root = root_p
|
| 203 |
+
self.meta_root = self.root / "meta"
|
| 204 |
+
self.data_root = self.root / "data"
|
| 205 |
+
self.video_root = self.root / "videos"
|
| 206 |
+
self.delta_timestamps = delta_timestamps or {}
|
| 207 |
+
self.image_transforms = image_transforms
|
| 208 |
+
self.video_backend = video_backend
|
| 209 |
+
|
| 210 |
+
with open(self.meta_root / "info.json") as _f:
|
| 211 |
+
info = json.load(_f)
|
| 212 |
+
v = info.get("codebase_version", "")
|
| 213 |
+
if not v.startswith("v2"):
|
| 214 |
+
raise ValueError(
|
| 215 |
+
f"LeRobotV21Adapter: {self.root} is codebase_version={v!r}, "
|
| 216 |
+
f"expected v2.x. Use the *_old suffix dataset if this is v3."
|
| 217 |
+
)
|
| 218 |
+
self._info = info
|
| 219 |
+
self._chunks_size = int(info.get("chunks_size", 1000))
|
| 220 |
+
self._episodes = _read_episodes_jsonl(self.meta_root)
|
| 221 |
+
self._ep_starts, self._ep_lens = _ep_starts_lens(self._episodes)
|
| 222 |
+
|
| 223 |
+
def _load_meta_and_stats(self, external_stats: dict | None, override_schema):
|
| 224 |
+
"""Phase 2: tasks index, stats (+ external override), schema
|
| 225 |
+
discovery, next-frame stats patch. Returns ``(stats, schema)``."""
|
| 226 |
+
info = self._info
|
| 227 |
+
|
| 228 |
+
# Load tasks.jsonl -> task_index (int) -> task (str). v2.1 parquet stores
|
| 229 |
+
# integer `task_index` per frame; downstream transforms expect the string
|
| 230 |
+
# `task` key (language instruction). Resolve on adapter load.
|
| 231 |
+
self._tasks_by_idx: dict[int, str] = {}
|
| 232 |
+
tasks_jsonl = self.meta_root / "tasks.jsonl"
|
| 233 |
+
if tasks_jsonl.exists():
|
| 234 |
+
with open(tasks_jsonl) as f:
|
| 235 |
+
for line in f:
|
| 236 |
+
line = line.strip()
|
| 237 |
+
if not line:
|
| 238 |
+
continue
|
| 239 |
+
rec = json.loads(line)
|
| 240 |
+
ti = rec.get("task_index")
|
| 241 |
+
if ti is not None:
|
| 242 |
+
self._tasks_by_idx[int(ti)] = rec.get("task", "")
|
| 243 |
+
|
| 244 |
+
# Stats: absolute-value per-feature dict. external_stats overrides.
|
| 245 |
+
stats_path = self.meta_root / "stats.json"
|
| 246 |
+
if stats_path.exists():
|
| 247 |
+
from src.dataset.utils import cast_stats_to_numpy
|
| 248 |
+
with open(stats_path) as _f:
|
| 249 |
+
stats: dict = cast_stats_to_numpy(json.load(_f))
|
| 250 |
+
else:
|
| 251 |
+
stats = {}
|
| 252 |
+
if external_stats:
|
| 253 |
+
stats = {**stats, **external_stats}
|
| 254 |
+
|
| 255 |
+
# Schema discovery (Tier 0 override > Tier 1 manifest > Tier 2 infer).
|
| 256 |
+
from src.schema import discover_schema, SchemaDiscoveryError
|
| 257 |
+
try:
|
| 258 |
+
schema = discover_schema(
|
| 259 |
+
self.root,
|
| 260 |
+
robot_type=info.get("robot_type"),
|
| 261 |
+
override=override_schema,
|
| 262 |
+
)
|
| 263 |
+
except SchemaDiscoveryError as e:
|
| 264 |
+
if override_schema is not None:
|
| 265 |
+
# The override came from --dataset_schema; discover_schema also
|
| 266 |
+
# VALIDATES it against the on-disk meta (camera mapping,
|
| 267 |
+
# annotation columns, ...). Swallowing the failure here would
|
| 268 |
+
# train on the unvalidated override with only a warning.
|
| 269 |
+
raise
|
| 270 |
+
logger.warning("[v21-adapter] schema discovery failed: %s", e)
|
| 271 |
+
schema = override_schema
|
| 272 |
+
|
| 273 |
+
stats = self.patch_stats_for_next_frame_actions(stats, schema)
|
| 274 |
+
return stats, schema
|
| 275 |
+
|
| 276 |
+
def _filter_episodes_by_schema(self, schema) -> None:
|
| 277 |
+
"""Phase 3: drop episodes whose parquet lacks schema-required columns
|
| 278 |
+
or whose row count contradicts episodes.jsonl (scan-cached)."""
|
| 279 |
+
repo_id = self.repo_id
|
| 280 |
+
read_state_keys = (
|
| 281 |
+
tuple(getattr(schema, "source_state_keys", ()) or ())
|
| 282 |
+
or tuple(getattr(schema, "state_keys", ()) or ())
|
| 283 |
+
)
|
| 284 |
+
read_action_keys = (
|
| 285 |
+
tuple(getattr(schema, "source_action_keys", ()) or ())
|
| 286 |
+
or tuple(getattr(schema, "action_keys", ()) or ())
|
| 287 |
+
)
|
| 288 |
+
# _resolve_physical_column also maps virtual state keys to their
|
| 289 |
+
# physical source β a virtual key must never appear in `needed` or
|
| 290 |
+
# every episode would be dropped for "missing" it.
|
| 291 |
+
needed = list(dict.fromkeys(
|
| 292 |
+
self._resolve_physical_column(schema, k)
|
| 293 |
+
for k in (list(read_state_keys) + list(read_action_keys))
|
| 294 |
+
))
|
| 295 |
+
# For canonical single-key schemas ("observation.state", "action")
|
| 296 |
+
# also accept the v2.1 legacy variants ("state", "actions").
|
| 297 |
+
alt = {"observation.state": "state", "action": "actions"}
|
| 298 |
+
|
| 299 |
+
# Per-key declared dim from schema (for the overflow check below).
|
| 300 |
+
# Also register SOURCE keys/dims: `needed` holds source column names
|
| 301 |
+
# when the schema declares them, so a canonical-only map would skip
|
| 302 |
+
# the overflow check for source-layout schemas.
|
| 303 |
+
declared_dim: dict[str, int] = {}
|
| 304 |
+
for k, d in zip(getattr(schema, "state_keys", ()),
|
| 305 |
+
getattr(schema, "state_dims", ())):
|
| 306 |
+
declared_dim[k] = int(d)
|
| 307 |
+
for k, d in zip(getattr(schema, "action_keys", ()),
|
| 308 |
+
getattr(schema, "action_dims", ())):
|
| 309 |
+
declared_dim[k] = int(d)
|
| 310 |
+
for k, d in zip(getattr(schema, "source_state_keys", ()) or (),
|
| 311 |
+
getattr(schema, "source_state_dims", ()) or ()):
|
| 312 |
+
declared_dim[k] = int(d)
|
| 313 |
+
for k, d in zip(getattr(schema, "source_action_keys", ()) or (),
|
| 314 |
+
getattr(schema, "source_action_dims", ()) or ()):
|
| 315 |
+
declared_dim[k] = int(d)
|
| 316 |
+
# `needed` holds the PHYSICAL source column for virtual state keys;
|
| 317 |
+
# attach the virtual key's declared dim to that physical name so the
|
| 318 |
+
# overflow check still probes it. setdefault: a column with its own
|
| 319 |
+
# schema-declared dim (e.g. it doubles as an action key) keeps that dim.
|
| 320 |
+
for vk, vsrc in (
|
| 321 |
+
getattr(schema, "virtual_state_sources", None) or {}
|
| 322 |
+
).items():
|
| 323 |
+
if vk in declared_dim:
|
| 324 |
+
declared_dim.setdefault(str(vsrc), declared_dim[vk])
|
| 325 |
+
|
| 326 |
+
from src.utils import env_flags as _env_flags_t
|
| 327 |
+
_allow_truncate = _env_flags_t.get("LABVLA_ALLOW_TRUNCATE") == "1"
|
| 328 |
+
|
| 329 |
+
# Expected per-episode frame count from episodes.jsonl, cross-checked
|
| 330 |
+
# against the parquet's actual row count below.
|
| 331 |
+
_ep_len_by_idx: dict[int, int] = {
|
| 332 |
+
int(ep["episode_index"]): int(ep.get("length", -1))
|
| 333 |
+
for ep in self._episodes
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
def _parquet_ok(p: Path) -> bool:
|
| 337 |
+
# Shim binding the phase-local context to module-level _parquet_ok_v21.
|
| 338 |
+
return _parquet_ok_v21(
|
| 339 |
+
p,
|
| 340 |
+
needed=needed,
|
| 341 |
+
alt=alt,
|
| 342 |
+
declared_dim=declared_dim,
|
| 343 |
+
ep_len_by_idx=_ep_len_by_idx,
|
| 344 |
+
repo_id=repo_id,
|
| 345 |
+
warn_key_root=str(self.root),
|
| 346 |
+
allow_truncate=_allow_truncate,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# Disk-persistent scan cache: for N-task adapters sharing a
|
| 350 |
+
# source_root, only the first pays the scan cost (~10s); the rest
|
| 351 |
+
# read the cached result (~10ms).
|
| 352 |
+
cache_key = _scan_cache_key(
|
| 353 |
+
self.meta_root,
|
| 354 |
+
schema_id=getattr(schema, "schema_id", "unknown"),
|
| 355 |
+
chunks_size=self._chunks_size,
|
| 356 |
+
data_root=self.data_root,
|
| 357 |
+
)
|
| 358 |
+
cache_key["required_columns"] = list(needed)
|
| 359 |
+
# Scan semantics include the per-episode row-count check, source-key
|
| 360 |
+
# overflow dims, declared dims and env gates; bump to invalidate caches
|
| 361 |
+
# written by an older scan version.
|
| 362 |
+
cache_key["integrity_checks"] = 3
|
| 363 |
+
cache_key["declared_dims"] = sorted(
|
| 364 |
+
(str(k), int(v)) for k, v in (declared_dim or {}).items()
|
| 365 |
+
)
|
| 366 |
+
cached = _load_scan_cache(self.meta_root, cache_key)
|
| 367 |
+
|
| 368 |
+
if cached is not None:
|
| 369 |
+
chunk_ok, existing_ep_indices = cached
|
| 370 |
+
else:
|
| 371 |
+
# Per-file validation is the safe DEFAULT. The alternative
|
| 372 |
+
# (LABVLA_V21_VALIDATE_PER_FILE=0) trusts one sampled parquet
|
| 373 |
+
# per chunk β fast on huge known-clean OXE datasets, but it can
|
| 374 |
+
# keep bad episodes from chunks whose sample happened to be fine.
|
| 375 |
+
from src.utils import env_flags as _env_flags
|
| 376 |
+
_validate_per_file = (
|
| 377 |
+
_env_flags.get("LABVLA_V21_VALIDATE_PER_FILE") != "0"
|
| 378 |
+
)
|
| 379 |
+
chunk_ok: dict[int, bool] = {}
|
| 380 |
+
file_ok: dict[Path, bool] = {}
|
| 381 |
+
for ep in self._episodes:
|
| 382 |
+
chunk = int(ep.get("episode_index", 0)) // self._chunks_size
|
| 383 |
+
if chunk in chunk_ok:
|
| 384 |
+
continue
|
| 385 |
+
chunk_dir = self.data_root / f"chunk-{chunk:03d}"
|
| 386 |
+
if _validate_per_file:
|
| 387 |
+
# Validate every parquet; chunk is OK if at least one
|
| 388 |
+
# passes. Cache per-file results to drop individual bad
|
| 389 |
+
# episodes below.
|
| 390 |
+
any_ok = False
|
| 391 |
+
if chunk_dir.is_dir():
|
| 392 |
+
for child in chunk_dir.iterdir():
|
| 393 |
+
if child.suffix != ".parquet":
|
| 394 |
+
continue
|
| 395 |
+
ok = _parquet_ok(child)
|
| 396 |
+
file_ok[child] = ok
|
| 397 |
+
any_ok = any_ok or ok
|
| 398 |
+
chunk_ok[chunk] = any_ok
|
| 399 |
+
else:
|
| 400 |
+
sample_path = None
|
| 401 |
+
if chunk_dir.is_dir():
|
| 402 |
+
for child in chunk_dir.iterdir():
|
| 403 |
+
if child.suffix == ".parquet":
|
| 404 |
+
sample_path = child
|
| 405 |
+
break
|
| 406 |
+
chunk_ok[chunk] = bool(sample_path and _parquet_ok(sample_path))
|
| 407 |
+
|
| 408 |
+
# Also filter per-episode by parquet existence ("cleaned"
|
| 409 |
+
# datasets sometimes keep the episodes.jsonl entry but delete
|
| 410 |
+
# the parquet) and, under per-file validation, by whether that
|
| 411 |
+
# specific parquet passed β otherwise file_ok would go unused
|
| 412 |
+
# and a bad file in an OK chunk would slip through.
|
| 413 |
+
import re as _re
|
| 414 |
+
_ep_re = _re.compile(r"episode_(\d+)")
|
| 415 |
+
existing_ep_indices: set[int] = set()
|
| 416 |
+
for _chunk, _ok in chunk_ok.items():
|
| 417 |
+
if not _ok:
|
| 418 |
+
continue
|
| 419 |
+
_chunk_dir = self.data_root / f"chunk-{_chunk:03d}"
|
| 420 |
+
if not _chunk_dir.is_dir():
|
| 421 |
+
continue
|
| 422 |
+
for _child in _chunk_dir.iterdir():
|
| 423 |
+
if _child.suffix != ".parquet":
|
| 424 |
+
continue
|
| 425 |
+
if _validate_per_file and not file_ok.get(_child, False):
|
| 426 |
+
continue
|
| 427 |
+
_m = _ep_re.match(_child.stem)
|
| 428 |
+
if _m:
|
| 429 |
+
existing_ep_indices.add(int(_m.group(1)))
|
| 430 |
+
|
| 431 |
+
# Persist to disk for subsequent adapter inits on the same repo.
|
| 432 |
+
_save_scan_cache(
|
| 433 |
+
self.meta_root, cache_key, chunk_ok, existing_ep_indices,
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
keep_eps: list[dict] = []
|
| 437 |
+
dropped = 0
|
| 438 |
+
for ep in self._episodes:
|
| 439 |
+
chunk = int(ep.get("episode_index", 0)) // self._chunks_size
|
| 440 |
+
if chunk_ok.get(chunk, False):
|
| 441 |
+
keep_eps.append(ep)
|
| 442 |
+
else:
|
| 443 |
+
dropped += 1
|
| 444 |
+
|
| 445 |
+
before_existence = len(keep_eps)
|
| 446 |
+
keep_eps = [
|
| 447 |
+
ep for ep in keep_eps
|
| 448 |
+
if int(ep.get("episode_index", -1)) in existing_ep_indices
|
| 449 |
+
]
|
| 450 |
+
missing_parquets = before_existence - len(keep_eps)
|
| 451 |
+
if missing_parquets:
|
| 452 |
+
logger.warning(
|
| 453 |
+
"[v21-adapter] %s: dropped %d additional episodes whose "
|
| 454 |
+
"parquet file is missing on disk (e.g. 'episode_%06d.parquet' "
|
| 455 |
+
"absent from data/chunk-*/)",
|
| 456 |
+
repo_id,
|
| 457 |
+
missing_parquets,
|
| 458 |
+
next(
|
| 459 |
+
(int(ep.get("episode_index", 0)) for ep in self._episodes
|
| 460 |
+
if int(ep.get("episode_index", -1)) not in existing_ep_indices
|
| 461 |
+
and int(ep.get("episode_index", 0)) // self._chunks_size in chunk_ok
|
| 462 |
+
and chunk_ok[int(ep.get("episode_index", 0)) // self._chunks_size]),
|
| 463 |
+
0,
|
| 464 |
+
),
|
| 465 |
+
)
|
| 466 |
+
dropped += missing_parquets
|
| 467 |
+
|
| 468 |
+
if dropped:
|
| 469 |
+
# Key on (repo_id, tuple(needed)) so a second repo with the
|
| 470 |
+
# same missing columns still emits once.
|
| 471 |
+
from src.utils.logging_utils import warn_once
|
| 472 |
+
warn_once(
|
| 473 |
+
logger,
|
| 474 |
+
("repo_col_drop", repo_id, tuple(needed)),
|
| 475 |
+
"[v21-adapter] %s: dropped %d/%d episodes lacking "
|
| 476 |
+
"schema-required columns (%s)",
|
| 477 |
+
repo_id, dropped, len(self._episodes), needed,
|
| 478 |
+
)
|
| 479 |
+
self._episodes = keep_eps
|
| 480 |
+
self._ep_starts, self._ep_lens = _ep_starts_lens(self._episodes)
|
| 481 |
+
|
| 482 |
+
def _finalize_meta_and_caches(self, stats, schema) -> None:
|
| 483 |
+
"""Phase 4: feature/camera key extraction, fps gate, DatasetMeta,
|
| 484 |
+
video/parquet caches, shared counters."""
|
| 485 |
+
info = self._info
|
| 486 |
+
repo_id = self.repo_id
|
| 487 |
+
|
| 488 |
+
feats = info.get("features", {}) or {}
|
| 489 |
+
video_keys = [
|
| 490 |
+
k for k, val in feats.items()
|
| 491 |
+
if isinstance(val, dict) and val.get("dtype") == "video"
|
| 492 |
+
]
|
| 493 |
+
# dtype=image (PNG-in-parquet) cameras: datasets like
|
| 494 |
+
# LabUtopia/Level3_open_old ship images embedded in parquet, not as
|
| 495 |
+
# mp4. The base __getitem__ decodes them inline via self._image_keys.
|
| 496 |
+
# v21 reads full parquet (no projection), so image columns are already
|
| 497 |
+
# included.
|
| 498 |
+
image_keys = [
|
| 499 |
+
k for k, val in feats.items()
|
| 500 |
+
if isinstance(val, dict) and val.get("dtype") == "image"
|
| 501 |
+
]
|
| 502 |
+
self._image_keys = tuple(image_keys)
|
| 503 |
+
|
| 504 |
+
# Frame-index boundaries per episode β consumed by MultiLeRobotDataset
|
| 505 |
+
# to build cross-repo combined indexing.
|
| 506 |
+
_ep_ends = self._ep_starts + self._ep_lens
|
| 507 |
+
# Fail loudly if 'fps' is missing/non-numeric: a silent default of 10
|
| 508 |
+
# produced wrong delta_timestamps on 30fps videos (~3x drift per chunk).
|
| 509 |
+
_raw_fps = info.get("fps")
|
| 510 |
+
if _raw_fps is None:
|
| 511 |
+
raise ValueError(
|
| 512 |
+
f"info.json at {repo_id} missing required 'fps' field. "
|
| 513 |
+
f"Set it explicitly in meta/info.json."
|
| 514 |
+
)
|
| 515 |
+
if not isinstance(_raw_fps, (int, float)) or isinstance(_raw_fps, bool):
|
| 516 |
+
raise TypeError(
|
| 517 |
+
f"info.json fps must be int or float, got {type(_raw_fps).__name__}: {_raw_fps!r}"
|
| 518 |
+
)
|
| 519 |
+
self.meta = DatasetMeta(
|
| 520 |
+
robot_type=info.get("robot_type"),
|
| 521 |
+
stats=stats if stats else None,
|
| 522 |
+
fps=float(_raw_fps),
|
| 523 |
+
total_episodes=len(self._episodes),
|
| 524 |
+
total_frames=int(self._ep_lens.sum()),
|
| 525 |
+
features=feats,
|
| 526 |
+
video_keys=video_keys,
|
| 527 |
+
# camera_keys = full set (mp4 video + PNG-in-parquet image);
|
| 528 |
+
# video_keys alone is empty for image-only datasets.
|
| 529 |
+
camera_keys=list(video_keys) + list(image_keys),
|
| 530 |
+
schema=schema,
|
| 531 |
+
episodes={
|
| 532 |
+
"dataset_from_index": self._ep_starts.astype(int).tolist(),
|
| 533 |
+
"dataset_to_index": _ep_ends.astype(int).tolist(),
|
| 534 |
+
},
|
| 535 |
+
)
|
| 536 |
+
logger.info(
|
| 537 |
+
"[v21-adapter] %s: %d episodes, %d frames, %d video_cameras, "
|
| 538 |
+
"%d image_cameras, schema=%s",
|
| 539 |
+
repo_id, self.meta.total_episodes, self.meta.total_frames,
|
| 540 |
+
len(video_keys), len(image_keys),
|
| 541 |
+
getattr(schema, "schema_id", None),
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
# Warn once per (repo, horizon) if the longest offset clips past most
|
| 545 |
+
# of the shortest episode. Cheap; does not change clip behavior.
|
| 546 |
+
self._validate_delta_timestamps_frame_aligned()
|
| 547 |
+
self._validate_delta_timestamps_vs_episode_lens()
|
| 548 |
+
|
| 549 |
+
# Hook into the process-wide PyAV container LRU (shared with v30):
|
| 550 |
+
# consecutive frames in one episode reuse the cached container instead
|
| 551 |
+
# of paying a fresh av.open+seek+close per frame.
|
| 552 |
+
self._video_cache = _get_shared_video_cache()
|
| 553 |
+
self._video_cache_owner_id = id(self)
|
| 554 |
+
|
| 555 |
+
# Fork-shared zero-frame fallback counter (must exist before DataLoader
|
| 556 |
+
# workers fork so worker increments reach the main process).
|
| 557 |
+
self._init_zero_frame_shared()
|
| 558 |
+
|
| 559 |
+
# Per-INSTANCE parquet LRU. A class-level @lru_cache on the method keyed
|
| 560 |
+
# (self, ep_idx) would make all adapters in a mixture share ONE 8-slot
|
| 561 |
+
# cache (near-zero hit rate at 60+ adapters) and retain strong `self`
|
| 562 |
+
# references. Binding lru_cache to the instance gives each adapter its
|
| 563 |
+
# own 8-slot window. Fork-only DataLoader workers inherit the bound
|
| 564 |
+
# wrapper without pickling.
|
| 565 |
+
self._cached_ep_parquet = lru_cache(maxsize=8)(self._load_ep_parquet_uncached)
|
| 566 |
+
|
| 567 |
+
def _close_video_containers(self) -> None:
|
| 568 |
+
"""Best-effort flush of cached PyAV containers (used at adapter teardown).
|
| 569 |
+
|
| 570 |
+
Drops only entries owned by this adapter from the shared cache;
|
| 571 |
+
other adapters in the same worker keep their entries.
|
| 572 |
+
"""
|
| 573 |
+
try:
|
| 574 |
+
self._video_cache.drop_owner(self._video_cache_owner_id)
|
| 575 |
+
except Exception:
|
| 576 |
+
pass
|
| 577 |
+
|
| 578 |
+
def __del__(self):
|
| 579 |
+
try:
|
| 580 |
+
self._close_video_containers()
|
| 581 |
+
except Exception:
|
| 582 |
+
pass
|
| 583 |
+
|
| 584 |
+
# ---- format-specific I/O hooks (overrides LeRobotAdapterBase) ----
|
| 585 |
+
|
| 586 |
+
# maxsize=8 (bound per-instance in __init__): each adapter holds an
|
| 587 |
+
# independent cache, so larger values multiply parquet residency across
|
| 588 |
+
# adaptersΓranksΓworkers. 8 covers the typical consecutive-episode window.
|
| 589 |
+
def _load_ep_parquet_uncached(self, ep_idx: int) -> pd.DataFrame:
|
| 590 |
+
chunk = ep_idx // self._chunks_size
|
| 591 |
+
p = self.data_root / f"chunk-{chunk:03d}" / f"episode_{ep_idx:06d}.parquet"
|
| 592 |
+
return read_parquet_with_storage_retry(p)
|
| 593 |
+
|
| 594 |
+
def _load_ep_parquet(self, ep_idx: int) -> pd.DataFrame:
|
| 595 |
+
return self._cached_ep_parquet(ep_idx).copy()
|
| 596 |
+
|
| 597 |
+
def _read_video_frame(self, ep_idx: int, vkey: str, frame: int) -> torch.Tensor:
|
| 598 |
+
"""Read a single mp4 frame using keyframe seek + short forward decode.
|
| 599 |
+
|
| 600 |
+
Decoding from frame 0 is O(frame_index) and saturates CPU/IO at scale.
|
| 601 |
+
Instead, seek to the nearest keyframe <= target and forward-decode a
|
| 602 |
+
handful of frames: O(keyframe_interval), ~3-6x faster, pixel-identical.
|
| 603 |
+
The opened container is kept in the process-wide cache so consecutive
|
| 604 |
+
frames in one chunk reuse it (50x fewer av.open calls).
|
| 605 |
+
"""
|
| 606 |
+
chunk = ep_idx // self._chunks_size
|
| 607 |
+
p = self.video_root / f"chunk-{chunk:03d}" / vkey / f"episode_{ep_idx:06d}.mp4"
|
| 608 |
+
if not storage_path_exists(p):
|
| 609 |
+
# Missing video is common in multi-robot merges (differing camera
|
| 610 |
+
# layouts); return a black frame for the model to treat as padding.
|
| 611 |
+
return self._zero_frame(reason="missing_file")
|
| 612 |
+
import av
|
| 613 |
+
|
| 614 |
+
full_key = (self._video_cache_owner_id, vkey, ep_idx)
|
| 615 |
+
video_cache = self._video_cache
|
| 616 |
+
|
| 617 |
+
def _drop_cached_container(_exc, _attempt) -> None:
|
| 618 |
+
cached_container = video_cache.pop(full_key)
|
| 619 |
+
if cached_container is not None:
|
| 620 |
+
try:
|
| 621 |
+
cached_container[0].close()
|
| 622 |
+
except Exception:
|
| 623 |
+
pass
|
| 624 |
+
|
| 625 |
+
def _decode_once():
|
| 626 |
+
cached = video_cache.get(full_key)
|
| 627 |
+
if cached is None:
|
| 628 |
+
container = av.open(str(p))
|
| 629 |
+
stream = container.streams.video[0]
|
| 630 |
+
# thread_type "AUTO" hits a pyav/libav internal futex deadlock
|
| 631 |
+
# at 128-process scale (each with its own thread pool). Episode
|
| 632 |
+
# mp4s are short, so single-threaded decode is fine and safe.
|
| 633 |
+
stream.thread_type = "NONE"
|
| 634 |
+
stream.thread_count = 1
|
| 635 |
+
# LRU eviction (closes evicted container) handled inside .put().
|
| 636 |
+
video_cache.put(full_key, (container, stream))
|
| 637 |
+
else:
|
| 638 |
+
container, stream = cached
|
| 639 |
+
|
| 640 |
+
# Exact Fraction frame arithmetic (mirrors the v30 adapter). A float
|
| 641 |
+
# `round(pts*tb*fps)` mapping can skip the target frame on
|
| 642 |
+
# non-integer average_rate / VFR streams and silently fall back to a
|
| 643 |
+
# zero frame (reason=index_overshoot).
|
| 644 |
+
fps_frac = Fraction(stream.average_rate) if stream.average_rate else Fraction(30)
|
| 645 |
+
fps = float(fps_frac)
|
| 646 |
+
tb = stream.time_base # e.g. 1/15360 for 30 fps
|
| 647 |
+
|
| 648 |
+
# Seek to the nearest keyframe <= target; on failure (malformed
|
| 649 |
+
# mp4) fall through to linear decode.
|
| 650 |
+
target_pts = int(frame / fps / tb) if tb else 0
|
| 651 |
+
try:
|
| 652 |
+
container.seek(target_pts, stream=stream)
|
| 653 |
+
except av.AVError as e:
|
| 654 |
+
# Log (once per path) so genuine corruption surfaces instead of
|
| 655 |
+
# silently degrading to O(frame) decode.
|
| 656 |
+
logger.warning(
|
| 657 |
+
"[v21-adapter] seek failed for ep=%s key=%s frame=%s pts=%s: %s; "
|
| 658 |
+
"falling back to linear decode",
|
| 659 |
+
ep_idx, vkey, frame, target_pts, e,
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
# Forward-decode from the keyframe to the exact frame.
|
| 663 |
+
for f in container.decode(stream):
|
| 664 |
+
if f.pts is None:
|
| 665 |
+
continue
|
| 666 |
+
cur = round(f.pts * tb * fps_frac) # exact Fraction math
|
| 667 |
+
if cur < frame:
|
| 668 |
+
continue # still catching up from keyframe
|
| 669 |
+
if cur > frame:
|
| 670 |
+
break # overshoot (shouldn't happen with backward seek)
|
| 671 |
+
img = f.to_ndarray(format="rgb24")
|
| 672 |
+
t = torch.from_numpy(img).permute(2, 0, 1).contiguous().float() / 255.0
|
| 673 |
+
if self.image_transforms is not None:
|
| 674 |
+
apply_seeded = getattr(self.image_transforms, "apply_with_seed", None)
|
| 675 |
+
if callable(apply_seeded):
|
| 676 |
+
t = apply_seeded(t, seed_parts=(self.repo_id, ep_idx, vkey, frame))
|
| 677 |
+
else:
|
| 678 |
+
t = self.image_transforms(t)
|
| 679 |
+
return t
|
| 680 |
+
return None
|
| 681 |
+
|
| 682 |
+
try:
|
| 683 |
+
decoded = run_with_storage_retry(
|
| 684 |
+
_decode_once,
|
| 685 |
+
path=p,
|
| 686 |
+
description="v21 video decode",
|
| 687 |
+
on_retry=_drop_cached_container,
|
| 688 |
+
)
|
| 689 |
+
if decoded is not None:
|
| 690 |
+
return decoded
|
| 691 |
+
except Exception as e:
|
| 692 |
+
# Drop the cached container on error; it may be in a bad state.
|
| 693 |
+
cached = video_cache.pop(full_key)
|
| 694 |
+
if cached is not None:
|
| 695 |
+
try:
|
| 696 |
+
cached[0].close()
|
| 697 |
+
except Exception:
|
| 698 |
+
pass
|
| 699 |
+
logger.warning("[v21-adapter] video decode failed for %s (%s); "
|
| 700 |
+
"returning zero frame.", p, e)
|
| 701 |
+
return self._zero_frame(reason="decode_error")
|
| 702 |
+
# Frame past end or seek mis-aligned: drop the cached container (its
|
| 703 |
+
# cursor is past `frame`, so reopen next call) and pad with zero.
|
| 704 |
+
cached = video_cache.pop(full_key)
|
| 705 |
+
if cached is not None:
|
| 706 |
+
try:
|
| 707 |
+
cached[0].close()
|
| 708 |
+
except Exception:
|
| 709 |
+
pass
|
| 710 |
+
return self._zero_frame(reason="index_overshoot")
|
src/adapters/lerobot_v30.py
ADDED
|
@@ -0,0 +1,942 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LeRobot v3.0 dataset adapter.
|
| 2 |
+
|
| 3 |
+
v3.0 layout (vs v2.1):
|
| 4 |
+
<root>/meta/info.json (codebase_version="v3.0")
|
| 5 |
+
<root>/meta/episodes/chunk-XXX/file-NNN.parquet (per-episode indexing + stats)
|
| 6 |
+
<root>/meta/tasks.parquet (task_index β task string)
|
| 7 |
+
<root>/meta/stats.json (global dataset stats β same format as v2.1)
|
| 8 |
+
<root>/data/chunk-XXX/file-NNN.parquet (shard: many episodes per file)
|
| 9 |
+
<root>/videos/<cam>/chunk-XXX/file-NNN.mp4 (shard: many episodes per file)
|
| 10 |
+
|
| 11 |
+
Key difference: v3 packs many episodes into each shard. Per-episode row
|
| 12 |
+
range is in the episodes meta parquet as `dataset_from_index / dataset_to_index`
|
| 13 |
+
β the adapter opens the shard, slices to those rows, and hands a standard
|
| 14 |
+
per-episode `pd.DataFrame` to the shared transformation logic.
|
| 15 |
+
|
| 16 |
+
Shares `LeRobotAdapterBase`'s per-frame transformation pipeline (padding,
|
| 17 |
+
task resolution, delta-timestamp expansion) via inheritance; only the
|
| 18 |
+
three format-specific methods are defined locally:
|
| 19 |
+
1. __init__ β reads episodes.parquet + tasks.parquet
|
| 20 |
+
2. _load_ep_parquet β slices a shard
|
| 21 |
+
3. _read_video_frame β opens a packed mp4 with from_timestamp offset
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import logging
|
| 27 |
+
from collections import OrderedDict
|
| 28 |
+
from fractions import Fraction
|
| 29 |
+
from functools import lru_cache
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
import pandas as pd
|
| 34 |
+
import pyarrow as pa
|
| 35 |
+
import pyarrow.parquet as pq
|
| 36 |
+
import torch
|
| 37 |
+
|
| 38 |
+
from .base import DatasetMeta
|
| 39 |
+
from .lerobot_base import (
|
| 40 |
+
LeRobotAdapterBase,
|
| 41 |
+
_ep_starts_lens,
|
| 42 |
+
_get_shared_video_cache,
|
| 43 |
+
)
|
| 44 |
+
# Task-text heuristics are unified in schema/task_text.
|
| 45 |
+
from src.schema.task_text import normalize_tasks as _normalize_tasks_unified
|
| 46 |
+
from src.utils.storage_retry import (
|
| 47 |
+
read_parquet_with_storage_retry,
|
| 48 |
+
run_with_storage_retry,
|
| 49 |
+
storage_path_exists,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
logger = logging.getLogger(__name__)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _is_missing_scalar(value) -> bool:
|
| 56 |
+
try:
|
| 57 |
+
return bool(pd.isna(value))
|
| 58 |
+
except (TypeError, ValueError):
|
| 59 |
+
return False
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _read_episodes_parquet_v3(meta_root: Path) -> list[dict]:
|
| 63 |
+
"""Concat meta/episodes/chunk-*/file-*.parquet β list of per-episode dicts.
|
| 64 |
+
|
| 65 |
+
Kept columns (everything we need for slicing + video seek):
|
| 66 |
+
episode_index, length, tasks,
|
| 67 |
+
data/chunk_index, data/file_index, dataset_from_index, dataset_to_index,
|
| 68 |
+
videos/<cam>/chunk_index, videos/<cam>/file_index,
|
| 69 |
+
videos/<cam>/from_timestamp, videos/<cam>/to_timestamp
|
| 70 |
+
"""
|
| 71 |
+
ep_root = meta_root / "episodes"
|
| 72 |
+
if not ep_root.is_dir():
|
| 73 |
+
raise FileNotFoundError(f"v3 meta/episodes dir missing at {ep_root}")
|
| 74 |
+
paths = sorted(ep_root.rglob("*.parquet"))
|
| 75 |
+
if not paths:
|
| 76 |
+
raise FileNotFoundError(f"No episode parquets under {ep_root}")
|
| 77 |
+
|
| 78 |
+
# Go through pandas for heterogeneous-schema-safe concat: merged
|
| 79 |
+
# oxe-auge_clean has differing camera-key-sets and two `tasks` column types
|
| 80 |
+
# (list<string> vs list<list<int>>). pa.concat_tables can't union these;
|
| 81 |
+
# pd.concat(sort=False) can.
|
| 82 |
+
dfs_with_paths = [
|
| 83 |
+
(
|
| 84 |
+
p,
|
| 85 |
+
run_with_storage_retry(
|
| 86 |
+
lambda _p=p: pq.read_table(_p).to_pandas(),
|
| 87 |
+
path=p,
|
| 88 |
+
description="read v3 episodes parquet",
|
| 89 |
+
),
|
| 90 |
+
)
|
| 91 |
+
for p in paths
|
| 92 |
+
]
|
| 93 |
+
dfs = [df for _, df in dfs_with_paths]
|
| 94 |
+
|
| 95 |
+
def _normalize_tasks(val):
|
| 96 |
+
# Normalize the `tasks` column so it's always VLM-tokenizable.
|
| 97 |
+
# list<string> / scalar pass through unchanged. Tokenized
|
| 98 |
+
# (list<list<int>>) tasks fail-loud by default (coercing to repr would
|
| 99 |
+
# train the VLM on digit strings); LABVLA_ALLOW_TOKENIZED_TASK_COERCION=1
|
| 100 |
+
# restores the legacy coercion for inspection only.
|
| 101 |
+
#
|
| 102 |
+
# Exception: OXE `language_table_*` stores strings as NUL-padded ASCII
|
| 103 |
+
# byte arrays (TFDS idiom), not tokenizer output β the unified
|
| 104 |
+
# heuristic (schema/task_text) decodes those BEFORE the raise. The env
|
| 105 |
+
# flag is read per call; the shared code takes the policy as an
|
| 106 |
+
# explicit parameter.
|
| 107 |
+
from src.utils import env_flags as _env_flags
|
| 108 |
+
return _normalize_tasks_unified(
|
| 109 |
+
val,
|
| 110 |
+
allow_tokenized_coercion=(
|
| 111 |
+
_env_flags.get("LABVLA_ALLOW_TOKENIZED_TASK_COERCION") == "1"
|
| 112 |
+
),
|
| 113 |
+
undecodable_msg=(
|
| 114 |
+
"v30 adapter: encountered a tokenized (list<int>) "
|
| 115 |
+
"task element. Coercing it to str() would train the "
|
| 116 |
+
"VLM on digit strings rather than language. Either "
|
| 117 |
+
"decode the tokens back to text in the upstream "
|
| 118 |
+
"dataset, exclude tokenized-task shards from "
|
| 119 |
+
"training, or set "
|
| 120 |
+
"LABVLA_ALLOW_TOKENIZED_TASK_COERCION=1 for a "
|
| 121 |
+
"best-effort inspection-only run."
|
| 122 |
+
),
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# Warn loud when heterogeneous `tasks` column types are detected, naming the
|
| 126 |
+
# shards with tokenized (list<list<int>>) tasks so the operator can
|
| 127 |
+
# spot-check before training.
|
| 128 |
+
tokenized_paths: list[Path] = []
|
| 129 |
+
for p, df in dfs_with_paths:
|
| 130 |
+
if "tasks" not in df.columns:
|
| 131 |
+
continue
|
| 132 |
+
sample = next((v for v in df["tasks"].values if v is not None), None)
|
| 133 |
+
if isinstance(sample, (list, np.ndarray)) and len(sample) > 0:
|
| 134 |
+
first = sample[0]
|
| 135 |
+
if isinstance(first, (list, np.ndarray)):
|
| 136 |
+
tokenized_paths.append(p)
|
| 137 |
+
if tokenized_paths:
|
| 138 |
+
from src.utils.logging_utils import warn_once
|
| 139 |
+
# Heads-up that _normalize_tasks will raise at first read unless
|
| 140 |
+
# LABVLA_ALLOW_TOKENIZED_TASK_COERCION=1.
|
| 141 |
+
warn_once(
|
| 142 |
+
logger,
|
| 143 |
+
("v30_tasks_heterogeneous", tuple(str(p) for p in tokenized_paths)),
|
| 144 |
+
"[v30-adapter] Heterogeneous tasks column type detected β %d "
|
| 145 |
+
"shard(s) contain tokenized (list<list<int>>) tasks while others "
|
| 146 |
+
"contain list<string>. These will FAIL LOUD on first read; set "
|
| 147 |
+
"LABVLA_ALLOW_TOKENIZED_TASK_COERCION=1 to fall back to legacy "
|
| 148 |
+
"str() coercion (inspection-only β VLM should not be trained on "
|
| 149 |
+
"the resulting digit strings). Affected paths: %s",
|
| 150 |
+
len(tokenized_paths),
|
| 151 |
+
", ".join(str(p) for p in tokenized_paths[:5])
|
| 152 |
+
+ (" ..." if len(tokenized_paths) > 5 else ""),
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
for df in dfs:
|
| 156 |
+
if "tasks" in df.columns:
|
| 157 |
+
df["tasks"] = df["tasks"].map(_normalize_tasks)
|
| 158 |
+
|
| 159 |
+
df = pd.concat(dfs, axis=0, ignore_index=True, sort=False)
|
| 160 |
+
table = pa.Table.from_pandas(df, preserve_index=False)
|
| 161 |
+
|
| 162 |
+
# Keep `videos/<cam>/β¦` columns verbatim for _read_video_frame; drop
|
| 163 |
+
# `stats/<feature>/*` (per-episode stats the adapter doesn't use).
|
| 164 |
+
keep_prefix = (
|
| 165 |
+
"episode_index", "length", "tasks",
|
| 166 |
+
"data/", "dataset_from_index", "dataset_to_index",
|
| 167 |
+
"videos/",
|
| 168 |
+
)
|
| 169 |
+
keep_cols = [c for c in table.schema.names if any(
|
| 170 |
+
c == p or c.startswith(p) for p in keep_prefix
|
| 171 |
+
)]
|
| 172 |
+
sub = table.select(keep_cols).to_pandas()
|
| 173 |
+
out = [row.to_dict() for _, row in sub.iterrows()]
|
| 174 |
+
# tasks is list<str> (np.ndarray from pandas); take the first (per-ep task).
|
| 175 |
+
for e in out:
|
| 176 |
+
tk = e.get("tasks")
|
| 177 |
+
if isinstance(tk, (list, np.ndarray)) and len(tk) > 0:
|
| 178 |
+
e["task"] = str(tk[0])
|
| 179 |
+
else:
|
| 180 |
+
e["task"] = ""
|
| 181 |
+
out.sort(key=lambda e: int(e["episode_index"]))
|
| 182 |
+
return out
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _read_tasks_parquet_v3(tasks_path: Path) -> dict[int, str]:
|
| 186 |
+
"""Parse meta/tasks.parquet β {task_index: task_string}.
|
| 187 |
+
|
| 188 |
+
Observed conversion variants:
|
| 189 |
+
(a) columns = {"task_index": int64, "task": string}
|
| 190 |
+
(b) task string as the DataFrame index (`__index_level_0__` in pyarrow),
|
| 191 |
+
`task_index: int64` as a column.
|
| 192 |
+
Handle both.
|
| 193 |
+
"""
|
| 194 |
+
if not storage_path_exists(tasks_path):
|
| 195 |
+
return {}
|
| 196 |
+
table = run_with_storage_retry(
|
| 197 |
+
lambda: pq.read_table(tasks_path),
|
| 198 |
+
path=tasks_path,
|
| 199 |
+
description="read v3 tasks parquet",
|
| 200 |
+
)
|
| 201 |
+
df = table.to_pandas()
|
| 202 |
+
if "task" in df.columns and "task_index" in df.columns:
|
| 203 |
+
return {int(r["task_index"]): str(r["task"]) for _, r in df.iterrows()}
|
| 204 |
+
# Variant (b): task string is df.index, task_index is a column.
|
| 205 |
+
if "task_index" in df.columns:
|
| 206 |
+
return {int(r["task_index"]): str(idx) for idx, r in df.iterrows()}
|
| 207 |
+
logger.warning("[v30-adapter] unexpected tasks.parquet schema: cols=%s", list(df.columns))
|
| 208 |
+
return {}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _shard_ok_v30(
|
| 214 |
+
ci: int,
|
| 215 |
+
fi: int,
|
| 216 |
+
*,
|
| 217 |
+
data_root: Path,
|
| 218 |
+
needed: list,
|
| 219 |
+
alt: dict,
|
| 220 |
+
shard_span: dict,
|
| 221 |
+
declared_dim: dict,
|
| 222 |
+
check_overwide: bool,
|
| 223 |
+
repo_id: str,
|
| 224 |
+
) -> bool:
|
| 225 |
+
"""Schema-satisfies check for one v3 data shard.
|
| 226 |
+
|
| 227 |
+
Checks: required columns (with v2.1 alt fallback), row-span sufficiency,
|
| 228 |
+
and an overwide first-row probe.
|
| 229 |
+
"""
|
| 230 |
+
p = data_root / f"chunk-{ci:03d}" / f"file-{fi:03d}.parquet"
|
| 231 |
+
if not p.exists():
|
| 232 |
+
return False
|
| 233 |
+
try:
|
| 234 |
+
pf = pq.ParquetFile(str(p))
|
| 235 |
+
cols = set(pf.schema_arrow.names)
|
| 236 |
+
except Exception:
|
| 237 |
+
return False
|
| 238 |
+
resolved: dict[str, str] = {}
|
| 239 |
+
for k in needed:
|
| 240 |
+
if k in cols:
|
| 241 |
+
resolved[k] = k
|
| 242 |
+
continue
|
| 243 |
+
a = alt.get(k, None)
|
| 244 |
+
if a in cols:
|
| 245 |
+
resolved[k] = a
|
| 246 |
+
continue
|
| 247 |
+
return False
|
| 248 |
+
# The shard must hold enough rows for every episode slice it
|
| 249 |
+
# serves; otherwise _load_ep_parquet's iloc would return short
|
| 250 |
+
# frames β IndexError mid-training.
|
| 251 |
+
span = shard_span.get((ci, fi))
|
| 252 |
+
if span is not None:
|
| 253 |
+
try:
|
| 254 |
+
n_rows = int(pf.metadata.num_rows)
|
| 255 |
+
except Exception:
|
| 256 |
+
return False
|
| 257 |
+
need_rows = span[1] - span[0]
|
| 258 |
+
if n_rows < need_rows:
|
| 259 |
+
logger.warning(
|
| 260 |
+
"[v30-adapter] %s: shard %s has %d rows but "
|
| 261 |
+
"meta/episodes requires %d (span [%d, %d)) β "
|
| 262 |
+
"dropping shard (meta/data inconsistency).",
|
| 263 |
+
repo_id, p.name, n_rows, need_rows, span[0], span[1],
|
| 264 |
+
)
|
| 265 |
+
return False
|
| 266 |
+
# Overwide-column probe on the first row.
|
| 267 |
+
if check_overwide and declared_dim:
|
| 268 |
+
try:
|
| 269 |
+
probe_cols = [
|
| 270 |
+
resolved[k] for k in declared_dim if k in resolved
|
| 271 |
+
]
|
| 272 |
+
if probe_cols and pf.metadata.num_row_groups > 0:
|
| 273 |
+
head = pf.read_row_group(0, columns=probe_cols)
|
| 274 |
+
if len(head) > 0:
|
| 275 |
+
for k in declared_dim:
|
| 276 |
+
if k not in resolved:
|
| 277 |
+
continue
|
| 278 |
+
raw0 = head.column(resolved[k])[0].as_py()
|
| 279 |
+
if (isinstance(raw0, (list, tuple))
|
| 280 |
+
and len(raw0) > declared_dim[k]):
|
| 281 |
+
logger.warning(
|
| 282 |
+
"[v30-adapter] %s: shard %s column "
|
| 283 |
+
"%r is %d-wide > declared %d β "
|
| 284 |
+
"dropping shard (set "
|
| 285 |
+
"LABVLA_ALLOW_TRUNCATE=1 to keep "
|
| 286 |
+
"and truncate).",
|
| 287 |
+
repo_id, p.name, resolved[k],
|
| 288 |
+
len(raw0), declared_dim[k],
|
| 289 |
+
)
|
| 290 |
+
return False
|
| 291 |
+
except Exception:
|
| 292 |
+
return False
|
| 293 |
+
return True
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class LeRobotV30Adapter(LeRobotAdapterBase):
|
| 297 |
+
"""Adapter for LeRobot v3.0 shard-packed datasets.
|
| 298 |
+
|
| 299 |
+
Inherits the shared per-frame transformation pipeline
|
| 300 |
+
(``__getitem__``, row-padding, task resolution, delta-timestamp
|
| 301 |
+
expansion, CRIT-05 ``_is_pad`` postcondition, zero-frame fallback)
|
| 302 |
+
from ``LeRobotAdapterBase`` and overrides only the format-specific
|
| 303 |
+
I/O hooks: ``_load_ep_parquet`` (slices a shard) and
|
| 304 |
+
``_read_video_frame`` (reads a packed mp4 with ``from_timestamp``
|
| 305 |
+
offset).
|
| 306 |
+
"""
|
| 307 |
+
|
| 308 |
+
def __init__(
|
| 309 |
+
self,
|
| 310 |
+
repo_id: str,
|
| 311 |
+
root: str | Path,
|
| 312 |
+
delta_timestamps: dict | None = None,
|
| 313 |
+
image_transforms=None,
|
| 314 |
+
external_stats: dict | None = None,
|
| 315 |
+
override_schema=None,
|
| 316 |
+
video_backend: str = "pyav",
|
| 317 |
+
episode_filter: list[int] | tuple[int, ...] | None = None,
|
| 318 |
+
):
|
| 319 |
+
"""See LeRobotV21Adapter for episode_filter semantics.
|
| 320 |
+
|
| 321 |
+
__init__ is a thin orchestrator over the four phase methods below.
|
| 322 |
+
"""
|
| 323 |
+
self._resolve_root(
|
| 324 |
+
repo_id, root, delta_timestamps, image_transforms, video_backend
|
| 325 |
+
)
|
| 326 |
+
stats, schema = self._load_meta_and_stats(external_stats, override_schema)
|
| 327 |
+
|
| 328 |
+
# Filter episodes whose data shard lacks schema-required columns. In v3
|
| 329 |
+
# a shard shares one schema, so check each unique (chunk, file) once and
|
| 330 |
+
# drop episodes pointing at a failed shard.
|
| 331 |
+
if schema is not None:
|
| 332 |
+
self._filter_episodes_by_schema(schema)
|
| 333 |
+
|
| 334 |
+
# Task-uniform support: restrict to a user-supplied episode subset.
|
| 335 |
+
if episode_filter is not None:
|
| 336 |
+
allowed = {int(i) for i in episode_filter}
|
| 337 |
+
before = len(self._episodes)
|
| 338 |
+
self._episodes = [
|
| 339 |
+
ep for ep in self._episodes
|
| 340 |
+
if int(ep.get("episode_index", -1)) in allowed
|
| 341 |
+
]
|
| 342 |
+
self._ep_starts, self._ep_lens = _ep_starts_lens(self._episodes)
|
| 343 |
+
logger.info(
|
| 344 |
+
"[v30-adapter] %s: episode_filter kept %d/%d episodes",
|
| 345 |
+
repo_id, len(self._episodes), before,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
self._drop_terminal_samples_for_next_frame_actions(schema)
|
| 349 |
+
|
| 350 |
+
self._finalize_meta_and_caches(stats, schema)
|
| 351 |
+
|
| 352 |
+
# ---- __init__ phase methods --------------------------------------------
|
| 353 |
+
|
| 354 |
+
def _resolve_root(
|
| 355 |
+
self,
|
| 356 |
+
repo_id: str,
|
| 357 |
+
root: str | Path,
|
| 358 |
+
delta_timestamps: dict | None,
|
| 359 |
+
image_transforms,
|
| 360 |
+
video_backend: str,
|
| 361 |
+
) -> None:
|
| 362 |
+
"""Phase 1: root resolution, info.json version gate, episodes meta +
|
| 363 |
+
length invariant."""
|
| 364 |
+
self.repo_id = repo_id
|
| 365 |
+
root_p = Path(root)
|
| 366 |
+
if root_p.name != Path(repo_id).name and (root_p / repo_id).exists():
|
| 367 |
+
root_p = root_p / repo_id
|
| 368 |
+
self.root = root_p
|
| 369 |
+
self.meta_root = self.root / "meta"
|
| 370 |
+
self.data_root = self.root / "data"
|
| 371 |
+
self.video_root = self.root / "videos"
|
| 372 |
+
self.delta_timestamps = delta_timestamps or {}
|
| 373 |
+
self.image_transforms = image_transforms
|
| 374 |
+
self.video_backend = video_backend
|
| 375 |
+
|
| 376 |
+
with open(self.meta_root / "info.json") as _f:
|
| 377 |
+
info = json.load(_f)
|
| 378 |
+
v = info.get("codebase_version", "")
|
| 379 |
+
if not v.startswith("v3"):
|
| 380 |
+
raise ValueError(
|
| 381 |
+
f"LeRobotV30Adapter: {self.root} is codebase_version={v!r}, "
|
| 382 |
+
f"expected v3.x."
|
| 383 |
+
)
|
| 384 |
+
self._info = info
|
| 385 |
+
# Merged products re-index the global tasks.parquet; per-frame
|
| 386 |
+
# task_index values still carry per-source indices and MUST NOT resolve
|
| 387 |
+
# language through the merged table.
|
| 388 |
+
self._task_index_unreliable = bool(info.get("task_index_remapped", False))
|
| 389 |
+
self._chunks_size = int(info.get("chunks_size", 1000))
|
| 390 |
+
self._episodes = _read_episodes_parquet_v3(self.meta_root)
|
| 391 |
+
|
| 392 |
+
# Enforce `length == dataset_to_index - dataset_from_index`
|
| 393 |
+
# for every episode. This is pure meta arithmetic (zero I/O) and is the
|
| 394 |
+
# invariant the whole indexing path rests on: `_flat_to_ep` samples
|
| 395 |
+
# frame_in_ep β [0, length) while `_load_ep_parquet` slices [from, to).
|
| 396 |
+
# length > (to-from) β IndexError mid-training; length < (to-from) β
|
| 397 |
+
# tail frames silently never sampled. Fail loud at init instead.
|
| 398 |
+
_bad_len = [
|
| 399 |
+
(int(e["episode_index"]), int(e.get("length", -1)),
|
| 400 |
+
int(e["dataset_to_index"]) - int(e["dataset_from_index"]))
|
| 401 |
+
for e in self._episodes
|
| 402 |
+
if int(e.get("length", -1))
|
| 403 |
+
!= int(e["dataset_to_index"]) - int(e["dataset_from_index"])
|
| 404 |
+
]
|
| 405 |
+
if _bad_len:
|
| 406 |
+
_sample = ", ".join(
|
| 407 |
+
f"ep{ei}: length={ln} vs to-from={rng}" for ei, ln, rng in _bad_len[:5]
|
| 408 |
+
)
|
| 409 |
+
raise ValueError(
|
| 410 |
+
f"[v30-adapter] {repo_id}: {len(_bad_len)} episode(s) violate "
|
| 411 |
+
f"length == dataset_to_index - dataset_from_index ({_sample}"
|
| 412 |
+
f"{' ...' if len(_bad_len) > 5 else ''}). meta/episodes is "
|
| 413 |
+
f"internally inconsistent β fix the dataset before training "
|
| 414 |
+
f"(mismatch means either mid-training IndexError or silently "
|
| 415 |
+
f"unsampled tail frames)."
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# Preserve unfiltered episodes for shard offsets: the offset is the
|
| 419 |
+
# minimum dataset_from_index of ANY episode in the shard, since parquet
|
| 420 |
+
# rows are numbered 0..N across all packed episodes (not just filtered).
|
| 421 |
+
self._unfiltered_episodes = list(self._episodes)
|
| 422 |
+
self._ep_starts, self._ep_lens = _ep_starts_lens(self._episodes)
|
| 423 |
+
|
| 424 |
+
def _load_meta_and_stats(self, external_stats: dict | None, override_schema):
|
| 425 |
+
"""Phase 2: tasks index, stats (+ external override), schema
|
| 426 |
+
discovery, next-frame stats patch. Returns ``(stats, schema)``."""
|
| 427 |
+
info = self._info
|
| 428 |
+
|
| 429 |
+
# tasks.parquet β {int: str} (v21 uses tasks.jsonl; same lookup path).
|
| 430 |
+
self._tasks_by_idx = _read_tasks_parquet_v3(self.meta_root / "tasks.parquet")
|
| 431 |
+
|
| 432 |
+
# stats.json β same format across v2.1 and v3.
|
| 433 |
+
stats_path = self.meta_root / "stats.json"
|
| 434 |
+
if stats_path.exists():
|
| 435 |
+
from src.dataset.utils import cast_stats_to_numpy
|
| 436 |
+
with open(stats_path) as _f:
|
| 437 |
+
stats: dict = cast_stats_to_numpy(json.load(_f))
|
| 438 |
+
else:
|
| 439 |
+
stats = {}
|
| 440 |
+
if external_stats:
|
| 441 |
+
stats = {**stats, **external_stats}
|
| 442 |
+
|
| 443 |
+
# Schema discovery (same chain as v21).
|
| 444 |
+
from src.schema import discover_schema, SchemaDiscoveryError
|
| 445 |
+
try:
|
| 446 |
+
schema = discover_schema(
|
| 447 |
+
self.root,
|
| 448 |
+
robot_type=info.get("robot_type"),
|
| 449 |
+
override=override_schema,
|
| 450 |
+
)
|
| 451 |
+
except SchemaDiscoveryError as e:
|
| 452 |
+
if override_schema is not None:
|
| 453 |
+
# The override came from --dataset_schema; discover_schema also
|
| 454 |
+
# VALIDATES it against the on-disk meta (camera mapping,
|
| 455 |
+
# annotation columns, ...). Swallowing the failure here would
|
| 456 |
+
# train on the unvalidated override with only a warning.
|
| 457 |
+
raise
|
| 458 |
+
logger.warning("[v30-adapter] schema discovery failed: %s", e)
|
| 459 |
+
schema = override_schema
|
| 460 |
+
|
| 461 |
+
stats = self.patch_stats_for_next_frame_actions(stats, schema)
|
| 462 |
+
return stats, schema
|
| 463 |
+
|
| 464 |
+
def _filter_episodes_by_schema(self, schema) -> None:
|
| 465 |
+
"""Phase 3: drop episodes whose shard lacks schema-required columns,
|
| 466 |
+
rows, or width envelope (scan-cached; one check per unique shard)."""
|
| 467 |
+
repo_id = self.repo_id
|
| 468 |
+
read_state_keys = (
|
| 469 |
+
tuple(getattr(schema, "source_state_keys", ()) or ())
|
| 470 |
+
or tuple(getattr(schema, "state_keys", ()) or ())
|
| 471 |
+
)
|
| 472 |
+
read_action_keys = (
|
| 473 |
+
tuple(getattr(schema, "source_action_keys", ()) or ())
|
| 474 |
+
or tuple(getattr(schema, "action_keys", ()) or ())
|
| 475 |
+
)
|
| 476 |
+
# _resolve_physical_column also maps virtual state keys to their
|
| 477 |
+
# physical source β a virtual key must never appear in `needed` or
|
| 478 |
+
# every shard would be dropped for "missing" it.
|
| 479 |
+
needed = list(dict.fromkeys(
|
| 480 |
+
self._resolve_physical_column(schema, k)
|
| 481 |
+
for k in (list(read_state_keys) + list(read_action_keys))
|
| 482 |
+
))
|
| 483 |
+
alt = {"observation.state": "state", "action": "actions"}
|
| 484 |
+
|
| 485 |
+
# Per-shard expected row span (min from / max to over ALL episodes in
|
| 486 |
+
# the shard) so _shard_ok can verify the parquet really holds enough
|
| 487 |
+
# rows for every episode slice.
|
| 488 |
+
_shard_span: dict[tuple[int, int], tuple[int, int]] = {}
|
| 489 |
+
for _e in self._episodes:
|
| 490 |
+
_key = (int(_e["data/chunk_index"]), int(_e["data/file_index"]))
|
| 491 |
+
_a = int(_e["dataset_from_index"])
|
| 492 |
+
_b = int(_e["dataset_to_index"])
|
| 493 |
+
_cur = _shard_span.get(_key)
|
| 494 |
+
_shard_span[_key] = (
|
| 495 |
+
(_a, _b) if _cur is None
|
| 496 |
+
else (min(_cur[0], _a), max(_cur[1], _b))
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
# Per-read-key declared dims (SOURCE space when declared, mirroring
|
| 500 |
+
# what the projection actually reads) for the overwide check, matching
|
| 501 |
+
# v21's _parquet_ok. Without it an overwide shard crashes later in
|
| 502 |
+
# _pad_row mid-training instead of being dropped at init. Honors
|
| 503 |
+
# LABVLA_ALLOW_TRUNCATE.
|
| 504 |
+
_rs_dims = (
|
| 505 |
+
tuple(getattr(schema, "source_state_dims", ()) or ())
|
| 506 |
+
or tuple(getattr(schema, "state_dims", ()) or ())
|
| 507 |
+
)
|
| 508 |
+
_ra_dims = (
|
| 509 |
+
tuple(getattr(schema, "source_action_dims", ()) or ())
|
| 510 |
+
or tuple(getattr(schema, "action_dims", ()) or ())
|
| 511 |
+
)
|
| 512 |
+
_declared_dim: dict[str, int] = {}
|
| 513 |
+
for _k, _d in zip(read_state_keys, _rs_dims):
|
| 514 |
+
_declared_dim[_k] = int(_d)
|
| 515 |
+
for _k, _d in zip(read_action_keys, _ra_dims):
|
| 516 |
+
_declared_dim[_k] = int(_d)
|
| 517 |
+
# The overwide probe below resolves `needed` (physical names) β attach
|
| 518 |
+
# each virtual state key's declared dim to its physical source column
|
| 519 |
+
# so the probe still covers it. setdefault: a column with its own
|
| 520 |
+
# schema-declared dim keeps that dim.
|
| 521 |
+
for _vk, _vsrc in (
|
| 522 |
+
getattr(schema, "virtual_state_sources", None) or {}
|
| 523 |
+
).items():
|
| 524 |
+
if _vk in _declared_dim:
|
| 525 |
+
_declared_dim.setdefault(str(_vsrc), _declared_dim[_vk])
|
| 526 |
+
from src.utils import env_flags as _env_flags
|
| 527 |
+
_check_overwide = _env_flags.get("LABVLA_ALLOW_TRUNCATE") != "1"
|
| 528 |
+
|
| 529 |
+
def _shard_ok(ci: int, fi: int) -> bool:
|
| 530 |
+
# Shim binding the phase-local context to module-level _shard_ok_v30.
|
| 531 |
+
return _shard_ok_v30(
|
| 532 |
+
ci, fi,
|
| 533 |
+
data_root=self.data_root,
|
| 534 |
+
needed=needed,
|
| 535 |
+
alt=alt,
|
| 536 |
+
shard_span=_shard_span,
|
| 537 |
+
declared_dim=_declared_dim,
|
| 538 |
+
check_overwide=_check_overwide,
|
| 539 |
+
repo_id=repo_id,
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
# Disk-persistent scan cache (v3 variant β keyed by ok_shards). Shared
|
| 543 |
+
# infrastructure in adapters/_scan_cache.py; v3 has no chunks_size, so
|
| 544 |
+
# -1 sentinel.
|
| 545 |
+
from ._scan_cache import (
|
| 546 |
+
_scan_cache_key, _load_scan_cache, _save_scan_cache,
|
| 547 |
+
)
|
| 548 |
+
cache_key = _scan_cache_key(
|
| 549 |
+
self.meta_root,
|
| 550 |
+
schema_id=getattr(schema, "schema_id", "unknown"),
|
| 551 |
+
chunks_size=-1, # v3 sentinel
|
| 552 |
+
data_root=self.data_root,
|
| 553 |
+
)
|
| 554 |
+
cache_key["required_columns"] = list(needed)
|
| 555 |
+
# Scan semantics include the row-span check, overwide check, declared
|
| 556 |
+
# dims and env gates; bump to invalidate caches written by an older
|
| 557 |
+
# scan version.
|
| 558 |
+
cache_key["integrity_checks"] = 3
|
| 559 |
+
cache_key["declared_dims"] = sorted(
|
| 560 |
+
(str(k), int(v)) for k, v in (_declared_dim or {}).items()
|
| 561 |
+
)
|
| 562 |
+
cached = _load_scan_cache(self.meta_root, cache_key)
|
| 563 |
+
|
| 564 |
+
unique_shards = {
|
| 565 |
+
(int(e["data/chunk_index"]), int(e["data/file_index"]))
|
| 566 |
+
for e in self._episodes
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
# The cache packs (ci, fi) as ``ci*_PACK_BASE + fi`` β unambiguous
|
| 570 |
+
# only while fi < _PACK_BASE. Assert loudly so >1M-shards-per-chunk
|
| 571 |
+
# datasets fail at launch instead of mis-filtering silently.
|
| 572 |
+
_PACK_BASE = 1_000_000
|
| 573 |
+
max_fi = max((fi for (_, fi) in unique_shards), default=0)
|
| 574 |
+
assert max_fi < _PACK_BASE, (
|
| 575 |
+
f"[v30-adapter] shard fi={max_fi} β₯ cache pack base {_PACK_BASE}; "
|
| 576 |
+
f"cache collision risk β update encoding before reusing."
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
if cached is not None:
|
| 580 |
+
# Reuse the v21 cache's `existing_episodes` slot as our
|
| 581 |
+
# ok_shards set (packed ints).
|
| 582 |
+
_packed_ok = cached[1]
|
| 583 |
+
ok_shards = {(p // _PACK_BASE, p % _PACK_BASE) for p in _packed_ok}
|
| 584 |
+
# Intersect with the current episode set, which can drift
|
| 585 |
+
# without a schema change (which would invalidate the cache).
|
| 586 |
+
ok_shards = ok_shards & unique_shards
|
| 587 |
+
else:
|
| 588 |
+
ok_shards = {s for s in unique_shards if _shard_ok(*s)}
|
| 589 |
+
_packed_ok = {ci * _PACK_BASE + fi for (ci, fi) in ok_shards}
|
| 590 |
+
_save_scan_cache(
|
| 591 |
+
self.meta_root, cache_key, chunk_ok={}, existing_episodes=_packed_ok,
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
if ok_shards != unique_shards:
|
| 595 |
+
keep = [e for e in self._episodes
|
| 596 |
+
if (int(e["data/chunk_index"]), int(e["data/file_index"])) in ok_shards]
|
| 597 |
+
dropped = len(self._episodes) - len(keep)
|
| 598 |
+
logger.warning(
|
| 599 |
+
"[v30-adapter] %s: dropped %d/%d episodes in %d shards "
|
| 600 |
+
"lacking schema-required columns (%s)",
|
| 601 |
+
repo_id, dropped, len(self._episodes),
|
| 602 |
+
len(unique_shards) - len(ok_shards), needed,
|
| 603 |
+
)
|
| 604 |
+
self._episodes = keep
|
| 605 |
+
self._ep_starts, self._ep_lens = _ep_starts_lens(self._episodes)
|
| 606 |
+
|
| 607 |
+
def _finalize_meta_and_caches(self, stats, schema) -> None:
|
| 608 |
+
"""Phase 4: feature/camera keys, fps gate, DatasetMeta, shard
|
| 609 |
+
offsets + column projection, video/shard caches, shared counters."""
|
| 610 |
+
info = self._info
|
| 611 |
+
repo_id = self.repo_id
|
| 612 |
+
|
| 613 |
+
feats = info.get("features", {}) or {}
|
| 614 |
+
video_keys = [
|
| 615 |
+
k for k, val in feats.items()
|
| 616 |
+
if isinstance(val, dict) and val.get("dtype") == "video"
|
| 617 |
+
]
|
| 618 |
+
# dtype=image columns are PNG-in-parquet (HF Image feature), NOT mp4.
|
| 619 |
+
# Datasets like LabUtopia/Level3_open ship images this way with no
|
| 620 |
+
# videos/ dir; the base __getitem__ decodes them inline via
|
| 621 |
+
# self._image_keys (else the video loop trains on all-black frames).
|
| 622 |
+
image_keys = [
|
| 623 |
+
k for k, val in feats.items()
|
| 624 |
+
if isinstance(val, dict) and val.get("dtype") == "image"
|
| 625 |
+
]
|
| 626 |
+
self._image_keys = tuple(image_keys)
|
| 627 |
+
|
| 628 |
+
_ep_ends = self._ep_starts + self._ep_lens
|
| 629 |
+
if "fps" not in info:
|
| 630 |
+
raise ValueError(
|
| 631 |
+
f"{self.meta_root}/info.json is missing 'fps'. v3.0 adapter "
|
| 632 |
+
"requires an explicit fps to build delta_timestamps; a silent "
|
| 633 |
+
"default of 10 caused action-vs-video drift when the real fps "
|
| 634 |
+
"differs (e.g. 30)."
|
| 635 |
+
)
|
| 636 |
+
self.meta = DatasetMeta(
|
| 637 |
+
robot_type=info.get("robot_type"),
|
| 638 |
+
stats=stats if stats else None,
|
| 639 |
+
fps=float(info["fps"]),
|
| 640 |
+
total_episodes=len(self._episodes),
|
| 641 |
+
total_frames=int(self._ep_lens.sum()),
|
| 642 |
+
features=feats,
|
| 643 |
+
video_keys=video_keys,
|
| 644 |
+
# camera_keys = full set (mp4 video + PNG-in-parquet image);
|
| 645 |
+
# video_keys alone is empty for image-only datasets.
|
| 646 |
+
camera_keys=list(video_keys) + list(image_keys),
|
| 647 |
+
schema=schema,
|
| 648 |
+
episodes={
|
| 649 |
+
"dataset_from_index": self._ep_starts.astype(int).tolist(),
|
| 650 |
+
"dataset_to_index": _ep_ends.astype(int).tolist(),
|
| 651 |
+
},
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
# episode_index β meta row lookup, used by _load_ep_parquet /
|
| 655 |
+
# _read_video_frame to recover shard + timestamp info O(1).
|
| 656 |
+
self._ep_by_idx = {int(e["episode_index"]): e for e in self._episodes}
|
| 657 |
+
|
| 658 |
+
# Per-shard globalβlocal offset. `dataset_from_index` is cumulative
|
| 659 |
+
# over the WHOLE dataset while each shard's rows are locally numbered;
|
| 660 |
+
# offset = min(dataset_from_index) over ALL (unfiltered) episodes in
|
| 661 |
+
# the shard β see _load_ep_parquet.
|
| 662 |
+
self._shard_offsets: dict[tuple[int, int], int] = {}
|
| 663 |
+
for _e in self._unfiltered_episodes:
|
| 664 |
+
_key = (int(_e["data/chunk_index"]), int(_e["data/file_index"]))
|
| 665 |
+
_a = int(_e["dataset_from_index"])
|
| 666 |
+
_cur = self._shard_offsets.get(_key)
|
| 667 |
+
if _cur is None or _a < _cur:
|
| 668 |
+
self._shard_offsets[_key] = _a
|
| 669 |
+
|
| 670 |
+
# Minimal column set for `_load_shard`: oxe-auge shards have ~49 columns
|
| 671 |
+
# but we only need schema state/action + task-resolution fields.
|
| 672 |
+
# Projecting cuts I/O ~10x and keeps LRU entries compact.
|
| 673 |
+
needed: set[str] = set()
|
| 674 |
+
if schema is not None:
|
| 675 |
+
read_state_keys = (
|
| 676 |
+
tuple(getattr(schema, "source_state_keys", ()) or ())
|
| 677 |
+
or tuple(getattr(schema, "state_keys", ()) or ())
|
| 678 |
+
)
|
| 679 |
+
read_action_keys = (
|
| 680 |
+
tuple(getattr(schema, "source_action_keys", ()) or ())
|
| 681 |
+
or tuple(getattr(schema, "action_keys", ()) or ())
|
| 682 |
+
)
|
| 683 |
+
# Project the PHYSICAL source column for virtual state keys (a
|
| 684 |
+
# virtual name never exists in the shard; projecting it would
|
| 685 |
+
# silently drop the real source from the read).
|
| 686 |
+
for k in read_state_keys:
|
| 687 |
+
needed.add(self._resolve_physical_column(schema, k))
|
| 688 |
+
for k in read_action_keys:
|
| 689 |
+
needed.add(self._resolve_physical_column(schema, k))
|
| 690 |
+
# Canonical siblings so the pluralization normalization can reach
|
| 691 |
+
# them β ONLY when the schema actually reads a canonical-named
|
| 692 |
+
# column. For fully non-canonical read sets (e.g. oxe-auge reads
|
| 693 |
+
# only observation.joints), an unconditional update would drag the
|
| 694 |
+
# heterogeneous raw observation.state through every sample dict
|
| 695 |
+
# until ComposeFieldsTransform overwrote it β wasted shard I/O and
|
| 696 |
+
# a trap for any future transform that iterates all dict keys.
|
| 697 |
+
_canonical_siblings = {"observation.state", "state", "action", "actions"}
|
| 698 |
+
if needed & _canonical_siblings:
|
| 699 |
+
needed.update(_canonical_siblings)
|
| 700 |
+
# Task resolution needs task_index (β tasks.parquet) or
|
| 701 |
+
# natural_language_instruction; include both.
|
| 702 |
+
needed.update({"task_index", "natural_language_instruction", "task"})
|
| 703 |
+
if schema is not None:
|
| 704 |
+
for spec in getattr(schema, "annotation_losses", ()) or ():
|
| 705 |
+
field = getattr(spec, "field", None)
|
| 706 |
+
if field:
|
| 707 |
+
needed.add(str(field))
|
| 708 |
+
# "annotation.unified" is SYNTHESIZED at transform time by
|
| 709 |
+
# BuildUnifiedAnnotationTransformFn from the raw per-field
|
| 710 |
+
# annotation columns β projecting only the synthesized name would
|
| 711 |
+
# drop the raw columns from the shard read, and the builder would
|
| 712 |
+
# silently emit an empty string (zero annotation CE). Project the
|
| 713 |
+
# builder's source fields too; absent columns are filtered against
|
| 714 |
+
# the shard's actual schema below, so heterogeneous shards stay fine.
|
| 715 |
+
if any(
|
| 716 |
+
getattr(spec, "field", None) == "annotation.unified"
|
| 717 |
+
for spec in getattr(schema, "annotation_losses", ()) or ()
|
| 718 |
+
):
|
| 719 |
+
# The source-field list is schema-layer data (shared by the
|
| 720 |
+
# transform that synthesizes annotation.unified and this
|
| 721 |
+
# projection) β import it from schema, not from transforms.
|
| 722 |
+
from src.schema.annotation_loss import (
|
| 723 |
+
UNIFIED_ANNOTATION_FIELDS as _UNIFIED_RAW_FIELDS,
|
| 724 |
+
)
|
| 725 |
+
needed.update(str(f) for f in _UNIFIED_RAW_FIELDS)
|
| 726 |
+
# Minimal metadata for any downstream transform that inspects index.
|
| 727 |
+
needed.update({"timestamp", "frame_index", "episode_index", "index"})
|
| 728 |
+
# Project dtype=image PNG columns too, else _load_shard drops them and
|
| 729 |
+
# __getitem__ falls through to all-black _zero_frame tensors.
|
| 730 |
+
needed.update(image_keys)
|
| 731 |
+
self._shard_load_columns: tuple[str, ...] | None = (
|
| 732 |
+
tuple(needed) if needed else None
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
logger.info(
|
| 736 |
+
"[v30-adapter] %s: %d episodes, %d frames, %d video_cameras, "
|
| 737 |
+
"%d image_cameras, schema=%s, shard_load_columns=%d",
|
| 738 |
+
repo_id, self.meta.total_episodes, self.meta.total_frames,
|
| 739 |
+
len(video_keys), len(image_keys),
|
| 740 |
+
getattr(schema, "schema_id", None),
|
| 741 |
+
len(self._shard_load_columns) if self._shard_load_columns else -1,
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
# Warn once per (repo, horizon) if the longest offset clips past most
|
| 745 |
+
# of the shortest episode. See base class.
|
| 746 |
+
self._validate_delta_timestamps_frame_aligned() # M15
|
| 747 |
+
self._validate_delta_timestamps_vs_episode_lens()
|
| 748 |
+
|
| 749 |
+
# Process-wide PyAV container LRU (shared with v21): frames within a
|
| 750 |
+
# sample share a packed mp4, so caching avoids a fresh av.open+seek per
|
| 751 |
+
# frame. Keys namespaced by adapter id to avoid (vkey, ci, fi) collisions.
|
| 752 |
+
self._video_cache = _get_shared_video_cache()
|
| 753 |
+
self._video_cache_owner_id = id(self)
|
| 754 |
+
|
| 755 |
+
# Fork-shared zero-frame fallback counter (must exist before DataLoader
|
| 756 |
+
# workers fork so worker increments reach the main process).
|
| 757 |
+
self._init_zero_frame_shared()
|
| 758 |
+
|
| 759 |
+
# Per-INSTANCE shard LRU (see lerobot_v21 for rationale β a class-level
|
| 760 |
+
# @lru_cache would share 64 slots across every adapter in a mixture and
|
| 761 |
+
# pin `self` references in a class-level cache).
|
| 762 |
+
self._load_shard = lru_cache(maxsize=64)(self._load_shard_uncached)
|
| 763 |
+
|
| 764 |
+
def _close_video_containers(self) -> None:
|
| 765 |
+
"""Best-effort flush of cached PyAV containers (used at adapter teardown).
|
| 766 |
+
|
| 767 |
+
Now drops only entries owned by this adapter from the shared cache;
|
| 768 |
+
other adapters in the same worker keep their entries.
|
| 769 |
+
"""
|
| 770 |
+
try:
|
| 771 |
+
self._video_cache.drop_owner(self._video_cache_owner_id)
|
| 772 |
+
except Exception:
|
| 773 |
+
pass
|
| 774 |
+
|
| 775 |
+
def __del__(self):
|
| 776 |
+
try:
|
| 777 |
+
self._close_video_containers()
|
| 778 |
+
except Exception:
|
| 779 |
+
pass
|
| 780 |
+
|
| 781 |
+
# ---- shard-sliced parquet loader (overrides v21) ----
|
| 782 |
+
|
| 783 |
+
# Bound per-instance in __init__ via lru_cache(maxsize=64).
|
| 784 |
+
def _load_shard_uncached(self, ci: int, fi: int) -> pd.DataFrame:
|
| 785 |
+
"""Whole-shard DataFrame, LRU-cached at 64 shards (a BS=64 batch spans
|
| 786 |
+
many short oxe-auge episodes).
|
| 787 |
+
|
| 788 |
+
Projects onto `self._shard_load_columns` (schema state/action + task
|
| 789 |
+
cols): a full oxe-auge shard is ~50MB / 49 cols; projection drops it to
|
| 790 |
+
~5-10MB (~10x I/O reduction).
|
| 791 |
+
"""
|
| 792 |
+
p = self.data_root / f"chunk-{ci:03d}" / f"file-{fi:03d}.parquet"
|
| 793 |
+
cols = self._shard_load_columns
|
| 794 |
+
if cols is None:
|
| 795 |
+
return read_parquet_with_storage_retry(p)
|
| 796 |
+
# Sub-repos differ in columns (e.g. natural_language_instruction only
|
| 797 |
+
# in some OXE sources); read only the subset on disk to avoid ArrowInvalid.
|
| 798 |
+
try:
|
| 799 |
+
pf = run_with_storage_retry(
|
| 800 |
+
lambda: pq.ParquetFile(str(p)),
|
| 801 |
+
path=p,
|
| 802 |
+
description="open parquet metadata",
|
| 803 |
+
)
|
| 804 |
+
avail = set(pf.schema_arrow.names)
|
| 805 |
+
proj = [c for c in cols if c in avail]
|
| 806 |
+
return run_with_storage_retry(
|
| 807 |
+
lambda: pf.read(columns=proj).to_pandas(),
|
| 808 |
+
path=p,
|
| 809 |
+
description="read parquet projection",
|
| 810 |
+
)
|
| 811 |
+
except Exception:
|
| 812 |
+
# Column-metadata read failed: full-column read (slow but functional).
|
| 813 |
+
return read_parquet_with_storage_retry(p)
|
| 814 |
+
|
| 815 |
+
def _load_ep_parquet(self, ep_idx: int) -> pd.DataFrame:
|
| 816 |
+
ep = self._ep_by_idx[ep_idx]
|
| 817 |
+
ci = int(ep["data/chunk_index"])
|
| 818 |
+
fi = int(ep["data/file_index"])
|
| 819 |
+
a = int(ep["dataset_from_index"])
|
| 820 |
+
b = int(ep["dataset_to_index"])
|
| 821 |
+
# Global cumulative frame indices β shard-local rows: subtract the
|
| 822 |
+
# smallest dataset_from_index of any episode in this shard.
|
| 823 |
+
offset = self._shard_offsets.get((ci, fi), 0)
|
| 824 |
+
return (
|
| 825 |
+
self._load_shard(ci, fi)
|
| 826 |
+
.iloc[a - offset:b - offset]
|
| 827 |
+
.copy()
|
| 828 |
+
.reset_index(drop=True)
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
# ---- packed mp4 video loader (overrides v21) ----
|
| 832 |
+
|
| 833 |
+
def _read_video_frame(self, ep_idx: int, vkey: str, frame: int) -> torch.Tensor:
|
| 834 |
+
"""Read frame N of episode `ep_idx` from a packed mp4 shard.
|
| 835 |
+
|
| 836 |
+
v3 packs many episodes into a single mp4. The episode's sub-window
|
| 837 |
+
is given by `videos/<cam>/from_timestamp` and `to_timestamp` in
|
| 838 |
+
the episodes meta. Target pts = from_ts + frame/fps.
|
| 839 |
+
"""
|
| 840 |
+
ep = self._ep_by_idx.get(ep_idx)
|
| 841 |
+
if ep is None:
|
| 842 |
+
return self._zero_frame(reason="missing_episode")
|
| 843 |
+
vci_key = f"videos/{vkey}/chunk_index"
|
| 844 |
+
vfi_key = f"videos/{vkey}/file_index"
|
| 845 |
+
vfrom_key = f"videos/{vkey}/from_timestamp"
|
| 846 |
+
if vci_key not in ep or vfi_key not in ep or vfrom_key not in ep:
|
| 847 |
+
# Schema asked for a camera v3 info doesn't declare.
|
| 848 |
+
return self._zero_frame(reason="schema_camera_missing")
|
| 849 |
+
if any(_is_missing_scalar(ep.get(k)) for k in (vci_key, vfi_key, vfrom_key)):
|
| 850 |
+
return self._zero_frame(reason="video_metadata_missing")
|
| 851 |
+
ci = int(ep[vci_key])
|
| 852 |
+
fi = int(ep[vfi_key])
|
| 853 |
+
from_ts = float(ep[vfrom_key])
|
| 854 |
+
p = self.video_root / vkey / f"chunk-{ci:03d}" / f"file-{fi:03d}.mp4"
|
| 855 |
+
if not storage_path_exists(p):
|
| 856 |
+
return self._zero_frame(reason="missing_file")
|
| 857 |
+
|
| 858 |
+
import av
|
| 859 |
+
full_key = (self._video_cache_owner_id, vkey, ci, fi)
|
| 860 |
+
video_cache = self._video_cache
|
| 861 |
+
|
| 862 |
+
def _drop_cached_container(_exc, _attempt) -> None:
|
| 863 |
+
cached_container = video_cache.pop(full_key)
|
| 864 |
+
if cached_container is not None:
|
| 865 |
+
try:
|
| 866 |
+
cached_container[0].close()
|
| 867 |
+
except Exception:
|
| 868 |
+
pass
|
| 869 |
+
|
| 870 |
+
def _decode_once():
|
| 871 |
+
cached = video_cache.get(full_key)
|
| 872 |
+
if cached is None:
|
| 873 |
+
container = av.open(str(p))
|
| 874 |
+
stream = container.streams.video[0]
|
| 875 |
+
# "AUTO" hits a libav internal futex deadlock at 128-process
|
| 876 |
+
# scale; "NONE" + thread_count=1 is the only safe production default.
|
| 877 |
+
stream.thread_type = "NONE"
|
| 878 |
+
stream.thread_count = 1
|
| 879 |
+
# LRU eviction (closes evicted container) handled inside .put().
|
| 880 |
+
video_cache.put(full_key, (container, stream))
|
| 881 |
+
else:
|
| 882 |
+
container, stream = cached
|
| 883 |
+
|
| 884 |
+
fps_frac = Fraction(stream.average_rate) if stream.average_rate else Fraction(30)
|
| 885 |
+
fps = float(fps_frac)
|
| 886 |
+
tb = stream.time_base
|
| 887 |
+
|
| 888 |
+
# Target = episode window start + local frame offset.
|
| 889 |
+
target_sec = from_ts + frame / fps
|
| 890 |
+
target_pts = int(target_sec / tb) if tb else 0
|
| 891 |
+
try:
|
| 892 |
+
container.seek(target_pts, stream=stream)
|
| 893 |
+
except av.AVError:
|
| 894 |
+
pass
|
| 895 |
+
|
| 896 |
+
_start_pts = round(Fraction(from_ts) / tb) if tb else 0
|
| 897 |
+
target_global_frame = round(_start_pts * tb * fps_frac) + frame
|
| 898 |
+
for f in container.decode(stream):
|
| 899 |
+
if f.pts is None:
|
| 900 |
+
continue
|
| 901 |
+
cur = round(f.pts * tb * fps_frac)
|
| 902 |
+
if cur < target_global_frame:
|
| 903 |
+
continue
|
| 904 |
+
if cur > target_global_frame:
|
| 905 |
+
break
|
| 906 |
+
img = f.to_ndarray(format="rgb24")
|
| 907 |
+
t = torch.from_numpy(img).permute(2, 0, 1).contiguous().float() / 255.0
|
| 908 |
+
if self.image_transforms is not None:
|
| 909 |
+
apply_seeded = getattr(self.image_transforms, "apply_with_seed", None)
|
| 910 |
+
if callable(apply_seeded):
|
| 911 |
+
t = apply_seeded(t, seed_parts=(self.repo_id, ep_idx, vkey, frame))
|
| 912 |
+
else:
|
| 913 |
+
t = self.image_transforms(t)
|
| 914 |
+
return t
|
| 915 |
+
return None
|
| 916 |
+
|
| 917 |
+
try:
|
| 918 |
+
decoded = run_with_storage_retry(
|
| 919 |
+
_decode_once,
|
| 920 |
+
path=p,
|
| 921 |
+
description="v30 video decode",
|
| 922 |
+
on_retry=_drop_cached_container,
|
| 923 |
+
)
|
| 924 |
+
if decoded is not None:
|
| 925 |
+
return decoded
|
| 926 |
+
cached = video_cache.pop(full_key)
|
| 927 |
+
if cached is not None:
|
| 928 |
+
try:
|
| 929 |
+
cached[0].close()
|
| 930 |
+
except Exception:
|
| 931 |
+
pass
|
| 932 |
+
return self._zero_frame(reason="frame_overshoot")
|
| 933 |
+
except Exception as e:
|
| 934 |
+
# Drop the cached container on error; it may be in a bad state.
|
| 935 |
+
cached = video_cache.pop(full_key)
|
| 936 |
+
if cached is not None:
|
| 937 |
+
try:
|
| 938 |
+
cached[0].close()
|
| 939 |
+
except Exception:
|
| 940 |
+
pass
|
| 941 |
+
logger.warning("[v30-adapter] video decode failed for %s (%s); zero frame.", p, e)
|
| 942 |
+
return self._zero_frame(reason="decode_error")
|
src/adapters/registry.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adapter factory β dispatches by info.json codebase_version.
|
| 2 |
+
|
| 3 |
+
v2.x β LeRobotV21Adapter (one parquet + one mp4 per episode)
|
| 4 |
+
v3.x β LeRobotV30Adapter (many episodes per shard β slice ranges live
|
| 5 |
+
in meta/episodes/*.parquet)
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def create_adapter(
|
| 16 |
+
repo_id: str,
|
| 17 |
+
root: str | Path | None = None,
|
| 18 |
+
data_root: str | Path | None = None,
|
| 19 |
+
delta_timestamps: dict | None = None,
|
| 20 |
+
image_transforms=None,
|
| 21 |
+
video_backend: str | None = None,
|
| 22 |
+
external_stats: dict | None = None,
|
| 23 |
+
override_schema=None,
|
| 24 |
+
episode_filter: list[int] | tuple[int, ...] | None = None,
|
| 25 |
+
):
|
| 26 |
+
"""Create a LeRobotV21Adapter for the given repo_id.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
repo_id: Dataset repository ID (e.g., "robointer_droid_clean").
|
| 30 |
+
root: Direct path to dataset root. If None, uses data_root/repo_id.
|
| 31 |
+
data_root: Parent directory containing repo_id subdirectory.
|
| 32 |
+
delta_timestamps: Action chunk timestamps for temporal indexing.
|
| 33 |
+
image_transforms: Optional image augmentation transforms.
|
| 34 |
+
video_backend: Video decoding backend (default "pyav").
|
| 35 |
+
external_stats: Override stats dict (for reusing pretrain stats during finetune).
|
| 36 |
+
override_schema: Optional DatasetSchema to use instead of discovery.
|
| 37 |
+
"""
|
| 38 |
+
if root is None and data_root is not None:
|
| 39 |
+
candidate = Path(data_root) / repo_id
|
| 40 |
+
if candidate.exists():
|
| 41 |
+
root = candidate
|
| 42 |
+
if root is None:
|
| 43 |
+
raise ValueError(
|
| 44 |
+
f"Cannot find dataset root for {repo_id!r}. "
|
| 45 |
+
f"Provide --data_root or --root."
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
root = Path(root)
|
| 49 |
+
# VQA repos carry vqa_manifest.json instead of a LeRobot info.json.
|
| 50 |
+
vqa_manifest = root / "meta" / "vqa_manifest.json"
|
| 51 |
+
info_path = root / "meta" / "info.json"
|
| 52 |
+
if vqa_manifest.exists():
|
| 53 |
+
from .vqa_adapter import VQAAdapter
|
| 54 |
+
return VQAAdapter(
|
| 55 |
+
repo_id=repo_id,
|
| 56 |
+
root=str(root),
|
| 57 |
+
override_schema=override_schema,
|
| 58 |
+
delta_timestamps=delta_timestamps,
|
| 59 |
+
image_transforms=image_transforms,
|
| 60 |
+
external_stats=external_stats,
|
| 61 |
+
video_backend=video_backend,
|
| 62 |
+
episode_filter=episode_filter,
|
| 63 |
+
)
|
| 64 |
+
if not info_path.exists():
|
| 65 |
+
raise FileNotFoundError(
|
| 66 |
+
f"Neither {info_path} nor {vqa_manifest} found. "
|
| 67 |
+
"create_adapter expects a LeRobot dataset (info.json) or a "
|
| 68 |
+
"VQA dataset (vqa_manifest.json)."
|
| 69 |
+
)
|
| 70 |
+
with open(info_path) as f:
|
| 71 |
+
version = json.load(f).get("codebase_version", "unknown")
|
| 72 |
+
|
| 73 |
+
kwargs = dict(
|
| 74 |
+
repo_id=repo_id,
|
| 75 |
+
root=str(root),
|
| 76 |
+
delta_timestamps=delta_timestamps,
|
| 77 |
+
image_transforms=image_transforms,
|
| 78 |
+
external_stats=external_stats,
|
| 79 |
+
override_schema=override_schema,
|
| 80 |
+
video_backend=video_backend or "pyav",
|
| 81 |
+
episode_filter=episode_filter,
|
| 82 |
+
)
|
| 83 |
+
if version.startswith("v2"):
|
| 84 |
+
from .lerobot_v21 import LeRobotV21Adapter
|
| 85 |
+
return LeRobotV21Adapter(**kwargs)
|
| 86 |
+
if version.startswith("v3"):
|
| 87 |
+
from .lerobot_v30 import LeRobotV30Adapter
|
| 88 |
+
return LeRobotV30Adapter(**kwargs)
|
| 89 |
+
raise ValueError(
|
| 90 |
+
f"Unsupported codebase_version {version!r} at {info_path}. "
|
| 91 |
+
f"Expected v2.x or v3.x."
|
| 92 |
+
)
|
src/adapters/vqa_adapter.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Thin adapter wrapper around `RoboInterVQADataset` so it can be plumbed
|
| 2 |
+
through the existing `build_dataset` β `TransformedAdapterDataset` pipeline.
|
| 3 |
+
|
| 4 |
+
VQA repos do not have a LeRobot info.json. Detection in `create_adapter`:
|
| 5 |
+
the repo root must contain a `meta/vqa_manifest.json` file describing which
|
| 6 |
+
JSON files to load and which task family they belong to.
|
| 7 |
+
|
| 8 |
+
`vqa_manifest.json` schema (minimal):
|
| 9 |
+
{
|
| 10 |
+
"task_family": "understanding" | "generation_short" | "generation_traj"
|
| 11 |
+
| "task_planning",
|
| 12 |
+
"image_root_subdir": "Understanding/image/train/droid", // relative to repo root
|
| 13 |
+
"json_files": [
|
| 14 |
+
"Understanding/meta/train/droid/contact_decide.json",
|
| 15 |
+
"Understanding/meta/train/droid/grounding_choice.json"
|
| 16 |
+
]
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
The image_root_subdir resolves relative paths in the JSON `images` field
|
| 20 |
+
(LLaVA-style path). Image paths inside JSON typically include the same prefix
|
| 21 |
+
already, so `image_root_subdir` is usually the repo root itself ("").
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
from dataclasses import dataclass
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any
|
| 30 |
+
|
| 31 |
+
from .base import BaseAdapter
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class _VQAAdapterMeta:
|
| 36 |
+
"""Mimic the ``DatasetMeta`` interface that build_dataset uses.
|
| 37 |
+
|
| 38 |
+
Satisfies the full surface (``total_episodes``, ``total_frames``,
|
| 39 |
+
``camera_keys``, ``episodes``, ``require_schema()``) with minimal correct
|
| 40 |
+
values: VQA has no robot trajectory (one "episode" per sample, no shard
|
| 41 |
+
frame ranges, cameras from the schema's ``image_mapping``).
|
| 42 |
+
"""
|
| 43 |
+
schema: Any
|
| 44 |
+
stats: dict
|
| 45 |
+
fps: float = 1.0
|
| 46 |
+
robot_type: str = "vqa_no_robot"
|
| 47 |
+
total_episodes: int = 0
|
| 48 |
+
total_frames: int = 0
|
| 49 |
+
video_keys: tuple = ()
|
| 50 |
+
camera_keys: tuple = ()
|
| 51 |
+
features: dict = None
|
| 52 |
+
# MultiLeRobotDataset reads meta.episodes["dataset_from_index"/"to_index"].
|
| 53 |
+
# VQA samples aren't packed into shards, so expose empty parallel arrays.
|
| 54 |
+
episodes: dict = None
|
| 55 |
+
|
| 56 |
+
def __post_init__(self):
|
| 57 |
+
if self.features is None:
|
| 58 |
+
self.features = {}
|
| 59 |
+
if self.episodes is None:
|
| 60 |
+
self.episodes = {
|
| 61 |
+
"dataset_from_index": [],
|
| 62 |
+
"dataset_to_index": [],
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
def require_schema(self):
|
| 66 |
+
"""Return ``self.schema`` or raise if it is still ``None``.
|
| 67 |
+
|
| 68 |
+
Mirrors ``DatasetMeta.require_schema`` so generic code can enforce the
|
| 69 |
+
schema-present invariant uniformly across LeRobot and VQA adapters.
|
| 70 |
+
"""
|
| 71 |
+
if self.schema is None:
|
| 72 |
+
from src.schema.errors import SchemaDiscoveryError
|
| 73 |
+
|
| 74 |
+
raise SchemaDiscoveryError(
|
| 75 |
+
"_VQAAdapterMeta.schema is None after adapter construction. "
|
| 76 |
+
"VQAAdapter must resolve a schema (override_schema, or "
|
| 77 |
+
"manifest schema_name) before handing meta to the pipeline."
|
| 78 |
+
)
|
| 79 |
+
return self.schema
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class VQAAdapter(BaseAdapter):
|
| 83 |
+
"""Adapter wrapping RoboInterVQADataset, satisfying the LeRobot adapter
|
| 84 |
+
surface that build_dataset uses (.meta with .schema/.stats, .num_episodes,
|
| 85 |
+
.num_frames, __len__/__getitem__). A ``BaseAdapter`` subclass so generic
|
| 86 |
+
factory consumers get the full documented contract.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
repo_id: str,
|
| 92 |
+
root: str,
|
| 93 |
+
override_schema: Any = None,
|
| 94 |
+
# Other adapter kwargs accepted for API compatibility (ignored by VQA):
|
| 95 |
+
delta_timestamps: dict | None = None,
|
| 96 |
+
image_transforms=None,
|
| 97 |
+
external_stats: dict | None = None,
|
| 98 |
+
use_external_stats: bool = False,
|
| 99 |
+
video_backend: str | None = None,
|
| 100 |
+
episode_filter=None,
|
| 101 |
+
):
|
| 102 |
+
self.repo_id = repo_id
|
| 103 |
+
self.root = Path(root)
|
| 104 |
+
|
| 105 |
+
# VQA normalization stats are the built-in identity VQA_STATS
|
| 106 |
+
# (state/action are zero-filled). Fail loud rather than silently ignore
|
| 107 |
+
# an external-stats override so callers don't believe it took effect.
|
| 108 |
+
if external_stats or use_external_stats:
|
| 109 |
+
raise ValueError(
|
| 110 |
+
"VQAAdapter does not support external_stats: VQA samples have "
|
| 111 |
+
"zero-filled state/action and MUST use the built-in identity "
|
| 112 |
+
f"VQA_STATS (got external_stats={external_stats!r}, "
|
| 113 |
+
f"use_external_stats={use_external_stats!r}). Remove the "
|
| 114 |
+
"external-stats override for VQA repos, or exclude this repo "
|
| 115 |
+
"from external-stats resolution."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
manifest_path = self.root / "meta" / "vqa_manifest.json"
|
| 119 |
+
if not manifest_path.is_file():
|
| 120 |
+
raise FileNotFoundError(
|
| 121 |
+
f"VQAAdapter expects {manifest_path} (vqa_manifest.json missing). "
|
| 122 |
+
f"See src/adapters/vqa_adapter.py docstring for schema."
|
| 123 |
+
)
|
| 124 |
+
with open(manifest_path) as f:
|
| 125 |
+
manifest = json.load(f)
|
| 126 |
+
|
| 127 |
+
# Resolve schema: caller override > manifest `schema_name`. Require an
|
| 128 |
+
# explicit schema_name (no silent default) so a corpus with different
|
| 129 |
+
# semantics isn't bound to the wrong schema.
|
| 130 |
+
if override_schema is not None:
|
| 131 |
+
schema = override_schema
|
| 132 |
+
else:
|
| 133 |
+
from src.schema.registry import resolve as _resolve_schema
|
| 134 |
+
schema_name = manifest.get("schema_name")
|
| 135 |
+
if not schema_name:
|
| 136 |
+
raise ValueError(
|
| 137 |
+
f"VQA manifest {manifest_path} is missing required "
|
| 138 |
+
"'schema_name'. Add an explicit schema_name (e.g. "
|
| 139 |
+
"\"robointer_vqa\") to the manifest, or pass "
|
| 140 |
+
"override_schema. Refusing to default silently so a "
|
| 141 |
+
"non-robointer_vqa corpus is not bound to the wrong schema."
|
| 142 |
+
)
|
| 143 |
+
schema = _resolve_schema(schema_name)
|
| 144 |
+
|
| 145 |
+
from src.dataset.adapters.robointer_vqa_adapter import RoboInterVQADataset
|
| 146 |
+
|
| 147 |
+
json_paths = [
|
| 148 |
+
os.path.join(root, jp) for jp in manifest["json_files"]
|
| 149 |
+
]
|
| 150 |
+
image_root = os.path.join(root, manifest.get("image_root_subdir", ""))
|
| 151 |
+
task_family = manifest["task_family"]
|
| 152 |
+
|
| 153 |
+
self._dataset = RoboInterVQADataset(
|
| 154 |
+
json_paths=json_paths,
|
| 155 |
+
image_root=image_root,
|
| 156 |
+
task_family=task_family,
|
| 157 |
+
schema=schema,
|
| 158 |
+
)
|
| 159 |
+
# One "episode" per VQA sample so PI0Mixture n^0.43 weighting and the
|
| 160 |
+
# inherited num_episodes/num_frames properties (read from meta) work.
|
| 161 |
+
n = len(self._dataset)
|
| 162 |
+
# VQA has no on-disk video; the only image slot is the schema's
|
| 163 |
+
# image_mapping target(s) (e.g. observation.images.primary).
|
| 164 |
+
camera_keys = tuple(
|
| 165 |
+
getattr(schema, "image_mapping", None) or {}
|
| 166 |
+
)
|
| 167 |
+
# Identity stats: state/action are zero-filled so identity normalization
|
| 168 |
+
# leaves them at zero. Populating observation.state/action/action_abs
|
| 169 |
+
# also satisfies the action_mode='abs' guard.
|
| 170 |
+
from schemas.robointer_vqa import VQA_STATS as _VQA_STATS
|
| 171 |
+
self.meta = _VQAAdapterMeta(
|
| 172 |
+
schema=schema,
|
| 173 |
+
stats=dict(_VQA_STATS),
|
| 174 |
+
total_episodes=n,
|
| 175 |
+
total_frames=n,
|
| 176 |
+
camera_keys=camera_keys,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def __len__(self) -> int:
|
| 180 |
+
return len(self._dataset)
|
| 181 |
+
|
| 182 |
+
def __getitem__(self, idx: int) -> dict:
|
| 183 |
+
return self._dataset[idx]
|
src/config/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Config package (draccus dataclass CLI plumbing)."""
|
src/config/default.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass, field
|
| 18 |
+
|
| 19 |
+
import abc
|
| 20 |
+
import draccus
|
| 21 |
+
|
| 22 |
+
from src.dataset.transforms import ImageTransformsConfig
|
| 23 |
+
from src.transforms.core import TransformGroup
|
| 24 |
+
from src.dataset.video_utils import get_safe_default_codec
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class DatasetConfig(draccus.ChoiceRegistry, abc.ABC):
|
| 29 |
+
# You may provide a list of datasets here. `train.py` creates them all and concatenates them. Note: only data
|
| 30 |
+
# keys common between the datasets are kept. Each dataset gets and additional transform that inserts the
|
| 31 |
+
# "dataset_index" into the returned item. The index mapping is made according to the order in which the
|
| 32 |
+
# datasets are provided.
|
| 33 |
+
repo_id: str
|
| 34 |
+
# Root directory where the dataset will be stored (e.g. 'dataset/path').
|
| 35 |
+
root: str | None = None
|
| 36 |
+
episodes: list[int] | None = None
|
| 37 |
+
image_transforms: ImageTransformsConfig = field(default_factory=ImageTransformsConfig)
|
| 38 |
+
revision: str | None = None
|
| 39 |
+
use_imagenet_stats: bool = True
|
| 40 |
+
use_external_stats: bool = False
|
| 41 |
+
external_stats_path: str | None = None
|
| 42 |
+
weight_rules_path: str | None = None
|
| 43 |
+
video_backend: str = field(default_factory=get_safe_default_codec)
|
| 44 |
+
streaming: bool = False
|
| 45 |
+
dist_loading: bool = False
|
| 46 |
+
buffer_size: int = 1024
|
| 47 |
+
action_mode: str = "abs" # abs | delta
|
| 48 |
+
repack_transforms: TransformGroup = field(default_factory=TransformGroup)
|
| 49 |
+
data_transforms: TransformGroup = field(default_factory=TransformGroup)
|
| 50 |
+
model_transforms: TransformGroup = field(default_factory=TransformGroup)
|
| 51 |
+
|
| 52 |
+
def __post_init__(self):
|
| 53 |
+
assert self.action_mode in ['abs', 'delta'], "Either abs or delta for 'action_type'. "
|
| 54 |
+
# The two external-stats knobs must agree, else stats silently go
|
| 55 |
+
# missing or a real custom-stats file is silently ignored.
|
| 56 |
+
if self.use_external_stats and not self.external_stats_path:
|
| 57 |
+
raise ValueError(
|
| 58 |
+
"use_external_stats=True but external_stats_path is None. "
|
| 59 |
+
"Either set external_stats_path, or set use_external_stats=False."
|
| 60 |
+
)
|
| 61 |
+
if (not self.use_external_stats) and self.external_stats_path:
|
| 62 |
+
raise ValueError(
|
| 63 |
+
f"external_stats_path={self.external_stats_path!r} is set but "
|
| 64 |
+
f"use_external_stats=False. The path would be silently ignored. "
|
| 65 |
+
f"Set use_external_stats=True to consume it, or clear the path."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
src/config/policies.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import abc
|
| 15 |
+
import builtins
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import tempfile
|
| 19 |
+
from dataclasses import dataclass, field
|
| 20 |
+
from logging import getLogger
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any, TypeVar
|
| 23 |
+
|
| 24 |
+
import draccus
|
| 25 |
+
from huggingface_hub import hf_hub_download
|
| 26 |
+
from huggingface_hub.constants import CONFIG_NAME as _HF_CONFIG_NAME
|
| 27 |
+
from huggingface_hub.errors import HfHubHTTPError
|
| 28 |
+
|
| 29 |
+
# Keep module-level `CONFIG_NAME` alias for back-compat with any caller that
|
| 30 |
+
# imports `from config.policies import CONFIG_NAME`. New callers should
|
| 31 |
+
# prefer the class-level `PreTrainedConfig.CONFIG_NAME` attribute which can
|
| 32 |
+
# be overridden in subclasses.
|
| 33 |
+
CONFIG_NAME = _HF_CONFIG_NAME
|
| 34 |
+
|
| 35 |
+
from src.config.types import FeatureType, PolicyFeature
|
| 36 |
+
from src.optim.optimizers import OptimizerConfig
|
| 37 |
+
from src.optim.schedulers import LRSchedulerConfig
|
| 38 |
+
from src.utils.constants import ACTION, OBS_STATE
|
| 39 |
+
from src.utils.hub import HubMixin
|
| 40 |
+
from src.utils.utils import auto_select_torch_device, is_amp_available, is_torch_device_available
|
| 41 |
+
|
| 42 |
+
T = TypeVar("T", bound="PreTrainedConfig")
|
| 43 |
+
logger = getLogger(__name__)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class PreTrainedConfig(draccus.ChoiceRegistry, HubMixin, abc.ABC): # type: ignore[misc,name-defined] #TODO: draccus issue
|
| 48 |
+
"""
|
| 49 |
+
Base configuration class for policy models.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
n_obs_steps: Number of environment steps worth of observations to pass to the policy (takes the
|
| 53 |
+
current step and additional steps going back).
|
| 54 |
+
input_shapes: A dictionary defining the shapes of the input data for the policy.
|
| 55 |
+
output_shapes: A dictionary defining the shapes of the output data for the policy.
|
| 56 |
+
input_normalization_modes: A dictionary with key representing the modality and the value specifies the
|
| 57 |
+
normalization mode to apply.
|
| 58 |
+
output_normalization_modes: Similar dictionary as `input_normalization_modes`, but to unnormalize to
|
| 59 |
+
the original scale.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
# Override-able config-file name (default "config.json"); subclasses can set
|
| 63 |
+
# e.g. "train_config.json" without monkeypatching the HF module.
|
| 64 |
+
CONFIG_NAME: str = _HF_CONFIG_NAME
|
| 65 |
+
|
| 66 |
+
n_obs_steps: int = 1
|
| 67 |
+
|
| 68 |
+
input_features: dict[str, PolicyFeature] = field(default_factory=dict)
|
| 69 |
+
output_features: dict[str, PolicyFeature] = field(default_factory=dict)
|
| 70 |
+
|
| 71 |
+
device: str | None = None # e.g. "cuda", "cuda:0", "cpu", or "mps"
|
| 72 |
+
# `use_amp` determines whether to use Automatic Mixed Precision (AMP) for training and evaluation. With AMP,
|
| 73 |
+
# automatic gradient scaling is used.
|
| 74 |
+
use_amp: bool = False
|
| 75 |
+
|
| 76 |
+
push_to_hub: bool = True # type: ignore[assignment] # TODO: use a different name to avoid override
|
| 77 |
+
repo_id: str | None = None
|
| 78 |
+
|
| 79 |
+
# Upload on private repository on the Hugging Face hub.
|
| 80 |
+
private: bool | None = None
|
| 81 |
+
# Add tags to your policy on the hub.
|
| 82 |
+
tags: list[str] | None = None
|
| 83 |
+
# Add tags to your policy on the hub.
|
| 84 |
+
license: str | None = None
|
| 85 |
+
# Either the repo ID of a model hosted on the Hub or a path to a directory containing weights
|
| 86 |
+
# saved using `Policy.save_pretrained`. If not provided, the policy is initialized from scratch.
|
| 87 |
+
pretrained_path: Path | None = None
|
| 88 |
+
|
| 89 |
+
def __post_init__(self) -> None:
|
| 90 |
+
if not self.device or not is_torch_device_available(self.device):
|
| 91 |
+
auto_device = auto_select_torch_device()
|
| 92 |
+
# rank_zero_warn_once: only rank 0 emits, and it's safe before
|
| 93 |
+
# torch.distributed is initialized.
|
| 94 |
+
from src.utils.logging_utils import rank_zero_warn_once
|
| 95 |
+
rank_zero_warn_once(
|
| 96 |
+
logger,
|
| 97 |
+
("device_switch", str(self.device), str(auto_device)),
|
| 98 |
+
"Device '%s' is not available. Switching to '%s'.",
|
| 99 |
+
self.device, auto_device,
|
| 100 |
+
)
|
| 101 |
+
self.device = auto_device.type
|
| 102 |
+
|
| 103 |
+
# Automatically deactivate AMP if necessary
|
| 104 |
+
if self.use_amp and not is_amp_available(self.device):
|
| 105 |
+
logger.warning(
|
| 106 |
+
f"Automatic Mixed Precision (amp) is not available on device '{self.device}'. Deactivating AMP."
|
| 107 |
+
)
|
| 108 |
+
self.use_amp = False
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def type(self) -> str:
|
| 112 |
+
choice_name = self.get_choice_name(self.__class__)
|
| 113 |
+
if not isinstance(choice_name, str):
|
| 114 |
+
raise TypeError(f"Expected string from get_choice_name, got {type(choice_name)}")
|
| 115 |
+
return choice_name
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
@abc.abstractmethod
|
| 119 |
+
def observation_delta_indices(self) -> list | None: # type: ignore[type-arg] #TODO: No implementation
|
| 120 |
+
raise NotImplementedError
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
@abc.abstractmethod
|
| 124 |
+
def action_delta_indices(self) -> list | None: # type: ignore[type-arg] #TODO: No implementation
|
| 125 |
+
raise NotImplementedError
|
| 126 |
+
|
| 127 |
+
@property
|
| 128 |
+
@abc.abstractmethod
|
| 129 |
+
def reward_delta_indices(self) -> list | None: # type: ignore[type-arg] #TODO: No implementation
|
| 130 |
+
raise NotImplementedError
|
| 131 |
+
|
| 132 |
+
@abc.abstractmethod
|
| 133 |
+
def get_optimizer_preset(self) -> OptimizerConfig:
|
| 134 |
+
raise NotImplementedError
|
| 135 |
+
|
| 136 |
+
@abc.abstractmethod
|
| 137 |
+
def get_scheduler_preset(self) -> LRSchedulerConfig | None:
|
| 138 |
+
raise NotImplementedError
|
| 139 |
+
|
| 140 |
+
@abc.abstractmethod
|
| 141 |
+
def validate_features(self) -> None:
|
| 142 |
+
raise NotImplementedError
|
| 143 |
+
|
| 144 |
+
@property
|
| 145 |
+
def robot_state_feature(self) -> PolicyFeature | None:
|
| 146 |
+
for ft_name, ft in self.input_features.items():
|
| 147 |
+
if ft.type is FeatureType.STATE and ft_name == OBS_STATE:
|
| 148 |
+
return ft
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
@property
|
| 152 |
+
def env_state_feature(self) -> PolicyFeature | None:
|
| 153 |
+
for _, ft in self.input_features.items():
|
| 154 |
+
if ft.type is FeatureType.ENV:
|
| 155 |
+
return ft
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def image_features(self) -> dict[str, PolicyFeature]:
|
| 160 |
+
return {key: ft for key, ft in self.input_features.items() if ft.type is FeatureType.VISUAL}
|
| 161 |
+
|
| 162 |
+
@property
|
| 163 |
+
def action_feature(self) -> PolicyFeature | None:
|
| 164 |
+
for ft_name, ft in self.output_features.items():
|
| 165 |
+
if ft.type is FeatureType.ACTION and ft_name == ACTION:
|
| 166 |
+
return ft
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
def _save_pretrained(self, save_directory: Path) -> None:
|
| 170 |
+
with open(save_directory / self.CONFIG_NAME, "w") as f, draccus.config_type("json"):
|
| 171 |
+
draccus.dump(self, f, indent=4)
|
| 172 |
+
|
| 173 |
+
@classmethod
|
| 174 |
+
def from_pretrained(
|
| 175 |
+
cls: builtins.type[T],
|
| 176 |
+
pretrained_name_or_path: str | Path,
|
| 177 |
+
*,
|
| 178 |
+
force_download: bool = False,
|
| 179 |
+
resume_download: bool | None = None,
|
| 180 |
+
proxies: dict[Any, Any] | None = None,
|
| 181 |
+
token: str | bool | None = None,
|
| 182 |
+
cache_dir: str | Path | None = None,
|
| 183 |
+
local_files_only: bool = False,
|
| 184 |
+
revision: str | None = None,
|
| 185 |
+
**policy_kwargs: Any,
|
| 186 |
+
) -> T:
|
| 187 |
+
model_id = str(pretrained_name_or_path)
|
| 188 |
+
config_file: str | None = None
|
| 189 |
+
if Path(model_id).is_dir():
|
| 190 |
+
if cls.CONFIG_NAME in os.listdir(model_id):
|
| 191 |
+
config_file = os.path.join(model_id, cls.CONFIG_NAME)
|
| 192 |
+
else:
|
| 193 |
+
logger.error(f"{cls.CONFIG_NAME} not found in {Path(model_id).resolve()}")
|
| 194 |
+
else:
|
| 195 |
+
try:
|
| 196 |
+
config_file = hf_hub_download(
|
| 197 |
+
repo_id=model_id,
|
| 198 |
+
filename=cls.CONFIG_NAME,
|
| 199 |
+
revision=revision,
|
| 200 |
+
cache_dir=cache_dir,
|
| 201 |
+
force_download=force_download,
|
| 202 |
+
proxies=proxies,
|
| 203 |
+
resume_download=resume_download,
|
| 204 |
+
token=token,
|
| 205 |
+
local_files_only=local_files_only,
|
| 206 |
+
)
|
| 207 |
+
except HfHubHTTPError as e:
|
| 208 |
+
raise FileNotFoundError(
|
| 209 |
+
f"{cls.CONFIG_NAME} not found on the HuggingFace Hub in {model_id}"
|
| 210 |
+
) from e
|
| 211 |
+
|
| 212 |
+
# Fail loud BEFORE parse so a missing config file yields a clean
|
| 213 |
+
# FileNotFoundError instead of a confusing draccus traceback.
|
| 214 |
+
if config_file is None:
|
| 215 |
+
raise FileNotFoundError(f"{cls.CONFIG_NAME} not found in {model_id}")
|
| 216 |
+
|
| 217 |
+
# HACK: Parse the original config to get the config subclass, so that we can
|
| 218 |
+
# apply cli overrides.
|
| 219 |
+
# This is very ugly, ideally we'd like to be able to do that natively with draccus
|
| 220 |
+
# something like --policy.path (in addition to --policy.type)
|
| 221 |
+
with draccus.config_type("json"):
|
| 222 |
+
orig_config = draccus.parse(cls, config_file, args=[])
|
| 223 |
+
|
| 224 |
+
with open(config_file) as f:
|
| 225 |
+
config = json.load(f)
|
| 226 |
+
|
| 227 |
+
config.pop("type")
|
| 228 |
+
with tempfile.NamedTemporaryFile("w+", delete=False, suffix=".json") as f:
|
| 229 |
+
json.dump(config, f)
|
| 230 |
+
config_file = f.name
|
| 231 |
+
|
| 232 |
+
cli_overrides = policy_kwargs.pop("cli_overrides", [])
|
| 233 |
+
with draccus.config_type("json"):
|
| 234 |
+
return draccus.parse(orig_config.__class__, config_file, args=cli_overrides)
|
src/config/types.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# Note: We subclass str so that serialization is straightforward
|
| 15 |
+
# https://stackoverflow.com/questions/24481852/serialising-an-enum-member-to-json
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from enum import Enum
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class FeatureType(str, Enum):
|
| 21 |
+
STATE = "STATE"
|
| 22 |
+
VISUAL = "VISUAL"
|
| 23 |
+
ENV = "ENV"
|
| 24 |
+
ACTION = "ACTION"
|
| 25 |
+
REWARD = "REWARD"
|
| 26 |
+
LANGUAGE = "LANGUAGE"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class NormalizationMode(str, Enum):
|
| 30 |
+
MIN_MAX = "MIN_MAX"
|
| 31 |
+
MEAN_STD = "MEAN_STD"
|
| 32 |
+
IDENTITY = "IDENTITY"
|
| 33 |
+
QUANTILES = "QUANTILES"
|
| 34 |
+
QUANTILE10 = "QUANTILE10"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass
|
| 38 |
+
class PolicyFeature:
|
| 39 |
+
type: FeatureType
|
| 40 |
+
shape: tuple[int, ...]
|
| 41 |
+
|
| 42 |
+
|
src/dataset/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Dataset package (LeRobot-derived datasets, mixtures, helpers)."""
|
src/dataset/adapters/__init__.py
ADDED
|
File without changes
|
src/dataset/adapters/robointer_token_budget.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Centralized token-length budget for RoboInter VQA + annotation co-training.
|
| 2 |
+
|
| 3 |
+
All sequence-length related hyperparameters live here. Adapters / transforms /
|
| 4 |
+
schemas / launch scripts MUST read from this dataclass β do NOT hardcode their
|
| 5 |
+
own copies. Drift between scripts is a common source of silent regressions
|
| 6 |
+
(e.g. a discrete_action_max_length mismatch between a launch script and the
|
| 7 |
+
train.py argparse default).
|
| 8 |
+
|
| 9 |
+
Reference:
|
| 10 |
+
- Ο0.5 paper Β§B.1 "Robot proprioceptive state is discretized and input to the
|
| 11 |
+
model as text tokens" β state_num_bins=256.
|
| 12 |
+
- FAST tokenizer `physical-intelligence/fast` β vocab_size=2048.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass(frozen=True)
|
| 20 |
+
class RoboInterTokenBudget:
|
| 21 |
+
# ---- State discretization (Ο0.5 Β§B.1) ----
|
| 22 |
+
state_num_bins: int = 256
|
| 23 |
+
|
| 24 |
+
# ---- VQA β per task family answer length ----
|
| 25 |
+
# Understanding: MCQ "Yes"/"No"/"A-D"; very short.
|
| 26 |
+
vqa_understanding_answer_max_length: int = 8
|
| 27 |
+
# Generation: bbox / single point / contact frame.
|
| 28 |
+
vqa_generation_short_answer_max_length: int = 48
|
| 29 |
+
# Generation/traj_qa: 16 (x,y) waypoints serialized as text.
|
| 30 |
+
vqa_generation_traj_answer_max_length: int = 256
|
| 31 |
+
# Task_planning: free-form short subtask sentence.
|
| 32 |
+
vqa_task_planning_answer_max_length: int = 64
|
| 33 |
+
vqa_question_max_length: int = 128
|
| 34 |
+
# V1 trains on a single selected frame because the Qwen3-VL processor is
|
| 35 |
+
# wired for three fixed image slots shared with robot cameras, not arbitrary
|
| 36 |
+
# multi-image VQA packing.
|
| 37 |
+
vqa_task_planning_num_frames: int = 1
|
| 38 |
+
|
| 39 |
+
# ---- Annotation (12 RoboInter types unified into 1 text field) ----
|
| 40 |
+
annotation_unified_max_length: int = 256
|
| 41 |
+
# Q_trace can be 100+ pixel waypoints β downsample to bound token count.
|
| 42 |
+
annotation_trace_max_points: int = 16
|
| 43 |
+
# Skip Q_segmentation: dense pixel mask, too heavy to tokenize as text.
|
| 44 |
+
annotation_skip_fields: tuple[str, ...] = ("annotation.segmentation",)
|
| 45 |
+
# Qwen3-VL grounding format uses integer coords in [0, 1000].
|
| 46 |
+
annotation_coord_scale: int = 1000
|
| 47 |
+
|
| 48 |
+
# ---- Action / FAST (sourced from existing LabVLA defaults; do not change) ----
|
| 49 |
+
chunk_size: int = 50
|
| 50 |
+
# Must match (or exceed) the configuration_labvla.py runtime default, else
|
| 51 |
+
# this budget under-counts FAST token length. A smaller value silently
|
| 52 |
+
# truncates a few percent of FAST CE targets (robointer p99=70,
|
| 53 |
+
# robocoin p99=124).
|
| 54 |
+
discrete_action_max_length: int = 240
|
| 55 |
+
discrete_action_vocab_size: int = 2048 # FAST processor (physical-intelligence/fast)
|
| 56 |
+
max_state_dim: int = 32
|
| 57 |
+
max_action_dim: int = 32
|
| 58 |
+
|
| 59 |
+
# ---- Hard caps for the full LM input sequence ----
|
| 60 |
+
# Single-frame action sample budget: 256 image + 80 prompt + 256 ann + 240 FAST
|
| 61 |
+
# + 50 action expert β 882. VQA Task_planning V1 uses one selected frame:
|
| 62 |
+
# 256 image + 128 question + 64 answer β 448. Budget 2048 leaves headroom.
|
| 63 |
+
total_seq_len_hard_cap: int = 2048
|
| 64 |
+
|
| 65 |
+
def estimate_action_sample_length(self, num_cams: int = 2) -> int:
|
| 66 |
+
"""Estimate full prefix+suffix length for an action+annotation sample."""
|
| 67 |
+
return (
|
| 68 |
+
256 * num_cams # vision tokens (Qwen3-VL @ 224x224)
|
| 69 |
+
+ 80 # state-text + instruction
|
| 70 |
+
+ self.annotation_unified_max_length # unified annotation text
|
| 71 |
+
+ self.discrete_action_max_length # FAST tokens
|
| 72 |
+
+ self.chunk_size # action-expert tokens (suffix)
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
def estimate_vqa_sample_length(self, task_family: str, num_frames: int = 1) -> int:
|
| 76 |
+
"""Estimate length for a VQA-only sample (no action, no annotation)."""
|
| 77 |
+
if task_family == "understanding":
|
| 78 |
+
ans = self.vqa_understanding_answer_max_length
|
| 79 |
+
elif task_family == "generation_short":
|
| 80 |
+
ans = self.vqa_generation_short_answer_max_length
|
| 81 |
+
elif task_family == "generation_traj":
|
| 82 |
+
ans = self.vqa_generation_traj_answer_max_length
|
| 83 |
+
elif task_family == "task_planning":
|
| 84 |
+
ans = self.vqa_task_planning_answer_max_length
|
| 85 |
+
num_frames = min(num_frames, self.vqa_task_planning_num_frames)
|
| 86 |
+
else:
|
| 87 |
+
raise ValueError(f"unknown task_family {task_family!r}")
|
| 88 |
+
return 256 * num_frames + self.vqa_question_max_length + ans + 50 # + chat-template overhead
|
| 89 |
+
|
| 90 |
+
def __post_init__(self) -> None:
|
| 91 |
+
# Worst-case sanity: every supported sample type must fit under the hard
|
| 92 |
+
# cap. Fail at import time if a hyperparameter drifts in the future.
|
| 93 |
+
for nc in (1, 2, 4):
|
| 94 |
+
est = self.estimate_action_sample_length(nc)
|
| 95 |
+
if est > self.total_seq_len_hard_cap:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
f"action sample at num_cams={nc} estimated {est} tokens, "
|
| 98 |
+
f"exceeds total_seq_len_hard_cap={self.total_seq_len_hard_cap}"
|
| 99 |
+
)
|
| 100 |
+
for fam, nf in [
|
| 101 |
+
("understanding", 1),
|
| 102 |
+
("generation_short", 1),
|
| 103 |
+
("generation_traj", 1),
|
| 104 |
+
("task_planning", self.vqa_task_planning_num_frames),
|
| 105 |
+
]:
|
| 106 |
+
est = self.estimate_vqa_sample_length(fam, nf)
|
| 107 |
+
if est > self.total_seq_len_hard_cap:
|
| 108 |
+
raise ValueError(
|
| 109 |
+
f"VQA {fam} at {nf} frames estimated {est} tokens, "
|
| 110 |
+
f"exceeds total_seq_len_hard_cap={self.total_seq_len_hard_cap}"
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# Module-level singleton.
|
| 115 |
+
ROBOINTER_BUDGET = RoboInterTokenBudget()
|
src/dataset/adapters/robointer_vqa_adapter.py
ADDED
|
@@ -0,0 +1,544 @@
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RoboInter-VQA dataset adapter.
|
| 2 |
+
|
| 3 |
+
Reads LLaVA-format JSON (image + question + answer) from
|
| 4 |
+
`/path/to/pretrain_data/RoboInter-VQA/` and emits LabVLA sample dicts
|
| 5 |
+
that flow through the existing transform chain alongside action samples.
|
| 6 |
+
|
| 7 |
+
Design choices:
|
| 8 |
+
* Single-loader heterogeneous-batch approach (Ο0.5 + OpenTau pattern). VQA
|
| 9 |
+
samples have NO action / state β we emit zero-filled placeholders + set
|
| 10 |
+
`action_is_pad` all True so the model's flow-matching MSE is auto-skipped.
|
| 11 |
+
Only `annotation.vqa_answer` provides the supervision signal (CE via
|
| 12 |
+
`vlm.lm_head`, identical machinery to RoboInter's `annotation.unified`).
|
| 13 |
+
* `has_real_state=False` flag is read by `DiscretizeStateTransformFn` to
|
| 14 |
+
skip discretization β VQA samples must NOT have a fake "<state>128 128
|
| 15 |
+
...</state>" string injected into their question prompt.
|
| 16 |
+
* Single image per sample for V1 (Generation, Understanding). Task_planning
|
| 17 |
+
multi-frame samples are reduced to the LAST frame in V1 (full multi-frame
|
| 18 |
+
support is V2 β requires Qwen3-VL multi-image packing). The adapter
|
| 19 |
+
accepts but ignores extra image paths.
|
| 20 |
+
* Image path resolution: relative to `image_root` (typically
|
| 21 |
+
`/path/to/pretrain_data/RoboInter-VQA`).
|
| 22 |
+
* Conversations format: `[{from: "human" or "huamn", value: ...},
|
| 23 |
+
{from: "gpt", value: ...}]`. Typo "huamn" appears in some val files β
|
| 24 |
+
handled.
|
| 25 |
+
|
| 26 |
+
Schema requirement: a paired schema must declare
|
| 27 |
+
AnnotationLossSpec(field="annotation.vqa_answer",
|
| 28 |
+
loss_type="ce_text",
|
| 29 |
+
weight=1.0,
|
| 30 |
+
max_length=...).
|
| 31 |
+
See `schemas/robointer_vqa.py`.
|
| 32 |
+
"""
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
import io
|
| 36 |
+
import json
|
| 37 |
+
import logging
|
| 38 |
+
import os
|
| 39 |
+
from bisect import bisect_right
|
| 40 |
+
from dataclasses import dataclass
|
| 41 |
+
from typing import Any, Sequence
|
| 42 |
+
|
| 43 |
+
import torch
|
| 44 |
+
from PIL import Image, UnidentifiedImageError
|
| 45 |
+
from torch.utils.data import Dataset
|
| 46 |
+
|
| 47 |
+
from src.dataset.adapters.robointer_token_budget import ROBOINTER_BUDGET, RoboInterTokenBudget
|
| 48 |
+
from src.utils.storage_retry import run_with_storage_retry, storage_path_exists
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# Conversations role tags. The dataset has a typo "huamn" in some val files.
|
| 52 |
+
_USER_ROLES = {"human", "huamn", "user"}
|
| 53 |
+
_ASSISTANT_ROLES = {"gpt", "assistant"}
|
| 54 |
+
_JSONL_OFFSETS_SUFFIX = ".offsets.npy"
|
| 55 |
+
_VQA_SKIP_RETRY_STRIDES = (1, 37, 1009)
|
| 56 |
+
|
| 57 |
+
# Process-wide bad-record counter. The per-dataset
|
| 58 |
+
# `_missing_image_fallback_count` resets when a dataset object is rebuilt (e.g.
|
| 59 |
+
# on resume) and does not aggregate across VQA dataset instances in the same
|
| 60 |
+
# worker process. This module-level counter keeps the silent dilution of the
|
| 61 |
+
# batch (bad records replaced by zero-supervision sentinels) observable. It does
|
| 62 |
+
# not change the default sentinel behavior and does not hard-fail.
|
| 63 |
+
_VQA_BAD_RECORD_COUNT = 0
|
| 64 |
+
# Rate-limit policy: always log the first N occurrences, then every Nth, so a
|
| 65 |
+
# steady stream of bad records keeps surfacing instead of going silent after
|
| 66 |
+
# the initial burst.
|
| 67 |
+
_VQA_BAD_RECORD_LOG_FIRST_N = 10
|
| 68 |
+
_VQA_BAD_RECORD_LOG_EVERY = 1000
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _note_vqa_bad_record() -> int:
|
| 72 |
+
"""Increment the process-wide bad-record counter and return the new total.
|
| 73 |
+
|
| 74 |
+
Returns the post-increment count so the caller can decide (via the
|
| 75 |
+
rate-limit policy) whether to emit a warning for this occurrence.
|
| 76 |
+
"""
|
| 77 |
+
global _VQA_BAD_RECORD_COUNT
|
| 78 |
+
_VQA_BAD_RECORD_COUNT += 1
|
| 79 |
+
return _VQA_BAD_RECORD_COUNT
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _should_log_vqa_bad_record(total: int) -> bool:
|
| 83 |
+
return total <= _VQA_BAD_RECORD_LOG_FIRST_N or (total % _VQA_BAD_RECORD_LOG_EVERY == 0)
|
| 84 |
+
|
| 85 |
+
# Per-task-family answer length cap (sourced from ROBOINTER_BUDGET).
|
| 86 |
+
_TASK_FAMILY_TO_ANSWER_LEN: dict[str, str] = {
|
| 87 |
+
"understanding": "vqa_understanding_answer_max_length",
|
| 88 |
+
"generation_short": "vqa_generation_short_answer_max_length",
|
| 89 |
+
"generation_traj": "vqa_generation_traj_answer_max_length",
|
| 90 |
+
"task_planning": "vqa_task_planning_answer_max_length",
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _resolve_answer_max_length(task_family: str, budget: RoboInterTokenBudget) -> int:
|
| 95 |
+
if task_family not in _TASK_FAMILY_TO_ANSWER_LEN:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
f"unknown task_family {task_family!r}; valid: "
|
| 98 |
+
f"{sorted(_TASK_FAMILY_TO_ANSWER_LEN)}"
|
| 99 |
+
)
|
| 100 |
+
return getattr(budget, _TASK_FAMILY_TO_ANSWER_LEN[task_family])
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _vqa_skip_max_attempts(dataset_len: int) -> int:
|
| 104 |
+
raw = os.environ.get("LABVLA_VQA_SKIP_MAX_ATTEMPTS", "auto").strip().lower()
|
| 105 |
+
if raw in {"", "auto", "default"}:
|
| 106 |
+
return max(64, min(1024, max(1, int(dataset_len)) // 1000))
|
| 107 |
+
try:
|
| 108 |
+
return max(1, int(raw))
|
| 109 |
+
except ValueError:
|
| 110 |
+
logging.warning(
|
| 111 |
+
"Invalid LABVLA_VQA_SKIP_MAX_ATTEMPTS=%r; using auto policy.", raw
|
| 112 |
+
)
|
| 113 |
+
return max(64, min(1024, max(1, int(dataset_len)) // 1000))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _vqa_skip_offset(attempt: int) -> int:
|
| 117 |
+
if int(attempt) <= 0:
|
| 118 |
+
return 0
|
| 119 |
+
stride = _VQA_SKIP_RETRY_STRIDES[(int(attempt) - 1) % len(_VQA_SKIP_RETRY_STRIDES)]
|
| 120 |
+
multiplier = ((int(attempt) - 1) // len(_VQA_SKIP_RETRY_STRIDES)) + 1
|
| 121 |
+
return stride * multiplier
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _infer_family_from_path(json_path: str) -> str:
|
| 125 |
+
"""Path-based family inference for ``task_family='mixed'`` manifests.
|
| 126 |
+
|
| 127 |
+
Mapping (matches RoboInter-VQA's directory layout):
|
| 128 |
+
``Task_planning/...`` β ``task_planning``
|
| 129 |
+
``Understanding/...`` β ``understanding``
|
| 130 |
+
``Generation/.../*traj_qa*.json`` β ``generation_traj``
|
| 131 |
+
``Generation/...`` β ``generation_short``
|
| 132 |
+
"""
|
| 133 |
+
p = json_path.replace("\\", "/")
|
| 134 |
+
# Match either absolute (/Task_planning/) or relative (Task_planning/) prefix.
|
| 135 |
+
parts = p.split("/")
|
| 136 |
+
if "Task_planning" in parts:
|
| 137 |
+
return "task_planning"
|
| 138 |
+
if "Understanding" in parts:
|
| 139 |
+
return "understanding"
|
| 140 |
+
if "Generation" in parts:
|
| 141 |
+
# traj_qa serializes 16-keypoint waypoints (answers up to 256 tokens);
|
| 142 |
+
# everything else (current_box, final_box, contact_box, contact_point,
|
| 143 |
+
# gripper_det) is short.
|
| 144 |
+
if "traj_qa" in p:
|
| 145 |
+
return "generation_traj"
|
| 146 |
+
return "generation_short"
|
| 147 |
+
raise ValueError(
|
| 148 |
+
f"_infer_family_from_path: cannot infer task family from path "
|
| 149 |
+
f"{json_path!r}. Expected one of Task_planning/, Understanding/, "
|
| 150 |
+
f"Generation/ in the path."
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _load_image(path: str) -> torch.Tensor:
|
| 155 |
+
"""Open + RGB-convert a JPEG/PNG, return as [3, H, W] float tensor in
|
| 156 |
+
[0, 1]. Matches the format LeRobot adapters emit, so the downstream
|
| 157 |
+
`ResizeImagesWithPadFn` (which calls `image.ndim`) works on both VQA and
|
| 158 |
+
action samples uniformly."""
|
| 159 |
+
if not storage_path_exists(path):
|
| 160 |
+
raise FileNotFoundError(f"VQA image missing: {path}")
|
| 161 |
+
|
| 162 |
+
def _read_image_bytes() -> bytes:
|
| 163 |
+
with open(path, "rb") as f:
|
| 164 |
+
return f.read()
|
| 165 |
+
|
| 166 |
+
try:
|
| 167 |
+
pil = Image.open(
|
| 168 |
+
io.BytesIO(
|
| 169 |
+
run_with_storage_retry(
|
| 170 |
+
_read_image_bytes,
|
| 171 |
+
path=path,
|
| 172 |
+
description="read VQA image",
|
| 173 |
+
)
|
| 174 |
+
)
|
| 175 |
+
).convert("RGB")
|
| 176 |
+
except (UnidentifiedImageError, OSError, ValueError) as exc:
|
| 177 |
+
raise OSError(f"VQA image unreadable: {path}: {exc}") from exc
|
| 178 |
+
# PIL (H, W, 3) uint8 -> torch (3, H, W) float32 in [0, 1].
|
| 179 |
+
import numpy as _np
|
| 180 |
+
arr = _np.asarray(pil, dtype=_np.uint8).copy()
|
| 181 |
+
tensor = torch.from_numpy(arr).permute(2, 0, 1).float() / 255.0
|
| 182 |
+
return tensor
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@dataclass
|
| 186 |
+
class _VQAMeta:
|
| 187 |
+
"""Tiny stand-in for LabVLA's adapter `.meta` interface so the
|
| 188 |
+
TransformedLeRobotDataset hydration path can find a schema. Most fields
|
| 189 |
+
not used by VQA β only `schema` and `stats` matter for hydrate_all."""
|
| 190 |
+
schema: Any
|
| 191 |
+
stats: dict
|
| 192 |
+
fps: float = 1.0
|
| 193 |
+
video_keys: tuple = ()
|
| 194 |
+
features: dict = None
|
| 195 |
+
|
| 196 |
+
def __post_init__(self):
|
| 197 |
+
if self.features is None:
|
| 198 |
+
self.features = {}
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@dataclass
|
| 202 |
+
class _VQARecordSource:
|
| 203 |
+
"""One backing record source.
|
| 204 |
+
|
| 205 |
+
Small legacy ``.json`` files are held in memory. Large ``.jsonl`` files are
|
| 206 |
+
accessed through a sidecar numpy offset index so multi-rank training does
|
| 207 |
+
not expand multi-GB JSON arrays into Python objects in every process.
|
| 208 |
+
"""
|
| 209 |
+
|
| 210 |
+
path: str
|
| 211 |
+
start: int
|
| 212 |
+
length: int
|
| 213 |
+
records: list[dict] | None = None
|
| 214 |
+
offsets: Any = None
|
| 215 |
+
family: str | None = None
|
| 216 |
+
answer_max_length: int | None = None
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _jsonl_offsets_path(jsonl_path: str) -> str:
|
| 220 |
+
return f"{jsonl_path}{_JSONL_OFFSETS_SUFFIX}"
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _load_jsonl_offsets(jsonl_path: str) -> Any:
|
| 224 |
+
offsets_path = _jsonl_offsets_path(jsonl_path)
|
| 225 |
+
if not storage_path_exists(offsets_path):
|
| 226 |
+
raise FileNotFoundError(
|
| 227 |
+
f"VQA jsonl offset index missing: {offsets_path}. "
|
| 228 |
+
"Generate it before distributed training; otherwise every rank "
|
| 229 |
+
"would have to scan/load the large metadata file."
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
import numpy as _np
|
| 233 |
+
|
| 234 |
+
offsets = _np.load(offsets_path, mmap_mode="r")
|
| 235 |
+
if getattr(offsets, "ndim", None) != 1:
|
| 236 |
+
raise ValueError(
|
| 237 |
+
f"VQA jsonl offset index must be 1-D: {offsets_path}, "
|
| 238 |
+
f"got shape={getattr(offsets, 'shape', None)}"
|
| 239 |
+
)
|
| 240 |
+
if len(offsets) <= 0:
|
| 241 |
+
raise ValueError(f"VQA jsonl offset index is empty: {offsets_path}")
|
| 242 |
+
return offsets
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _read_jsonl_record(jsonl_path: str, offset: int) -> dict:
|
| 246 |
+
def _read_line() -> bytes:
|
| 247 |
+
with open(jsonl_path, "rb") as f:
|
| 248 |
+
f.seek(int(offset))
|
| 249 |
+
return f.readline()
|
| 250 |
+
|
| 251 |
+
raw = run_with_storage_retry(
|
| 252 |
+
_read_line,
|
| 253 |
+
path=jsonl_path,
|
| 254 |
+
description="read VQA jsonl record",
|
| 255 |
+
)
|
| 256 |
+
if not raw.strip():
|
| 257 |
+
raise ValueError(f"empty VQA jsonl record at {jsonl_path}:{offset}")
|
| 258 |
+
rec = json.loads(raw.decode("utf-8"))
|
| 259 |
+
if not isinstance(rec, dict):
|
| 260 |
+
raise ValueError(
|
| 261 |
+
f"VQA jsonl record at {jsonl_path}:{offset} has type "
|
| 262 |
+
f"{type(rec).__name__}; expected dict"
|
| 263 |
+
)
|
| 264 |
+
return rec
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class RoboInterVQADataset(Dataset):
|
| 268 |
+
"""Iterable over LLaVA-format VQA records from one or more metadata files.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
json_paths: list of .json files (each is a JSON list of records) or
|
| 272 |
+
.jsonl files. JSONL files must have a sidecar
|
| 273 |
+
``<file>.offsets.npy`` int64 offset index and are read lazily.
|
| 274 |
+
image_root: absolute base dir for resolving relative image paths.
|
| 275 |
+
Records' "images" field is joined onto this root.
|
| 276 |
+
task_family: one of "understanding", "generation_short",
|
| 277 |
+
"generation_traj", "task_planning". Selects the answer-length cap
|
| 278 |
+
from ROBOINTER_BUDGET. (Caller is expected to know which json
|
| 279 |
+
corresponds to which family β there's no auto-classifier.)
|
| 280 |
+
schema: a DatasetSchema (typically `schemas.robointer_vqa.SCHEMA`)
|
| 281 |
+
attached to .meta for hydrate_all consumption.
|
| 282 |
+
budget: RoboInterTokenBudget (default = module singleton).
|
| 283 |
+
max_state_dim / max_action_dim / chunk_size: shape of the zero-filled
|
| 284 |
+
placeholders. MUST match LabVLAConfig values; default = budget.
|
| 285 |
+
primary_image_key: name under which the loaded image is stored. Maps
|
| 286 |
+
to schema.image_mapping for downstream RemapImageKeyTransformFn.
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
def __init__(
|
| 290 |
+
self,
|
| 291 |
+
json_paths: Sequence[str],
|
| 292 |
+
image_root: str,
|
| 293 |
+
task_family: str,
|
| 294 |
+
schema: Any,
|
| 295 |
+
budget: RoboInterTokenBudget = ROBOINTER_BUDGET,
|
| 296 |
+
primary_image_key: str = "observation.images.primary",
|
| 297 |
+
):
|
| 298 |
+
self.image_root = image_root
|
| 299 |
+
self.task_family = task_family
|
| 300 |
+
self.budget = budget
|
| 301 |
+
self.primary_image_key = primary_image_key
|
| 302 |
+
# task_family='mixed' enables per-record family inference from source
|
| 303 |
+
# path. Otherwise a single answer_max_length is shared across all
|
| 304 |
+
# records (V1 single-family behavior).
|
| 305 |
+
self._mixed = (task_family == "mixed")
|
| 306 |
+
if not self._mixed:
|
| 307 |
+
self.answer_max_length = _resolve_answer_max_length(task_family, budget)
|
| 308 |
+
else:
|
| 309 |
+
# Sentinel β never read in mixed mode (per-record _family decides).
|
| 310 |
+
self.answer_max_length = budget.vqa_generation_traj_answer_max_length
|
| 311 |
+
|
| 312 |
+
self.records: list[dict] = []
|
| 313 |
+
self._sources: list[_VQARecordSource] = []
|
| 314 |
+
self._source_starts: list[int] = []
|
| 315 |
+
self._num_records = 0
|
| 316 |
+
for jp in json_paths:
|
| 317 |
+
if not storage_path_exists(jp):
|
| 318 |
+
raise FileNotFoundError(f"VQA metadata missing: {jp}")
|
| 319 |
+
fam = _infer_family_from_path(jp) if self._mixed else None
|
| 320 |
+
ans_cap = (
|
| 321 |
+
_resolve_answer_max_length(fam, budget)
|
| 322 |
+
if fam is not None else None
|
| 323 |
+
)
|
| 324 |
+
if jp.endswith(".jsonl"):
|
| 325 |
+
offsets = _load_jsonl_offsets(jp)
|
| 326 |
+
self._append_source(
|
| 327 |
+
_VQARecordSource(
|
| 328 |
+
path=jp,
|
| 329 |
+
start=self._num_records,
|
| 330 |
+
length=int(len(offsets)),
|
| 331 |
+
offsets=offsets,
|
| 332 |
+
family=fam,
|
| 333 |
+
answer_max_length=ans_cap,
|
| 334 |
+
)
|
| 335 |
+
)
|
| 336 |
+
continue
|
| 337 |
+
if not jp.endswith(".json"):
|
| 338 |
+
raise ValueError(
|
| 339 |
+
f"VQA metadata file must end with .json or .jsonl: {jp}"
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
with open(jp, "r", encoding="utf-8") as f:
|
| 343 |
+
data = json.load(f)
|
| 344 |
+
if not isinstance(data, list):
|
| 345 |
+
raise ValueError(
|
| 346 |
+
f"VQA json {jp} top-level type is {type(data).__name__}; "
|
| 347 |
+
"expected list[dict]"
|
| 348 |
+
)
|
| 349 |
+
if self._mixed:
|
| 350 |
+
# Tag each record with its family + per-family answer cap so
|
| 351 |
+
# __getitem__ doesn't have to re-classify on every call.
|
| 352 |
+
for rec in data:
|
| 353 |
+
if isinstance(rec, dict):
|
| 354 |
+
rec.setdefault("_family", fam)
|
| 355 |
+
rec.setdefault("_answer_max_length", int(ans_cap))
|
| 356 |
+
self.records.extend(data)
|
| 357 |
+
else:
|
| 358 |
+
self.records.extend(data)
|
| 359 |
+
self._append_source(
|
| 360 |
+
_VQARecordSource(
|
| 361 |
+
path=jp,
|
| 362 |
+
start=self._num_records,
|
| 363 |
+
length=len(data),
|
| 364 |
+
records=data,
|
| 365 |
+
family=fam,
|
| 366 |
+
answer_max_length=ans_cap,
|
| 367 |
+
)
|
| 368 |
+
)
|
| 369 |
+
if self._num_records <= 0:
|
| 370 |
+
raise ValueError(
|
| 371 |
+
"RoboInterVQADataset loaded zero records from "
|
| 372 |
+
f"{list(json_paths)!r}"
|
| 373 |
+
)
|
| 374 |
+
# Pre-scanning all images for existence is too slow on the DPC filesystem
|
| 375 |
+
# (1.6M+ stat() calls). Bad records are handled lazily in __getitem__;
|
| 376 |
+
# default is fail-loud so corruption is not hidden by substituting a
|
| 377 |
+
# different training sample.
|
| 378 |
+
# Stand-in `.meta` so TransformedLeRobotDataset / _hydrate_unified finds
|
| 379 |
+
# a schema. stats is empty: VQA samples never go through
|
| 380 |
+
# NormalizeTransformFn (schema declares no state/action keys -> no-op).
|
| 381 |
+
self.meta = _VQAMeta(schema=schema, stats={"_vqa_no_norm": {}})
|
| 382 |
+
# TransformedLeRobotDataset late-discovery uses obj.root.
|
| 383 |
+
self.root = image_root
|
| 384 |
+
self._missing_image_fallback_count = 0
|
| 385 |
+
|
| 386 |
+
def __len__(self) -> int:
|
| 387 |
+
return self._num_records
|
| 388 |
+
|
| 389 |
+
def _append_source(self, source: _VQARecordSource) -> None:
|
| 390 |
+
if source.length <= 0:
|
| 391 |
+
return
|
| 392 |
+
self._source_starts.append(source.start)
|
| 393 |
+
self._sources.append(source)
|
| 394 |
+
self._num_records += source.length
|
| 395 |
+
|
| 396 |
+
def _record_at(self, idx: int) -> dict:
|
| 397 |
+
if idx < 0 or idx >= self._num_records:
|
| 398 |
+
raise IndexError(
|
| 399 |
+
f"VQA record index out of range: idx={idx}, len={self._num_records}"
|
| 400 |
+
)
|
| 401 |
+
source_pos = bisect_right(self._source_starts, idx) - 1
|
| 402 |
+
source = self._sources[source_pos]
|
| 403 |
+
local_idx = idx - source.start
|
| 404 |
+
if source.records is not None:
|
| 405 |
+
rec = source.records[local_idx]
|
| 406 |
+
if not isinstance(rec, dict):
|
| 407 |
+
raise ValueError(
|
| 408 |
+
f"VQA record at {source.path}[{local_idx}] has type "
|
| 409 |
+
f"{type(rec).__name__}; expected dict"
|
| 410 |
+
)
|
| 411 |
+
else:
|
| 412 |
+
rec = _read_jsonl_record(source.path, int(source.offsets[local_idx]))
|
| 413 |
+
|
| 414 |
+
if source.family is not None:
|
| 415 |
+
rec.setdefault("_family", source.family)
|
| 416 |
+
rec.setdefault("_answer_max_length", int(source.answer_max_length))
|
| 417 |
+
return rec
|
| 418 |
+
|
| 419 |
+
@staticmethod
|
| 420 |
+
def _extract_qa(rec: dict) -> tuple[str, str]:
|
| 421 |
+
"""Pull (question, answer) text from a LLaVA-format record."""
|
| 422 |
+
question, answer = "", ""
|
| 423 |
+
for turn in rec.get("conversations", []):
|
| 424 |
+
who = str(turn.get("from", "")).lower()
|
| 425 |
+
val = turn.get("value", "")
|
| 426 |
+
if who in _USER_ROLES and not question:
|
| 427 |
+
question = str(val) if val is not None else ""
|
| 428 |
+
elif who in _ASSISTANT_ROLES and not answer:
|
| 429 |
+
answer = str(val) if val is not None else ""
|
| 430 |
+
# LLaVA convention: <image> placeholder marks where the image goes.
|
| 431 |
+
# We embed the image separately via Qwen3-VL processor, so strip the
|
| 432 |
+
# placeholder from the prompt text.
|
| 433 |
+
question = question.replace("<image>\n", "").replace("<image>", "").strip()
|
| 434 |
+
return question, answer
|
| 435 |
+
|
| 436 |
+
def __getitem__(self, idx: int) -> dict:
|
| 437 |
+
# VQA metadata can contain stale paths or damaged images. Keep
|
| 438 |
+
# __getitem__(idx) deterministic: do not redirect idx to a neighbor here.
|
| 439 |
+
# If skip is enabled, return a zero-loss sentinel for this same idx; the
|
| 440 |
+
# outer SkipBadSamplesDataset remains responsible for real neighbor retry
|
| 441 |
+
# on non-VQA datasets.
|
| 442 |
+
skip_errors = os.environ.get(
|
| 443 |
+
"LABVLA_VQA_SKIP_BAD_RECORDS", "true"
|
| 444 |
+
).lower() == "true"
|
| 445 |
+
dataset_len = len(self)
|
| 446 |
+
if dataset_len <= 0:
|
| 447 |
+
raise IndexError("RoboInterVQADataset is empty")
|
| 448 |
+
try:
|
| 449 |
+
return self._getitem_inner(int(idx) % dataset_len)
|
| 450 |
+
except (
|
| 451 |
+
FileNotFoundError,
|
| 452 |
+
OSError,
|
| 453 |
+
ValueError,
|
| 454 |
+
KeyError,
|
| 455 |
+
IndexError,
|
| 456 |
+
TypeError,
|
| 457 |
+
json.JSONDecodeError,
|
| 458 |
+
) as e:
|
| 459 |
+
if not skip_errors:
|
| 460 |
+
raise
|
| 461 |
+
self._missing_image_fallback_count += 1
|
| 462 |
+
# Rate-limited warning so the silent dilution of the batch (this idx
|
| 463 |
+
# now contributes zero gradient) stays observable.
|
| 464 |
+
total = _note_vqa_bad_record()
|
| 465 |
+
if _should_log_vqa_bad_record(total):
|
| 466 |
+
logging.warning(
|
| 467 |
+
"RoboInterVQADataset bad record at idx=%s; returning "
|
| 468 |
+
"zero-loss sentinel for the same idx (process bad-record "
|
| 469 |
+
"count=%d, this-dataset count=%d). Set "
|
| 470 |
+
"LABVLA_VQA_SKIP_BAD_RECORDS=false to fail loud. error=%s",
|
| 471 |
+
idx,
|
| 472 |
+
total,
|
| 473 |
+
self._missing_image_fallback_count,
|
| 474 |
+
e,
|
| 475 |
+
)
|
| 476 |
+
return self._bad_record_sentinel(int(idx), e)
|
| 477 |
+
|
| 478 |
+
def _bad_record_sentinel(self, idx: int, exc: BaseException) -> dict:
|
| 479 |
+
"""Structurally valid sample with all supervision masks disabled."""
|
| 480 |
+
return {
|
| 481 |
+
"task": "Answer.",
|
| 482 |
+
self.primary_image_key: torch.zeros(3, 224, 224, dtype=torch.float32),
|
| 483 |
+
"observation.state": torch.zeros(self.budget.max_state_dim, dtype=torch.float32),
|
| 484 |
+
"action": torch.zeros(self.budget.chunk_size, self.budget.max_action_dim, dtype=torch.float32),
|
| 485 |
+
"action_is_pad": torch.ones(self.budget.chunk_size, dtype=torch.bool),
|
| 486 |
+
"has_real_state": False,
|
| 487 |
+
"annotation.vqa_answer": "",
|
| 488 |
+
"annotation.vqa_answer_max_length": 1,
|
| 489 |
+
"vqa_bad_record_idx": int(idx),
|
| 490 |
+
"vqa_bad_record_error": f"{type(exc).__name__}: {exc}",
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
def _getitem_inner(self, idx: int) -> dict:
|
| 494 |
+
rec = self._record_at(idx)
|
| 495 |
+
question, answer = self._extract_qa(rec)
|
| 496 |
+
|
| 497 |
+
image_paths = rec.get("images", [])
|
| 498 |
+
if isinstance(image_paths, str):
|
| 499 |
+
image_paths = [image_paths]
|
| 500 |
+
if not image_paths:
|
| 501 |
+
raise ValueError(
|
| 502 |
+
f"VQA record at idx={idx} has no images. id={rec.get('id', '?')!r}"
|
| 503 |
+
)
|
| 504 |
+
# V1: single-frame only. For task_planning's multi-frame samples, use the
|
| 505 |
+
# last frame (most informative for next-step prediction); V2 will pack
|
| 506 |
+
# all frames into a multi-image Qwen3-VL prompt. Per-record family in
|
| 507 |
+
# mixed mode falls back to self.task_family for legacy manifests.
|
| 508 |
+
record_family = rec.get("_family", self.task_family)
|
| 509 |
+
if record_family == "task_planning" and len(image_paths) > 1:
|
| 510 |
+
chosen = image_paths[-1]
|
| 511 |
+
else:
|
| 512 |
+
chosen = image_paths[0]
|
| 513 |
+
image_path = os.path.join(self.image_root, chosen)
|
| 514 |
+
try:
|
| 515 |
+
image = _load_image(image_path)
|
| 516 |
+
except Exception as exc:
|
| 517 |
+
raise type(exc)(
|
| 518 |
+
f"{exc} (vqa_idx={idx}, id={rec.get('id', '?')!r}, image={chosen!r})"
|
| 519 |
+
) from exc
|
| 520 |
+
|
| 521 |
+
sample: dict[str, Any] = {
|
| 522 |
+
# Prompt for Qwen3VL processor.
|
| 523 |
+
"task": question if question else "Answer.",
|
| 524 |
+
# Single image β RemapImageKeyTransformFn will remap to image0.
|
| 525 |
+
self.primary_image_key: image,
|
| 526 |
+
# Zero-fill state + action. VQA has no proprioception; downstream
|
| 527 |
+
# MSE is skipped via action_is_pad=True.
|
| 528 |
+
"observation.state": torch.zeros(self.budget.max_state_dim, dtype=torch.float32),
|
| 529 |
+
"action": torch.zeros(self.budget.chunk_size, self.budget.max_action_dim, dtype=torch.float32),
|
| 530 |
+
"action_is_pad": torch.ones(self.budget.chunk_size, dtype=torch.bool),
|
| 531 |
+
# Skip state discretization (no real proprioception).
|
| 532 |
+
"has_real_state": False,
|
| 533 |
+
# Supervision target β tokenized by AnnotationTokenizeTransformFn.
|
| 534 |
+
"annotation.vqa_answer": answer,
|
| 535 |
+
# Per-sample max_length override. The schema declares the union upper
|
| 536 |
+
# bound (256, sized for generation_traj); AnnotationTokenizeTransformFn
|
| 537 |
+
# honors this task-family-specific cap via the f"{spec.field}_max_length"
|
| 538 |
+
# convention, clamping real-token CE to the family's answer length. In
|
| 539 |
+
# mixed mode this is the per-record cap; otherwise the constructor cap.
|
| 540 |
+
"annotation.vqa_answer_max_length": int(
|
| 541 |
+
rec.get("_answer_max_length", self.answer_max_length)
|
| 542 |
+
),
|
| 543 |
+
}
|
| 544 |
+
return sample
|
src/dataset/pi0_mixture.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ο0-style volume-weighted multi-dataset mixing.
|
| 2 |
+
|
| 3 |
+
Implements the processor-granularity n^0.43 formula from the Ο0 paper
|
| 4 |
+
(Section V-A: "we weight each task-robot combination by n^0.43").
|
| 5 |
+
|
| 6 |
+
Unlike MultiLeRobotDataset (concat-by-length) or MultiStreamingLeRobotDataset
|
| 7 |
+
(IterableDataset), this is a map-style Dataset that performs weighted random
|
| 8 |
+
adapter selection per __getitem__. Each sub-dataset is assumed to be a
|
| 9 |
+
TransformedAdapterDataset around a LeRobot adapter β its __getitem__ returns
|
| 10 |
+
a transform-ready frame dict.
|
| 11 |
+
|
| 12 |
+
Caller contract:
|
| 13 |
+
- `datasets`: list of map-style Datasets with a valid __len__
|
| 14 |
+
- `weights`: non-negative floats, one per dataset; normalized internally
|
| 15 |
+
- `repo_ids`: optional list[str] for logging
|
| 16 |
+
- `seed`: base seed for deterministic sampling (default 42)
|
| 17 |
+
|
| 18 |
+
Sampling is deterministic w.r.t. (epoch, idx): per-call seed =
|
| 19 |
+
numpy.SeedSequence([seed, epoch, idx]) -> default_rng. (The Python `random`
|
| 20 |
+
module is non-deterministic across ranks/resume and leaks state across
|
| 21 |
+
DataLoader workers.) Use `set_epoch(epoch)` (DistributedSampler convention) to
|
| 22 |
+
advance the seed each epoch. `__len__` returns the sum of per-dataset lengths so
|
| 23 |
+
DataLoader sizing is unchanged.
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import logging
|
| 28 |
+
from typing import Iterator, Sequence
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
from torch.utils.data import Dataset, Sampler
|
| 32 |
+
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PI0MixtureDataset(Dataset):
|
| 37 |
+
"""Volume-weighted mixture of map-style Datasets."""
|
| 38 |
+
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
datasets: Sequence[Dataset],
|
| 42 |
+
weights: Sequence[float],
|
| 43 |
+
repo_ids: Sequence[str] | None = None,
|
| 44 |
+
seed: int = 42,
|
| 45 |
+
) -> None:
|
| 46 |
+
if len(datasets) != len(weights):
|
| 47 |
+
raise ValueError(
|
| 48 |
+
f"PI0MixtureDataset: len(datasets)={len(datasets)} != "
|
| 49 |
+
f"len(weights)={len(weights)}"
|
| 50 |
+
)
|
| 51 |
+
if not datasets:
|
| 52 |
+
raise ValueError("PI0MixtureDataset: requires at least one dataset")
|
| 53 |
+
self._datasets = list(datasets)
|
| 54 |
+
self._lengths = [len(d) for d in self._datasets]
|
| 55 |
+
self._total_len = sum(self._lengths)
|
| 56 |
+
|
| 57 |
+
# Normalize weights defensively (caller should have normalized).
|
| 58 |
+
weights_arr = np.asarray([float(w) for w in weights], dtype=np.float64)
|
| 59 |
+
if (weights_arr < 0).any():
|
| 60 |
+
raise ValueError(f"PI0MixtureDataset: weights must be non-negative, got {weights_arr.tolist()}")
|
| 61 |
+
total = float(weights_arr.sum())
|
| 62 |
+
if total <= 0:
|
| 63 |
+
raise ValueError(f"PI0MixtureDataset: sum(weights)={total} <= 0")
|
| 64 |
+
self._weights = weights_arr / total
|
| 65 |
+
|
| 66 |
+
# Reject zero-length sub-datasets with positive weight. Both __getitem__
|
| 67 |
+
# and PI0MixtureBatchSampler call rng.integers(0, len(ds)), which raises
|
| 68 |
+
# "low >= high" the moment such a dataset is sampled; fail loud at
|
| 69 |
+
# construction instead of mid-training. Zero-length with zero weight is
|
| 70 |
+
# harmless (rng.choice with p=0 never selects it) and allowed.
|
| 71 |
+
empty_weighted = [
|
| 72 |
+
(repo_ids[i] if repo_ids is not None else f"dataset[{i}]")
|
| 73 |
+
for i in range(len(self._datasets))
|
| 74 |
+
if self._lengths[i] == 0 and self._weights[i] > 0
|
| 75 |
+
]
|
| 76 |
+
if empty_weighted:
|
| 77 |
+
raise ValueError(
|
| 78 |
+
f"PI0MixtureDataset: zero-length sub-dataset(s) with positive "
|
| 79 |
+
f"weight: {empty_weighted}. Drop these datasets (and renormalize "
|
| 80 |
+
f"weights) or set their weight to 0 before constructing the "
|
| 81 |
+
f"mixture β otherwise sampling one raises 'low >= high'."
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
self._repo_ids = list(repo_ids) if repo_ids is not None else [
|
| 85 |
+
f"dataset[{i}]" for i in range(len(self._datasets))
|
| 86 |
+
]
|
| 87 |
+
|
| 88 |
+
# Deterministic RNG state.
|
| 89 |
+
self._base_seed = int(seed)
|
| 90 |
+
self._epoch = 0
|
| 91 |
+
|
| 92 |
+
pairs = ", ".join(
|
| 93 |
+
f"{r}={w:.3f}" for r, w in zip(self._repo_ids, self._weights)
|
| 94 |
+
)
|
| 95 |
+
logger.info(f"[Ο0-mix] weights: [{pairs}]")
|
| 96 |
+
logger.info(
|
| 97 |
+
f"[Ο0-mix] total_len={self._total_len:,} "
|
| 98 |
+
f"({[l for l in self._lengths]} frames per dataset) "
|
| 99 |
+
f"seed={self._base_seed}"
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def set_epoch(self, epoch: int) -> None:
|
| 103 |
+
"""Advance the deterministic-sampling epoch.
|
| 104 |
+
|
| 105 |
+
Mirrors ``torch.utils.data.distributed.DistributedSampler.set_epoch``
|
| 106 |
+
β call before each new epoch so that per-(epoch, idx) RNG seeds
|
| 107 |
+
differ across epochs while still being identical across ranks for
|
| 108 |
+
the same epoch.
|
| 109 |
+
"""
|
| 110 |
+
self._epoch = int(epoch)
|
| 111 |
+
|
| 112 |
+
def __len__(self) -> int:
|
| 113 |
+
return self._total_len
|
| 114 |
+
|
| 115 |
+
def __getitem__(self, idx: int | tuple[int, int]) -> dict:
|
| 116 |
+
if isinstance(idx, tuple):
|
| 117 |
+
dataset_index, local_index = idx
|
| 118 |
+
dataset_index = int(dataset_index)
|
| 119 |
+
local_index = int(local_index)
|
| 120 |
+
if not 0 <= dataset_index < len(self._datasets):
|
| 121 |
+
raise IndexError(
|
| 122 |
+
f"PI0MixtureDataset direct dataset index {dataset_index} "
|
| 123 |
+
f"out of range [0, {len(self._datasets)})"
|
| 124 |
+
)
|
| 125 |
+
if not 0 <= local_index < self._lengths[dataset_index]:
|
| 126 |
+
raise IndexError(
|
| 127 |
+
f"PI0MixtureDataset direct local index {local_index} "
|
| 128 |
+
f"out of range [0, {self._lengths[dataset_index]}) "
|
| 129 |
+
f"for dataset {dataset_index}"
|
| 130 |
+
)
|
| 131 |
+
return self._datasets[dataset_index][local_index]
|
| 132 |
+
|
| 133 |
+
# Deterministic per-(base_seed, epoch, idx) RNG: two ranks asking the
|
| 134 |
+
# same idx in the same epoch get the same sample, making resume
|
| 135 |
+
# reproducible. The DataLoader index is a nominal counter (Ο0 convention)
|
| 136 |
+
# used only as a seed component, not as direct selection content, so
|
| 137 |
+
# different idx values still draw different samples within an epoch.
|
| 138 |
+
ss = np.random.SeedSequence([self._base_seed, self._epoch, int(idx)])
|
| 139 |
+
rng = np.random.default_rng(ss)
|
| 140 |
+
ds_idx = int(rng.choice(len(self._datasets), p=self._weights))
|
| 141 |
+
ds = self._datasets[ds_idx]
|
| 142 |
+
local_idx = int(rng.integers(0, len(ds)))
|
| 143 |
+
return ds[local_idx]
|
| 144 |
+
|
| 145 |
+
# Expose per-dataset metadata for downstream logging / checkpointing.
|
| 146 |
+
@property
|
| 147 |
+
def num_frames(self) -> int:
|
| 148 |
+
return self._total_len
|
| 149 |
+
|
| 150 |
+
@property
|
| 151 |
+
def num_episodes(self) -> int:
|
| 152 |
+
total = 0
|
| 153 |
+
for ds in self._datasets:
|
| 154 |
+
n = getattr(ds, "num_episodes", None)
|
| 155 |
+
if n is None:
|
| 156 |
+
adapter = getattr(ds, "adapter", None)
|
| 157 |
+
n = getattr(adapter, "num_episodes", None) if adapter is not None else None
|
| 158 |
+
if n is not None:
|
| 159 |
+
total += int(n)
|
| 160 |
+
return total
|
| 161 |
+
|
| 162 |
+
@property
|
| 163 |
+
def weights(self) -> list[float]:
|
| 164 |
+
return list(self._weights)
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def repo_ids(self) -> list[str]:
|
| 168 |
+
return list(self._repo_ids)
|
| 169 |
+
|
| 170 |
+
@property
|
| 171 |
+
def epoch(self) -> int:
|
| 172 |
+
return self._epoch
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def base_seed(self) -> int:
|
| 176 |
+
return self._base_seed
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class PI0MixtureBatchSampler(Sampler[list[tuple[int, int]]]):
|
| 180 |
+
"""Homogeneous mini-batches for ``PI0MixtureDataset``.
|
| 181 |
+
|
| 182 |
+
Choose exactly one source dataset per mini-batch, then sample all local
|
| 183 |
+
indices from that source. This preserves Ο0-style weighted mixture
|
| 184 |
+
semantics at the batch level while preventing one heterogeneous collate
|
| 185 |
+
from taking the union of every annotation/FAST field across unrelated
|
| 186 |
+
dataset schemas.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
def __init__(
|
| 190 |
+
self,
|
| 191 |
+
dataset: PI0MixtureDataset,
|
| 192 |
+
batch_size: int,
|
| 193 |
+
drop_last: bool = True,
|
| 194 |
+
seed: int | None = None,
|
| 195 |
+
start_batch_index: int = 0,
|
| 196 |
+
) -> None:
|
| 197 |
+
if not isinstance(dataset, PI0MixtureDataset):
|
| 198 |
+
raise TypeError(
|
| 199 |
+
"PI0MixtureBatchSampler requires a PI0MixtureDataset, got "
|
| 200 |
+
f"{type(dataset).__name__}"
|
| 201 |
+
)
|
| 202 |
+
if int(batch_size) <= 0:
|
| 203 |
+
raise ValueError(f"batch_size must be positive, got {batch_size}")
|
| 204 |
+
self.dataset = dataset
|
| 205 |
+
self.batch_size = int(batch_size)
|
| 206 |
+
self.drop_last = bool(drop_last)
|
| 207 |
+
self._base_seed = dataset.base_seed if seed is None else int(seed)
|
| 208 |
+
self.start_batch_index = max(0, int(start_batch_index))
|
| 209 |
+
|
| 210 |
+
def set_start_batch_index(self, start_batch_index: int) -> None:
|
| 211 |
+
self.start_batch_index = max(0, int(start_batch_index))
|
| 212 |
+
|
| 213 |
+
def __len__(self) -> int:
|
| 214 |
+
total = len(self.dataset)
|
| 215 |
+
if self.drop_last:
|
| 216 |
+
total_batches = total // self.batch_size
|
| 217 |
+
else:
|
| 218 |
+
total_batches = (total + self.batch_size - 1) // self.batch_size
|
| 219 |
+
return max(0, total_batches - min(self.start_batch_index, total_batches))
|
| 220 |
+
|
| 221 |
+
def __iter__(self) -> Iterator[list[tuple[int, int]]]:
|
| 222 |
+
epoch = int(self.dataset.epoch)
|
| 223 |
+
if self.drop_last:
|
| 224 |
+
total_batches = len(self.dataset) // self.batch_size
|
| 225 |
+
else:
|
| 226 |
+
total_batches = (len(self.dataset) + self.batch_size - 1) // self.batch_size
|
| 227 |
+
start = min(self.start_batch_index, total_batches)
|
| 228 |
+
for batch_index in range(start, total_batches):
|
| 229 |
+
current_batch_size = self.batch_size
|
| 230 |
+
if not self.drop_last and batch_index == total_batches - 1:
|
| 231 |
+
remainder = len(self.dataset) % self.batch_size
|
| 232 |
+
if remainder:
|
| 233 |
+
current_batch_size = remainder
|
| 234 |
+
|
| 235 |
+
seed_sequence = np.random.SeedSequence(
|
| 236 |
+
[self._base_seed, epoch, int(batch_index), 271828]
|
| 237 |
+
)
|
| 238 |
+
rng = np.random.default_rng(seed_sequence)
|
| 239 |
+
dataset_index = int(
|
| 240 |
+
rng.choice(len(self.dataset._datasets), p=self.dataset._weights)
|
| 241 |
+
)
|
| 242 |
+
source_length = self.dataset._lengths[dataset_index]
|
| 243 |
+
local_indices = rng.integers(
|
| 244 |
+
0, source_length, size=current_batch_size
|
| 245 |
+
)
|
| 246 |
+
yield [
|
| 247 |
+
(dataset_index, int(local_index))
|
| 248 |
+
for local_index in local_indices
|
| 249 |
+
]
|
src/dataset/transforms.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
import collections
|
| 17 |
+
import hashlib
|
| 18 |
+
from collections.abc import Callable, Sequence
|
| 19 |
+
from dataclasses import dataclass, field
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from torchvision.transforms import v2
|
| 24 |
+
from torchvision.transforms.v2 import (
|
| 25 |
+
Transform,
|
| 26 |
+
functional as F, # noqa: N812
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class RandomSubsetApply(Transform):
|
| 31 |
+
"""Apply a random subset of N transformations from a list of transformations.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
transforms: list of transformations.
|
| 35 |
+
p: represents the multinomial probabilities (with no replacement) used for sampling the transform.
|
| 36 |
+
If the sum of the weights is not 1, they will be normalized. If ``None`` (default), all transforms
|
| 37 |
+
have the same probability.
|
| 38 |
+
n_subset: number of transformations to apply. If ``None``, all transforms are applied.
|
| 39 |
+
Must be in [1, len(transforms)].
|
| 40 |
+
random_order: apply transformations in a random order.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
transforms: Sequence[Callable],
|
| 46 |
+
p: list[float] | None = None,
|
| 47 |
+
n_subset: int | None = None,
|
| 48 |
+
random_order: bool = False,
|
| 49 |
+
) -> None:
|
| 50 |
+
super().__init__()
|
| 51 |
+
if not isinstance(transforms, Sequence):
|
| 52 |
+
raise TypeError("Argument transforms should be a sequence of callables")
|
| 53 |
+
if p is None:
|
| 54 |
+
p = [1] * len(transforms)
|
| 55 |
+
elif len(p) != len(transforms):
|
| 56 |
+
raise ValueError(
|
| 57 |
+
f"Length of p doesn't match the number of transforms: {len(p)} != {len(transforms)}"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
if n_subset is None:
|
| 61 |
+
n_subset = len(transforms)
|
| 62 |
+
elif not isinstance(n_subset, int):
|
| 63 |
+
raise TypeError("n_subset should be an int or None")
|
| 64 |
+
elif not (1 <= n_subset <= len(transforms)):
|
| 65 |
+
raise ValueError(f"n_subset should be in the interval [1, {len(transforms)}]")
|
| 66 |
+
|
| 67 |
+
self.transforms = transforms
|
| 68 |
+
total = sum(p)
|
| 69 |
+
self.p = [prob / total for prob in p]
|
| 70 |
+
self.n_subset = n_subset
|
| 71 |
+
self.random_order = random_order
|
| 72 |
+
|
| 73 |
+
self.selected_transforms = None
|
| 74 |
+
|
| 75 |
+
def forward(self, *inputs: Any) -> Any:
|
| 76 |
+
needs_unpacking = len(inputs) > 1
|
| 77 |
+
|
| 78 |
+
selected_indices = torch.multinomial(torch.tensor(self.p), self.n_subset)
|
| 79 |
+
if not self.random_order:
|
| 80 |
+
selected_indices = selected_indices.sort().values
|
| 81 |
+
|
| 82 |
+
self.selected_transforms = [self.transforms[i] for i in selected_indices]
|
| 83 |
+
|
| 84 |
+
for transform in self.selected_transforms:
|
| 85 |
+
outputs = transform(*inputs)
|
| 86 |
+
inputs = outputs if needs_unpacking else (outputs,)
|
| 87 |
+
|
| 88 |
+
return outputs
|
| 89 |
+
|
| 90 |
+
def extra_repr(self) -> str:
|
| 91 |
+
return (
|
| 92 |
+
f"transforms={self.transforms}, "
|
| 93 |
+
f"p={self.p}, "
|
| 94 |
+
f"n_subset={self.n_subset}, "
|
| 95 |
+
f"random_order={self.random_order}"
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class SharpnessJitter(Transform):
|
| 100 |
+
"""Randomly change the sharpness of an image or video.
|
| 101 |
+
|
| 102 |
+
Similar to a v2.RandomAdjustSharpness with p=1 and a sharpness_factor sampled randomly.
|
| 103 |
+
While v2.RandomAdjustSharpness applies β with a given probability β a fixed sharpness_factor to an image,
|
| 104 |
+
SharpnessJitter applies a random sharpness_factor each time. This is to have a more diverse set of
|
| 105 |
+
augmentations as a result.
|
| 106 |
+
|
| 107 |
+
A sharpness_factor of 0 gives a blurred image, 1 gives the original image while 2 increases the sharpness
|
| 108 |
+
by a factor of 2.
|
| 109 |
+
|
| 110 |
+
If the input is a :class:`torch.Tensor`,
|
| 111 |
+
it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
sharpness: How much to jitter sharpness. sharpness_factor is chosen uniformly from
|
| 115 |
+
[max(0, 1 - sharpness), 1 + sharpness] or the given
|
| 116 |
+
[min, max]. Should be non negative numbers.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def __init__(self, sharpness: float | Sequence[float]) -> None:
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.sharpness = self._check_input(sharpness)
|
| 122 |
+
|
| 123 |
+
def _check_input(self, sharpness):
|
| 124 |
+
if isinstance(sharpness, (int | float)):
|
| 125 |
+
if sharpness < 0:
|
| 126 |
+
raise ValueError("If sharpness is a single number, it must be non negative.")
|
| 127 |
+
sharpness = [1.0 - sharpness, 1.0 + sharpness]
|
| 128 |
+
sharpness[0] = max(sharpness[0], 0.0)
|
| 129 |
+
elif isinstance(sharpness, collections.abc.Sequence) and len(sharpness) == 2:
|
| 130 |
+
sharpness = [float(v) for v in sharpness]
|
| 131 |
+
else:
|
| 132 |
+
raise TypeError(f"{sharpness=} should be a single number or a sequence with length 2.")
|
| 133 |
+
|
| 134 |
+
if not 0.0 <= sharpness[0] <= sharpness[1]:
|
| 135 |
+
raise ValueError(f"sharpness values should be between (0., inf), but got {sharpness}.")
|
| 136 |
+
|
| 137 |
+
return float(sharpness[0]), float(sharpness[1])
|
| 138 |
+
|
| 139 |
+
def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]:
|
| 140 |
+
sharpness_factor = torch.empty(1).uniform_(self.sharpness[0], self.sharpness[1]).item()
|
| 141 |
+
return {"sharpness_factor": sharpness_factor}
|
| 142 |
+
|
| 143 |
+
def transform(self, inpt: Any, params: dict[str, Any]) -> Any:
|
| 144 |
+
sharpness_factor = params["sharpness_factor"]
|
| 145 |
+
return self._call_kernel(F.adjust_sharpness, inpt, sharpness_factor=sharpness_factor)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@dataclass
|
| 149 |
+
class ImageTransformConfig:
|
| 150 |
+
"""
|
| 151 |
+
For each transform, the following parameters are available:
|
| 152 |
+
weight: This represents the multinomial probability (with no replacement)
|
| 153 |
+
used for sampling the transform. If the sum of the weights is not 1,
|
| 154 |
+
they will be normalized.
|
| 155 |
+
type: The name of the class used. This is either a class available under torchvision.transforms.v2 or a
|
| 156 |
+
custom transform defined here.
|
| 157 |
+
kwargs: Lower & upper bound respectively used for sampling the transform's parameter
|
| 158 |
+
(following uniform distribution) when it's applied.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
weight: float = 1.0
|
| 162 |
+
type: str = "Identity"
|
| 163 |
+
kwargs: dict[str, Any] = field(default_factory=dict)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@dataclass
|
| 167 |
+
class ImageTransformsConfig:
|
| 168 |
+
"""
|
| 169 |
+
These transforms are all using standard torchvision.transforms.v2
|
| 170 |
+
You can find out how these transformations affect images here:
|
| 171 |
+
https://pytorch.org/vision/0.18/auto_examples/transforms/plot_transforms_illustrations.html
|
| 172 |
+
We use a custom RandomSubsetApply container to sample them.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
# Set this flag to `true` to enable transforms during training
|
| 176 |
+
enable: bool = False
|
| 177 |
+
# This is the maximum number of transforms (sampled from these below) that will be applied to each frame.
|
| 178 |
+
# It's an integer in the interval [1, number_of_available_transforms].
|
| 179 |
+
max_num_transforms: int = 3
|
| 180 |
+
# By default, transforms are applied in Torchvision's suggested order (shown below).
|
| 181 |
+
# Set this to True to apply them in a random order.
|
| 182 |
+
random_order: bool = False
|
| 183 |
+
tfs: dict[str, ImageTransformConfig] = field(
|
| 184 |
+
default_factory=lambda: {
|
| 185 |
+
"brightness": ImageTransformConfig(
|
| 186 |
+
weight=1.0,
|
| 187 |
+
type="ColorJitter",
|
| 188 |
+
kwargs={"brightness": (0.8, 1.2)},
|
| 189 |
+
),
|
| 190 |
+
"contrast": ImageTransformConfig(
|
| 191 |
+
weight=1.0,
|
| 192 |
+
type="ColorJitter",
|
| 193 |
+
kwargs={"contrast": (0.8, 1.2)},
|
| 194 |
+
),
|
| 195 |
+
"saturation": ImageTransformConfig(
|
| 196 |
+
weight=1.0,
|
| 197 |
+
type="ColorJitter",
|
| 198 |
+
kwargs={"saturation": (0.5, 1.5)},
|
| 199 |
+
),
|
| 200 |
+
"hue": ImageTransformConfig(
|
| 201 |
+
weight=1.0,
|
| 202 |
+
type="ColorJitter",
|
| 203 |
+
kwargs={"hue": (-0.05, 0.05)},
|
| 204 |
+
),
|
| 205 |
+
"sharpness": ImageTransformConfig(
|
| 206 |
+
weight=1.0,
|
| 207 |
+
type="SharpnessJitter",
|
| 208 |
+
kwargs={"sharpness": (0.5, 1.5)},
|
| 209 |
+
),
|
| 210 |
+
"affine": ImageTransformConfig(
|
| 211 |
+
weight=1.0,
|
| 212 |
+
type="RandomAffine",
|
| 213 |
+
kwargs={"degrees": (-5.0, 5.0), "translate": (0.05, 0.05)},
|
| 214 |
+
),
|
| 215 |
+
}
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def make_transform_from_config(cfg: ImageTransformConfig):
|
| 220 |
+
if cfg.type == "Identity":
|
| 221 |
+
return v2.Identity(**cfg.kwargs)
|
| 222 |
+
elif cfg.type == "ColorJitter":
|
| 223 |
+
return v2.ColorJitter(**cfg.kwargs)
|
| 224 |
+
elif cfg.type == "SharpnessJitter":
|
| 225 |
+
return SharpnessJitter(**cfg.kwargs)
|
| 226 |
+
elif cfg.type == "RandomAffine":
|
| 227 |
+
return v2.RandomAffine(**cfg.kwargs)
|
| 228 |
+
else:
|
| 229 |
+
raise ValueError(f"Transform '{cfg.type}' is not valid.")
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class ImageTransforms(Transform):
|
| 233 |
+
"""A class to compose image transforms based on configuration."""
|
| 234 |
+
|
| 235 |
+
def __init__(self, cfg: ImageTransformsConfig) -> None:
|
| 236 |
+
super().__init__()
|
| 237 |
+
self._cfg = cfg
|
| 238 |
+
|
| 239 |
+
self.weights = []
|
| 240 |
+
self.transforms = {}
|
| 241 |
+
for tf_name, tf_cfg in cfg.tfs.items():
|
| 242 |
+
if tf_cfg.weight <= 0.0:
|
| 243 |
+
continue
|
| 244 |
+
|
| 245 |
+
self.transforms[tf_name] = make_transform_from_config(tf_cfg)
|
| 246 |
+
self.weights.append(tf_cfg.weight)
|
| 247 |
+
|
| 248 |
+
n_subset = min(len(self.transforms), cfg.max_num_transforms)
|
| 249 |
+
if n_subset == 0 or not cfg.enable:
|
| 250 |
+
self.tf = v2.Identity()
|
| 251 |
+
else:
|
| 252 |
+
self.tf = RandomSubsetApply(
|
| 253 |
+
transforms=list(self.transforms.values()),
|
| 254 |
+
p=self.weights,
|
| 255 |
+
n_subset=n_subset,
|
| 256 |
+
random_order=cfg.random_order,
|
| 257 |
+
)
|
| 258 |
+
self._base_seed = 0
|
| 259 |
+
self._epoch = 0
|
| 260 |
+
# Per-sample augmentation seeds include the epoch, but a local `_epoch`
|
| 261 |
+
# int is frozen inside DataLoader worker processes (fork-time snapshot;
|
| 262 |
+
# with persistent_workers it never updates), so every epoch would
|
| 263 |
+
# re-apply identical jitter to every sample. A multiprocessing.Value
|
| 264 |
+
# lives in shared memory, so the main process's set_epoch() write is
|
| 265 |
+
# visible live to all forked workers. Best-effort: on failure we fall
|
| 266 |
+
# back to the local int.
|
| 267 |
+
try:
|
| 268 |
+
import multiprocessing as _mp
|
| 269 |
+
self._epoch_shared = _mp.Value("i", 0)
|
| 270 |
+
except Exception:
|
| 271 |
+
self._epoch_shared = None
|
| 272 |
+
|
| 273 |
+
def __getstate__(self):
|
| 274 |
+
# multiprocessing.Value is fork-inheritable but not picklable; drop it
|
| 275 |
+
# for spawn-pickled copies (they fall back to the local _epoch snapshot).
|
| 276 |
+
state = self.__dict__.copy()
|
| 277 |
+
state.pop("_epoch_shared", None)
|
| 278 |
+
return state
|
| 279 |
+
|
| 280 |
+
def set_base_seed(self, seed: int) -> None:
|
| 281 |
+
self._base_seed = int(seed)
|
| 282 |
+
|
| 283 |
+
def set_epoch(self, epoch: int) -> None:
|
| 284 |
+
self._epoch = int(epoch)
|
| 285 |
+
shared = getattr(self, "_epoch_shared", None)
|
| 286 |
+
if shared is not None:
|
| 287 |
+
try:
|
| 288 |
+
with shared.get_lock():
|
| 289 |
+
shared.value = int(epoch)
|
| 290 |
+
except Exception:
|
| 291 |
+
pass
|
| 292 |
+
|
| 293 |
+
def _current_epoch(self) -> int:
|
| 294 |
+
"""Live epoch: prefer the fork-shared value (visible across workers)."""
|
| 295 |
+
shared = getattr(self, "_epoch_shared", None)
|
| 296 |
+
if shared is not None:
|
| 297 |
+
try:
|
| 298 |
+
return int(shared.value)
|
| 299 |
+
except Exception:
|
| 300 |
+
pass
|
| 301 |
+
return int(self._epoch)
|
| 302 |
+
|
| 303 |
+
def _seed_from_parts(self, seed_parts: Sequence[Any]) -> int:
|
| 304 |
+
h = hashlib.blake2b(digest_size=8)
|
| 305 |
+
for part in (self._base_seed, self._current_epoch(), *seed_parts):
|
| 306 |
+
h.update(repr(part).encode("utf-8"))
|
| 307 |
+
h.update(b"\0")
|
| 308 |
+
return int.from_bytes(h.digest(), byteorder="little", signed=False) % (2**63 - 1)
|
| 309 |
+
|
| 310 |
+
def apply_with_seed(self, *inputs: Any, seed_parts: Sequence[Any]) -> Any:
|
| 311 |
+
"""Apply augmentation with stateless per-sample randomness.
|
| 312 |
+
|
| 313 |
+
DataLoader workers may resume from a checkpoint at a non-zero sampler
|
| 314 |
+
cursor. If augmentation consumes the worker-global torch RNG sequence,
|
| 315 |
+
full resume changes image jitter even when the sample index is restored.
|
| 316 |
+
This method derives a deterministic torch seed from stable sample
|
| 317 |
+
metadata while preserving the caller's ambient RNG state.
|
| 318 |
+
"""
|
| 319 |
+
seed = self._seed_from_parts(seed_parts)
|
| 320 |
+
with torch.random.fork_rng(devices=[]):
|
| 321 |
+
torch.manual_seed(seed)
|
| 322 |
+
return self.forward(*inputs)
|
| 323 |
+
|
| 324 |
+
def forward(self, *inputs: Any) -> Any:
|
| 325 |
+
return self.tf(*inputs)
|
src/dataset/utils.py
ADDED
|
@@ -0,0 +1,1283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
import contextlib
|
| 17 |
+
import importlib.resources
|
| 18 |
+
import json
|
| 19 |
+
import logging
|
| 20 |
+
from collections import deque
|
| 21 |
+
from collections.abc import Iterable, Iterator
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from pprint import pformat
|
| 24 |
+
from typing import Any, Generic, TypeVar
|
| 25 |
+
|
| 26 |
+
import datasets
|
| 27 |
+
import numpy as np
|
| 28 |
+
import packaging.version
|
| 29 |
+
import pandas
|
| 30 |
+
import pandas as pd
|
| 31 |
+
import pyarrow.dataset as pa_ds
|
| 32 |
+
import pyarrow.parquet as pq
|
| 33 |
+
import torch
|
| 34 |
+
from datasets import Dataset
|
| 35 |
+
from datasets.table import embed_table_storage
|
| 36 |
+
from huggingface_hub import DatasetCard, DatasetCardData, HfApi
|
| 37 |
+
from huggingface_hub.errors import RevisionNotFoundError
|
| 38 |
+
from PIL import Image as PILImage
|
| 39 |
+
from torchvision import transforms
|
| 40 |
+
|
| 41 |
+
from src.config.types import FeatureType, PolicyFeature
|
| 42 |
+
from src.utils.constants import ACTION, OBS_ENV_STATE, OBS_STR
|
| 43 |
+
from src.utils.utils import SuppressProgressBars, is_valid_numpy_dtype_string
|
| 44 |
+
|
| 45 |
+
DEFAULT_CHUNK_SIZE = 1000 # Max number of files per chunk
|
| 46 |
+
DEFAULT_DATA_FILE_SIZE_IN_MB = 100 # Max size per file
|
| 47 |
+
DEFAULT_VIDEO_FILE_SIZE_IN_MB = 200 # Max size per file
|
| 48 |
+
|
| 49 |
+
INFO_PATH = "meta/info.json"
|
| 50 |
+
STATS_PATH = "meta/stats.json"
|
| 51 |
+
|
| 52 |
+
EPISODES_DIR = "meta/episodes"
|
| 53 |
+
DATA_DIR = "data"
|
| 54 |
+
VIDEO_DIR = "videos"
|
| 55 |
+
|
| 56 |
+
CHUNK_FILE_PATTERN = "chunk-{chunk_index:03d}/file-{file_index:03d}"
|
| 57 |
+
DEFAULT_TASKS_PATH = "meta/tasks.parquet"
|
| 58 |
+
DEFAULT_EPISODES_PATH = EPISODES_DIR + "/" + CHUNK_FILE_PATTERN + ".parquet"
|
| 59 |
+
DEFAULT_DATA_PATH = DATA_DIR + "/" + CHUNK_FILE_PATTERN + ".parquet"
|
| 60 |
+
DEFAULT_VIDEO_PATH = VIDEO_DIR + "/{video_key}/" + CHUNK_FILE_PATTERN + ".mp4"
|
| 61 |
+
DEFAULT_IMAGE_PATH = "images/{image_key}/episode-{episode_index:06d}/frame-{frame_index:06d}.png"
|
| 62 |
+
|
| 63 |
+
DEFAULT_FEATURES = {
|
| 64 |
+
"timestamp": {"dtype": "float32", "shape": (1,), "names": None},
|
| 65 |
+
"frame_index": {"dtype": "int64", "shape": (1,), "names": None},
|
| 66 |
+
"episode_index": {"dtype": "int64", "shape": (1,), "names": None},
|
| 67 |
+
"index": {"dtype": "int64", "shape": (1,), "names": None},
|
| 68 |
+
"task_index": {"dtype": "int64", "shape": (1,), "names": None},
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
T = TypeVar("T")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_parquet_file_size_in_mb(parquet_path: str | Path) -> float:
|
| 75 |
+
metadata = pq.read_metadata(parquet_path)
|
| 76 |
+
total_uncompressed_size = 0
|
| 77 |
+
for row_group in range(metadata.num_row_groups):
|
| 78 |
+
rg_metadata = metadata.row_group(row_group)
|
| 79 |
+
for column in range(rg_metadata.num_columns):
|
| 80 |
+
col_metadata = rg_metadata.column(column)
|
| 81 |
+
total_uncompressed_size += col_metadata.total_uncompressed_size
|
| 82 |
+
return total_uncompressed_size / (1024**2)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_hf_dataset_size_in_mb(hf_ds: Dataset) -> int:
|
| 86 |
+
return hf_ds.data.nbytes // (1024**2)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def update_chunk_file_indices(chunk_idx: int, file_idx: int, chunks_size: int) -> tuple[int, int]:
|
| 90 |
+
if file_idx == chunks_size - 1:
|
| 91 |
+
file_idx = 0
|
| 92 |
+
chunk_idx += 1
|
| 93 |
+
else:
|
| 94 |
+
file_idx += 1
|
| 95 |
+
return chunk_idx, file_idx
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def load_nested_dataset(
|
| 99 |
+
pq_dir: Path, features: datasets.Features | None = None, episodes: list[int] | None = None
|
| 100 |
+
) -> Dataset:
|
| 101 |
+
"""Find parquet files in provided directory {pq_dir}/chunk-xxx/file-xxx.parquet
|
| 102 |
+
Convert parquet files to pyarrow memory mapped in a cache folder for efficient RAM usage
|
| 103 |
+
Concatenate all pyarrow references to return HF Dataset format
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
pq_dir: Directory containing parquet files
|
| 107 |
+
features: Optional features schema to ensure consistent loading of complex types like images
|
| 108 |
+
episodes: Optional list of episode indices to filter. Uses PyArrow predicate pushdown for efficiency.
|
| 109 |
+
"""
|
| 110 |
+
paths = sorted(pq_dir.glob("*/*.parquet"))
|
| 111 |
+
if len(paths) == 0:
|
| 112 |
+
raise FileNotFoundError(f"Provided directory does not contain any parquet file: {pq_dir}")
|
| 113 |
+
|
| 114 |
+
with SuppressProgressBars():
|
| 115 |
+
# When no filtering needed, Dataset uses memory-mapped loading for efficiency
|
| 116 |
+
# PyArrow loads the entire dataset into memory
|
| 117 |
+
if episodes is None:
|
| 118 |
+
return Dataset.from_parquet([str(path) for path in paths], features=features)
|
| 119 |
+
|
| 120 |
+
arrow_dataset = pa_ds.dataset(paths, format="parquet")
|
| 121 |
+
filter_expr = pa_ds.field("episode_index").isin(episodes)
|
| 122 |
+
table = arrow_dataset.to_table(filter=filter_expr)
|
| 123 |
+
|
| 124 |
+
if features is not None:
|
| 125 |
+
table = table.cast(features.arrow_schema)
|
| 126 |
+
|
| 127 |
+
return Dataset(table)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def get_parquet_num_frames(parquet_path: str | Path) -> int:
|
| 131 |
+
metadata = pq.read_metadata(parquet_path)
|
| 132 |
+
return metadata.num_rows
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def get_file_size_in_mb(file_path: Path) -> float:
|
| 136 |
+
"""Get file size on disk in megabytes.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
file_path (Path): Path to the file.
|
| 140 |
+
"""
|
| 141 |
+
file_size_bytes = file_path.stat().st_size
|
| 142 |
+
return file_size_bytes / (1024**2)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# flatten_dict/unflatten_dict live in ``utils.dict_utils`` (generic dict helpers;
|
| 146 |
+
# keeping them here forced the base ``utils`` package to import ``dataset``).
|
| 147 |
+
# Re-exported so every existing importer keeps working.
|
| 148 |
+
from src.utils.dict_utils import flatten_dict, unflatten_dict # noqa: F401
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def serialize_dict(stats: dict[str, torch.Tensor | np.ndarray | dict]) -> dict:
|
| 152 |
+
"""Serialize a dictionary containing tensors or numpy arrays to be JSON-compatible.
|
| 153 |
+
|
| 154 |
+
Converts torch.Tensor, np.ndarray, and np.generic types to lists or native Python types.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
stats (dict): A dictionary that may contain non-serializable numeric types.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
dict: A dictionary with all values converted to JSON-serializable types.
|
| 161 |
+
|
| 162 |
+
Raises:
|
| 163 |
+
NotImplementedError: If a value has an unsupported type.
|
| 164 |
+
"""
|
| 165 |
+
serialized_dict = {}
|
| 166 |
+
for key, value in flatten_dict(stats).items():
|
| 167 |
+
if isinstance(value, (torch.Tensor | np.ndarray)):
|
| 168 |
+
serialized_dict[key] = value.tolist()
|
| 169 |
+
elif isinstance(value, list) and len(value) == 0:
|
| 170 |
+
# Pass empty lists through unchanged; the typed-element branch below
|
| 171 |
+
# would index value[0] and raise IndexError.
|
| 172 |
+
serialized_dict[key] = value
|
| 173 |
+
elif isinstance(value, list) and isinstance(value[0], (int | float | list)):
|
| 174 |
+
serialized_dict[key] = value
|
| 175 |
+
elif isinstance(value, np.generic):
|
| 176 |
+
serialized_dict[key] = value.item()
|
| 177 |
+
elif isinstance(value, (int | float)):
|
| 178 |
+
serialized_dict[key] = value
|
| 179 |
+
else:
|
| 180 |
+
raise NotImplementedError(f"The value '{value}' of type '{type(value)}' is not supported.")
|
| 181 |
+
return unflatten_dict(serialized_dict)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def embed_images(dataset: datasets.Dataset) -> datasets.Dataset:
|
| 185 |
+
"""Embed image bytes into the dataset table before saving to Parquet.
|
| 186 |
+
|
| 187 |
+
This function prepares a Hugging Face dataset for serialization by converting
|
| 188 |
+
image objects into an embedded format that can be stored in Arrow/Parquet.
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
dataset (datasets.Dataset): The input dataset, possibly containing image features.
|
| 192 |
+
|
| 193 |
+
Returns:
|
| 194 |
+
datasets.Dataset: The dataset with images embedded in the table storage.
|
| 195 |
+
"""
|
| 196 |
+
# Embed image bytes into the table before saving to parquet
|
| 197 |
+
format = dataset.format
|
| 198 |
+
dataset = dataset.with_format("arrow")
|
| 199 |
+
dataset = dataset.map(embed_table_storage, batched=False)
|
| 200 |
+
dataset = dataset.with_format(**format)
|
| 201 |
+
return dataset
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def load_json(fpath: Path) -> Any:
|
| 205 |
+
"""Load data from a JSON file.
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
fpath (Path): Path to the JSON file.
|
| 209 |
+
|
| 210 |
+
Returns:
|
| 211 |
+
Any: The data loaded from the JSON file.
|
| 212 |
+
"""
|
| 213 |
+
with open(fpath) as f:
|
| 214 |
+
return json.load(f)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def write_json(data: dict, fpath: Path) -> None:
|
| 218 |
+
"""Write data to a JSON file.
|
| 219 |
+
|
| 220 |
+
Creates parent directories if they don't exist.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
data (dict): The dictionary to write.
|
| 224 |
+
fpath (Path): The path to the output JSON file.
|
| 225 |
+
"""
|
| 226 |
+
fpath.parent.mkdir(exist_ok=True, parents=True)
|
| 227 |
+
with open(fpath, "w") as f:
|
| 228 |
+
json.dump(data, f, indent=4, ensure_ascii=False)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def write_info(info: dict, local_dir: Path) -> None:
|
| 232 |
+
write_json(info, local_dir / INFO_PATH)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def load_info(local_dir: Path) -> dict:
|
| 236 |
+
"""Load dataset info metadata from its standard file path.
|
| 237 |
+
|
| 238 |
+
Also converts shape lists to tuples for consistency.
|
| 239 |
+
|
| 240 |
+
Args:
|
| 241 |
+
local_dir (Path): The root directory of the dataset.
|
| 242 |
+
|
| 243 |
+
Returns:
|
| 244 |
+
dict: The dataset information dictionary.
|
| 245 |
+
"""
|
| 246 |
+
info = load_json(local_dir / INFO_PATH)
|
| 247 |
+
for ft in info["features"].values():
|
| 248 |
+
ft["shape"] = tuple(ft["shape"])
|
| 249 |
+
return info
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def write_stats(stats: dict, local_dir: Path) -> None:
|
| 253 |
+
"""Serialize and write dataset statistics to their standard file path.
|
| 254 |
+
|
| 255 |
+
Args:
|
| 256 |
+
stats (dict): The statistics dictionary (can contain tensors/numpy arrays).
|
| 257 |
+
local_dir (Path): The root directory of the dataset.
|
| 258 |
+
"""
|
| 259 |
+
serialized_stats = serialize_dict(stats)
|
| 260 |
+
write_json(serialized_stats, local_dir / STATS_PATH)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def cast_stats_to_numpy(stats: dict) -> dict[str, dict[str, np.ndarray]]:
|
| 264 |
+
"""Recursively cast numerical values in a stats dictionary to numpy arrays.
|
| 265 |
+
|
| 266 |
+
Args:
|
| 267 |
+
stats (dict): The statistics dictionary.
|
| 268 |
+
|
| 269 |
+
Returns:
|
| 270 |
+
dict: The statistics dictionary with values cast to numpy arrays.
|
| 271 |
+
"""
|
| 272 |
+
stats = {key: np.array(value) for key, value in flatten_dict(stats).items()}
|
| 273 |
+
return unflatten_dict(stats)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def load_stats(local_dir: Path) -> dict[str, dict[str, np.ndarray]] | None:
|
| 277 |
+
"""Load dataset statistics and cast numerical values to numpy arrays.
|
| 278 |
+
|
| 279 |
+
Returns None if the stats file doesn't exist.
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
local_dir (Path): The root directory of the dataset.
|
| 283 |
+
|
| 284 |
+
Returns:
|
| 285 |
+
A dictionary of statistics or None if the file is not found.
|
| 286 |
+
"""
|
| 287 |
+
if not (local_dir / STATS_PATH).exists():
|
| 288 |
+
return None
|
| 289 |
+
stats = load_json(local_dir / STATS_PATH)
|
| 290 |
+
return cast_stats_to_numpy(stats)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def write_tasks(tasks: pandas.DataFrame, local_dir: Path) -> None:
|
| 294 |
+
path = local_dir / DEFAULT_TASKS_PATH
|
| 295 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 296 |
+
tasks.to_parquet(path)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def load_tasks(local_dir: Path) -> pandas.DataFrame:
|
| 300 |
+
tasks = pd.read_parquet(local_dir / DEFAULT_TASKS_PATH)
|
| 301 |
+
return tasks
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def write_episodes(episodes: Dataset, local_dir: Path) -> None:
|
| 305 |
+
"""Write episode metadata to a parquet file in the LeRobot v3.0 format.
|
| 306 |
+
This function writes episode-level metadata to a single parquet file.
|
| 307 |
+
Used primarily during dataset conversion (v2.1 β v3.0) and in test fixtures.
|
| 308 |
+
|
| 309 |
+
Args:
|
| 310 |
+
episodes: HuggingFace Dataset containing episode metadata
|
| 311 |
+
local_dir: Root directory where the dataset will be stored
|
| 312 |
+
"""
|
| 313 |
+
fpath = local_dir / DEFAULT_EPISODES_PATH.format(chunk_index=0, file_index=0)
|
| 314 |
+
fpath.parent.mkdir(parents=True, exist_ok=True)
|
| 315 |
+
episodes.to_parquet(fpath)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def load_episodes(local_dir: Path) -> datasets.Dataset:
|
| 319 |
+
episodes = load_nested_dataset(local_dir / EPISODES_DIR)
|
| 320 |
+
# Select episode features/columns containing references to episode data and videos
|
| 321 |
+
# (e.g. tasks, dataset_from_index, dataset_to_index, data/chunk_index, data/file_index, etc.)
|
| 322 |
+
# This is to speedup access to these data, instead of having to load episode stats.
|
| 323 |
+
episodes = episodes.select_columns([key for key in episodes.features if not key.startswith("stats/")])
|
| 324 |
+
return episodes
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def load_image_as_numpy(
|
| 328 |
+
fpath: str | Path, dtype: np.dtype = np.float32, channel_first: bool = True
|
| 329 |
+
) -> np.ndarray:
|
| 330 |
+
"""Load an image from a file into a numpy array.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
fpath (str | Path): Path to the image file.
|
| 334 |
+
dtype (np.dtype): The desired data type of the output array. If floating,
|
| 335 |
+
pixels are scaled to [0, 1].
|
| 336 |
+
channel_first (bool): If True, converts the image to (C, H, W) format.
|
| 337 |
+
Otherwise, it remains in (H, W, C) format.
|
| 338 |
+
|
| 339 |
+
Returns:
|
| 340 |
+
np.ndarray: The image as a numpy array.
|
| 341 |
+
"""
|
| 342 |
+
img = PILImage.open(fpath).convert("RGB")
|
| 343 |
+
img_array = np.array(img, dtype=dtype)
|
| 344 |
+
if channel_first: # (H, W, C) -> (C, H, W)
|
| 345 |
+
img_array = np.transpose(img_array, (2, 0, 1))
|
| 346 |
+
if np.issubdtype(dtype, np.floating):
|
| 347 |
+
img_array /= 255.0
|
| 348 |
+
return img_array
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def hf_transform_to_torch(items_dict: dict[str, list[Any]]) -> dict[str, list[torch.Tensor | str]]:
|
| 352 |
+
"""Convert a batch from a Hugging Face dataset to torch tensors.
|
| 353 |
+
|
| 354 |
+
This transform function converts items from Hugging Face dataset format (pyarrow)
|
| 355 |
+
to torch tensors. Importantly, images are converted from PIL objects (H, W, C, uint8)
|
| 356 |
+
to a torch image representation (C, H, W, float32) in the range [0, 1]. Other
|
| 357 |
+
types are converted to torch.tensor.
|
| 358 |
+
|
| 359 |
+
Args:
|
| 360 |
+
items_dict (dict): A dictionary representing a batch of data from a
|
| 361 |
+
Hugging Face dataset.
|
| 362 |
+
|
| 363 |
+
Returns:
|
| 364 |
+
dict: The batch with items converted to torch tensors.
|
| 365 |
+
"""
|
| 366 |
+
for key in items_dict:
|
| 367 |
+
first_item = items_dict[key][0]
|
| 368 |
+
if isinstance(first_item, PILImage.Image):
|
| 369 |
+
to_tensor = transforms.ToTensor()
|
| 370 |
+
items_dict[key] = [to_tensor(img) for img in items_dict[key]]
|
| 371 |
+
elif first_item is None:
|
| 372 |
+
pass
|
| 373 |
+
else:
|
| 374 |
+
items_dict[key] = [x if isinstance(x, str) else torch.tensor(x) for x in items_dict[key]]
|
| 375 |
+
return items_dict
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def is_valid_version(version: str) -> bool:
|
| 379 |
+
"""Check if a string is a valid PEP 440 version.
|
| 380 |
+
|
| 381 |
+
Args:
|
| 382 |
+
version (str): The version string to check.
|
| 383 |
+
|
| 384 |
+
Returns:
|
| 385 |
+
bool: True if the version string is valid, False otherwise.
|
| 386 |
+
"""
|
| 387 |
+
try:
|
| 388 |
+
packaging.version.parse(version)
|
| 389 |
+
return True
|
| 390 |
+
except packaging.version.InvalidVersion:
|
| 391 |
+
return False
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def get_repo_versions(repo_id: str) -> list[packaging.version.Version]:
|
| 395 |
+
"""Return available valid versions (branches and tags) on a given Hub repo.
|
| 396 |
+
|
| 397 |
+
Args:
|
| 398 |
+
repo_id (str): The repository ID on the Hugging Face Hub.
|
| 399 |
+
|
| 400 |
+
Returns:
|
| 401 |
+
list[packaging.version.Version]: A list of valid versions found.
|
| 402 |
+
"""
|
| 403 |
+
api = HfApi()
|
| 404 |
+
repo_refs = api.list_repo_refs(repo_id, repo_type="dataset")
|
| 405 |
+
repo_refs = [b.name for b in repo_refs.branches + repo_refs.tags]
|
| 406 |
+
repo_versions = []
|
| 407 |
+
for ref in repo_refs:
|
| 408 |
+
with contextlib.suppress(packaging.version.InvalidVersion):
|
| 409 |
+
repo_versions.append(packaging.version.parse(ref))
|
| 410 |
+
|
| 411 |
+
return repo_versions
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class CompatibilityError(Exception):
|
| 415 |
+
"""Base for dataset codebase-version compatibility failures (M39)."""
|
| 416 |
+
|
| 417 |
+
def __init__(self, repo_id, version):
|
| 418 |
+
self.repo_id = repo_id
|
| 419 |
+
self.version = version
|
| 420 |
+
super().__init__(
|
| 421 |
+
f"{type(self).__name__}: repo {repo_id!r} only offers an "
|
| 422 |
+
f"incompatible codebase version {version} for this reader."
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class BackwardCompatibilityError(CompatibilityError):
|
| 427 |
+
"""Repo only has an OLDER major codebase version than this code reads."""
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
class ForwardCompatibilityError(CompatibilityError):
|
| 431 |
+
"""Repo only has a NEWER major codebase version than this code reads."""
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def get_safe_version(repo_id: str, version: str | packaging.version.Version) -> str:
|
| 435 |
+
"""Return the specified version if available on repo, or the latest compatible one.
|
| 436 |
+
|
| 437 |
+
If the exact version is not found, it looks for the latest version with the
|
| 438 |
+
same major version number that is less than or equal to the target minor version.
|
| 439 |
+
|
| 440 |
+
Args:
|
| 441 |
+
repo_id (str): The repository ID on the Hugging Face Hub.
|
| 442 |
+
version (str | packaging.version.Version): The target version.
|
| 443 |
+
|
| 444 |
+
Returns:
|
| 445 |
+
str: The safe version string (e.g., "v1.2.3") to use as a revision.
|
| 446 |
+
|
| 447 |
+
Raises:
|
| 448 |
+
RevisionNotFoundError: If the repo has no version tags.
|
| 449 |
+
BackwardCompatibilityError: If only older major versions are available.
|
| 450 |
+
ForwardCompatibilityError: If only newer major versions are available.
|
| 451 |
+
"""
|
| 452 |
+
target_version = (
|
| 453 |
+
packaging.version.parse(version) if not isinstance(version, packaging.version.Version) else version
|
| 454 |
+
)
|
| 455 |
+
hub_versions = get_repo_versions(repo_id)
|
| 456 |
+
|
| 457 |
+
if not hub_versions:
|
| 458 |
+
raise RevisionNotFoundError(
|
| 459 |
+
f"""Your dataset must be tagged with a codebase version.
|
| 460 |
+
Assuming _version_ is the codebase_version value in the info.json, you can run this:
|
| 461 |
+
```python
|
| 462 |
+
from huggingface_hub import HfApi
|
| 463 |
+
|
| 464 |
+
hub_api = HfApi()
|
| 465 |
+
hub_api.create_tag("{repo_id}", tag="_version_", repo_type="dataset")
|
| 466 |
+
```
|
| 467 |
+
"""
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
if target_version in hub_versions:
|
| 471 |
+
return f"v{target_version}"
|
| 472 |
+
|
| 473 |
+
compatibles = [
|
| 474 |
+
v for v in hub_versions if v.major == target_version.major and v.minor <= target_version.minor
|
| 475 |
+
]
|
| 476 |
+
if compatibles:
|
| 477 |
+
return_version = max(compatibles)
|
| 478 |
+
if return_version < target_version:
|
| 479 |
+
logging.warning(f"Revision {version} for {repo_id} not found, using version v{return_version}")
|
| 480 |
+
return f"v{return_version}"
|
| 481 |
+
|
| 482 |
+
lower_major = [v for v in hub_versions if v.major < target_version.major]
|
| 483 |
+
if lower_major:
|
| 484 |
+
raise BackwardCompatibilityError(repo_id, max(lower_major))
|
| 485 |
+
|
| 486 |
+
upper_versions = [v for v in hub_versions if v > target_version]
|
| 487 |
+
assert len(upper_versions) > 0
|
| 488 |
+
raise ForwardCompatibilityError(repo_id, min(upper_versions))
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def get_hf_features_from_features(features: dict) -> datasets.Features:
|
| 492 |
+
"""Convert a LeRobot features dictionary to a `datasets.Features` object.
|
| 493 |
+
|
| 494 |
+
Args:
|
| 495 |
+
features (dict): A LeRobot-style feature dictionary.
|
| 496 |
+
|
| 497 |
+
Returns:
|
| 498 |
+
datasets.Features: The corresponding Hugging Face `datasets.Features` object.
|
| 499 |
+
|
| 500 |
+
Raises:
|
| 501 |
+
ValueError: If a feature has an unsupported shape.
|
| 502 |
+
"""
|
| 503 |
+
hf_features = {}
|
| 504 |
+
for key, ft in features.items():
|
| 505 |
+
if ft["dtype"] == "video":
|
| 506 |
+
continue
|
| 507 |
+
elif ft["dtype"] == "image":
|
| 508 |
+
hf_features[key] = datasets.Image()
|
| 509 |
+
elif ft["shape"] == (1,):
|
| 510 |
+
hf_features[key] = datasets.Value(dtype=ft["dtype"])
|
| 511 |
+
elif len(ft["shape"]) == 1:
|
| 512 |
+
hf_features[key] = datasets.Sequence(
|
| 513 |
+
length=ft["shape"][0], feature=datasets.Value(dtype=ft["dtype"])
|
| 514 |
+
)
|
| 515 |
+
elif len(ft["shape"]) == 2:
|
| 516 |
+
hf_features[key] = datasets.Array2D(shape=ft["shape"], dtype=ft["dtype"])
|
| 517 |
+
elif len(ft["shape"]) == 3:
|
| 518 |
+
hf_features[key] = datasets.Array3D(shape=ft["shape"], dtype=ft["dtype"])
|
| 519 |
+
elif len(ft["shape"]) == 4:
|
| 520 |
+
hf_features[key] = datasets.Array4D(shape=ft["shape"], dtype=ft["dtype"])
|
| 521 |
+
elif len(ft["shape"]) == 5:
|
| 522 |
+
hf_features[key] = datasets.Array5D(shape=ft["shape"], dtype=ft["dtype"])
|
| 523 |
+
else:
|
| 524 |
+
raise ValueError(f"Corresponding feature is not valid: {ft}")
|
| 525 |
+
|
| 526 |
+
return datasets.Features(hf_features)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def _validate_feature_names(features: dict[str, dict]) -> None:
|
| 530 |
+
"""Validate that feature names do not contain invalid characters.
|
| 531 |
+
|
| 532 |
+
Args:
|
| 533 |
+
features (dict): The LeRobot features dictionary.
|
| 534 |
+
|
| 535 |
+
Raises:
|
| 536 |
+
ValueError: If any feature name contains '/'.
|
| 537 |
+
"""
|
| 538 |
+
invalid_features = {name: ft for name, ft in features.items() if "/" in name}
|
| 539 |
+
if invalid_features:
|
| 540 |
+
raise ValueError(f"Feature names should not contain '/'. Found '/' in '{invalid_features}'.")
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def hw_to_dataset_features(
|
| 544 |
+
hw_features: dict[str, type | tuple], prefix: str, use_video: bool = True
|
| 545 |
+
) -> dict[str, dict]:
|
| 546 |
+
"""Convert hardware-specific features to a LeRobot dataset feature dictionary.
|
| 547 |
+
|
| 548 |
+
This function takes a dictionary describing hardware outputs (like joint states
|
| 549 |
+
or camera image shapes) and formats it into the standard LeRobot feature
|
| 550 |
+
specification.
|
| 551 |
+
|
| 552 |
+
Args:
|
| 553 |
+
hw_features (dict): Dictionary mapping feature names to their type (float for
|
| 554 |
+
joints) or shape (tuple for images).
|
| 555 |
+
prefix (str): The prefix to add to the feature keys (e.g., "observation"
|
| 556 |
+
or "action").
|
| 557 |
+
use_video (bool): If True, image features are marked as "video", otherwise "image".
|
| 558 |
+
|
| 559 |
+
Returns:
|
| 560 |
+
dict: A LeRobot features dictionary.
|
| 561 |
+
"""
|
| 562 |
+
features = {}
|
| 563 |
+
joint_fts = {
|
| 564 |
+
key: ftype
|
| 565 |
+
for key, ftype in hw_features.items()
|
| 566 |
+
if ftype is float or (isinstance(ftype, PolicyFeature) and ftype.type != FeatureType.VISUAL)
|
| 567 |
+
}
|
| 568 |
+
cam_fts = {key: shape for key, shape in hw_features.items() if isinstance(shape, tuple)}
|
| 569 |
+
|
| 570 |
+
if joint_fts and prefix == ACTION:
|
| 571 |
+
features[prefix] = {
|
| 572 |
+
"dtype": "float32",
|
| 573 |
+
"shape": (len(joint_fts),),
|
| 574 |
+
"names": list(joint_fts),
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
if joint_fts and prefix == OBS_STR:
|
| 578 |
+
features[f"{prefix}.state"] = {
|
| 579 |
+
"dtype": "float32",
|
| 580 |
+
"shape": (len(joint_fts),),
|
| 581 |
+
"names": list(joint_fts),
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
for key, shape in cam_fts.items():
|
| 585 |
+
features[f"{prefix}.images.{key}"] = {
|
| 586 |
+
"dtype": "video" if use_video else "image",
|
| 587 |
+
"shape": shape,
|
| 588 |
+
"names": ["height", "width", "channels"],
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
_validate_feature_names(features)
|
| 592 |
+
return features
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def build_dataset_frame(
|
| 596 |
+
ds_features: dict[str, dict], values: dict[str, Any], prefix: str
|
| 597 |
+
) -> dict[str, np.ndarray]:
|
| 598 |
+
"""Construct a single data frame from raw values based on dataset features.
|
| 599 |
+
|
| 600 |
+
A "frame" is a dictionary containing all the data for a single timestep,
|
| 601 |
+
formatted as numpy arrays according to the feature specification.
|
| 602 |
+
|
| 603 |
+
Args:
|
| 604 |
+
ds_features (dict): The LeRobot dataset features dictionary.
|
| 605 |
+
values (dict): A dictionary of raw values from the hardware/environment.
|
| 606 |
+
prefix (str): The prefix to filter features by (e.g., "observation"
|
| 607 |
+
or "action").
|
| 608 |
+
|
| 609 |
+
Returns:
|
| 610 |
+
dict: A dictionary representing a single frame of data.
|
| 611 |
+
"""
|
| 612 |
+
frame = {}
|
| 613 |
+
for key, ft in ds_features.items():
|
| 614 |
+
if key in DEFAULT_FEATURES or not key.startswith(prefix):
|
| 615 |
+
continue
|
| 616 |
+
elif ft["dtype"] == "float32" and len(ft["shape"]) == 1:
|
| 617 |
+
frame[key] = np.array([values[name] for name in ft["names"]], dtype=np.float32)
|
| 618 |
+
elif ft["dtype"] in ["image", "video"]:
|
| 619 |
+
frame[key] = values[key.removeprefix(f"{prefix}.images.")]
|
| 620 |
+
|
| 621 |
+
return frame
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def dataset_to_policy_features(features: dict[str, dict]) -> dict[str, PolicyFeature]:
|
| 625 |
+
"""Convert dataset features to policy features.
|
| 626 |
+
|
| 627 |
+
This function transforms the dataset's feature specification into a format
|
| 628 |
+
that a policy can use, classifying features by type (e.g., visual, state,
|
| 629 |
+
action) and ensuring correct shapes (e.g., channel-first for images).
|
| 630 |
+
|
| 631 |
+
Args:
|
| 632 |
+
features (dict): The LeRobot dataset features dictionary.
|
| 633 |
+
|
| 634 |
+
Returns:
|
| 635 |
+
dict: A dictionary mapping feature keys to `PolicyFeature` objects.
|
| 636 |
+
|
| 637 |
+
Raises:
|
| 638 |
+
ValueError: If an image feature does not have a 3D shape.
|
| 639 |
+
"""
|
| 640 |
+
# TODO(aliberts): Implement "type" in dataset features and simplify this
|
| 641 |
+
policy_features = {}
|
| 642 |
+
for key, ft in features.items():
|
| 643 |
+
shape = ft["shape"]
|
| 644 |
+
if ft["dtype"] in ["image", "video"]:
|
| 645 |
+
type = FeatureType.VISUAL
|
| 646 |
+
if len(shape) != 3:
|
| 647 |
+
raise ValueError(f"Number of dimensions of {key} != 3 (shape={shape})")
|
| 648 |
+
|
| 649 |
+
names = ft["names"]
|
| 650 |
+
# Backward compatibility for "channel" which is an error introduced in LeRobotDataset v2.0 for ported datasets.
|
| 651 |
+
if names[2] in ["channel", "channels"]: # (h, w, c) -> (c, h, w)
|
| 652 |
+
shape = (shape[2], shape[0], shape[1])
|
| 653 |
+
elif key == OBS_ENV_STATE:
|
| 654 |
+
type = FeatureType.ENV
|
| 655 |
+
elif key.startswith(OBS_STR):
|
| 656 |
+
type = FeatureType.STATE
|
| 657 |
+
elif key.startswith(ACTION):
|
| 658 |
+
type = FeatureType.ACTION
|
| 659 |
+
else:
|
| 660 |
+
continue
|
| 661 |
+
|
| 662 |
+
policy_features[key] = PolicyFeature(
|
| 663 |
+
type=type,
|
| 664 |
+
shape=shape,
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
return policy_features
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def combine_feature_dicts(*dicts: dict) -> dict:
|
| 671 |
+
"""Merge LeRobot grouped feature dicts.
|
| 672 |
+
|
| 673 |
+
- For 1D numeric specs (dtype not image/video/string) with "names": we merge the names and recompute the shape.
|
| 674 |
+
- For others (e.g. `observation.images.*`), the last one wins (if they are identical).
|
| 675 |
+
|
| 676 |
+
Args:
|
| 677 |
+
*dicts: A variable number of LeRobot feature dictionaries to merge.
|
| 678 |
+
|
| 679 |
+
Returns:
|
| 680 |
+
dict: A single merged feature dictionary.
|
| 681 |
+
|
| 682 |
+
Raises:
|
| 683 |
+
ValueError: If there's a dtype mismatch for a feature being merged.
|
| 684 |
+
"""
|
| 685 |
+
out: dict = {}
|
| 686 |
+
for d in dicts:
|
| 687 |
+
for key, value in d.items():
|
| 688 |
+
if not isinstance(value, dict):
|
| 689 |
+
out[key] = value
|
| 690 |
+
continue
|
| 691 |
+
|
| 692 |
+
dtype = value.get("dtype")
|
| 693 |
+
shape = value.get("shape")
|
| 694 |
+
is_vector = (
|
| 695 |
+
dtype not in ("image", "video", "string")
|
| 696 |
+
and isinstance(shape, tuple)
|
| 697 |
+
and len(shape) == 1
|
| 698 |
+
and "names" in value
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
if is_vector:
|
| 702 |
+
# Initialize or retrieve the accumulating dict for this feature key
|
| 703 |
+
target = out.setdefault(key, {"dtype": dtype, "names": [], "shape": (0,)})
|
| 704 |
+
# Ensure consistent data types across merged entries
|
| 705 |
+
if "dtype" in target and dtype != target["dtype"]:
|
| 706 |
+
raise ValueError(f"dtype mismatch for '{key}': {target['dtype']} vs {dtype}")
|
| 707 |
+
|
| 708 |
+
# Merge feature names: append only new ones to preserve order without duplicates
|
| 709 |
+
seen = set(target["names"])
|
| 710 |
+
for n in value["names"]:
|
| 711 |
+
if n not in seen:
|
| 712 |
+
target["names"].append(n)
|
| 713 |
+
seen.add(n)
|
| 714 |
+
# Recompute the shape to reflect the updated number of features
|
| 715 |
+
target["shape"] = (len(target["names"]),)
|
| 716 |
+
else:
|
| 717 |
+
# For images/videos and non-1D entries: last-writer-wins is only
|
| 718 |
+
# safe when the colliding definitions are actually identical.
|
| 719 |
+
# Silently overwriting a differing spec (shape/dtype/names) would
|
| 720 |
+
# drop the earlier feature's metadata, so reject the conflict.
|
| 721 |
+
prev = out.get(key)
|
| 722 |
+
if isinstance(prev, dict):
|
| 723 |
+
prev_sig = (prev.get("dtype"), prev.get("shape"), prev.get("names"))
|
| 724 |
+
cur_sig = (value.get("dtype"), value.get("shape"), value.get("names"))
|
| 725 |
+
if prev_sig != cur_sig:
|
| 726 |
+
raise ValueError(
|
| 727 |
+
f"Conflicting feature definitions for '{key}': "
|
| 728 |
+
f"dtype/shape/names {prev_sig} vs {cur_sig}. "
|
| 729 |
+
f"combine_feature_dicts() only allows last-writer-wins "
|
| 730 |
+
f"for identical specs."
|
| 731 |
+
)
|
| 732 |
+
out[key] = value
|
| 733 |
+
return out
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def create_empty_dataset_info(
|
| 737 |
+
codebase_version: str,
|
| 738 |
+
fps: int,
|
| 739 |
+
features: dict,
|
| 740 |
+
use_videos: bool,
|
| 741 |
+
robot_type: str | None = None,
|
| 742 |
+
chunks_size: int | None = None,
|
| 743 |
+
data_files_size_in_mb: int | None = None,
|
| 744 |
+
video_files_size_in_mb: int | None = None,
|
| 745 |
+
) -> dict:
|
| 746 |
+
"""Create a template dictionary for a new dataset's `info.json`.
|
| 747 |
+
|
| 748 |
+
Args:
|
| 749 |
+
codebase_version (str): The version of the LeRobot codebase.
|
| 750 |
+
fps (int): The frames per second of the data.
|
| 751 |
+
features (dict): The LeRobot features dictionary for the dataset.
|
| 752 |
+
use_videos (bool): Whether the dataset will store videos.
|
| 753 |
+
robot_type (str | None): The type of robot used, if any.
|
| 754 |
+
|
| 755 |
+
Returns:
|
| 756 |
+
dict: A dictionary with the initial dataset metadata.
|
| 757 |
+
"""
|
| 758 |
+
return {
|
| 759 |
+
"codebase_version": codebase_version,
|
| 760 |
+
"robot_type": robot_type,
|
| 761 |
+
"total_episodes": 0,
|
| 762 |
+
"total_frames": 0,
|
| 763 |
+
"total_tasks": 0,
|
| 764 |
+
"chunks_size": chunks_size or DEFAULT_CHUNK_SIZE,
|
| 765 |
+
"data_files_size_in_mb": data_files_size_in_mb or DEFAULT_DATA_FILE_SIZE_IN_MB,
|
| 766 |
+
"video_files_size_in_mb": video_files_size_in_mb or DEFAULT_VIDEO_FILE_SIZE_IN_MB,
|
| 767 |
+
"fps": fps,
|
| 768 |
+
"splits": {},
|
| 769 |
+
"data_path": DEFAULT_DATA_PATH,
|
| 770 |
+
"video_path": DEFAULT_VIDEO_PATH if use_videos else None,
|
| 771 |
+
"features": features,
|
| 772 |
+
}
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def check_delta_timestamps(
|
| 776 |
+
delta_timestamps: dict[str, list[float]], fps: int, tolerance_s: float, raise_value_error: bool = True
|
| 777 |
+
) -> bool:
|
| 778 |
+
"""Check if delta timestamps are multiples of 1/fps +/- tolerance.
|
| 779 |
+
|
| 780 |
+
This ensures that adding these delta timestamps to any existing timestamp in
|
| 781 |
+
the dataset will result in a value that aligns with the dataset's frame rate.
|
| 782 |
+
|
| 783 |
+
Args:
|
| 784 |
+
delta_timestamps (dict): A dictionary where values are lists of time
|
| 785 |
+
deltas in seconds.
|
| 786 |
+
fps (int): The frames per second of the dataset.
|
| 787 |
+
tolerance_s (float): The allowed tolerance in seconds.
|
| 788 |
+
raise_value_error (bool): If True, raises an error on failure.
|
| 789 |
+
|
| 790 |
+
Returns:
|
| 791 |
+
bool: True if all deltas are valid, False otherwise.
|
| 792 |
+
|
| 793 |
+
Raises:
|
| 794 |
+
ValueError: If any delta is outside the tolerance and `raise_value_error` is True.
|
| 795 |
+
"""
|
| 796 |
+
outside_tolerance = {}
|
| 797 |
+
for key, delta_ts in delta_timestamps.items():
|
| 798 |
+
within_tolerance = [abs(ts * fps - round(ts * fps)) / fps <= tolerance_s for ts in delta_ts]
|
| 799 |
+
if not all(within_tolerance):
|
| 800 |
+
outside_tolerance[key] = [
|
| 801 |
+
ts for ts, is_within in zip(delta_ts, within_tolerance, strict=True) if not is_within
|
| 802 |
+
]
|
| 803 |
+
|
| 804 |
+
if len(outside_tolerance) > 0:
|
| 805 |
+
if raise_value_error:
|
| 806 |
+
raise ValueError(
|
| 807 |
+
f"""
|
| 808 |
+
The following delta_timestamps are found outside of tolerance range.
|
| 809 |
+
Please make sure they are multiples of 1/{fps} +/- tolerance and adjust
|
| 810 |
+
their values accordingly.
|
| 811 |
+
\n{pformat(outside_tolerance)}
|
| 812 |
+
"""
|
| 813 |
+
)
|
| 814 |
+
return False
|
| 815 |
+
|
| 816 |
+
return True
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
def get_delta_indices(delta_timestamps: dict[str, list[float]], fps: int) -> dict[str, list[int]]:
|
| 820 |
+
"""Convert delta timestamps in seconds to delta indices in frames.
|
| 821 |
+
|
| 822 |
+
Args:
|
| 823 |
+
delta_timestamps (dict): A dictionary of time deltas in seconds.
|
| 824 |
+
fps (int): The frames per second of the dataset.
|
| 825 |
+
|
| 826 |
+
Returns:
|
| 827 |
+
dict: A dictionary of frame delta indices.
|
| 828 |
+
"""
|
| 829 |
+
delta_indices = {}
|
| 830 |
+
for key, delta_ts in delta_timestamps.items():
|
| 831 |
+
delta_indices[key] = [round(d * fps) for d in delta_ts]
|
| 832 |
+
|
| 833 |
+
return delta_indices
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def cycle(iterable: Any) -> Iterator[Any]:
|
| 837 |
+
"""Create a dataloader-safe cyclical iterator.
|
| 838 |
+
|
| 839 |
+
This is an equivalent of `itertools.cycle` but is safe for use with
|
| 840 |
+
PyTorch DataLoaders with multiple workers.
|
| 841 |
+
See https://github.com/pytorch/pytorch/issues/23900 for details.
|
| 842 |
+
|
| 843 |
+
Args:
|
| 844 |
+
iterable: The iterable to cycle over.
|
| 845 |
+
|
| 846 |
+
Yields:
|
| 847 |
+
Items from the iterable, restarting from the beginning when exhausted.
|
| 848 |
+
"""
|
| 849 |
+
iterator = iter(iterable)
|
| 850 |
+
while True:
|
| 851 |
+
try:
|
| 852 |
+
yield next(iterator)
|
| 853 |
+
except StopIteration:
|
| 854 |
+
iterator = iter(iterable)
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def create_branch(repo_id: str, *, branch: str, repo_type: str | None = None) -> None:
|
| 858 |
+
"""Create a branch on an existing Hugging Face repo.
|
| 859 |
+
|
| 860 |
+
Deletes the branch if it already exists before creating it.
|
| 861 |
+
|
| 862 |
+
Args:
|
| 863 |
+
repo_id (str): The ID of the repository.
|
| 864 |
+
branch (str): The name of the branch to create.
|
| 865 |
+
repo_type (str | None): The type of the repository (e.g., "dataset").
|
| 866 |
+
"""
|
| 867 |
+
api = HfApi()
|
| 868 |
+
|
| 869 |
+
branches = api.list_repo_refs(repo_id, repo_type=repo_type).branches
|
| 870 |
+
refs = [branch.ref for branch in branches]
|
| 871 |
+
ref = f"refs/heads/{branch}"
|
| 872 |
+
if ref in refs:
|
| 873 |
+
api.delete_branch(repo_id, repo_type=repo_type, branch=branch)
|
| 874 |
+
|
| 875 |
+
api.create_branch(repo_id, repo_type=repo_type, branch=branch)
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def validate_frame(frame: dict, features: dict) -> None:
|
| 879 |
+
expected_features = set(features) - set(DEFAULT_FEATURES)
|
| 880 |
+
actual_features = set(frame)
|
| 881 |
+
|
| 882 |
+
# task is a special required field that's not part of regular features
|
| 883 |
+
if "task" not in actual_features:
|
| 884 |
+
raise ValueError("Feature mismatch in `frame` dictionary:\nMissing features: {'task'}\n")
|
| 885 |
+
|
| 886 |
+
# Remove task from actual_features for regular feature validation
|
| 887 |
+
actual_features_for_validation = actual_features - {"task"}
|
| 888 |
+
|
| 889 |
+
error_message = validate_features_presence(actual_features_for_validation, expected_features)
|
| 890 |
+
|
| 891 |
+
common_features = actual_features_for_validation & expected_features
|
| 892 |
+
for name in common_features:
|
| 893 |
+
error_message += validate_feature_dtype_and_shape(name, features[name], frame[name])
|
| 894 |
+
|
| 895 |
+
if error_message:
|
| 896 |
+
raise ValueError(error_message)
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def validate_features_presence(actual_features: set[str], expected_features: set[str]) -> str:
|
| 900 |
+
"""Check for missing or extra features in a frame.
|
| 901 |
+
|
| 902 |
+
Args:
|
| 903 |
+
actual_features (set[str]): The set of feature names present in the frame.
|
| 904 |
+
expected_features (set[str]): The set of feature names expected in the frame.
|
| 905 |
+
|
| 906 |
+
Returns:
|
| 907 |
+
str: An error message string if there's a mismatch, otherwise an empty string.
|
| 908 |
+
"""
|
| 909 |
+
error_message = ""
|
| 910 |
+
missing_features = expected_features - actual_features
|
| 911 |
+
extra_features = actual_features - expected_features
|
| 912 |
+
|
| 913 |
+
if missing_features or extra_features:
|
| 914 |
+
error_message += "Feature mismatch in `frame` dictionary:\n"
|
| 915 |
+
if missing_features:
|
| 916 |
+
error_message += f"Missing features: {missing_features}\n"
|
| 917 |
+
if extra_features:
|
| 918 |
+
error_message += f"Extra features: {extra_features}\n"
|
| 919 |
+
|
| 920 |
+
return error_message
|
| 921 |
+
|
| 922 |
+
|
| 923 |
+
def validate_feature_dtype_and_shape(
|
| 924 |
+
name: str, feature: dict, value: np.ndarray | PILImage.Image | str
|
| 925 |
+
) -> str:
|
| 926 |
+
"""Validate the dtype and shape of a single feature's value.
|
| 927 |
+
|
| 928 |
+
Args:
|
| 929 |
+
name (str): The name of the feature.
|
| 930 |
+
feature (dict): The feature specification from the LeRobot features dictionary.
|
| 931 |
+
value: The value of the feature to validate.
|
| 932 |
+
|
| 933 |
+
Returns:
|
| 934 |
+
str: An error message if validation fails, otherwise an empty string.
|
| 935 |
+
|
| 936 |
+
Raises:
|
| 937 |
+
NotImplementedError: If the feature dtype is not supported for validation.
|
| 938 |
+
"""
|
| 939 |
+
expected_dtype = feature["dtype"]
|
| 940 |
+
expected_shape = feature["shape"]
|
| 941 |
+
if is_valid_numpy_dtype_string(expected_dtype):
|
| 942 |
+
return validate_feature_numpy_array(name, expected_dtype, expected_shape, value)
|
| 943 |
+
elif expected_dtype in ["image", "video"]:
|
| 944 |
+
return validate_feature_image_or_video(name, expected_shape, value)
|
| 945 |
+
elif expected_dtype == "string":
|
| 946 |
+
return validate_feature_string(name, value)
|
| 947 |
+
else:
|
| 948 |
+
raise NotImplementedError(f"The feature dtype '{expected_dtype}' is not implemented yet.")
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def validate_feature_numpy_array(
|
| 952 |
+
name: str, expected_dtype: str, expected_shape: list[int], value: np.ndarray
|
| 953 |
+
) -> str:
|
| 954 |
+
"""Validate a feature that is expected to be a numpy array.
|
| 955 |
+
|
| 956 |
+
Args:
|
| 957 |
+
name (str): The name of the feature.
|
| 958 |
+
expected_dtype (str): The expected numpy dtype as a string.
|
| 959 |
+
expected_shape (list[int]): The expected shape.
|
| 960 |
+
value (np.ndarray): The numpy array to validate.
|
| 961 |
+
|
| 962 |
+
Returns:
|
| 963 |
+
str: An error message if validation fails, otherwise an empty string.
|
| 964 |
+
"""
|
| 965 |
+
error_message = ""
|
| 966 |
+
if isinstance(value, np.ndarray):
|
| 967 |
+
actual_dtype = value.dtype
|
| 968 |
+
actual_shape = value.shape
|
| 969 |
+
|
| 970 |
+
if actual_dtype != np.dtype(expected_dtype):
|
| 971 |
+
error_message += f"The feature '{name}' of dtype '{actual_dtype}' is not of the expected dtype '{expected_dtype}'.\n"
|
| 972 |
+
|
| 973 |
+
if actual_shape != expected_shape:
|
| 974 |
+
error_message += f"The feature '{name}' of shape '{actual_shape}' does not have the expected shape '{expected_shape}'.\n"
|
| 975 |
+
else:
|
| 976 |
+
error_message += f"The feature '{name}' is not a 'np.ndarray'. Expected type is '{expected_dtype}', but type '{type(value)}' provided instead.\n"
|
| 977 |
+
|
| 978 |
+
return error_message
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def validate_feature_image_or_video(
|
| 982 |
+
name: str, expected_shape: list[str], value: np.ndarray | PILImage.Image
|
| 983 |
+
) -> str:
|
| 984 |
+
"""Validate a feature that is expected to be an image or video frame.
|
| 985 |
+
|
| 986 |
+
Accepts `np.ndarray` (channel-first or channel-last) or `PIL.Image.Image`.
|
| 987 |
+
|
| 988 |
+
Args:
|
| 989 |
+
name (str): The name of the feature.
|
| 990 |
+
expected_shape (list[str]): The expected shape (C, H, W).
|
| 991 |
+
value: The image data to validate.
|
| 992 |
+
|
| 993 |
+
Returns:
|
| 994 |
+
str: An error message if validation fails, otherwise an empty string.
|
| 995 |
+
"""
|
| 996 |
+
# Note: The check of pixels range ([0,1] for float and [0,255] for uint8) is done by the image writer threads.
|
| 997 |
+
error_message = ""
|
| 998 |
+
if isinstance(value, np.ndarray):
|
| 999 |
+
actual_shape = value.shape
|
| 1000 |
+
c, h, w = expected_shape
|
| 1001 |
+
if len(actual_shape) != 3 or (actual_shape != (c, h, w) and actual_shape != (h, w, c)):
|
| 1002 |
+
error_message += f"The feature '{name}' of shape '{actual_shape}' does not have the expected shape '{(c, h, w)}' or '{(h, w, c)}'.\n"
|
| 1003 |
+
elif isinstance(value, PILImage.Image):
|
| 1004 |
+
pass
|
| 1005 |
+
else:
|
| 1006 |
+
error_message += f"The feature '{name}' is expected to be of type 'PIL.Image' or 'np.ndarray' channel first or channel last, but type '{type(value)}' provided instead.\n"
|
| 1007 |
+
|
| 1008 |
+
return error_message
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
def validate_feature_string(name: str, value: str) -> str:
|
| 1012 |
+
"""Validate a feature that is expected to be a string.
|
| 1013 |
+
|
| 1014 |
+
Args:
|
| 1015 |
+
name (str): The name of the feature.
|
| 1016 |
+
value (str): The value to validate.
|
| 1017 |
+
|
| 1018 |
+
Returns:
|
| 1019 |
+
str: An error message if validation fails, otherwise an empty string.
|
| 1020 |
+
"""
|
| 1021 |
+
if not isinstance(value, str):
|
| 1022 |
+
return f"The feature '{name}' is expected to be of type 'str', but type '{type(value)}' provided instead.\n"
|
| 1023 |
+
return ""
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
def validate_episode_buffer(episode_buffer: dict, total_episodes: int, features: dict) -> None:
|
| 1027 |
+
"""Validate the episode buffer before it's written to disk.
|
| 1028 |
+
|
| 1029 |
+
Ensures the buffer has the required keys, contains at least one frame, and
|
| 1030 |
+
has features consistent with the dataset's specification.
|
| 1031 |
+
|
| 1032 |
+
Args:
|
| 1033 |
+
episode_buffer (dict): The buffer containing data for a single episode.
|
| 1034 |
+
total_episodes (int): The current total number of episodes in the dataset.
|
| 1035 |
+
features (dict): The LeRobot features dictionary for the dataset.
|
| 1036 |
+
|
| 1037 |
+
Raises:
|
| 1038 |
+
ValueError: If the buffer is invalid.
|
| 1039 |
+
NotImplementedError: If the episode index is manually set and doesn't match.
|
| 1040 |
+
"""
|
| 1041 |
+
if "size" not in episode_buffer:
|
| 1042 |
+
raise ValueError("size key not found in episode_buffer")
|
| 1043 |
+
|
| 1044 |
+
if "task" not in episode_buffer:
|
| 1045 |
+
raise ValueError("task key not found in episode_buffer")
|
| 1046 |
+
|
| 1047 |
+
if episode_buffer["episode_index"] != total_episodes:
|
| 1048 |
+
# TODO(aliberts): Add option to use existing episode_index
|
| 1049 |
+
raise NotImplementedError(
|
| 1050 |
+
"You might have manually provided the episode_buffer with an episode_index that doesn't "
|
| 1051 |
+
"match the total number of episodes already in the dataset. This is not supported for now."
|
| 1052 |
+
)
|
| 1053 |
+
|
| 1054 |
+
if episode_buffer["size"] == 0:
|
| 1055 |
+
raise ValueError("You must add one or several frames with `add_frame` before calling `add_episode`.")
|
| 1056 |
+
|
| 1057 |
+
buffer_keys = set(episode_buffer.keys()) - {"task", "size"}
|
| 1058 |
+
if not buffer_keys == set(features):
|
| 1059 |
+
raise ValueError(
|
| 1060 |
+
f"Features from `episode_buffer` don't match the ones in `features`."
|
| 1061 |
+
f"In episode_buffer not in features: {buffer_keys - set(features)}"
|
| 1062 |
+
f"In features not in episode_buffer: {set(features) - buffer_keys}"
|
| 1063 |
+
)
|
| 1064 |
+
|
| 1065 |
+
|
| 1066 |
+
def to_parquet_with_hf_images(df: pandas.DataFrame, path: Path) -> None:
|
| 1067 |
+
"""This function correctly writes to parquet a panda DataFrame that contains images encoded by HF dataset.
|
| 1068 |
+
This way, it can be loaded by HF dataset and correctly formatted images are returned.
|
| 1069 |
+
"""
|
| 1070 |
+
# TODO(qlhoest): replace this weird synthax by `df.to_parquet(path)` only
|
| 1071 |
+
datasets.Dataset.from_dict(df.to_dict(orient="list")).to_parquet(path)
|
| 1072 |
+
|
| 1073 |
+
|
| 1074 |
+
def item_to_torch(item: dict) -> dict:
|
| 1075 |
+
"""Convert all items in a dictionary to PyTorch tensors where appropriate.
|
| 1076 |
+
|
| 1077 |
+
This function is used to convert an item from a streaming dataset to PyTorch tensors.
|
| 1078 |
+
|
| 1079 |
+
Args:
|
| 1080 |
+
item (dict): Dictionary of items from a dataset.
|
| 1081 |
+
|
| 1082 |
+
Returns:
|
| 1083 |
+
dict: Dictionary with all tensor-like items converted to torch.Tensor.
|
| 1084 |
+
"""
|
| 1085 |
+
for key, val in item.items():
|
| 1086 |
+
if key not in ["task", "timestamp", "frame_index", "episode_index", "index", "task_index"]:
|
| 1087 |
+
item[key] = torch.as_tensor(val)
|
| 1088 |
+
return item
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
def is_float_in_list(target, float_list, threshold=1e-6):
|
| 1092 |
+
return any(abs(target - x) <= threshold for x in float_list)
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
def find_float_index(target, float_list, threshold=1e-6):
|
| 1096 |
+
for i, x in enumerate(float_list):
|
| 1097 |
+
if abs(target - x) <= threshold:
|
| 1098 |
+
return i
|
| 1099 |
+
return -1
|
| 1100 |
+
|
| 1101 |
+
|
| 1102 |
+
class LookBackError(Exception):
|
| 1103 |
+
"""
|
| 1104 |
+
Exception raised when trying to look back in the history of a Backtrackable object.
|
| 1105 |
+
"""
|
| 1106 |
+
|
| 1107 |
+
pass
|
| 1108 |
+
|
| 1109 |
+
|
| 1110 |
+
class LookAheadError(Exception):
|
| 1111 |
+
"""
|
| 1112 |
+
Exception raised when trying to look ahead in the future of a Backtrackable object.
|
| 1113 |
+
"""
|
| 1114 |
+
|
| 1115 |
+
pass
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
class Backtrackable(Generic[T]):
|
| 1119 |
+
"""
|
| 1120 |
+
Wrap any iterator/iterable so you can step back up to `history` items
|
| 1121 |
+
and look ahead up to `lookahead` items.
|
| 1122 |
+
|
| 1123 |
+
This is useful for streaming datasets where you need to access previous and future items
|
| 1124 |
+
but can't load the entire dataset into memory.
|
| 1125 |
+
|
| 1126 |
+
Example:
|
| 1127 |
+
-------
|
| 1128 |
+
```python
|
| 1129 |
+
ds = load_dataset("c4", "en", streaming=True, split="train")
|
| 1130 |
+
rev = Backtrackable(ds, history=3, lookahead=2)
|
| 1131 |
+
|
| 1132 |
+
x0 = next(rev) # forward
|
| 1133 |
+
x1 = next(rev)
|
| 1134 |
+
x2 = next(rev)
|
| 1135 |
+
|
| 1136 |
+
# Look ahead
|
| 1137 |
+
x3_peek = rev.peek_ahead(1) # next item without moving cursor
|
| 1138 |
+
x4_peek = rev.peek_ahead(2) # two items ahead
|
| 1139 |
+
|
| 1140 |
+
# Look back
|
| 1141 |
+
x1_again = rev.peek_back(1) # previous item without moving cursor
|
| 1142 |
+
x0_again = rev.peek_back(2) # two items back
|
| 1143 |
+
|
| 1144 |
+
# Move backward
|
| 1145 |
+
x1_back = rev.prev() # back one step
|
| 1146 |
+
next(rev) # returns x2, continues forward from where we were
|
| 1147 |
+
```
|
| 1148 |
+
"""
|
| 1149 |
+
|
| 1150 |
+
__slots__ = ("_source", "_back_buf", "_ahead_buf", "_cursor", "_history", "_lookahead")
|
| 1151 |
+
|
| 1152 |
+
def __init__(self, iterable: Iterable[T], *, history: int = 1, lookahead: int = 1):
|
| 1153 |
+
if history < 1:
|
| 1154 |
+
raise ValueError("history must be >= 1")
|
| 1155 |
+
if lookahead <= 0:
|
| 1156 |
+
raise ValueError("lookahead must be > 0")
|
| 1157 |
+
|
| 1158 |
+
self._source: Iterator[T] = iter(iterable)
|
| 1159 |
+
self._back_buf: deque[T] = deque(maxlen=history)
|
| 1160 |
+
self._ahead_buf: deque[T] = deque(maxlen=lookahead) if lookahead > 0 else deque()
|
| 1161 |
+
self._cursor: int = 0
|
| 1162 |
+
self._history = history
|
| 1163 |
+
self._lookahead = lookahead
|
| 1164 |
+
|
| 1165 |
+
def __iter__(self) -> "Backtrackable[T]":
|
| 1166 |
+
return self
|
| 1167 |
+
|
| 1168 |
+
def __next__(self) -> T:
|
| 1169 |
+
# Cursor convention: the *current* item always lives at
|
| 1170 |
+
# `self._back_buf[self._cursor - 1]`. `_cursor == 0` => current is the
|
| 1171 |
+
# most-recent appended item (`_back_buf[-1]`); each prev() decrements
|
| 1172 |
+
# `_cursor`, walking one step older. peek_back()/history()/
|
| 1173 |
+
# can_peek_back() all share this `cursor - 1` base.
|
| 1174 |
+
#
|
| 1175 |
+
# If we've stepped back, replay forward from the back buffer first.
|
| 1176 |
+
if self._cursor < 0:
|
| 1177 |
+
self._cursor += 1
|
| 1178 |
+
return self._back_buf[self._cursor - 1]
|
| 1179 |
+
|
| 1180 |
+
# If we have items in the ahead buffer, use them first
|
| 1181 |
+
item = self._ahead_buf.popleft() if self._ahead_buf else next(self._source)
|
| 1182 |
+
|
| 1183 |
+
# Add current item to back buffer and reset cursor
|
| 1184 |
+
self._back_buf.append(item)
|
| 1185 |
+
self._cursor = 0
|
| 1186 |
+
return item
|
| 1187 |
+
|
| 1188 |
+
def prev(self) -> T:
|
| 1189 |
+
"""
|
| 1190 |
+
Step one item back in history and return the PREVIOUS item.
|
| 1191 |
+
|
| 1192 |
+
The current item is `_back_buf[self._cursor - 1]`; prev() walks one
|
| 1193 |
+
step older and returns that older item (not the current one), and the
|
| 1194 |
+
following next() returns the item we stepped back from.
|
| 1195 |
+
|
| 1196 |
+
Example (source = [0, 1, 2, 3, ...], history >= 3):
|
| 1197 |
+
next() -> 0; next() -> 1; next() -> 2 # current is 2
|
| 1198 |
+
prev() -> 1 # previous item
|
| 1199 |
+
next() -> 2 # resume forward
|
| 1200 |
+
next() -> 3
|
| 1201 |
+
|
| 1202 |
+
Raises LookBackError if already at the oldest buffered item.
|
| 1203 |
+
"""
|
| 1204 |
+
if len(self._back_buf) + self._cursor <= 1:
|
| 1205 |
+
raise LookBackError("At start of history")
|
| 1206 |
+
|
| 1207 |
+
self._cursor -= 1
|
| 1208 |
+
return self._back_buf[self._cursor - 1]
|
| 1209 |
+
|
| 1210 |
+
def peek_back(self, n: int = 1) -> T:
|
| 1211 |
+
"""
|
| 1212 |
+
Look `n` items back (n=1 == previous item) without moving the cursor.
|
| 1213 |
+
"""
|
| 1214 |
+
if n < 0 or n + 1 > len(self._back_buf) + self._cursor:
|
| 1215 |
+
raise LookBackError("peek_back distance out of range")
|
| 1216 |
+
|
| 1217 |
+
return self._back_buf[self._cursor - (n + 1)]
|
| 1218 |
+
|
| 1219 |
+
def peek_ahead(self, n: int = 1) -> T:
|
| 1220 |
+
"""
|
| 1221 |
+
Look `n` items ahead (n=1 == next item) without moving the cursor.
|
| 1222 |
+
Fills the ahead buffer if necessary.
|
| 1223 |
+
"""
|
| 1224 |
+
if n < 1:
|
| 1225 |
+
raise LookAheadError("peek_ahead distance must be 1 or more")
|
| 1226 |
+
elif n > self._lookahead:
|
| 1227 |
+
raise LookAheadError("peek_ahead distance exceeds lookahead limit")
|
| 1228 |
+
|
| 1229 |
+
# Fill ahead buffer if we don't have enough items
|
| 1230 |
+
while len(self._ahead_buf) < n:
|
| 1231 |
+
try:
|
| 1232 |
+
item = next(self._source)
|
| 1233 |
+
self._ahead_buf.append(item)
|
| 1234 |
+
|
| 1235 |
+
except StopIteration as err:
|
| 1236 |
+
raise LookAheadError("peek_ahead: not enough items in source") from err
|
| 1237 |
+
|
| 1238 |
+
return self._ahead_buf[n - 1]
|
| 1239 |
+
|
| 1240 |
+
def history(self) -> list[T]:
|
| 1241 |
+
"""
|
| 1242 |
+
Return a copy of the buffered history (most recent last).
|
| 1243 |
+
The list length β€ `history` argument passed at construction.
|
| 1244 |
+
"""
|
| 1245 |
+
if self._cursor == 0:
|
| 1246 |
+
return list(self._back_buf)
|
| 1247 |
+
|
| 1248 |
+
# When cursor<0, slice so the order remains chronological
|
| 1249 |
+
return list(self._back_buf)[: self._cursor or None]
|
| 1250 |
+
|
| 1251 |
+
def can_peek_back(self, steps: int = 1) -> bool:
|
| 1252 |
+
"""
|
| 1253 |
+
Check if we can go back `steps` items without raising an IndexError.
|
| 1254 |
+
"""
|
| 1255 |
+
return steps <= len(self._back_buf) + self._cursor
|
| 1256 |
+
|
| 1257 |
+
def can_peek_ahead(self, steps: int = 1) -> bool:
|
| 1258 |
+
"""
|
| 1259 |
+
Check if we can peek ahead `steps` items.
|
| 1260 |
+
This may involve trying to fill the ahead buffer.
|
| 1261 |
+
"""
|
| 1262 |
+
if self._lookahead > 0 and steps > self._lookahead:
|
| 1263 |
+
return False
|
| 1264 |
+
|
| 1265 |
+
# Try to fill ahead buffer to check if we can peek that far
|
| 1266 |
+
try:
|
| 1267 |
+
while len(self._ahead_buf) < steps:
|
| 1268 |
+
if self._lookahead > 0 and len(self._ahead_buf) >= self._lookahead:
|
| 1269 |
+
return False
|
| 1270 |
+
item = next(self._source)
|
| 1271 |
+
self._ahead_buf.append(item)
|
| 1272 |
+
return True
|
| 1273 |
+
except StopIteration:
|
| 1274 |
+
return False
|
| 1275 |
+
|
| 1276 |
+
|
| 1277 |
+
def safe_shard(dataset: datasets.IterableDataset, index: int, num_shards: int) -> datasets.Dataset:
|
| 1278 |
+
"""
|
| 1279 |
+
Safe shards the dataset.
|
| 1280 |
+
"""
|
| 1281 |
+
shard_idx = min(dataset.num_shards, index + 1) - 1
|
| 1282 |
+
|
| 1283 |
+
return dataset.shard(num_shards, index=shard_idx)
|
src/dataset/video_utils.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""Video codec helper β live remainder after the 2026-06-11 dead-code sweep.
|
| 17 |
+
|
| 18 |
+
The torchcodec/torchvision decode stack that lived here served the deleted
|
| 19 |
+
lerobot dataset modules; training decodes video through
|
| 20 |
+
``src/adapters/lerobot_base._read_video_frame`` (shared PyAV container cache).
|
| 21 |
+
"""
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import importlib
|
| 25 |
+
import logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def get_safe_default_codec():
|
| 29 |
+
if importlib.util.find_spec("torchcodec"):
|
| 30 |
+
return "torchcodec"
|
| 31 |
+
logging.warning(
|
| 32 |
+
"'torchcodec' is not available in your platform, falling back to 'pyav' as a default decoder"
|
| 33 |
+
)
|
| 34 |
+
return "pyav"
|
src/optim/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .optimizers import OptimizerConfig as OptimizerConfig
|
src/optim/ema.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
"""Exponential Moving Average (EMA) of model parameters.
|
| 2 |
+
|
| 3 |
+
Aligned with openpi:
|
| 4 |
+
|
| 5 |
+
ema_params = ema_decay * ema_params + (1 - ema_decay) * params
|
| 6 |
+
|
| 7 |
+
Update is unconditional every step, no warmup. EMA is initialized from the
|
| 8 |
+
current params on first call (mirrors openpi `ema_params=params` at init).
|
| 9 |
+
|
| 10 |
+
Parameter alignment with openpi:
|
| 11 |
+
- pretrain configs (pi0_base / pi05 / pi0_fast): ema_decay = 0.999
|
| 12 |
+
- finetune default : ema_decay = 0.99
|
| 13 |
+
- LoRA finetune : ema_decay = None (disabled)
|
| 14 |
+
|
| 15 |
+
The implementation tracks ONLY trainable parameters (matches openpi's
|
| 16 |
+
`config.trainable_filter`). Buffer dtype is fp32 to avoid bf16/fp16
|
| 17 |
+
accumulation drift. Each DDP / ZeRO-2 rank keeps its own EMA copy; since
|
| 18 |
+
ZeRO-2 does not shard parameters and Accelerate keeps weights in sync, all
|
| 19 |
+
ranks see the same param values and produce identical EMA buffers without
|
| 20 |
+
explicit synchronization.
|
| 21 |
+
|
| 22 |
+
Usage:
|
| 23 |
+
|
| 24 |
+
ema = ModelEMA(model, decay=0.99)
|
| 25 |
+
for step in range(num_steps):
|
| 26 |
+
loss.backward()
|
| 27 |
+
optimizer.step()
|
| 28 |
+
ema.update(model) # call AFTER optimizer.step
|
| 29 |
+
|
| 30 |
+
# Evaluate using EMA weights (in-place swap, then restore)
|
| 31 |
+
backup = ema.apply_to(model)
|
| 32 |
+
eval(model)
|
| 33 |
+
ema.restore(model, backup)
|
| 34 |
+
|
| 35 |
+
# Checkpointing
|
| 36 |
+
torch.save(ema.state_dict(), ckpt_dir / "ema.pt")
|
| 37 |
+
ema.load_state_dict(torch.load(ckpt_dir / "ema.pt"))
|
| 38 |
+
"""
|
| 39 |
+
from __future__ import annotations
|
| 40 |
+
|
| 41 |
+
import logging
|
| 42 |
+
from typing import Dict
|
| 43 |
+
|
| 44 |
+
import torch
|
| 45 |
+
import torch.nn as nn
|
| 46 |
+
|
| 47 |
+
logger = logging.getLogger(__name__)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class ModelEMA:
|
| 51 |
+
"""Exponential Moving Average over trainable parameters of a nn.Module.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
model: The model to track. Only parameters with `requires_grad=True`
|
| 55 |
+
are tracked. EMA buffer is initialized to a fp32 copy of the
|
| 56 |
+
current parameter values (matches openpi init).
|
| 57 |
+
decay: EMA decay factor in (0, 1). openpi default is 0.99 for
|
| 58 |
+
finetune, 0.999 for pretrain. Higher decay β smoother trajectory
|
| 59 |
+
but slower adaptation (effective averaging window β 1 / (1 - decay)
|
| 60 |
+
steps; 0.99 β ~100 steps, 0.999 β ~1000 steps).
|
| 61 |
+
device: Device for the EMA buffer. Defaults to the parameter device.
|
| 62 |
+
Set to "cpu" to save GPU memory at the cost of slower update.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
model: nn.Module,
|
| 68 |
+
decay: float = 0.99,
|
| 69 |
+
device: torch.device | str | None = None,
|
| 70 |
+
):
|
| 71 |
+
if not 0.0 < decay < 1.0:
|
| 72 |
+
raise ValueError(f"EMA decay must be in (0, 1), got {decay}")
|
| 73 |
+
self.decay = float(decay)
|
| 74 |
+
self._device_override = device
|
| 75 |
+
# name -> fp32 buffer on the chosen device
|
| 76 |
+
self.shadow: Dict[str, torch.Tensor] = {}
|
| 77 |
+
for name, param in model.named_parameters():
|
| 78 |
+
if param.requires_grad:
|
| 79 |
+
buf = param.detach().to(torch.float32)
|
| 80 |
+
if device is not None:
|
| 81 |
+
buf = buf.to(device)
|
| 82 |
+
self.shadow[name] = buf.clone()
|
| 83 |
+
|
| 84 |
+
@torch.no_grad()
|
| 85 |
+
def update(self, model: nn.Module) -> None:
|
| 86 |
+
"""In-place EMA update: shadow = decay * shadow + (1 - decay) * param.
|
| 87 |
+
|
| 88 |
+
Skips parameters that are not in the shadow (e.g. dynamically added
|
| 89 |
+
modules or parameters whose `requires_grad` flipped after init).
|
| 90 |
+
"""
|
| 91 |
+
one_minus_decay = 1.0 - self.decay
|
| 92 |
+
for name, param in model.named_parameters():
|
| 93 |
+
buf = self.shadow.get(name)
|
| 94 |
+
if buf is None:
|
| 95 |
+
continue
|
| 96 |
+
# Cast param to fp32 on the buffer's device for the linear combination.
|
| 97 |
+
new_value = param.detach().to(buf.device, dtype=torch.float32)
|
| 98 |
+
buf.mul_(self.decay).add_(new_value, alpha=one_minus_decay)
|
| 99 |
+
|
| 100 |
+
@torch.no_grad()
|
| 101 |
+
def apply_to(self, model: nn.Module) -> Dict[str, torch.Tensor]:
|
| 102 |
+
"""Copy EMA buffers into the model in-place. Returns a backup of the
|
| 103 |
+
original parameter tensors so callers can ``restore()`` afterward.
|
| 104 |
+
|
| 105 |
+
The model's original dtype is preserved (EMA buffer is cast back from
|
| 106 |
+
fp32 to each parameter's native dtype on copy).
|
| 107 |
+
"""
|
| 108 |
+
backup: Dict[str, torch.Tensor] = {}
|
| 109 |
+
for name, param in model.named_parameters():
|
| 110 |
+
buf = self.shadow.get(name)
|
| 111 |
+
if buf is None:
|
| 112 |
+
continue
|
| 113 |
+
backup[name] = param.detach().clone()
|
| 114 |
+
param.data.copy_(buf.to(device=param.device, dtype=param.dtype))
|
| 115 |
+
return backup
|
| 116 |
+
|
| 117 |
+
@torch.no_grad()
|
| 118 |
+
def restore(self, model: nn.Module, backup: Dict[str, torch.Tensor]) -> None:
|
| 119 |
+
"""Restore parameters from a backup produced by ``apply_to``."""
|
| 120 |
+
for name, param in model.named_parameters():
|
| 121 |
+
if name in backup:
|
| 122 |
+
param.data.copy_(backup[name])
|
| 123 |
+
|
| 124 |
+
def state_dict(self) -> Dict[str, torch.Tensor]:
|
| 125 |
+
"""Return the EMA buffer as a plain ``{name: fp32 tensor}`` dict.
|
| 126 |
+
|
| 127 |
+
Suitable for ``torch.save``. The tensors share storage with the live
|
| 128 |
+
EMA buffer β callers should not mutate them.
|
| 129 |
+
"""
|
| 130 |
+
return {"decay": torch.tensor(self.decay), **self.shadow}
|
| 131 |
+
|
| 132 |
+
def load_state_dict(self, state_dict: Dict[str, torch.Tensor], strict: bool = True) -> None:
|
| 133 |
+
"""Load EMA buffer from a state dict produced by ``state_dict``.
|
| 134 |
+
|
| 135 |
+
The ``decay`` entry is honored if present (overrides the constructor
|
| 136 |
+
argument), so a resumed run uses the same decay it was created with.
|
| 137 |
+
|
| 138 |
+
Validates the key sets to avoid silently resuming a "part historical
|
| 139 |
+
EMA + part current params" mix (e.g. after a param rename or LoRA
|
| 140 |
+
toggle):
|
| 141 |
+
|
| 142 |
+
- ``strict=True`` (default): raise ``RuntimeError`` if the sets differ.
|
| 143 |
+
- ``strict=False``: WARN but load the intersecting keys.
|
| 144 |
+
|
| 145 |
+
The saved ``decay`` scalar is metadata and excluded from the comparison.
|
| 146 |
+
"""
|
| 147 |
+
decay = state_dict.get("decay")
|
| 148 |
+
if isinstance(decay, torch.Tensor):
|
| 149 |
+
self.decay = float(decay.item())
|
| 150 |
+
|
| 151 |
+
saved_keys = {k for k in state_dict.keys() if k != "decay"}
|
| 152 |
+
shadow_keys = set(self.shadow.keys())
|
| 153 |
+
missing = shadow_keys - saved_keys # tracked but not in checkpoint
|
| 154 |
+
unexpected = saved_keys - shadow_keys # in checkpoint but not tracked
|
| 155 |
+
|
| 156 |
+
if missing or unexpected:
|
| 157 |
+
def _sample(s: set[str], n: int = 5) -> list[str]:
|
| 158 |
+
return sorted(s)[:n]
|
| 159 |
+
|
| 160 |
+
detail = (
|
| 161 |
+
f"EMA state_dict key mismatch: "
|
| 162 |
+
f"{len(missing)} missing (tracked param absent from checkpoint, "
|
| 163 |
+
f"would stay at current params), "
|
| 164 |
+
f"{len(unexpected)} unexpected (checkpoint key not tracked). "
|
| 165 |
+
f"missing_sample={_sample(missing)} "
|
| 166 |
+
f"unexpected_sample={_sample(unexpected)}"
|
| 167 |
+
)
|
| 168 |
+
if strict:
|
| 169 |
+
raise RuntimeError(
|
| 170 |
+
detail
|
| 171 |
+
+ " β refusing to silently resume a part-historical-EMA / "
|
| 172 |
+
"part-current-params mix. Pass strict=False to load the "
|
| 173 |
+
"intersection anyway."
|
| 174 |
+
)
|
| 175 |
+
logger.warning("%s β loading intersection only (strict=False).", detail)
|
| 176 |
+
|
| 177 |
+
for name, buf in self.shadow.items():
|
| 178 |
+
saved = state_dict.get(name)
|
| 179 |
+
if saved is None:
|
| 180 |
+
continue
|
| 181 |
+
buf.copy_(saved.to(device=buf.device, dtype=buf.dtype))
|
| 182 |
+
|
| 183 |
+
def __len__(self) -> int:
|
| 184 |
+
return len(self.shadow)
|
| 185 |
+
|
| 186 |
+
def __repr__(self) -> str:
|
| 187 |
+
n_params = sum(b.numel() for b in self.shadow.values())
|
| 188 |
+
return (
|
| 189 |
+
f"ModelEMA(decay={self.decay}, tracked_params={len(self.shadow)}, "
|
| 190 |
+
f"total_elements={n_params:,})"
|
| 191 |
+
)
|
src/optim/optimizers.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
import abc
|
| 17 |
+
import logging
|
| 18 |
+
from dataclasses import asdict, dataclass, field
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
import draccus
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class OptimizerConfig(draccus.ChoiceRegistry, abc.ABC):
|
| 31 |
+
lr: float
|
| 32 |
+
weight_decay: float
|
| 33 |
+
grad_clip_norm: float
|
| 34 |
+
|
| 35 |
+
@property
|
| 36 |
+
def type(self) -> str:
|
| 37 |
+
return self.get_choice_name(self.__class__)
|
| 38 |
+
|
| 39 |
+
@classmethod
|
| 40 |
+
def default_choice_name(cls) -> str | None:
|
| 41 |
+
return "adam"
|
| 42 |
+
|
| 43 |
+
@abc.abstractmethod
|
| 44 |
+
def build(self) -> torch.optim.Optimizer | dict[str, torch.optim.Optimizer]:
|
| 45 |
+
"""Build the optimizer for this config.
|
| 46 |
+
|
| 47 |
+
Most subclasses return a single ``torch.optim.Optimizer``; only
|
| 48 |
+
``MultiAdamConfig`` returns a ``dict[str, torch.optim.Optimizer]``. The
|
| 49 |
+
union return type keeps interface compatibility with multi-optimizer
|
| 50 |
+
setups (e.g. policy + value in RL).
|
| 51 |
+
"""
|
| 52 |
+
raise NotImplementedError
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@OptimizerConfig.register_subclass("adam")
|
| 56 |
+
@dataclass
|
| 57 |
+
class AdamConfig(OptimizerConfig):
|
| 58 |
+
lr: float = 1e-3
|
| 59 |
+
betas: tuple[float, float] = (0.9, 0.999)
|
| 60 |
+
eps: float = 1e-8
|
| 61 |
+
weight_decay: float = 0.0
|
| 62 |
+
grad_clip_norm: float = 10.0
|
| 63 |
+
|
| 64 |
+
def build(self, params: dict) -> torch.optim.Optimizer:
|
| 65 |
+
kwargs = asdict(self)
|
| 66 |
+
kwargs.pop("grad_clip_norm")
|
| 67 |
+
return torch.optim.Adam(params, **kwargs)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@OptimizerConfig.register_subclass("adamw")
|
| 71 |
+
@dataclass
|
| 72 |
+
class AdamWConfig(OptimizerConfig):
|
| 73 |
+
lr: float = 1e-3
|
| 74 |
+
betas: tuple[float, float] = (0.9, 0.999)
|
| 75 |
+
eps: float = 1e-8
|
| 76 |
+
weight_decay: float = 1e-2
|
| 77 |
+
grad_clip_norm: float = 10.0
|
| 78 |
+
|
| 79 |
+
def build(self, params: dict) -> torch.optim.Optimizer:
|
| 80 |
+
kwargs = asdict(self)
|
| 81 |
+
kwargs.pop("grad_clip_norm")
|
| 82 |
+
return torch.optim.AdamW(params, **kwargs)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@OptimizerConfig.register_subclass("sgd")
|
| 86 |
+
@dataclass
|
| 87 |
+
class SGDConfig(OptimizerConfig):
|
| 88 |
+
lr: float = 1e-3
|
| 89 |
+
momentum: float = 0.0
|
| 90 |
+
dampening: float = 0.0
|
| 91 |
+
nesterov: bool = False
|
| 92 |
+
weight_decay: float = 0.0
|
| 93 |
+
grad_clip_norm: float = 10.0
|
| 94 |
+
|
| 95 |
+
def build(self, params: dict) -> torch.optim.Optimizer:
|
| 96 |
+
kwargs = asdict(self)
|
| 97 |
+
kwargs.pop("grad_clip_norm")
|
| 98 |
+
return torch.optim.SGD(params, **kwargs)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@OptimizerConfig.register_subclass("labvla-adamw")
|
| 102 |
+
@dataclass
|
| 103 |
+
class LabVLAAdamWConfig(OptimizerConfig):
|
| 104 |
+
"""AdamW optimizer with grouped learning rates for LabVLA DiT architecture.
|
| 105 |
+
|
| 106 |
+
Parameter Groups:
|
| 107 |
+
- Group 0 (vlm): VLM backbone parameters at vlm_lr
|
| 108 |
+
- Group 1 (dit_action_head): DiT action head at dit_lr
|
| 109 |
+
- Group 2 (other): Projections, compressor, etc. at full lr
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
lr: float = 5e-5
|
| 113 |
+
betas: tuple[float, float] = (0.9, 0.95)
|
| 114 |
+
eps: float = 1e-8
|
| 115 |
+
weight_decay: float = 0.01
|
| 116 |
+
grad_clip_norm: float = 1.0
|
| 117 |
+
vlm_lr: float = 5e-5
|
| 118 |
+
dit_lr: float = 1e-4
|
| 119 |
+
|
| 120 |
+
def build(self, params: dict) -> torch.optim.Optimizer:
|
| 121 |
+
assert isinstance(params, dict), "LabVLAAdamW requires named_parameters() dict as input."
|
| 122 |
+
|
| 123 |
+
# Within each of the 4 semantic groups (vlm/dit/ki/other), split into
|
| 124 |
+
# decay/no_decay. ndim<=1 params (biases, norm weights, scalar
|
| 125 |
+
# embeddings) get NO weight decay (GPT/pi0/Qwen convention) β decaying
|
| 126 |
+
# norm/bias measurably hurts long-run stability.
|
| 127 |
+
def _no_decay(name: str, p: torch.nn.Parameter) -> bool:
|
| 128 |
+
if p.ndim <= 1:
|
| 129 |
+
return True
|
| 130 |
+
nl = name.lower()
|
| 131 |
+
return nl.endswith(".bias") or "norm" in nl
|
| 132 |
+
|
| 133 |
+
buckets: dict[str, dict[str, list[torch.nn.Parameter]]] = {
|
| 134 |
+
"vlm": {"decay": [], "no_decay": []},
|
| 135 |
+
"dit_action_head": {"decay": [], "no_decay": []},
|
| 136 |
+
"ki": {"decay": [], "no_decay": []},
|
| 137 |
+
"other": {"decay": [], "no_decay": []},
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
dit_side_modules = {
|
| 141 |
+
"dit_action_head",
|
| 142 |
+
"proj_vlm_to_dit",
|
| 143 |
+
"state_proj",
|
| 144 |
+
"action_in_proj",
|
| 145 |
+
"action_out_proj",
|
| 146 |
+
}
|
| 147 |
+
ki_modules = {"ki_head", "state_vlm_proj"}
|
| 148 |
+
|
| 149 |
+
for name, p in params.items():
|
| 150 |
+
if not p.requires_grad:
|
| 151 |
+
continue
|
| 152 |
+
root = name.split(".", 1)[0]
|
| 153 |
+
if root == "model" and "." in name:
|
| 154 |
+
root = name.split(".", 2)[1]
|
| 155 |
+
if root in dit_side_modules:
|
| 156 |
+
bucket = "dit_action_head"
|
| 157 |
+
elif root in ki_modules:
|
| 158 |
+
# Ο0.5 / KI randomly-initialized modules: use dit_lr for fast convergence.
|
| 159 |
+
bucket = "ki"
|
| 160 |
+
elif root == "vlm":
|
| 161 |
+
bucket = "vlm"
|
| 162 |
+
else:
|
| 163 |
+
bucket = "other"
|
| 164 |
+
subkey = "no_decay" if _no_decay(name, p) else "decay"
|
| 165 |
+
buckets[bucket][subkey].append(p)
|
| 166 |
+
|
| 167 |
+
group_lrs = {
|
| 168 |
+
"vlm": self.vlm_lr,
|
| 169 |
+
"dit_action_head": self.dit_lr,
|
| 170 |
+
"ki": self.dit_lr,
|
| 171 |
+
"other": self.lr,
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
param_groups = []
|
| 175 |
+
for gname, sub in buckets.items():
|
| 176 |
+
lr = group_lrs[gname]
|
| 177 |
+
if sub["decay"]:
|
| 178 |
+
param_groups.append({
|
| 179 |
+
"params": sub["decay"],
|
| 180 |
+
"lr": lr,
|
| 181 |
+
"weight_decay": self.weight_decay,
|
| 182 |
+
"name": gname,
|
| 183 |
+
})
|
| 184 |
+
if sub["no_decay"]:
|
| 185 |
+
param_groups.append({
|
| 186 |
+
"params": sub["no_decay"],
|
| 187 |
+
"lr": lr,
|
| 188 |
+
"weight_decay": 0.0,
|
| 189 |
+
"name": f"{gname}_no_decay",
|
| 190 |
+
})
|
| 191 |
+
|
| 192 |
+
return torch.optim.AdamW(
|
| 193 |
+
param_groups,
|
| 194 |
+
betas=self.betas,
|
| 195 |
+
eps=self.eps,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@OptimizerConfig.register_subclass("xvla-adamw")
|
| 200 |
+
@dataclass
|
| 201 |
+
class XVLAAdamWConfig(OptimizerConfig):
|
| 202 |
+
"""Custom AdamW optimizer for XVLA with differential learning rates.
|
| 203 |
+
|
| 204 |
+
The Vision-Language Model (VLM) is trained with 1/10 of the base learning rate
|
| 205 |
+
for stable optimization, while all other components use the full LR.
|
| 206 |
+
|
| 207 |
+
This LR ratio is crucial for achieving strong and stable finetuning performance.
|
| 208 |
+
|
| 209 |
+
Soft-prompts can optionally use a separate learning rate with warm-up support.
|
| 210 |
+
Set `soft_prompt_lr_scale` to a value < 1.0 (e.g., 0.1) to start soft-prompts
|
| 211 |
+
at a lower LR. Combine with a warmup scheduler for optimal results.
|
| 212 |
+
|
| 213 |
+
Note:
|
| 214 |
+
Completely matching official reported performance may require an additional
|
| 215 |
+
warm-up LR schedule for soft-prompts, which can bring minor improvements.
|
| 216 |
+
When `soft_prompt_warmup_lr_scale` is set, soft-prompts start at
|
| 217 |
+
`lr * soft_prompt_warmup_lr_scale` and should be warmed up via the scheduler.
|
| 218 |
+
|
| 219 |
+
Parameter Groups:
|
| 220 |
+
- Group 0 (vlm): VLM parameters at lr * 0.1, weight_decay * 0.1
|
| 221 |
+
- Group 1 (soft_prompts): Soft-prompt parameters at lr * soft_prompt_lr_scale
|
| 222 |
+
- Group 2 (other): All other parameters at full lr
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
lr: float = 1e-4
|
| 226 |
+
betas: tuple[float, float] = (0.9, 0.99)
|
| 227 |
+
eps: float = 1e-8
|
| 228 |
+
weight_decay: float = 0.0
|
| 229 |
+
grad_clip_norm: float = 10.0
|
| 230 |
+
# Soft-prompt specific settings
|
| 231 |
+
soft_prompt_lr_scale: float = 1.0 # Scale factor for soft-prompt LR (1.0 = same as base LR)
|
| 232 |
+
soft_prompt_warmup_lr_scale: float | None = None # If set, start soft-prompts at this scale (e.g., 0.01)
|
| 233 |
+
|
| 234 |
+
def build(self, params: dict) -> torch.optim.Optimizer:
|
| 235 |
+
"""
|
| 236 |
+
Build AdamW optimizer with differential learning rates.
|
| 237 |
+
|
| 238 |
+
Expects `named_parameters()` as input (dict of name -> param).
|
| 239 |
+
Applies:
|
| 240 |
+
- lr * 0.1 for all VLM-related parameters
|
| 241 |
+
- lr * soft_prompt_lr_scale for soft-prompt parameters (with optional warmup)
|
| 242 |
+
- full lr for all other parameters
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
params: Dictionary of parameter names to parameters (from named_parameters())
|
| 246 |
+
|
| 247 |
+
Returns:
|
| 248 |
+
AdamW optimizer with parameter groups for VLM, soft-prompts, and other components
|
| 249 |
+
"""
|
| 250 |
+
assert isinstance(params, dict), "Custom LR optimizer requires `named_parameters()` as inputs."
|
| 251 |
+
|
| 252 |
+
vlm_group, soft_prompt_group, other_group = [], [], []
|
| 253 |
+
for name, p in params.items():
|
| 254 |
+
if not p.requires_grad:
|
| 255 |
+
continue
|
| 256 |
+
if "vlm" in name.lower():
|
| 257 |
+
vlm_group.append(p)
|
| 258 |
+
elif "soft_prompt" in name.lower():
|
| 259 |
+
soft_prompt_group.append(p)
|
| 260 |
+
else:
|
| 261 |
+
other_group.append(p)
|
| 262 |
+
|
| 263 |
+
# Determine soft-prompt LR
|
| 264 |
+
soft_prompt_lr = self.lr * self.soft_prompt_lr_scale
|
| 265 |
+
if self.soft_prompt_warmup_lr_scale is not None:
|
| 266 |
+
# Start at warmup scale, scheduler will warm up to soft_prompt_lr
|
| 267 |
+
soft_prompt_lr = self.lr * self.soft_prompt_warmup_lr_scale
|
| 268 |
+
|
| 269 |
+
param_groups = [
|
| 270 |
+
{
|
| 271 |
+
"params": vlm_group,
|
| 272 |
+
"lr": self.lr * 0.1,
|
| 273 |
+
"weight_decay": self.weight_decay * 0.1,
|
| 274 |
+
"name": "vlm",
|
| 275 |
+
},
|
| 276 |
+
{
|
| 277 |
+
"params": soft_prompt_group,
|
| 278 |
+
"lr": soft_prompt_lr,
|
| 279 |
+
"weight_decay": self.weight_decay,
|
| 280 |
+
"name": "soft_prompts",
|
| 281 |
+
},
|
| 282 |
+
{
|
| 283 |
+
"params": other_group,
|
| 284 |
+
"lr": self.lr,
|
| 285 |
+
"weight_decay": self.weight_decay,
|
| 286 |
+
"name": "other",
|
| 287 |
+
},
|
| 288 |
+
]
|
| 289 |
+
|
| 290 |
+
# Filter out empty groups
|
| 291 |
+
param_groups = [g for g in param_groups if len(g["params"]) > 0]
|
| 292 |
+
|
| 293 |
+
return torch.optim.AdamW(
|
| 294 |
+
param_groups,
|
| 295 |
+
betas=self.betas,
|
| 296 |
+
eps=self.eps,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
@OptimizerConfig.register_subclass("multi_adam")
|
| 301 |
+
@dataclass
|
| 302 |
+
class MultiAdamConfig(OptimizerConfig):
|
| 303 |
+
"""Configuration for multiple Adam optimizers with different parameter groups.
|
| 304 |
+
|
| 305 |
+
This creates a dictionary of Adam optimizers, each with its own hyperparameters.
|
| 306 |
+
|
| 307 |
+
Args:
|
| 308 |
+
lr: Default learning rate (used if not specified for a group)
|
| 309 |
+
weight_decay: Default weight decay (used if not specified for a group)
|
| 310 |
+
optimizer_groups: Dictionary mapping parameter group names to their hyperparameters
|
| 311 |
+
grad_clip_norm: Gradient clipping norm
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
lr: float = 1e-3
|
| 315 |
+
weight_decay: float = 0.0
|
| 316 |
+
grad_clip_norm: float = 10.0
|
| 317 |
+
optimizer_groups: dict[str, dict[str, Any]] = field(default_factory=dict)
|
| 318 |
+
|
| 319 |
+
def build(self, params_dict: dict[str, list]) -> dict[str, torch.optim.Optimizer]:
|
| 320 |
+
"""Build multiple Adam optimizers.
|
| 321 |
+
|
| 322 |
+
Args:
|
| 323 |
+
params_dict: Dictionary mapping parameter group names to lists of parameters
|
| 324 |
+
The keys should match the keys in optimizer_groups
|
| 325 |
+
|
| 326 |
+
Returns:
|
| 327 |
+
Dictionary mapping parameter group names to their optimizers
|
| 328 |
+
"""
|
| 329 |
+
# Require params_dict.keys() == optimizer_groups.keys() exactly. Failing
|
| 330 |
+
# open let a typo'd group silently run with default hyperparameters (or
|
| 331 |
+
# a declared group be dropped with no optimizer and no error).
|
| 332 |
+
if self.optimizer_groups:
|
| 333 |
+
declared = set(self.optimizer_groups.keys())
|
| 334 |
+
provided = set(params_dict.keys())
|
| 335 |
+
undeclared = provided - declared # params with no config
|
| 336 |
+
unused = declared - provided # config with no params
|
| 337 |
+
if undeclared or unused:
|
| 338 |
+
raise ValueError(
|
| 339 |
+
"MultiAdamConfig group-name mismatch: "
|
| 340 |
+
f"params without optimizer_groups config={sorted(undeclared)}, "
|
| 341 |
+
f"optimizer_groups declared but no params provided={sorted(unused)}. "
|
| 342 |
+
"params_dict.keys() must match optimizer_groups.keys() exactly."
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
optimizers = {}
|
| 346 |
+
|
| 347 |
+
for name, params in params_dict.items():
|
| 348 |
+
# Reject declared-but-empty groups (can't build an optimizer).
|
| 349 |
+
if not params:
|
| 350 |
+
raise ValueError(
|
| 351 |
+
f"MultiAdamConfig group '{name}' has no parameters; "
|
| 352 |
+
"cannot build an optimizer for an empty parameter group."
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
group_config = self.optimizer_groups.get(name, {})
|
| 356 |
+
optimizer_kwargs = {
|
| 357 |
+
"lr": group_config.get("lr", self.lr),
|
| 358 |
+
"betas": group_config.get("betas", (0.9, 0.999)),
|
| 359 |
+
"eps": group_config.get("eps", 1e-5),
|
| 360 |
+
"weight_decay": group_config.get("weight_decay", self.weight_decay),
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
optimizers[name] = torch.optim.Adam(params, **optimizer_kwargs)
|
| 364 |
+
|
| 365 |
+
return optimizers
|
| 366 |
+
|
| 367 |
+
|
src/optim/schedulers.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
import abc
|
| 17 |
+
import logging
|
| 18 |
+
import math
|
| 19 |
+
from dataclasses import asdict, dataclass
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import draccus
|
| 23 |
+
from torch.optim import Optimizer
|
| 24 |
+
from torch.optim.lr_scheduler import LambdaLR, LRScheduler
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class LRSchedulerConfig(draccus.ChoiceRegistry, abc.ABC):
|
| 30 |
+
num_warmup_steps: int
|
| 31 |
+
|
| 32 |
+
@property
|
| 33 |
+
def type(self) -> str:
|
| 34 |
+
return self.get_choice_name(self.__class__)
|
| 35 |
+
|
| 36 |
+
@abc.abstractmethod
|
| 37 |
+
def build(self, optimizer: Optimizer, num_training_steps: int) -> LRScheduler | None:
|
| 38 |
+
raise NotImplementedError
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@LRSchedulerConfig.register_subclass("diffuser")
|
| 42 |
+
@dataclass
|
| 43 |
+
class DiffuserSchedulerConfig(LRSchedulerConfig):
|
| 44 |
+
name: str = "cosine"
|
| 45 |
+
num_warmup_steps: int | None = None
|
| 46 |
+
|
| 47 |
+
def build(self, optimizer: Optimizer, num_training_steps: int) -> LambdaLR:
|
| 48 |
+
from diffusers.optimization import get_scheduler
|
| 49 |
+
|
| 50 |
+
kwargs = {**asdict(self), "num_training_steps": num_training_steps, "optimizer": optimizer}
|
| 51 |
+
return get_scheduler(**kwargs)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@LRSchedulerConfig.register_subclass("vqbet")
|
| 55 |
+
@dataclass
|
| 56 |
+
class VQBeTSchedulerConfig(LRSchedulerConfig):
|
| 57 |
+
num_warmup_steps: int
|
| 58 |
+
num_vqvae_training_steps: int
|
| 59 |
+
num_cycles: float = 0.5
|
| 60 |
+
|
| 61 |
+
def build(self, optimizer: Optimizer, num_training_steps: int) -> LambdaLR:
|
| 62 |
+
def lr_lambda(current_step):
|
| 63 |
+
if current_step < self.num_vqvae_training_steps:
|
| 64 |
+
return float(1)
|
| 65 |
+
else:
|
| 66 |
+
adjusted_step = current_step - self.num_vqvae_training_steps
|
| 67 |
+
if adjusted_step < self.num_warmup_steps:
|
| 68 |
+
return float(adjusted_step) / float(max(1, self.num_warmup_steps))
|
| 69 |
+
progress = float(adjusted_step - self.num_warmup_steps) / float(
|
| 70 |
+
max(1, num_training_steps - self.num_warmup_steps)
|
| 71 |
+
)
|
| 72 |
+
return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(self.num_cycles) * 2.0 * progress)))
|
| 73 |
+
|
| 74 |
+
return LambdaLR(optimizer, lr_lambda, -1)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@LRSchedulerConfig.register_subclass("cosine_decay_with_warmup")
|
| 78 |
+
@dataclass
|
| 79 |
+
class CosineDecayWithWarmupSchedulerConfig(LRSchedulerConfig):
|
| 80 |
+
"""Used by Physical Intelligence to train pi0 (adopted by LabVLA).
|
| 81 |
+
|
| 82 |
+
When ``num_training_steps < num_decay_steps`` the configured recipe cannot
|
| 83 |
+
run as written. By default (``allow_auto_scale=False``) this is treated as a
|
| 84 |
+
configuration error and raises, rather than silently rewriting the schedule
|
| 85 |
+
into a different training recipe. Set ``allow_auto_scale=True`` to opt into
|
| 86 |
+
the historical behavior of scaling warmup/decay to fit the available steps;
|
| 87 |
+
when allowed, a >10% rewrite still escalates to a WARNING.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
num_warmup_steps: int
|
| 91 |
+
num_decay_steps: int
|
| 92 |
+
decay_lr: float
|
| 93 |
+
peak_lr: float | None = None # unused β per-group base lr is authoritative
|
| 94 |
+
allow_auto_scale: bool = False # fail-closed unless explicitly opted in
|
| 95 |
+
|
| 96 |
+
def build(self, optimizer: Optimizer, num_training_steps: int) -> LambdaLR:
|
| 97 |
+
actual_warmup_steps = self.num_warmup_steps
|
| 98 |
+
actual_decay_steps = self.num_decay_steps
|
| 99 |
+
self._auto_scaled = False
|
| 100 |
+
|
| 101 |
+
if num_training_steps < self.num_decay_steps:
|
| 102 |
+
# Refuse to silently rewrite the recipe unless explicitly allowed:
|
| 103 |
+
# a short run / post-resume step change would otherwise become a
|
| 104 |
+
# different schedule without the caller's consent.
|
| 105 |
+
if not self.allow_auto_scale:
|
| 106 |
+
raise ValueError(
|
| 107 |
+
"CosineDecayWithWarmup: num_training_steps "
|
| 108 |
+
f"({num_training_steps}) < num_decay_steps ({self.num_decay_steps}). "
|
| 109 |
+
"This would auto-rewrite the LR recipe. Refusing by default; set "
|
| 110 |
+
"allow_auto_scale=True to opt into scaling warmup/decay to fit "
|
| 111 |
+
"the available training steps."
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Scale the schedule to fit the available training steps.
|
| 115 |
+
scale_factor = num_training_steps / self.num_decay_steps
|
| 116 |
+
actual_warmup_steps = int(self.num_warmup_steps * scale_factor)
|
| 117 |
+
actual_decay_steps = num_training_steps
|
| 118 |
+
self._auto_scaled = True
|
| 119 |
+
|
| 120 |
+
# <=10% drift is typical (shaving total_steps to fit a job slot) and
|
| 121 |
+
# logs at INFO; beyond 10% it's effectively a different recipe, so
|
| 122 |
+
# escalate to a once-per-(config,run) WARNING.
|
| 123 |
+
drift_frac = abs(num_training_steps - self.num_decay_steps) / self.num_decay_steps
|
| 124 |
+
if drift_frac > 0.10:
|
| 125 |
+
from src.utils.logging_utils import warn_once
|
| 126 |
+
warn_once(
|
| 127 |
+
logging.getLogger(__name__),
|
| 128 |
+
("cosine_autoscale", num_training_steps, self.num_decay_steps),
|
| 129 |
+
"Auto-scaling LR scheduler with >10%% drift: "
|
| 130 |
+
"num_training_steps (%d) vs configured num_decay_steps (%d) "
|
| 131 |
+
"β this is effectively a different training recipe. "
|
| 132 |
+
"Scaling warmup: %d β %d, decay: %d β %d (scale factor: %.3f)",
|
| 133 |
+
num_training_steps, self.num_decay_steps,
|
| 134 |
+
self.num_warmup_steps, actual_warmup_steps,
|
| 135 |
+
self.num_decay_steps, actual_decay_steps, scale_factor,
|
| 136 |
+
)
|
| 137 |
+
else:
|
| 138 |
+
logging.info(
|
| 139 |
+
f"Auto-scaling LR scheduler: "
|
| 140 |
+
f"num_training_steps ({num_training_steps}) < num_decay_steps ({self.num_decay_steps}). "
|
| 141 |
+
f"Scaling warmup: {self.num_warmup_steps} β {actual_warmup_steps}, "
|
| 142 |
+
f"decay: {self.num_decay_steps} β {actual_decay_steps} "
|
| 143 |
+
f"(scale factor: {scale_factor:.3f})"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
# Keep the cosine formula identical to scripts/train.py:lr_lambda (the
|
| 147 |
+
# production curve); a step-0-indexed variant would diverge from it.
|
| 148 |
+
decay_lr = self.decay_lr
|
| 149 |
+
warmup_steps = actual_warmup_steps
|
| 150 |
+
decay_steps = actual_decay_steps
|
| 151 |
+
|
| 152 |
+
# Per-group lambdas so every param_group's cosine decay lands at
|
| 153 |
+
# decay_lr ABSOLUTELY. A single shared lambda would end DiT/KI groups
|
| 154 |
+
# (base_lr != args.lr) at the wrong final lr.
|
| 155 |
+
def make_lambda(alpha: float):
|
| 156 |
+
def lr_lambda(step):
|
| 157 |
+
if step < warmup_steps:
|
| 158 |
+
if step <= 0:
|
| 159 |
+
return 1.0 / (warmup_steps + 1)
|
| 160 |
+
frac = 1.0 - step / warmup_steps
|
| 161 |
+
return (1.0 / (warmup_steps + 1) - 1.0) * frac + 1.0
|
| 162 |
+
|
| 163 |
+
decay_progress = min(step - warmup_steps, decay_steps - warmup_steps)
|
| 164 |
+
decay_total = max(1, decay_steps - warmup_steps)
|
| 165 |
+
cosine_decay = 0.5 * (1.0 + math.cos(math.pi * decay_progress / decay_total))
|
| 166 |
+
return (1.0 - alpha) * cosine_decay + alpha
|
| 167 |
+
return lr_lambda
|
| 168 |
+
|
| 169 |
+
lr_lambdas = [
|
| 170 |
+
make_lambda(decay_lr / max(float(g["lr"]), 1e-12))
|
| 171 |
+
for g in optimizer.param_groups
|
| 172 |
+
]
|
| 173 |
+
|
| 174 |
+
return LambdaLR(optimizer, lr_lambdas, -1)
|
| 175 |
+
|
| 176 |
+
|
src/policies/LabVLA/__init__.py
ADDED
|
File without changes
|
src/policies/LabVLA/configuration_labvla.py
ADDED
|
@@ -0,0 +1,656 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
# LabVLA Configuration
|
| 4 |
+
# DiT Cross-Attention action head + Flow Matching
|
| 5 |
+
# Independent VLM forward + DiT cross-attention denoising
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass, field, replace
|
| 8 |
+
|
| 9 |
+
from src.config.default import DatasetConfig
|
| 10 |
+
from src.config.policies import PreTrainedConfig
|
| 11 |
+
from src.config.types import FeatureType, NormalizationMode, PolicyFeature
|
| 12 |
+
from src.optim.optimizers import AdamWConfig, LabVLAAdamWConfig
|
| 13 |
+
from src.utils.constants import OBS_IMAGES
|
| 14 |
+
from src.transforms.core import *
|
| 15 |
+
from src.transforms.annotation_tokenize import AnnotationTokenizeTransformFn
|
| 16 |
+
from src.transforms.build_unified_annotation import BuildUnifiedAnnotationTransformFn
|
| 17 |
+
from src.transforms.agibot_subtask import BuildAgiBotSubtaskTransformFn
|
| 18 |
+
from src.transforms.vlm_processor import Qwen3_VLProcessorTransformFn, UnifyLabVLAInputsTransformFn
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Single source of truth for the non-discretized task-prompt token budget,
|
| 22 |
+
# shared by the training-side processor (LabVLADatasetConfig.__post_init__) and
|
| 23 |
+
# the deploy-side reader (LabVLAConfig.tokenizer_max_length) so the two can't
|
| 24 |
+
# silently desync between train and serve.
|
| 25 |
+
DEFAULT_TOKENIZER_MAX_LENGTH = 48
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@DatasetConfig.register_subclass("labvla")
|
| 29 |
+
@dataclass
|
| 30 |
+
class LabVLADatasetConfig(DatasetConfig):
|
| 31 |
+
height: int = 224
|
| 32 |
+
width: int = 224
|
| 33 |
+
max_state_dim: int = 32
|
| 34 |
+
max_action_dim: int = 32
|
| 35 |
+
|
| 36 |
+
# Ο0.5 VLM pretrain / KI β FAST action tokenizer (default off, transform chain unchanged)
|
| 37 |
+
use_fast_tokenizer: bool = False
|
| 38 |
+
fast_tokenizer_path: str = "physical-intelligence/fast"
|
| 39 |
+
discrete_action_vocab_size: int = 2048
|
| 40 |
+
discrete_action_max_length: int = 240 # above the historical max observed (229) so FAST CE targets aren't truncated (4ds p99 β 175); encode() still warns past max_length. Smoke tests may pass an explicit 128.
|
| 41 |
+
source_shape_convergence: bool = False
|
| 42 |
+
|
| 43 |
+
# Ο0.5 Β§B.1: state discretized into 256 bins, prepended to language prompt as text.
|
| 44 |
+
# Mirror of LabVLAConfig.discretize_state_in_vlm_pretrain β kept here too so the
|
| 45 |
+
# transform chain can be specialized at config-build time. Only takes effect when
|
| 46 |
+
# training_phase == "vlm_pretrain". Posttrain keeps state as a continuous tensor
|
| 47 |
+
# (state_proj into DiT) β out of scope for this feature.
|
| 48 |
+
training_phase: str = "posttrain"
|
| 49 |
+
# Persist the data-side action target mode so deployment can decide whether
|
| 50 |
+
# to add current state back to predicted arm deltas.
|
| 51 |
+
action_mode: str = "delta"
|
| 52 |
+
discretize_state_in_vlm_pretrain: bool = True
|
| 53 |
+
# When discretization is on, the language prompt becomes much longer (32 dim Γ
|
| 54 |
+
# ~3 chars per bin idx β 100+ tokens). Bump max_length to fit. 192 covers
|
| 55 |
+
# 32-dim discretized state + the original instruction tokens with headroom.
|
| 56 |
+
tokenizer_max_length_with_discretized_state: int = 192
|
| 57 |
+
|
| 58 |
+
# The Qwen3VL processor and AnnotationTokenize tokenizer both default to the
|
| 59 |
+
# HF repo id 'Qwen/Qwen3-VL-4B-Instruct', which needs that repo cached under
|
| 60 |
+
# HF_HUB_OFFLINE. Plumb the actual `--vlm_pretrained_path` (typically a local
|
| 61 |
+
# dir) through so the transform chain stays self-contained and offline-safe.
|
| 62 |
+
vlm_pretrained_path: str = "Qwen/Qwen3-VL-4B-Instruct"
|
| 63 |
+
|
| 64 |
+
# LabUtopia-side gripper canonicalize. When True, snap raw gripper width to
|
| 65 |
+
# {0, gripper_max_width} BEFORE NormalizeTransformFn (continuous [0, 0.04m] β
|
| 66 |
+
# bimodal {0, 0.04m}). Use for LabUtopia finetune from an OXE pretrain ckpt
|
| 67 |
+
# that saw gripper as binary {0,1}.
|
| 68 |
+
#
|
| 69 |
+
# IMPORTANT: the gripper-dim stats override is NOT automatic. For the snapped
|
| 70 |
+
# {0, max_width} values to normalize to exactly {-1, +1}, the stats.json
|
| 71 |
+
# gripper dim MUST already have q01=0, q99=max_width β pre-patch it with
|
| 72 |
+
# `data_process/labutopia_canonicalize_stats.py`, otherwise the snapped values
|
| 73 |
+
# are normalized through the dataset's RAW q01/q99 (mis-scaled gripper).
|
| 74 |
+
# `hydrate_all` fails loud when snap_gripper_to_binary=True but the stats are
|
| 75 |
+
# not canonicalized (bypass: LABVLA_ALLOW_UNPATCHED_SNAP_STATS=1).
|
| 76 |
+
snap_gripper_to_binary: bool = False
|
| 77 |
+
gripper_max_width: float = 0.04 # Franka Panda max gripper width (m)
|
| 78 |
+
gripper_canonical_dim: int = 7 # canonical gripper index (7-DoF arm + grip)
|
| 79 |
+
|
| 80 |
+
data_transforms: TransformGroup | None = field(default=None)
|
| 81 |
+
|
| 82 |
+
def __post_init__(self):
|
| 83 |
+
super().__post_init__()
|
| 84 |
+
if (
|
| 85 |
+
self.source_shape_convergence
|
| 86 |
+
and self.use_fast_tokenizer
|
| 87 |
+
and self.discrete_action_max_length < 192
|
| 88 |
+
):
|
| 89 |
+
raise ValueError(
|
| 90 |
+
"source_shape_convergence=True requires "
|
| 91 |
+
"discrete_action_max_length>=192 for current Phase-C FAST "
|
| 92 |
+
"budgets; pass --discrete_action_max_length 192 or disable "
|
| 93 |
+
"source shape convergence."
|
| 94 |
+
)
|
| 95 |
+
# When Ο0.5 VLM-pretrain + state discretization are both on, build the
|
| 96 |
+
# chain in an order that lets DiscretizeStateTransformFn read normalized
|
| 97 |
+
# state values BEFORE Qwen3_VLProcessorTransformFn tokenizes the task
|
| 98 |
+
# prompt: [...image transforms..., NormalizeTransformFn,
|
| 99 |
+
# DiscretizeStateTransformFn, Qwen3_VLProcessorTransformFn,
|
| 100 |
+
# AnnotationTokenizeTransformFn, ComposeFieldsTransform, ...].
|
| 101 |
+
# Otherwise (posttrain or discretize off) keep the original chain order.
|
| 102 |
+
do_discretize = (
|
| 103 |
+
self.training_phase == "vlm_pretrain"
|
| 104 |
+
and self.discretize_state_in_vlm_pretrain
|
| 105 |
+
)
|
| 106 |
+
# Build transforms using instance attributes (not class-level defaults)
|
| 107 |
+
# to ensure custom height/width/max_state_dim/max_action_dim are respected.
|
| 108 |
+
if self.data_transforms is None:
|
| 109 |
+
qwen_processor = Qwen3_VLProcessorTransformFn(
|
| 110 |
+
pretrained_model_name_or_path=self.vlm_pretrained_path,
|
| 111 |
+
max_length=(
|
| 112 |
+
self.tokenizer_max_length_with_discretized_state
|
| 113 |
+
if do_discretize else DEFAULT_TOKENIZER_MAX_LENGTH
|
| 114 |
+
),
|
| 115 |
+
)
|
| 116 |
+
normalize_xform = NormalizeTransformFn(mode="mean_std")
|
| 117 |
+
base_inputs = [
|
| 118 |
+
CanonicalArmLayoutTransformFn(),
|
| 119 |
+
CanonicalSingleArmLayoutTransformFn(),
|
| 120 |
+
DeltaActionTransformFn(),
|
| 121 |
+
# GripperSemanticCanonicalizeFn() is disabled: q01/q99
|
| 122 |
+
# NormalizeTransformFn already maps each repo's gripper to [-1, +1]
|
| 123 |
+
# equivalently across width / open_fraction / data-driven sources,
|
| 124 |
+
# and per-robot max_width is unknown for UR/Festo/Rizon4 (Franka
|
| 125 |
+
# 0.04m doesn't generalize). Re-enable only with per-robot
|
| 126 |
+
# calibration metadata.
|
| 127 |
+
ResizeImagesWithPadFn(height=self.height, width=self.width),
|
| 128 |
+
RemapImageKeyTransformFn(),
|
| 129 |
+
]
|
| 130 |
+
# BuildUnifiedAnnotationTransformFn packs the 12 RoboInter
|
| 131 |
+
# `annotation.<X>` parquet columns into a single
|
| 132 |
+
# `annotation.unified` text field. No-op for datasets without
|
| 133 |
+
# those columns (cheap absent-key skip).
|
| 134 |
+
unify_anno = BuildUnifiedAnnotationTransformFn()
|
| 135 |
+
# Agibot subtask builder: copies data['task'] β data['annotation.subtask']
|
| 136 |
+
# and rewrites prompt for agibot. Must run BEFORE
|
| 137 |
+
# DiscretizeStateTransformFn β that transform PREPENDS
|
| 138 |
+
# "<state>...</state>\n" to data['task'], so reading data['task']
|
| 139 |
+
# afterwards would put discretized digits into the CE target.
|
| 140 |
+
# No-op for other schemas (enabled=False default; flipped True by
|
| 141 |
+
# hydrate_all when schema declares annotation.subtask in annotation_losses).
|
| 142 |
+
agibot_subtask = BuildAgiBotSubtaskTransformFn()
|
| 143 |
+
if do_discretize:
|
| 144 |
+
from src.transforms.state_discretize import DiscretizeStateTransformFn
|
| 145 |
+
from src.dataset.adapters.robointer_token_budget import ROBOINTER_BUDGET
|
| 146 |
+
# Order: ... β AgibotSubtask β Normalize β Discretize β
|
| 147 |
+
# BuildUnifiedAnno β Qwen3VL processor β AnnotationTokenize β ...
|
| 148 |
+
# AgibotSubtask runs early so it sees the clean task string,
|
| 149 |
+
# then Discretize prepends the <state>...</state> bin digits
|
| 150 |
+
# to the rewritten generic prompt.
|
| 151 |
+
input_transforms = base_inputs + [
|
| 152 |
+
agibot_subtask,
|
| 153 |
+
normalize_xform,
|
| 154 |
+
DiscretizeStateTransformFn(num_bins=ROBOINTER_BUDGET.state_num_bins),
|
| 155 |
+
unify_anno,
|
| 156 |
+
qwen_processor,
|
| 157 |
+
AnnotationTokenizeTransformFn(
|
| 158 |
+
tokenizer_path=self.vlm_pretrained_path,
|
| 159 |
+
dynamic_shape=self.source_shape_convergence,
|
| 160 |
+
),
|
| 161 |
+
ComposeFieldsTransform(),
|
| 162 |
+
PadStateAndActionTransformFn(
|
| 163 |
+
max_state_dim=self.max_state_dim,
|
| 164 |
+
max_action_dim=self.max_action_dim,
|
| 165 |
+
),
|
| 166 |
+
UnifyLabVLAInputsTransformFn(),
|
| 167 |
+
]
|
| 168 |
+
else:
|
| 169 |
+
# Original order + unified-anno builder before tokenize. Posttrain
|
| 170 |
+
# stays bit-identical for datasets with no annotation_losses
|
| 171 |
+
# (BuildUnified is a no-op then). Optional SnapGripperToEndpointsFn
|
| 172 |
+
# runs just before NormalizeTransformFn for LabUtopia finetune from
|
| 173 |
+
# an OXE ckpt that saw binary gripper; the q01[grip]=0 /
|
| 174 |
+
# q99[grip]=max_width stats override is NOT applied here (pre-patch
|
| 175 |
+
# stats.json β hydrate_all fails loud if snap is on but stats
|
| 176 |
+
# aren't canonicalized).
|
| 177 |
+
pre_normalize: list = []
|
| 178 |
+
if self.snap_gripper_to_binary:
|
| 179 |
+
pre_normalize.append(SnapGripperToEndpointsFn(
|
| 180 |
+
gripper_dim=self.gripper_canonical_dim,
|
| 181 |
+
max_width=self.gripper_max_width,
|
| 182 |
+
threshold_ratio=0.5,
|
| 183 |
+
))
|
| 184 |
+
input_transforms = base_inputs + [
|
| 185 |
+
agibot_subtask,
|
| 186 |
+
unify_anno,
|
| 187 |
+
qwen_processor,
|
| 188 |
+
AnnotationTokenizeTransformFn(
|
| 189 |
+
tokenizer_path=self.vlm_pretrained_path,
|
| 190 |
+
dynamic_shape=self.source_shape_convergence,
|
| 191 |
+
),
|
| 192 |
+
*pre_normalize,
|
| 193 |
+
normalize_xform,
|
| 194 |
+
ComposeFieldsTransform(),
|
| 195 |
+
PadStateAndActionTransformFn(
|
| 196 |
+
max_state_dim=self.max_state_dim,
|
| 197 |
+
max_action_dim=self.max_action_dim,
|
| 198 |
+
),
|
| 199 |
+
UnifyLabVLAInputsTransformFn(),
|
| 200 |
+
]
|
| 201 |
+
self.data_transforms = TransformGroup(inputs=input_transforms, outputs=[])
|
| 202 |
+
inputs = list(self.data_transforms.inputs)
|
| 203 |
+
has_delta = any(isinstance(t, DeltaActionTransformFn) for t in inputs)
|
| 204 |
+
if self.action_mode == "delta":
|
| 205 |
+
if not has_delta:
|
| 206 |
+
inputs = [DeltaActionTransformFn(), *inputs]
|
| 207 |
+
self.data_transforms = replace(self.data_transforms, inputs=inputs)
|
| 208 |
+
else:
|
| 209 |
+
if has_delta:
|
| 210 |
+
# Warn loudly when stripping a user-declared Delta in abs mode: a
|
| 211 |
+
# silent removal (e.g. a typo action_mode='abs' on a chunk-delta
|
| 212 |
+
# dataset) would drop delta semantics and train on wrong targets.
|
| 213 |
+
import logging as _logging
|
| 214 |
+
_logging.warning(
|
| 215 |
+
"[LabVLADatasetConfig] action_mode='abs' but user-provided "
|
| 216 |
+
"data_transforms includes DeltaActionTransformFn. Stripping "
|
| 217 |
+
"it. If you meant delta, set action_mode='delta'."
|
| 218 |
+
)
|
| 219 |
+
inputs = [t for t in inputs if not isinstance(t, DeltaActionTransformFn)]
|
| 220 |
+
self.data_transforms = replace(self.data_transforms, inputs=inputs)
|
| 221 |
+
|
| 222 |
+
# Ο0.5 / KI: optionally insert FAST action tokenizer AFTER
|
| 223 |
+
# NormalizeTransformFn + ComposeFieldsTransform but BEFORE
|
| 224 |
+
# PadStateAndActionTransformFn. Running before pad is critical β otherwise
|
| 225 |
+
# DCT+BPE encodes the zero-padded trailing dims into the FAST token
|
| 226 |
+
# sequence and pollutes the CE signal (up to 24 of 32 dims are zeros for
|
| 227 |
+
# robointer_droid).
|
| 228 |
+
if self.use_fast_tokenizer:
|
| 229 |
+
from src.transforms.fast_action import FastActionEncodeTransformFn
|
| 230 |
+
has_fast = any(isinstance(t, FastActionEncodeTransformFn) for t in inputs)
|
| 231 |
+
if not has_fast:
|
| 232 |
+
# Find the Pad transform; insert FAST immediately before it.
|
| 233 |
+
pad_idx = next(
|
| 234 |
+
(i for i, t in enumerate(inputs)
|
| 235 |
+
if isinstance(t, PadStateAndActionTransformFn)),
|
| 236 |
+
len(inputs),
|
| 237 |
+
)
|
| 238 |
+
inputs = [
|
| 239 |
+
*inputs[:pad_idx],
|
| 240 |
+
FastActionEncodeTransformFn(
|
| 241 |
+
path=self.fast_tokenizer_path,
|
| 242 |
+
vocab_size=self.discrete_action_vocab_size,
|
| 243 |
+
max_length=self.discrete_action_max_length,
|
| 244 |
+
source_shape_convergence=self.source_shape_convergence,
|
| 245 |
+
trim_to_mask=self.source_shape_convergence,
|
| 246 |
+
),
|
| 247 |
+
*inputs[pad_idx:],
|
| 248 |
+
]
|
| 249 |
+
self.data_transforms = replace(self.data_transforms, inputs=inputs)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@PreTrainedConfig.register_subclass("labvla")
|
| 253 |
+
@dataclass
|
| 254 |
+
class LabVLAConfig(PreTrainedConfig):
|
| 255 |
+
dtype: str = "bfloat16"
|
| 256 |
+
|
| 257 |
+
# DiT Action Head config (replaces Qwen3 Transformer action expert)
|
| 258 |
+
# Default params match Spirit-v1.5: 18 layers, hidden=1024, 8 heads, head_dim=128
|
| 259 |
+
dit_num_layers: int = 18
|
| 260 |
+
dit_num_heads: int = 8
|
| 261 |
+
dit_head_dim: int = 128
|
| 262 |
+
dit_dropout: float = 0.0
|
| 263 |
+
dit_cross_attention_dim: int | None = None # None = same as dit_hidden_size
|
| 264 |
+
# Spirit-v1.5-style interleaved self-attention in the DiT. When True
|
| 265 |
+
# (default), odd-indexed DiT blocks are self-attention only so the prepended
|
| 266 |
+
# state token and action tokens exchange information layer-by-layer;
|
| 267 |
+
# even-indexed blocks remain cross-attention to VLM features. Persisted in the
|
| 268 |
+
# config so deployment and resume can't silently mismatch the Python default.
|
| 269 |
+
dit_interleave_self_attention: bool = True
|
| 270 |
+
# starVLA-style layerwise VLM features. When True, each cross-attn DiT block
|
| 271 |
+
# reads a DIFFERENT VLM hidden-state layer (last-N of VLM, one per cross-attn
|
| 272 |
+
# block) instead of all sharing VLM's last layer. Costs ~1.7 GB/GPU extra
|
| 273 |
+
# (retains all VLM hidden states). Only supported on the posttrain+KI=False
|
| 274 |
+
# path.
|
| 275 |
+
dit_layerwise_vlm_features: bool = False
|
| 276 |
+
|
| 277 |
+
n_obs_steps: int = 1
|
| 278 |
+
chunk_size: int = 50
|
| 279 |
+
n_action_steps: int = 50
|
| 280 |
+
|
| 281 |
+
max_state_dim: int = 32
|
| 282 |
+
max_action_dim: int = 32
|
| 283 |
+
|
| 284 |
+
# Flow matching parameters
|
| 285 |
+
num_inference_steps: int = 10
|
| 286 |
+
time_sampling_beta_alpha: float = 1.5
|
| 287 |
+
time_sampling_beta_beta: float = 1.0
|
| 288 |
+
time_sampling_scale: float = 0.999
|
| 289 |
+
time_sampling_offset: float = 0.0 # Flipped convention (t=0=noise, t=1=clean): include pure-noise end, exclude pure-clean end (ill-defined target)
|
| 290 |
+
image_resolution: tuple[int, int] = (224, 224)
|
| 291 |
+
|
| 292 |
+
empty_cameras: int = 0
|
| 293 |
+
|
| 294 |
+
# VLM pretrained weights path
|
| 295 |
+
vlm_pretrained_path: str = "Qwen/Qwen3-VL-4B-Instruct"
|
| 296 |
+
|
| 297 |
+
# Attention implementation
|
| 298 |
+
attn_implementation: str = "flash_attention_2"
|
| 299 |
+
|
| 300 |
+
# Normalization -- Note: set to IDENTITY because normalization is done inside data_processors
|
| 301 |
+
# (pretrain_processor.py / lerobot_v30_processor.py hardcode mean_std normalization),
|
| 302 |
+
# not through the standard lerobot Transform chain's NormalizeTransformFn.
|
| 303 |
+
# Denormalization at deployment time is manually implemented in serve_labvla.py.
|
| 304 |
+
# If normalization is migrated to the Transform chain, this must be updated to the corresponding NormalizationMode.
|
| 305 |
+
normalization_mapping: dict[str, NormalizationMode] = field(
|
| 306 |
+
default_factory=lambda: {
|
| 307 |
+
"VISUAL": NormalizationMode.IDENTITY,
|
| 308 |
+
"STATE": NormalizationMode.IDENTITY,
|
| 309 |
+
"ACTION": NormalizationMode.IDENTITY,
|
| 310 |
+
}
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
# Training control
|
| 314 |
+
gradient_checkpointing: bool = False
|
| 315 |
+
gc_visual_encoder: bool = True # Vision encoder gradient checkpointing (only effective when gradient_checkpointing=True)
|
| 316 |
+
gc_language_model: bool = True # VLM Language Model gradient checkpointing (only effective when gradient_checkpointing=True)
|
| 317 |
+
gc_dit: bool = False # DiT Action Head gradient checkpointing (only effective when gradient_checkpointing=True)
|
| 318 |
+
# compile_model applies torch.compile to `sample_actions` (inference) ONLY.
|
| 319 |
+
# Training `forward()` stays under @dynamo.disable for DeepSpeed + flash_attn
|
| 320 |
+
# compatibility, so this flag does NOT speed up training.
|
| 321 |
+
compile_model: bool = False
|
| 322 |
+
compile_mode: str = "max-autotune"
|
| 323 |
+
device: str | None = None
|
| 324 |
+
|
| 325 |
+
# Optimizer
|
| 326 |
+
optimizer_lr: float = 5e-5
|
| 327 |
+
optimizer_betas: tuple[float, float] = (0.9, 0.95)
|
| 328 |
+
optimizer_eps: float = 1e-8
|
| 329 |
+
optimizer_weight_decay: float = 0.01
|
| 330 |
+
optimizer_grad_clip_norm: float = 1.0
|
| 331 |
+
|
| 332 |
+
# Grouped learning rates (starVLA style)
|
| 333 |
+
# VLM uses low LR to protect pretrained weights, DiT uses high LR to accelerate convergence of randomly initialized modules
|
| 334 |
+
optimizer_vlm_lr: float = 5e-5 # VLM backbone lr (same as base lr, no scaling)
|
| 335 |
+
optimizer_dit_lr: float = 1e-4 # DiT action head lr
|
| 336 |
+
|
| 337 |
+
# Scheduler
|
| 338 |
+
scheduler_warmup_steps: int = 1_000
|
| 339 |
+
scheduler_decay_steps: int = 100_000
|
| 340 |
+
scheduler_decay_lr: float = 2.5e-6
|
| 341 |
+
# Opt-in for the cosine scheduler to auto-rewrite warmup/decay when the
|
| 342 |
+
# optimizer-step horizon (num_training_steps) is shorter than
|
| 343 |
+
# scheduler_decay_steps. Default False = fail-closed (raise), so a
|
| 344 |
+
# misconfigured decay length surfaces instead of silently becoming a different
|
| 345 |
+
# LR recipe. With gradient_accumulation>1 the horizon is steps//GA, so a
|
| 346 |
+
# launcher that sets decay_steps==steps must express decay_steps in
|
| 347 |
+
# optimizer-step units or set this True.
|
| 348 |
+
scheduler_allow_auto_scale: bool = False
|
| 349 |
+
|
| 350 |
+
# Deploy-side readers (serve_labvla) consume this field; the training-side
|
| 351 |
+
# processor budget comes from the SAME module constant via
|
| 352 |
+
# LabVLADatasetConfig.__post_init__, so the two can no longer drift.
|
| 353 |
+
tokenizer_max_length: int = DEFAULT_TOKENIZER_MAX_LENGTH
|
| 354 |
+
|
| 355 |
+
# Freeze control
|
| 356 |
+
freeze_vision_encoder: bool = True
|
| 357 |
+
train_expert_only: bool = False
|
| 358 |
+
train_vlm_only: bool = False
|
| 359 |
+
|
| 360 |
+
# -------- Ο0.5 VLM pretrain + Knowledge Isolation (opt-in, default = current behavior) --------
|
| 361 |
+
# training_phase:
|
| 362 |
+
# "posttrain" (default) current VLM + DiT + Flow Matching MSE pipeline (bit-identical).
|
| 363 |
+
# "vlm_pretrain" Ο0.5 Sec 3.3 pretrain style: VLM-only + FAST action token CE.
|
| 364 |
+
# DiT not instantiated. Sequence: [state_tok | image | lang | FAST tokens].
|
| 365 |
+
training_phase: str = "posttrain"
|
| 366 |
+
# Delta mode predicts action deltas for delta_mask dims; abs mode predicts
|
| 367 |
+
# target poses directly. VLM pretrain launchers set this to "abs".
|
| 368 |
+
action_mode: str = "delta"
|
| 369 |
+
|
| 370 |
+
# knowledge_isolation: only meaningful in posttrain (vlm_pretrain implies True-like).
|
| 371 |
+
# True -> a) vlm_features.detach() blocks DiT -> VLM gradients
|
| 372 |
+
# b) adds FAST CE loss alongside MSE: total = ki_mse_weight * MSE + CE
|
| 373 |
+
# False -> preserves current bit-identical posttrain behavior
|
| 374 |
+
knowledge_isolation: bool = False
|
| 375 |
+
|
| 376 |
+
# use_fast_tokenizer: whether the DataLoader computes FAST action tokens.
|
| 377 |
+
# vlm_pretrain requires True; posttrain only when knowledge_isolation=True.
|
| 378 |
+
use_fast_tokenizer: bool = False
|
| 379 |
+
|
| 380 |
+
fast_tokenizer_path: str = "physical-intelligence/fast"
|
| 381 |
+
discrete_action_vocab_size: int = 2048
|
| 382 |
+
discrete_action_max_length: int = 240 # above the historical max observed (229) so FAST CE targets aren't truncated (4ds p99 β 175); encode() still warns past max_length. Smoke tests may pass an explicit 128.
|
| 383 |
+
|
| 384 |
+
# KI loss mixing (posttrain+KI): total = ki_mse_weight * MSE + CE, per Ο0.5
|
| 385 |
+
# Eq (1) with Ξ±=10.0 (App B.3 p.19). vlm_pretrain ignores this (Ξ±=0 there).
|
| 386 |
+
# Renamed from ki_ce_weight to match paper: Ξ± multiplies MSE, not CE.
|
| 387 |
+
ki_mse_weight: float = 10.0
|
| 388 |
+
|
| 389 |
+
# Gripper loss weighting. When >1.0, the per-element flow-matching MSE for
|
| 390 |
+
# dims in `gripper_action_dims` is scaled before the mean β counteracting the
|
| 391 |
+
# structural dilution of a single gripper scalar against 7 joint dims in
|
| 392 |
+
# uniform-average MSE.
|
| 393 |
+
# Default 1.0 keeps current behaviour. `gripper_action_dims` is populated
|
| 394 |
+
# from the active dataset schema in scripts/train.py before model
|
| 395 |
+
# construction; an empty tuple disables the weighting branch entirely.
|
| 396 |
+
gripper_loss_weight: float = 1.0
|
| 397 |
+
gripper_action_dims: tuple[int, ...] = ()
|
| 398 |
+
|
| 399 |
+
# Ο0.5 Β§B.1: discretize proprioceptive state into 256 bins β text tokens
|
| 400 |
+
# prepended to language prompt (vlm_pretrain only). Default True so Ο0.5
|
| 401 |
+
# paradigm pretrain runs are paper-faithful out-of-the-box. Posttrain
|
| 402 |
+
# ignores this flag (state continues to flow through state_proj into DiT).
|
| 403 |
+
discretize_state_in_vlm_pretrain: bool = True
|
| 404 |
+
|
| 405 |
+
# Ο0.5 Appendix B.1 + Figure 11 specify a block-wise attention mask: the
|
| 406 |
+
# prefix (images + state + prompt) is FULLY bidirectional, FAST tokens see
|
| 407 |
+
# prefix fully and are causal among themselves, and annotation/text tokens are
|
| 408 |
+
# causal on themselves but see prefix fully. The default HF Qwen3-VL forward
|
| 409 |
+
# uses pure decoder-only causal attention. Enable this to build and pass a
|
| 410 |
+
# (B, 1, L, L) 4D block-wise mask to `self.vlm.language_model(...)`; HF
|
| 411 |
+
# `create_causal_mask()` early-exits on a 4D mask and uses it as-is.
|
| 412 |
+
#
|
| 413 |
+
# WARNING: changing this flag mid-training (ckpt trained with one value,
|
| 414 |
+
# continued with the other) causes a train/deploy distribution mismatch. Set
|
| 415 |
+
# True before step 0 for paper-faithful new training; keep False to deploy
|
| 416 |
+
# legacy ckpts trained with causal-only prefix attention. Default False
|
| 417 |
+
# preserves bit-identical loading of pre-flag ckpts.
|
| 418 |
+
pi05_block_attention_mask: bool = False
|
| 419 |
+
|
| 420 |
+
def __post_init__(self):
|
| 421 |
+
super().__post_init__()
|
| 422 |
+
# n_action_steps governs deploy-time queue length / how many predicted
|
| 423 |
+
# actions are executed per inference; it CANNOT exceed chunk_size (the
|
| 424 |
+
# model only predicts chunk_size frames per call). Historical default
|
| 425 |
+
# was 50 == chunk_size; when chunk_size shrinks we silently clamp
|
| 426 |
+
# n_action_steps so a single `--chunk_size N` flag in launchers is
|
| 427 |
+
# sufficient (no need to also remember `--n_action_steps`). If callers
|
| 428 |
+
# ever want a smaller deploy horizon (e.g. execute only 5 of 32 chunk
|
| 429 |
+
# actions) they can construct LabVLAConfig directly with an explicit
|
| 430 |
+
# smaller n_action_steps.
|
| 431 |
+
if self.n_action_steps > self.chunk_size:
|
| 432 |
+
self.n_action_steps = self.chunk_size
|
| 433 |
+
|
| 434 |
+
# Double gradient checkpointing is a HARD RULE violation (~2x step time).
|
| 435 |
+
if (
|
| 436 |
+
self.gradient_checkpointing
|
| 437 |
+
and self.gc_visual_encoder
|
| 438 |
+
and self.gc_language_model
|
| 439 |
+
):
|
| 440 |
+
raise ValueError(
|
| 441 |
+
"HARD RULE: gc_visual_encoder=True and gc_language_model=True cannot "
|
| 442 |
+
"both be enabled when gradient_checkpointing=True β double-GC causes "
|
| 443 |
+
"~2Γ per-step time. Pick exactly one. See CLAUDE.md for details."
|
| 444 |
+
)
|
| 445 |
+
if self.dtype not in ["bfloat16", "float32"]:
|
| 446 |
+
raise ValueError(f"Invalid dtype: {self.dtype}")
|
| 447 |
+
# train_expert_only freezes the VLM and train_vlm_only freezes the DiT +
|
| 448 |
+
# projections; both at once freezes every trainable param. Catch it at
|
| 449 |
+
# config-time instead of a confusing "No trainable parameters" later.
|
| 450 |
+
if self.train_expert_only and self.train_vlm_only:
|
| 451 |
+
raise ValueError(
|
| 452 |
+
"train_expert_only and train_vlm_only are mutually exclusive β "
|
| 453 |
+
"both freeze 100% of the model. Pick exactly one."
|
| 454 |
+
)
|
| 455 |
+
# Mirror the CLI's gripper_loss_weight>0 guard at the config layer so
|
| 456 |
+
# direct LabVLAConfig(...) paths (tests, notebooks, deploy wrapper) can't
|
| 457 |
+
# pass 0 (zeros gripper supervision) or negative (flips MSE gradient sign).
|
| 458 |
+
if not (self.gripper_loss_weight > 0):
|
| 459 |
+
raise ValueError(
|
| 460 |
+
f"gripper_loss_weight must be > 0 (got "
|
| 461 |
+
f"{self.gripper_loss_weight!r}); 0 zeros gripper "
|
| 462 |
+
f"supervision and negative values flip the MSE "
|
| 463 |
+
f"gradient sign. Pass 1.0 for no-op weighting."
|
| 464 |
+
)
|
| 465 |
+
if self.training_phase not in ("posttrain", "vlm_pretrain"):
|
| 466 |
+
raise ValueError(
|
| 467 |
+
f"training_phase must be 'posttrain' or 'vlm_pretrain', got {self.training_phase!r}"
|
| 468 |
+
)
|
| 469 |
+
if self.action_mode not in ("delta", "abs"):
|
| 470 |
+
raise ValueError(
|
| 471 |
+
f"action_mode must be 'delta' or 'abs', got {self.action_mode!r}"
|
| 472 |
+
)
|
| 473 |
+
if self.training_phase == "vlm_pretrain" and not self.use_fast_tokenizer:
|
| 474 |
+
raise ValueError(
|
| 475 |
+
"training_phase='vlm_pretrain' requires use_fast_tokenizer=True "
|
| 476 |
+
"(VLM pretrain's only training signal is FAST action token CE)"
|
| 477 |
+
)
|
| 478 |
+
if self.knowledge_isolation and not self.use_fast_tokenizer:
|
| 479 |
+
raise ValueError(
|
| 480 |
+
"knowledge_isolation=True requires use_fast_tokenizer=True "
|
| 481 |
+
"(KI's CE branch needs FAST tokens as target)"
|
| 482 |
+
)
|
| 483 |
+
if self.knowledge_isolation and self.train_expert_only:
|
| 484 |
+
raise ValueError(
|
| 485 |
+
"knowledge_isolation=True is incompatible with train_expert_only=True. "
|
| 486 |
+
"KI needs CE gradient to flow through the VLM backbone, but "
|
| 487 |
+
"train_expert_only freezes the entire VLM. Pick exactly one."
|
| 488 |
+
)
|
| 489 |
+
# Reject (posttrain, KI=False, fast_tok=True): that path early-returns MSE
|
| 490 |
+
# before touching ki_head, so fast_tok only creates dead ki_head params
|
| 491 |
+
# that pollute optimizer state + checkpoints.
|
| 492 |
+
if (self.training_phase == "posttrain"
|
| 493 |
+
and not self.knowledge_isolation
|
| 494 |
+
and self.use_fast_tokenizer):
|
| 495 |
+
raise ValueError(
|
| 496 |
+
"use_fast_tokenizer=True is only meaningful in vlm_pretrain "
|
| 497 |
+
"or posttrain+knowledge_isolation. The current config "
|
| 498 |
+
"(posttrain, KI=False, fast_tok=True) would build ki_head "
|
| 499 |
+
"without ever using it β pick vlm_pretrain, KI=True, or "
|
| 500 |
+
"set use_fast_tokenizer=False."
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
# vlm_pretrain + train_vlm_only is broken: train_vlm_only freezes
|
| 504 |
+
# everything but the VLM backbone, including ki_head β yet vlm_pretrain's
|
| 505 |
+
# only signal is FAST CE through ki_head, so the VLM would train against a
|
| 506 |
+
# frozen random classifier. Refuse to start.
|
| 507 |
+
if (self.training_phase == "vlm_pretrain"
|
| 508 |
+
and self.train_vlm_only):
|
| 509 |
+
raise ValueError(
|
| 510 |
+
"training_phase='vlm_pretrain' is incompatible with "
|
| 511 |
+
"train_vlm_only=True. vlm_pretrain trains the VLM via FAST "
|
| 512 |
+
"CE through ki_head; train_vlm_only freezes ki_head along "
|
| 513 |
+
"with the DiT/projection, leaving the VLM to train against "
|
| 514 |
+
"a randomly-initialised classifier head. Either turn off "
|
| 515 |
+
"train_vlm_only or switch to posttrain (where the DiT/MSE "
|
| 516 |
+
"path is the supervision signal)."
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
# Symmetric trap to the above: train_expert_only freezes the entire VLM
|
| 520 |
+
# backbone, but vlm_pretrain's only signal is FAST CE through that
|
| 521 |
+
# backbone, so CE would only update ki_head over frozen random features.
|
| 522 |
+
if (self.training_phase == "vlm_pretrain"
|
| 523 |
+
and self.train_expert_only):
|
| 524 |
+
raise ValueError(
|
| 525 |
+
"training_phase='vlm_pretrain' is incompatible with "
|
| 526 |
+
"train_expert_only=True. vlm_pretrain trains the VLM via "
|
| 527 |
+
"FAST CE; train_expert_only freezes the entire VLM, so the "
|
| 528 |
+
"only thing left to train would be the ki_head classifier "
|
| 529 |
+
"over random VLM features. Either turn off train_expert_only "
|
| 530 |
+
"or switch to posttrain."
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
# vlm_pretrain + knowledge_isolation=True is incoherent: KI is
|
| 534 |
+
# posttrain-only (CE via ki_head + MSE via DiT with detached flow between
|
| 535 |
+
# them), but vlm_pretrain already runs CE-only through ki_head with no DiT,
|
| 536 |
+
# so KI=True has nothing to isolate and just adds a trainable
|
| 537 |
+
# state_vlm_proj (never invoked when state is discretized) that trips DDP
|
| 538 |
+
# find_unused_parameters / pollutes optimizer state.
|
| 539 |
+
if (self.training_phase == "vlm_pretrain"
|
| 540 |
+
and self.knowledge_isolation):
|
| 541 |
+
raise ValueError(
|
| 542 |
+
"training_phase='vlm_pretrain' is incompatible with "
|
| 543 |
+
"knowledge_isolation=True. KI is a posttrain-only construct "
|
| 544 |
+
"(CE + Flow-Matching MSE simultaneously with information "
|
| 545 |
+
"isolation between them). vlm_pretrain is already CE-only "
|
| 546 |
+
"via ki_head β KI=True here builds unused trainable params "
|
| 547 |
+
"(state_vlm_proj) when state is discretized into the prompt."
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
# posttrain + KI + train_vlm_only freezes ki_head/DiT/projections β
|
| 551 |
+
# everything but the VLM. KI co-trains the VLM (CE through ki_head) against
|
| 552 |
+
# a *trained* ki_head, so a frozen random ki_head gives no useful signal.
|
| 553 |
+
# Dangerous even with --resume because the heads are silently frozen; force
|
| 554 |
+
# the operator to confront it.
|
| 555 |
+
if (self.training_phase == "posttrain"
|
| 556 |
+
and self.knowledge_isolation
|
| 557 |
+
and self.train_vlm_only):
|
| 558 |
+
raise ValueError(
|
| 559 |
+
"training_phase='posttrain' + knowledge_isolation=True + "
|
| 560 |
+
"train_vlm_only=True is unsafe: train_vlm_only freezes "
|
| 561 |
+
"ki_head/DiT/projections, but KI's CE branch needs the VLM "
|
| 562 |
+
"to learn against a *trained* ki_head classifier β a "
|
| 563 |
+
"randomly-initialised frozen ki_head produces no useful "
|
| 564 |
+
"signal. If you want VLM-only finetuning under KI, do it "
|
| 565 |
+
"from a checkpoint that already has a trained ki_head and "
|
| 566 |
+
"instead lower vlm_lr."
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
# Ο0.5 block-wise attention passes a custom 4D mask to the LM forward, but
|
| 570 |
+
# HF's flash_attention_2 honours only the padding part of attention_mask
|
| 571 |
+
# (FA2 uses cu_seqlens, not bias matrices). Setting both would silently
|
| 572 |
+
# fall back to FA2 causal+padding and ignore the block structure, so force
|
| 573 |
+
# SDPA.
|
| 574 |
+
if (self.pi05_block_attention_mask
|
| 575 |
+
and self.attn_implementation == "flash_attention_2"):
|
| 576 |
+
raise ValueError(
|
| 577 |
+
"pi05_block_attention_mask=True is incompatible with "
|
| 578 |
+
"attn_implementation='flash_attention_2'. FA2 only honours "
|
| 579 |
+
"padding portions of attention_mask and silently ignores "
|
| 580 |
+
"arbitrary 4D attention patterns, so the Ο0.5 block-wise "
|
| 581 |
+
"mask would have no effect on attention. Switch to "
|
| 582 |
+
"attn_implementation='sdpa' (slight perf cost) to get "
|
| 583 |
+
"paper-faithful Ο0.5 prefix-bidirectional attention."
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
# KI + layerwise VLM features is unsupported: the KI posttrain branch reads
|
| 587 |
+
# the LM output as a single Tensor and slices/detaches the prefix portion,
|
| 588 |
+
# while layerwise returns a List[Tensor] (one per cross-attn block) that
|
| 589 |
+
# this code would misinterpret. Refuse at config time.
|
| 590 |
+
if (self.knowledge_isolation
|
| 591 |
+
and self.dit_layerwise_vlm_features):
|
| 592 |
+
raise ValueError(
|
| 593 |
+
"knowledge_isolation=True is incompatible with "
|
| 594 |
+
"dit_layerwise_vlm_features=True. The KI posttrain branch "
|
| 595 |
+
"reads a single-Tensor last hidden state (and slices its "
|
| 596 |
+
"prefix portion before detaching), while layerwise expects "
|
| 597 |
+
"a List[Tensor] of per-block VLM hiddens. Pick exactly "
|
| 598 |
+
"one. (If you need both in the future, the KI branch's "
|
| 599 |
+
"prefix-slice + detach logic has to be extended to handle "
|
| 600 |
+
"the per-layer list explicitly.)"
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
def validate_features(self) -> None:
|
| 604 |
+
for i in range(self.empty_cameras):
|
| 605 |
+
key = f"{OBS_IMAGES}.empty_camera_{i}"
|
| 606 |
+
empty_camera = PolicyFeature(
|
| 607 |
+
type=FeatureType.VISUAL,
|
| 608 |
+
shape=(3, *self.image_resolution),
|
| 609 |
+
)
|
| 610 |
+
self.input_features[key] = empty_camera
|
| 611 |
+
|
| 612 |
+
if "observation.state" not in self.input_features:
|
| 613 |
+
state_feature = PolicyFeature(
|
| 614 |
+
type=FeatureType.STATE,
|
| 615 |
+
shape=(self.max_state_dim,),
|
| 616 |
+
)
|
| 617 |
+
self.input_features["observation.state"] = state_feature
|
| 618 |
+
|
| 619 |
+
if "action" not in self.output_features:
|
| 620 |
+
action_feature = PolicyFeature(
|
| 621 |
+
type=FeatureType.ACTION,
|
| 622 |
+
shape=(self.max_action_dim,),
|
| 623 |
+
)
|
| 624 |
+
self.output_features["action"] = action_feature
|
| 625 |
+
|
| 626 |
+
def get_optimizer_preset(self) -> LabVLAAdamWConfig:
|
| 627 |
+
return LabVLAAdamWConfig(
|
| 628 |
+
lr=self.optimizer_lr,
|
| 629 |
+
betas=self.optimizer_betas,
|
| 630 |
+
eps=self.optimizer_eps,
|
| 631 |
+
weight_decay=self.optimizer_weight_decay,
|
| 632 |
+
grad_clip_norm=self.optimizer_grad_clip_norm,
|
| 633 |
+
vlm_lr=self.optimizer_vlm_lr,
|
| 634 |
+
dit_lr=self.optimizer_dit_lr,
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
def get_scheduler_preset(self):
|
| 638 |
+
# train.py builds its own LambdaLR scheduler inline, so this is not used.
|
| 639 |
+
# Kept to satisfy PreTrainedConfig abstract method requirement.
|
| 640 |
+
return None
|
| 641 |
+
|
| 642 |
+
@property
|
| 643 |
+
def observation_delta_indices(self) -> None:
|
| 644 |
+
return None
|
| 645 |
+
|
| 646 |
+
@property
|
| 647 |
+
def action_delta_indices(self) -> list:
|
| 648 |
+
return list(range(self.chunk_size))
|
| 649 |
+
|
| 650 |
+
@property
|
| 651 |
+
def reward_delta_indices(self) -> None:
|
| 652 |
+
return None
|
| 653 |
+
|
| 654 |
+
@property
|
| 655 |
+
def image_delta_indices(self) -> list | None:
|
| 656 |
+
return None
|
src/policies/LabVLA/dit_action_head.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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uses cross-attention to VLM features
|
| 4 |
+
with AdaLayerNorm timestep conditioning for flow matching action generation.
|
| 5 |
+
|
| 6 |
+
Architecture: TimestepEncoder + N x BasicTransformerBlock(CrossAttn + FFN) + output projection
|
| 7 |
+
~268M params with default config (18 layers, hidden=1024, 8 heads)
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from typing import Optional
|
| 11 |
+
from functools import partial
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from torch.utils.checkpoint import checkpoint as torch_checkpoint
|
| 16 |
+
from diffusers.models.attention import Attention, FeedForward
|
| 17 |
+
from diffusers.models.embeddings import (
|
| 18 |
+
SinusoidalPositionalEmbedding,
|
| 19 |
+
TimestepEmbedding,
|
| 20 |
+
Timesteps,
|
| 21 |
+
)
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TimestepEncoder(nn.Module):
|
| 26 |
+
"""Encode scalar timestep to embedding vector via sinusoidal + MLP."""
|
| 27 |
+
|
| 28 |
+
def __init__(self, embedding_dim: int):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.time_proj = Timesteps(
|
| 31 |
+
num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=1
|
| 32 |
+
)
|
| 33 |
+
self.timestep_embedder = TimestepEmbedding(
|
| 34 |
+
in_channels=256, time_embed_dim=embedding_dim
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
def forward(self, timesteps: torch.Tensor) -> torch.Tensor:
|
| 38 |
+
dtype = next(self.parameters()).dtype
|
| 39 |
+
timesteps_proj = self.time_proj(timesteps).to(dtype)
|
| 40 |
+
return self.timestep_embedder(timesteps_proj)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class AdaLayerNorm(nn.Module):
|
| 44 |
+
"""Adaptive Layer Normalization conditioned on timestep embedding.
|
| 45 |
+
|
| 46 |
+
output = LayerNorm(x) * (1 + scale) + shift
|
| 47 |
+
where (scale, shift) = Linear(SiLU(temb))
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
embedding_dim: int,
|
| 53 |
+
norm_elementwise_affine: bool = False,
|
| 54 |
+
norm_eps: float = 1e-5,
|
| 55 |
+
):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.silu = nn.SiLU()
|
| 58 |
+
self.linear = nn.Linear(embedding_dim, embedding_dim * 2)
|
| 59 |
+
self.norm = nn.LayerNorm(embedding_dim, norm_eps, norm_elementwise_affine)
|
| 60 |
+
|
| 61 |
+
def forward(self, x: torch.Tensor, temb: torch.Tensor) -> torch.Tensor:
|
| 62 |
+
temb = self.linear(self.silu(temb))
|
| 63 |
+
scale, shift = temb.chunk(2, dim=-1)
|
| 64 |
+
return self.norm(x) * (1 + scale[:, None]) + shift[:, None]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class BasicTransformerBlock(nn.Module):
|
| 68 |
+
"""Single DiT transformer block with cross-attention and timestep conditioning.
|
| 69 |
+
|
| 70 |
+
Structure:
|
| 71 |
+
1. AdaLayerNorm(x, temb) -> CrossAttention(query=x, kv=encoder_hidden_states) -> residual
|
| 72 |
+
2. LayerNorm -> FeedForward (GEGLU) -> residual
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
dim: int,
|
| 78 |
+
num_attention_heads: int,
|
| 79 |
+
attention_head_dim: int,
|
| 80 |
+
dropout: float = 0.0,
|
| 81 |
+
cross_attention_dim: Optional[int] = None,
|
| 82 |
+
activation_fn: str = "geglu",
|
| 83 |
+
attention_bias: bool = False,
|
| 84 |
+
norm_elementwise_affine: bool = False,
|
| 85 |
+
norm_eps: float = 1e-5,
|
| 86 |
+
positional_embeddings: Optional[str] = None,
|
| 87 |
+
num_positional_embeddings: Optional[int] = None,
|
| 88 |
+
):
|
| 89 |
+
super().__init__()
|
| 90 |
+
# 1. AdaLayerNorm + Cross-Attention
|
| 91 |
+
self.norm1 = AdaLayerNorm(dim, norm_elementwise_affine, norm_eps)
|
| 92 |
+
|
| 93 |
+
if positional_embeddings == "sinusoidal":
|
| 94 |
+
self.pos_embed = SinusoidalPositionalEmbedding(
|
| 95 |
+
dim, max_seq_length=num_positional_embeddings
|
| 96 |
+
)
|
| 97 |
+
else:
|
| 98 |
+
self.pos_embed = None
|
| 99 |
+
|
| 100 |
+
self.attn1 = Attention(
|
| 101 |
+
query_dim=dim,
|
| 102 |
+
heads=num_attention_heads,
|
| 103 |
+
dim_head=attention_head_dim,
|
| 104 |
+
dropout=dropout,
|
| 105 |
+
bias=attention_bias,
|
| 106 |
+
cross_attention_dim=cross_attention_dim,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# 2. LayerNorm + FeedForward
|
| 110 |
+
self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
|
| 111 |
+
self.ff = FeedForward(
|
| 112 |
+
dim,
|
| 113 |
+
dropout=dropout,
|
| 114 |
+
activation_fn=activation_fn,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def forward(
|
| 118 |
+
self,
|
| 119 |
+
hidden_states: torch.Tensor,
|
| 120 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 121 |
+
temb: Optional[torch.Tensor] = None,
|
| 122 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 123 |
+
) -> torch.Tensor:
|
| 124 |
+
# Cross-attention with timestep conditioning.
|
| 125 |
+
# Forward `encoder_attention_mask` to the diffusers Attention so padded
|
| 126 |
+
# text tokens / masked-out camera slots in the VLM prefix don't contribute
|
| 127 |
+
# to action-token cross-attention. `Attention.forward(attention_mask=...)`
|
| 128 |
+
# accepts shape (B, S_kv) with 1=keep / 0=mask and converts internally,
|
| 129 |
+
# keeping this compatible with both SDPA and flash backends.
|
| 130 |
+
norm_hidden_states = self.norm1(hidden_states, temb)
|
| 131 |
+
if self.pos_embed is not None:
|
| 132 |
+
norm_hidden_states = self.pos_embed(norm_hidden_states)
|
| 133 |
+
|
| 134 |
+
attn_output = self.attn1(
|
| 135 |
+
norm_hidden_states,
|
| 136 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 137 |
+
attention_mask=encoder_attention_mask,
|
| 138 |
+
)
|
| 139 |
+
hidden_states = attn_output + hidden_states
|
| 140 |
+
|
| 141 |
+
if hidden_states.ndim == 4:
|
| 142 |
+
hidden_states = hidden_states.squeeze(1)
|
| 143 |
+
|
| 144 |
+
# Feed-forward
|
| 145 |
+
norm_hidden_states = self.norm3(hidden_states)
|
| 146 |
+
ff_output = self.ff(norm_hidden_states)
|
| 147 |
+
hidden_states = ff_output + hidden_states
|
| 148 |
+
|
| 149 |
+
if hidden_states.ndim == 4:
|
| 150 |
+
hidden_states = hidden_states.squeeze(1)
|
| 151 |
+
|
| 152 |
+
return hidden_states
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class DiTActionHead(nn.Module):
|
| 156 |
+
"""DiT-based action head for flow matching action generation.
|
| 157 |
+
|
| 158 |
+
Replaces the Qwen3 Transformer action expert (~760M) with a lightweight
|
| 159 |
+
DiT (~268M). VLM features are used as encoder_hidden_states for
|
| 160 |
+
cross-attention conditioning.
|
| 161 |
+
|
| 162 |
+
Spirit-v1.5 interleave: when ``interleave_self_attention=True`` (default),
|
| 163 |
+
odd-indexed blocks are *self-attention only* (no encoder KV) so query tokens
|
| 164 |
+
(state + action) mix among themselves before the next cross-attention layer
|
| 165 |
+
reads VLM features. This mirrors Spirit-v1.5
|
| 166 |
+
(``use_self_attn = idx % 2 == 1 and interleave_self_attention``) and is the
|
| 167 |
+
*only* path by which the state token (prepended to hidden_states by
|
| 168 |
+
``_embed_suffix``) influences action tokens before the trailing slice in
|
| 169 |
+
``_denoise_step``. Without it, stateβaction gradient is dead (the original
|
| 170 |
+
bug) and actionβaction interactions are absent (suspected cause of a
|
| 171 |
+
mid-training regression on TransportBeaker).
|
| 172 |
+
|
| 173 |
+
Config defaults (matching Spirit-v1.5):
|
| 174 |
+
num_attention_heads=8, attention_head_dim=128, num_layers=18
|
| 175 |
+
inner_dim = 8 * 128 = 1024
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
def __init__(
|
| 179 |
+
self,
|
| 180 |
+
num_attention_heads: int = 8,
|
| 181 |
+
attention_head_dim: int = 128,
|
| 182 |
+
num_layers: int = 18,
|
| 183 |
+
dropout: float = 0.0,
|
| 184 |
+
attention_bias: bool = True,
|
| 185 |
+
activation_fn: str = "gelu-approximate",
|
| 186 |
+
norm_elementwise_affine: bool = False,
|
| 187 |
+
norm_eps: float = 1e-5,
|
| 188 |
+
positional_embeddings: Optional[str] = "sinusoidal",
|
| 189 |
+
max_num_positional_embeddings: int = 512,
|
| 190 |
+
cross_attention_dim: Optional[int] = None,
|
| 191 |
+
interleave_self_attention: bool = True,
|
| 192 |
+
):
|
| 193 |
+
super().__init__()
|
| 194 |
+
self.inner_dim = num_attention_heads * attention_head_dim
|
| 195 |
+
self.num_layers = num_layers
|
| 196 |
+
self.interleave_self_attention = bool(interleave_self_attention)
|
| 197 |
+
self.gradient_checkpointing = False
|
| 198 |
+
# Store dropout so forward() can decide whether to preserve RNG state
|
| 199 |
+
# across gradient checkpointing: with dit_dropout > 0 and
|
| 200 |
+
# preserve_rng_state=False the recompute pass would use a different
|
| 201 |
+
# dropout mask than the forward pass, producing wrong gradients.
|
| 202 |
+
self._dropout = float(dropout)
|
| 203 |
+
|
| 204 |
+
# Timestep encoder
|
| 205 |
+
self.timestep_encoder = TimestepEncoder(embedding_dim=self.inner_dim)
|
| 206 |
+
|
| 207 |
+
# Transformer blocks. Per Spirit, odd-indexed blocks are self-attention
|
| 208 |
+
# when interleave is on (constructed with ``cross_attention_dim=None``
|
| 209 |
+
# so diffusers' ``Attention`` runs Q/K/V over ``hidden_states``).
|
| 210 |
+
blocks = []
|
| 211 |
+
for idx in range(num_layers):
|
| 212 |
+
use_self_attn = bool(self.interleave_self_attention and (idx % 2 == 1))
|
| 213 |
+
block_cross_dim = None if use_self_attn else cross_attention_dim
|
| 214 |
+
blocks.append(
|
| 215 |
+
BasicTransformerBlock(
|
| 216 |
+
dim=self.inner_dim,
|
| 217 |
+
num_attention_heads=num_attention_heads,
|
| 218 |
+
attention_head_dim=attention_head_dim,
|
| 219 |
+
dropout=dropout,
|
| 220 |
+
cross_attention_dim=block_cross_dim,
|
| 221 |
+
activation_fn=activation_fn,
|
| 222 |
+
attention_bias=attention_bias,
|
| 223 |
+
norm_elementwise_affine=norm_elementwise_affine,
|
| 224 |
+
norm_eps=norm_eps,
|
| 225 |
+
positional_embeddings=positional_embeddings,
|
| 226 |
+
num_positional_embeddings=max_num_positional_embeddings,
|
| 227 |
+
)
|
| 228 |
+
)
|
| 229 |
+
self.transformer_blocks = nn.ModuleList(blocks)
|
| 230 |
+
# Cache per-block self-attn-ness so forward doesn't re-check each step.
|
| 231 |
+
self._block_is_self_attn = [
|
| 232 |
+
bool(self.interleave_self_attention and (i % 2 == 1)) for i in range(num_layers)
|
| 233 |
+
]
|
| 234 |
+
# Cache cross-attn block count for layerwise VLM-features routing
|
| 235 |
+
# (used by `LabVLAModel._project_vlm_for_dit` to slice the matching
|
| 236 |
+
# number of VLM hidden states from the last-N).
|
| 237 |
+
self._num_cross_attn_blocks = sum(1 for is_self in self._block_is_self_attn if not is_self)
|
| 238 |
+
|
| 239 |
+
# Output: AdaLayerNorm-style scale/shift + projection
|
| 240 |
+
self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
|
| 241 |
+
self.proj_out_1 = nn.Linear(self.inner_dim, 2 * self.inner_dim)
|
| 242 |
+
|
| 243 |
+
def forward(
|
| 244 |
+
self,
|
| 245 |
+
hidden_states: torch.Tensor, # (B, T_q, inner_dim) β state+action suffix
|
| 246 |
+
encoder_hidden_states, # (B, S, D) Tensor OR List[Tensor] (layerwise)
|
| 247 |
+
timestep: torch.Tensor, # (B,) β flow matching timestep
|
| 248 |
+
encoder_attention_mask: Optional[torch.Tensor] = None, # (B, S) β 1=keep, 0=pad
|
| 249 |
+
) -> torch.Tensor:
|
| 250 |
+
"""
|
| 251 |
+
`encoder_attention_mask` (B, S) β 1 for valid VLM tokens, 0 for padding
|
| 252 |
+
(text padding, masked-out camera slots). When None, cross-attention attends
|
| 253 |
+
to all S positions. Diffusers Attention takes the mask as `attention_mask`
|
| 254 |
+
with the same convention.
|
| 255 |
+
|
| 256 |
+
Layerwise VLM features: ``encoder_hidden_states`` may be a
|
| 257 |
+
Python list of length ``self._num_cross_attn_blocks``. When it is,
|
| 258 |
+
cross-attn block i consumes ``encoder_hidden_states[i]`` (mapped in
|
| 259 |
+
construction order β i.e. shallowβdeep across cross-attn blocks); the
|
| 260 |
+
same VLM-position attention mask is reused for every layer (VLM
|
| 261 |
+
padding/camera mask is shared across LM depths). Self-attn blocks
|
| 262 |
+
always receive ``encoder_hidden_states=None`` regardless of list/Tensor.
|
| 263 |
+
|
| 264 |
+
Returns:
|
| 265 |
+
hidden_states: (B, T, inner_dim) β denoised action embeddings
|
| 266 |
+
"""
|
| 267 |
+
temb = self.timestep_encoder(timestep)
|
| 268 |
+
|
| 269 |
+
hidden_states = hidden_states.contiguous()
|
| 270 |
+
layerwise = isinstance(encoder_hidden_states, (list, tuple))
|
| 271 |
+
if layerwise:
|
| 272 |
+
if len(encoder_hidden_states) != self._num_cross_attn_blocks:
|
| 273 |
+
raise ValueError(
|
| 274 |
+
f"Layerwise encoder_hidden_states has length "
|
| 275 |
+
f"{len(encoder_hidden_states)} but DiT has "
|
| 276 |
+
f"{self._num_cross_attn_blocks} cross-attn blocks."
|
| 277 |
+
)
|
| 278 |
+
encoder_hidden_states = [e.contiguous() for e in encoder_hidden_states]
|
| 279 |
+
else:
|
| 280 |
+
encoder_hidden_states = encoder_hidden_states.contiguous()
|
| 281 |
+
if encoder_attention_mask is not None:
|
| 282 |
+
# Diffusers Attention forwards `attention_mask` to F.scaled_dot_product_attention,
|
| 283 |
+
# which only accepts `bool` or `float` matching query dtype. The VLM-side mask
|
| 284 |
+
# is typically `torch.long` (1=keep, 0=pad), so convert to bool here once and
|
| 285 |
+
# let downstream broadcasting handle the (B, S) β (B, n_heads, T_q, S) reshape.
|
| 286 |
+
if encoder_attention_mask.dtype != torch.bool:
|
| 287 |
+
encoder_attention_mask = encoder_attention_mask.to(torch.bool)
|
| 288 |
+
encoder_attention_mask = encoder_attention_mask.contiguous()
|
| 289 |
+
|
| 290 |
+
# When dit_dropout > 0 the gradient-checkpointing recompute MUST use the
|
| 291 |
+
# same dropout mask as the forward pass: preserve_rng_state=True restores
|
| 292 |
+
# torch's CPU+GPU RNG so Bernoulli draws stay bit-identical, whereas False
|
| 293 |
+
# silently gives wrong gradients. dropout=0 keeps the cheaper False path.
|
| 294 |
+
_preserve_rng = self._dropout > 0.0
|
| 295 |
+
cross_attn_counter = 0
|
| 296 |
+
for idx, block in enumerate(self.transformer_blocks):
|
| 297 |
+
# Spirit interleave: self-attn blocks must receive
|
| 298 |
+
# encoder_hidden_states=None (so diffusers' Attention computes
|
| 299 |
+
# Q/K/V from hidden_states) and a matching encoder_attention_mask=None.
|
| 300 |
+
# Cross-attn blocks pass both through unchanged.
|
| 301 |
+
if self._block_is_self_attn[idx]:
|
| 302 |
+
block_encoder_states = None
|
| 303 |
+
block_encoder_mask = None
|
| 304 |
+
else:
|
| 305 |
+
if layerwise:
|
| 306 |
+
block_encoder_states = encoder_hidden_states[cross_attn_counter]
|
| 307 |
+
else:
|
| 308 |
+
block_encoder_states = encoder_hidden_states
|
| 309 |
+
block_encoder_mask = encoder_attention_mask
|
| 310 |
+
cross_attn_counter += 1
|
| 311 |
+
|
| 312 |
+
if self.gradient_checkpointing and self.training:
|
| 313 |
+
# Pass kwargs to block so adding future params to
|
| 314 |
+
# BasicTransformerBlock.forward doesn't silently shift positions.
|
| 315 |
+
hidden_states = torch_checkpoint(
|
| 316 |
+
block,
|
| 317 |
+
hidden_states,
|
| 318 |
+
encoder_hidden_states=block_encoder_states,
|
| 319 |
+
temb=temb,
|
| 320 |
+
encoder_attention_mask=block_encoder_mask,
|
| 321 |
+
use_reentrant=False,
|
| 322 |
+
preserve_rng_state=_preserve_rng,
|
| 323 |
+
)
|
| 324 |
+
else:
|
| 325 |
+
hidden_states = block(
|
| 326 |
+
hidden_states,
|
| 327 |
+
encoder_hidden_states=block_encoder_states,
|
| 328 |
+
temb=temb,
|
| 329 |
+
encoder_attention_mask=block_encoder_mask,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
# Output shift/scale conditioning. Keep this order for compatibility
|
| 333 |
+
# with existing LabVLA checkpoints: their proj_out_1 weights were learned
|
| 334 |
+
# with the first half as shift and the second half as scale.
|
| 335 |
+
shift, scale = self.proj_out_1(F.silu(temb)).chunk(2, dim=-1)
|
| 336 |
+
hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
|
| 337 |
+
|
| 338 |
+
return hidden_states
|
src/policies/LabVLA/ki/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util as _importlib_util
|
| 2 |
+
|
| 3 |
+
from .fast_tokenizer import FastTokenizerWrapper
|
| 4 |
+
|
| 5 |
+
__all__ = ["FastTokenizerWrapper"]
|
| 6 |
+
|
| 7 |
+
# Optional DiscreteActionHead import. Check module presence first so a real
|
| 8 |
+
# ImportError *inside* an existing ki_head.py (bad import, renamed symbol,
|
| 9 |
+
# broken dependency) propagates instead of being swallowed as "module absent",
|
| 10 |
+
# which would silently drop DiscreteActionHead and mask a main-path failure.
|
| 11 |
+
if _importlib_util.find_spec(".ki_head", __name__) is not None:
|
| 12 |
+
from .ki_head import DiscreteActionHead
|
| 13 |
+
__all__.append("DiscreteActionHead")
|
src/policies/LabVLA/ki/fast_tokenizer.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Back-compat shim.
|
| 2 |
+
|
| 3 |
+
``FastTokenizerWrapper`` is a data-encoding utility (DCT+BPE action
|
| 4 |
+
tokenization) consumed by the FAST transform; it now lives in
|
| 5 |
+
``transforms.fast_tokenizer``. Import-only re-export; the class is defined
|
| 6 |
+
exactly once in its new home.
|
| 7 |
+
"""
|
| 8 |
+
from src.transforms.fast_tokenizer import FastTokenizerWrapper # noqa: F401
|
| 9 |
+
|
| 10 |
+
__all__ = ["FastTokenizerWrapper"]
|
src/policies/LabVLA/ki/ki_head.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Discrete Action Head for Knowledge Isolation / Ο0.5 VLM pretrain.
|
| 2 |
+
|
| 3 |
+
Responsibilities:
|
| 4 |
+
- Embed FAST discrete action tokens into VLM hidden dim (for feeding into VLM forward)
|
| 5 |
+
- Project VLM last hidden state back to FAST vocab (for next-token CE loss)
|
| 6 |
+
- Compute masked CE loss over FAST action token positions
|
| 7 |
+
|
| 8 |
+
Design: fully decoupled from VLM/DiT architecture. Takes only the VLM hidden size
|
| 9 |
+
as a construction param. Used in BOTH vlm_pretrain and posttrain+KI modes.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from torch import nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class DiscreteActionHead(nn.Module):
|
| 19 |
+
"""FAST token embedding (vocab -> hidden) + classifier (hidden -> vocab)."""
|
| 20 |
+
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
vocab_size: int,
|
| 24 |
+
hidden_size: int,
|
| 25 |
+
dtype: torch.dtype = torch.bfloat16,
|
| 26 |
+
):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.vocab_size = int(vocab_size)
|
| 29 |
+
self.hidden_size = int(hidden_size)
|
| 30 |
+
|
| 31 |
+
# Embedding stays in bf16 (matches VLM input-embedding scale; quantization
|
| 32 |
+
# of Β±0.02-std weights is harmless).
|
| 33 |
+
self.embedding = nn.Embedding(self.vocab_size, self.hidden_size)
|
| 34 |
+
# Classifier kept in fp32 for logits precision. bf16's 7-bit mantissa
|
| 35 |
+
# loses ~0.07 CE nats to quantization in a softmax over 2048 classes at
|
| 36 |
+
# logits ~O(20). Cost of fp32: ~20 MB params + an fp32
|
| 37 |
+
# (BΒ·L, 2560)Β·(2560, 2048) matmul per step β negligible vs VLM forward.
|
| 38 |
+
self.classifier = nn.Linear(self.hidden_size, self.vocab_size, bias=False)
|
| 39 |
+
|
| 40 |
+
nn.init.normal_(self.embedding.weight, mean=0.0, std=0.02)
|
| 41 |
+
nn.init.kaiming_uniform_(self.classifier.weight, a=5 ** 0.5)
|
| 42 |
+
|
| 43 |
+
# Split-dtype: embedding bf16 to match VLM; classifier fp32 for precise CE.
|
| 44 |
+
self.embedding.to(dtype=dtype)
|
| 45 |
+
self.classifier.to(dtype=torch.float32)
|
| 46 |
+
|
| 47 |
+
def assert_classifier_fp32_invariant(self) -> None:
|
| 48 |
+
"""Raise AssertionError if classifier weight is not fp32.
|
| 49 |
+
|
| 50 |
+
CE precision (Ο0.5 "no precision tradeoffs" red line) requires the
|
| 51 |
+
classifier weight to be fp32. Three redundant defenses keep CE
|
| 52 |
+
numerically identical regardless of DeepSpeed ZeRO master-shard behavior:
|
| 53 |
+
|
| 54 |
+
1. `__init__` casts classifier to fp32 (this file, ctor).
|
| 55 |
+
2. `scripts/train.py` re-casts classifier to fp32 AFTER
|
| 56 |
+
`accelerator.prepare` because DS bfloat16() recasts everything.
|
| 57 |
+
3. `compute_ce_loss` defensively casts the matmul operands to fp32
|
| 58 |
+
on every call.
|
| 59 |
+
|
| 60 |
+
If defenses 1 + 2 are removed AND defense 3 is removed, classifier
|
| 61 |
+
silently downgrades to bf16 -> CE quantization. Call this assert on
|
| 62 |
+
a known-trained (>= step 1) model to detect regression. Cheap dtype
|
| 63 |
+
check (no allocation).
|
| 64 |
+
"""
|
| 65 |
+
assert self.classifier.weight.dtype == torch.float32, (
|
| 66 |
+
f"ki_head.classifier.weight.dtype={self.classifier.weight.dtype} "
|
| 67 |
+
f"(expected torch.float32). The fp32 invariant is set in "
|
| 68 |
+
f"DiscreteActionHead.__init__ and re-asserted in scripts/train.py "
|
| 69 |
+
f"after accelerator.prepare (DeepSpeed bfloat16() recasts every "
|
| 70 |
+
f"param). If you removed either, CE precision regresses (red-team "
|
| 71 |
+
f"H5: bf16 quantization adds ~0.07 nat to CE loss over 2048 "
|
| 72 |
+
f"classes). Restore the cast or accept the precision loss."
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
def embed(self, tokens: torch.Tensor) -> torch.Tensor:
|
| 76 |
+
"""tokens: (B, L) int64 -> (B, L, hidden) same dtype as weights."""
|
| 77 |
+
return self.embedding(tokens)
|
| 78 |
+
|
| 79 |
+
def compute_ce_loss(
|
| 80 |
+
self,
|
| 81 |
+
hidden: torch.Tensor, # (B, L, hidden) β VLM output aligned with target_tokens
|
| 82 |
+
target_tokens: torch.Tensor, # (B, L) int64, ground truth FAST tokens
|
| 83 |
+
mask: torch.Tensor, # (B, L) bool, True = valid
|
| 84 |
+
) -> torch.Tensor:
|
| 85 |
+
"""Next-token CE loss, masked averaged to scalar.
|
| 86 |
+
|
| 87 |
+
Caller is responsible for the one-position shift (hidden[i] predicts
|
| 88 |
+
target_tokens[i]). This function just applies the classifier + masked CE.
|
| 89 |
+
|
| 90 |
+
DeepSpeed ZeRO-2's bf16 master shard can write classifier.weight back to
|
| 91 |
+
bf16 on optimizer.step() even after we re-cast to fp32 post-prepare. Run
|
| 92 |
+
the matmul in fp32 regardless of the stored weight dtype to keep CE
|
| 93 |
+
precision invariant; the classifier is tiny (~20MB) so the fp32 cast is
|
| 94 |
+
cheap and CE is numerically identical whether the weight is bf16 or fp32.
|
| 95 |
+
"""
|
| 96 |
+
w = self.classifier.weight
|
| 97 |
+
# Explicit `.to(torch.float32)` (not `.float()`) so the fp32-CE intent is
|
| 98 |
+
# obvious regardless of whatever dtype DeepSpeed's master shard last wrote.
|
| 99 |
+
logits = F.linear(hidden.to(torch.float32), w.to(torch.float32), None)
|
| 100 |
+
loss_flat = F.cross_entropy(
|
| 101 |
+
logits.view(-1, self.vocab_size),
|
| 102 |
+
target_tokens.view(-1).to(hidden.device).long(),
|
| 103 |
+
reduction="none",
|
| 104 |
+
)
|
| 105 |
+
mask_flat = mask.view(-1).to(loss_flat.device).float()
|
| 106 |
+
denom = mask_flat.sum().clamp(min=1.0)
|
| 107 |
+
return (loss_flat * mask_flat).sum() / denom
|
src/policies/LabVLA/modeling_labvla.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
src/policies/LabVLA/transform_labvla.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Back-compat shim.
|
| 2 |
+
|
| 3 |
+
``Qwen3_VLProcessorTransformFn`` / ``UnifyLabVLAInputsTransformFn`` are DATA
|
| 4 |
+
TRANSFORMS and now live in ``transforms.vlm_processor``. Import-only re-export:
|
| 5 |
+
the classes are defined (and draccus-registered) exactly once, in their new
|
| 6 |
+
home. Existing checkpoints/configs and any out-of-tree caller importing this
|
| 7 |
+
path keep working.
|
| 8 |
+
"""
|
| 9 |
+
from src.transforms.vlm_processor import ( # noqa: F401
|
| 10 |
+
Qwen3_VLProcessorTransformFn,
|
| 11 |
+
UnifyLabVLAInputsTransformFn,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
__all__ = ["Qwen3_VLProcessorTransformFn", "UnifyLabVLAInputsTransformFn"]
|
src/policies/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .LabVLA.configuration_labvla import LabVLAConfig as LabVLAConfig
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"LabVLAConfig",
|
| 19 |
+
]
|
src/policies/pretrained.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import abc
|
| 15 |
+
import builtins
|
| 16 |
+
import logging
|
| 17 |
+
import os
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from tempfile import TemporaryDirectory
|
| 20 |
+
from typing import TypedDict, TypeVar
|
| 21 |
+
|
| 22 |
+
import packaging
|
| 23 |
+
import safetensors
|
| 24 |
+
from huggingface_hub import HfApi, ModelCard, ModelCardData, hf_hub_download
|
| 25 |
+
from huggingface_hub.constants import SAFETENSORS_SINGLE_FILE
|
| 26 |
+
from huggingface_hub.errors import HfHubHTTPError
|
| 27 |
+
from safetensors.torch import load_model as load_model_as_safetensor, save_model as save_model_as_safetensor
|
| 28 |
+
from torch import Tensor, nn
|
| 29 |
+
from typing_extensions import Unpack
|
| 30 |
+
|
| 31 |
+
from src.config.policies import PreTrainedConfig
|
| 32 |
+
from src.policies.utils import log_model_loading_keys
|
| 33 |
+
from src.utils.hub import HubMixin
|
| 34 |
+
|
| 35 |
+
T = TypeVar("T", bound="PreTrainedPolicy")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class ActionSelectKwargs(TypedDict, total=False):
|
| 39 |
+
noise: Tensor | None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class PreTrainedPolicy(nn.Module, HubMixin, abc.ABC):
|
| 43 |
+
"""
|
| 44 |
+
Base class for policy models.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
config_class: None
|
| 48 |
+
name: None
|
| 49 |
+
|
| 50 |
+
def __init__(self, config: PreTrainedConfig, *inputs, **kwargs):
|
| 51 |
+
super().__init__()
|
| 52 |
+
if not isinstance(config, PreTrainedConfig):
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"Parameter config in `{self.__class__.__name__}(config)` should be an instance of class "
|
| 55 |
+
"`PreTrainedConfig`. To create a model from a pretrained model use "
|
| 56 |
+
f"`model = {self.__class__.__name__}.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
| 57 |
+
)
|
| 58 |
+
self.config = config
|
| 59 |
+
|
| 60 |
+
def __init_subclass__(cls, **kwargs):
|
| 61 |
+
super().__init_subclass__(**kwargs)
|
| 62 |
+
if not getattr(cls, "config_class", None):
|
| 63 |
+
raise TypeError(f"Class {cls.__name__} must define 'config_class'")
|
| 64 |
+
if not getattr(cls, "name", None):
|
| 65 |
+
raise TypeError(f"Class {cls.__name__} must define 'name'")
|
| 66 |
+
|
| 67 |
+
def _save_pretrained(self, save_directory: Path) -> None:
|
| 68 |
+
self.config._save_pretrained(save_directory)
|
| 69 |
+
model_to_save = self.module if hasattr(self, "module") else self
|
| 70 |
+
save_model_as_safetensor(model_to_save, str(save_directory / SAFETENSORS_SINGLE_FILE))
|
| 71 |
+
|
| 72 |
+
@classmethod
|
| 73 |
+
def from_pretrained(
|
| 74 |
+
cls: builtins.type[T],
|
| 75 |
+
pretrained_name_or_path: str | Path,
|
| 76 |
+
*,
|
| 77 |
+
config: PreTrainedConfig | None = None,
|
| 78 |
+
force_download: bool = False,
|
| 79 |
+
resume_download: bool | None = None,
|
| 80 |
+
proxies: dict | None = None,
|
| 81 |
+
token: str | bool | None = None,
|
| 82 |
+
cache_dir: str | Path | None = None,
|
| 83 |
+
local_files_only: bool = False,
|
| 84 |
+
revision: str | None = None,
|
| 85 |
+
strict: bool | None = None,
|
| 86 |
+
**kwargs,
|
| 87 |
+
) -> T:
|
| 88 |
+
"""
|
| 89 |
+
The policy is set in evaluation mode by default using `policy.eval()` (dropout modules are
|
| 90 |
+
deactivated). To train it, you should first set it back in training mode with `policy.train()`.
|
| 91 |
+
|
| 92 |
+
`strict` defaults to ``None``. With the default, a COMPLETE
|
| 93 |
+
local-directory checkpoint is loaded fail-loud on MISSING keys (any KEY
|
| 94 |
+
module absent from the file raises), so a structurally-mismatched
|
| 95 |
+
checkpoint can't be silently loaded with random-initialised modules left
|
| 96 |
+
in place. Callers needing a partial load must opt in with ``strict=False``
|
| 97 |
+
(e.g. the deploy LABVLA_DEPLOY_ALLOW_PARTIAL_LOAD escape hatch);
|
| 98 |
+
``strict=True`` keeps full safetensors strict semantics (missing AND
|
| 99 |
+
unexpected keys raise).
|
| 100 |
+
"""
|
| 101 |
+
if config is None:
|
| 102 |
+
config = PreTrainedConfig.from_pretrained(
|
| 103 |
+
pretrained_name_or_path=pretrained_name_or_path,
|
| 104 |
+
force_download=force_download,
|
| 105 |
+
resume_download=resume_download,
|
| 106 |
+
proxies=proxies,
|
| 107 |
+
token=token,
|
| 108 |
+
cache_dir=cache_dir,
|
| 109 |
+
local_files_only=local_files_only,
|
| 110 |
+
revision=revision,
|
| 111 |
+
**kwargs,
|
| 112 |
+
)
|
| 113 |
+
# The config above is resolved via the *generic*
|
| 114 |
+
# PreTrainedConfig.from_pretrained, so a checkpoint from a different policy
|
| 115 |
+
# type still produces a config object. Reject it before constructing `cls`,
|
| 116 |
+
# otherwise we'd build the wrong policy and "successfully" partial-load
|
| 117 |
+
# mismatched weights. `config_class` may be unset on abstract bases β only
|
| 118 |
+
# enforce when the concrete policy declares one.
|
| 119 |
+
expected_config_cls = getattr(cls, "config_class", None)
|
| 120 |
+
if expected_config_cls is not None and not isinstance(config, expected_config_cls):
|
| 121 |
+
raise TypeError(
|
| 122 |
+
f"{cls.__name__}.from_pretrained got a config of type "
|
| 123 |
+
f"{type(config).__name__}, but {cls.__name__} requires "
|
| 124 |
+
f"{expected_config_cls.__name__}. The checkpoint at "
|
| 125 |
+
f"{pretrained_name_or_path!r} likely belongs to a different "
|
| 126 |
+
f"policy type."
|
| 127 |
+
)
|
| 128 |
+
model_id = str(pretrained_name_or_path)
|
| 129 |
+
instance = cls(config, **kwargs)
|
| 130 |
+
if os.path.isdir(model_id):
|
| 131 |
+
print("Loading weights from local directory")
|
| 132 |
+
model_file = os.path.join(model_id, SAFETENSORS_SINGLE_FILE)
|
| 133 |
+
# A local directory is a complete checkpoint β default to
|
| 134 |
+
# fail-loud-on-missing-keys when the caller did not specify `strict`.
|
| 135 |
+
local_strict = strict if strict is not None else "missing"
|
| 136 |
+
policy = cls._load_as_safetensor(instance, model_file, config.device, local_strict)
|
| 137 |
+
else:
|
| 138 |
+
# Hub download path: keep the historical lenient default (remote
|
| 139 |
+
# repos may legitimately ship partial weights); only enforce when a
|
| 140 |
+
# caller explicitly requested strict loading.
|
| 141 |
+
# The local default rejects missing keys; align the Hub default to
|
| 142 |
+
# match β callers wanting lenient remote loads pass strict=False.
|
| 143 |
+
hub_strict = bool(strict) if strict is not None else True
|
| 144 |
+
try:
|
| 145 |
+
model_file = hf_hub_download(
|
| 146 |
+
repo_id=model_id,
|
| 147 |
+
filename=SAFETENSORS_SINGLE_FILE,
|
| 148 |
+
revision=revision,
|
| 149 |
+
cache_dir=cache_dir,
|
| 150 |
+
force_download=force_download,
|
| 151 |
+
proxies=proxies,
|
| 152 |
+
resume_download=resume_download,
|
| 153 |
+
token=token,
|
| 154 |
+
local_files_only=local_files_only,
|
| 155 |
+
)
|
| 156 |
+
policy = cls._load_as_safetensor(instance, model_file, config.device, hub_strict)
|
| 157 |
+
except HfHubHTTPError as e:
|
| 158 |
+
raise FileNotFoundError(
|
| 159 |
+
f"{SAFETENSORS_SINGLE_FILE} not found on the HuggingFace Hub in {model_id}"
|
| 160 |
+
) from e
|
| 161 |
+
|
| 162 |
+
policy.to(config.device)
|
| 163 |
+
policy.eval()
|
| 164 |
+
return policy
|
| 165 |
+
|
| 166 |
+
@classmethod
|
| 167 |
+
def _load_as_safetensor(cls, model: T, model_file: str, map_location: str, strict) -> T:
|
| 168 |
+
# `strict` may be a bool OR the sentinel string "missing" (fail-loud on
|
| 169 |
+
# missing keys but tolerate benign *unexpected* keys, e.g. extra buffers).
|
| 170 |
+
# For "missing" mode, load non-strictly so safetensors returns the key
|
| 171 |
+
# diff, then raise if any KEY module is missing.
|
| 172 |
+
fail_on_missing_only = strict == "missing"
|
| 173 |
+
load_strict = False if fail_on_missing_only else bool(strict)
|
| 174 |
+
|
| 175 |
+
# Create base kwargs
|
| 176 |
+
kwargs = {"strict": load_strict}
|
| 177 |
+
|
| 178 |
+
# Add device parameter for newer versions that support it
|
| 179 |
+
if packaging.version.parse(safetensors.__version__) >= packaging.version.parse("0.4.3"):
|
| 180 |
+
kwargs["device"] = map_location
|
| 181 |
+
|
| 182 |
+
# Load the model with appropriate kwargs. Older LabVLA checkpoints saved
|
| 183 |
+
# both sides of Qwen's tied lm-head/input-embedding alias, while current
|
| 184 |
+
# model state_dicts expose only the canonical lm_head key. Preserve
|
| 185 |
+
# strict loading for all real mismatches, but tolerate that legacy alias.
|
| 186 |
+
allowed_unexpected = {"model.vlm.model.language_model.embed_tokens.weight"}
|
| 187 |
+
try:
|
| 188 |
+
missing_keys, unexpected_keys = load_model_as_safetensor(model, model_file, **kwargs)
|
| 189 |
+
except RuntimeError:
|
| 190 |
+
if not load_strict:
|
| 191 |
+
raise
|
| 192 |
+
relaxed_kwargs = dict(kwargs)
|
| 193 |
+
relaxed_kwargs["strict"] = False
|
| 194 |
+
missing_keys, unexpected_keys = load_model_as_safetensor(model, model_file, **relaxed_kwargs)
|
| 195 |
+
residual_missing = set(missing_keys)
|
| 196 |
+
residual_unexpected = set(unexpected_keys) - allowed_unexpected
|
| 197 |
+
if residual_missing or residual_unexpected:
|
| 198 |
+
raise
|
| 199 |
+
logging.warning(
|
| 200 |
+
"Strict safetensor load accepted legacy tied embedding alias: %s",
|
| 201 |
+
sorted(allowed_unexpected & set(unexpected_keys)),
|
| 202 |
+
)
|
| 203 |
+
log_model_loading_keys(missing_keys, unexpected_keys)
|
| 204 |
+
|
| 205 |
+
if fail_on_missing_only and missing_keys:
|
| 206 |
+
raise RuntimeError(
|
| 207 |
+
f"{cls.__name__}.from_pretrained: checkpoint {model_file} is "
|
| 208 |
+
f"missing {len(missing_keys)} key(s) required by the model; "
|
| 209 |
+
f"those modules would stay randomly-initialised. Refusing to "
|
| 210 |
+
f"load a partial checkpoint. Missing (up to 10 shown): "
|
| 211 |
+
f"{missing_keys[:10]}. If this partial load is intentional, "
|
| 212 |
+
f"pass strict=False explicitly."
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
# For older versions, manually move to device if needed
|
| 216 |
+
if "device" not in kwargs and map_location != "cpu":
|
| 217 |
+
logging.warning(
|
| 218 |
+
"Loading model weights on other devices than 'cpu' is not supported natively in your version of safetensors."
|
| 219 |
+
" This means that the model is loaded on 'cpu' first and then copied to the device."
|
| 220 |
+
" This leads to a slower loading time."
|
| 221 |
+
" Please update safetensors to version 0.4.3 or above for improved performance."
|
| 222 |
+
)
|
| 223 |
+
model.to(map_location)
|
| 224 |
+
return model
|
| 225 |
+
|
| 226 |
+
@abc.abstractmethod
|
| 227 |
+
def get_optim_params(self) -> dict:
|
| 228 |
+
"""
|
| 229 |
+
Returns the policy-specific parameters dict to be passed on to the optimizer.
|
| 230 |
+
"""
|
| 231 |
+
raise NotImplementedError
|
| 232 |
+
|
| 233 |
+
@abc.abstractmethod
|
| 234 |
+
def reset(self):
|
| 235 |
+
"""To be called whenever the environment is reset.
|
| 236 |
+
|
| 237 |
+
Does things like clearing caches.
|
| 238 |
+
"""
|
| 239 |
+
raise NotImplementedError
|
| 240 |
+
|
| 241 |
+
# TODO(aliberts, rcadene): split into 'forward' and 'compute_loss'?
|
| 242 |
+
@abc.abstractmethod
|
| 243 |
+
def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, dict | None]:
|
| 244 |
+
"""_summary_
|
| 245 |
+
|
| 246 |
+
Args:
|
| 247 |
+
batch (dict[str, Tensor]): _description_
|
| 248 |
+
|
| 249 |
+
Returns:
|
| 250 |
+
tuple[Tensor, dict | None]: The loss and potentially other information. Apart from the loss which
|
| 251 |
+
is a Tensor, all other items should be logging-friendly, native Python types.
|
| 252 |
+
"""
|
| 253 |
+
raise NotImplementedError
|
| 254 |
+
|
| 255 |
+
@abc.abstractmethod
|
| 256 |
+
def predict_action_chunk(self, batch: dict[str, Tensor], **kwargs: Unpack[ActionSelectKwargs]) -> Tensor:
|
| 257 |
+
"""Returns the action chunk (for action chunking policies) for a given observation, potentially in batch mode.
|
| 258 |
+
|
| 259 |
+
Child classes using action chunking should use this method within `select_action` to form the action chunk
|
| 260 |
+
cached for selection.
|
| 261 |
+
"""
|
| 262 |
+
raise NotImplementedError
|
| 263 |
+
|
| 264 |
+
@abc.abstractmethod
|
| 265 |
+
def select_action(self, batch: dict[str, Tensor], **kwargs: Unpack[ActionSelectKwargs]) -> Tensor:
|
| 266 |
+
"""Return one action to run in the environment (potentially in batch mode).
|
| 267 |
+
|
| 268 |
+
When the model uses a history of observations, or outputs a sequence of actions, this method deals
|
| 269 |
+
with caching.
|
| 270 |
+
"""
|
| 271 |
+
raise NotImplementedError
|
| 272 |
+
|
src/policies/utils.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import logging
|
| 18 |
+
from collections import deque
|
| 19 |
+
from typing import Any
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from src.config.policies import PreTrainedConfig
|
| 26 |
+
from src.config.types import FeatureType, PolicyFeature
|
| 27 |
+
from src.utils.constants import ACTION, OBS_STR
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def populate_queues(
|
| 31 |
+
queues: dict[str, deque], batch: dict[str, torch.Tensor], exclude_keys: list[str] | None = None
|
| 32 |
+
):
|
| 33 |
+
if exclude_keys is None:
|
| 34 |
+
exclude_keys = []
|
| 35 |
+
for key in batch:
|
| 36 |
+
# Ignore keys not in the queues already (leaving the responsibility to the caller to make sure the
|
| 37 |
+
# queues have the keys they want).
|
| 38 |
+
if key not in queues or key in exclude_keys:
|
| 39 |
+
continue
|
| 40 |
+
if len(queues[key]) != queues[key].maxlen:
|
| 41 |
+
# initialize by copying the first observation several times until the queue is full
|
| 42 |
+
while len(queues[key]) != queues[key].maxlen:
|
| 43 |
+
queues[key].append(batch[key])
|
| 44 |
+
else:
|
| 45 |
+
# add latest observation to the queue
|
| 46 |
+
queues[key].append(batch[key])
|
| 47 |
+
return queues
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_device_from_parameters(module: nn.Module) -> torch.device:
|
| 51 |
+
"""Get a module's device by checking one of its parameters.
|
| 52 |
+
|
| 53 |
+
Note: assumes that all parameters have the same device
|
| 54 |
+
"""
|
| 55 |
+
return next(iter(module.parameters())).device
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_dtype_from_parameters(module: nn.Module) -> torch.dtype:
|
| 59 |
+
"""Get a module's parameter dtype by checking one of its parameters.
|
| 60 |
+
|
| 61 |
+
Note: assumes that all parameters have the same dtype.
|
| 62 |
+
"""
|
| 63 |
+
return next(iter(module.parameters())).dtype
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_output_shape(module: nn.Module, input_shape: tuple) -> tuple:
|
| 67 |
+
"""
|
| 68 |
+
Calculates the output shape of a PyTorch module given an input shape.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
module (nn.Module): a PyTorch module
|
| 72 |
+
input_shape (tuple): A tuple representing the input shape, e.g., (batch_size, channels, height, width)
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
tuple: The output shape of the module.
|
| 76 |
+
"""
|
| 77 |
+
dummy_input = torch.zeros(size=input_shape)
|
| 78 |
+
with torch.inference_mode():
|
| 79 |
+
output = module(dummy_input)
|
| 80 |
+
return tuple(output.shape)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def log_model_loading_keys(missing_keys: list[str], unexpected_keys: list[str]) -> None:
|
| 84 |
+
"""Log missing and unexpected keys when loading a model.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
missing_keys (list[str]): Keys that were expected but not found.
|
| 88 |
+
unexpected_keys (list[str]): Keys that were found but not expected.
|
| 89 |
+
"""
|
| 90 |
+
if missing_keys:
|
| 91 |
+
logging.warning(f"Missing key(s) when loading model: {missing_keys}")
|
| 92 |
+
if unexpected_keys:
|
| 93 |
+
logging.warning(f"Unexpected key(s) when loading model: {unexpected_keys}")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def raise_feature_mismatch_error(
|
| 97 |
+
provided_features: set[str],
|
| 98 |
+
expected_features: set[str],
|
| 99 |
+
) -> None:
|
| 100 |
+
"""
|
| 101 |
+
Raises a standardized ValueError for feature mismatches between dataset/environment and policy config.
|
| 102 |
+
"""
|
| 103 |
+
missing = expected_features - provided_features
|
| 104 |
+
extra = provided_features - expected_features
|
| 105 |
+
# TODO (jadechoghari): provide a dynamic rename map suggestion to the user.
|
| 106 |
+
raise ValueError(
|
| 107 |
+
f"Feature mismatch between dataset/environment and policy config.\n"
|
| 108 |
+
f"- Missing features: {sorted(missing) if missing else 'None'}\n"
|
| 109 |
+
f"- Extra features: {sorted(extra) if extra else 'None'}\n\n"
|
| 110 |
+
f"Please ensure your dataset and policy use consistent feature names.\n"
|
| 111 |
+
f"If your dataset uses different observation keys (e.g., cameras named differently), "
|
| 112 |
+
f"use the `--rename_map` argument, for example:\n"
|
| 113 |
+
f' --rename_map=\'{{"observation.images.left": "observation.images.camera1", '
|
| 114 |
+
f'"observation.images.top": "observation.images.camera2"}}\''
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def validate_visual_features_consistency(
|
| 119 |
+
cfg: PreTrainedConfig,
|
| 120 |
+
features: dict[str, PolicyFeature],
|
| 121 |
+
) -> None:
|
| 122 |
+
"""
|
| 123 |
+
Validates visual feature consistency between a policy config and provided dataset/environment features.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
cfg (PreTrainedConfig): The model or policy configuration containing input_features and type.
|
| 127 |
+
features (Dict[str, PolicyFeature]): A mapping of feature names to PolicyFeature objects.
|
| 128 |
+
"""
|
| 129 |
+
expected_visuals = {k for k, v in cfg.input_features.items() if v.type == FeatureType.VISUAL}
|
| 130 |
+
provided_visuals = {k for k, v in features.items() if v.type == FeatureType.VISUAL}
|
| 131 |
+
if not provided_visuals.issubset(expected_visuals):
|
| 132 |
+
raise_feature_mismatch_error(provided_visuals, expected_visuals)
|
src/schema/__init__.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dataset schema discovery β single source of truth for dataset layout.
|
| 2 |
+
|
| 3 |
+
Replaces the fragile `robot_type` -> constants dict lookup with a two-tier
|
| 4 |
+
chain (explicit meta/labvla_manifest.json > info.json `names` auto-infer)
|
| 5 |
+
that produces a frozen `DatasetSchema` object consumed by all downstream code.
|
| 6 |
+
|
| 7 |
+
See doc/schema_manifest.md for the manifest format and when each tier kicks in.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from src.utils.constants import ACTION, OBS_IMAGES, OBS_STATE
|
| 11 |
+
|
| 12 |
+
from .dataset_schema import DatasetSchema
|
| 13 |
+
from .discovery import discover_schema
|
| 14 |
+
from .errors import (
|
| 15 |
+
SchemaDiscoveryError,
|
| 16 |
+
SchemaError,
|
| 17 |
+
SchemaSpecError,
|
| 18 |
+
SchemaValidationError,
|
| 19 |
+
)
|
| 20 |
+
from .registry import register, resolve, registered_names
|
| 21 |
+
|
| 22 |
+
# Blueprint: declarative authoring layer. New schemas should be written as
|
| 23 |
+
# SingleArmBlueprint(...).build() or MultiChannelBlueprint(...).build() β
|
| 24 |
+
# the compiler emits a DatasetSchema identical to hand-authored low-level
|
| 25 |
+
# form, but derives delta_mask / gripper_action_dims / arm_layout
|
| 26 |
+
# automatically from the high-level SingleArm spec.
|
| 27 |
+
from .annotation_loss import AnnotationLossSpec
|
| 28 |
+
from .arm_layout import ArmCount, ArmLayoutSpec
|
| 29 |
+
from .blueprint import (
|
| 30 |
+
AnnotationSpec,
|
| 31 |
+
MultiChannelBlueprint,
|
| 32 |
+
SingleArm,
|
| 33 |
+
SingleArmBlueprint,
|
| 34 |
+
StateActionChannel,
|
| 35 |
+
)
|
| 36 |
+
from .camera_mapping import (
|
| 37 |
+
expand_camera_mapping,
|
| 38 |
+
expand_camera_source,
|
| 39 |
+
expand_camera_target,
|
| 40 |
+
infer_image_mapping_from_info,
|
| 41 |
+
validate_camera_mapping,
|
| 42 |
+
)
|
| 43 |
+
from .merge_recipe import MergeRecipe, SourceArmLayout
|
| 44 |
+
from .validate import validate_arm_layout, validate_schema
|
| 45 |
+
|
| 46 |
+
__all__ = [
|
| 47 |
+
# Constants re-exported from utils.constants so `from schema import
|
| 48 |
+
# OBS_IMAGES` works without pulling the whole utils package.
|
| 49 |
+
"ACTION",
|
| 50 |
+
"OBS_IMAGES",
|
| 51 |
+
"OBS_STATE",
|
| 52 |
+
# Internal normalized form (still public for rare low-level authoring).
|
| 53 |
+
"DatasetSchema",
|
| 54 |
+
"SchemaError",
|
| 55 |
+
"SchemaDiscoveryError",
|
| 56 |
+
"SchemaSpecError",
|
| 57 |
+
"SchemaValidationError",
|
| 58 |
+
"discover_schema",
|
| 59 |
+
"register",
|
| 60 |
+
"resolve",
|
| 61 |
+
"registered_names",
|
| 62 |
+
# Declarative authoring (preferred entrypoint for new datasets).
|
| 63 |
+
"AnnotationSpec",
|
| 64 |
+
"AnnotationLossSpec",
|
| 65 |
+
"ArmCount",
|
| 66 |
+
"ArmLayoutSpec",
|
| 67 |
+
"MergeRecipe",
|
| 68 |
+
"MultiChannelBlueprint",
|
| 69 |
+
"SingleArm",
|
| 70 |
+
"SingleArmBlueprint",
|
| 71 |
+
"SourceArmLayout",
|
| 72 |
+
"StateActionChannel",
|
| 73 |
+
# Camera mapping SSOT helpers.
|
| 74 |
+
"expand_camera_mapping",
|
| 75 |
+
"expand_camera_source",
|
| 76 |
+
"expand_camera_target",
|
| 77 |
+
"infer_image_mapping_from_info",
|
| 78 |
+
"validate_camera_mapping",
|
| 79 |
+
# Validators.
|
| 80 |
+
"validate_arm_layout",
|
| 81 |
+
"validate_schema",
|
| 82 |
+
]
|
src/schema/annotation_loss.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-dataset annotation loss specification.
|
| 2 |
+
|
| 3 |
+
A schema can declare one or more `AnnotationLossSpec` entries to request
|
| 4 |
+
auxiliary losses computed on annotation columns present in the parquet data.
|
| 5 |
+
Dataset adapters pass through arbitrary string columns (e.g. RoboInter's
|
| 6 |
+
`annotation.substask`); this spec tells the training pipeline which ones to
|
| 7 |
+
tokenize and supervise with a text next-token CE loss.
|
| 8 |
+
|
| 9 |
+
Only datasets whose parquet actually contains the named `field` should declare
|
| 10 |
+
the spec. Datasets with no annotation_losses (e.g. oxe-auge) take the fast
|
| 11 |
+
pure-MSE path β completely decoupled from this feature.
|
| 12 |
+
|
| 13 |
+
Decoupling from Knowledge Isolation
|
| 14 |
+
-----------------------------------
|
| 15 |
+
Annotation CE is orthogonal to the KI toggle:
|
| 16 |
+
|
| 17 |
+
- KI=false: annotation CE flows to VLM (standard Ο0 joint-grad, same as MSE).
|
| 18 |
+
- KI=true : annotation CE still flows to VLM (MSE detach does not affect it β
|
| 19 |
+
KI only detaches the MSE path into DiT).
|
| 20 |
+
|
| 21 |
+
The whole point of annotation CE is to *train the VLM on semantic labels*, so
|
| 22 |
+
it must always be un-detached. Only MSE detaching is governed by KI.
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
from dataclasses import dataclass
|
| 27 |
+
from typing import Any
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
_SUPPORTED_LOSS_TYPES = ("ce_text",)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# The raw per-field columns that BuildUnifiedAnnotationTransformFn packs into
|
| 34 |
+
# the synthesized `annotation.unified` text. Both the transform (builder) and
|
| 35 |
+
# the v3.0 adapter's column projection (which must fetch these physical columns
|
| 36 |
+
# so the builder has inputs) consume it.
|
| 37 |
+
#
|
| 38 |
+
# Field order matters (it is the order the model sees): bbox/object-location
|
| 39 |
+
# fields come BEFORE annotation.substask per Ο0.5 App B.2 "locate first, then
|
| 40 |
+
# subtask". `annotation.segmentation` is intentionally OMITTED β a dense pixel
|
| 41 |
+
# mask is too heavy to tokenize as text. NOTE: "substask" (double s) is the
|
| 42 |
+
# dataset's REAL column spelling.
|
| 43 |
+
UNIFIED_ANNOTATION_FIELDS: tuple[str, ...] = (
|
| 44 |
+
"annotation.object_box",
|
| 45 |
+
"annotation.gripper_box",
|
| 46 |
+
"annotation.affordance_box",
|
| 47 |
+
"annotation.substask",
|
| 48 |
+
"annotation.primitive_skill",
|
| 49 |
+
"annotation.instruction_add",
|
| 50 |
+
"annotation.placement_proposal",
|
| 51 |
+
"annotation.state_affordance",
|
| 52 |
+
"annotation.contact_frame",
|
| 53 |
+
"annotation.contact_points",
|
| 54 |
+
"annotation.trace",
|
| 55 |
+
# annotation.time_clip kept available but lower-signal β included for
|
| 56 |
+
# completeness, model will learn to skip if useless.
|
| 57 |
+
"annotation.time_clip",
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass(frozen=True)
|
| 62 |
+
class AnnotationLossSpec:
|
| 63 |
+
"""Frozen spec for a single annotation-driven auxiliary loss.
|
| 64 |
+
|
| 65 |
+
Fields:
|
| 66 |
+
field:
|
| 67 |
+
Parquet column name, e.g. "annotation.substask". Must be a
|
| 68 |
+
string-typed column; the adapter passes its raw value through to
|
| 69 |
+
the sample dict unchanged.
|
| 70 |
+
loss_type:
|
| 71 |
+
Only "ce_text" in v1 β tokenize the string with the VLM tokenizer
|
| 72 |
+
and apply next-token cross entropy on VLM hidden states at the
|
| 73 |
+
annotation positions.
|
| 74 |
+
weight:
|
| 75 |
+
Multiplier applied to this CE term when added to the total loss.
|
| 76 |
+
Must be > 0. Typical range [0.1, 1.0].
|
| 77 |
+
max_length:
|
| 78 |
+
Max token count after tokenization. Shorter strings are padded;
|
| 79 |
+
longer ones are truncated. Padding positions are excluded from the
|
| 80 |
+
CE computation via an attention-like mask.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
field: str
|
| 84 |
+
loss_type: str = "ce_text"
|
| 85 |
+
weight: float = 0.5
|
| 86 |
+
max_length: int = 32
|
| 87 |
+
|
| 88 |
+
def __post_init__(self) -> None:
|
| 89 |
+
if not self.field or not isinstance(self.field, str):
|
| 90 |
+
raise ValueError(
|
| 91 |
+
f"AnnotationLossSpec.field must be a non-empty string, got {self.field!r}"
|
| 92 |
+
)
|
| 93 |
+
if self.loss_type not in _SUPPORTED_LOSS_TYPES:
|
| 94 |
+
raise ValueError(
|
| 95 |
+
f"AnnotationLossSpec.loss_type must be one of {_SUPPORTED_LOSS_TYPES}, "
|
| 96 |
+
f"got {self.loss_type!r}"
|
| 97 |
+
)
|
| 98 |
+
# bool is a subclass of int, so ``isinstance(True, (int, float))`` is
|
| 99 |
+
# True. Without the explicit bool guard a config typo like
|
| 100 |
+
# ``weight: true`` / ``max_length: false`` would be silently coerced to
|
| 101 |
+
# 1.0 / 1 / 0 and change the loss semantics instead of being rejected.
|
| 102 |
+
if (isinstance(self.weight, bool)
|
| 103 |
+
or not isinstance(self.weight, (int, float))
|
| 104 |
+
or self.weight <= 0):
|
| 105 |
+
raise ValueError(
|
| 106 |
+
f"AnnotationLossSpec.weight must be a real number > 0, got "
|
| 107 |
+
f"{type(self.weight).__name__}={self.weight!r}"
|
| 108 |
+
)
|
| 109 |
+
if (isinstance(self.max_length, bool)
|
| 110 |
+
or not isinstance(self.max_length, int)
|
| 111 |
+
or self.max_length <= 0):
|
| 112 |
+
raise ValueError(
|
| 113 |
+
f"AnnotationLossSpec.max_length must be a positive int, got "
|
| 114 |
+
f"{type(self.max_length).__name__}={self.max_length!r}"
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def to_dict(self) -> dict[str, Any]:
|
| 118 |
+
return {
|
| 119 |
+
"field": self.field,
|
| 120 |
+
"loss_type": self.loss_type,
|
| 121 |
+
"weight": float(self.weight),
|
| 122 |
+
"max_length": int(self.max_length),
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
@classmethod
|
| 126 |
+
def from_dict(cls, d: dict[str, Any]) -> "AnnotationLossSpec":
|
| 127 |
+
# Validate the RAW types before float()/int() coercion. Otherwise
|
| 128 |
+
# ``"weight": true`` round-trips through float(True)==1.0 (and
|
| 129 |
+
# ``"max_length": false`` through int(False)==0) and silently changes
|
| 130 |
+
# semantics instead of raising. bool is a subclass of int, so it is
|
| 131 |
+
# excluded explicitly here as well as in __post_init__.
|
| 132 |
+
weight_raw = d.get("weight", 0.5)
|
| 133 |
+
if isinstance(weight_raw, bool) or not isinstance(weight_raw, (int, float)):
|
| 134 |
+
raise ValueError(
|
| 135 |
+
f"AnnotationLossSpec.weight must be a real number, got "
|
| 136 |
+
f"{type(weight_raw).__name__}={weight_raw!r}"
|
| 137 |
+
)
|
| 138 |
+
max_length_raw = d.get("max_length", 32)
|
| 139 |
+
if isinstance(max_length_raw, bool) or not isinstance(max_length_raw, int):
|
| 140 |
+
raise ValueError(
|
| 141 |
+
f"AnnotationLossSpec.max_length must be an int, got "
|
| 142 |
+
f"{type(max_length_raw).__name__}={max_length_raw!r}"
|
| 143 |
+
)
|
| 144 |
+
return cls(
|
| 145 |
+
field=d["field"],
|
| 146 |
+
loss_type=d.get("loss_type", "ce_text"),
|
| 147 |
+
weight=float(weight_raw),
|
| 148 |
+
max_length=int(max_length_raw),
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
def batch_key_tokens(self) -> str:
|
| 152 |
+
"""Sample-dict / batch-dict key for this annotation's token IDs."""
|
| 153 |
+
return f"annotation_tokens__{self.field}"
|
| 154 |
+
|
| 155 |
+
def batch_key_mask(self) -> str:
|
| 156 |
+
"""Sample-dict / batch-dict key for this annotation's valid-token mask."""
|
| 157 |
+
return f"annotation_mask__{self.field}"
|
| 158 |
+
|
| 159 |
+
def batch_key_weight(self) -> str:
|
| 160 |
+
"""Sample-dict / batch-dict key carrying `spec.weight` as a scalar
|
| 161 |
+
tensor. Per-sample scalar lets the model compose loss without a
|
| 162 |
+
schema reference plumbed through the training loop."""
|
| 163 |
+
return f"annotation_weight__{self.field}"
|
| 164 |
+
|
| 165 |
+
@staticmethod
|
| 166 |
+
def field_from_tokens_key(key: str) -> str | None:
|
| 167 |
+
"""Reverse of `batch_key_tokens` β extract field name or None."""
|
| 168 |
+
prefix = "annotation_tokens__"
|
| 169 |
+
return key[len(prefix):] if key.startswith(prefix) else None
|
src/schema/arm_layout.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Canonical arm-count layouts for LabVLA action/state vectors.
|
| 2 |
+
|
| 3 |
+
Design principle (openpi-aligned, simpler than InternVLA-A1's per-robot mapping):
|
| 4 |
+
|
| 5 |
+
- **Single-arm** data β **8-dim canonical**: arm joints at dim 0..6 (pad 0 at
|
| 6 |
+
dim 6 for 6-DoF arms like UR5/WidowX/Jaco), gripper at dim 7.
|
| 7 |
+
- **Dual-arm** data β **14-dim canonical**: left arm at dim 0..5 (6 joints,
|
| 8 |
+
pad if 5-DoF), left gripper at dim 6, right arm at dim 7..12, right
|
| 9 |
+
gripper at dim 13. Matches openpi Aloha's `state[[6, 13]]` gripper
|
| 10 |
+
indexing.
|
| 11 |
+
|
| 12 |
+
Both layouts are then right-padded to `max_action_dim=32` by
|
| 13 |
+
`PadStateAndActionTransformFn` downstream.
|
| 14 |
+
|
| 15 |
+
Pretrain, fine-tune, and deployment MUST all use the same
|
| 16 |
+
`ArmLayoutSpec` for a given robot, so the model sees a consistent
|
| 17 |
+
gripper position throughout its life. This module is the single source
|
| 18 |
+
of truth.
|
| 19 |
+
|
| 20 |
+
References:
|
| 21 |
+
- openpi DROID (Franka 7-DoF single-arm, gripper dim 7).
|
| 22 |
+
- openpi Aloha (dual-arm, grippers at [6, 13]).
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
from dataclasses import dataclass
|
| 27 |
+
from enum import Enum
|
| 28 |
+
from typing import Optional
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
SINGLE_ARM_CANONICAL_DIM = 8
|
| 34 |
+
SINGLE_ARM_GRIPPER_INDEX = 7
|
| 35 |
+
|
| 36 |
+
DUAL_ARM_CANONICAL_DIM = 14
|
| 37 |
+
DUAL_ARM_GRIPPER_INDICES = (6, 13)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class ArmCount(str, Enum):
|
| 41 |
+
SINGLE = "single"
|
| 42 |
+
DUAL = "dual"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
GRIPPER_BINARIZE_THRESHOLD_DEFAULT = 0.5
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass(frozen=True)
|
| 49 |
+
class ArmLayoutSpec:
|
| 50 |
+
"""Describes how a raw robot's joint+gripper data maps to canonical form.
|
| 51 |
+
|
| 52 |
+
Used by:
|
| 53 |
+
- Data merge / preprocessing: forward_map_* writes canonical shards
|
| 54 |
+
- Adapter: can apply forward_map_* on-the-fly if data isn't pre-merged
|
| 55 |
+
- Deployment: reverse_map_* converts canonical output back to raw
|
| 56 |
+
- Schema discovery: stored in `DatasetSchema.arm_layout`
|
| 57 |
+
|
| 58 |
+
Example (single-arm, Franka 7-DoF):
|
| 59 |
+
ArmLayoutSpec(arm_count=ArmCount.SINGLE, arm_dof=7, gripper_index_in_raw=7)
|
| 60 |
+
Example (single-arm, UR5 6-DoF, gripper at raw index 6):
|
| 61 |
+
ArmLayoutSpec(arm_count=ArmCount.SINGLE, arm_dof=6, gripper_index_in_raw=6)
|
| 62 |
+
Example (dual-arm Aloha, both 6-DoF):
|
| 63 |
+
ArmLayoutSpec(arm_count=ArmCount.DUAL,
|
| 64 |
+
left_arm_dof=6, right_arm_dof=6,
|
| 65 |
+
left_gripper_index_in_raw=6,
|
| 66 |
+
right_gripper_index_in_raw=13)
|
| 67 |
+
"""
|
| 68 |
+
arm_count: ArmCount
|
| 69 |
+
|
| 70 |
+
# Single-arm fields.
|
| 71 |
+
arm_dof: Optional[int] = None
|
| 72 |
+
gripper_index_in_raw: Optional[int] = None
|
| 73 |
+
|
| 74 |
+
# Dual-arm fields (future: robocoin_clean / Aloha / etc.).
|
| 75 |
+
left_arm_dof: Optional[int] = None
|
| 76 |
+
right_arm_dof: Optional[int] = None
|
| 77 |
+
left_gripper_index_in_raw: Optional[int] = None
|
| 78 |
+
right_gripper_index_in_raw: Optional[int] = None
|
| 79 |
+
|
| 80 |
+
# Per-robot gripper-binarization threshold (on q01/q99-normalized
|
| 81 |
+
# [-1, 1] action space). Default 0.5 matches starVLA/openpi convention β a
|
| 82 |
+
# conservative "open only when confidently positive" policy that
|
| 83 |
+
# corresponds to the 75% quantile of the raw gripper distribution. Robots
|
| 84 |
+
# with asymmetric gripper stats (e.g. a distribution with most mass in the
|
| 85 |
+
# open state) may override; always read via the schema at deploy time,
|
| 86 |
+
# never hard-code in the inference code path.
|
| 87 |
+
gripper_binarize_threshold: float = GRIPPER_BINARIZE_THRESHOLD_DEFAULT
|
| 88 |
+
|
| 89 |
+
def __post_init__(self) -> None:
|
| 90 |
+
# Structural validation lives in schema/validate.py (SSOT).
|
| 91 |
+
from .validate import validate_arm_layout
|
| 92 |
+
validate_arm_layout(self)
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def canonical_dim(self) -> int:
|
| 96 |
+
return (SINGLE_ARM_CANONICAL_DIM if self.arm_count == ArmCount.SINGLE
|
| 97 |
+
else DUAL_ARM_CANONICAL_DIM)
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def gripper_indices_canonical(self) -> tuple[int, ...]:
|
| 101 |
+
return ((SINGLE_ARM_GRIPPER_INDEX,) if self.arm_count == ArmCount.SINGLE
|
| 102 |
+
else DUAL_ARM_GRIPPER_INDICES)
|
| 103 |
+
|
| 104 |
+
def to_dict(self) -> dict:
|
| 105 |
+
"""Serialize to JSON-friendly dict for labvla_manifest.json.
|
| 106 |
+
|
| 107 |
+
``gripper_binarize_threshold`` is always emitted (even when equal to
|
| 108 |
+
the default) so the on-disk record is self-describing β consumers
|
| 109 |
+
downstream (e.g. deploy) read the threshold from the schema rather
|
| 110 |
+
than assume a hard-coded 0.5.
|
| 111 |
+
"""
|
| 112 |
+
base: dict = {"arm_count": self.arm_count.value}
|
| 113 |
+
if self.arm_count == ArmCount.SINGLE:
|
| 114 |
+
base["arm_dof"] = self.arm_dof
|
| 115 |
+
base["gripper_index_in_raw"] = self.gripper_index_in_raw
|
| 116 |
+
else:
|
| 117 |
+
base["left_arm_dof"] = self.left_arm_dof
|
| 118 |
+
base["right_arm_dof"] = self.right_arm_dof
|
| 119 |
+
base["left_gripper_index_in_raw"] = self.left_gripper_index_in_raw
|
| 120 |
+
base["right_gripper_index_in_raw"] = self.right_gripper_index_in_raw
|
| 121 |
+
base["gripper_binarize_threshold"] = float(self.gripper_binarize_threshold)
|
| 122 |
+
return base
|
| 123 |
+
|
| 124 |
+
@classmethod
|
| 125 |
+
def from_dict(cls, d: dict) -> "ArmLayoutSpec":
|
| 126 |
+
arm_count = ArmCount(d["arm_count"])
|
| 127 |
+
# Backward compatible β older manifests without the threshold
|
| 128 |
+
# key fall back to the module default. New manifests always carry it.
|
| 129 |
+
threshold = float(d.get(
|
| 130 |
+
"gripper_binarize_threshold", GRIPPER_BINARIZE_THRESHOLD_DEFAULT
|
| 131 |
+
))
|
| 132 |
+
if arm_count == ArmCount.SINGLE:
|
| 133 |
+
return cls(
|
| 134 |
+
arm_count=arm_count,
|
| 135 |
+
arm_dof=d["arm_dof"],
|
| 136 |
+
gripper_index_in_raw=d["gripper_index_in_raw"],
|
| 137 |
+
gripper_binarize_threshold=threshold,
|
| 138 |
+
)
|
| 139 |
+
return cls(
|
| 140 |
+
arm_count=arm_count,
|
| 141 |
+
left_arm_dof=d["left_arm_dof"],
|
| 142 |
+
right_arm_dof=d["right_arm_dof"],
|
| 143 |
+
left_gripper_index_in_raw=d["left_gripper_index_in_raw"],
|
| 144 |
+
right_gripper_index_in_raw=d["right_gripper_index_in_raw"],
|
| 145 |
+
gripper_binarize_threshold=threshold,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ====================== Single-arm forward / reverse ======================
|
| 150 |
+
|
| 151 |
+
def forward_map_single(
|
| 152 |
+
raw: np.ndarray,
|
| 153 |
+
arm_dof: int,
|
| 154 |
+
gripper_index_in_raw: int,
|
| 155 |
+
) -> np.ndarray:
|
| 156 |
+
"""Raw single-arm [arm + gripper, possibly 7 or 8 dim] β 8-dim canonical.
|
| 157 |
+
|
| 158 |
+
The canonical layout:
|
| 159 |
+
dim 0..6 = arm joints (pad 0 at dim 6 if arm_dof=6)
|
| 160 |
+
dim 7 = gripper
|
| 161 |
+
|
| 162 |
+
Works on a 1-D vector of shape (raw_dim,) or a batched (..., raw_dim).
|
| 163 |
+
Returns (..., 8) with the last axis permuted.
|
| 164 |
+
|
| 165 |
+
Examples:
|
| 166 |
+
UR5 raw = [j0, j1, j2, j3, j4, j5, grip] (7 dim, dof=6)
|
| 167 |
+
β [j0, j1, j2, j3, j4, j5, 0.0, grip] (8 dim, gripper at dim 7)
|
| 168 |
+
|
| 169 |
+
Franka raw = [j0, j1, j2, j3, j4, j5, j6, grip] (8 dim, dof=7)
|
| 170 |
+
β unchanged (8 dim, gripper at dim 7)
|
| 171 |
+
"""
|
| 172 |
+
raw = np.asarray(raw)
|
| 173 |
+
raw_last_dim = raw.shape[-1]
|
| 174 |
+
out_shape = raw.shape[:-1] + (SINGLE_ARM_CANONICAL_DIM,)
|
| 175 |
+
out = np.zeros(out_shape, dtype=raw.dtype)
|
| 176 |
+
|
| 177 |
+
if arm_dof == 7:
|
| 178 |
+
# Expected raw layout: [j0..j6, gripper] β gripper_index_in_raw == 7
|
| 179 |
+
if raw_last_dim != 8 or gripper_index_in_raw != 7:
|
| 180 |
+
raise ValueError(
|
| 181 |
+
f"forward_map_single(7-DoF): expected raw 8-dim with gripper at idx 7, "
|
| 182 |
+
f"got raw_dim={raw_last_dim}, gripper_idx={gripper_index_in_raw}"
|
| 183 |
+
)
|
| 184 |
+
# Already canonical.
|
| 185 |
+
out[...] = raw
|
| 186 |
+
elif arm_dof == 6:
|
| 187 |
+
# Expected raw layout: [j0..j5, gripper] β gripper_index_in_raw == 6
|
| 188 |
+
if raw_last_dim != 7 or gripper_index_in_raw != 6:
|
| 189 |
+
raise ValueError(
|
| 190 |
+
f"forward_map_single(6-DoF): expected raw 7-dim with gripper at idx 6, "
|
| 191 |
+
f"got raw_dim={raw_last_dim}, gripper_idx={gripper_index_in_raw}"
|
| 192 |
+
)
|
| 193 |
+
# arm joints at dim 0..5, pad 0 at dim 6, gripper at dim 7.
|
| 194 |
+
out[..., :6] = raw[..., :6]
|
| 195 |
+
out[..., 6] = 0.0
|
| 196 |
+
out[..., 7] = raw[..., 6]
|
| 197 |
+
else:
|
| 198 |
+
raise ValueError(f"arm_dof must be 6 or 7, got {arm_dof}")
|
| 199 |
+
|
| 200 |
+
return out
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def reverse_map_single(
|
| 204 |
+
canonical: np.ndarray,
|
| 205 |
+
arm_dof: int,
|
| 206 |
+
gripper_index_in_raw: int,
|
| 207 |
+
) -> np.ndarray:
|
| 208 |
+
"""8-dim canonical β raw robot format (for deployment).
|
| 209 |
+
|
| 210 |
+
Inverse of `forward_map_single`. Drops the 0-pad at dim 6 for 6-DoF arms.
|
| 211 |
+
"""
|
| 212 |
+
canonical = np.asarray(canonical)
|
| 213 |
+
if canonical.shape[-1] != SINGLE_ARM_CANONICAL_DIM:
|
| 214 |
+
raise ValueError(
|
| 215 |
+
f"reverse_map_single expects canonical dim {SINGLE_ARM_CANONICAL_DIM}, "
|
| 216 |
+
f"got {canonical.shape[-1]}"
|
| 217 |
+
)
|
| 218 |
+
if arm_dof == 7:
|
| 219 |
+
# No-op: canonical already matches raw.
|
| 220 |
+
return canonical.copy()
|
| 221 |
+
if arm_dof == 6:
|
| 222 |
+
out_shape = canonical.shape[:-1] + (7,)
|
| 223 |
+
out = np.zeros(out_shape, dtype=canonical.dtype)
|
| 224 |
+
out[..., :6] = canonical[..., :6]
|
| 225 |
+
out[..., 6] = canonical[..., 7] # gripper
|
| 226 |
+
return out
|
| 227 |
+
raise ValueError(f"arm_dof must be 6 or 7, got {arm_dof}")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# ====================== Dual-arm forward / reverse ======================
|
| 231 |
+
# Used by dual-arm schema canonicalization (AgiBot/Aloha-style layouts).
|
| 232 |
+
|
| 233 |
+
def reverse_map_dual(
|
| 234 |
+
canonical: np.ndarray,
|
| 235 |
+
left_arm_dof: int,
|
| 236 |
+
right_arm_dof: int,
|
| 237 |
+
) -> dict[str, np.ndarray]:
|
| 238 |
+
"""Split 14-dim canonical back into per-component raw arrays.
|
| 239 |
+
|
| 240 |
+
This reverse map is exact only for dual-arm layouts with at most six joint
|
| 241 |
+
slots per side. AgiBot-style 7-DoF inputs are lossy in the forward map
|
| 242 |
+
because joint 6 from each side is deliberately dropped to fit the canonical
|
| 243 |
+
14-dim layout; pretending to reconstruct those missing joints would mix the
|
| 244 |
+
gripper slots into arm joints.
|
| 245 |
+
"""
|
| 246 |
+
if canonical.shape[-1] != DUAL_ARM_CANONICAL_DIM:
|
| 247 |
+
raise ValueError(
|
| 248 |
+
f"reverse_map_dual expects canonical dim {DUAL_ARM_CANONICAL_DIM}, "
|
| 249 |
+
f"got {canonical.shape[-1]}"
|
| 250 |
+
)
|
| 251 |
+
if left_arm_dof > 6 or right_arm_dof > 6:
|
| 252 |
+
raise ValueError(
|
| 253 |
+
"reverse_map_dual cannot reconstruct lossy 7-DoF dual-arm inputs; "
|
| 254 |
+
"the canonical 14-dim layout keeps only six joints per side and "
|
| 255 |
+
"stores grippers at dims 6 and 13."
|
| 256 |
+
)
|
| 257 |
+
return {
|
| 258 |
+
"left_arm": canonical[..., :left_arm_dof].copy(),
|
| 259 |
+
"left_gripper": canonical[..., 6:7].copy(),
|
| 260 |
+
"right_arm": canonical[..., 7:7 + right_arm_dof].copy(),
|
| 261 |
+
"right_gripper": canonical[..., 13:14].copy(),
|
| 262 |
+
}
|
src/schema/blueprint.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 1 |
+
"""Dataset Blueprint β declarative single-source-of-truth for authoring schemas.
|
| 2 |
+
|
| 3 |
+
Users describe a dataset with high-level constructs (arm DoF, parquet columns,
|
| 4 |
+
camera roles, annotations). `.build()` compiles these into a `DatasetSchema` β
|
| 5 |
+
the same internal dataclass that every downstream module (stats, merge,
|
| 6 |
+
preflight, adapter, transform chain, model, deploy) already consumes.
|
| 7 |
+
|
| 8 |
+
Two top-level blueprints cover every dataset we have:
|
| 9 |
+
|
| 10 |
+
SingleArmBlueprint β arm + gripper layout (oxe_auge, labutopia_level3,
|
| 11 |
+
future droid-family datasets).
|
| 12 |
+
MultiChannelBlueprint β arbitrary list of (state_col, action_col, dim,
|
| 13 |
+
mode) channels (robocoin's action + dedicated
|
| 14 |
+
gripper_open_scale_action).
|
| 15 |
+
|
| 16 |
+
Anything a DatasetSchema needs but the blueprint can't infer (e.g. canonical
|
| 17 |
+
dual-arm layout on a multi-channel robocoin) is passed explicitly as an
|
| 18 |
+
argument. The blueprint compiler is a pure function β running it twice
|
| 19 |
+
yields bit-identical DatasetSchema.to_dict() β which makes stats.json /
|
| 20 |
+
labvla_manifest.json / checkpoint compatibility self-verifying.
|
| 21 |
+
|
| 22 |
+
Normalization mode
|
| 23 |
+
------------------
|
| 24 |
+
The project-wide default is ``"mean_std"`` β z-score, set at the transform
|
| 25 |
+
chain level in ``policies/LabVLA/configuration_labvla.py``. ``hydrate_all``
|
| 26 |
+
in ``transforms/core.py`` then auto-injects per-dim ``"q01_q99"`` overrides
|
| 27 |
+
on the canonical gripper indices declared by ``schema.gripper_action_dims``,
|
| 28 |
+
so the effective policy is "arm dims β mean_std, gripper dims β q01_q99".
|
| 29 |
+
Schemas don't carry a per-dim normalization field; overrides flow through
|
| 30 |
+
``schema.gripper_action_dims`` (and ``arm_layout.gripper_indices_canonical``,
|
| 31 |
+
which mirrors it).
|
| 32 |
+
"""
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
from dataclasses import dataclass, field
|
| 36 |
+
from typing import Mapping, Optional
|
| 37 |
+
|
| 38 |
+
from .annotation_loss import AnnotationLossSpec
|
| 39 |
+
from .arm_layout import ArmLayoutSpec, ArmCount
|
| 40 |
+
from .camera_mapping import expand_camera_mapping
|
| 41 |
+
from .dataset_schema import DatasetSchema
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# --------------------------------------------------------------------------- #
|
| 45 |
+
# Authoring primitives #
|
| 46 |
+
# --------------------------------------------------------------------------- #
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass(frozen=True)
|
| 50 |
+
class AnnotationSpec:
|
| 51 |
+
"""Blueprint-level shorthand for an annotation CE loss declaration.
|
| 52 |
+
|
| 53 |
+
Compiled to `schema.annotation_loss.AnnotationLossSpec` at build() time.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
field: str
|
| 57 |
+
weight: float = 0.5
|
| 58 |
+
max_length: int = 32
|
| 59 |
+
loss_type: str = "ce_text"
|
| 60 |
+
|
| 61 |
+
def to_loss_spec(self) -> AnnotationLossSpec:
|
| 62 |
+
return AnnotationLossSpec(
|
| 63 |
+
field=self.field,
|
| 64 |
+
loss_type=self.loss_type,
|
| 65 |
+
weight=self.weight,
|
| 66 |
+
max_length=self.max_length,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass(frozen=True)
|
| 71 |
+
class SingleArm:
|
| 72 |
+
"""Single-arm spec: arm joints + one gripper channel.
|
| 73 |
+
|
| 74 |
+
The four parquet columns fully describe the per-frame layout. Gripper
|
| 75 |
+
state/action may live in the *same* column as arm joints (e.g. oxe_auge's
|
| 76 |
+
`observation.joints` holds both) β in that case the user sets the same
|
| 77 |
+
column name for both `joint_*` and `gripper_*`; the blueprint infers
|
| 78 |
+
that only one state/action key is needed.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
dof: int
|
| 82 |
+
joint_state_col: str
|
| 83 |
+
joint_action_col: str
|
| 84 |
+
gripper_state_col: str
|
| 85 |
+
gripper_action_col: str
|
| 86 |
+
arm_mode: str = "delta" # "delta" | "abs"
|
| 87 |
+
gripper_mode: str = "abs" # "delta" | "abs"
|
| 88 |
+
|
| 89 |
+
def __post_init__(self) -> None:
|
| 90 |
+
if self.dof <= 0:
|
| 91 |
+
raise ValueError(f"SingleArm.dof must be > 0, got {self.dof}")
|
| 92 |
+
for name, mode in (("arm_mode", self.arm_mode),
|
| 93 |
+
("gripper_mode", self.gripper_mode)):
|
| 94 |
+
if mode not in ("delta", "abs"):
|
| 95 |
+
raise ValueError(
|
| 96 |
+
f"SingleArm.{name} must be 'delta' or 'abs', got {mode!r}"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@dataclass(frozen=True)
|
| 101 |
+
class StateActionChannel:
|
| 102 |
+
"""One independent (state_col, action_col) channel with its own dim/mode.
|
| 103 |
+
|
| 104 |
+
Used by MultiChannelBlueprint for datasets whose action vector is split
|
| 105 |
+
across multiple parquet columns (robocoin: `action` for arm +
|
| 106 |
+
`gripper_open_scale_action` for gripper, with different dims and modes).
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
state_col: str
|
| 110 |
+
action_col: str
|
| 111 |
+
dim: int
|
| 112 |
+
mode: str = "delta" # "delta" | "abs"
|
| 113 |
+
is_gripper: bool = False # marks all `dim` flat indices as gripper dims
|
| 114 |
+
|
| 115 |
+
def __post_init__(self) -> None:
|
| 116 |
+
if self.dim <= 0:
|
| 117 |
+
raise ValueError(f"StateActionChannel.dim must be > 0, got {self.dim}")
|
| 118 |
+
if self.mode not in ("delta", "abs"):
|
| 119 |
+
raise ValueError(
|
| 120 |
+
f"StateActionChannel.mode must be 'delta' or 'abs', got {self.mode!r}"
|
| 121 |
+
)
|
| 122 |
+
if self.is_gripper and self.mode == "delta":
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"is_gripper=True channel must use mode='abs' (gripper never delta). "
|
| 125 |
+
f"Got mode={self.mode!r}, state_col={self.state_col!r}"
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# --------------------------------------------------------------------------- #
|
| 130 |
+
# Top-level blueprints #
|
| 131 |
+
# --------------------------------------------------------------------------- #
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@dataclass(frozen=True)
|
| 135 |
+
class SingleArmBlueprint:
|
| 136 |
+
"""Author a single-arm dataset in ~15 lines.
|
| 137 |
+
|
| 138 |
+
Given the SingleArm spec, the blueprint derives:
|
| 139 |
+
state_keys = (joint_state_col,) or (joint_state_col, gripper_state_col)
|
| 140 |
+
state_dims = (dof,) or (dof, 1) [merged when cols are identical]
|
| 141 |
+
action_keys = (joint_action_col,) or (joint_action_col, gripper_action_col)
|
| 142 |
+
action_dims = (dof,) or (dof, 1)
|
| 143 |
+
delta_mask = arm_mode Γ dof + gripper_mode Γ 1
|
| 144 |
+
gripper_action_dims = (dof,)
|
| 145 |
+
arm_layout = ArmLayoutSpec(SINGLE, arm_dof=dof, gripper_index_in_raw=dof)
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
schema_id: str
|
| 149 |
+
robot_type: str
|
| 150 |
+
arm: SingleArm
|
| 151 |
+
cameras: Mapping[str, str]
|
| 152 |
+
annotations: tuple[AnnotationSpec, ...] = ()
|
| 153 |
+
source_path: Optional[str] = None
|
| 154 |
+
# Consumed POST-build by `discover_schema` (only relaxes the reverse
|
| 155 |
+
# "info.json has extra cameras" check). Blueprint authoring does NOT read
|
| 156 |
+
# this flag β it only forwards the value into the built DatasetSchema.
|
| 157 |
+
allow_extra_cameras: bool = False
|
| 158 |
+
# Physical semantics of the gripper action channel β see
|
| 159 |
+
# DatasetSchema.gripper_semantic. Forwarded into the built schema; default
|
| 160 |
+
# None means no cross-dataset semantic guard.
|
| 161 |
+
gripper_semantic: Optional[str] = None
|
| 162 |
+
# Virtual state columns β see DatasetSchema.virtual_state_sources.
|
| 163 |
+
# Forwarded verbatim; validate_schema enforces the "virtual." prefix and
|
| 164 |
+
# membership rules on the built schema.
|
| 165 |
+
virtual_state_sources: Mapping[str, str] = field(default_factory=dict)
|
| 166 |
+
|
| 167 |
+
def build(self) -> DatasetSchema:
|
| 168 |
+
a = self.arm
|
| 169 |
+
|
| 170 |
+
# Same column for joint + gripper (e.g. oxe_auge observation.joints
|
| 171 |
+
# holds [j0..j6, grip] in a single column) β collapse to one key.
|
| 172 |
+
state_collapsed = a.joint_state_col == a.gripper_state_col
|
| 173 |
+
action_collapsed = a.joint_action_col == a.gripper_action_col
|
| 174 |
+
|
| 175 |
+
if state_collapsed:
|
| 176 |
+
state_keys = (a.joint_state_col,)
|
| 177 |
+
state_dims = (a.dof + 1,)
|
| 178 |
+
else:
|
| 179 |
+
state_keys = (a.joint_state_col, a.gripper_state_col)
|
| 180 |
+
state_dims = (a.dof, 1)
|
| 181 |
+
|
| 182 |
+
if action_collapsed:
|
| 183 |
+
action_keys = (a.joint_action_col,)
|
| 184 |
+
action_dims = (a.dof + 1,)
|
| 185 |
+
else:
|
| 186 |
+
action_keys = (a.joint_action_col, a.gripper_action_col)
|
| 187 |
+
action_dims = (a.dof, 1)
|
| 188 |
+
|
| 189 |
+
delta_mask = (
|
| 190 |
+
tuple([a.arm_mode == "delta"] * a.dof)
|
| 191 |
+
+ (a.gripper_mode == "delta",)
|
| 192 |
+
)
|
| 193 |
+
gripper_action_dims = (a.dof,)
|
| 194 |
+
|
| 195 |
+
arm_layout = ArmLayoutSpec(
|
| 196 |
+
arm_count=ArmCount.SINGLE,
|
| 197 |
+
arm_dof=a.dof,
|
| 198 |
+
gripper_index_in_raw=a.dof,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
annotation_losses = tuple(s.to_loss_spec() for s in self.annotations)
|
| 202 |
+
|
| 203 |
+
image_mapping = expand_camera_mapping(self.cameras)
|
| 204 |
+
|
| 205 |
+
return DatasetSchema(
|
| 206 |
+
schema_id=self.schema_id,
|
| 207 |
+
robot_type=self.robot_type,
|
| 208 |
+
state_keys=state_keys,
|
| 209 |
+
action_keys=action_keys,
|
| 210 |
+
state_dims=state_dims,
|
| 211 |
+
action_dims=action_dims,
|
| 212 |
+
delta_mask=delta_mask,
|
| 213 |
+
gripper_action_dims=gripper_action_dims,
|
| 214 |
+
image_mapping=image_mapping,
|
| 215 |
+
source="manifest",
|
| 216 |
+
source_path=self.source_path,
|
| 217 |
+
allow_extra_cameras=self.allow_extra_cameras,
|
| 218 |
+
arm_layout=arm_layout,
|
| 219 |
+
annotation_losses=annotation_losses,
|
| 220 |
+
gripper_semantic=self.gripper_semantic,
|
| 221 |
+
virtual_state_sources=self.virtual_state_sources,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@dataclass(frozen=True)
|
| 226 |
+
class MultiChannelBlueprint:
|
| 227 |
+
"""Author a dataset whose state/action spans multiple independent channels.
|
| 228 |
+
|
| 229 |
+
Use when the robot-native layout isn't ``arm + 1 gripper`` β e.g. robocoin
|
| 230 |
+
merges 16+ source robots with a dedicated dual-arm `gripper_open_scale_*`
|
| 231 |
+
channel separate from the main `action` column.
|
| 232 |
+
|
| 233 |
+
Because `channels` may not map onto any standard ArmLayout, the caller
|
| 234 |
+
passes `arm_layout_canonical` explicitly (or leaves it None if the dataset
|
| 235 |
+
is not "arm-shaped" at all).
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
schema_id: str
|
| 239 |
+
robot_type: str
|
| 240 |
+
channels: tuple[StateActionChannel, ...]
|
| 241 |
+
cameras: Mapping[str, str]
|
| 242 |
+
annotations: tuple[AnnotationSpec, ...] = ()
|
| 243 |
+
arm_layout_canonical: Optional[ArmLayoutSpec] = None
|
| 244 |
+
source_path: Optional[str] = None
|
| 245 |
+
# Consumed POST-build by `discover_schema`. See SingleArmBlueprint
|
| 246 |
+
# for the full note; same semantics apply here.
|
| 247 |
+
allow_extra_cameras: bool = False
|
| 248 |
+
# See SingleArmBlueprint.gripper_semantic.
|
| 249 |
+
gripper_semantic: Optional[str] = None
|
| 250 |
+
|
| 251 |
+
def __post_init__(self) -> None:
|
| 252 |
+
if not self.channels:
|
| 253 |
+
raise ValueError("MultiChannelBlueprint.channels must be non-empty")
|
| 254 |
+
|
| 255 |
+
def build(self) -> DatasetSchema:
|
| 256 |
+
state_keys = tuple(c.state_col for c in self.channels)
|
| 257 |
+
action_keys = tuple(c.action_col for c in self.channels)
|
| 258 |
+
state_dims = tuple(c.dim for c in self.channels)
|
| 259 |
+
action_dims = tuple(c.dim for c in self.channels)
|
| 260 |
+
|
| 261 |
+
# delta_mask: concatenate per-channel (dim Γ mode flag).
|
| 262 |
+
delta_mask: tuple[bool, ...] = ()
|
| 263 |
+
gripper_idx_list: list[int] = []
|
| 264 |
+
offset = 0
|
| 265 |
+
for c in self.channels:
|
| 266 |
+
delta_mask = delta_mask + tuple([c.mode == "delta"] * c.dim)
|
| 267 |
+
if c.is_gripper:
|
| 268 |
+
gripper_idx_list.extend(range(offset, offset + c.dim))
|
| 269 |
+
offset += c.dim
|
| 270 |
+
gripper_action_dims = tuple(gripper_idx_list)
|
| 271 |
+
|
| 272 |
+
annotation_losses = tuple(s.to_loss_spec() for s in self.annotations)
|
| 273 |
+
image_mapping = expand_camera_mapping(self.cameras)
|
| 274 |
+
|
| 275 |
+
return DatasetSchema(
|
| 276 |
+
schema_id=self.schema_id,
|
| 277 |
+
robot_type=self.robot_type,
|
| 278 |
+
state_keys=state_keys,
|
| 279 |
+
action_keys=action_keys,
|
| 280 |
+
state_dims=state_dims,
|
| 281 |
+
action_dims=action_dims,
|
| 282 |
+
delta_mask=delta_mask,
|
| 283 |
+
gripper_action_dims=gripper_action_dims,
|
| 284 |
+
image_mapping=image_mapping,
|
| 285 |
+
source="manifest",
|
| 286 |
+
source_path=self.source_path,
|
| 287 |
+
allow_extra_cameras=self.allow_extra_cameras,
|
| 288 |
+
arm_layout=self.arm_layout_canonical,
|
| 289 |
+
annotation_losses=annotation_losses,
|
| 290 |
+
gripper_semantic=self.gripper_semantic,
|
| 291 |
+
)
|
src/schema/cam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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Camera-mapping SSOT β expand short alias β full `observation.images.imageN`.
|
| 2 |
+
|
| 3 |
+
Single source of truth for "alias expansion" logic (used by the blueprint
|
| 4 |
+
compiler, manifest parser, and Tier-2 info.json auto-inferrer) plus the
|
| 5 |
+
info.json reverse-check/validation. Keeping one copy avoids silent
|
| 6 |
+
key-mismatch bugs at adapter time.
|
| 7 |
+
|
| 8 |
+
Conventions
|
| 9 |
+
-----------
|
| 10 |
+
A camera "target" is a string. It is either:
|
| 11 |
+
- A short numeric-slot alias like ``"image0"`` / ``"image1"``. Expanded to
|
| 12 |
+
``"{OBS_IMAGES}.{alias}"`` here.
|
| 13 |
+
- Already a fully qualified slot key like ``"observation.images.image0"``.
|
| 14 |
+
Kept as-is.
|
| 15 |
+
|
| 16 |
+
The only valid target slot form is ``imageN`` (N a non-negative integer).
|
| 17 |
+
Non-numeric aliases such as ``"image_left"`` are NOT accepted β the schema
|
| 18 |
+
validator (``schema/validate.py::_IMAGE_TARGET_RE``) only admits
|
| 19 |
+
``observation.images.imageN``, and the downstream Qwen3VL processor iterates a
|
| 20 |
+
fixed set of numbered slots. ``expand_camera_target`` rejects non-``imageN``
|
| 21 |
+
aliases at authoring time so the camera-mapping contract matches the validator
|
| 22 |
+
instead of failing later inside ``DatasetSchema.__post_init__``.
|
| 23 |
+
|
| 24 |
+
A camera "mapping" is ``{raw_camera_key: target}`` where raw_camera_key is
|
| 25 |
+
whatever the source dataset's parquet / info.json calls the camera (e.g.
|
| 26 |
+
``"camera_1_rgb"``, ``"observation.images.cam_head_rgb"``).
|
| 27 |
+
|
| 28 |
+
Tier-2 discovery
|
| 29 |
+
----------------
|
| 30 |
+
``infer_image_mapping_from_info`` produces a default mapping from an
|
| 31 |
+
info.json ``features`` block when no manifest / explicit schema exists.
|
| 32 |
+
It uses a semantic ordering (head/top/front cameras first, then
|
| 33 |
+
hand/wrist, then alphabetical) so ``image0`` consistently matches the
|
| 34 |
+
third-person/primary view that most pretrained policies expect.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
from __future__ import annotations
|
| 38 |
+
|
| 39 |
+
import re
|
| 40 |
+
from typing import Mapping
|
| 41 |
+
|
| 42 |
+
from src.utils.constants import OBS_IMAGES
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# A target slot alias must be ``imageN`` (N a non-negative integer). This
|
| 46 |
+
# mirrors ``schema/validate.py::_IMAGE_TARGET_RE`` (which matches the fully
|
| 47 |
+
# qualified ``observation.images.imageN``) so the authoring contract and the
|
| 48 |
+
# validator agree.
|
| 49 |
+
_IMAGE_SLOT_ALIAS_RE = re.compile(r"^image(\d+)$")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Tokens that mark a camera as the primary / third-person / scene view.
|
| 53 |
+
# Order within a tuple breaks ties between multiple matches.
|
| 54 |
+
_PRIMARY_TOKENS = ("head", "top", "front", "primary", "base", "exterior")
|
| 55 |
+
|
| 56 |
+
# Tokens that mark a camera as arm-mounted / wrist / ego view β placed
|
| 57 |
+
# after primary cameras so ``image0`` is almost always the scene cam.
|
| 58 |
+
_SECONDARY_TOKENS = ("hand", "wrist", "effector", "ego")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def expand_camera_target(raw: str, target: str) -> str:
|
| 62 |
+
"""Expand a possibly short camera target to the fully qualified form.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
raw: The source camera key (used only in error messages).
|
| 66 |
+
target: Either a short numeric-slot alias (``"image0"``) or a full
|
| 67 |
+
``observation.images.image0`` key. Non-string / empty values
|
| 68 |
+
raise ``ValueError``. Non-``imageN`` short aliases (e.g.
|
| 69 |
+
``"image_left"``) are rejected.
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
The fully qualified ``observation.images.imageN`` key.
|
| 73 |
+
"""
|
| 74 |
+
if not isinstance(target, str) or not target:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
f"camera target for {raw!r} must be a non-empty string, got {target!r}"
|
| 77 |
+
)
|
| 78 |
+
if target.startswith(OBS_IMAGES + "."):
|
| 79 |
+
# Already fully qualified β pass through verbatim. The schema validator
|
| 80 |
+
# still enforces the ``imageN`` slot form on it.
|
| 81 |
+
return target
|
| 82 |
+
# A short alias must be ``imageN``. Reject anything else here, at authoring
|
| 83 |
+
# time, with an actionable message β otherwise it would be rejected deep
|
| 84 |
+
# inside ``DatasetSchema.__post_init__``.
|
| 85 |
+
if _IMAGE_SLOT_ALIAS_RE.match(target) is None:
|
| 86 |
+
raise ValueError(
|
| 87 |
+
f"camera target for {raw!r} must be a numbered slot alias "
|
| 88 |
+
f"'imageN' (e.g. 'image0') or a fully qualified "
|
| 89 |
+
f"'{OBS_IMAGES}.imageN' key, got {target!r}. Non-numeric aliases "
|
| 90 |
+
f"like 'image_left' are not supported β the VLM processor consumes "
|
| 91 |
+
f"a fixed set of numbered camera slots."
|
| 92 |
+
)
|
| 93 |
+
return f"{OBS_IMAGES}.{target}"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# The legacy single-image-prefix some older datasets use. Treat as
|
| 97 |
+
# already-qualified to keep backward compatibility with manifests that
|
| 98 |
+
# happen to declare e.g. ``observation.image.head`` instead of
|
| 99 |
+
# ``observation.images.head``.
|
| 100 |
+
_OBS_IMAGE_LEGACY = "observation.image"
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def expand_camera_source(raw: str) -> str:
|
| 104 |
+
"""Expand a possibly short camera SOURCE key to its fully qualified form.
|
| 105 |
+
|
| 106 |
+
Mirror of :func:`expand_camera_target` for source keys (the LHS of
|
| 107 |
+
``schema.image_mapping``). Many schemas were authored with just the
|
| 108 |
+
parquet column name (``"camera_1_rgb"``) on the LHS, then expanded the
|
| 109 |
+
target on the RHS only. Adapters iterate ``image_mapping.keys()`` to
|
| 110 |
+
decide which cameras to read, so a partial expansion left source keys
|
| 111 |
+
in two different shapes downstream and led to the
|
| 112 |
+
``RemapImageKeyTransformFn`` silently popping a key that the adapter
|
| 113 |
+
never wrote (the all-zero training-vs-inference bug).
|
| 114 |
+
|
| 115 |
+
Behavior:
|
| 116 |
+
- Already-prefixed (``observation.images.<x>`` or
|
| 117 |
+
``observation.image.<x>``) β returned verbatim.
|
| 118 |
+
- Otherwise β ``f"{OBS_IMAGES}.{raw}"``.
|
| 119 |
+
|
| 120 |
+
Idempotent on already-prefixed keys, so existing schemas authored
|
| 121 |
+
with full keys (oxe_auge ``observation.images.image``,
|
| 122 |
+
robointer_droid ``observation.images.primary``) continue to work
|
| 123 |
+
unchanged.
|
| 124 |
+
"""
|
| 125 |
+
if not isinstance(raw, str) or not raw:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
f"camera source key must be a non-empty string, got {raw!r}"
|
| 128 |
+
)
|
| 129 |
+
if raw.startswith(OBS_IMAGES + ".") or raw.startswith(_OBS_IMAGE_LEGACY + "."):
|
| 130 |
+
return raw
|
| 131 |
+
return f"{OBS_IMAGES}.{raw}"
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def expand_camera_mapping(mapping: Mapping[str, str]) -> dict[str, str]:
|
| 135 |
+
"""Expand every key AND value of a rawβtarget camera mapping.
|
| 136 |
+
|
| 137 |
+
Short aliases are expanded via ``expand_camera_source`` (LHS) and
|
| 138 |
+
``expand_camera_target`` (RHS); already fully qualified keys/values
|
| 139 |
+
are preserved verbatim. The returned dict is a fresh copy β callers
|
| 140 |
+
may mutate freely.
|
| 141 |
+
|
| 142 |
+
Both the source key and the target are normalized to the unified
|
| 143 |
+
``observation.images.<x>`` form so adapter writes and
|
| 144 |
+
``RemapImageKeyTransformFn`` reads agree. (Expanding only the value left
|
| 145 |
+
legacy schemas like ``cameras={"camera_1_rgb": "image0"}`` with an
|
| 146 |
+
unprefixed source key, so adapters and transforms iterated two different
|
| 147 |
+
key shapes.)
|
| 148 |
+
"""
|
| 149 |
+
return {
|
| 150 |
+
expand_camera_source(raw): expand_camera_target(raw, target)
|
| 151 |
+
for raw, target in mapping.items()
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def validate_camera_mapping(
|
| 156 |
+
mapping: Mapping[str, str],
|
| 157 |
+
num_slots: int,
|
| 158 |
+
) -> None:
|
| 159 |
+
"""Raise ``ValueError`` if the mapping declares more cameras than slots.
|
| 160 |
+
|
| 161 |
+
Most policies are pretrained with a fixed number of camera slots
|
| 162 |
+
(typical ``image0`` / ``image1`` / ``image2``). Declaring more source
|
| 163 |
+
cameras than the policy can consume is a user error, and usually means
|
| 164 |
+
the schema author forgot to consolidate or drop a camera.
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
mapping: raw β fully-qualified-target.
|
| 168 |
+
num_slots: max number of distinct camera slots the policy accepts.
|
| 169 |
+
"""
|
| 170 |
+
if num_slots < 0:
|
| 171 |
+
raise ValueError(f"num_slots must be >= 0, got {num_slots}")
|
| 172 |
+
if len(mapping) > num_slots:
|
| 173 |
+
raise ValueError(
|
| 174 |
+
f"camera mapping declares {len(mapping)} cameras but the policy "
|
| 175 |
+
f"only has {num_slots} slot(s). Mapping keys: {sorted(mapping)!r}"
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _bucket_for_key(key: str) -> tuple[int, int]:
|
| 180 |
+
"""Return a (major, minor) sort key β lower buckets come first."""
|
| 181 |
+
low = key.lower()
|
| 182 |
+
for i, tok in enumerate(_PRIMARY_TOKENS):
|
| 183 |
+
if tok in low:
|
| 184 |
+
return (0, i)
|
| 185 |
+
for i, tok in enumerate(_SECONDARY_TOKENS):
|
| 186 |
+
if tok in low:
|
| 187 |
+
return (1, i)
|
| 188 |
+
return (2, 0)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def infer_image_mapping_from_info(features: dict) -> dict[str, str]:
|
| 192 |
+
"""Tier-2 discovery: derive a camera mapping from an info.json features block.
|
| 193 |
+
|
| 194 |
+
Scans ``features`` for entries whose ``dtype`` is ``"video"`` or
|
| 195 |
+
``"image"`` and produces an ordered mapping to ``image0``,
|
| 196 |
+
``image1``, ... using semantic priority: head/top/front first,
|
| 197 |
+
then hand/wrist, then alphabetical among the remainder.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
features: the ``info["features"]`` dict from LeRobot v2.1/v3.0.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
``{raw_camera_key: "observation.images.imageN"}`` β may be empty
|
| 204 |
+
if ``features`` declares no image/video entries.
|
| 205 |
+
"""
|
| 206 |
+
visual = [
|
| 207 |
+
k for k, v in features.items()
|
| 208 |
+
if isinstance(v, dict) and v.get("dtype") in ("video", "image")
|
| 209 |
+
]
|
| 210 |
+
ordered = sorted(visual, key=lambda k: (_bucket_for_key(k), k))
|
| 211 |
+
return {k: f"{OBS_IMAGES}.image{i}" for i, k in enumerate(ordered)}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
__all__ = [
|
| 215 |
+
"expand_camera_target",
|
| 216 |
+
"expand_camera_mapping",
|
| 217 |
+
"validate_camera_mapping",
|
| 218 |
+
"infer_image_mapping_from_info",
|
| 219 |
+
]
|
src/schema/dataset_schema.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DatasetSchema dataclass β single source of truth for dataset layout.
|
| 2 |
+
|
| 3 |
+
Everything downstream (transforms, stats remapping, compute_stats,
|
| 4 |
+
deployment) consumes this object instead of dispatching on `robot_type`.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from dataclasses import dataclass, field
|
| 10 |
+
from types import MappingProxyType
|
| 11 |
+
from typing import Any, Mapping, Optional
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
from src.utils.constants import ACTION, OBS_STATE
|
| 16 |
+
|
| 17 |
+
from .annotation_loss import AnnotationLossSpec
|
| 18 |
+
from .arm_layout import ArmLayoutSpec
|
| 19 |
+
from .errors import SchemaDiscoveryError # noqa: F401 # re-export for backward compat
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _freeze_mapping(m: Mapping[str, str]) -> Mapping[str, str]:
|
| 23 |
+
return MappingProxyType(dict(m))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass(frozen=True)
|
| 27 |
+
class DatasetSchema:
|
| 28 |
+
"""Frozen description of a LeRobot v3.0 dataset's concrete layout.
|
| 29 |
+
|
| 30 |
+
Fields:
|
| 31 |
+
schema_id:
|
| 32 |
+
Stable, human-readable identifier, e.g. "labutopia_level3_press_v1".
|
| 33 |
+
Used in stats keying and log messages.
|
| 34 |
+
robot_type:
|
| 35 |
+
The `robot_type` string from info.json. Kept for attribution;
|
| 36 |
+
NOT used for dispatch.
|
| 37 |
+
state_keys / action_keys:
|
| 38 |
+
Concat order of feature keys that make up the state and action
|
| 39 |
+
vectors after any schema-declared canonicalization. Tuples because
|
| 40 |
+
the schema is hashable + worker-pickleable.
|
| 41 |
+
state_dims / action_dims:
|
| 42 |
+
Per-key dimensionalities (parallel to state_keys / action_keys).
|
| 43 |
+
`sum(action_dims) == len(delta_mask)` is enforced.
|
| 44 |
+
source_state_keys / source_action_keys:
|
| 45 |
+
Optional raw parquet columns required to construct the canonical
|
| 46 |
+
state/action keys. Empty means state_keys/action_keys are already
|
| 47 |
+
present on disk. This supports datasets such as AgiBot, whose raw
|
| 48 |
+
16-dim layout is remapped to the 14-dim dual-arm canonical layout
|
| 49 |
+
before normalization and tokenization.
|
| 50 |
+
delta_mask:
|
| 51 |
+
Length `sum(action_dims)` bool tuple. True means "this action dim
|
| 52 |
+
is delta (relative to t0 state)"; False means "absolute" (gripper
|
| 53 |
+
dims typically).
|
| 54 |
+
gripper_action_dims:
|
| 55 |
+
Indices (into the flat concatenated action vector) that correspond
|
| 56 |
+
to gripper/effector channels. Must all be False in delta_mask.
|
| 57 |
+
image_mapping:
|
| 58 |
+
Raw camera key -> unified "observation.images.imageN" target.
|
| 59 |
+
Frozen to MappingProxyType in __post_init__.
|
| 60 |
+
source:
|
| 61 |
+
Which discovery tier produced this schema: "manifest" | "info_names".
|
| 62 |
+
source_path:
|
| 63 |
+
Absolute path of the manifest / info.json that produced this
|
| 64 |
+
schema. Debugging only.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
schema_id: str
|
| 68 |
+
robot_type: str
|
| 69 |
+
state_keys: tuple[str, ...]
|
| 70 |
+
action_keys: tuple[str, ...]
|
| 71 |
+
state_dims: tuple[int, ...]
|
| 72 |
+
action_dims: tuple[int, ...]
|
| 73 |
+
delta_mask: tuple[bool, ...]
|
| 74 |
+
gripper_action_dims: tuple[int, ...]
|
| 75 |
+
image_mapping: Mapping[str, str]
|
| 76 |
+
source: str
|
| 77 |
+
source_path: Optional[str] = None
|
| 78 |
+
# When True, `discover_schema` skips the reverse check that flags info.json
|
| 79 |
+
# video features absent from image_mapping. Needed for multi-robot merged
|
| 80 |
+
# datasets (e.g. robocoin) where info.json declares all source cameras but
|
| 81 |
+
# the schema intentionally picks only a few.
|
| 82 |
+
#
|
| 83 |
+
# This flag is checked POST-build by ``discover_schema``, not during
|
| 84 |
+
# Blueprint construction. Setting it on a blueprint propagates through
|
| 85 |
+
# ``.build()`` to the resulting DatasetSchema; downstream validators read it
|
| 86 |
+
# after the schema object already exists. It does NOT relax any checks
|
| 87 |
+
# performed during Blueprint authoring itself (e.g. dim arithmetic).
|
| 88 |
+
allow_extra_cameras: bool = False
|
| 89 |
+
|
| 90 |
+
# Optional canonical arm-count layout (single-arm 8-dim / dual-arm 14-dim).
|
| 91 |
+
# When set, pretrain/finetune/deploy all use this layout to position
|
| 92 |
+
# gripper(s) at stable canonical indices β see src/schema/arm_layout.py.
|
| 93 |
+
# None = legacy behavior (no canonical remap; gripper_action_dims is the
|
| 94 |
+
# only layout hint).
|
| 95 |
+
arm_layout: Optional[ArmLayoutSpec] = None
|
| 96 |
+
|
| 97 |
+
# Per-dataset auxiliary annotation losses. Empty tuple = pure MSE path
|
| 98 |
+
# (oxe-auge, plain OXE, etc.). Non-empty = additional text-CE losses on
|
| 99 |
+
# the named parquet columns. See src/schema/annotation_loss.py.
|
| 100 |
+
# Decoupled from knowledge_isolation: these CEs always flow to the VLM
|
| 101 |
+
# (that is the whole point β supervise the VLM on high-level labels).
|
| 102 |
+
annotation_losses: tuple[AnnotationLossSpec, ...] = ()
|
| 103 |
+
|
| 104 |
+
# Gripper physical semantics β what the gripper action channel actually
|
| 105 |
+
# represents in the source data. Used by the cross-dataset semantic guard
|
| 106 |
+
# in scripts/train.py:build_dataset to fail-loud when a
|
| 107 |
+
# multi-repo training set mixes incompatible representations (e.g.
|
| 108 |
+
# robointer's velocity command with LabUtopia's metric-width target).
|
| 109 |
+
# q01/q99 normalization aligns scale but not semantics; mixing them
|
| 110 |
+
# without a canonicalizer trains the model on contradictory targets.
|
| 111 |
+
#
|
| 112 |
+
# Values:
|
| 113 |
+
# "velocity" β gripper command is rate-of-change in [-1, +1]
|
| 114 |
+
# (e.g. DROID / robointer convention).
|
| 115 |
+
# "width" β gripper position as physical width (meters or
|
| 116 |
+
# similar metric); LabUtopia / many sim datasets.
|
| 117 |
+
# "position" β gripper position as joint angle / actuator pose
|
| 118 |
+
# (units depend on robot).
|
| 119 |
+
# "open_fraction" β normalized 0..1 where 0=closed, 1=fully open.
|
| 120 |
+
# "binary" β discrete open/close (0 or 1).
|
| 121 |
+
# None β semantics not declared (legacy schemas; the
|
| 122 |
+
# cross-dataset guard skips comparison and only
|
| 123 |
+
# warns once per launch). Set to a real value to
|
| 124 |
+
# opt into the guard.
|
| 125 |
+
gripper_semantic: Optional[str] = None
|
| 126 |
+
|
| 127 |
+
# Optional raw source columns used to build the canonical state/action
|
| 128 |
+
# vectors before NormalizeTransformFn / DeltaActionTransformFn. These are
|
| 129 |
+
# deliberately separate from state_keys/action_keys so downstream model code
|
| 130 |
+
# sees only the canonical contract while adapters still know which parquet
|
| 131 |
+
# columns to project from disk.
|
| 132 |
+
source_state_keys: tuple[str, ...] = ()
|
| 133 |
+
source_action_keys: tuple[str, ...] = ()
|
| 134 |
+
source_state_dims: tuple[int, ...] = ()
|
| 135 |
+
source_action_dims: tuple[int, ...] = ()
|
| 136 |
+
|
| 137 |
+
# Virtual state columns. Maps a schema state key with the mandatory
|
| 138 |
+
# "virtual." prefix (e.g. "virtual.joints_state") to the
|
| 139 |
+
# PHYSICAL parquet column whose same-frame value backs it (e.g.
|
| 140 |
+
# "observation.joints"). The adapter materializes the virtual key in
|
| 141 |
+
# __getitem__ by copying the source column's row β no on-disk column is
|
| 142 |
+
# read under the virtual name, and the stats readers resolve it to the
|
| 143 |
+
# physical column the same way. Use this when a dataset's nominal state
|
| 144 |
+
# column is unusable (oxe-auge_clean_v2: `observation.state` is the raw
|
| 145 |
+
# per-source vector with widths {2, 7, 15, 24} on ~94% of rows) but a
|
| 146 |
+
# reliable physical column holds the true canonical state. Keys must be
|
| 147 |
+
# state_keys members; action keys can never be virtual (the delta/chunk
|
| 148 |
+
# machinery reads disk columns). Frozen to MappingProxyType like
|
| 149 |
+
# image_mapping.
|
| 150 |
+
virtual_state_sources: Mapping[str, str] = field(default_factory=dict)
|
| 151 |
+
|
| 152 |
+
def __post_init__(self) -> None:
|
| 153 |
+
# Normalize mutable inputs into their canonical frozen forms BEFORE
|
| 154 |
+
# validation β otherwise an un-normalized list of AnnotationLossSpec
|
| 155 |
+
# objects could pass the validator but later silently mutate.
|
| 156 |
+
if not isinstance(self.image_mapping, MappingProxyType) and self.image_mapping:
|
| 157 |
+
object.__setattr__(
|
| 158 |
+
self, "image_mapping", _freeze_mapping(self.image_mapping)
|
| 159 |
+
)
|
| 160 |
+
if not isinstance(self.annotation_losses, tuple):
|
| 161 |
+
object.__setattr__(
|
| 162 |
+
self, "annotation_losses", tuple(self.annotation_losses)
|
| 163 |
+
)
|
| 164 |
+
if not isinstance(self.virtual_state_sources, MappingProxyType):
|
| 165 |
+
# Freeze even the EMPTY default β a mutable {} on a frozen
|
| 166 |
+
# dataclass lets callers rebind state sources in place,
|
| 167 |
+
# bypassing validate_schema entirely.
|
| 168 |
+
object.__setattr__(
|
| 169 |
+
self,
|
| 170 |
+
"virtual_state_sources",
|
| 171 |
+
_freeze_mapping(self.virtual_state_sources or {}),
|
| 172 |
+
)
|
| 173 |
+
# Structural validation lives in schema/validate.py (SSOT).
|
| 174 |
+
from .validate import validate_schema
|
| 175 |
+
validate_schema(self)
|
| 176 |
+
|
| 177 |
+
def to_feature_mapping(self) -> dict[str, list[str]]:
|
| 178 |
+
return {
|
| 179 |
+
OBS_STATE: list(self.state_keys),
|
| 180 |
+
ACTION: list(self.action_keys),
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
def to_bool_mask(self) -> torch.BoolTensor:
|
| 184 |
+
return torch.tensor(self.delta_mask, dtype=torch.bool)
|
| 185 |
+
|
| 186 |
+
def to_dict(self) -> dict[str, Any]:
|
| 187 |
+
out = {
|
| 188 |
+
"schema_id": self.schema_id,
|
| 189 |
+
"robot_type": self.robot_type,
|
| 190 |
+
"state_keys": list(self.state_keys),
|
| 191 |
+
"action_keys": list(self.action_keys),
|
| 192 |
+
"state_dims": list(self.state_dims),
|
| 193 |
+
"action_dims": list(self.action_dims),
|
| 194 |
+
"delta_mask": list(self.delta_mask),
|
| 195 |
+
"gripper_action_dims": list(self.gripper_action_dims),
|
| 196 |
+
"image_mapping": dict(self.image_mapping),
|
| 197 |
+
"source": self.source,
|
| 198 |
+
"source_path": self.source_path,
|
| 199 |
+
}
|
| 200 |
+
if self.arm_layout is not None:
|
| 201 |
+
out["arm_layout"] = self.arm_layout.to_dict()
|
| 202 |
+
if self.annotation_losses:
|
| 203 |
+
out["annotation_losses"] = [s.to_dict() for s in self.annotation_losses]
|
| 204 |
+
if self.gripper_semantic is not None:
|
| 205 |
+
out["gripper_semantic"] = self.gripper_semantic
|
| 206 |
+
if self.source_state_keys or self.source_action_keys:
|
| 207 |
+
out["source_state_keys"] = list(self.source_state_keys)
|
| 208 |
+
out["source_action_keys"] = list(self.source_action_keys)
|
| 209 |
+
out["source_state_dims"] = list(self.source_state_dims)
|
| 210 |
+
out["source_action_dims"] = list(self.source_action_dims)
|
| 211 |
+
if self.virtual_state_sources:
|
| 212 |
+
out["virtual_state_sources"] = dict(self.virtual_state_sources)
|
| 213 |
+
return out
|
src/schema/discovery.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Two-tier schema discovery chain.
|
| 2 |
+
|
| 3 |
+
Order: override > manifest > info.json names auto-infer > raise.
|
| 4 |
+
|
| 5 |
+
The previous third tier (RobotConfig registry under src/robots/) was removed:
|
| 6 |
+
dispatching on `robot_type` was fragile (same robot_type in different datasets
|
| 7 |
+
can have different state/action layouts). Every
|
| 8 |
+
dataset must now either (1) ship a meta/labvla_manifest.json, or (2) have
|
| 9 |
+
rich enough info.json `features[*].names` for the auto-inferrer to identify
|
| 10 |
+
gripper dims.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import logging
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
from .dataset_schema import DatasetSchema, SchemaDiscoveryError
|
| 21 |
+
from .manifest import MANIFEST_NAME, load_manifest
|
| 22 |
+
from .infer import try_infer_from_info
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# Annotation-loss fields that are *synthesized at runtime* by a transform
|
| 29 |
+
# (or a VQA adapter) rather than read directly from a parquet column, so they
|
| 30 |
+
# are legitimately absent from info.json ``features``:
|
| 31 |
+
# - "annotation.unified" β built by BuildUnifiedAnnotationTransformFn from
|
| 32 |
+
# the per-annotation.* columns.
|
| 33 |
+
# - "annotation.subtask" β copied from data["task"] by
|
| 34 |
+
# BuildAgiBotSubtaskTransformFn.
|
| 35 |
+
# - "annotation.vqa_answer" β written into the sample dict by the VQA adapter.
|
| 36 |
+
# Any other annotation field is expected to correspond to a real data column;
|
| 37 |
+
# if it is absent from info.json features it is almost certainly a config typo.
|
| 38 |
+
_SYNTHESIZED_ANNOTATION_FIELDS = frozenset({
|
| 39 |
+
"annotation.unified",
|
| 40 |
+
"annotation.subtask",
|
| 41 |
+
"annotation.vqa_answer",
|
| 42 |
+
})
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _load_info_json(root: Path) -> Optional[dict]:
|
| 46 |
+
"""Best-effort load of ``<root>/meta/info.json``. Returns None if missing or
|
| 47 |
+
unreadable so callers can skip schema-vs-info cross-checks gracefully (the
|
| 48 |
+
same posture as ``_warn_if_image_mapping_missing``)."""
|
| 49 |
+
info_path = root / "meta" / "info.json"
|
| 50 |
+
if not info_path.exists():
|
| 51 |
+
return None
|
| 52 |
+
try:
|
| 53 |
+
with open(info_path) as f:
|
| 54 |
+
return json.load(f)
|
| 55 |
+
except Exception as e: # noqa: BLE001
|
| 56 |
+
logger.debug("_load_info_json: could not read %s (%s)", info_path, e)
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _validate_annotation_fields(schema, info: dict, root: Path) -> None:
|
| 61 |
+
"""Fail loud on an annotation-loss field that references a non-existent column.
|
| 62 |
+
|
| 63 |
+
A typo'd ``field`` (e.g. ``annotation.vqa_anwser``) would otherwise pass
|
| 64 |
+
the type/duplicate checks in ``validate_schema``, then tokenization reads
|
| 65 |
+
``data.get(field, "")`` β empty string β all-zero mask β silent 0-CE, so
|
| 66 |
+
the annotation supervision is effectively off while training "succeeds".
|
| 67 |
+
Here, once info.json is available, we reject a field that is neither a
|
| 68 |
+
known transform-synthesized field nor present in info.json ``features``.
|
| 69 |
+
|
| 70 |
+
Note: the authoritative runtime guard (warn-once when a configured field is
|
| 71 |
+
absent from the *materialized* sample dict) belongs in the tokenize
|
| 72 |
+
transform; this is the schema-layer best effort that does not false-positive
|
| 73 |
+
on the runtime-synthesized fields above.
|
| 74 |
+
"""
|
| 75 |
+
losses = getattr(schema, "annotation_losses", ()) or ()
|
| 76 |
+
if not losses:
|
| 77 |
+
return
|
| 78 |
+
features = info.get("features") or {}
|
| 79 |
+
feature_keys = set(features.keys()) if isinstance(features, dict) else set()
|
| 80 |
+
missing = []
|
| 81 |
+
bad_producer = []
|
| 82 |
+
_rt = str(getattr(schema, "robot_type", "") or "").lower()
|
| 83 |
+
_sid = str(getattr(schema, "schema_id", "") or "").lower()
|
| 84 |
+
for spec in losses:
|
| 85 |
+
field = getattr(spec, "field", None)
|
| 86 |
+
if not field:
|
| 87 |
+
continue
|
| 88 |
+
if field in _SYNTHESIZED_ANNOTATION_FIELDS:
|
| 89 |
+
# A legal synthesized field name on the WRONG producer family
|
| 90 |
+
# passes this whitelist but no transform ever materializes it β
|
| 91 |
+
# annotation CE then trains on empty text with an all-zero mask.
|
| 92 |
+
# Bind each synthesized field to the family whose transform/adapter
|
| 93 |
+
# actually produces it.
|
| 94 |
+
if field == "annotation.subtask" and not (
|
| 95 |
+
_rt.startswith("agibot") or _sid.startswith("agibot")
|
| 96 |
+
):
|
| 97 |
+
bad_producer.append(
|
| 98 |
+
f"{field}: only AgiBot schemas have the taskβsubtask "
|
| 99 |
+
f"backfill producer (BuildAgiBotSubtaskTransformFn gates "
|
| 100 |
+
f"on robot_type/schema_id 'agibot*'; this schema is "
|
| 101 |
+
f"{schema.schema_id!r})"
|
| 102 |
+
)
|
| 103 |
+
elif field == "annotation.vqa_answer" and "vqa" not in _sid and "vqa" not in _rt:
|
| 104 |
+
bad_producer.append(
|
| 105 |
+
f"{field}: only the VQA adapter writes this field; "
|
| 106 |
+
f"schema {schema.schema_id!r} is not a VQA schema"
|
| 107 |
+
)
|
| 108 |
+
elif field == "annotation.unified":
|
| 109 |
+
_raw_ann = [k for k in feature_keys
|
| 110 |
+
if k.startswith("annotation.")
|
| 111 |
+
and k not in _SYNTHESIZED_ANNOTATION_FIELDS]
|
| 112 |
+
if not _raw_ann:
|
| 113 |
+
bad_producer.append(
|
| 114 |
+
f"{field}: dataset exposes no raw annotation.* "
|
| 115 |
+
f"columns for BuildUnifiedAnnotationTransformFn to "
|
| 116 |
+
f"consume β the unified text would always be empty"
|
| 117 |
+
)
|
| 118 |
+
continue
|
| 119 |
+
if field not in feature_keys:
|
| 120 |
+
missing.append(field)
|
| 121 |
+
if bad_producer:
|
| 122 |
+
raise SchemaDiscoveryError(
|
| 123 |
+
f"[schema] schema_id={schema.schema_id!r} declares runtime-"
|
| 124 |
+
f"synthesized annotation field(s) without a matching producer "
|
| 125 |
+
f"(H16): " + "; ".join(bad_producer)
|
| 126 |
+
)
|
| 127 |
+
if missing:
|
| 128 |
+
raise SchemaDiscoveryError(
|
| 129 |
+
f"[schema] schema_id={schema.schema_id!r} declares annotation_losses "
|
| 130 |
+
f"on field(s) {missing} that are neither a known runtime-synthesized "
|
| 131 |
+
f"annotation field {sorted(_SYNTHESIZED_ANNOTATION_FIELDS)} nor present "
|
| 132 |
+
f"in info.json features at {root}. This is almost certainly a typo β "
|
| 133 |
+
f"it would otherwise tokenize an empty string and train a silent "
|
| 134 |
+
f"all-zero (0-CE) annotation loss. Available feature keys: "
|
| 135 |
+
f"{sorted(feature_keys)}"
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _warn_if_image_mapping_missing(schema, root: Path) -> None:
|
| 140 |
+
"""Raise SchemaDiscoveryError if manifest image keys don't match info.json.
|
| 141 |
+
|
| 142 |
+
Forward direction: any schema image key absent from info.json features is
|
| 143 |
+
a hard error β the dataset doesn't carry what we promised.
|
| 144 |
+
|
| 145 |
+
Reverse direction: any video feature in info.json that the schema doesn't
|
| 146 |
+
map to an image slot is a hard error too. A dataset with
|
| 147 |
+
3 cameras but a manifest that only declares 1 would silently drop 2
|
| 148 |
+
modalities during training, producing a ckpt that at deploy time expects
|
| 149 |
+
1 camera while the robot hardware sends 3 β classic silent skew.
|
| 150 |
+
"""
|
| 151 |
+
try:
|
| 152 |
+
import json as _json
|
| 153 |
+
from .camera_mapping import expand_camera_source as _expand_src
|
| 154 |
+
with open(root / "meta" / "info.json") as _f:
|
| 155 |
+
info = _json.load(_f)
|
| 156 |
+
features = info.get("features", {})
|
| 157 |
+
# schema.image_mapping LHS is uniformly the canonical
|
| 158 |
+
# ``observation.images.<x>`` form (both halves of
|
| 159 |
+
# expand_camera_mapping). info.json features still use whatever the
|
| 160 |
+
# source dataset declares (v3.0: prefixed; v2.1: often raw
|
| 161 |
+
# ``camera_1_rgb``). Build a reverse lookup so the same physical
|
| 162 |
+
# camera is recognized under either spelling.
|
| 163 |
+
feature_canonical = {_expand_src(k): k for k in features.keys()}
|
| 164 |
+
missing = []
|
| 165 |
+
for src in schema.image_mapping:
|
| 166 |
+
if src in features:
|
| 167 |
+
continue
|
| 168 |
+
if src in feature_canonical:
|
| 169 |
+
continue
|
| 170 |
+
missing.append(src)
|
| 171 |
+
if missing:
|
| 172 |
+
raise SchemaDiscoveryError(
|
| 173 |
+
f"[schema] manifest {schema.source_path} references image keys "
|
| 174 |
+
f"not present in info.json features: {missing}. Either the "
|
| 175 |
+
f"manifest is stale or the info.json was regenerated β reconcile "
|
| 176 |
+
f"them before training."
|
| 177 |
+
)
|
| 178 |
+
# Reverse check: find all image/video features in info.json and confirm
|
| 179 |
+
# every one appears in schema.image_mapping. Only treat dtype=video or
|
| 180 |
+
# keys with an obvious image prefix as camera features, so non-image
|
| 181 |
+
# arrays (state, action, etc.) don't trip the check.
|
| 182 |
+
# schema.allow_extra_cameras=True opts out β used by merged multi-robot
|
| 183 |
+
# datasets (e.g. robocoin) where info.json declares the union of all
|
| 184 |
+
# source cameras but the schema intentionally picks a 3-cam subset.
|
| 185 |
+
if not getattr(schema, "allow_extra_cameras", False):
|
| 186 |
+
declared = set(schema.image_mapping)
|
| 187 |
+
extra_cams = []
|
| 188 |
+
for key, entry in features.items():
|
| 189 |
+
if not isinstance(entry, dict):
|
| 190 |
+
continue
|
| 191 |
+
dtype = entry.get("dtype", "")
|
| 192 |
+
# v2.1 datasets set dtype="image" with a raw key like
|
| 193 |
+
# "camera_1_rgb"; v3.0 sets dtype="image" with the prefixed
|
| 194 |
+
# "observation.images.camera_1_rgb". Both shapes are valid
|
| 195 |
+
# camera features for the reverse check.
|
| 196 |
+
is_camera = dtype == "video" or dtype == "image"
|
| 197 |
+
if not is_camera:
|
| 198 |
+
continue
|
| 199 |
+
# Compare in canonical-prefixed form so a feature key like
|
| 200 |
+
# ``camera_1_rgb`` matches a schema entry
|
| 201 |
+
# ``observation.images.camera_1_rgb`` and vice versa.
|
| 202 |
+
canonical_key = _expand_src(key)
|
| 203 |
+
if canonical_key not in declared and key not in declared:
|
| 204 |
+
extra_cams.append(key)
|
| 205 |
+
if extra_cams:
|
| 206 |
+
raise SchemaDiscoveryError(
|
| 207 |
+
f"[schema] dataset at {root} has camera features not declared "
|
| 208 |
+
f"in the schema's image_mapping: {extra_cams}. Declared cameras: "
|
| 209 |
+
f"{sorted(declared)!r}. Training would silently drop the extra "
|
| 210 |
+
f"modalities and produce a ckpt incompatible with the robot's "
|
| 211 |
+
f"actual camera count at deploy time. Either add the missing "
|
| 212 |
+
f"cameras to the manifest/schema, set "
|
| 213 |
+
f"allow_extra_cameras=True on the schema (for merged multi-"
|
| 214 |
+
f"robot datasets), or explicitly exclude them."
|
| 215 |
+
)
|
| 216 |
+
except SchemaDiscoveryError:
|
| 217 |
+
raise
|
| 218 |
+
except Exception as e:
|
| 219 |
+
# This is the only camera/manifest cross-check; swallowing it at debug
|
| 220 |
+
# level would hide a corrupt info.json entirely.
|
| 221 |
+
logger.warning(
|
| 222 |
+
"_warn_if_image_mapping_missing: camera cross-check skipped (%s) "
|
| 223 |
+
"β info.json may be unreadable/corrupt.", e
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def discover_schema(
|
| 228 |
+
root: str | Path,
|
| 229 |
+
robot_type: Optional[str] = None,
|
| 230 |
+
override: Optional[DatasetSchema] = None,
|
| 231 |
+
) -> DatasetSchema:
|
| 232 |
+
"""Resolve a DatasetSchema for a dataset on disk.
|
| 233 |
+
|
| 234 |
+
Priority order:
|
| 235 |
+
1. `override` argument (for CLI/config injection)
|
| 236 |
+
2. `<root>/meta/labvla_manifest.json` (preferred, explicit)
|
| 237 |
+
3. Auto-infer from `<root>/meta/info.json` `features[*].names`
|
| 238 |
+
4. Raise SchemaDiscoveryError with guidance
|
| 239 |
+
|
| 240 |
+
Args:
|
| 241 |
+
root: dataset root directory (contains `meta/info.json`)
|
| 242 |
+
robot_type: value of `info["robot_type"]` (kept for attribution/logging,
|
| 243 |
+
not for dispatch)
|
| 244 |
+
override: skip discovery, use this schema verbatim (debugging/tests)
|
| 245 |
+
"""
|
| 246 |
+
root = Path(root)
|
| 247 |
+
|
| 248 |
+
if override is not None:
|
| 249 |
+
logger.info(
|
| 250 |
+
"[schema] using override schema_id=%s source=%s",
|
| 251 |
+
override.schema_id, override.source,
|
| 252 |
+
)
|
| 253 |
+
# Still validate image_mapping against info.json β same guard we
|
| 254 |
+
# apply to Tier 1 manifests, so a stale Python schema referencing
|
| 255 |
+
# non-existent camera keys fails loudly instead of KeyError'ing
|
| 256 |
+
# deep inside a DataLoader worker.
|
| 257 |
+
_warn_if_image_mapping_missing(override, root)
|
| 258 |
+
# Reject annotation-loss fields that reference non-existent columns.
|
| 259 |
+
_info = _load_info_json(root)
|
| 260 |
+
if _info is not None:
|
| 261 |
+
_validate_annotation_fields(override, _info, root)
|
| 262 |
+
return override
|
| 263 |
+
|
| 264 |
+
# Tier 1: explicit manifest
|
| 265 |
+
manifest_path = root / "meta" / MANIFEST_NAME
|
| 266 |
+
if manifest_path.exists():
|
| 267 |
+
schema = load_manifest(manifest_path)
|
| 268 |
+
logger.info(
|
| 269 |
+
"[schema] loaded manifest schema_id=%s robot_type=%s from %s",
|
| 270 |
+
schema.schema_id, schema.robot_type, manifest_path,
|
| 271 |
+
)
|
| 272 |
+
_warn_if_image_mapping_missing(schema, root)
|
| 273 |
+
# Reject annotation-loss fields that reference non-existent columns.
|
| 274 |
+
_info = _load_info_json(root)
|
| 275 |
+
if _info is not None:
|
| 276 |
+
_validate_annotation_fields(schema, _info, root)
|
| 277 |
+
return schema
|
| 278 |
+
|
| 279 |
+
# Parse info.json once for tier 2.
|
| 280 |
+
info_path = root / "meta" / "info.json"
|
| 281 |
+
if not info_path.exists():
|
| 282 |
+
raise SchemaDiscoveryError(
|
| 283 |
+
f"[schema] info.json missing at {info_path} β cannot discover schema "
|
| 284 |
+
f"for dataset at {root}"
|
| 285 |
+
)
|
| 286 |
+
with open(info_path) as f:
|
| 287 |
+
info = json.load(f)
|
| 288 |
+
|
| 289 |
+
inferred_robot_type = robot_type or info.get("robot_type")
|
| 290 |
+
|
| 291 |
+
# Tier 2: auto-infer from info.json names
|
| 292 |
+
inferred = try_infer_from_info(info, inferred_robot_type, root)
|
| 293 |
+
if inferred is not None:
|
| 294 |
+
logger.info(
|
| 295 |
+
"[schema] auto-inferred schema_id=%s robot_type=%s from info.json names",
|
| 296 |
+
inferred.schema_id, inferred.robot_type,
|
| 297 |
+
)
|
| 298 |
+
return inferred
|
| 299 |
+
|
| 300 |
+
raise SchemaDiscoveryError(
|
| 301 |
+
f"[schema] could not discover schema for dataset at {root}. Tried:\n"
|
| 302 |
+
f" 1. {manifest_path} β missing\n"
|
| 303 |
+
f" 2. auto-infer from info.json names β insufficient "
|
| 304 |
+
f"(features['action']/['state'].names lacked gripper tokens or were opaque)\n"
|
| 305 |
+
f"To fix: create {manifest_path} describing this dataset's layout. "
|
| 306 |
+
f"See doc/schema_manifest.md for the template."
|
| 307 |
+
)
|