Kensag commited on
Commit
6b446e4
·
verified ·
1 Parent(s): 9281c84

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tools/lerobot_v21_runtime/src/lerobot/cameras/opencv/__init__.py +16 -0
  2. tools/lerobot_v21_runtime/src/lerobot/cameras/opencv/camera_opencv.py +486 -0
  3. tools/lerobot_v21_runtime/src/lerobot/cameras/opencv/configuration_opencv.py +73 -0
  4. tools/lerobot_v21_runtime/src/lerobot/cameras/realsense/__init__.py +16 -0
  5. tools/lerobot_v21_runtime/src/lerobot/cameras/realsense/camera_realsense.py +556 -0
  6. tools/lerobot_v21_runtime/src/lerobot/cameras/realsense/configuration_realsense.py +82 -0
  7. tools/lerobot_v21_runtime/src/lerobot/datasets/push_dataset_to_hub/utils.py +130 -0
  8. tools/lerobot_v21_runtime/src/lerobot/datasets/v2/batch_convert_dataset_v1_to_v2.py +884 -0
  9. tools/lerobot_v21_runtime/src/lerobot/datasets/v2/convert_dataset_v1_to_v2.py +687 -0
  10. tools/lerobot_v21_runtime/src/lerobot/datasets/v21/_remove_language_instruction.py +87 -0
  11. tools/lerobot_v21_runtime/src/lerobot/datasets/v21/batch_convert_dataset_v20_to_v21.py +54 -0
  12. tools/lerobot_v21_runtime/src/lerobot/datasets/v21/convert_dataset_v20_to_v21.py +114 -0
  13. tools/lerobot_v21_runtime/src/lerobot/datasets/v21/convert_stats.py +99 -0
  14. tools/lerobot_v21_runtime/src/lerobot/motors/dynamixel/__init__.py +18 -0
  15. tools/lerobot_v21_runtime/src/lerobot/motors/dynamixel/dynamixel.py +264 -0
  16. tools/lerobot_v21_runtime/src/lerobot/motors/dynamixel/tables.py +197 -0
  17. tools/lerobot_v21_runtime/src/lerobot/motors/feetech/__init__.py +18 -0
  18. tools/lerobot_v21_runtime/src/lerobot/motors/feetech/feetech.py +455 -0
  19. tools/lerobot_v21_runtime/src/lerobot/motors/feetech/tables.py +252 -0
  20. tools/lerobot_v21_runtime/src/lerobot/policies/act/README.md +1 -0
  21. tools/lerobot_v21_runtime/src/lerobot/policies/act/configuration_act.py +186 -0
  22. tools/lerobot_v21_runtime/src/lerobot/policies/act/modeling_act.py +766 -0
  23. tools/lerobot_v21_runtime/src/lerobot/policies/diffusion/README.md +1 -0
  24. tools/lerobot_v21_runtime/src/lerobot/policies/diffusion/configuration_diffusion.py +238 -0
  25. tools/lerobot_v21_runtime/src/lerobot/policies/diffusion/modeling_diffusion.py +771 -0
  26. tools/lerobot_v21_runtime/src/lerobot/policies/pi0/configuration_pi0.py +149 -0
  27. tools/lerobot_v21_runtime/src/lerobot/policies/pi0/conversion_scripts/benchmark.py +82 -0
  28. tools/lerobot_v21_runtime/src/lerobot/policies/pi0/conversion_scripts/compare_with_jax.py +131 -0
  29. tools/lerobot_v21_runtime/src/lerobot/policies/pi0/conversion_scripts/conversion_utils.py +84 -0
  30. tools/lerobot_v21_runtime/src/lerobot/policies/pi0/conversion_scripts/convert_pi0_to_hf_lerobot.py +437 -0
  31. tools/lerobot_v21_runtime/src/lerobot/policies/pi0/flex_attention.py +141 -0
  32. tools/lerobot_v21_runtime/src/lerobot/policies/pi0/modeling_pi0.py +837 -0
  33. tools/lerobot_v21_runtime/src/lerobot/policies/pi0/paligemma_with_expert.py +420 -0
  34. tools/lerobot_v21_runtime/src/lerobot/policies/pi0fast/configuration_pi0fast.py +136 -0
  35. tools/lerobot_v21_runtime/src/lerobot/policies/pi0fast/modeling_pi0fast.py +995 -0
  36. tools/lerobot_v21_runtime/src/lerobot/policies/sac/configuration_sac.py +245 -0
  37. tools/lerobot_v21_runtime/src/lerobot/policies/sac/modeling_sac.py +1117 -0
  38. tools/lerobot_v21_runtime/src/lerobot/policies/sac/reward_model/configuration_classifier.py +76 -0
  39. tools/lerobot_v21_runtime/src/lerobot/policies/sac/reward_model/modeling_classifier.py +323 -0
  40. tools/lerobot_v21_runtime/src/lerobot/policies/smolvla/README.md +1 -0
  41. tools/lerobot_v21_runtime/src/lerobot/policies/smolvla/configuration_smolvla.py +154 -0
  42. tools/lerobot_v21_runtime/src/lerobot/policies/smolvla/modeling_smolvla.py +941 -0
  43. tools/lerobot_v21_runtime/src/lerobot/policies/smolvla/smolvlm_with_expert.py +549 -0
  44. tools/lerobot_v21_runtime/src/lerobot/policies/tdmpc/README.md +1 -0
  45. tools/lerobot_v21_runtime/src/lerobot/policies/tdmpc/configuration_tdmpc.py +220 -0
  46. tools/lerobot_v21_runtime/src/lerobot/policies/tdmpc/modeling_tdmpc.py +839 -0
  47. tools/lerobot_v21_runtime/src/lerobot/policies/vqbet/README.md +1 -0
  48. tools/lerobot_v21_runtime/src/lerobot/policies/vqbet/configuration_vqbet.py +200 -0
  49. tools/lerobot_v21_runtime/src/lerobot/policies/vqbet/modeling_vqbet.py +918 -0
  50. tools/lerobot_v21_runtime/src/lerobot/policies/vqbet/vqbet_utils.py +1462 -0
tools/lerobot_v21_runtime/src/lerobot/cameras/opencv/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .camera_opencv import OpenCVCamera
16
+ from .configuration_opencv import OpenCVCameraConfig
tools/lerobot_v21_runtime/src/lerobot/cameras/opencv/camera_opencv.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
16
+ Provides the OpenCVCamera class for capturing frames from cameras using OpenCV.
17
+ """
18
+
19
+ import logging
20
+ import math
21
+ import os
22
+ import platform
23
+ import time
24
+ from pathlib import Path
25
+ from threading import Event, Lock, Thread
26
+ from typing import Any
27
+
28
+ # Fix MSMF hardware transform compatibility for Windows before importing cv2
29
+ if platform.system() == "Windows" and "OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS" not in os.environ:
30
+ os.environ["OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS"] = "0"
31
+ import cv2
32
+ import numpy as np
33
+
34
+ from lerobot.errors import DeviceAlreadyConnectedError, DeviceNotConnectedError
35
+
36
+ from ..camera import Camera
37
+ from ..utils import get_cv2_backend, get_cv2_rotation
38
+ from .configuration_opencv import ColorMode, OpenCVCameraConfig
39
+
40
+ # NOTE(Steven): The maximum opencv device index depends on your operating system. For instance,
41
+ # if you have 3 cameras, they should be associated to index 0, 1, and 2. This is the case
42
+ # on MacOS. However, on Ubuntu, the indices are different like 6, 16, 23.
43
+ # When you change the USB port or reboot the computer, the operating system might
44
+ # treat the same cameras as new devices. Thus we select a higher bound to search indices.
45
+ MAX_OPENCV_INDEX = 60
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+
50
+ class OpenCVCamera(Camera):
51
+ """
52
+ Manages camera interactions using OpenCV for efficient frame recording.
53
+
54
+ This class provides a high-level interface to connect to, configure, and read
55
+ frames from cameras compatible with OpenCV's VideoCapture. It supports both
56
+ synchronous and asynchronous frame reading.
57
+
58
+ An OpenCVCamera instance requires a camera index (e.g., 0) or a device path
59
+ (e.g., '/dev/video0' on Linux). Camera indices can be unstable across reboots
60
+ or port changes, especially on Linux. Use the provided utility script to find
61
+ available camera indices or paths:
62
+ ```bash
63
+ python -m lerobot.find_cameras opencv
64
+ ```
65
+
66
+ The camera's default settings (FPS, resolution, color mode) are used unless
67
+ overridden in the configuration.
68
+
69
+ Example:
70
+ ```python
71
+ from lerobot.cameras.opencv import OpenCVCamera
72
+ from lerobot.cameras.configuration_opencv import OpenCVCameraConfig, ColorMode, Cv2Rotation
73
+
74
+ # Basic usage with camera index 0
75
+ config = OpenCVCameraConfig(index_or_path=0)
76
+ camera = OpenCVCamera(config)
77
+ camera.connect()
78
+
79
+ # Read 1 frame synchronously
80
+ color_image = camera.read()
81
+ print(color_image.shape)
82
+
83
+ # Read 1 frame asynchronously
84
+ async_image = camera.async_read()
85
+
86
+ # When done, properly disconnect the camera using
87
+ camera.disconnect()
88
+
89
+ # Example with custom settings
90
+ custom_config = OpenCVCameraConfig(
91
+ index_or_path='/dev/video0', # Or use an index
92
+ fps=30,
93
+ width=1280,
94
+ height=720,
95
+ color_mode=ColorMode.RGB,
96
+ rotation=Cv2Rotation.ROTATE_90
97
+ )
98
+ custom_camera = OpenCVCamera(custom_config)
99
+ # ... connect, read, disconnect ...
100
+ ```
101
+ """
102
+
103
+ def __init__(self, config: OpenCVCameraConfig):
104
+ """
105
+ Initializes the OpenCVCamera instance.
106
+
107
+ Args:
108
+ config: The configuration settings for the camera.
109
+ """
110
+ super().__init__(config)
111
+
112
+ self.config = config
113
+ self.index_or_path = config.index_or_path
114
+
115
+ self.fps = config.fps
116
+ self.color_mode = config.color_mode
117
+ self.warmup_s = config.warmup_s
118
+
119
+ self.videocapture: cv2.VideoCapture | None = None
120
+
121
+ self.thread: Thread | None = None
122
+ self.stop_event: Event | None = None
123
+ self.frame_lock: Lock = Lock()
124
+ self.latest_frame: np.ndarray | None = None
125
+ self.new_frame_event: Event = Event()
126
+
127
+ self.rotation: int | None = get_cv2_rotation(config.rotation)
128
+ self.backend: int = get_cv2_backend()
129
+
130
+ if self.height and self.width:
131
+ self.capture_width, self.capture_height = self.width, self.height
132
+ if self.rotation in [cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_90_COUNTERCLOCKWISE]:
133
+ self.capture_width, self.capture_height = self.height, self.width
134
+
135
+ def __str__(self) -> str:
136
+ return f"{self.__class__.__name__}({self.index_or_path})"
137
+
138
+ @property
139
+ def is_connected(self) -> bool:
140
+ """Checks if the camera is currently connected and opened."""
141
+ return isinstance(self.videocapture, cv2.VideoCapture) and self.videocapture.isOpened()
142
+
143
+ def connect(self, warmup: bool = True):
144
+ """
145
+ Connects to the OpenCV camera specified in the configuration.
146
+
147
+ Initializes the OpenCV VideoCapture object, sets desired camera properties
148
+ (FPS, width, height), and performs initial checks.
149
+
150
+ Raises:
151
+ DeviceAlreadyConnectedError: If the camera is already connected.
152
+ ConnectionError: If the specified camera index/path is not found or the camera is found but fails to open.
153
+ RuntimeError: If the camera opens but fails to apply requested FPS/resolution settings.
154
+ """
155
+ if self.is_connected:
156
+ raise DeviceAlreadyConnectedError(f"{self} is already connected.")
157
+
158
+ # Use 1 thread for OpenCV operations to avoid potential conflicts or
159
+ # blocking in multi-threaded applications, especially during data collection.
160
+ cv2.setNumThreads(1)
161
+
162
+ self.videocapture = cv2.VideoCapture(self.index_or_path, self.backend)
163
+
164
+ if not self.videocapture.isOpened():
165
+ self.videocapture.release()
166
+ self.videocapture = None
167
+ raise ConnectionError(
168
+ f"Failed to open {self}."
169
+ f"Run `python -m lerobot.find_cameras opencv` to find available cameras."
170
+ )
171
+
172
+ self._configure_capture_settings()
173
+
174
+ if warmup:
175
+ start_time = time.time()
176
+ while time.time() - start_time < self.warmup_s:
177
+ self.read()
178
+ time.sleep(0.1)
179
+
180
+ logger.info(f"{self} connected.")
181
+
182
+ def _configure_capture_settings(self) -> None:
183
+ """
184
+ Applies the specified FPS, width, and height settings to the connected camera.
185
+
186
+ This method attempts to set the camera properties via OpenCV. It checks if
187
+ the camera successfully applied the settings and raises an error if not.
188
+
189
+ Args:
190
+ fps: The desired frames per second. If None, the setting is skipped.
191
+ width: The desired capture width. If None, the setting is skipped.
192
+ height: The desired capture height. If None, the setting is skipped.
193
+
194
+ Raises:
195
+ RuntimeError: If the camera fails to set any of the specified properties
196
+ to the requested value.
197
+ DeviceNotConnectedError: If the camera is not connected when attempting
198
+ to configure settings.
199
+ """
200
+ if not self.is_connected:
201
+ raise DeviceNotConnectedError(f"Cannot configure settings for {self} as it is not connected.")
202
+
203
+ if self.fps is None:
204
+ self.fps = self.videocapture.get(cv2.CAP_PROP_FPS)
205
+ else:
206
+ self._validate_fps()
207
+
208
+ default_width = int(round(self.videocapture.get(cv2.CAP_PROP_FRAME_WIDTH)))
209
+ default_height = int(round(self.videocapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
210
+
211
+ if self.width is None or self.height is None:
212
+ self.width, self.height = default_width, default_height
213
+ self.capture_width, self.capture_height = default_width, default_height
214
+ if self.rotation in [cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_90_COUNTERCLOCKWISE]:
215
+ self.width, self.height = default_height, default_width
216
+ self.capture_width, self.capture_height = default_width, default_height
217
+ else:
218
+ self._validate_width_and_height()
219
+
220
+ def _validate_fps(self) -> None:
221
+ """Validates and sets the camera's frames per second (FPS)."""
222
+
223
+ success = self.videocapture.set(cv2.CAP_PROP_FPS, float(self.fps))
224
+ actual_fps = self.videocapture.get(cv2.CAP_PROP_FPS)
225
+ # Use math.isclose for robust float comparison
226
+ if not success or not math.isclose(self.fps, actual_fps, rel_tol=1e-3):
227
+ raise RuntimeError(f"{self} failed to set fps={self.fps} ({actual_fps=}).")
228
+
229
+ def _validate_width_and_height(self) -> None:
230
+ """Validates and sets the camera's frame capture width and height."""
231
+
232
+ width_success = self.videocapture.set(cv2.CAP_PROP_FRAME_WIDTH, float(self.capture_width))
233
+ height_success = self.videocapture.set(cv2.CAP_PROP_FRAME_HEIGHT, float(self.capture_height))
234
+
235
+ actual_width = int(round(self.videocapture.get(cv2.CAP_PROP_FRAME_WIDTH)))
236
+ if not width_success or self.capture_width != actual_width:
237
+ raise RuntimeError(
238
+ f"{self} failed to set capture_width={self.capture_width} ({actual_width=}, {width_success=})."
239
+ )
240
+
241
+ actual_height = int(round(self.videocapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
242
+ if not height_success or self.capture_height != actual_height:
243
+ raise RuntimeError(
244
+ f"{self} failed to set capture_height={self.capture_height} ({actual_height=}, {height_success=})."
245
+ )
246
+
247
+ @staticmethod
248
+ def find_cameras() -> list[dict[str, Any]]:
249
+ """
250
+ Detects available OpenCV cameras connected to the system.
251
+
252
+ On Linux, it scans '/dev/video*' paths. On other systems (like macOS, Windows),
253
+ it checks indices from 0 up to `MAX_OPENCV_INDEX`.
254
+
255
+ Returns:
256
+ List[Dict[str, Any]]: A list of dictionaries,
257
+ where each dictionary contains 'type', 'id' (port index or path),
258
+ and the default profile properties (width, height, fps, format).
259
+ """
260
+ found_cameras_info = []
261
+
262
+ if platform.system() == "Linux":
263
+ possible_paths = sorted(Path("/dev").glob("video*"), key=lambda p: p.name)
264
+ targets_to_scan = [str(p) for p in possible_paths]
265
+ else:
266
+ targets_to_scan = list(range(MAX_OPENCV_INDEX))
267
+
268
+ for target in targets_to_scan:
269
+ camera = cv2.VideoCapture(target)
270
+ if camera.isOpened():
271
+ default_width = int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))
272
+ default_height = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT))
273
+ default_fps = camera.get(cv2.CAP_PROP_FPS)
274
+ default_format = camera.get(cv2.CAP_PROP_FORMAT)
275
+ camera_info = {
276
+ "name": f"OpenCV Camera @ {target}",
277
+ "type": "OpenCV",
278
+ "id": target,
279
+ "backend_api": camera.getBackendName(),
280
+ "default_stream_profile": {
281
+ "format": default_format,
282
+ "width": default_width,
283
+ "height": default_height,
284
+ "fps": default_fps,
285
+ },
286
+ }
287
+
288
+ found_cameras_info.append(camera_info)
289
+ camera.release()
290
+
291
+ return found_cameras_info
292
+
293
+ def read(self, color_mode: ColorMode | None = None) -> np.ndarray:
294
+ """
295
+ Reads a single frame synchronously from the camera.
296
+
297
+ This is a blocking call. It waits for the next available frame from the
298
+ camera hardware via OpenCV.
299
+
300
+ Args:
301
+ color_mode (Optional[ColorMode]): If specified, overrides the default
302
+ color mode (`self.color_mode`) for this read operation (e.g.,
303
+ request RGB even if default is BGR).
304
+
305
+ Returns:
306
+ np.ndarray: The captured frame as a NumPy array in the format
307
+ (height, width, channels), using the specified or default
308
+ color mode and applying any configured rotation.
309
+
310
+ Raises:
311
+ DeviceNotConnectedError: If the camera is not connected.
312
+ RuntimeError: If reading the frame from the camera fails or if the
313
+ received frame dimensions don't match expectations before rotation.
314
+ ValueError: If an invalid `color_mode` is requested.
315
+ """
316
+ if not self.is_connected:
317
+ raise DeviceNotConnectedError(f"{self} is not connected.")
318
+
319
+ start_time = time.perf_counter()
320
+
321
+ ret, frame = self.videocapture.read()
322
+
323
+ if not ret or frame is None:
324
+ raise RuntimeError(f"{self} read failed (status={ret}).")
325
+
326
+ processed_frame = self._postprocess_image(frame, color_mode)
327
+
328
+ read_duration_ms = (time.perf_counter() - start_time) * 1e3
329
+ logger.debug(f"{self} read took: {read_duration_ms:.1f}ms")
330
+
331
+ return processed_frame
332
+
333
+ def _postprocess_image(self, image: np.ndarray, color_mode: ColorMode | None = None) -> np.ndarray:
334
+ """
335
+ Applies color conversion, dimension validation, and rotation to a raw frame.
336
+
337
+ Args:
338
+ image (np.ndarray): The raw image frame (expected BGR format from OpenCV).
339
+ color_mode (Optional[ColorMode]): The target color mode (RGB or BGR). If None,
340
+ uses the instance's default `self.color_mode`.
341
+
342
+ Returns:
343
+ np.ndarray: The processed image frame.
344
+
345
+ Raises:
346
+ ValueError: If the requested `color_mode` is invalid.
347
+ RuntimeError: If the raw frame dimensions do not match the configured
348
+ `width` and `height`.
349
+ """
350
+ requested_color_mode = self.color_mode if color_mode is None else color_mode
351
+
352
+ if requested_color_mode not in (ColorMode.RGB, ColorMode.BGR):
353
+ raise ValueError(
354
+ f"Invalid color mode '{requested_color_mode}'. Expected {ColorMode.RGB} or {ColorMode.BGR}."
355
+ )
356
+
357
+ h, w, c = image.shape
358
+
359
+ if h != self.capture_height or w != self.capture_width:
360
+ raise RuntimeError(
361
+ f"{self} frame width={w} or height={h} do not match configured width={self.capture_width} or height={self.capture_height}."
362
+ )
363
+
364
+ if c != 3:
365
+ raise RuntimeError(f"{self} frame channels={c} do not match expected 3 channels (RGB/BGR).")
366
+
367
+ processed_image = image
368
+ if requested_color_mode == ColorMode.RGB:
369
+ processed_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
370
+
371
+ if self.rotation in [cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_90_COUNTERCLOCKWISE, cv2.ROTATE_180]:
372
+ processed_image = cv2.rotate(processed_image, self.rotation)
373
+
374
+ return processed_image
375
+
376
+ def _read_loop(self):
377
+ """
378
+ Internal loop run by the background thread for asynchronous reading.
379
+
380
+ On each iteration:
381
+ 1. Reads a color frame
382
+ 2. Stores result in latest_frame (thread-safe)
383
+ 3. Sets new_frame_event to notify listeners
384
+
385
+ Stops on DeviceNotConnectedError, logs other errors and continues.
386
+ """
387
+ while not self.stop_event.is_set():
388
+ try:
389
+ color_image = self.read()
390
+
391
+ with self.frame_lock:
392
+ self.latest_frame = color_image
393
+ self.new_frame_event.set()
394
+
395
+ except DeviceNotConnectedError:
396
+ break
397
+ except Exception as e:
398
+ logger.warning(f"Error reading frame in background thread for {self}: {e}")
399
+
400
+ def _start_read_thread(self) -> None:
401
+ """Starts or restarts the background read thread if it's not running."""
402
+ if self.thread is not None and self.thread.is_alive():
403
+ self.thread.join(timeout=0.1)
404
+ if self.stop_event is not None:
405
+ self.stop_event.set()
406
+
407
+ self.stop_event = Event()
408
+ self.thread = Thread(target=self._read_loop, args=(), name=f"{self}_read_loop")
409
+ self.thread.daemon = True
410
+ self.thread.start()
411
+
412
+ def _stop_read_thread(self) -> None:
413
+ """Signals the background read thread to stop and waits for it to join."""
414
+ if self.stop_event is not None:
415
+ self.stop_event.set()
416
+
417
+ if self.thread is not None and self.thread.is_alive():
418
+ self.thread.join(timeout=2.0)
419
+
420
+ self.thread = None
421
+ self.stop_event = None
422
+
423
+ def async_read(self, timeout_ms: float = 200) -> np.ndarray:
424
+ """
425
+ Reads the latest available frame asynchronously.
426
+
427
+ This method retrieves the most recent frame captured by the background
428
+ read thread. It does not block waiting for the camera hardware directly,
429
+ but may wait up to timeout_ms for the background thread to provide a frame.
430
+
431
+ Args:
432
+ timeout_ms (float): Maximum time in milliseconds to wait for a frame
433
+ to become available. Defaults to 200ms (0.2 seconds).
434
+
435
+ Returns:
436
+ np.ndarray: The latest captured frame as a NumPy array in the format
437
+ (height, width, channels), processed according to configuration.
438
+
439
+ Raises:
440
+ DeviceNotConnectedError: If the camera is not connected.
441
+ TimeoutError: If no frame becomes available within the specified timeout.
442
+ RuntimeError: If an unexpected error occurs.
443
+ """
444
+ if not self.is_connected:
445
+ raise DeviceNotConnectedError(f"{self} is not connected.")
446
+
447
+ if self.thread is None or not self.thread.is_alive():
448
+ self._start_read_thread()
449
+
450
+ if not self.new_frame_event.wait(timeout=timeout_ms / 1000.0):
451
+ thread_alive = self.thread is not None and self.thread.is_alive()
452
+ raise TimeoutError(
453
+ f"Timed out waiting for frame from camera {self} after {timeout_ms} ms. "
454
+ f"Read thread alive: {thread_alive}."
455
+ )
456
+
457
+ with self.frame_lock:
458
+ frame = self.latest_frame
459
+ self.new_frame_event.clear()
460
+
461
+ if frame is None:
462
+ raise RuntimeError(f"Internal error: Event set but no frame available for {self}.")
463
+
464
+ return frame
465
+
466
+ def disconnect(self):
467
+ """
468
+ Disconnects from the camera and cleans up resources.
469
+
470
+ Stops the background read thread (if running) and releases the OpenCV
471
+ VideoCapture object.
472
+
473
+ Raises:
474
+ DeviceNotConnectedError: If the camera is already disconnected.
475
+ """
476
+ if not self.is_connected and self.thread is None:
477
+ raise DeviceNotConnectedError(f"{self} not connected.")
478
+
479
+ if self.thread is not None:
480
+ self._stop_read_thread()
481
+
482
+ if self.videocapture is not None:
483
+ self.videocapture.release()
484
+ self.videocapture = None
485
+
486
+ logger.info(f"{self} disconnected.")
tools/lerobot_v21_runtime/src/lerobot/cameras/opencv/configuration_opencv.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ from ..configs import CameraConfig, ColorMode, Cv2Rotation
19
+
20
+
21
+ @CameraConfig.register_subclass("opencv")
22
+ @dataclass
23
+ class OpenCVCameraConfig(CameraConfig):
24
+ """Configuration class for OpenCV-based camera devices or video files.
25
+
26
+ This class provides configuration options for cameras accessed through OpenCV,
27
+ supporting both physical camera devices and video files. It includes settings
28
+ for resolution, frame rate, color mode, and image rotation.
29
+
30
+ Example configurations:
31
+ ```python
32
+ # Basic configurations
33
+ OpenCVCameraConfig(0, 30, 1280, 720) # 1280x720 @ 30FPS
34
+ OpenCVCameraConfig(/dev/video4, 60, 640, 480) # 640x480 @ 60FPS
35
+
36
+ # Advanced configurations
37
+ OpenCVCameraConfig(128422271347, 30, 640, 480, rotation=Cv2Rotation.ROTATE_90) # With 90° rotation
38
+ ```
39
+
40
+ Attributes:
41
+ index_or_path: Either an integer representing the camera device index,
42
+ or a Path object pointing to a video file.
43
+ fps: Requested frames per second for the color stream.
44
+ width: Requested frame width in pixels for the color stream.
45
+ height: Requested frame height in pixels for the color stream.
46
+ color_mode: Color mode for image output (RGB or BGR). Defaults to RGB.
47
+ rotation: Image rotation setting (0°, 90°, 180°, or 270°). Defaults to no rotation.
48
+ warmup_s: Time reading frames before returning from connect (in seconds)
49
+
50
+ Note:
51
+ - Only 3-channel color output (RGB/BGR) is currently supported.
52
+ """
53
+
54
+ index_or_path: int | Path
55
+ color_mode: ColorMode = ColorMode.RGB
56
+ rotation: Cv2Rotation = Cv2Rotation.NO_ROTATION
57
+ warmup_s: int = 1
58
+
59
+ def __post_init__(self):
60
+ if self.color_mode not in (ColorMode.RGB, ColorMode.BGR):
61
+ raise ValueError(
62
+ f"`color_mode` is expected to be {ColorMode.RGB.value} or {ColorMode.BGR.value}, but {self.color_mode} is provided."
63
+ )
64
+
65
+ if self.rotation not in (
66
+ Cv2Rotation.NO_ROTATION,
67
+ Cv2Rotation.ROTATE_90,
68
+ Cv2Rotation.ROTATE_180,
69
+ Cv2Rotation.ROTATE_270,
70
+ ):
71
+ raise ValueError(
72
+ f"`rotation` is expected to be in {(Cv2Rotation.NO_ROTATION, Cv2Rotation.ROTATE_90, Cv2Rotation.ROTATE_180, Cv2Rotation.ROTATE_270)}, but {self.rotation} is provided."
73
+ )
tools/lerobot_v21_runtime/src/lerobot/cameras/realsense/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .camera_realsense import RealSenseCamera
16
+ from .configuration_realsense import RealSenseCameraConfig
tools/lerobot_v21_runtime/src/lerobot/cameras/realsense/camera_realsense.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
16
+ Provides the RealSenseCamera class for capturing frames from Intel RealSense cameras.
17
+ """
18
+
19
+ import logging
20
+ import time
21
+ from threading import Event, Lock, Thread
22
+ from typing import Any
23
+
24
+ import cv2
25
+ import numpy as np
26
+
27
+ try:
28
+ import pyrealsense2 as rs
29
+ except Exception as e:
30
+ logging.info(f"Could not import realsense: {e}")
31
+
32
+ from lerobot.errors import DeviceAlreadyConnectedError, DeviceNotConnectedError
33
+
34
+ from ..camera import Camera
35
+ from ..configs import ColorMode
36
+ from ..utils import get_cv2_rotation
37
+ from .configuration_realsense import RealSenseCameraConfig
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+
42
+ class RealSenseCamera(Camera):
43
+ """
44
+ Manages interactions with Intel RealSense cameras for frame and depth recording.
45
+
46
+ This class provides an interface similar to `OpenCVCamera` but tailored for
47
+ RealSense devices, leveraging the `pyrealsense2` library. It uses the camera's
48
+ unique serial number for identification, offering more stability than device
49
+ indices, especially on Linux. It also supports capturing depth maps alongside
50
+ color frames.
51
+
52
+ Use the provided utility script to find available camera indices and default profiles:
53
+ ```bash
54
+ python -m lerobot.find_cameras realsense
55
+ ```
56
+
57
+ A `RealSenseCamera` instance requires a configuration object specifying the
58
+ camera's serial number or a unique device name. If using the name, ensure only
59
+ one camera with that name is connected.
60
+
61
+ The camera's default settings (FPS, resolution, color mode) from the stream
62
+ profile are used unless overridden in the configuration.
63
+
64
+ Example:
65
+ ```python
66
+ from lerobot.cameras.realsense import RealSenseCamera, RealSenseCameraConfig
67
+ from lerobot.cameras import ColorMode, Cv2Rotation
68
+
69
+ # Basic usage with serial number
70
+ config = RealSenseCameraConfig(serial_number_or_name="0123456789") # Replace with actual SN
71
+ camera = RealSenseCamera(config)
72
+ camera.connect()
73
+
74
+ # Read 1 frame synchronously
75
+ color_image = camera.read()
76
+ print(color_image.shape)
77
+
78
+ # Read 1 frame asynchronously
79
+ async_image = camera.async_read()
80
+
81
+ # When done, properly disconnect the camera using
82
+ camera.disconnect()
83
+
84
+ # Example with depth capture and custom settings
85
+ custom_config = RealSenseCameraConfig(
86
+ serial_number_or_name="0123456789", # Replace with actual SN
87
+ fps=30,
88
+ width=1280,
89
+ height=720,
90
+ color_mode=ColorMode.BGR, # Request BGR output
91
+ rotation=Cv2Rotation.NO_ROTATION,
92
+ use_depth=True
93
+ )
94
+ depth_camera = RealSenseCamera(custom_config)
95
+ depth_camera.connect()
96
+
97
+ # Read 1 depth frame
98
+ depth_map = depth_camera.read_depth()
99
+
100
+ # Example using a unique camera name
101
+ name_config = RealSenseCameraConfig(serial_number_or_name="Intel RealSense D435") # If unique
102
+ name_camera = RealSenseCamera(name_config)
103
+ # ... connect, read, disconnect ...
104
+ ```
105
+ """
106
+
107
+ def __init__(self, config: RealSenseCameraConfig):
108
+ """
109
+ Initializes the RealSenseCamera instance.
110
+
111
+ Args:
112
+ config: The configuration settings for the camera.
113
+ """
114
+
115
+ super().__init__(config)
116
+
117
+ self.config = config
118
+
119
+ if config.serial_number_or_name.isdigit():
120
+ self.serial_number = config.serial_number_or_name
121
+ else:
122
+ self.serial_number = self._find_serial_number_from_name(config.serial_number_or_name)
123
+
124
+ self.fps = config.fps
125
+ self.color_mode = config.color_mode
126
+ self.use_depth = config.use_depth
127
+ self.warmup_s = config.warmup_s
128
+
129
+ self.rs_pipeline: rs.pipeline | None = None
130
+ self.rs_profile: rs.pipeline_profile | None = None
131
+
132
+ self.thread: Thread | None = None
133
+ self.stop_event: Event | None = None
134
+ self.frame_lock: Lock = Lock()
135
+ self.latest_frame: np.ndarray | None = None
136
+ self.new_frame_event: Event = Event()
137
+
138
+ self.rotation: int | None = get_cv2_rotation(config.rotation)
139
+
140
+ if self.height and self.width:
141
+ self.capture_width, self.capture_height = self.width, self.height
142
+ if self.rotation in [cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_90_COUNTERCLOCKWISE]:
143
+ self.capture_width, self.capture_height = self.height, self.width
144
+
145
+ def __str__(self) -> str:
146
+ return f"{self.__class__.__name__}({self.serial_number})"
147
+
148
+ @property
149
+ def is_connected(self) -> bool:
150
+ """Checks if the camera pipeline is started and streams are active."""
151
+ return self.rs_pipeline is not None and self.rs_profile is not None
152
+
153
+ def connect(self, warmup: bool = True):
154
+ """
155
+ Connects to the RealSense camera specified in the configuration.
156
+
157
+ Initializes the RealSense pipeline, configures the required streams (color
158
+ and optionally depth), starts the pipeline, and validates the actual stream settings.
159
+
160
+ Raises:
161
+ DeviceAlreadyConnectedError: If the camera is already connected.
162
+ ValueError: If the configuration is invalid (e.g., missing serial/name, name not unique).
163
+ ConnectionError: If the camera is found but fails to start the pipeline or no RealSense devices are detected at all.
164
+ RuntimeError: If the pipeline starts but fails to apply requested settings.
165
+ """
166
+ if self.is_connected:
167
+ raise DeviceAlreadyConnectedError(f"{self} is already connected.")
168
+
169
+ self.rs_pipeline = rs.pipeline()
170
+ rs_config = rs.config()
171
+ self._configure_rs_pipeline_config(rs_config)
172
+
173
+ try:
174
+ self.rs_profile = self.rs_pipeline.start(rs_config)
175
+ except RuntimeError as e:
176
+ self.rs_profile = None
177
+ self.rs_pipeline = None
178
+ raise ConnectionError(
179
+ f"Failed to open {self}."
180
+ "Run `python -m lerobot.find_cameras realsense` to find available cameras."
181
+ ) from e
182
+
183
+ self._configure_capture_settings()
184
+
185
+ if warmup:
186
+ time.sleep(
187
+ 1
188
+ ) # NOTE(Steven): RS cameras need a bit of time to warm up before the first read. If we don't wait, the first read from the warmup will raise.
189
+ start_time = time.time()
190
+ while time.time() - start_time < self.warmup_s:
191
+ self.read()
192
+ time.sleep(0.1)
193
+
194
+ logger.info(f"{self} connected.")
195
+
196
+ @staticmethod
197
+ def find_cameras() -> list[dict[str, Any]]:
198
+ """
199
+ Detects available Intel RealSense cameras connected to the system.
200
+
201
+ Returns:
202
+ List[Dict[str, Any]]: A list of dictionaries,
203
+ where each dictionary contains 'type', 'id' (serial number), 'name',
204
+ firmware version, USB type, and other available specs, and the default profile properties (width, height, fps, format).
205
+
206
+ Raises:
207
+ OSError: If pyrealsense2 is not installed.
208
+ ImportError: If pyrealsense2 is not installed.
209
+ """
210
+ found_cameras_info = []
211
+ context = rs.context()
212
+ devices = context.query_devices()
213
+
214
+ for device in devices:
215
+ camera_info = {
216
+ "name": device.get_info(rs.camera_info.name),
217
+ "type": "RealSense",
218
+ "id": device.get_info(rs.camera_info.serial_number),
219
+ "firmware_version": device.get_info(rs.camera_info.firmware_version),
220
+ "usb_type_descriptor": device.get_info(rs.camera_info.usb_type_descriptor),
221
+ "physical_port": device.get_info(rs.camera_info.physical_port),
222
+ "product_id": device.get_info(rs.camera_info.product_id),
223
+ "product_line": device.get_info(rs.camera_info.product_line),
224
+ }
225
+
226
+ # Get stream profiles for each sensor
227
+ sensors = device.query_sensors()
228
+ for sensor in sensors:
229
+ profiles = sensor.get_stream_profiles()
230
+
231
+ for profile in profiles:
232
+ if profile.is_video_stream_profile() and profile.is_default():
233
+ vprofile = profile.as_video_stream_profile()
234
+ stream_info = {
235
+ "stream_type": vprofile.stream_name(),
236
+ "format": vprofile.format().name,
237
+ "width": vprofile.width(),
238
+ "height": vprofile.height(),
239
+ "fps": vprofile.fps(),
240
+ }
241
+ camera_info["default_stream_profile"] = stream_info
242
+
243
+ found_cameras_info.append(camera_info)
244
+
245
+ return found_cameras_info
246
+
247
+ def _find_serial_number_from_name(self, name: str) -> str:
248
+ """Finds the serial number for a given unique camera name."""
249
+ camera_infos = self.find_cameras()
250
+ found_devices = [cam for cam in camera_infos if str(cam["name"]) == name]
251
+
252
+ if not found_devices:
253
+ available_names = [cam["name"] for cam in camera_infos]
254
+ raise ValueError(
255
+ f"No RealSense camera found with name '{name}'. Available camera names: {available_names}"
256
+ )
257
+
258
+ if len(found_devices) > 1:
259
+ serial_numbers = [dev["serial_number"] for dev in found_devices]
260
+ raise ValueError(
261
+ f"Multiple RealSense cameras found with name '{name}'. "
262
+ f"Please use a unique serial number instead. Found SNs: {serial_numbers}"
263
+ )
264
+
265
+ serial_number = str(found_devices[0]["serial_number"])
266
+ return serial_number
267
+
268
+ def _configure_rs_pipeline_config(self, rs_config):
269
+ """Creates and configures the RealSense pipeline configuration object."""
270
+ rs.config.enable_device(rs_config, self.serial_number)
271
+
272
+ if self.width and self.height and self.fps:
273
+ rs_config.enable_stream(
274
+ rs.stream.color, self.capture_width, self.capture_height, rs.format.rgb8, self.fps
275
+ )
276
+ if self.use_depth:
277
+ rs_config.enable_stream(
278
+ rs.stream.depth, self.capture_width, self.capture_height, rs.format.z16, self.fps
279
+ )
280
+ else:
281
+ rs_config.enable_stream(rs.stream.color)
282
+ if self.use_depth:
283
+ rs_config.enable_stream(rs.stream.depth)
284
+
285
+ def _configure_capture_settings(self) -> None:
286
+ """Sets fps, width, and height from device stream if not already configured.
287
+
288
+ Uses the color stream profile to update unset attributes. Handles rotation by
289
+ swapping width/height when needed. Original capture dimensions are always stored.
290
+
291
+ Raises:
292
+ DeviceNotConnectedError: If device is not connected.
293
+ """
294
+ if not self.is_connected:
295
+ raise DeviceNotConnectedError(f"Cannot validate settings for {self} as it is not connected.")
296
+
297
+ stream = self.rs_profile.get_stream(rs.stream.color).as_video_stream_profile()
298
+
299
+ if self.fps is None:
300
+ self.fps = stream.fps()
301
+
302
+ if self.width is None or self.height is None:
303
+ actual_width = int(round(stream.width()))
304
+ actual_height = int(round(stream.height()))
305
+ if self.rotation in [cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_90_COUNTERCLOCKWISE]:
306
+ self.width, self.height = actual_height, actual_width
307
+ self.capture_width, self.capture_height = actual_width, actual_height
308
+ else:
309
+ self.width, self.height = actual_width, actual_height
310
+ self.capture_width, self.capture_height = actual_width, actual_height
311
+
312
+ def read_depth(self, timeout_ms: int = 200) -> np.ndarray:
313
+ """
314
+ Reads a single frame (depth) synchronously from the camera.
315
+
316
+ This is a blocking call. It waits for a coherent set of frames (depth)
317
+ from the camera hardware via the RealSense pipeline.
318
+
319
+ Args:
320
+ timeout_ms (int): Maximum time in milliseconds to wait for a frame. Defaults to 200ms.
321
+
322
+ Returns:
323
+ np.ndarray: The depth map as a NumPy array (height, width)
324
+ of type `np.uint16` (raw depth values in millimeters) and rotation.
325
+
326
+ Raises:
327
+ DeviceNotConnectedError: If the camera is not connected.
328
+ RuntimeError: If reading frames from the pipeline fails or frames are invalid.
329
+ """
330
+
331
+ if not self.is_connected:
332
+ raise DeviceNotConnectedError(f"{self} is not connected.")
333
+ if not self.use_depth:
334
+ raise RuntimeError(
335
+ f"Failed to capture depth frame '.read_depth()'. Depth stream is not enabled for {self}."
336
+ )
337
+
338
+ start_time = time.perf_counter()
339
+
340
+ ret, frame = self.rs_pipeline.try_wait_for_frames(timeout_ms=timeout_ms)
341
+
342
+ if not ret or frame is None:
343
+ raise RuntimeError(f"{self} read_depth failed (status={ret}).")
344
+
345
+ depth_frame = frame.get_depth_frame()
346
+ depth_map = np.asanyarray(depth_frame.get_data())
347
+
348
+ depth_map_processed = self._postprocess_image(depth_map, depth_frame=True)
349
+
350
+ read_duration_ms = (time.perf_counter() - start_time) * 1e3
351
+ logger.debug(f"{self} read took: {read_duration_ms:.1f}ms")
352
+
353
+ return depth_map_processed
354
+
355
+ def read(self, color_mode: ColorMode | None = None, timeout_ms: int = 200) -> np.ndarray:
356
+ """
357
+ Reads a single frame (color) synchronously from the camera.
358
+
359
+ This is a blocking call. It waits for a coherent set of frames (color)
360
+ from the camera hardware via the RealSense pipeline.
361
+
362
+ Args:
363
+ timeout_ms (int): Maximum time in milliseconds to wait for a frame. Defaults to 200ms.
364
+
365
+ Returns:
366
+ np.ndarray: The captured color frame as a NumPy array
367
+ (height, width, channels), processed according to `color_mode` and rotation.
368
+
369
+ Raises:
370
+ DeviceNotConnectedError: If the camera is not connected.
371
+ RuntimeError: If reading frames from the pipeline fails or frames are invalid.
372
+ ValueError: If an invalid `color_mode` is requested.
373
+ """
374
+
375
+ if not self.is_connected:
376
+ raise DeviceNotConnectedError(f"{self} is not connected.")
377
+
378
+ start_time = time.perf_counter()
379
+
380
+ ret, frame = self.rs_pipeline.try_wait_for_frames(timeout_ms=timeout_ms)
381
+
382
+ if not ret or frame is None:
383
+ raise RuntimeError(f"{self} read failed (status={ret}).")
384
+
385
+ color_frame = frame.get_color_frame()
386
+ color_image_raw = np.asanyarray(color_frame.get_data())
387
+
388
+ color_image_processed = self._postprocess_image(color_image_raw, color_mode)
389
+
390
+ read_duration_ms = (time.perf_counter() - start_time) * 1e3
391
+ logger.debug(f"{self} read took: {read_duration_ms:.1f}ms")
392
+
393
+ return color_image_processed
394
+
395
+ def _postprocess_image(
396
+ self, image: np.ndarray, color_mode: ColorMode | None = None, depth_frame: bool = False
397
+ ) -> np.ndarray:
398
+ """
399
+ Applies color conversion, dimension validation, and rotation to a raw color frame.
400
+
401
+ Args:
402
+ image (np.ndarray): The raw image frame (expected RGB format from RealSense).
403
+ color_mode (Optional[ColorMode]): The target color mode (RGB or BGR). If None,
404
+ uses the instance's default `self.color_mode`.
405
+
406
+ Returns:
407
+ np.ndarray: The processed image frame according to `self.color_mode` and `self.rotation`.
408
+
409
+ Raises:
410
+ ValueError: If the requested `color_mode` is invalid.
411
+ RuntimeError: If the raw frame dimensions do not match the configured
412
+ `width` and `height`.
413
+ """
414
+
415
+ if color_mode and color_mode not in (ColorMode.RGB, ColorMode.BGR):
416
+ raise ValueError(
417
+ f"Invalid requested color mode '{color_mode}'. Expected {ColorMode.RGB} or {ColorMode.BGR}."
418
+ )
419
+
420
+ if depth_frame:
421
+ h, w = image.shape
422
+ else:
423
+ h, w, c = image.shape
424
+
425
+ if c != 3:
426
+ raise RuntimeError(f"{self} frame channels={c} do not match expected 3 channels (RGB/BGR).")
427
+
428
+ if h != self.capture_height or w != self.capture_width:
429
+ raise RuntimeError(
430
+ f"{self} frame width={w} or height={h} do not match configured width={self.capture_width} or height={self.capture_height}."
431
+ )
432
+
433
+ processed_image = image
434
+ if self.color_mode == ColorMode.BGR:
435
+ processed_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
436
+
437
+ if self.rotation in [cv2.ROTATE_90_CLOCKWISE, cv2.ROTATE_90_COUNTERCLOCKWISE, cv2.ROTATE_180]:
438
+ processed_image = cv2.rotate(processed_image, self.rotation)
439
+
440
+ return processed_image
441
+
442
+ def _read_loop(self):
443
+ """
444
+ Internal loop run by the background thread for asynchronous reading.
445
+
446
+ On each iteration:
447
+ 1. Reads a color frame with 500ms timeout
448
+ 2. Stores result in latest_frame (thread-safe)
449
+ 3. Sets new_frame_event to notify listeners
450
+
451
+ Stops on DeviceNotConnectedError, logs other errors and continues.
452
+ """
453
+ while not self.stop_event.is_set():
454
+ try:
455
+ color_image = self.read(timeout_ms=500)
456
+
457
+ with self.frame_lock:
458
+ self.latest_frame = color_image
459
+ self.new_frame_event.set()
460
+
461
+ except DeviceNotConnectedError:
462
+ break
463
+ except Exception as e:
464
+ logger.warning(f"Error reading frame in background thread for {self}: {e}")
465
+
466
+ def _start_read_thread(self) -> None:
467
+ """Starts or restarts the background read thread if it's not running."""
468
+ if self.thread is not None and self.thread.is_alive():
469
+ self.thread.join(timeout=0.1)
470
+ if self.stop_event is not None:
471
+ self.stop_event.set()
472
+
473
+ self.stop_event = Event()
474
+ self.thread = Thread(target=self._read_loop, args=(), name=f"{self}_read_loop")
475
+ self.thread.daemon = True
476
+ self.thread.start()
477
+
478
+ def _stop_read_thread(self):
479
+ """Signals the background read thread to stop and waits for it to join."""
480
+ if self.stop_event is not None:
481
+ self.stop_event.set()
482
+
483
+ if self.thread is not None and self.thread.is_alive():
484
+ self.thread.join(timeout=2.0)
485
+
486
+ self.thread = None
487
+ self.stop_event = None
488
+
489
+ # NOTE(Steven): Missing implementation for depth for now
490
+ def async_read(self, timeout_ms: float = 200) -> np.ndarray:
491
+ """
492
+ Reads the latest available frame data (color) asynchronously.
493
+
494
+ This method retrieves the most recent color frame captured by the background
495
+ read thread. It does not block waiting for the camera hardware directly,
496
+ but may wait up to timeout_ms for the background thread to provide a frame.
497
+
498
+ Args:
499
+ timeout_ms (float): Maximum time in milliseconds to wait for a frame
500
+ to become available. Defaults to 200ms (0.2 seconds).
501
+
502
+ Returns:
503
+ np.ndarray:
504
+ The latest captured frame data (color image), processed according to configuration.
505
+
506
+ Raises:
507
+ DeviceNotConnectedError: If the camera is not connected.
508
+ TimeoutError: If no frame data becomes available within the specified timeout.
509
+ RuntimeError: If the background thread died unexpectedly or another error occurs.
510
+ """
511
+ if not self.is_connected:
512
+ raise DeviceNotConnectedError(f"{self} is not connected.")
513
+
514
+ if self.thread is None or not self.thread.is_alive():
515
+ self._start_read_thread()
516
+
517
+ if not self.new_frame_event.wait(timeout=timeout_ms / 1000.0):
518
+ thread_alive = self.thread is not None and self.thread.is_alive()
519
+ raise TimeoutError(
520
+ f"Timed out waiting for frame from camera {self} after {timeout_ms} ms. "
521
+ f"Read thread alive: {thread_alive}."
522
+ )
523
+
524
+ with self.frame_lock:
525
+ frame = self.latest_frame
526
+ self.new_frame_event.clear()
527
+
528
+ if frame is None:
529
+ raise RuntimeError(f"Internal error: Event set but no frame available for {self}.")
530
+
531
+ return frame
532
+
533
+ def disconnect(self):
534
+ """
535
+ Disconnects from the camera, stops the pipeline, and cleans up resources.
536
+
537
+ Stops the background read thread (if running) and stops the RealSense pipeline.
538
+
539
+ Raises:
540
+ DeviceNotConnectedError: If the camera is already disconnected (pipeline not running).
541
+ """
542
+
543
+ if not self.is_connected and self.thread is None:
544
+ raise DeviceNotConnectedError(
545
+ f"Attempted to disconnect {self}, but it appears already disconnected."
546
+ )
547
+
548
+ if self.thread is not None:
549
+ self._stop_read_thread()
550
+
551
+ if self.rs_pipeline is not None:
552
+ self.rs_pipeline.stop()
553
+ self.rs_pipeline = None
554
+ self.rs_profile = None
555
+
556
+ logger.info(f"{self} disconnected.")
tools/lerobot_v21_runtime/src/lerobot/cameras/realsense/configuration_realsense.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dataclasses import dataclass
16
+
17
+ from ..configs import CameraConfig, ColorMode, Cv2Rotation
18
+
19
+
20
+ @CameraConfig.register_subclass("intelrealsense")
21
+ @dataclass
22
+ class RealSenseCameraConfig(CameraConfig):
23
+ """Configuration class for Intel RealSense cameras.
24
+
25
+ This class provides specialized configuration options for Intel RealSense cameras,
26
+ including support for depth sensing and device identification via serial number or name.
27
+
28
+ Example configurations for Intel RealSense D405:
29
+ ```python
30
+ # Basic configurations
31
+ RealSenseCameraConfig("0123456789", 30, 1280, 720) # 1280x720 @ 30FPS
32
+ RealSenseCameraConfig("0123456789", 60, 640, 480) # 640x480 @ 60FPS
33
+
34
+ # Advanced configurations
35
+ RealSenseCameraConfig("0123456789", 30, 640, 480, use_depth=True) # With depth sensing
36
+ RealSenseCameraConfig("0123456789", 30, 640, 480, rotation=Cv2Rotation.ROTATE_90) # With 90° rotation
37
+ ```
38
+
39
+ Attributes:
40
+ fps: Requested frames per second for the color stream.
41
+ width: Requested frame width in pixels for the color stream.
42
+ height: Requested frame height in pixels for the color stream.
43
+ serial_number_or_name: Unique serial number or human-readable name to identify the camera.
44
+ color_mode: Color mode for image output (RGB or BGR). Defaults to RGB.
45
+ use_depth: Whether to enable depth stream. Defaults to False.
46
+ rotation: Image rotation setting (0°, 90°, 180°, or 270°). Defaults to no rotation.
47
+ warmup_s: Time reading frames before returning from connect (in seconds)
48
+
49
+ Note:
50
+ - Either name or serial_number must be specified.
51
+ - Depth stream configuration (if enabled) will use the same FPS as the color stream.
52
+ - The actual resolution and FPS may be adjusted by the camera to the nearest supported mode.
53
+ - For `fps`, `width` and `height`, either all of them need to be set, or none of them.
54
+ """
55
+
56
+ serial_number_or_name: str
57
+ color_mode: ColorMode = ColorMode.RGB
58
+ use_depth: bool = False
59
+ rotation: Cv2Rotation = Cv2Rotation.NO_ROTATION
60
+ warmup_s: int = 1
61
+
62
+ def __post_init__(self):
63
+ if self.color_mode not in (ColorMode.RGB, ColorMode.BGR):
64
+ raise ValueError(
65
+ f"`color_mode` is expected to be {ColorMode.RGB.value} or {ColorMode.BGR.value}, but {self.color_mode} is provided."
66
+ )
67
+
68
+ if self.rotation not in (
69
+ Cv2Rotation.NO_ROTATION,
70
+ Cv2Rotation.ROTATE_90,
71
+ Cv2Rotation.ROTATE_180,
72
+ Cv2Rotation.ROTATE_270,
73
+ ):
74
+ raise ValueError(
75
+ f"`rotation` is expected to be in {(Cv2Rotation.NO_ROTATION, Cv2Rotation.ROTATE_90, Cv2Rotation.ROTATE_180, Cv2Rotation.ROTATE_270)}, but {self.rotation} is provided."
76
+ )
77
+
78
+ values = (self.fps, self.width, self.height)
79
+ if any(v is not None for v in values) and any(v is None for v in values):
80
+ raise ValueError(
81
+ "For `fps`, `width` and `height`, either all of them need to be set, or none of them."
82
+ )
tools/lerobot_v21_runtime/src/lerobot/datasets/push_dataset_to_hub/utils.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 inspect
17
+ from concurrent.futures import ThreadPoolExecutor
18
+ from pathlib import Path
19
+
20
+ import datasets
21
+ import numpy
22
+ import PIL
23
+ import torch
24
+
25
+ from lerobot.datasets.video_utils import encode_video_frames
26
+
27
+
28
+ def concatenate_episodes(ep_dicts):
29
+ data_dict = {}
30
+
31
+ keys = ep_dicts[0].keys()
32
+ for key in keys:
33
+ if torch.is_tensor(ep_dicts[0][key][0]):
34
+ data_dict[key] = torch.cat([ep_dict[key] for ep_dict in ep_dicts])
35
+ else:
36
+ if key not in data_dict:
37
+ data_dict[key] = []
38
+ for ep_dict in ep_dicts:
39
+ for x in ep_dict[key]:
40
+ data_dict[key].append(x)
41
+
42
+ total_frames = data_dict["frame_index"].shape[0]
43
+ data_dict["index"] = torch.arange(0, total_frames, 1)
44
+ return data_dict
45
+
46
+
47
+ def save_images_concurrently(imgs_array: numpy.array, out_dir: Path, max_workers: int = 4):
48
+ out_dir = Path(out_dir)
49
+ out_dir.mkdir(parents=True, exist_ok=True)
50
+
51
+ def save_image(img_array, i, out_dir):
52
+ img = PIL.Image.fromarray(img_array)
53
+ img.save(str(out_dir / f"frame_{i:06d}.png"), quality=100)
54
+
55
+ num_images = len(imgs_array)
56
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
57
+ [executor.submit(save_image, imgs_array[i], i, out_dir) for i in range(num_images)]
58
+
59
+
60
+ def get_default_encoding() -> dict:
61
+ """Returns the default ffmpeg encoding parameters used by `encode_video_frames`."""
62
+ signature = inspect.signature(encode_video_frames)
63
+ return {
64
+ k: v.default
65
+ for k, v in signature.parameters.items()
66
+ if v.default is not inspect.Parameter.empty and k in ["vcodec", "pix_fmt", "g", "crf"]
67
+ }
68
+
69
+
70
+ def check_repo_id(repo_id: str) -> None:
71
+ if len(repo_id.split("/")) != 2:
72
+ raise ValueError(
73
+ f"""`repo_id` is expected to contain a community or user id `/` the name of the dataset
74
+ (e.g. 'lerobot/pusht'), but contains '{repo_id}'."""
75
+ )
76
+
77
+
78
+ # TODO(aliberts): remove
79
+ def calculate_episode_data_index(hf_dataset: datasets.Dataset) -> dict[str, torch.Tensor]:
80
+ """
81
+ Calculate episode data index for the provided HuggingFace Dataset. Relies on episode_index column of hf_dataset.
82
+
83
+ Parameters:
84
+ - hf_dataset (datasets.Dataset): A HuggingFace dataset containing the episode index.
85
+
86
+ Returns:
87
+ - episode_data_index: A dictionary containing the data index for each episode. The dictionary has two keys:
88
+ - "from": A tensor containing the starting index of each episode.
89
+ - "to": A tensor containing the ending index of each episode.
90
+ """
91
+ episode_data_index = {"from": [], "to": []}
92
+
93
+ current_episode = None
94
+ """
95
+ The episode_index is a list of integers, each representing the episode index of the corresponding example.
96
+ For instance, the following is a valid episode_index:
97
+ [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2]
98
+
99
+ Below, we iterate through the episode_index and populate the episode_data_index dictionary with the starting and
100
+ ending index of each episode. For the episode_index above, the episode_data_index dictionary will look like this:
101
+ {
102
+ "from": [0, 3, 7],
103
+ "to": [3, 7, 12]
104
+ }
105
+ """
106
+ if len(hf_dataset) == 0:
107
+ episode_data_index = {
108
+ "from": torch.tensor([]),
109
+ "to": torch.tensor([]),
110
+ }
111
+ return episode_data_index
112
+ for idx, episode_idx in enumerate(hf_dataset["episode_index"]):
113
+ if episode_idx != current_episode:
114
+ # We encountered a new episode, so we append its starting location to the "from" list
115
+ episode_data_index["from"].append(idx)
116
+ # If this is not the first episode, we append the ending location of the previous episode to the "to" list
117
+ if current_episode is not None:
118
+ episode_data_index["to"].append(idx)
119
+ # Let's keep track of the current episode index
120
+ current_episode = episode_idx
121
+ else:
122
+ # We are still in the same episode, so there is nothing for us to do here
123
+ pass
124
+ # We have reached the end of the dataset, so we append the ending location of the last episode to the "to" list
125
+ episode_data_index["to"].append(idx + 1)
126
+
127
+ for k in ["from", "to"]:
128
+ episode_data_index[k] = torch.tensor(episode_data_index[k])
129
+
130
+ return episode_data_index
tools/lerobot_v21_runtime/src/lerobot/datasets/v2/batch_convert_dataset_v1_to_v2.py ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
18
+ This script is for internal use to convert all datasets under the 'lerobot' hub user account to v2.
19
+
20
+ Note: Since the original Aloha datasets don't use shadow motors, you need to comment those out in
21
+ lerobot/configs/robot/aloha.yaml before running this script.
22
+ """
23
+
24
+ import traceback
25
+ from pathlib import Path
26
+ from textwrap import dedent
27
+
28
+ from lerobot import available_datasets
29
+ from lerobot.datasets.v2.convert_dataset_v1_to_v2 import convert_dataset
30
+ from lerobot.robots.aloha.configuration_aloha import AlohaRobotConfig
31
+
32
+ LOCAL_DIR = Path("data/")
33
+
34
+ # spellchecker:off
35
+ ALOHA_MOBILE_INFO = {
36
+ "robot_config": AlohaRobotConfig(),
37
+ "license": "mit",
38
+ "url": "https://mobile-aloha.github.io/",
39
+ "paper": "https://huggingface.co/papers/2401.02117",
40
+ "citation_bibtex": dedent(r"""
41
+ @inproceedings{fu2024mobile,
42
+ author = {Fu, Zipeng and Zhao, Tony Z. and Finn, Chelsea},
43
+ title = {Mobile ALOHA: Learning Bimanual Mobile Manipulation with Low-Cost Whole-Body Teleoperation},
44
+ booktitle = {arXiv},
45
+ year = {2024},
46
+ }""").lstrip(),
47
+ }
48
+ ALOHA_STATIC_INFO = {
49
+ "robot_config": AlohaRobotConfig(),
50
+ "license": "mit",
51
+ "url": "https://tonyzhaozh.github.io/aloha/",
52
+ "paper": "https://huggingface.co/papers/2304.13705",
53
+ "citation_bibtex": dedent(r"""
54
+ @article{Zhao2023LearningFB,
55
+ title={Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardware},
56
+ author={Tony Zhao and Vikash Kumar and Sergey Levine and Chelsea Finn},
57
+ journal={RSS},
58
+ year={2023},
59
+ volume={abs/2304.13705},
60
+ url={https://huggingface.co/papers/2304.13705}
61
+ }""").lstrip(),
62
+ }
63
+ PUSHT_INFO = {
64
+ "license": "mit",
65
+ "url": "https://diffusion-policy.cs.columbia.edu/",
66
+ "paper": "https://huggingface.co/papers/2303.04137",
67
+ "citation_bibtex": dedent(r"""
68
+ @article{chi2024diffusionpolicy,
69
+ author = {Cheng Chi and Zhenjia Xu and Siyuan Feng and Eric Cousineau and Yilun Du and Benjamin Burchfiel and Russ Tedrake and Shuran Song},
70
+ title ={Diffusion Policy: Visuomotor Policy Learning via Action Diffusion},
71
+ journal = {The International Journal of Robotics Research},
72
+ year = {2024},
73
+ }""").lstrip(),
74
+ }
75
+ XARM_INFO = {
76
+ "license": "mit",
77
+ "url": "https://www.nicklashansen.com/td-mpc/",
78
+ "paper": "https://huggingface.co/papers/2203.04955",
79
+ "citation_bibtex": dedent(r"""
80
+ @inproceedings{Hansen2022tdmpc,
81
+ title={Temporal Difference Learning for Model Predictive Control},
82
+ author={Nicklas Hansen and Xiaolong Wang and Hao Su},
83
+ booktitle={ICML},
84
+ year={2022}
85
+ }
86
+ """),
87
+ }
88
+ UNITREEH_INFO = {
89
+ "license": "apache-2.0",
90
+ }
91
+
92
+ DATASETS = {
93
+ "aloha_mobile_cabinet": {
94
+ "single_task": "Open the top cabinet, store the pot inside it then close the cabinet.",
95
+ **ALOHA_MOBILE_INFO,
96
+ },
97
+ "aloha_mobile_chair": {
98
+ "single_task": "Push the chairs in front of the desk to place them against it.",
99
+ **ALOHA_MOBILE_INFO,
100
+ },
101
+ "aloha_mobile_elevator": {
102
+ "single_task": "Take the elevator to the 1st floor.",
103
+ **ALOHA_MOBILE_INFO,
104
+ },
105
+ "aloha_mobile_shrimp": {
106
+ "single_task": "Sauté the raw shrimp on both sides, then serve it in the bowl.",
107
+ **ALOHA_MOBILE_INFO,
108
+ },
109
+ "aloha_mobile_wash_pan": {
110
+ "single_task": "Pick up the pan, rinse it in the sink and then place it in the drying rack.",
111
+ **ALOHA_MOBILE_INFO,
112
+ },
113
+ "aloha_mobile_wipe_wine": {
114
+ "single_task": "Pick up the wet cloth on the faucet and use it to clean the spilled wine on the table and underneath the glass.",
115
+ **ALOHA_MOBILE_INFO,
116
+ },
117
+ "aloha_static_battery": {
118
+ "single_task": "Place the battery into the slot of the remote controller.",
119
+ **ALOHA_STATIC_INFO,
120
+ },
121
+ "aloha_static_candy": {"single_task": "Pick up the candy and unwrap it.", **ALOHA_STATIC_INFO},
122
+ "aloha_static_coffee": {
123
+ "single_task": "Place the coffee capsule inside the capsule container, then place the cup onto the center of the cup tray, then push the 'Hot Water' and 'Travel Mug' buttons.",
124
+ **ALOHA_STATIC_INFO,
125
+ },
126
+ "aloha_static_coffee_new": {
127
+ "single_task": "Place the coffee capsule inside the capsule container, then place the cup onto the center of the cup tray.",
128
+ **ALOHA_STATIC_INFO,
129
+ },
130
+ "aloha_static_cups_open": {
131
+ "single_task": "Pick up the plastic cup and open its lid.",
132
+ **ALOHA_STATIC_INFO,
133
+ },
134
+ "aloha_static_fork_pick_up": {
135
+ "single_task": "Pick up the fork and place it on the plate.",
136
+ **ALOHA_STATIC_INFO,
137
+ },
138
+ "aloha_static_pingpong_test": {
139
+ "single_task": "Transfer one of the two balls in the right glass into the left glass, then transfer it back to the right glass.",
140
+ **ALOHA_STATIC_INFO,
141
+ },
142
+ "aloha_static_pro_pencil": {
143
+ "single_task": "Pick up the pencil with the right arm, hand it over to the left arm then place it back onto the table.",
144
+ **ALOHA_STATIC_INFO,
145
+ },
146
+ "aloha_static_screw_driver": {
147
+ "single_task": "Pick up the screwdriver with the right arm, hand it over to the left arm then place it into the cup.",
148
+ **ALOHA_STATIC_INFO,
149
+ },
150
+ "aloha_static_tape": {
151
+ "single_task": "Cut a small piece of tape from the tape dispenser then place it on the cardboard box's edge.",
152
+ **ALOHA_STATIC_INFO,
153
+ },
154
+ "aloha_static_thread_velcro": {
155
+ "single_task": "Pick up the velcro cable tie with the left arm, then insert the end of the velcro tie into the other end's loop with the right arm.",
156
+ **ALOHA_STATIC_INFO,
157
+ },
158
+ "aloha_static_towel": {
159
+ "single_task": "Pick up a piece of paper towel and place it on the spilled liquid.",
160
+ **ALOHA_STATIC_INFO,
161
+ },
162
+ "aloha_static_vinh_cup": {
163
+ "single_task": "Pick up the plastic cup with the right arm, then pop its lid open with the left arm.",
164
+ **ALOHA_STATIC_INFO,
165
+ },
166
+ "aloha_static_vinh_cup_left": {
167
+ "single_task": "Pick up the plastic cup with the left arm, then pop its lid open with the right arm.",
168
+ **ALOHA_STATIC_INFO,
169
+ },
170
+ "aloha_static_ziploc_slide": {"single_task": "Slide open the ziploc bag.", **ALOHA_STATIC_INFO},
171
+ "aloha_sim_insertion_scripted": {"single_task": "Insert the peg into the socket.", **ALOHA_STATIC_INFO},
172
+ "aloha_sim_insertion_scripted_image": {
173
+ "single_task": "Insert the peg into the socket.",
174
+ **ALOHA_STATIC_INFO,
175
+ },
176
+ "aloha_sim_insertion_human": {"single_task": "Insert the peg into the socket.", **ALOHA_STATIC_INFO},
177
+ "aloha_sim_insertion_human_image": {
178
+ "single_task": "Insert the peg into the socket.",
179
+ **ALOHA_STATIC_INFO,
180
+ },
181
+ "aloha_sim_transfer_cube_scripted": {
182
+ "single_task": "Pick up the cube with the right arm and transfer it to the left arm.",
183
+ **ALOHA_STATIC_INFO,
184
+ },
185
+ "aloha_sim_transfer_cube_scripted_image": {
186
+ "single_task": "Pick up the cube with the right arm and transfer it to the left arm.",
187
+ **ALOHA_STATIC_INFO,
188
+ },
189
+ "aloha_sim_transfer_cube_human": {
190
+ "single_task": "Pick up the cube with the right arm and transfer it to the left arm.",
191
+ **ALOHA_STATIC_INFO,
192
+ },
193
+ "aloha_sim_transfer_cube_human_image": {
194
+ "single_task": "Pick up the cube with the right arm and transfer it to the left arm.",
195
+ **ALOHA_STATIC_INFO,
196
+ },
197
+ "pusht": {"single_task": "Push the T-shaped block onto the T-shaped target.", **PUSHT_INFO},
198
+ "pusht_image": {"single_task": "Push the T-shaped block onto the T-shaped target.", **PUSHT_INFO},
199
+ "unitreeh1_fold_clothes": {"single_task": "Fold the sweatshirt.", **UNITREEH_INFO},
200
+ "unitreeh1_rearrange_objects": {"single_task": "Put the object into the bin.", **UNITREEH_INFO},
201
+ "unitreeh1_two_robot_greeting": {
202
+ "single_task": "Greet the other robot with a high five.",
203
+ **UNITREEH_INFO,
204
+ },
205
+ "unitreeh1_warehouse": {
206
+ "single_task": "Grab the spray paint on the shelf and place it in the bin on top of the robot dog.",
207
+ **UNITREEH_INFO,
208
+ },
209
+ "xarm_lift_medium": {"single_task": "Pick up the cube and lift it.", **XARM_INFO},
210
+ "xarm_lift_medium_image": {"single_task": "Pick up the cube and lift it.", **XARM_INFO},
211
+ "xarm_lift_medium_replay": {"single_task": "Pick up the cube and lift it.", **XARM_INFO},
212
+ "xarm_lift_medium_replay_image": {"single_task": "Pick up the cube and lift it.", **XARM_INFO},
213
+ "xarm_push_medium": {"single_task": "Push the cube onto the target.", **XARM_INFO},
214
+ "xarm_push_medium_image": {"single_task": "Push the cube onto the target.", **XARM_INFO},
215
+ "xarm_push_medium_replay": {"single_task": "Push the cube onto the target.", **XARM_INFO},
216
+ "xarm_push_medium_replay_image": {"single_task": "Push the cube onto the target.", **XARM_INFO},
217
+ "umi_cup_in_the_wild": {
218
+ "single_task": "Put the cup on the plate.",
219
+ "license": "apache-2.0",
220
+ },
221
+ "asu_table_top": {
222
+ "tasks_col": "language_instruction",
223
+ "license": "mit",
224
+ "paper": "https://link.springer.com/article/10.1007/s10514-023-10129-1",
225
+ "citation_bibtex": dedent(r"""
226
+ @inproceedings{zhou2023modularity,
227
+ title={Modularity through Attention: Efficient Training and Transfer of Language-Conditioned Policies for Robot Manipulation},
228
+ author={Zhou, Yifan and Sonawani, Shubham and Phielipp, Mariano and Stepputtis, Simon and Amor, Heni},
229
+ booktitle={Conference on Robot Learning},
230
+ pages={1684--1695},
231
+ year={2023},
232
+ organization={PMLR}
233
+ }
234
+ @article{zhou2023learning,
235
+ title={Learning modular language-conditioned robot policies through attention},
236
+ author={Zhou, Yifan and Sonawani, Shubham and Phielipp, Mariano and Ben Amor, Heni and Stepputtis, Simon},
237
+ journal={Autonomous Robots},
238
+ pages={1--21},
239
+ year={2023},
240
+ publisher={Springer}
241
+ }""").lstrip(),
242
+ },
243
+ "austin_buds_dataset": {
244
+ "tasks_col": "language_instruction",
245
+ "license": "mit",
246
+ "url": "https://ut-austin-rpl.github.io/BUDS-website/",
247
+ "paper": "https://huggingface.co/papers/2109.13841",
248
+ "citation_bibtex": dedent(r"""
249
+ @article{zhu2022bottom,
250
+ title={Bottom-Up Skill Discovery From Unsegmented Demonstrations for Long-Horizon Robot Manipulation},
251
+ author={Zhu, Yifeng and Stone, Peter and Zhu, Yuke},
252
+ journal={IEEE Robotics and Automation Letters},
253
+ volume={7},
254
+ number={2},
255
+ pages={4126--4133},
256
+ year={2022},
257
+ publisher={IEEE}
258
+ }""").lstrip(),
259
+ },
260
+ "austin_sailor_dataset": {
261
+ "tasks_col": "language_instruction",
262
+ "license": "mit",
263
+ "url": "https://ut-austin-rpl.github.io/sailor/",
264
+ "paper": "https://huggingface.co/papers/2210.11435",
265
+ "citation_bibtex": dedent(r"""
266
+ @inproceedings{nasiriany2022sailor,
267
+ title={Learning and Retrieval from Prior Data for Skill-based Imitation Learning},
268
+ author={Soroush Nasiriany and Tian Gao and Ajay Mandlekar and Yuke Zhu},
269
+ booktitle={Conference on Robot Learning (CoRL)},
270
+ year={2022}
271
+ }""").lstrip(),
272
+ },
273
+ "austin_sirius_dataset": {
274
+ "tasks_col": "language_instruction",
275
+ "license": "mit",
276
+ "url": "https://ut-austin-rpl.github.io/sirius/",
277
+ "paper": "https://huggingface.co/papers/2211.08416",
278
+ "citation_bibtex": dedent(r"""
279
+ @inproceedings{liu2022robot,
280
+ title = {Robot Learning on the Job: Human-in-the-Loop Autonomy and Learning During Deployment},
281
+ author = {Huihan Liu and Soroush Nasiriany and Lance Zhang and Zhiyao Bao and Yuke Zhu},
282
+ booktitle = {Robotics: Science and Systems (RSS)},
283
+ year = {2023}
284
+ }""").lstrip(),
285
+ },
286
+ "berkeley_autolab_ur5": {
287
+ "tasks_col": "language_instruction",
288
+ "license": "cc-by-4.0",
289
+ "url": "https://sites.google.com/view/berkeley-ur5/home",
290
+ "citation_bibtex": dedent(r"""
291
+ @misc{BerkeleyUR5Website,
292
+ title = {Berkeley {UR5} Demonstration Dataset},
293
+ author = {Lawrence Yunliang Chen and Simeon Adebola and Ken Goldberg},
294
+ howpublished = {https://sites.google.com/view/berkeley-ur5/home},
295
+ }""").lstrip(),
296
+ },
297
+ "berkeley_cable_routing": {
298
+ "tasks_col": "language_instruction",
299
+ "license": "cc-by-4.0",
300
+ "url": "https://sites.google.com/view/cablerouting/home",
301
+ "paper": "https://huggingface.co/papers/2307.08927",
302
+ "citation_bibtex": dedent(r"""
303
+ @article{luo2023multistage,
304
+ author = {Jianlan Luo and Charles Xu and Xinyang Geng and Gilbert Feng and Kuan Fang and Liam Tan and Stefan Schaal and Sergey Levine},
305
+ title = {Multi-Stage Cable Routing through Hierarchical Imitation Learning},
306
+ journal = {arXiv pre-print},
307
+ year = {2023},
308
+ url = {https://huggingface.co/papers/2307.08927},
309
+ }""").lstrip(),
310
+ },
311
+ "berkeley_fanuc_manipulation": {
312
+ "tasks_col": "language_instruction",
313
+ "license": "mit",
314
+ "url": "https://sites.google.com/berkeley.edu/fanuc-manipulation",
315
+ "citation_bibtex": dedent(r"""
316
+ @article{fanuc_manipulation2023,
317
+ title={Fanuc Manipulation: A Dataset for Learning-based Manipulation with FANUC Mate 200iD Robot},
318
+ author={Zhu, Xinghao and Tian, Ran and Xu, Chenfeng and Ding, Mingyu and Zhan, Wei and Tomizuka, Masayoshi},
319
+ year={2023},
320
+ }""").lstrip(),
321
+ },
322
+ "berkeley_gnm_cory_hall": {
323
+ "tasks_col": "language_instruction",
324
+ "license": "mit",
325
+ "paper": "https://huggingface.co/papers/1709.10489",
326
+ "citation_bibtex": dedent(r"""
327
+ @inproceedings{kahn2018self,
328
+ title={Self-supervised deep reinforcement learning with generalized computation graphs for robot navigation},
329
+ author={Kahn, Gregory and Villaflor, Adam and Ding, Bosen and Abbeel, Pieter and Levine, Sergey},
330
+ booktitle={2018 IEEE international conference on robotics and automation (ICRA)},
331
+ pages={5129--5136},
332
+ year={2018},
333
+ organization={IEEE}
334
+ }""").lstrip(),
335
+ },
336
+ "berkeley_gnm_recon": {
337
+ "tasks_col": "language_instruction",
338
+ "license": "mit",
339
+ "url": "https://sites.google.com/view/recon-robot",
340
+ "paper": "https://huggingface.co/papers/2104.05859",
341
+ "citation_bibtex": dedent(r"""
342
+ @inproceedings{shah2021rapid,
343
+ title={Rapid Exploration for Open-World Navigation with Latent Goal Models},
344
+ author={Dhruv Shah and Benjamin Eysenbach and Nicholas Rhinehart and Sergey Levine},
345
+ booktitle={5th Annual Conference on Robot Learning },
346
+ year={2021},
347
+ url={https://openreview.net/forum?id=d_SWJhyKfVw}
348
+ }""").lstrip(),
349
+ },
350
+ "berkeley_gnm_sac_son": {
351
+ "tasks_col": "language_instruction",
352
+ "license": "mit",
353
+ "url": "https://sites.google.com/view/SACSoN-review",
354
+ "paper": "https://huggingface.co/papers/2306.01874",
355
+ "citation_bibtex": dedent(r"""
356
+ @article{hirose2023sacson,
357
+ title={SACSoN: Scalable Autonomous Data Collection for Social Navigation},
358
+ author={Hirose, Noriaki and Shah, Dhruv and Sridhar, Ajay and Levine, Sergey},
359
+ journal={arXiv preprint arXiv:2306.01874},
360
+ year={2023}
361
+ }""").lstrip(),
362
+ },
363
+ "berkeley_mvp": {
364
+ "tasks_col": "language_instruction",
365
+ "license": "mit",
366
+ "paper": "https://huggingface.co/papers/2203.06173",
367
+ "citation_bibtex": dedent(r"""
368
+ @InProceedings{Radosavovic2022,
369
+ title = {Real-World Robot Learning with Masked Visual Pre-training},
370
+ author = {Ilija Radosavovic and Tete Xiao and Stephen James and Pieter Abbeel and Jitendra Malik and Trevor Darrell},
371
+ booktitle = {CoRL},
372
+ year = {2022}
373
+ }""").lstrip(),
374
+ },
375
+ "berkeley_rpt": {
376
+ "tasks_col": "language_instruction",
377
+ "license": "mit",
378
+ "paper": "https://huggingface.co/papers/2306.10007",
379
+ "citation_bibtex": dedent(r"""
380
+ @article{Radosavovic2023,
381
+ title={Robot Learning with Sensorimotor Pre-training},
382
+ author={Ilija Radosavovic and Baifeng Shi and Letian Fu and Ken Goldberg and Trevor Darrell and Jitendra Malik},
383
+ year={2023},
384
+ journal={arXiv:2306.10007}
385
+ }""").lstrip(),
386
+ },
387
+ "cmu_franka_exploration_dataset": {
388
+ "tasks_col": "language_instruction",
389
+ "license": "mit",
390
+ "url": "https://human-world-model.github.io/",
391
+ "paper": "https://huggingface.co/papers/2308.10901",
392
+ "citation_bibtex": dedent(r"""
393
+ @inproceedings{mendonca2023structured,
394
+ title={Structured World Models from Human Videos},
395
+ author={Mendonca, Russell and Bahl, Shikhar and Pathak, Deepak},
396
+ journal={RSS},
397
+ year={2023}
398
+ }""").lstrip(),
399
+ },
400
+ "cmu_play_fusion": {
401
+ "tasks_col": "language_instruction",
402
+ "license": "mit",
403
+ "url": "https://play-fusion.github.io/",
404
+ "paper": "https://huggingface.co/papers/2312.04549",
405
+ "citation_bibtex": dedent(r"""
406
+ @inproceedings{chen2023playfusion,
407
+ title={PlayFusion: Skill Acquisition via Diffusion from Language-Annotated Play},
408
+ author={Chen, Lili and Bahl, Shikhar and Pathak, Deepak},
409
+ booktitle={CoRL},
410
+ year={2023}
411
+ }""").lstrip(),
412
+ },
413
+ "cmu_stretch": {
414
+ "tasks_col": "language_instruction",
415
+ "license": "mit",
416
+ "url": "https://robo-affordances.github.io/",
417
+ "paper": "https://huggingface.co/papers/2304.08488",
418
+ "citation_bibtex": dedent(r"""
419
+ @inproceedings{bahl2023affordances,
420
+ title={Affordances from Human Videos as a Versatile Representation for Robotics},
421
+ author={Bahl, Shikhar and Mendonca, Russell and Chen, Lili and Jain, Unnat and Pathak, Deepak},
422
+ booktitle={CVPR},
423
+ year={2023}
424
+ }
425
+ @article{mendonca2023structured,
426
+ title={Structured World Models from Human Videos},
427
+ author={Mendonca, Russell and Bahl, Shikhar and Pathak, Deepak},
428
+ journal={CoRL},
429
+ year={2023}
430
+ }""").lstrip(),
431
+ },
432
+ "columbia_cairlab_pusht_real": {
433
+ "tasks_col": "language_instruction",
434
+ "license": "mit",
435
+ "url": "https://diffusion-policy.cs.columbia.edu/",
436
+ "paper": "https://huggingface.co/papers/2303.04137",
437
+ "citation_bibtex": dedent(r"""
438
+ @inproceedings{chi2023diffusionpolicy,
439
+ title={Diffusion Policy: Visuomotor Policy Learning via Action Diffusion},
440
+ author={Chi, Cheng and Feng, Siyuan and Du, Yilun and Xu, Zhenjia and Cousineau, Eric and Burchfiel, Benjamin and Song, Shuran},
441
+ booktitle={Proceedings of Robotics: Science and Systems (RSS)},
442
+ year={2023}
443
+ }""").lstrip(),
444
+ },
445
+ "conq_hose_manipulation": {
446
+ "tasks_col": "language_instruction",
447
+ "license": "mit",
448
+ "url": "https://sites.google.com/view/conq-hose-manipulation-dataset/home",
449
+ "citation_bibtex": dedent(r"""
450
+ @misc{ConqHoseManipData,
451
+ author={Peter Mitrano and Dmitry Berenson},
452
+ title={Conq Hose Manipulation Dataset, v1.15.0},
453
+ year={2024},
454
+ howpublished={https://sites.google.com/view/conq-hose-manipulation-dataset}
455
+ }""").lstrip(),
456
+ },
457
+ "dlr_edan_shared_control": {
458
+ "tasks_col": "language_instruction",
459
+ "license": "mit",
460
+ "paper": "https://ieeexplore.ieee.org/document/9341156",
461
+ "citation_bibtex": dedent(r"""
462
+ @inproceedings{vogel_edan_2020,
463
+ title = {EDAN - an EMG-Controlled Daily Assistant to Help People with Physical Disabilities},
464
+ language = {en},
465
+ booktitle = {2020 {IEEE}/{RSJ} {International} {Conference} on {Intelligent} {Robots} and {Systems} ({IROS})},
466
+ author = {Vogel, Jörn and Hagengruber, Annette and Iskandar, Maged and Quere, Gabriel and Leipscher, Ulrike and Bustamante, Samuel and Dietrich, Alexander and Hoeppner, Hannes and Leidner, Daniel and Albu-Schäffer, Alin},
467
+ year = {2020}
468
+ }
469
+ @inproceedings{quere_shared_2020,
470
+ address = {Paris, France},
471
+ title = {Shared {Control} {Templates} for {Assistive} {Robotics}},
472
+ language = {en},
473
+ booktitle = {2020 {IEEE} {International} {Conference} on {Robotics} and {Automation} ({ICRA})},
474
+ author = {Quere, Gabriel and Hagengruber, Annette and Iskandar, Maged and Bustamante, Samuel and Leidner, Daniel and Stulp, Freek and Vogel, Joern},
475
+ year = {2020},
476
+ pages = {7},
477
+ }""").lstrip(),
478
+ },
479
+ "dlr_sara_grid_clamp": {
480
+ "tasks_col": "language_instruction",
481
+ "license": "mit",
482
+ "paper": "https://www.researchsquare.com/article/rs-3289569/v1",
483
+ "citation_bibtex": dedent(r"""
484
+ @article{padalkar2023guided,
485
+ title={A guided reinforcement learning approach using shared control templates for learning manipulation skills in the real world},
486
+ author={Padalkar, Abhishek and Quere, Gabriel and Raffin, Antonin and Silv{\'e}rio, Jo{\~a}o and Stulp, Freek},
487
+ journal={Research square preprint rs-3289569/v1},
488
+ year={2023}
489
+ }""").lstrip(),
490
+ },
491
+ "dlr_sara_pour": {
492
+ "tasks_col": "language_instruction",
493
+ "license": "mit",
494
+ "paper": "https://elib.dlr.de/193739/1/padalkar2023rlsct.pdf",
495
+ "citation_bibtex": dedent(r"""
496
+ @inproceedings{padalkar2023guiding,
497
+ title={Guiding Reinforcement Learning with Shared Control Templates},
498
+ author={Padalkar, Abhishek and Quere, Gabriel and Steinmetz, Franz and Raffin, Antonin and Nieuwenhuisen, Matthias and Silv{\'e}rio, Jo{\~a}o and Stulp, Freek},
499
+ booktitle={40th IEEE International Conference on Robotics and Automation, ICRA 2023},
500
+ year={2023},
501
+ organization={IEEE}
502
+ }""").lstrip(),
503
+ },
504
+ "droid_100": {
505
+ "tasks_col": "language_instruction",
506
+ "license": "mit",
507
+ "url": "https://droid-dataset.github.io/",
508
+ "paper": "https://huggingface.co/papers/2403.12945",
509
+ "citation_bibtex": dedent(r"""
510
+ @article{khazatsky2024droid,
511
+ title = {DROID: A Large-Scale In-The-Wild Robot Manipulation Dataset},
512
+ author = {Alexander Khazatsky and Karl Pertsch and Suraj Nair and Ashwin Balakrishna and Sudeep Dasari and Siddharth Karamcheti and Soroush Nasiriany and Mohan Kumar Srirama and Lawrence Yunliang Chen and Kirsty Ellis and Peter David Fagan and Joey Hejna and Masha Itkina and Marion Lepert and Yecheng Jason Ma and Patrick Tree Miller and Jimmy Wu and Suneel Belkhale and Shivin Dass and Huy Ha and Arhan Jain and Abraham Lee and Youngwoon Lee and Marius Memmel and Sungjae Park and Ilija Radosavovic and Kaiyuan Wang and Albert Zhan and Kevin Black and Cheng Chi and Kyle Beltran Hatch and Shan Lin and Jingpei Lu and Jean Mercat and Abdul Rehman and Pannag R Sanketi and Archit Sharma and Cody Simpson and Quan Vuong and Homer Rich Walke and Blake Wulfe and Ted Xiao and Jonathan Heewon Yang and Arefeh Yavary and Tony Z. Zhao and Christopher Agia and Rohan Baijal and Mateo Guaman Castro and Daphne Chen and Qiuyu Chen and Trinity Chung and Jaimyn Drake and Ethan Paul Foster and Jensen Gao and David Antonio Herrera and Minho Heo and Kyle Hsu and Jiaheng Hu and Donovon Jackson and Charlotte Le and Yunshuang Li and Kevin Lin and Roy Lin and Zehan Ma and Abhiram Maddukuri and Suvir Mirchandani and Daniel Morton and Tony Nguyen and Abigail O'Neill and Rosario Scalise and Derick Seale and Victor Son and Stephen Tian and Emi Tran and Andrew E. Wang and Yilin Wu and Annie Xie and Jingyun Yang and Patrick Yin and Yunchu Zhang and Osbert Bastani and Glen Berseth and Jeannette Bohg and Ken Goldberg and Abhinav Gupta and Abhishek Gupta and Dinesh Jayaraman and Joseph J Lim and Jitendra Malik and Roberto Martín-Martín and Subramanian Ramamoorthy and Dorsa Sadigh and Shuran Song and Jiajun Wu and Michael C. Yip and Yuke Zhu and Thomas Kollar and Sergey Levine and Chelsea Finn},
513
+ year = {2024},
514
+ }""").lstrip(),
515
+ },
516
+ "fmb": {
517
+ "tasks_col": "language_instruction",
518
+ "license": "cc-by-4.0",
519
+ "url": "https://functional-manipulation-benchmark.github.io/",
520
+ "paper": "https://huggingface.co/papers/2401.08553",
521
+ "citation_bibtex": dedent(r"""
522
+ @article{luo2024fmb,
523
+ title={FMB: a Functional Manipulation Benchmark for Generalizable Robotic Learning},
524
+ author={Luo, Jianlan and Xu, Charles and Liu, Fangchen and Tan, Liam and Lin, Zipeng and Wu, Jeffrey and Abbeel, Pieter and Levine, Sergey},
525
+ journal={arXiv preprint arXiv:2401.08553},
526
+ year={2024}
527
+ }""").lstrip(),
528
+ },
529
+ "iamlab_cmu_pickup_insert": {
530
+ "tasks_col": "language_instruction",
531
+ "license": "mit",
532
+ "url": "https://openreview.net/forum?id=WuBv9-IGDUA",
533
+ "paper": "https://huggingface.co/papers/2401.14502",
534
+ "citation_bibtex": dedent(r"""
535
+ @inproceedings{saxena2023multiresolution,
536
+ title={Multi-Resolution Sensing for Real-Time Control with Vision-Language Models},
537
+ author={Saumya Saxena and Mohit Sharma and Oliver Kroemer},
538
+ booktitle={7th Annual Conference on Robot Learning},
539
+ year={2023},
540
+ url={https://openreview.net/forum?id=WuBv9-IGDUA}
541
+ }""").lstrip(),
542
+ },
543
+ "imperialcollege_sawyer_wrist_cam": {
544
+ "tasks_col": "language_instruction",
545
+ "license": "mit",
546
+ },
547
+ "jaco_play": {
548
+ "tasks_col": "language_instruction",
549
+ "license": "cc-by-4.0",
550
+ "url": "https://github.com/clvrai/clvr_jaco_play_dataset",
551
+ "citation_bibtex": dedent(r"""
552
+ @software{dass2023jacoplay,
553
+ author = {Dass, Shivin and Yapeter, Jullian and Zhang, Jesse and Zhang, Jiahui
554
+ and Pertsch, Karl and Nikolaidis, Stefanos and Lim, Joseph J.},
555
+ title = {CLVR Jaco Play Dataset},
556
+ url = {https://github.com/clvrai/clvr_jaco_play_dataset},
557
+ version = {1.0.0},
558
+ year = {2023}
559
+ }""").lstrip(),
560
+ },
561
+ "kaist_nonprehensile": {
562
+ "tasks_col": "language_instruction",
563
+ "license": "cc-by-4.0",
564
+ "url": "https://github.com/JaeHyung-Kim/rlds_dataset_builder",
565
+ "citation_bibtex": dedent(r"""
566
+ @article{kimpre,
567
+ title={Pre-and post-contact policy decomposition for non-prehensile manipulation with zero-shot sim-to-real transfer},
568
+ author={Kim, Minchan and Han, Junhyek and Kim, Jaehyung and Kim, Beomjoon},
569
+ booktitle={2023 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS)},
570
+ year={2023},
571
+ organization={IEEE}
572
+ }""").lstrip(),
573
+ },
574
+ "nyu_door_opening_surprising_effectiveness": {
575
+ "tasks_col": "language_instruction",
576
+ "license": "mit",
577
+ "url": "https://jyopari.github.io/VINN/",
578
+ "paper": "https://huggingface.co/papers/2112.01511",
579
+ "citation_bibtex": dedent(r"""
580
+ @misc{pari2021surprising,
581
+ title={The Surprising Effectiveness of Representation Learning for Visual Imitation},
582
+ author={Jyothish Pari and Nur Muhammad Shafiullah and Sridhar Pandian Arunachalam and Lerrel Pinto},
583
+ year={2021},
584
+ eprint={2112.01511},
585
+ archivePrefix={arXiv},
586
+ primaryClass={cs.RO}
587
+ }""").lstrip(),
588
+ },
589
+ "nyu_franka_play_dataset": {
590
+ "tasks_col": "language_instruction",
591
+ "license": "mit",
592
+ "url": "https://play-to-policy.github.io/",
593
+ "paper": "https://huggingface.co/papers/2210.10047",
594
+ "citation_bibtex": dedent(r"""
595
+ @article{cui2022play,
596
+ title = {From Play to Policy: Conditional Behavior Generation from Uncurated Robot Data},
597
+ author = {Cui, Zichen Jeff and Wang, Yibin and Shafiullah, Nur Muhammad Mahi and Pinto, Lerrel},
598
+ journal = {arXiv preprint arXiv:2210.10047},
599
+ year = {2022}
600
+ }""").lstrip(),
601
+ },
602
+ "nyu_rot_dataset": {
603
+ "tasks_col": "language_instruction",
604
+ "license": "mit",
605
+ "url": "https://rot-robot.github.io/",
606
+ "paper": "https://huggingface.co/papers/2206.15469",
607
+ "citation_bibtex": dedent(r"""
608
+ @inproceedings{haldar2023watch,
609
+ title={Watch and match: Supercharging imitation with regularized optimal transport},
610
+ author={Haldar, Siddhant and Mathur, Vaibhav and Yarats, Denis and Pinto, Lerrel},
611
+ booktitle={Conference on Robot Learning},
612
+ pages={32--43},
613
+ year={2023},
614
+ organization={PMLR}
615
+ }""").lstrip(),
616
+ },
617
+ "roboturk": {
618
+ "tasks_col": "language_instruction",
619
+ "license": "mit",
620
+ "url": "https://roboturk.stanford.edu/dataset_real.html",
621
+ "paper": "PAPER",
622
+ "citation_bibtex": dedent(r"""
623
+ @inproceedings{mandlekar2019scaling,
624
+ title={Scaling robot supervision to hundreds of hours with roboturk: Robotic manipulation dataset through human reasoning and dexterity},
625
+ author={Mandlekar, Ajay and Booher, Jonathan and Spero, Max and Tung, Albert and Gupta, Anchit and Zhu, Yuke and Garg, Animesh and Savarese, Silvio and Fei-Fei, Li},
626
+ booktitle={2019 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS)},
627
+ pages={1048--1055},
628
+ year={2019},
629
+ organization={IEEE}
630
+ }""").lstrip(),
631
+ },
632
+ "stanford_hydra_dataset": {
633
+ "tasks_col": "language_instruction",
634
+ "license": "mit",
635
+ "url": "https://sites.google.com/view/hydra-il-2023",
636
+ "paper": "https://huggingface.co/papers/2306.17237",
637
+ "citation_bibtex": dedent(r"""
638
+ @article{belkhale2023hydra,
639
+ title={HYDRA: Hybrid Robot Actions for Imitation Learning},
640
+ author={Belkhale, Suneel and Cui, Yuchen and Sadigh, Dorsa},
641
+ journal={arxiv},
642
+ year={2023}
643
+ }""").lstrip(),
644
+ },
645
+ "stanford_kuka_multimodal_dataset": {
646
+ "tasks_col": "language_instruction",
647
+ "license": "mit",
648
+ "url": "https://sites.google.com/view/visionandtouch",
649
+ "paper": "https://huggingface.co/papers/1810.10191",
650
+ "citation_bibtex": dedent(r"""
651
+ @inproceedings{lee2019icra,
652
+ title={Making sense of vision and touch: Self-supervised learning of multimodal representations for contact-rich tasks},
653
+ author={Lee, Michelle A and Zhu, Yuke and Srinivasan, Krishnan and Shah, Parth and Savarese, Silvio and Fei-Fei, Li and Garg, Animesh and Bohg, Jeannette},
654
+ booktitle={2019 IEEE International Conference on Robotics and Automation (ICRA)},
655
+ year={2019},
656
+ url={https://huggingface.co/papers/1810.10191}
657
+ }""").lstrip(),
658
+ },
659
+ "stanford_robocook": {
660
+ "tasks_col": "language_instruction",
661
+ "license": "mit",
662
+ "url": "https://hshi74.github.io/robocook/",
663
+ "paper": "https://huggingface.co/papers/2306.14447",
664
+ "citation_bibtex": dedent(r"""
665
+ @article{shi2023robocook,
666
+ title={RoboCook: Long-Horizon Elasto-Plastic Object Manipulation with Diverse Tools},
667
+ author={Shi, Haochen and Xu, Huazhe and Clarke, Samuel and Li, Yunzhu and Wu, Jiajun},
668
+ journal={arXiv preprint arXiv:2306.14447},
669
+ year={2023}
670
+ }""").lstrip(),
671
+ },
672
+ "taco_play": {
673
+ "tasks_col": "language_instruction",
674
+ "license": "cc-by-4.0",
675
+ "url": "https://www.kaggle.com/datasets/oiermees/taco-robot",
676
+ "paper": "https://huggingface.co/papers/2209.08959, https://huggingface.co/papers/2210.01911",
677
+ "citation_bibtex": dedent(r"""
678
+ @inproceedings{rosete2022tacorl,
679
+ author = {Erick Rosete-Beas and Oier Mees and Gabriel Kalweit and Joschka Boedecker and Wolfram Burgard},
680
+ title = {Latent Plans for Task Agnostic Offline Reinforcement Learning},
681
+ journal = {Proceedings of the 6th Conference on Robot Learning (CoRL)},
682
+ year = {2022}
683
+ }
684
+ @inproceedings{mees23hulc2,
685
+ title={Grounding Language with Visual Affordances over Unstructured Data},
686
+ author={Oier Mees and Jessica Borja-Diaz and Wolfram Burgard},
687
+ booktitle = {Proceedings of the IEEE International Conference on Robotics and Automation (ICRA)},
688
+ year={2023},
689
+ address = {London, UK}
690
+ }""").lstrip(),
691
+ },
692
+ "tokyo_u_lsmo": {
693
+ "tasks_col": "language_instruction",
694
+ "license": "mit",
695
+ "url": "URL",
696
+ "paper": "https://huggingface.co/papers/2107.05842",
697
+ "citation_bibtex": dedent(r"""
698
+ @Article{Osa22,
699
+ author = {Takayuki Osa},
700
+ journal = {The International Journal of Robotics Research},
701
+ title = {Motion Planning by Learning the Solution Manifold in Trajectory Optimization},
702
+ year = {2022},
703
+ number = {3},
704
+ pages = {291--311},
705
+ volume = {41},
706
+ }""").lstrip(),
707
+ },
708
+ "toto": {
709
+ "tasks_col": "language_instruction",
710
+ "license": "mit",
711
+ "url": "https://toto-benchmark.org/",
712
+ "paper": "https://huggingface.co/papers/2306.00942",
713
+ "citation_bibtex": dedent(r"""
714
+ @inproceedings{zhou2023train,
715
+ author={Zhou, Gaoyue and Dean, Victoria and Srirama, Mohan Kumar and Rajeswaran, Aravind and Pari, Jyothish and Hatch, Kyle and Jain, Aryan and Yu, Tianhe and Abbeel, Pieter and Pinto, Lerrel and Finn, Chelsea and Gupta, Abhinav},
716
+ booktitle={2023 IEEE International Conference on Robotics and Automation (ICRA)},
717
+ title={Train Offline, Test Online: A Real Robot Learning Benchmark},
718
+ year={2023},
719
+ }""").lstrip(),
720
+ },
721
+ "ucsd_kitchen_dataset": {
722
+ "tasks_col": "language_instruction",
723
+ "license": "mit",
724
+ "citation_bibtex": dedent(r"""
725
+ @ARTICLE{ucsd_kitchens,
726
+ author = {Ge Yan, Kris Wu, and Xiaolong Wang},
727
+ title = {{ucsd kitchens Dataset}},
728
+ year = {2023},
729
+ month = {August}
730
+ }""").lstrip(),
731
+ },
732
+ "ucsd_pick_and_place_dataset": {
733
+ "tasks_col": "language_instruction",
734
+ "license": "mit",
735
+ "url": "https://owmcorl.github.io/#",
736
+ "paper": "https://huggingface.co/papers/2310.16029",
737
+ "citation_bibtex": dedent(r"""
738
+ @preprint{Feng2023Finetuning,
739
+ title={Finetuning Offline World Models in the Real World},
740
+ author={Yunhai Feng, Nicklas Hansen, Ziyan Xiong, Chandramouli Rajagopalan, Xiaolong Wang},
741
+ year={2023}
742
+ }""").lstrip(),
743
+ },
744
+ "uiuc_d3field": {
745
+ "tasks_col": "language_instruction",
746
+ "license": "mit",
747
+ "url": "https://robopil.github.io/d3fields/",
748
+ "paper": "https://huggingface.co/papers/2309.16118",
749
+ "citation_bibtex": dedent(r"""
750
+ @article{wang2023d3field,
751
+ title={D^3Field: Dynamic 3D Descriptor Fields for Generalizable Robotic Manipulation},
752
+ author={Wang, Yixuan and Li, Zhuoran and Zhang, Mingtong and Driggs-Campbell, Katherine and Wu, Jiajun and Fei-Fei, Li and Li, Yunzhu},
753
+ journal={arXiv preprint arXiv:},
754
+ year={2023},
755
+ }""").lstrip(),
756
+ },
757
+ "usc_cloth_sim": {
758
+ "tasks_col": "language_instruction",
759
+ "license": "mit",
760
+ "url": "https://uscresl.github.io/dmfd/",
761
+ "paper": "https://huggingface.co/papers/2207.10148",
762
+ "citation_bibtex": dedent(r"""
763
+ @article{salhotra2022dmfd,
764
+ author={Salhotra, Gautam and Liu, I-Chun Arthur and Dominguez-Kuhne, Marcus and Sukhatme, Gaurav S.},
765
+ journal={IEEE Robotics and Automation Letters},
766
+ title={Learning Deformable Object Manipulation From Expert Demonstrations},
767
+ year={2022},
768
+ volume={7},
769
+ number={4},
770
+ pages={8775-8782},
771
+ doi={10.1109/LRA.2022.3187843}
772
+ }""").lstrip(),
773
+ },
774
+ "utaustin_mutex": {
775
+ "tasks_col": "language_instruction",
776
+ "license": "mit",
777
+ "url": "https://ut-austin-rpl.github.io/MUTEX/",
778
+ "paper": "https://huggingface.co/papers/2309.14320",
779
+ "citation_bibtex": dedent(r"""
780
+ @inproceedings{shah2023mutex,
781
+ title={{MUTEX}: Learning Unified Policies from Multimodal Task Specifications},
782
+ author={Rutav Shah and Roberto Mart{\'\i}n-Mart{\'\i}n and Yuke Zhu},
783
+ booktitle={7th Annual Conference on Robot Learning},
784
+ year={2023},
785
+ url={https://openreview.net/forum?id=PwqiqaaEzJ}
786
+ }""").lstrip(),
787
+ },
788
+ "utokyo_pr2_opening_fridge": {
789
+ "tasks_col": "language_instruction",
790
+ "license": "mit",
791
+ "citation_bibtex": dedent(r"""
792
+ @misc{oh2023pr2utokyodatasets,
793
+ author={Jihoon Oh and Naoaki Kanazawa and Kento Kawaharazuka},
794
+ title={X-Embodiment U-Tokyo PR2 Datasets},
795
+ year={2023},
796
+ url={https://github.com/ojh6404/rlds_dataset_builder},
797
+ }""").lstrip(),
798
+ },
799
+ "utokyo_pr2_tabletop_manipulation": {
800
+ "tasks_col": "language_instruction",
801
+ "license": "mit",
802
+ "citation_bibtex": dedent(r"""
803
+ @misc{oh2023pr2utokyodatasets,
804
+ author={Jihoon Oh and Naoaki Kanazawa and Kento Kawaharazuka},
805
+ title={X-Embodiment U-Tokyo PR2 Datasets},
806
+ year={2023},
807
+ url={https://github.com/ojh6404/rlds_dataset_builder},
808
+ }""").lstrip(),
809
+ },
810
+ "utokyo_saytap": {
811
+ "tasks_col": "language_instruction",
812
+ "license": "mit",
813
+ "url": "https://saytap.github.io/",
814
+ "paper": "https://huggingface.co/papers/2306.07580",
815
+ "citation_bibtex": dedent(r"""
816
+ @article{saytap2023,
817
+ author = {Yujin Tang and Wenhao Yu and Jie Tan and Heiga Zen and Aleksandra Faust and
818
+ Tatsuya Harada},
819
+ title = {SayTap: Language to Quadrupedal Locomotion},
820
+ eprint = {arXiv:2306.07580},
821
+ url = {https://saytap.github.io},
822
+ note = {https://saytap.github.io},
823
+ year = {2023}
824
+ }""").lstrip(),
825
+ },
826
+ "utokyo_xarm_bimanual": {
827
+ "tasks_col": "language_instruction",
828
+ "license": "cc-by-4.0",
829
+ "citation_bibtex": dedent(r"""
830
+ @misc{matsushima2023weblab,
831
+ title={Weblab xArm Dataset},
832
+ author={Tatsuya Matsushima and Hiroki Furuta and Yusuke Iwasawa and Yutaka Matsuo},
833
+ year={2023},
834
+ }""").lstrip(),
835
+ },
836
+ "utokyo_xarm_pick_and_place": {
837
+ "tasks_col": "language_instruction",
838
+ "license": "cc-by-4.0",
839
+ "citation_bibtex": dedent(r"""
840
+ @misc{matsushima2023weblab,
841
+ title={Weblab xArm Dataset},
842
+ author={Tatsuya Matsushima and Hiroki Furuta and Yusuke Iwasawa and Yutaka Matsuo},
843
+ year={2023},
844
+ }""").lstrip(),
845
+ },
846
+ "viola": {
847
+ "tasks_col": "language_instruction",
848
+ "license": "mit",
849
+ "url": "https://ut-austin-rpl.github.io/VIOLA/",
850
+ "paper": "https://huggingface.co/papers/2210.11339",
851
+ "citation_bibtex": dedent(r"""
852
+ @article{zhu2022viola,
853
+ title={VIOLA: Imitation Learning for Vision-Based Manipulation with Object Proposal Priors},
854
+ author={Zhu, Yifeng and Joshi, Abhishek and Stone, Peter and Zhu, Yuke},
855
+ journal={6th Annual Conference on Robot Learning (CoRL)},
856
+ year={2022}
857
+ }""").lstrip(),
858
+ },
859
+ }
860
+ # spellchecker:on
861
+
862
+
863
+ def batch_convert():
864
+ status = {}
865
+ logfile = LOCAL_DIR / "conversion_log.txt"
866
+ assert set(DATASETS) == {id_.split("/")[1] for id_ in available_datasets}
867
+ for num, (name, kwargs) in enumerate(DATASETS.items()):
868
+ repo_id = f"lerobot/{name}"
869
+ print(f"\nConverting {repo_id} ({num}/{len(DATASETS)})")
870
+ print("---------------------------------------------------------")
871
+ try:
872
+ convert_dataset(repo_id, LOCAL_DIR, **kwargs)
873
+ status = f"{repo_id}: success."
874
+ with open(logfile, "a") as file:
875
+ file.write(status + "\n")
876
+ except Exception:
877
+ status = f"{repo_id}: failed\n {traceback.format_exc()}"
878
+ with open(logfile, "a") as file:
879
+ file.write(status + "\n")
880
+ continue
881
+
882
+
883
+ if __name__ == "__main__":
884
+ batch_convert()
tools/lerobot_v21_runtime/src/lerobot/datasets/v2/convert_dataset_v1_to_v2.py ADDED
@@ -0,0 +1,687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
18
+ This script will help you convert any LeRobot dataset already pushed to the hub from codebase version 1.6 to
19
+ 2.0. You will be required to provide the 'tasks', which is a short but accurate description in plain English
20
+ for each of the task performed in the dataset. This will allow to easily train models with task-conditioning.
21
+
22
+ We support 3 different scenarios for these tasks (see instructions below):
23
+ 1. Single task dataset: all episodes of your dataset have the same single task.
24
+ 2. Single task episodes: the episodes of your dataset each contain a single task but they can differ from
25
+ one episode to the next.
26
+ 3. Multi task episodes: episodes of your dataset may each contain several different tasks.
27
+
28
+
29
+ Can you can also provide a robot config .yaml file (not mandatory) to this script via the option
30
+ '--robot-config' so that it writes information about the robot (robot type, motors names) this dataset was
31
+ recorded with. For now, only Aloha/Koch type robots are supported with this option.
32
+
33
+
34
+ # 1. Single task dataset
35
+ If your dataset contains a single task, you can simply provide it directly via the CLI with the
36
+ '--single-task' option.
37
+
38
+ Examples:
39
+
40
+ ```bash
41
+ python -m lerobot.datasets.v2.convert_dataset_v1_to_v2 \
42
+ --repo-id lerobot/aloha_sim_insertion_human_image \
43
+ --single-task "Insert the peg into the socket." \
44
+ --robot-config lerobot/configs/robot/aloha.yaml \
45
+ --local-dir data
46
+ ```
47
+
48
+ ```bash
49
+ python -m lerobot.datasets.v2.convert_dataset_v1_to_v2 \
50
+ --repo-id aliberts/koch_tutorial \
51
+ --single-task "Pick the Lego block and drop it in the box on the right." \
52
+ --robot-config lerobot/configs/robot/koch.yaml \
53
+ --local-dir data
54
+ ```
55
+
56
+
57
+ # 2. Single task episodes
58
+ If your dataset is a multi-task dataset, you have two options to provide the tasks to this script:
59
+
60
+ - If your dataset already contains a language instruction column in its parquet file, you can simply provide
61
+ this column's name with the '--tasks-col' arg.
62
+
63
+ Example:
64
+
65
+ ```bash
66
+ python -m lerobot.datasets.v2.convert_dataset_v1_to_v2 \
67
+ --repo-id lerobot/stanford_kuka_multimodal_dataset \
68
+ --tasks-col "language_instruction" \
69
+ --local-dir data
70
+ ```
71
+
72
+ - If your dataset doesn't contain a language instruction, you should provide the path to a .json file with the
73
+ '--tasks-path' arg. This file should have the following structure where keys correspond to each
74
+ episode_index in the dataset, and values are the language instruction for that episode.
75
+
76
+ Example:
77
+
78
+ ```json
79
+ {
80
+ "0": "Do something",
81
+ "1": "Do something else",
82
+ "2": "Do something",
83
+ "3": "Go there",
84
+ ...
85
+ }
86
+ ```
87
+
88
+ # 3. Multi task episodes
89
+ If you have multiple tasks per episodes, your dataset should contain a language instruction column in its
90
+ parquet file, and you must provide this column's name with the '--tasks-col' arg.
91
+
92
+ Example:
93
+
94
+ ```bash
95
+ python -m lerobot.datasets.v2.convert_dataset_v1_to_v2 \
96
+ --repo-id lerobot/stanford_kuka_multimodal_dataset \
97
+ --tasks-col "language_instruction" \
98
+ --local-dir data
99
+ ```
100
+ """
101
+
102
+ import argparse
103
+ import contextlib
104
+ import filecmp
105
+ import json
106
+ import logging
107
+ import math
108
+ import shutil
109
+ import subprocess
110
+ import tempfile
111
+ from pathlib import Path
112
+
113
+ import datasets
114
+ import pyarrow.compute as pc
115
+ import pyarrow.parquet as pq
116
+ import torch
117
+ from datasets import Dataset
118
+ from huggingface_hub import HfApi
119
+ from huggingface_hub.errors import EntryNotFoundError, HfHubHTTPError
120
+ from safetensors.torch import load_file
121
+
122
+ from lerobot.datasets.utils import (
123
+ DEFAULT_CHUNK_SIZE,
124
+ DEFAULT_PARQUET_PATH,
125
+ DEFAULT_VIDEO_PATH,
126
+ EPISODES_PATH,
127
+ INFO_PATH,
128
+ STATS_PATH,
129
+ TASKS_PATH,
130
+ create_branch,
131
+ create_lerobot_dataset_card,
132
+ flatten_dict,
133
+ get_safe_version,
134
+ load_json,
135
+ unflatten_dict,
136
+ write_json,
137
+ write_jsonlines,
138
+ )
139
+ from lerobot.datasets.video_utils import (
140
+ VideoFrame, # noqa: F401
141
+ get_image_pixel_channels,
142
+ get_video_info,
143
+ )
144
+ from lerobot.robots import RobotConfig
145
+
146
+ V16 = "v1.6"
147
+ V20 = "v2.0"
148
+
149
+ GITATTRIBUTES_REF = "aliberts/gitattributes_reference"
150
+ V1_VIDEO_FILE = "{video_key}_episode_{episode_index:06d}.mp4"
151
+ V1_INFO_PATH = "meta_data/info.json"
152
+ V1_STATS_PATH = "meta_data/stats.safetensors"
153
+
154
+
155
+ def parse_robot_config(robot_cfg: RobotConfig) -> tuple[str, dict]:
156
+ if robot_cfg.type in ["aloha", "koch"]:
157
+ state_names = [
158
+ f"{arm}_{motor}" if len(robot_cfg.follower_arms) > 1 else motor
159
+ for arm in robot_cfg.follower_arms
160
+ for motor in robot_cfg.follower_arms[arm].motors
161
+ ]
162
+ action_names = [
163
+ # f"{arm}_{motor}" for arm in ["left", "right"] for motor in robot_cfg["leader_arms"][arm]["motors"]
164
+ f"{arm}_{motor}" if len(robot_cfg.leader_arms) > 1 else motor
165
+ for arm in robot_cfg.leader_arms
166
+ for motor in robot_cfg.leader_arms[arm].motors
167
+ ]
168
+ # elif robot_cfg["robot_type"] == "stretch3": TODO
169
+ else:
170
+ raise NotImplementedError(
171
+ "Please provide robot_config={'robot_type': ..., 'names': ...} directly to convert_dataset()."
172
+ )
173
+
174
+ return {
175
+ "robot_type": robot_cfg.type,
176
+ "names": {
177
+ "observation.state": state_names,
178
+ "observation.effort": state_names,
179
+ "action": action_names,
180
+ },
181
+ }
182
+
183
+
184
+ def convert_stats_to_json(v1_dir: Path, v2_dir: Path) -> None:
185
+ safetensor_path = v1_dir / V1_STATS_PATH
186
+ stats = load_file(safetensor_path)
187
+ serialized_stats = {key: value.tolist() for key, value in stats.items()}
188
+ serialized_stats = unflatten_dict(serialized_stats)
189
+
190
+ json_path = v2_dir / STATS_PATH
191
+ json_path.parent.mkdir(exist_ok=True, parents=True)
192
+ with open(json_path, "w") as f:
193
+ json.dump(serialized_stats, f, indent=4)
194
+
195
+ # Sanity check
196
+ with open(json_path) as f:
197
+ stats_json = json.load(f)
198
+
199
+ stats_json = flatten_dict(stats_json)
200
+ stats_json = {key: torch.tensor(value) for key, value in stats_json.items()}
201
+ for key in stats:
202
+ torch.testing.assert_close(stats_json[key], stats[key])
203
+
204
+
205
+ def get_features_from_hf_dataset(
206
+ dataset: Dataset, robot_config: RobotConfig | None = None
207
+ ) -> dict[str, list]:
208
+ robot_config = parse_robot_config(robot_config)
209
+ features = {}
210
+ for key, ft in dataset.features.items():
211
+ if isinstance(ft, datasets.Value):
212
+ dtype = ft.dtype
213
+ shape = (1,)
214
+ names = None
215
+ if isinstance(ft, datasets.Sequence):
216
+ assert isinstance(ft.feature, datasets.Value)
217
+ dtype = ft.feature.dtype
218
+ shape = (ft.length,)
219
+ motor_names = (
220
+ robot_config["names"][key] if robot_config else [f"motor_{i}" for i in range(ft.length)]
221
+ )
222
+ assert len(motor_names) == shape[0]
223
+ names = {"motors": motor_names}
224
+ elif isinstance(ft, datasets.Image):
225
+ dtype = "image"
226
+ image = dataset[0][key] # Assuming first row
227
+ channels = get_image_pixel_channels(image)
228
+ shape = (image.height, image.width, channels)
229
+ names = ["height", "width", "channels"]
230
+ elif ft._type == "VideoFrame":
231
+ dtype = "video"
232
+ shape = None # Add shape later
233
+ names = ["height", "width", "channels"]
234
+
235
+ features[key] = {
236
+ "dtype": dtype,
237
+ "shape": shape,
238
+ "names": names,
239
+ }
240
+
241
+ return features
242
+
243
+
244
+ def add_task_index_by_episodes(dataset: Dataset, tasks_by_episodes: dict) -> tuple[Dataset, list[str]]:
245
+ df = dataset.to_pandas()
246
+ tasks = list(set(tasks_by_episodes.values()))
247
+ tasks_to_task_index = {task: task_idx for task_idx, task in enumerate(tasks)}
248
+ episodes_to_task_index = {ep_idx: tasks_to_task_index[task] for ep_idx, task in tasks_by_episodes.items()}
249
+ df["task_index"] = df["episode_index"].map(episodes_to_task_index).astype(int)
250
+
251
+ features = dataset.features
252
+ features["task_index"] = datasets.Value(dtype="int64")
253
+ dataset = Dataset.from_pandas(df, features=features, split="train")
254
+ return dataset, tasks
255
+
256
+
257
+ def add_task_index_from_tasks_col(
258
+ dataset: Dataset, tasks_col: str
259
+ ) -> tuple[Dataset, dict[str, list[str]], list[str]]:
260
+ df = dataset.to_pandas()
261
+
262
+ # HACK: This is to clean some of the instructions in our version of Open X datasets
263
+ prefix_to_clean = "tf.Tensor(b'"
264
+ suffix_to_clean = "', shape=(), dtype=string)"
265
+ df[tasks_col] = df[tasks_col].str.removeprefix(prefix_to_clean).str.removesuffix(suffix_to_clean)
266
+
267
+ # Create task_index col
268
+ tasks_by_episode = df.groupby("episode_index")[tasks_col].unique().apply(lambda x: x.tolist()).to_dict()
269
+ tasks = df[tasks_col].unique().tolist()
270
+ tasks_to_task_index = {task: idx for idx, task in enumerate(tasks)}
271
+ df["task_index"] = df[tasks_col].map(tasks_to_task_index).astype(int)
272
+
273
+ # Build the dataset back from df
274
+ features = dataset.features
275
+ features["task_index"] = datasets.Value(dtype="int64")
276
+ dataset = Dataset.from_pandas(df, features=features, split="train")
277
+ dataset = dataset.remove_columns(tasks_col)
278
+
279
+ return dataset, tasks, tasks_by_episode
280
+
281
+
282
+ def split_parquet_by_episodes(
283
+ dataset: Dataset,
284
+ total_episodes: int,
285
+ total_chunks: int,
286
+ output_dir: Path,
287
+ ) -> list:
288
+ table = dataset.data.table
289
+ episode_lengths = []
290
+ for ep_chunk in range(total_chunks):
291
+ ep_chunk_start = DEFAULT_CHUNK_SIZE * ep_chunk
292
+ ep_chunk_end = min(DEFAULT_CHUNK_SIZE * (ep_chunk + 1), total_episodes)
293
+ chunk_dir = "/".join(DEFAULT_PARQUET_PATH.split("/")[:-1]).format(episode_chunk=ep_chunk)
294
+ (output_dir / chunk_dir).mkdir(parents=True, exist_ok=True)
295
+ for ep_idx in range(ep_chunk_start, ep_chunk_end):
296
+ ep_table = table.filter(pc.equal(table["episode_index"], ep_idx))
297
+ episode_lengths.insert(ep_idx, len(ep_table))
298
+ output_file = output_dir / DEFAULT_PARQUET_PATH.format(
299
+ episode_chunk=ep_chunk, episode_index=ep_idx
300
+ )
301
+ pq.write_table(ep_table, output_file)
302
+
303
+ return episode_lengths
304
+
305
+
306
+ def move_videos(
307
+ repo_id: str,
308
+ video_keys: list[str],
309
+ total_episodes: int,
310
+ total_chunks: int,
311
+ work_dir: Path,
312
+ clean_gittatributes: Path,
313
+ branch: str = "main",
314
+ ) -> None:
315
+ """
316
+ HACK: Since HfApi() doesn't provide a way to move files directly in a repo, this function will run git
317
+ commands to fetch git lfs video files references to move them into subdirectories without having to
318
+ actually download them.
319
+ """
320
+ _lfs_clone(repo_id, work_dir, branch)
321
+
322
+ videos_moved = False
323
+ video_files = [str(f.relative_to(work_dir)) for f in work_dir.glob("videos*/*.mp4")]
324
+ if len(video_files) == 0:
325
+ video_files = [str(f.relative_to(work_dir)) for f in work_dir.glob("videos*/*/*/*.mp4")]
326
+ videos_moved = True # Videos have already been moved
327
+
328
+ assert len(video_files) == total_episodes * len(video_keys)
329
+
330
+ lfs_untracked_videos = _get_lfs_untracked_videos(work_dir, video_files)
331
+
332
+ current_gittatributes = work_dir / ".gitattributes"
333
+ if not filecmp.cmp(current_gittatributes, clean_gittatributes, shallow=False):
334
+ fix_gitattributes(work_dir, current_gittatributes, clean_gittatributes)
335
+
336
+ if lfs_untracked_videos:
337
+ fix_lfs_video_files_tracking(work_dir, video_files)
338
+
339
+ if videos_moved:
340
+ return
341
+
342
+ video_dirs = sorted(work_dir.glob("videos*/"))
343
+ for ep_chunk in range(total_chunks):
344
+ ep_chunk_start = DEFAULT_CHUNK_SIZE * ep_chunk
345
+ ep_chunk_end = min(DEFAULT_CHUNK_SIZE * (ep_chunk + 1), total_episodes)
346
+ for vid_key in video_keys:
347
+ chunk_dir = "/".join(DEFAULT_VIDEO_PATH.split("/")[:-1]).format(
348
+ episode_chunk=ep_chunk, video_key=vid_key
349
+ )
350
+ (work_dir / chunk_dir).mkdir(parents=True, exist_ok=True)
351
+
352
+ for ep_idx in range(ep_chunk_start, ep_chunk_end):
353
+ target_path = DEFAULT_VIDEO_PATH.format(
354
+ episode_chunk=ep_chunk, video_key=vid_key, episode_index=ep_idx
355
+ )
356
+ video_file = V1_VIDEO_FILE.format(video_key=vid_key, episode_index=ep_idx)
357
+ if len(video_dirs) == 1:
358
+ video_path = video_dirs[0] / video_file
359
+ else:
360
+ for dir in video_dirs:
361
+ if (dir / video_file).is_file():
362
+ video_path = dir / video_file
363
+ break
364
+
365
+ video_path.rename(work_dir / target_path)
366
+
367
+ commit_message = "Move video files into chunk subdirectories"
368
+ subprocess.run(["git", "add", "."], cwd=work_dir, check=True)
369
+ subprocess.run(["git", "commit", "-m", commit_message], cwd=work_dir, check=True)
370
+ subprocess.run(["git", "push"], cwd=work_dir, check=True)
371
+
372
+
373
+ def fix_lfs_video_files_tracking(work_dir: Path, lfs_untracked_videos: list[str]) -> None:
374
+ """
375
+ HACK: This function fixes the tracking by git lfs which was not properly set on some repos. In that case,
376
+ there's no other option than to download the actual files and reupload them with lfs tracking.
377
+ """
378
+ for i in range(0, len(lfs_untracked_videos), 100):
379
+ files = lfs_untracked_videos[i : i + 100]
380
+ try:
381
+ subprocess.run(["git", "rm", "--cached", *files], cwd=work_dir, capture_output=True, check=True)
382
+ except subprocess.CalledProcessError as e:
383
+ print("git rm --cached ERROR:")
384
+ print(e.stderr)
385
+ subprocess.run(["git", "add", *files], cwd=work_dir, check=True)
386
+
387
+ commit_message = "Track video files with git lfs"
388
+ subprocess.run(["git", "commit", "-m", commit_message], cwd=work_dir, check=True)
389
+ subprocess.run(["git", "push"], cwd=work_dir, check=True)
390
+
391
+
392
+ def fix_gitattributes(work_dir: Path, current_gittatributes: Path, clean_gittatributes: Path) -> None:
393
+ shutil.copyfile(clean_gittatributes, current_gittatributes)
394
+ subprocess.run(["git", "add", ".gitattributes"], cwd=work_dir, check=True)
395
+ subprocess.run(["git", "commit", "-m", "Fix .gitattributes"], cwd=work_dir, check=True)
396
+ subprocess.run(["git", "push"], cwd=work_dir, check=True)
397
+
398
+
399
+ def _lfs_clone(repo_id: str, work_dir: Path, branch: str) -> None:
400
+ subprocess.run(["git", "lfs", "install"], cwd=work_dir, check=True)
401
+ repo_url = f"https://huggingface.co/datasets/{repo_id}"
402
+ env = {"GIT_LFS_SKIP_SMUDGE": "1"} # Prevent downloading LFS files
403
+ subprocess.run(
404
+ ["git", "clone", "--branch", branch, "--single-branch", "--depth", "1", repo_url, str(work_dir)],
405
+ check=True,
406
+ env=env,
407
+ )
408
+
409
+
410
+ def _get_lfs_untracked_videos(work_dir: Path, video_files: list[str]) -> list[str]:
411
+ lfs_tracked_files = subprocess.run(
412
+ ["git", "lfs", "ls-files", "-n"], cwd=work_dir, capture_output=True, text=True, check=True
413
+ )
414
+ lfs_tracked_files = set(lfs_tracked_files.stdout.splitlines())
415
+ return [f for f in video_files if f not in lfs_tracked_files]
416
+
417
+
418
+ def get_videos_info(repo_id: str, local_dir: Path, video_keys: list[str], branch: str) -> dict:
419
+ # Assumes first episode
420
+ video_files = [
421
+ DEFAULT_VIDEO_PATH.format(episode_chunk=0, video_key=vid_key, episode_index=0)
422
+ for vid_key in video_keys
423
+ ]
424
+ hub_api = HfApi()
425
+ hub_api.snapshot_download(
426
+ repo_id=repo_id, repo_type="dataset", local_dir=local_dir, revision=branch, allow_patterns=video_files
427
+ )
428
+ videos_info_dict = {}
429
+ for vid_key, vid_path in zip(video_keys, video_files, strict=True):
430
+ videos_info_dict[vid_key] = get_video_info(local_dir / vid_path)
431
+
432
+ return videos_info_dict
433
+
434
+
435
+ def convert_dataset(
436
+ repo_id: str,
437
+ local_dir: Path,
438
+ single_task: str | None = None,
439
+ tasks_path: Path | None = None,
440
+ tasks_col: Path | None = None,
441
+ robot_config: RobotConfig | None = None,
442
+ test_branch: str | None = None,
443
+ **card_kwargs,
444
+ ):
445
+ v1 = get_safe_version(repo_id, V16)
446
+ v1x_dir = local_dir / V16 / repo_id
447
+ v20_dir = local_dir / V20 / repo_id
448
+ v1x_dir.mkdir(parents=True, exist_ok=True)
449
+ v20_dir.mkdir(parents=True, exist_ok=True)
450
+
451
+ hub_api = HfApi()
452
+ hub_api.snapshot_download(
453
+ repo_id=repo_id, repo_type="dataset", revision=v1, local_dir=v1x_dir, ignore_patterns="videos*/"
454
+ )
455
+ branch = "main"
456
+ if test_branch:
457
+ branch = test_branch
458
+ create_branch(repo_id=repo_id, branch=test_branch, repo_type="dataset")
459
+
460
+ metadata_v1 = load_json(v1x_dir / V1_INFO_PATH)
461
+ dataset = datasets.load_dataset("parquet", data_dir=v1x_dir / "data", split="train")
462
+ features = get_features_from_hf_dataset(dataset, robot_config)
463
+ video_keys = [key for key, ft in features.items() if ft["dtype"] == "video"]
464
+
465
+ if single_task and "language_instruction" in dataset.column_names:
466
+ logging.warning(
467
+ "'single_task' provided but 'language_instruction' tasks_col found. Using 'language_instruction'.",
468
+ )
469
+ single_task = None
470
+ tasks_col = "language_instruction"
471
+
472
+ # Episodes & chunks
473
+ episode_indices = sorted(dataset.unique("episode_index"))
474
+ total_episodes = len(episode_indices)
475
+ assert episode_indices == list(range(total_episodes))
476
+ total_videos = total_episodes * len(video_keys)
477
+ total_chunks = total_episodes // DEFAULT_CHUNK_SIZE
478
+ if total_episodes % DEFAULT_CHUNK_SIZE != 0:
479
+ total_chunks += 1
480
+
481
+ # Tasks
482
+ if single_task:
483
+ tasks_by_episodes = dict.fromkeys(episode_indices, single_task)
484
+ dataset, tasks = add_task_index_by_episodes(dataset, tasks_by_episodes)
485
+ tasks_by_episodes = {ep_idx: [task] for ep_idx, task in tasks_by_episodes.items()}
486
+ elif tasks_path:
487
+ tasks_by_episodes = load_json(tasks_path)
488
+ tasks_by_episodes = {int(ep_idx): task for ep_idx, task in tasks_by_episodes.items()}
489
+ dataset, tasks = add_task_index_by_episodes(dataset, tasks_by_episodes)
490
+ tasks_by_episodes = {ep_idx: [task] for ep_idx, task in tasks_by_episodes.items()}
491
+ elif tasks_col:
492
+ dataset, tasks, tasks_by_episodes = add_task_index_from_tasks_col(dataset, tasks_col)
493
+ else:
494
+ raise ValueError
495
+
496
+ assert set(tasks) == {task for ep_tasks in tasks_by_episodes.values() for task in ep_tasks}
497
+ tasks = [{"task_index": task_idx, "task": task} for task_idx, task in enumerate(tasks)]
498
+ write_jsonlines(tasks, v20_dir / TASKS_PATH)
499
+ features["task_index"] = {
500
+ "dtype": "int64",
501
+ "shape": (1,),
502
+ "names": None,
503
+ }
504
+
505
+ # Videos
506
+ if video_keys:
507
+ assert metadata_v1.get("video", False)
508
+ dataset = dataset.remove_columns(video_keys)
509
+ clean_gitattr = Path(
510
+ hub_api.hf_hub_download(
511
+ repo_id=GITATTRIBUTES_REF, repo_type="dataset", local_dir=local_dir, filename=".gitattributes"
512
+ )
513
+ ).absolute()
514
+ with tempfile.TemporaryDirectory() as tmp_video_dir:
515
+ move_videos(
516
+ repo_id, video_keys, total_episodes, total_chunks, Path(tmp_video_dir), clean_gitattr, branch
517
+ )
518
+ videos_info = get_videos_info(repo_id, v1x_dir, video_keys=video_keys, branch=branch)
519
+ for key in video_keys:
520
+ features[key]["shape"] = (
521
+ videos_info[key].pop("video.height"),
522
+ videos_info[key].pop("video.width"),
523
+ videos_info[key].pop("video.channels"),
524
+ )
525
+ features[key]["video_info"] = videos_info[key]
526
+ assert math.isclose(videos_info[key]["video.fps"], metadata_v1["fps"], rel_tol=1e-3)
527
+ if "encoding" in metadata_v1:
528
+ assert videos_info[key]["video.pix_fmt"] == metadata_v1["encoding"]["pix_fmt"]
529
+ else:
530
+ assert metadata_v1.get("video", 0) == 0
531
+ videos_info = None
532
+
533
+ # Split data into 1 parquet file by episode
534
+ episode_lengths = split_parquet_by_episodes(dataset, total_episodes, total_chunks, v20_dir)
535
+
536
+ if robot_config is not None:
537
+ robot_type = robot_config.type
538
+ repo_tags = [robot_type]
539
+ else:
540
+ robot_type = "unknown"
541
+ repo_tags = None
542
+
543
+ # Episodes
544
+ episodes = [
545
+ {"episode_index": ep_idx, "tasks": tasks_by_episodes[ep_idx], "length": episode_lengths[ep_idx]}
546
+ for ep_idx in episode_indices
547
+ ]
548
+ write_jsonlines(episodes, v20_dir / EPISODES_PATH)
549
+
550
+ # Assemble metadata v2.0
551
+ metadata_v2_0 = {
552
+ "codebase_version": V20,
553
+ "robot_type": robot_type,
554
+ "total_episodes": total_episodes,
555
+ "total_frames": len(dataset),
556
+ "total_tasks": len(tasks),
557
+ "total_videos": total_videos,
558
+ "total_chunks": total_chunks,
559
+ "chunks_size": DEFAULT_CHUNK_SIZE,
560
+ "fps": metadata_v1["fps"],
561
+ "splits": {"train": f"0:{total_episodes}"},
562
+ "data_path": DEFAULT_PARQUET_PATH,
563
+ "video_path": DEFAULT_VIDEO_PATH if video_keys else None,
564
+ "features": features,
565
+ }
566
+ write_json(metadata_v2_0, v20_dir / INFO_PATH)
567
+ convert_stats_to_json(v1x_dir, v20_dir)
568
+ card = create_lerobot_dataset_card(tags=repo_tags, dataset_info=metadata_v2_0, **card_kwargs)
569
+
570
+ with contextlib.suppress(EntryNotFoundError, HfHubHTTPError):
571
+ hub_api.delete_folder(repo_id=repo_id, path_in_repo="data", repo_type="dataset", revision=branch)
572
+
573
+ with contextlib.suppress(EntryNotFoundError, HfHubHTTPError):
574
+ hub_api.delete_folder(repo_id=repo_id, path_in_repo="meta_data", repo_type="dataset", revision=branch)
575
+
576
+ with contextlib.suppress(EntryNotFoundError, HfHubHTTPError):
577
+ hub_api.delete_folder(repo_id=repo_id, path_in_repo="meta", repo_type="dataset", revision=branch)
578
+
579
+ hub_api.upload_folder(
580
+ repo_id=repo_id,
581
+ path_in_repo="data",
582
+ folder_path=v20_dir / "data",
583
+ repo_type="dataset",
584
+ revision=branch,
585
+ )
586
+ hub_api.upload_folder(
587
+ repo_id=repo_id,
588
+ path_in_repo="meta",
589
+ folder_path=v20_dir / "meta",
590
+ repo_type="dataset",
591
+ revision=branch,
592
+ )
593
+
594
+ card.push_to_hub(repo_id=repo_id, repo_type="dataset", revision=branch)
595
+
596
+ if not test_branch:
597
+ create_branch(repo_id=repo_id, branch=V20, repo_type="dataset")
598
+
599
+
600
+ def make_robot_config(robot_type: str, **kwargs) -> RobotConfig:
601
+ if robot_type == "aloha":
602
+ raise NotImplementedError # TODO
603
+
604
+ elif robot_type == "koch_follower":
605
+ from lerobot.robots.koch_follower import KochFollowerConfig
606
+
607
+ return KochFollowerConfig(**kwargs)
608
+ elif robot_type == "so100_follower":
609
+ from lerobot.robots.so100_follower import SO100FollowerConfig
610
+
611
+ return SO100FollowerConfig(**kwargs)
612
+ elif robot_type == "stretch":
613
+ from lerobot.robots.stretch3 import Stretch3RobotConfig
614
+
615
+ return Stretch3RobotConfig(**kwargs)
616
+ elif robot_type == "lekiwi":
617
+ from lerobot.robots.lekiwi import LeKiwiConfig
618
+
619
+ return LeKiwiConfig(**kwargs)
620
+ else:
621
+ raise ValueError(f"Robot type '{robot_type}' is not available.")
622
+
623
+
624
+ def main():
625
+ parser = argparse.ArgumentParser()
626
+ task_args = parser.add_mutually_exclusive_group(required=True)
627
+
628
+ parser.add_argument(
629
+ "--repo-id",
630
+ type=str,
631
+ required=True,
632
+ help="Repository identifier on Hugging Face: a community or a user name `/` the name of the dataset (e.g. `lerobot/pusht`, `cadene/aloha_sim_insertion_human`).",
633
+ )
634
+ task_args.add_argument(
635
+ "--single-task",
636
+ type=str,
637
+ help="A short but accurate description of the single task performed in the dataset.",
638
+ )
639
+ task_args.add_argument(
640
+ "--tasks-col",
641
+ type=str,
642
+ help="The name of the column containing language instructions",
643
+ )
644
+ task_args.add_argument(
645
+ "--tasks-path",
646
+ type=Path,
647
+ help="The path to a .json file containing one language instruction for each episode_index",
648
+ )
649
+ parser.add_argument(
650
+ "--robot",
651
+ type=str,
652
+ default=None,
653
+ help="Robot config used for the dataset during conversion (e.g. 'koch', 'aloha', 'so100', etc.)",
654
+ )
655
+ parser.add_argument(
656
+ "--local-dir",
657
+ type=Path,
658
+ default=None,
659
+ help="Local directory to store the dataset during conversion. Defaults to /tmp/lerobot_dataset_v2",
660
+ )
661
+ parser.add_argument(
662
+ "--license",
663
+ type=str,
664
+ default="apache-2.0",
665
+ help="Repo license. Must be one of https://huggingface.co/docs/hub/repositories-licenses. Defaults to mit.",
666
+ )
667
+ parser.add_argument(
668
+ "--test-branch",
669
+ type=str,
670
+ default=None,
671
+ help="Repo branch to test your conversion first (e.g. 'v2.0.test')",
672
+ )
673
+
674
+ args = parser.parse_args()
675
+ if not args.local_dir:
676
+ args.local_dir = Path("/tmp/lerobot_dataset_v2")
677
+
678
+ if args.robot is not None:
679
+ robot_config = make_robot_config(args.robot)
680
+
681
+ del args.robot
682
+
683
+ convert_dataset(**vars(args), robot_config=robot_config)
684
+
685
+
686
+ if __name__ == "__main__":
687
+ main()
tools/lerobot_v21_runtime/src/lerobot/datasets/v21/_remove_language_instruction.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import logging
16
+ import traceback
17
+ from pathlib import Path
18
+
19
+ from datasets import get_dataset_config_info
20
+ from huggingface_hub import HfApi
21
+
22
+ from lerobot import available_datasets
23
+ from lerobot.datasets.lerobot_dataset import LeRobotDatasetMetadata
24
+ from lerobot.datasets.utils import INFO_PATH, write_info
25
+ from lerobot.datasets.v21.convert_dataset_v20_to_v21 import V20, SuppressWarnings
26
+
27
+ LOCAL_DIR = Path("data/")
28
+
29
+ hub_api = HfApi()
30
+
31
+
32
+ def fix_dataset(repo_id: str) -> str:
33
+ if not hub_api.revision_exists(repo_id, V20, repo_type="dataset"):
34
+ return f"{repo_id}: skipped (not in {V20})."
35
+
36
+ dataset_info = get_dataset_config_info(repo_id, "default")
37
+ with SuppressWarnings():
38
+ lerobot_metadata = LeRobotDatasetMetadata(repo_id, revision=V20, force_cache_sync=True)
39
+
40
+ meta_features = {key for key, ft in lerobot_metadata.features.items() if ft["dtype"] != "video"}
41
+ parquet_features = set(dataset_info.features)
42
+
43
+ diff_parquet_meta = parquet_features - meta_features
44
+ diff_meta_parquet = meta_features - parquet_features
45
+
46
+ if diff_parquet_meta:
47
+ raise ValueError(f"In parquet not in info.json: {parquet_features - meta_features}")
48
+
49
+ if not diff_meta_parquet:
50
+ return f"{repo_id}: skipped (no diff)"
51
+
52
+ if diff_meta_parquet:
53
+ logging.warning(f"In info.json not in parquet: {meta_features - parquet_features}")
54
+ assert diff_meta_parquet == {"language_instruction"}
55
+ lerobot_metadata.features.pop("language_instruction")
56
+ write_info(lerobot_metadata.info, lerobot_metadata.root)
57
+ commit_info = hub_api.upload_file(
58
+ path_or_fileobj=lerobot_metadata.root / INFO_PATH,
59
+ path_in_repo=INFO_PATH,
60
+ repo_id=repo_id,
61
+ repo_type="dataset",
62
+ revision=V20,
63
+ commit_message="Remove 'language_instruction'",
64
+ create_pr=True,
65
+ )
66
+ return f"{repo_id}: success - PR: {commit_info.pr_url}"
67
+
68
+
69
+ def batch_fix():
70
+ status = {}
71
+ LOCAL_DIR.mkdir(parents=True, exist_ok=True)
72
+ logfile = LOCAL_DIR / "fix_features_v20.txt"
73
+ for num, repo_id in enumerate(available_datasets):
74
+ print(f"\nConverting {repo_id} ({num}/{len(available_datasets)})")
75
+ print("---------------------------------------------------------")
76
+ try:
77
+ status = fix_dataset(repo_id)
78
+ except Exception:
79
+ status = f"{repo_id}: failed\n {traceback.format_exc()}"
80
+
81
+ logging.info(status)
82
+ with open(logfile, "a") as file:
83
+ file.write(status + "\n")
84
+
85
+
86
+ if __name__ == "__main__":
87
+ batch_fix()
tools/lerobot_v21_runtime/src/lerobot/datasets/v21/batch_convert_dataset_v20_to_v21.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
18
+ This script is for internal use to convert all datasets under the 'lerobot' hub user account to v2.1.
19
+ """
20
+
21
+ import traceback
22
+ from pathlib import Path
23
+
24
+ from huggingface_hub import HfApi
25
+
26
+ from lerobot import available_datasets
27
+ from lerobot.datasets.v21.convert_dataset_v20_to_v21 import V21, convert_dataset
28
+
29
+ LOCAL_DIR = Path("data/")
30
+
31
+
32
+ def batch_convert():
33
+ status = {}
34
+ LOCAL_DIR.mkdir(parents=True, exist_ok=True)
35
+ logfile = LOCAL_DIR / "conversion_log_v21.txt"
36
+ hub_api = HfApi()
37
+ for num, repo_id in enumerate(available_datasets):
38
+ print(f"\nConverting {repo_id} ({num}/{len(available_datasets)})")
39
+ print("---------------------------------------------------------")
40
+ try:
41
+ if hub_api.revision_exists(repo_id, V21, repo_type="dataset"):
42
+ status = f"{repo_id}: success (already in {V21})."
43
+ else:
44
+ convert_dataset(repo_id)
45
+ status = f"{repo_id}: success."
46
+ except Exception:
47
+ status = f"{repo_id}: failed\n {traceback.format_exc()}"
48
+
49
+ with open(logfile, "a") as file:
50
+ file.write(status + "\n")
51
+
52
+
53
+ if __name__ == "__main__":
54
+ batch_convert()
tools/lerobot_v21_runtime/src/lerobot/datasets/v21/convert_dataset_v20_to_v21.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
16
+ This script will help you convert any LeRobot dataset already pushed to the hub from codebase version 2.0 to
17
+ 2.1. It will:
18
+
19
+ - Generate per-episodes stats and writes them in `episodes_stats.jsonl`
20
+ - Check consistency between these new stats and the old ones.
21
+ - Remove the deprecated `stats.json`.
22
+ - Update codebase_version in `info.json`.
23
+ - Push this new version to the hub on the 'main' branch and tags it with "v2.1".
24
+
25
+ Usage:
26
+
27
+ ```bash
28
+ python -m lerobot.datasets.v21.convert_dataset_v20_to_v21 \
29
+ --repo-id=aliberts/koch_tutorial
30
+ ```
31
+
32
+ """
33
+
34
+ import argparse
35
+ import logging
36
+
37
+ from huggingface_hub import HfApi
38
+
39
+ from lerobot.datasets.lerobot_dataset import CODEBASE_VERSION, LeRobotDataset
40
+ from lerobot.datasets.utils import EPISODES_STATS_PATH, STATS_PATH, load_stats, write_info
41
+ from lerobot.datasets.v21.convert_stats import check_aggregate_stats, convert_stats
42
+
43
+ V20 = "v2.0"
44
+ V21 = "v2.1"
45
+
46
+
47
+ class SuppressWarnings:
48
+ def __enter__(self):
49
+ self.previous_level = logging.getLogger().getEffectiveLevel()
50
+ logging.getLogger().setLevel(logging.ERROR)
51
+
52
+ def __exit__(self, exc_type, exc_val, exc_tb):
53
+ logging.getLogger().setLevel(self.previous_level)
54
+
55
+
56
+ def convert_dataset(
57
+ repo_id: str,
58
+ branch: str | None = None,
59
+ num_workers: int = 4,
60
+ ):
61
+ with SuppressWarnings():
62
+ dataset = LeRobotDataset(repo_id, revision=V20, force_cache_sync=True)
63
+
64
+ if (dataset.root / EPISODES_STATS_PATH).is_file():
65
+ (dataset.root / EPISODES_STATS_PATH).unlink()
66
+
67
+ convert_stats(dataset, num_workers=num_workers)
68
+ ref_stats = load_stats(dataset.root)
69
+ check_aggregate_stats(dataset, ref_stats)
70
+
71
+ dataset.meta.info["codebase_version"] = CODEBASE_VERSION
72
+ write_info(dataset.meta.info, dataset.root)
73
+
74
+ dataset.push_to_hub(branch=branch, tag_version=False, allow_patterns="meta/")
75
+
76
+ # delete old stats.json file
77
+ if (dataset.root / STATS_PATH).is_file:
78
+ (dataset.root / STATS_PATH).unlink()
79
+
80
+ hub_api = HfApi()
81
+ if hub_api.file_exists(
82
+ repo_id=dataset.repo_id, filename=STATS_PATH, revision=branch, repo_type="dataset"
83
+ ):
84
+ hub_api.delete_file(
85
+ path_in_repo=STATS_PATH, repo_id=dataset.repo_id, revision=branch, repo_type="dataset"
86
+ )
87
+
88
+ hub_api.create_tag(repo_id, tag=CODEBASE_VERSION, revision=branch, repo_type="dataset")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ parser = argparse.ArgumentParser()
93
+ parser.add_argument(
94
+ "--repo-id",
95
+ type=str,
96
+ required=True,
97
+ help="Repository identifier on Hugging Face: a community or a user name `/` the name of the dataset "
98
+ "(e.g. `lerobot/pusht`, `cadene/aloha_sim_insertion_human`).",
99
+ )
100
+ parser.add_argument(
101
+ "--branch",
102
+ type=str,
103
+ default=None,
104
+ help="Repo branch to push your dataset. Defaults to the main branch.",
105
+ )
106
+ parser.add_argument(
107
+ "--num-workers",
108
+ type=int,
109
+ default=4,
110
+ help="Number of workers for parallelizing stats compute. Defaults to 4.",
111
+ )
112
+
113
+ args = parser.parse_args()
114
+ convert_dataset(**vars(args))
tools/lerobot_v21_runtime/src/lerobot/datasets/v21/convert_stats.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 concurrent.futures import ThreadPoolExecutor, as_completed
16
+
17
+ import numpy as np
18
+ from tqdm import tqdm
19
+
20
+ from lerobot.datasets.compute_stats import aggregate_stats, get_feature_stats, sample_indices
21
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
22
+ from lerobot.datasets.utils import write_episode_stats
23
+
24
+
25
+ def sample_episode_video_frames(dataset: LeRobotDataset, episode_index: int, ft_key: str) -> np.ndarray:
26
+ ep_len = dataset.meta.episodes[episode_index]["length"]
27
+ sampled_indices = sample_indices(ep_len)
28
+ query_timestamps = dataset._get_query_timestamps(0.0, {ft_key: sampled_indices})
29
+ video_frames = dataset._query_videos(query_timestamps, episode_index)
30
+ return video_frames[ft_key].numpy()
31
+
32
+
33
+ def convert_episode_stats(dataset: LeRobotDataset, ep_idx: int):
34
+ ep_start_idx = dataset.episode_data_index["from"][ep_idx]
35
+ ep_end_idx = dataset.episode_data_index["to"][ep_idx]
36
+ ep_data = dataset.hf_dataset.select(range(ep_start_idx, ep_end_idx))
37
+
38
+ ep_stats = {}
39
+ for key, ft in dataset.features.items():
40
+ if ft["dtype"] == "video":
41
+ # We sample only for videos
42
+ ep_ft_data = sample_episode_video_frames(dataset, ep_idx, key)
43
+ else:
44
+ ep_ft_data = np.array(ep_data[key])
45
+
46
+ axes_to_reduce = (0, 2, 3) if ft["dtype"] in ["image", "video"] else 0
47
+ keepdims = True if ft["dtype"] in ["image", "video"] else ep_ft_data.ndim == 1
48
+ ep_stats[key] = get_feature_stats(ep_ft_data, axis=axes_to_reduce, keepdims=keepdims)
49
+
50
+ if ft["dtype"] in ["image", "video"]: # remove batch dim
51
+ ep_stats[key] = {
52
+ k: v if k == "count" else np.squeeze(v, axis=0) for k, v in ep_stats[key].items()
53
+ }
54
+
55
+ dataset.meta.episodes_stats[ep_idx] = ep_stats
56
+
57
+
58
+ def convert_stats(dataset: LeRobotDataset, num_workers: int = 0):
59
+ assert dataset.episodes is None
60
+ print("Computing episodes stats")
61
+ total_episodes = dataset.meta.total_episodes
62
+ if num_workers > 0:
63
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
64
+ futures = {
65
+ executor.submit(convert_episode_stats, dataset, ep_idx): ep_idx
66
+ for ep_idx in range(total_episodes)
67
+ }
68
+ for future in tqdm(as_completed(futures), total=total_episodes):
69
+ future.result()
70
+ else:
71
+ for ep_idx in tqdm(range(total_episodes)):
72
+ convert_episode_stats(dataset, ep_idx)
73
+
74
+ for ep_idx in tqdm(range(total_episodes)):
75
+ write_episode_stats(ep_idx, dataset.meta.episodes_stats[ep_idx], dataset.root)
76
+
77
+
78
+ def check_aggregate_stats(
79
+ dataset: LeRobotDataset,
80
+ reference_stats: dict[str, dict[str, np.ndarray]],
81
+ video_rtol_atol: tuple[float] = (1e-2, 1e-2),
82
+ default_rtol_atol: tuple[float] = (5e-6, 6e-5),
83
+ ):
84
+ """Verifies that the aggregated stats from episodes_stats are close to reference stats."""
85
+ agg_stats = aggregate_stats(list(dataset.meta.episodes_stats.values()))
86
+ for key, ft in dataset.features.items():
87
+ # These values might need some fine-tuning
88
+ if ft["dtype"] == "video":
89
+ # to account for image sub-sampling
90
+ rtol, atol = video_rtol_atol
91
+ else:
92
+ rtol, atol = default_rtol_atol
93
+
94
+ for stat, val in agg_stats[key].items():
95
+ if key in reference_stats and stat in reference_stats[key]:
96
+ err_msg = f"feature='{key}' stats='{stat}'"
97
+ np.testing.assert_allclose(
98
+ val, reference_stats[key][stat], rtol=rtol, atol=atol, err_msg=err_msg
99
+ )
tools/lerobot_v21_runtime/src/lerobot/motors/dynamixel/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2025 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 .dynamixel import DriveMode, DynamixelMotorsBus, OperatingMode, TorqueMode
18
+ from .tables import *
tools/lerobot_v21_runtime/src/lerobot/motors/dynamixel/dynamixel.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # TODO(aliberts): Should we implement FastSyncRead/Write?
16
+ # https://github.com/ROBOTIS-GIT/DynamixelSDK/pull/643
17
+ # https://github.com/ROBOTIS-GIT/DynamixelSDK/releases/tag/3.8.2
18
+ # https://emanual.robotis.com/docs/en/dxl/protocol2/#fast-sync-read-0x8a
19
+ # -> Need to check compatibility across models
20
+
21
+ import logging
22
+ from copy import deepcopy
23
+ from enum import Enum
24
+
25
+ from lerobot.utils.encoding_utils import decode_twos_complement, encode_twos_complement
26
+
27
+ from ..motors_bus import Motor, MotorCalibration, MotorsBus, NameOrID, Value, get_address
28
+ from .tables import (
29
+ AVAILABLE_BAUDRATES,
30
+ MODEL_BAUDRATE_TABLE,
31
+ MODEL_CONTROL_TABLE,
32
+ MODEL_ENCODING_TABLE,
33
+ MODEL_NUMBER_TABLE,
34
+ MODEL_RESOLUTION,
35
+ )
36
+
37
+ PROTOCOL_VERSION = 2.0
38
+ DEFAULT_BAUDRATE = 1_000_000
39
+ DEFAULT_TIMEOUT_MS = 1000
40
+
41
+ NORMALIZED_DATA = ["Goal_Position", "Present_Position"]
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+
46
+ class OperatingMode(Enum):
47
+ # DYNAMIXEL only controls current(torque) regardless of speed and position. This mode is ideal for a
48
+ # gripper or a system that only uses current(torque) control or a system that has additional
49
+ # velocity/position controllers.
50
+ CURRENT = 0
51
+
52
+ # This mode controls velocity. This mode is identical to the Wheel Mode(endless) from existing DYNAMIXEL.
53
+ # This mode is ideal for wheel-type robots.
54
+ VELOCITY = 1
55
+
56
+ # This mode controls position. This mode is identical to the Joint Mode from existing DYNAMIXEL. Operating
57
+ # position range is limited by the Max Position Limit(48) and the Min Position Limit(52). This mode is
58
+ # ideal for articulated robots that each joint rotates less than 360 degrees.
59
+ POSITION = 3
60
+
61
+ # This mode controls position. This mode is identical to the Multi-turn Position Control from existing
62
+ # DYNAMIXEL. 512 turns are supported(-256[rev] ~ 256[rev]). This mode is ideal for multi-turn wrists or
63
+ # conveyer systems or a system that requires an additional reduction gear. Note that Max Position
64
+ # Limit(48), Min Position Limit(52) are not used on Extended Position Control Mode.
65
+ EXTENDED_POSITION = 4
66
+
67
+ # This mode controls both position and current(torque). Up to 512 turns are supported (-256[rev] ~
68
+ # 256[rev]). This mode is ideal for a system that requires both position and current control such as
69
+ # articulated robots or grippers.
70
+ CURRENT_POSITION = 5
71
+
72
+ # This mode directly controls PWM output. (Voltage Control Mode)
73
+ PWM = 16
74
+
75
+
76
+ class DriveMode(Enum):
77
+ NON_INVERTED = 0
78
+ INVERTED = 1
79
+
80
+
81
+ class TorqueMode(Enum):
82
+ ENABLED = 1
83
+ DISABLED = 0
84
+
85
+
86
+ def _split_into_byte_chunks(value: int, length: int) -> list[int]:
87
+ import dynamixel_sdk as dxl
88
+
89
+ if length == 1:
90
+ data = [value]
91
+ elif length == 2:
92
+ data = [dxl.DXL_LOBYTE(value), dxl.DXL_HIBYTE(value)]
93
+ elif length == 4:
94
+ data = [
95
+ dxl.DXL_LOBYTE(dxl.DXL_LOWORD(value)),
96
+ dxl.DXL_HIBYTE(dxl.DXL_LOWORD(value)),
97
+ dxl.DXL_LOBYTE(dxl.DXL_HIWORD(value)),
98
+ dxl.DXL_HIBYTE(dxl.DXL_HIWORD(value)),
99
+ ]
100
+ return data
101
+
102
+
103
+ class DynamixelMotorsBus(MotorsBus):
104
+ """
105
+ The Dynamixel implementation for a MotorsBus. It relies on the python dynamixel sdk to communicate with
106
+ the motors. For more info, see the Dynamixel SDK Documentation:
107
+ https://emanual.robotis.com/docs/en/software/dynamixel/dynamixel_sdk/sample_code/python_read_write_protocol_2_0/#python-read-write-protocol-20
108
+ """
109
+
110
+ apply_drive_mode = False
111
+ available_baudrates = deepcopy(AVAILABLE_BAUDRATES)
112
+ default_baudrate = DEFAULT_BAUDRATE
113
+ default_timeout = DEFAULT_TIMEOUT_MS
114
+ model_baudrate_table = deepcopy(MODEL_BAUDRATE_TABLE)
115
+ model_ctrl_table = deepcopy(MODEL_CONTROL_TABLE)
116
+ model_encoding_table = deepcopy(MODEL_ENCODING_TABLE)
117
+ model_number_table = deepcopy(MODEL_NUMBER_TABLE)
118
+ model_resolution_table = deepcopy(MODEL_RESOLUTION)
119
+ normalized_data = deepcopy(NORMALIZED_DATA)
120
+
121
+ def __init__(
122
+ self,
123
+ port: str,
124
+ motors: dict[str, Motor],
125
+ calibration: dict[str, MotorCalibration] | None = None,
126
+ ):
127
+ super().__init__(port, motors, calibration)
128
+ import dynamixel_sdk as dxl
129
+
130
+ self.port_handler = dxl.PortHandler(self.port)
131
+ self.packet_handler = dxl.PacketHandler(PROTOCOL_VERSION)
132
+ self.sync_reader = dxl.GroupSyncRead(self.port_handler, self.packet_handler, 0, 0)
133
+ self.sync_writer = dxl.GroupSyncWrite(self.port_handler, self.packet_handler, 0, 0)
134
+ self._comm_success = dxl.COMM_SUCCESS
135
+ self._no_error = 0x00
136
+
137
+ def _assert_protocol_is_compatible(self, instruction_name: str) -> None:
138
+ pass
139
+
140
+ def _handshake(self) -> None:
141
+ self._assert_motors_exist()
142
+
143
+ def _find_single_motor(self, motor: str, initial_baudrate: int | None = None) -> tuple[int, int]:
144
+ model = self.motors[motor].model
145
+ search_baudrates = (
146
+ [initial_baudrate] if initial_baudrate is not None else self.model_baudrate_table[model]
147
+ )
148
+
149
+ for baudrate in search_baudrates:
150
+ self.set_baudrate(baudrate)
151
+ id_model = self.broadcast_ping()
152
+ if id_model:
153
+ found_id, found_model = next(iter(id_model.items()))
154
+ expected_model_nb = self.model_number_table[model]
155
+ if found_model != expected_model_nb:
156
+ raise RuntimeError(
157
+ f"Found one motor on {baudrate=} with id={found_id} but it has a "
158
+ f"model number '{found_model}' different than the one expected: '{expected_model_nb}'. "
159
+ f"Make sure you are connected only connected to the '{motor}' motor (model '{model}')."
160
+ )
161
+ return baudrate, found_id
162
+
163
+ raise RuntimeError(f"Motor '{motor}' (model '{model}') was not found. Make sure it is connected.")
164
+
165
+ def configure_motors(self, return_delay_time=0) -> None:
166
+ # By default, Dynamixel motors have a 500µs delay response time (corresponding to a value of 250 on
167
+ # the 'Return_Delay_Time' address). We ensure this is reduced to the minimum of 2µs (value of 0).
168
+ for motor in self.motors:
169
+ self.write("Return_Delay_Time", motor, return_delay_time)
170
+
171
+ @property
172
+ def is_calibrated(self) -> bool:
173
+ return self.calibration == self.read_calibration()
174
+
175
+ def read_calibration(self) -> dict[str, MotorCalibration]:
176
+ offsets = self.sync_read("Homing_Offset", normalize=False)
177
+ mins = self.sync_read("Min_Position_Limit", normalize=False)
178
+ maxes = self.sync_read("Max_Position_Limit", normalize=False)
179
+ drive_modes = self.sync_read("Drive_Mode", normalize=False)
180
+
181
+ calibration = {}
182
+ for motor, m in self.motors.items():
183
+ calibration[motor] = MotorCalibration(
184
+ id=m.id,
185
+ drive_mode=drive_modes[motor],
186
+ homing_offset=offsets[motor],
187
+ range_min=mins[motor],
188
+ range_max=maxes[motor],
189
+ )
190
+
191
+ return calibration
192
+
193
+ def write_calibration(self, calibration_dict: dict[str, MotorCalibration], cache: bool = True) -> None:
194
+ for motor, calibration in calibration_dict.items():
195
+ self.write("Homing_Offset", motor, calibration.homing_offset)
196
+ self.write("Min_Position_Limit", motor, calibration.range_min)
197
+ self.write("Max_Position_Limit", motor, calibration.range_max)
198
+
199
+ if cache:
200
+ self.calibration = calibration_dict
201
+
202
+ def disable_torque(self, motors: str | list[str] | None = None, num_retry: int = 0) -> None:
203
+ for motor in self._get_motors_list(motors):
204
+ self.write("Torque_Enable", motor, TorqueMode.DISABLED.value, num_retry=num_retry)
205
+
206
+ def _disable_torque(self, motor_id: int, model: str, num_retry: int = 0) -> None:
207
+ addr, length = get_address(self.model_ctrl_table, model, "Torque_Enable")
208
+ self._write(addr, length, motor_id, TorqueMode.DISABLED.value, num_retry=num_retry)
209
+
210
+ def enable_torque(self, motors: str | list[str] | None = None, num_retry: int = 0) -> None:
211
+ for motor in self._get_motors_list(motors):
212
+ self.write("Torque_Enable", motor, TorqueMode.ENABLED.value, num_retry=num_retry)
213
+
214
+ def _encode_sign(self, data_name: str, ids_values: dict[int, int]) -> dict[int, int]:
215
+ for id_ in ids_values:
216
+ model = self._id_to_model(id_)
217
+ encoding_table = self.model_encoding_table.get(model)
218
+ if encoding_table and data_name in encoding_table:
219
+ n_bytes = encoding_table[data_name]
220
+ ids_values[id_] = encode_twos_complement(ids_values[id_], n_bytes)
221
+
222
+ return ids_values
223
+
224
+ def _decode_sign(self, data_name: str, ids_values: dict[int, int]) -> dict[int, int]:
225
+ for id_ in ids_values:
226
+ model = self._id_to_model(id_)
227
+ encoding_table = self.model_encoding_table.get(model)
228
+ if encoding_table and data_name in encoding_table:
229
+ n_bytes = encoding_table[data_name]
230
+ ids_values[id_] = decode_twos_complement(ids_values[id_], n_bytes)
231
+
232
+ return ids_values
233
+
234
+ def _get_half_turn_homings(self, positions: dict[NameOrID, Value]) -> dict[NameOrID, Value]:
235
+ """
236
+ On Dynamixel Motors:
237
+ Present_Position = Actual_Position + Homing_Offset
238
+ """
239
+ half_turn_homings = {}
240
+ for motor, pos in positions.items():
241
+ model = self._get_motor_model(motor)
242
+ max_res = self.model_resolution_table[model] - 1
243
+ half_turn_homings[motor] = int(max_res / 2) - pos
244
+
245
+ return half_turn_homings
246
+
247
+ def _split_into_byte_chunks(self, value: int, length: int) -> list[int]:
248
+ return _split_into_byte_chunks(value, length)
249
+
250
+ def broadcast_ping(self, num_retry: int = 0, raise_on_error: bool = False) -> dict[int, int] | None:
251
+ for n_try in range(1 + num_retry):
252
+ data_list, comm = self.packet_handler.broadcastPing(self.port_handler)
253
+ if self._is_comm_success(comm):
254
+ break
255
+ logger.debug(f"Broadcast ping failed on port '{self.port}' ({n_try=})")
256
+ logger.debug(self.packet_handler.getTxRxResult(comm))
257
+
258
+ if not self._is_comm_success(comm):
259
+ if raise_on_error:
260
+ raise ConnectionError(self.packet_handler.getTxRxResult(comm))
261
+
262
+ return
263
+
264
+ return {id_: data[0] for id_, data in data_list.items()}
tools/lerobot_v21_runtime/src/lerobot/motors/dynamixel/tables.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # TODO(Steven): Consider doing the following:
16
+ # from enum import Enum
17
+ # class MyControlTableKey(Enum):
18
+ # ID = "ID"
19
+ # GOAL_SPEED = "Goal_Speed"
20
+ # ...
21
+ #
22
+ # MY_CONTROL_TABLE ={
23
+ # MyControlTableKey.ID.value: (5,1)
24
+ # MyControlTableKey.GOAL_SPEED.value: (46, 2)
25
+ # ...
26
+ # }
27
+ # This allows me do to:
28
+ # bus.write(MyControlTableKey.GOAL_SPEED, ...)
29
+ # Instead of:
30
+ # bus.write("Goal_Speed", ...)
31
+ # This is important for two reasons:
32
+ # 1. The linter will tell me if I'm trying to use an invalid key, instead of me realizing when I get the RunTimeError
33
+ # 2. We can change the value of the MyControlTableKey enums without impacting the client code
34
+
35
+
36
+ # {data_name: (address, size_byte)}
37
+ # https://emanual.robotis.com/docs/en/dxl/x/{MODEL}/#control-table
38
+ X_SERIES_CONTROL_TABLE = {
39
+ "Model_Number": (0, 2),
40
+ "Model_Information": (2, 4),
41
+ "Firmware_Version": (6, 1),
42
+ "ID": (7, 1),
43
+ "Baud_Rate": (8, 1),
44
+ "Return_Delay_Time": (9, 1),
45
+ "Drive_Mode": (10, 1),
46
+ "Operating_Mode": (11, 1),
47
+ "Secondary_ID": (12, 1),
48
+ "Protocol_Type": (13, 1),
49
+ "Homing_Offset": (20, 4),
50
+ "Moving_Threshold": (24, 4),
51
+ "Temperature_Limit": (31, 1),
52
+ "Max_Voltage_Limit": (32, 2),
53
+ "Min_Voltage_Limit": (34, 2),
54
+ "PWM_Limit": (36, 2),
55
+ "Current_Limit": (38, 2),
56
+ "Acceleration_Limit": (40, 4),
57
+ "Velocity_Limit": (44, 4),
58
+ "Max_Position_Limit": (48, 4),
59
+ "Min_Position_Limit": (52, 4),
60
+ "Shutdown": (63, 1),
61
+ "Torque_Enable": (64, 1),
62
+ "LED": (65, 1),
63
+ "Status_Return_Level": (68, 1),
64
+ "Registered_Instruction": (69, 1),
65
+ "Hardware_Error_Status": (70, 1),
66
+ "Velocity_I_Gain": (76, 2),
67
+ "Velocity_P_Gain": (78, 2),
68
+ "Position_D_Gain": (80, 2),
69
+ "Position_I_Gain": (82, 2),
70
+ "Position_P_Gain": (84, 2),
71
+ "Feedforward_2nd_Gain": (88, 2),
72
+ "Feedforward_1st_Gain": (90, 2),
73
+ "Bus_Watchdog": (98, 1),
74
+ "Goal_PWM": (100, 2),
75
+ "Goal_Current": (102, 2),
76
+ "Goal_Velocity": (104, 4),
77
+ "Profile_Acceleration": (108, 4),
78
+ "Profile_Velocity": (112, 4),
79
+ "Goal_Position": (116, 4),
80
+ "Realtime_Tick": (120, 2),
81
+ "Moving": (122, 1),
82
+ "Moving_Status": (123, 1),
83
+ "Present_PWM": (124, 2),
84
+ "Present_Current": (126, 2),
85
+ "Present_Velocity": (128, 4),
86
+ "Present_Position": (132, 4),
87
+ "Velocity_Trajectory": (136, 4),
88
+ "Position_Trajectory": (140, 4),
89
+ "Present_Input_Voltage": (144, 2),
90
+ "Present_Temperature": (146, 1),
91
+ }
92
+
93
+ # https://emanual.robotis.com/docs/en/dxl/x/{MODEL}/#baud-rate8
94
+ X_SERIES_BAUDRATE_TABLE = {
95
+ 9_600: 0,
96
+ 57_600: 1,
97
+ 115_200: 2,
98
+ 1_000_000: 3,
99
+ 2_000_000: 4,
100
+ 3_000_000: 5,
101
+ 4_000_000: 6,
102
+ }
103
+
104
+ # {data_name: size_byte}
105
+ X_SERIES_ENCODINGS_TABLE = {
106
+ "Homing_Offset": X_SERIES_CONTROL_TABLE["Homing_Offset"][1],
107
+ "Goal_PWM": X_SERIES_CONTROL_TABLE["Goal_PWM"][1],
108
+ "Goal_Current": X_SERIES_CONTROL_TABLE["Goal_Current"][1],
109
+ "Goal_Velocity": X_SERIES_CONTROL_TABLE["Goal_Velocity"][1],
110
+ "Present_PWM": X_SERIES_CONTROL_TABLE["Present_PWM"][1],
111
+ "Present_Current": X_SERIES_CONTROL_TABLE["Present_Current"][1],
112
+ "Present_Velocity": X_SERIES_CONTROL_TABLE["Present_Velocity"][1],
113
+ }
114
+
115
+ MODEL_ENCODING_TABLE = {
116
+ "x_series": X_SERIES_ENCODINGS_TABLE,
117
+ "xl330-m077": X_SERIES_ENCODINGS_TABLE,
118
+ "xl330-m288": X_SERIES_ENCODINGS_TABLE,
119
+ "xl430-w250": X_SERIES_ENCODINGS_TABLE,
120
+ "xm430-w350": X_SERIES_ENCODINGS_TABLE,
121
+ "xm540-w270": X_SERIES_ENCODINGS_TABLE,
122
+ "xc430-w150": X_SERIES_ENCODINGS_TABLE,
123
+ }
124
+
125
+ # {model: model_resolution}
126
+ # https://emanual.robotis.com/docs/en/dxl/x/{MODEL}/#specifications
127
+ MODEL_RESOLUTION = {
128
+ "x_series": 4096,
129
+ "xl330-m077": 4096,
130
+ "xl330-m288": 4096,
131
+ "xl430-w250": 4096,
132
+ "xm430-w350": 4096,
133
+ "xm540-w270": 4096,
134
+ "xc430-w150": 4096,
135
+ }
136
+
137
+ # {model: model_number}
138
+ # https://emanual.robotis.com/docs/en/dxl/x/{MODEL}/#control-table-of-eeprom-area
139
+ MODEL_NUMBER_TABLE = {
140
+ "xl330-m077": 1190,
141
+ "xl330-m288": 1200,
142
+ "xl430-w250": 1060,
143
+ "xm430-w350": 1020,
144
+ "xm540-w270": 1120,
145
+ "xc430-w150": 1070,
146
+ }
147
+
148
+ # {model: available_operating_modes}
149
+ # https://emanual.robotis.com/docs/en/dxl/x/{MODEL}/#operating-mode11
150
+ MODEL_OPERATING_MODES = {
151
+ "xl330-m077": [0, 1, 3, 4, 5, 16],
152
+ "xl330-m288": [0, 1, 3, 4, 5, 16],
153
+ "xl430-w250": [1, 3, 4, 16],
154
+ "xm430-w350": [0, 1, 3, 4, 5, 16],
155
+ "xm540-w270": [0, 1, 3, 4, 5, 16],
156
+ "xc430-w150": [1, 3, 4, 16],
157
+ }
158
+
159
+ MODEL_CONTROL_TABLE = {
160
+ "x_series": X_SERIES_CONTROL_TABLE,
161
+ "xl330-m077": X_SERIES_CONTROL_TABLE,
162
+ "xl330-m288": X_SERIES_CONTROL_TABLE,
163
+ "xl430-w250": X_SERIES_CONTROL_TABLE,
164
+ "xm430-w350": X_SERIES_CONTROL_TABLE,
165
+ "xm540-w270": X_SERIES_CONTROL_TABLE,
166
+ "xc430-w150": X_SERIES_CONTROL_TABLE,
167
+ }
168
+
169
+ MODEL_BAUDRATE_TABLE = {
170
+ "x_series": X_SERIES_BAUDRATE_TABLE,
171
+ "xl330-m077": X_SERIES_BAUDRATE_TABLE,
172
+ "xl330-m288": X_SERIES_BAUDRATE_TABLE,
173
+ "xl430-w250": X_SERIES_BAUDRATE_TABLE,
174
+ "xm430-w350": X_SERIES_BAUDRATE_TABLE,
175
+ "xm540-w270": X_SERIES_BAUDRATE_TABLE,
176
+ "xc430-w150": X_SERIES_BAUDRATE_TABLE,
177
+ }
178
+
179
+ AVAILABLE_BAUDRATES = [
180
+ 9_600,
181
+ 19_200,
182
+ 38_400,
183
+ 57_600,
184
+ 115_200,
185
+ 230_400,
186
+ 460_800,
187
+ 500_000,
188
+ 576_000,
189
+ 921_600,
190
+ 1_000_000,
191
+ 1_152_000,
192
+ 2_000_000,
193
+ 2_500_000,
194
+ 3_000_000,
195
+ 3_500_000,
196
+ 4_000_000,
197
+ ]
tools/lerobot_v21_runtime/src/lerobot/motors/feetech/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2025 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 .feetech import DriveMode, FeetechMotorsBus, OperatingMode, TorqueMode
18
+ from .tables import *
tools/lerobot_v21_runtime/src/lerobot/motors/feetech/feetech.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import logging
16
+ from copy import deepcopy
17
+ from enum import Enum
18
+ from pprint import pformat
19
+
20
+ from lerobot.utils.encoding_utils import decode_sign_magnitude, encode_sign_magnitude
21
+
22
+ from ..motors_bus import Motor, MotorCalibration, MotorsBus, NameOrID, Value, get_address
23
+ from .tables import (
24
+ FIRMWARE_MAJOR_VERSION,
25
+ FIRMWARE_MINOR_VERSION,
26
+ MODEL_BAUDRATE_TABLE,
27
+ MODEL_CONTROL_TABLE,
28
+ MODEL_ENCODING_TABLE,
29
+ MODEL_NUMBER,
30
+ MODEL_NUMBER_TABLE,
31
+ MODEL_PROTOCOL,
32
+ MODEL_RESOLUTION,
33
+ SCAN_BAUDRATES,
34
+ )
35
+
36
+ DEFAULT_PROTOCOL_VERSION = 0
37
+ DEFAULT_BAUDRATE = 1_000_000
38
+ DEFAULT_TIMEOUT_MS = 1000
39
+
40
+ NORMALIZED_DATA = ["Goal_Position", "Present_Position"]
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+
45
+ class OperatingMode(Enum):
46
+ # position servo mode
47
+ POSITION = 0
48
+ # The motor is in constant speed mode, which is controlled by parameter 0x2e, and the highest bit 15 is
49
+ # the direction bit
50
+ VELOCITY = 1
51
+ # PWM open-loop speed regulation mode, with parameter 0x2c running time parameter control, bit11 as
52
+ # direction bit
53
+ PWM = 2
54
+ # In step servo mode, the number of step progress is represented by parameter 0x2a, and the highest bit 15
55
+ # is the direction bit
56
+ STEP = 3
57
+
58
+
59
+ class DriveMode(Enum):
60
+ NON_INVERTED = 0
61
+ INVERTED = 1
62
+
63
+
64
+ class TorqueMode(Enum):
65
+ ENABLED = 1
66
+ DISABLED = 0
67
+
68
+
69
+ def _split_into_byte_chunks(value: int, length: int) -> list[int]:
70
+ import scservo_sdk as scs
71
+
72
+ if length == 1:
73
+ data = [value]
74
+ elif length == 2:
75
+ data = [scs.SCS_LOBYTE(value), scs.SCS_HIBYTE(value)]
76
+ elif length == 4:
77
+ data = [
78
+ scs.SCS_LOBYTE(scs.SCS_LOWORD(value)),
79
+ scs.SCS_HIBYTE(scs.SCS_LOWORD(value)),
80
+ scs.SCS_LOBYTE(scs.SCS_HIWORD(value)),
81
+ scs.SCS_HIBYTE(scs.SCS_HIWORD(value)),
82
+ ]
83
+ return data
84
+
85
+
86
+ def patch_setPacketTimeout(self, packet_length): # noqa: N802
87
+ """
88
+ HACK: This patches the PortHandler behavior to set the correct packet timeouts.
89
+
90
+ It fixes https://gitee.com/ftservo/SCServoSDK/issues/IBY2S6
91
+ The bug is fixed on the official Feetech SDK repo (https://gitee.com/ftservo/FTServo_Python)
92
+ but because that version is not published on PyPI, we rely on the (unofficial) on that is, which needs
93
+ patching.
94
+ """
95
+ self.packet_start_time = self.getCurrentTime()
96
+ self.packet_timeout = (self.tx_time_per_byte * packet_length) + (self.tx_time_per_byte * 3.0) + 50
97
+
98
+
99
+ class FeetechMotorsBus(MotorsBus):
100
+ """
101
+ The FeetechMotorsBus class allows to efficiently read and write to the attached motors. It relies on the
102
+ python feetech sdk to communicate with the motors, which is itself based on the dynamixel sdk.
103
+ """
104
+
105
+ apply_drive_mode = True
106
+ available_baudrates = deepcopy(SCAN_BAUDRATES)
107
+ default_baudrate = DEFAULT_BAUDRATE
108
+ default_timeout = DEFAULT_TIMEOUT_MS
109
+ model_baudrate_table = deepcopy(MODEL_BAUDRATE_TABLE)
110
+ model_ctrl_table = deepcopy(MODEL_CONTROL_TABLE)
111
+ model_encoding_table = deepcopy(MODEL_ENCODING_TABLE)
112
+ model_number_table = deepcopy(MODEL_NUMBER_TABLE)
113
+ model_resolution_table = deepcopy(MODEL_RESOLUTION)
114
+ normalized_data = deepcopy(NORMALIZED_DATA)
115
+
116
+ def __init__(
117
+ self,
118
+ port: str,
119
+ motors: dict[str, Motor],
120
+ calibration: dict[str, MotorCalibration] | None = None,
121
+ protocol_version: int = DEFAULT_PROTOCOL_VERSION,
122
+ ):
123
+ super().__init__(port, motors, calibration)
124
+ self.protocol_version = protocol_version
125
+ self._assert_same_protocol()
126
+ import scservo_sdk as scs
127
+
128
+ self.port_handler = scs.PortHandler(self.port)
129
+ # HACK: monkeypatch
130
+ self.port_handler.setPacketTimeout = patch_setPacketTimeout.__get__(
131
+ self.port_handler, scs.PortHandler
132
+ )
133
+ self.packet_handler = scs.PacketHandler(protocol_version)
134
+ self.sync_reader = scs.GroupSyncRead(self.port_handler, self.packet_handler, 0, 0)
135
+ self.sync_writer = scs.GroupSyncWrite(self.port_handler, self.packet_handler, 0, 0)
136
+ self._comm_success = scs.COMM_SUCCESS
137
+ self._no_error = 0x00
138
+
139
+ if any(MODEL_PROTOCOL[model] != self.protocol_version for model in self.models):
140
+ raise ValueError(f"Some motors are incompatible with protocol_version={self.protocol_version}")
141
+
142
+ def _assert_same_protocol(self) -> None:
143
+ if any(MODEL_PROTOCOL[model] != self.protocol_version for model in self.models):
144
+ raise RuntimeError("Some motors use an incompatible protocol.")
145
+
146
+ def _assert_protocol_is_compatible(self, instruction_name: str) -> None:
147
+ if instruction_name == "sync_read" and self.protocol_version == 1:
148
+ raise NotImplementedError(
149
+ "'Sync Read' is not available with Feetech motors using Protocol 1. Use 'Read' sequentially instead."
150
+ )
151
+ if instruction_name == "broadcast_ping" and self.protocol_version == 1:
152
+ raise NotImplementedError(
153
+ "'Broadcast Ping' is not available with Feetech motors using Protocol 1. Use 'Ping' sequentially instead."
154
+ )
155
+
156
+ def _assert_same_firmware(self) -> None:
157
+ firmware_versions = self._read_firmware_version(self.ids, raise_on_error=True)
158
+ if len(set(firmware_versions.values())) != 1:
159
+ raise RuntimeError(
160
+ "Some Motors use different firmware versions:"
161
+ f"\n{pformat(firmware_versions)}\n"
162
+ "Update their firmware first using Feetech's software. "
163
+ "Visit https://www.feetechrc.com/software."
164
+ )
165
+
166
+ def _handshake(self) -> None:
167
+ self._assert_motors_exist()
168
+ self._assert_same_firmware()
169
+
170
+ def _find_single_motor(self, motor: str, initial_baudrate: int | None = None) -> tuple[int, int]:
171
+ if self.protocol_version == 0:
172
+ return self._find_single_motor_p0(motor, initial_baudrate)
173
+ else:
174
+ return self._find_single_motor_p1(motor, initial_baudrate)
175
+
176
+ def _find_single_motor_p0(self, motor: str, initial_baudrate: int | None = None) -> tuple[int, int]:
177
+ model = self.motors[motor].model
178
+ search_baudrates = (
179
+ [initial_baudrate] if initial_baudrate is not None else self.model_baudrate_table[model]
180
+ )
181
+ expected_model_nb = self.model_number_table[model]
182
+
183
+ for baudrate in search_baudrates:
184
+ self.set_baudrate(baudrate)
185
+ id_model = self.broadcast_ping()
186
+ if id_model:
187
+ found_id, found_model = next(iter(id_model.items()))
188
+ if found_model != expected_model_nb:
189
+ raise RuntimeError(
190
+ f"Found one motor on {baudrate=} with id={found_id} but it has a "
191
+ f"model number '{found_model}' different than the one expected: '{expected_model_nb}'. "
192
+ f"Make sure you are connected only connected to the '{motor}' motor (model '{model}')."
193
+ )
194
+ return baudrate, found_id
195
+
196
+ raise RuntimeError(f"Motor '{motor}' (model '{model}') was not found. Make sure it is connected.")
197
+
198
+ def _find_single_motor_p1(self, motor: str, initial_baudrate: int | None = None) -> tuple[int, int]:
199
+ import scservo_sdk as scs
200
+
201
+ model = self.motors[motor].model
202
+ search_baudrates = (
203
+ [initial_baudrate] if initial_baudrate is not None else self.model_baudrate_table[model]
204
+ )
205
+ expected_model_nb = self.model_number_table[model]
206
+
207
+ for baudrate in search_baudrates:
208
+ self.set_baudrate(baudrate)
209
+ for id_ in range(scs.MAX_ID + 1):
210
+ found_model = self.ping(id_)
211
+ if found_model is not None:
212
+ if found_model != expected_model_nb:
213
+ raise RuntimeError(
214
+ f"Found one motor on {baudrate=} with id={id_} but it has a "
215
+ f"model number '{found_model}' different than the one expected: '{expected_model_nb}'. "
216
+ f"Make sure you are connected only connected to the '{motor}' motor (model '{model}')."
217
+ )
218
+ return baudrate, id_
219
+
220
+ raise RuntimeError(f"Motor '{motor}' (model '{model}') was not found. Make sure it is connected.")
221
+
222
+ def configure_motors(self, return_delay_time=0, maximum_acceleration=254, acceleration=254) -> None:
223
+ for motor in self.motors:
224
+ # By default, Feetech motors have a 500µs delay response time (corresponding to a value of 250 on
225
+ # the 'Return_Delay_Time' address). We ensure this is reduced to the minimum of 2µs (value of 0).
226
+ self.write("Return_Delay_Time", motor, return_delay_time)
227
+ # Set 'Maximum_Acceleration' to 254 to speedup acceleration and deceleration of the motors.
228
+ if self.protocol_version == 0:
229
+ self.write("Maximum_Acceleration", motor, maximum_acceleration)
230
+ self.write("Acceleration", motor, acceleration)
231
+
232
+ @property
233
+ def is_calibrated(self) -> bool:
234
+ motors_calibration = self.read_calibration()
235
+ if set(motors_calibration) != set(self.calibration):
236
+ return False
237
+
238
+ same_ranges = all(
239
+ self.calibration[motor].range_min == cal.range_min
240
+ and self.calibration[motor].range_max == cal.range_max
241
+ for motor, cal in motors_calibration.items()
242
+ )
243
+ if self.protocol_version == 1:
244
+ return same_ranges
245
+
246
+ same_offsets = all(
247
+ self.calibration[motor].homing_offset == cal.homing_offset
248
+ for motor, cal in motors_calibration.items()
249
+ )
250
+ return same_ranges and same_offsets
251
+
252
+ def read_calibration(self) -> dict[str, MotorCalibration]:
253
+ offsets, mins, maxes = {}, {}, {}
254
+ for motor in self.motors:
255
+ mins[motor] = self.read("Min_Position_Limit", motor, normalize=False)
256
+ maxes[motor] = self.read("Max_Position_Limit", motor, normalize=False)
257
+ offsets[motor] = (
258
+ self.read("Homing_Offset", motor, normalize=False) if self.protocol_version == 0 else 0
259
+ )
260
+
261
+ calibration = {}
262
+ for motor, m in self.motors.items():
263
+ calibration[motor] = MotorCalibration(
264
+ id=m.id,
265
+ drive_mode=0,
266
+ homing_offset=offsets[motor],
267
+ range_min=mins[motor],
268
+ range_max=maxes[motor],
269
+ )
270
+
271
+ return calibration
272
+
273
+ def write_calibration(self, calibration_dict: dict[str, MotorCalibration], cache: bool = True) -> None:
274
+ for motor, calibration in calibration_dict.items():
275
+ if self.protocol_version == 0:
276
+ self.write("Homing_Offset", motor, calibration.homing_offset)
277
+ self.write("Min_Position_Limit", motor, calibration.range_min)
278
+ self.write("Max_Position_Limit", motor, calibration.range_max)
279
+
280
+ if cache:
281
+ self.calibration = calibration_dict
282
+
283
+ def _get_half_turn_homings(self, positions: dict[NameOrID, Value]) -> dict[NameOrID, Value]:
284
+ """
285
+ On Feetech Motors:
286
+ Present_Position = Actual_Position - Homing_Offset
287
+ """
288
+ half_turn_homings = {}
289
+ for motor, pos in positions.items():
290
+ model = self._get_motor_model(motor)
291
+ max_res = self.model_resolution_table[model] - 1
292
+ half_turn_homings[motor] = pos - int(max_res / 2)
293
+
294
+ return half_turn_homings
295
+
296
+ def disable_torque(self, motors: str | list[str] | None = None, num_retry: int = 0) -> None:
297
+ for motor in self._get_motors_list(motors):
298
+ self.write("Torque_Enable", motor, TorqueMode.DISABLED.value, num_retry=num_retry)
299
+ self.write("Lock", motor, 0, num_retry=num_retry)
300
+
301
+ def _disable_torque(self, motor_id: int, model: str, num_retry: int = 0) -> None:
302
+ addr, length = get_address(self.model_ctrl_table, model, "Torque_Enable")
303
+ self._write(addr, length, motor_id, TorqueMode.DISABLED.value, num_retry=num_retry)
304
+ addr, length = get_address(self.model_ctrl_table, model, "Lock")
305
+ self._write(addr, length, motor_id, 0, num_retry=num_retry)
306
+
307
+ def enable_torque(self, motors: str | list[str] | None = None, num_retry: int = 0) -> None:
308
+ for motor in self._get_motors_list(motors):
309
+ self.write("Torque_Enable", motor, TorqueMode.ENABLED.value, num_retry=num_retry)
310
+ self.write("Lock", motor, 1, num_retry=num_retry)
311
+
312
+ def _encode_sign(self, data_name: str, ids_values: dict[int, int]) -> dict[int, int]:
313
+ for id_ in ids_values:
314
+ model = self._id_to_model(id_)
315
+ encoding_table = self.model_encoding_table.get(model)
316
+ if encoding_table and data_name in encoding_table:
317
+ sign_bit = encoding_table[data_name]
318
+ ids_values[id_] = encode_sign_magnitude(ids_values[id_], sign_bit)
319
+
320
+ return ids_values
321
+
322
+ def _decode_sign(self, data_name: str, ids_values: dict[int, int]) -> dict[int, int]:
323
+ for id_ in ids_values:
324
+ model = self._id_to_model(id_)
325
+ encoding_table = self.model_encoding_table.get(model)
326
+ if encoding_table and data_name in encoding_table:
327
+ sign_bit = encoding_table[data_name]
328
+ ids_values[id_] = decode_sign_magnitude(ids_values[id_], sign_bit)
329
+
330
+ return ids_values
331
+
332
+ def _split_into_byte_chunks(self, value: int, length: int) -> list[int]:
333
+ return _split_into_byte_chunks(value, length)
334
+
335
+ def _broadcast_ping(self) -> tuple[dict[int, int], int]:
336
+ import scservo_sdk as scs
337
+
338
+ data_list = {}
339
+
340
+ status_length = 6
341
+
342
+ rx_length = 0
343
+ wait_length = status_length * scs.MAX_ID
344
+
345
+ txpacket = [0] * 6
346
+
347
+ tx_time_per_byte = (1000.0 / self.port_handler.getBaudRate()) * 10.0
348
+
349
+ txpacket[scs.PKT_ID] = scs.BROADCAST_ID
350
+ txpacket[scs.PKT_LENGTH] = 2
351
+ txpacket[scs.PKT_INSTRUCTION] = scs.INST_PING
352
+
353
+ result = self.packet_handler.txPacket(self.port_handler, txpacket)
354
+ if result != scs.COMM_SUCCESS:
355
+ self.port_handler.is_using = False
356
+ return data_list, result
357
+
358
+ # set rx timeout
359
+ self.port_handler.setPacketTimeoutMillis((wait_length * tx_time_per_byte) + (3.0 * scs.MAX_ID) + 16.0)
360
+
361
+ rxpacket = []
362
+ while not self.port_handler.isPacketTimeout() and rx_length < wait_length:
363
+ rxpacket += self.port_handler.readPort(wait_length - rx_length)
364
+ rx_length = len(rxpacket)
365
+
366
+ self.port_handler.is_using = False
367
+
368
+ if rx_length == 0:
369
+ return data_list, scs.COMM_RX_TIMEOUT
370
+
371
+ while True:
372
+ if rx_length < status_length:
373
+ return data_list, scs.COMM_RX_CORRUPT
374
+
375
+ # find packet header
376
+ for idx in range(0, (rx_length - 1)):
377
+ if (rxpacket[idx] == 0xFF) and (rxpacket[idx + 1] == 0xFF):
378
+ break
379
+
380
+ if idx == 0: # found at the beginning of the packet
381
+ # calculate checksum
382
+ checksum = 0
383
+ for idx in range(2, status_length - 1): # except header & checksum
384
+ checksum += rxpacket[idx]
385
+
386
+ checksum = ~checksum & 0xFF
387
+ if rxpacket[status_length - 1] == checksum:
388
+ result = scs.COMM_SUCCESS
389
+ data_list[rxpacket[scs.PKT_ID]] = rxpacket[scs.PKT_ERROR]
390
+
391
+ del rxpacket[0:status_length]
392
+ rx_length = rx_length - status_length
393
+
394
+ if rx_length == 0:
395
+ return data_list, result
396
+ else:
397
+ result = scs.COMM_RX_CORRUPT
398
+ # remove header (0xFF 0xFF)
399
+ del rxpacket[0:2]
400
+ rx_length = rx_length - 2
401
+ else:
402
+ # remove unnecessary packets
403
+ del rxpacket[0:idx]
404
+ rx_length = rx_length - idx
405
+
406
+ def broadcast_ping(self, num_retry: int = 0, raise_on_error: bool = False) -> dict[int, int] | None:
407
+ self._assert_protocol_is_compatible("broadcast_ping")
408
+ for n_try in range(1 + num_retry):
409
+ ids_status, comm = self._broadcast_ping()
410
+ if self._is_comm_success(comm):
411
+ break
412
+ logger.debug(f"Broadcast ping failed on port '{self.port}' ({n_try=})")
413
+ logger.debug(self.packet_handler.getTxRxResult(comm))
414
+
415
+ if not self._is_comm_success(comm):
416
+ if raise_on_error:
417
+ raise ConnectionError(self.packet_handler.getTxRxResult(comm))
418
+ return
419
+
420
+ ids_errors = {id_: status for id_, status in ids_status.items() if self._is_error(status)}
421
+ if ids_errors:
422
+ display_dict = {id_: self.packet_handler.getRxPacketError(err) for id_, err in ids_errors.items()}
423
+ logger.error(f"Some motors found returned an error status:\n{pformat(display_dict, indent=4)}")
424
+
425
+ return self._read_model_number(list(ids_status), raise_on_error)
426
+
427
+ def _read_firmware_version(self, motor_ids: list[int], raise_on_error: bool = False) -> dict[int, str]:
428
+ firmware_versions = {}
429
+ for id_ in motor_ids:
430
+ firm_ver_major, comm, error = self._read(
431
+ *FIRMWARE_MAJOR_VERSION, id_, raise_on_error=raise_on_error
432
+ )
433
+ if not self._is_comm_success(comm) or self._is_error(error):
434
+ continue
435
+
436
+ firm_ver_minor, comm, error = self._read(
437
+ *FIRMWARE_MINOR_VERSION, id_, raise_on_error=raise_on_error
438
+ )
439
+ if not self._is_comm_success(comm) or self._is_error(error):
440
+ continue
441
+
442
+ firmware_versions[id_] = f"{firm_ver_major}.{firm_ver_minor}"
443
+
444
+ return firmware_versions
445
+
446
+ def _read_model_number(self, motor_ids: list[int], raise_on_error: bool = False) -> dict[int, int]:
447
+ model_numbers = {}
448
+ for id_ in motor_ids:
449
+ model_nb, comm, error = self._read(*MODEL_NUMBER, id_, raise_on_error=raise_on_error)
450
+ if not self._is_comm_success(comm) or self._is_error(error):
451
+ continue
452
+
453
+ model_numbers[id_] = model_nb
454
+
455
+ return model_numbers
tools/lerobot_v21_runtime/src/lerobot/motors/feetech/tables.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ FIRMWARE_MAJOR_VERSION = (0, 1)
16
+ FIRMWARE_MINOR_VERSION = (1, 1)
17
+ MODEL_NUMBER = (3, 2)
18
+
19
+ # TODO(Steven): Consider doing the following:
20
+ # from enum import Enum
21
+ # class MyControlTableKey(Enum):
22
+ # ID = "ID"
23
+ # GOAL_SPEED = "Goal_Speed"
24
+ # ...
25
+ #
26
+ # MY_CONTROL_TABLE ={
27
+ # MyControlTableKey.ID.value: (5,1)
28
+ # MyControlTableKey.GOAL_SPEED.value: (46, 2)
29
+ # ...
30
+ # }
31
+ # This allows me do to:
32
+ # bus.write(MyControlTableKey.GOAL_SPEED, ...)
33
+ # Instead of:
34
+ # bus.write("Goal_Speed", ...)
35
+ # This is important for two reasons:
36
+ # 1. The linter will tell me if I'm trying to use an invalid key, instead of me realizing when I get the RunTimeError
37
+ # 2. We can change the value of the MyControlTableKey enums without impacting the client code
38
+
39
+ # data_name: (address, size_byte)
40
+ # http://doc.feetech.cn/#/prodinfodownload?srcType=FT-SMS-STS-emanual-229f4476422d4059abfb1cb0
41
+ STS_SMS_SERIES_CONTROL_TABLE = {
42
+ # EPROM
43
+ "Firmware_Major_Version": FIRMWARE_MAJOR_VERSION, # read-only
44
+ "Firmware_Minor_Version": FIRMWARE_MINOR_VERSION, # read-only
45
+ "Model_Number": MODEL_NUMBER, # read-only
46
+ "ID": (5, 1),
47
+ "Baud_Rate": (6, 1),
48
+ "Return_Delay_Time": (7, 1),
49
+ "Response_Status_Level": (8, 1),
50
+ "Min_Position_Limit": (9, 2),
51
+ "Max_Position_Limit": (11, 2),
52
+ "Max_Temperature_Limit": (13, 1),
53
+ "Max_Voltage_Limit": (14, 1),
54
+ "Min_Voltage_Limit": (15, 1),
55
+ "Max_Torque_Limit": (16, 2),
56
+ "Phase": (18, 1),
57
+ "Unloading_Condition": (19, 1),
58
+ "LED_Alarm_Condition": (20, 1),
59
+ "P_Coefficient": (21, 1),
60
+ "D_Coefficient": (22, 1),
61
+ "I_Coefficient": (23, 1),
62
+ "Minimum_Startup_Force": (24, 2),
63
+ "CW_Dead_Zone": (26, 1),
64
+ "CCW_Dead_Zone": (27, 1),
65
+ "Protection_Current": (28, 2),
66
+ "Angular_Resolution": (30, 1),
67
+ "Homing_Offset": (31, 2),
68
+ "Operating_Mode": (33, 1),
69
+ "Protective_Torque": (34, 1),
70
+ "Protection_Time": (35, 1),
71
+ "Overload_Torque": (36, 1),
72
+ "Velocity_closed_loop_P_proportional_coefficient": (37, 1),
73
+ "Over_Current_Protection_Time": (38, 1),
74
+ "Velocity_closed_loop_I_integral_coefficient": (39, 1),
75
+ # SRAM
76
+ "Torque_Enable": (40, 1),
77
+ "Acceleration": (41, 1),
78
+ "Goal_Position": (42, 2),
79
+ "Goal_Time": (44, 2),
80
+ "Goal_Velocity": (46, 2),
81
+ "Torque_Limit": (48, 2),
82
+ "Lock": (55, 1),
83
+ "Present_Position": (56, 2), # read-only
84
+ "Present_Velocity": (58, 2), # read-only
85
+ "Present_Load": (60, 2), # read-only
86
+ "Present_Voltage": (62, 1), # read-only
87
+ "Present_Temperature": (63, 1), # read-only
88
+ "Status": (65, 1), # read-only
89
+ "Moving": (66, 1), # read-only
90
+ "Present_Current": (69, 2), # read-only
91
+ "Goal_Position_2": (71, 2), # read-only
92
+ # Factory
93
+ "Moving_Velocity": (80, 1),
94
+ "Moving_Velocity_Threshold": (80, 1),
95
+ "DTs": (81, 1), # (ms)
96
+ "Velocity_Unit_factor": (82, 1),
97
+ "Hts": (83, 1), # (ns) valid for firmware >= 2.54, other versions keep 0
98
+ "Maximum_Velocity_Limit": (84, 1),
99
+ "Maximum_Acceleration": (85, 1),
100
+ "Acceleration_Multiplier ": (86, 1), # Acceleration multiplier in effect when acceleration is 0
101
+ }
102
+
103
+ # http://doc.feetech.cn/#/prodinfodownload?srcType=FT-SCSCL-emanual-cbcc8ab2e3384282a01d4bf3
104
+ SCS_SERIES_CONTROL_TABLE = {
105
+ # EPROM
106
+ "Firmware_Major_Version": FIRMWARE_MAJOR_VERSION, # read-only
107
+ "Firmware_Minor_Version": FIRMWARE_MINOR_VERSION, # read-only
108
+ "Model_Number": MODEL_NUMBER, # read-only
109
+ "ID": (5, 1),
110
+ "Baud_Rate": (6, 1),
111
+ "Return_Delay_Time": (7, 1),
112
+ "Response_Status_Level": (8, 1),
113
+ "Min_Position_Limit": (9, 2),
114
+ "Max_Position_Limit": (11, 2),
115
+ "Max_Temperature_Limit": (13, 1),
116
+ "Max_Voltage_Limit": (14, 1),
117
+ "Min_Voltage_Limit": (15, 1),
118
+ "Max_Torque_Limit": (16, 2),
119
+ "Phase": (18, 1),
120
+ "Unloading_Condition": (19, 1),
121
+ "LED_Alarm_Condition": (20, 1),
122
+ "P_Coefficient": (21, 1),
123
+ "D_Coefficient": (22, 1),
124
+ "I_Coefficient": (23, 1),
125
+ "Minimum_Startup_Force": (24, 2),
126
+ "CW_Dead_Zone": (26, 1),
127
+ "CCW_Dead_Zone": (27, 1),
128
+ "Protective_Torque": (37, 1),
129
+ "Protection_Time": (38, 1),
130
+ # SRAM
131
+ "Torque_Enable": (40, 1),
132
+ "Acceleration": (41, 1),
133
+ "Goal_Position": (42, 2),
134
+ "Running_Time": (44, 2),
135
+ "Goal_Velocity": (46, 2),
136
+ "Lock": (48, 1),
137
+ "Present_Position": (56, 2), # read-only
138
+ "Present_Velocity": (58, 2), # read-only
139
+ "Present_Load": (60, 2), # read-only
140
+ "Present_Voltage": (62, 1), # read-only
141
+ "Present_Temperature": (63, 1), # read-only
142
+ "Sync_Write_Flag": (64, 1), # read-only
143
+ "Status": (65, 1), # read-only
144
+ "Moving": (66, 1), # read-only
145
+ # Factory
146
+ "PWM_Maximum_Step": (78, 1),
147
+ "Moving_Velocity_Threshold*50": (79, 1),
148
+ "DTs": (80, 1), # (ms)
149
+ "Minimum_Velocity_Limit*50": (81, 1),
150
+ "Maximum_Velocity_Limit*50": (82, 1),
151
+ "Acceleration_2": (83, 1), # don't know what that is
152
+ }
153
+
154
+ STS_SMS_SERIES_BAUDRATE_TABLE = {
155
+ 1_000_000: 0,
156
+ 500_000: 1,
157
+ 250_000: 2,
158
+ 128_000: 3,
159
+ 115_200: 4,
160
+ 57_600: 5,
161
+ 38_400: 6,
162
+ 19_200: 7,
163
+ }
164
+
165
+ SCS_SERIES_BAUDRATE_TABLE = {
166
+ 1_000_000: 0,
167
+ 500_000: 1,
168
+ 250_000: 2,
169
+ 128_000: 3,
170
+ 115_200: 4,
171
+ 57_600: 5,
172
+ 38_400: 6,
173
+ 19_200: 7,
174
+ }
175
+
176
+ MODEL_CONTROL_TABLE = {
177
+ "sts_series": STS_SMS_SERIES_CONTROL_TABLE,
178
+ "scs_series": SCS_SERIES_CONTROL_TABLE,
179
+ "sms_series": STS_SMS_SERIES_CONTROL_TABLE,
180
+ "sts3215": STS_SMS_SERIES_CONTROL_TABLE,
181
+ "sts3250": STS_SMS_SERIES_CONTROL_TABLE,
182
+ "scs0009": SCS_SERIES_CONTROL_TABLE,
183
+ "sm8512bl": STS_SMS_SERIES_CONTROL_TABLE,
184
+ }
185
+
186
+ MODEL_RESOLUTION = {
187
+ "sts_series": 4096,
188
+ "sms_series": 4096,
189
+ "scs_series": 1024,
190
+ "sts3215": 4096,
191
+ "sts3250": 4096,
192
+ "sm8512bl": 4096,
193
+ "scs0009": 1024,
194
+ }
195
+
196
+ MODEL_BAUDRATE_TABLE = {
197
+ "sts_series": STS_SMS_SERIES_BAUDRATE_TABLE,
198
+ "sms_series": STS_SMS_SERIES_BAUDRATE_TABLE,
199
+ "scs_series": SCS_SERIES_BAUDRATE_TABLE,
200
+ "sm8512bl": STS_SMS_SERIES_BAUDRATE_TABLE,
201
+ "sts3215": STS_SMS_SERIES_BAUDRATE_TABLE,
202
+ "sts3250": STS_SMS_SERIES_BAUDRATE_TABLE,
203
+ "scs0009": SCS_SERIES_BAUDRATE_TABLE,
204
+ }
205
+
206
+ # Sign-Magnitude encoding bits
207
+ STS_SMS_SERIES_ENCODINGS_TABLE = {
208
+ "Homing_Offset": 11,
209
+ "Goal_Velocity": 15,
210
+ "Present_Velocity": 15,
211
+ }
212
+
213
+ MODEL_ENCODING_TABLE = {
214
+ "sts_series": STS_SMS_SERIES_ENCODINGS_TABLE,
215
+ "sms_series": STS_SMS_SERIES_ENCODINGS_TABLE,
216
+ "scs_series": {},
217
+ "sts3215": STS_SMS_SERIES_ENCODINGS_TABLE,
218
+ "sts3250": STS_SMS_SERIES_ENCODINGS_TABLE,
219
+ "sm8512bl": STS_SMS_SERIES_ENCODINGS_TABLE,
220
+ "scs0009": {},
221
+ }
222
+
223
+ SCAN_BAUDRATES = [
224
+ 4_800,
225
+ 9_600,
226
+ 14_400,
227
+ 19_200,
228
+ 38_400,
229
+ 57_600,
230
+ 115_200,
231
+ 128_000,
232
+ 250_000,
233
+ 500_000,
234
+ 1_000_000,
235
+ ]
236
+
237
+ MODEL_NUMBER_TABLE = {
238
+ "sts3215": 777,
239
+ "sts3250": 2825,
240
+ "sm8512bl": 11272,
241
+ "scs0009": 1284,
242
+ }
243
+
244
+ MODEL_PROTOCOL = {
245
+ "sts_series": 0,
246
+ "sms_series": 0,
247
+ "scs_series": 1,
248
+ "sts3215": 0,
249
+ "sts3250": 0,
250
+ "sm8512bl": 0,
251
+ "scs0009": 1,
252
+ }
tools/lerobot_v21_runtime/src/lerobot/policies/act/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ ../../../../docs/source/policy_act_README.md
tools/lerobot_v21_runtime/src/lerobot/policies/act/configuration_act.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 Tony Z. Zhao and 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
+ from dataclasses import dataclass, field
17
+
18
+ from lerobot.configs.policies import PreTrainedConfig
19
+ from lerobot.configs.types import NormalizationMode
20
+ from lerobot.optim.optimizers import AdamWConfig
21
+
22
+
23
+ @PreTrainedConfig.register_subclass("act")
24
+ @dataclass
25
+ class ACTConfig(PreTrainedConfig):
26
+ """Configuration class for the Action Chunking Transformers policy.
27
+
28
+ Defaults are configured for training on bimanual Aloha tasks like "insertion" or "transfer".
29
+
30
+ The parameters you will most likely need to change are the ones which depend on the environment / sensors.
31
+ Those are: `input_shapes` and 'output_shapes`.
32
+
33
+ Notes on the inputs and outputs:
34
+ - Either:
35
+ - At least one key starting with "observation.image is required as an input.
36
+ AND/OR
37
+ - The key "observation.environment_state" is required as input.
38
+ - If there are multiple keys beginning with "observation.images." they are treated as multiple camera
39
+ views. Right now we only support all images having the same shape.
40
+ - May optionally work without an "observation.state" key for the proprioceptive robot state.
41
+ - "action" is required as an output key.
42
+
43
+ Args:
44
+ n_obs_steps: Number of environment steps worth of observations to pass to the policy (takes the
45
+ current step and additional steps going back).
46
+ chunk_size: The size of the action prediction "chunks" in units of environment steps.
47
+ n_action_steps: The number of action steps to run in the environment for one invocation of the policy.
48
+ This should be no greater than the chunk size. For example, if the chunk size size 100, you may
49
+ set this to 50. This would mean that the model predicts 100 steps worth of actions, runs 50 in the
50
+ environment, and throws the other 50 out.
51
+ input_shapes: A dictionary defining the shapes of the input data for the policy. The key represents
52
+ the input data name, and the value is a list indicating the dimensions of the corresponding data.
53
+ For example, "observation.image" refers to an input from a camera with dimensions [3, 96, 96],
54
+ indicating it has three color channels and 96x96 resolution. Importantly, `input_shapes` doesn't
55
+ include batch dimension or temporal dimension.
56
+ output_shapes: A dictionary defining the shapes of the output data for the policy. The key represents
57
+ the output data name, and the value is a list indicating the dimensions of the corresponding data.
58
+ For example, "action" refers to an output shape of [14], indicating 14-dimensional actions.
59
+ Importantly, `output_shapes` doesn't include batch dimension or temporal dimension.
60
+ input_normalization_modes: A dictionary with key representing the modality (e.g. "observation.state"),
61
+ and the value specifies the normalization mode to apply. The two available modes are "mean_std"
62
+ which subtracts the mean and divides by the standard deviation and "min_max" which rescale in a
63
+ [-1, 1] range.
64
+ output_normalization_modes: Similar dictionary as `normalize_input_modes`, but to unnormalize to the
65
+ original scale. Note that this is also used for normalizing the training targets.
66
+ vision_backbone: Name of the torchvision resnet backbone to use for encoding images.
67
+ pretrained_backbone_weights: Pretrained weights from torchvision to initialize the backbone.
68
+ `None` means no pretrained weights.
69
+ replace_final_stride_with_dilation: Whether to replace the ResNet's final 2x2 stride with a dilated
70
+ convolution.
71
+ pre_norm: Whether to use "pre-norm" in the transformer blocks.
72
+ dim_model: The transformer blocks' main hidden dimension.
73
+ n_heads: The number of heads to use in the transformer blocks' multi-head attention.
74
+ dim_feedforward: The dimension to expand the transformer's hidden dimension to in the feed-forward
75
+ layers.
76
+ feedforward_activation: The activation to use in the transformer block's feed-forward layers.
77
+ n_encoder_layers: The number of transformer layers to use for the transformer encoder.
78
+ n_decoder_layers: The number of transformer layers to use for the transformer decoder.
79
+ use_vae: Whether to use a variational objective during training. This introduces another transformer
80
+ which is used as the VAE's encoder (not to be confused with the transformer encoder - see
81
+ documentation in the policy class).
82
+ latent_dim: The VAE's latent dimension.
83
+ n_vae_encoder_layers: The number of transformer layers to use for the VAE's encoder.
84
+ temporal_ensemble_coeff: Coefficient for the exponential weighting scheme to apply for temporal
85
+ ensembling. Defaults to None which means temporal ensembling is not used. `n_action_steps` must be
86
+ 1 when using this feature, as inference needs to happen at every step to form an ensemble. For
87
+ more information on how ensembling works, please see `ACTTemporalEnsembler`.
88
+ dropout: Dropout to use in the transformer layers (see code for details).
89
+ kl_weight: The weight to use for the KL-divergence component of the loss if the variational objective
90
+ is enabled. Loss is then calculated as: `reconstruction_loss + kl_weight * kld_loss`.
91
+ """
92
+
93
+ # Input / output structure.
94
+ n_obs_steps: int = 1
95
+ chunk_size: int = 100
96
+ n_action_steps: int = 100
97
+
98
+ normalization_mapping: dict[str, NormalizationMode] = field(
99
+ default_factory=lambda: {
100
+ "VISUAL": NormalizationMode.MEAN_STD,
101
+ "STATE": NormalizationMode.MEAN_STD,
102
+ "ACTION": NormalizationMode.MEAN_STD,
103
+ }
104
+ )
105
+
106
+ # Architecture.
107
+ # Vision backbone.
108
+ vision_backbone: str = "resnet18"
109
+ pretrained_backbone_weights: str | None = "ResNet18_Weights.IMAGENET1K_V1"
110
+ replace_final_stride_with_dilation: int = False
111
+ # Transformer layers.
112
+ pre_norm: bool = False
113
+ dim_model: int = 512
114
+ n_heads: int = 8
115
+ dim_feedforward: int = 3200
116
+ feedforward_activation: str = "relu"
117
+ n_encoder_layers: int = 4
118
+ # Note: Although the original ACT implementation has 7 for `n_decoder_layers`, there is a bug in the code
119
+ # that means only the first layer is used. Here we match the original implementation by setting this to 1.
120
+ # See this issue https://github.com/tonyzhaozh/act/issues/25#issue-2258740521.
121
+ n_decoder_layers: int = 1
122
+ # VAE.
123
+ use_vae: bool = True
124
+ latent_dim: int = 32
125
+ n_vae_encoder_layers: int = 4
126
+
127
+ # Inference.
128
+ # Note: the value used in ACT when temporal ensembling is enabled is 0.01.
129
+ temporal_ensemble_coeff: float | None = None
130
+
131
+ # Training and loss computation.
132
+ dropout: float = 0.1
133
+ kl_weight: float = 10.0
134
+
135
+ # Training preset
136
+ optimizer_lr: float = 1e-5
137
+ optimizer_weight_decay: float = 1e-4
138
+ optimizer_lr_backbone: float = 1e-5
139
+
140
+ def __post_init__(self):
141
+ super().__post_init__()
142
+
143
+ """Input validation (not exhaustive)."""
144
+ if not self.vision_backbone.startswith("resnet"):
145
+ raise ValueError(
146
+ f"`vision_backbone` must be one of the ResNet variants. Got {self.vision_backbone}."
147
+ )
148
+ if self.temporal_ensemble_coeff is not None and self.n_action_steps > 1:
149
+ raise NotImplementedError(
150
+ "`n_action_steps` must be 1 when using temporal ensembling. This is "
151
+ "because the policy needs to be queried every step to compute the ensembled action."
152
+ )
153
+ if self.n_action_steps > self.chunk_size:
154
+ raise ValueError(
155
+ f"The chunk size is the upper bound for the number of action steps per model invocation. Got "
156
+ f"{self.n_action_steps} for `n_action_steps` and {self.chunk_size} for `chunk_size`."
157
+ )
158
+ if self.n_obs_steps != 1:
159
+ raise ValueError(
160
+ f"Multiple observation steps not handled yet. Got `nobs_steps={self.n_obs_steps}`"
161
+ )
162
+
163
+ def get_optimizer_preset(self) -> AdamWConfig:
164
+ return AdamWConfig(
165
+ lr=self.optimizer_lr,
166
+ weight_decay=self.optimizer_weight_decay,
167
+ )
168
+
169
+ def get_scheduler_preset(self) -> None:
170
+ return None
171
+
172
+ def validate_features(self) -> None:
173
+ if not self.image_features and not self.env_state_feature:
174
+ raise ValueError("You must provide at least one image or the environment state among the inputs.")
175
+
176
+ @property
177
+ def observation_delta_indices(self) -> None:
178
+ return None
179
+
180
+ @property
181
+ def action_delta_indices(self) -> list:
182
+ return list(range(self.chunk_size))
183
+
184
+ @property
185
+ def reward_delta_indices(self) -> None:
186
+ return None
tools/lerobot_v21_runtime/src/lerobot/policies/act/modeling_act.py ADDED
@@ -0,0 +1,766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 Tony Z. Zhao and 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
+ """Action Chunking Transformer Policy
17
+
18
+ As per Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardware (https://huggingface.co/papers/2304.13705).
19
+ The majority of changes here involve removing unused code, unifying naming, and adding helpful comments.
20
+ """
21
+
22
+ import math
23
+ from collections import deque
24
+ from collections.abc import Callable
25
+ from itertools import chain
26
+
27
+ import einops
28
+ import numpy as np
29
+ import torch
30
+ import torch.nn.functional as F # noqa: N812
31
+ import torchvision
32
+ from torch import Tensor, nn
33
+ from torchvision.models._utils import IntermediateLayerGetter
34
+ from torchvision.ops.misc import FrozenBatchNorm2d
35
+
36
+ from lerobot.constants import ACTION, OBS_IMAGES
37
+ from lerobot.policies.act.configuration_act import ACTConfig
38
+ from lerobot.policies.normalize import Normalize, Unnormalize
39
+ from lerobot.policies.pretrained import PreTrainedPolicy
40
+
41
+
42
+ class ACTPolicy(PreTrainedPolicy):
43
+ """
44
+ Action Chunking Transformer Policy as per Learning Fine-Grained Bimanual Manipulation with Low-Cost
45
+ Hardware (paper: https://huggingface.co/papers/2304.13705, code: https://github.com/tonyzhaozh/act)
46
+ """
47
+
48
+ config_class = ACTConfig
49
+ name = "act"
50
+
51
+ def __init__(
52
+ self,
53
+ config: ACTConfig,
54
+ dataset_stats: dict[str, dict[str, Tensor]] | None = None,
55
+ ):
56
+ """
57
+ Args:
58
+ config: Policy configuration class instance or None, in which case the default instantiation of
59
+ the configuration class is used.
60
+ dataset_stats: Dataset statistics to be used for normalization. If not passed here, it is expected
61
+ that they will be passed with a call to `load_state_dict` before the policy is used.
62
+ """
63
+ super().__init__(config)
64
+ config.validate_features()
65
+ self.config = config
66
+
67
+ self.normalize_inputs = Normalize(config.input_features, config.normalization_mapping, dataset_stats)
68
+ self.normalize_targets = Normalize(
69
+ config.output_features, config.normalization_mapping, dataset_stats
70
+ )
71
+ self.unnormalize_outputs = Unnormalize(
72
+ config.output_features, config.normalization_mapping, dataset_stats
73
+ )
74
+
75
+ self.model = ACT(config)
76
+
77
+ if config.temporal_ensemble_coeff is not None:
78
+ self.temporal_ensembler = ACTTemporalEnsembler(config.temporal_ensemble_coeff, config.chunk_size)
79
+
80
+ self.reset()
81
+
82
+ def get_optim_params(self) -> dict:
83
+ # TODO(aliberts, rcadene): As of now, lr_backbone == lr
84
+ # Should we remove this and just `return self.parameters()`?
85
+ return [
86
+ {
87
+ "params": [
88
+ p
89
+ for n, p in self.named_parameters()
90
+ if not n.startswith("model.backbone") and p.requires_grad
91
+ ]
92
+ },
93
+ {
94
+ "params": [
95
+ p
96
+ for n, p in self.named_parameters()
97
+ if n.startswith("model.backbone") and p.requires_grad
98
+ ],
99
+ "lr": self.config.optimizer_lr_backbone,
100
+ },
101
+ ]
102
+
103
+ def reset(self):
104
+ """This should be called whenever the environment is reset."""
105
+ if self.config.temporal_ensemble_coeff is not None:
106
+ self.temporal_ensembler.reset()
107
+ else:
108
+ self._action_queue = deque([], maxlen=self.config.n_action_steps)
109
+
110
+ @torch.no_grad()
111
+ def select_action(self, batch: dict[str, Tensor]) -> Tensor:
112
+ """Select a single action given environment observations.
113
+
114
+ This method wraps `select_actions` in order to return one action at a time for execution in the
115
+ environment. It works by managing the actions in a queue and only calling `select_actions` when the
116
+ queue is empty.
117
+ """
118
+ self.eval() # keeping the policy in eval mode as it could be set to train mode while queue is consumed
119
+
120
+ if self.config.temporal_ensemble_coeff is not None:
121
+ actions = self.predict_action_chunk(batch)
122
+ action = self.temporal_ensembler.update(actions)
123
+ return action
124
+
125
+ # Action queue logic for n_action_steps > 1. When the action_queue is depleted, populate it by
126
+ # querying the policy.
127
+ if len(self._action_queue) == 0:
128
+ actions = self.predict_action_chunk(batch)[:, : self.config.n_action_steps]
129
+
130
+ # `self.model.forward` returns a (batch_size, n_action_steps, action_dim) tensor, but the queue
131
+ # effectively has shape (n_action_steps, batch_size, *), hence the transpose.
132
+ self._action_queue.extend(actions.transpose(0, 1))
133
+ return self._action_queue.popleft()
134
+
135
+ @torch.no_grad()
136
+ def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor:
137
+ """Predict a chunk of actions given environment observations."""
138
+ self.eval()
139
+
140
+ batch = self.normalize_inputs(batch)
141
+ if self.config.image_features:
142
+ batch = dict(batch) # shallow copy so that adding a key doesn't modify the original
143
+ batch[OBS_IMAGES] = [batch[key] for key in self.config.image_features]
144
+
145
+ actions = self.model(batch)[0]
146
+ actions = self.unnormalize_outputs({ACTION: actions})[ACTION]
147
+ return actions
148
+
149
+ def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, dict]:
150
+ """Run the batch through the model and compute the loss for training or validation."""
151
+ batch = self.normalize_inputs(batch)
152
+ if self.config.image_features:
153
+ batch = dict(batch) # shallow copy so that adding a key doesn't modify the original
154
+ batch[OBS_IMAGES] = [batch[key] for key in self.config.image_features]
155
+
156
+ batch = self.normalize_targets(batch)
157
+ actions_hat, (mu_hat, log_sigma_x2_hat) = self.model(batch)
158
+
159
+ l1_loss = (
160
+ F.l1_loss(batch[ACTION], actions_hat, reduction="none") * ~batch["action_is_pad"].unsqueeze(-1)
161
+ ).mean()
162
+
163
+ loss_dict = {"l1_loss": l1_loss.item()}
164
+ if self.config.use_vae:
165
+ # Calculate Dₖₗ(latent_pdf || standard_normal). Note: After computing the KL-divergence for
166
+ # each dimension independently, we sum over the latent dimension to get the total
167
+ # KL-divergence per batch element, then take the mean over the batch.
168
+ # (See App. B of https://huggingface.co/papers/1312.6114 for more details).
169
+ mean_kld = (
170
+ (-0.5 * (1 + log_sigma_x2_hat - mu_hat.pow(2) - (log_sigma_x2_hat).exp())).sum(-1).mean()
171
+ )
172
+ loss_dict["kld_loss"] = mean_kld.item()
173
+ loss = l1_loss + mean_kld * self.config.kl_weight
174
+ else:
175
+ loss = l1_loss
176
+
177
+ return loss, loss_dict
178
+
179
+
180
+ class ACTTemporalEnsembler:
181
+ def __init__(self, temporal_ensemble_coeff: float, chunk_size: int) -> None:
182
+ """Temporal ensembling as described in Algorithm 2 of https://huggingface.co/papers/2304.13705.
183
+
184
+ The weights are calculated as wᵢ = exp(-temporal_ensemble_coeff * i) where w₀ is the oldest action.
185
+ They are then normalized to sum to 1 by dividing by Σwᵢ. Here's some intuition around how the
186
+ coefficient works:
187
+ - Setting it to 0 uniformly weighs all actions.
188
+ - Setting it positive gives more weight to older actions.
189
+ - Setting it negative gives more weight to newer actions.
190
+ NOTE: The default value for `temporal_ensemble_coeff` used by the original ACT work is 0.01. This
191
+ results in older actions being weighed more highly than newer actions (the experiments documented in
192
+ https://github.com/huggingface/lerobot/pull/319 hint at why highly weighing new actions might be
193
+ detrimental: doing so aggressively may diminish the benefits of action chunking).
194
+
195
+ Here we use an online method for computing the average rather than caching a history of actions in
196
+ order to compute the average offline. For a simple 1D sequence it looks something like:
197
+
198
+ ```
199
+ import torch
200
+
201
+ seq = torch.linspace(8, 8.5, 100)
202
+ print(seq)
203
+
204
+ m = 0.01
205
+ exp_weights = torch.exp(-m * torch.arange(len(seq)))
206
+ print(exp_weights)
207
+
208
+ # Calculate offline
209
+ avg = (exp_weights * seq).sum() / exp_weights.sum()
210
+ print("offline", avg)
211
+
212
+ # Calculate online
213
+ for i, item in enumerate(seq):
214
+ if i == 0:
215
+ avg = item
216
+ continue
217
+ avg *= exp_weights[:i].sum()
218
+ avg += item * exp_weights[i]
219
+ avg /= exp_weights[: i + 1].sum()
220
+ print("online", avg)
221
+ ```
222
+ """
223
+ self.chunk_size = chunk_size
224
+ self.ensemble_weights = torch.exp(-temporal_ensemble_coeff * torch.arange(chunk_size))
225
+ self.ensemble_weights_cumsum = torch.cumsum(self.ensemble_weights, dim=0)
226
+ self.reset()
227
+
228
+ def reset(self):
229
+ """Resets the online computation variables."""
230
+ self.ensembled_actions = None
231
+ # (chunk_size,) count of how many actions are in the ensemble for each time step in the sequence.
232
+ self.ensembled_actions_count = None
233
+
234
+ def update(self, actions: Tensor) -> Tensor:
235
+ """
236
+ Takes a (batch, chunk_size, action_dim) sequence of actions, update the temporal ensemble for all
237
+ time steps, and pop/return the next batch of actions in the sequence.
238
+ """
239
+ self.ensemble_weights = self.ensemble_weights.to(device=actions.device)
240
+ self.ensemble_weights_cumsum = self.ensemble_weights_cumsum.to(device=actions.device)
241
+ if self.ensembled_actions is None:
242
+ # Initializes `self._ensembled_action` to the sequence of actions predicted during the first
243
+ # time step of the episode.
244
+ self.ensembled_actions = actions.clone()
245
+ # Note: The last dimension is unsqueeze to make sure we can broadcast properly for tensor
246
+ # operations later.
247
+ self.ensembled_actions_count = torch.ones(
248
+ (self.chunk_size, 1), dtype=torch.long, device=self.ensembled_actions.device
249
+ )
250
+ else:
251
+ # self.ensembled_actions will have shape (batch_size, chunk_size - 1, action_dim). Compute
252
+ # the online update for those entries.
253
+ self.ensembled_actions *= self.ensemble_weights_cumsum[self.ensembled_actions_count - 1]
254
+ self.ensembled_actions += actions[:, :-1] * self.ensemble_weights[self.ensembled_actions_count]
255
+ self.ensembled_actions /= self.ensemble_weights_cumsum[self.ensembled_actions_count]
256
+ self.ensembled_actions_count = torch.clamp(self.ensembled_actions_count + 1, max=self.chunk_size)
257
+ # The last action, which has no prior online average, needs to get concatenated onto the end.
258
+ self.ensembled_actions = torch.cat([self.ensembled_actions, actions[:, -1:]], dim=1)
259
+ self.ensembled_actions_count = torch.cat(
260
+ [self.ensembled_actions_count, torch.ones_like(self.ensembled_actions_count[-1:])]
261
+ )
262
+ # "Consume" the first action.
263
+ action, self.ensembled_actions, self.ensembled_actions_count = (
264
+ self.ensembled_actions[:, 0],
265
+ self.ensembled_actions[:, 1:],
266
+ self.ensembled_actions_count[1:],
267
+ )
268
+ return action
269
+
270
+
271
+ class ACT(nn.Module):
272
+ """Action Chunking Transformer: The underlying neural network for ACTPolicy.
273
+
274
+ Note: In this code we use the terms `vae_encoder`, 'encoder', `decoder`. The meanings are as follows.
275
+ - The `vae_encoder` is, as per the literature around variational auto-encoders (VAE), the part of the
276
+ model that encodes the target data (a sequence of actions), and the condition (the robot
277
+ joint-space).
278
+ - A transformer with an `encoder` (not the VAE encoder) and `decoder` (not the VAE decoder) with
279
+ cross-attention is used as the VAE decoder. For these terms, we drop the `vae_` prefix because we
280
+ have an option to train this model without the variational objective (in which case we drop the
281
+ `vae_encoder` altogether, and nothing about this model has anything to do with a VAE).
282
+
283
+ Transformer
284
+ Used alone for inference
285
+ (acts as VAE decoder
286
+ during training)
287
+ ┌───────────────────────┐
288
+ │ Outputs │
289
+ │ ▲ │
290
+ │ ┌─────►┌───────┐ │
291
+ ┌──────┐ │ │ │Transf.│ │
292
+ │ │ │ ├─────►│decoder│ │
293
+ ┌────┴────┐ │ │ │ │ │ │
294
+ │ │ │ │ ┌───┴───┬─►│ │ │
295
+ │ VAE │ │ │ │ │ └───────┘ │
296
+ │ encoder │ │ │ │Transf.│ │
297
+ │ │ │ │ │encoder│ │
298
+ └───▲─────┘ │ │ │ │ │
299
+ │ │ │ └▲──▲─▲─┘ │
300
+ │ │ │ │ │ │ │
301
+ inputs └─────┼──┘ │ image emb. │
302
+ │ state emb. │
303
+ └───────────────────────┘
304
+ """
305
+
306
+ def __init__(self, config: ACTConfig):
307
+ # BERT style VAE encoder with input tokens [cls, robot_state, *action_sequence].
308
+ # The cls token forms parameters of the latent's distribution (like this [*means, *log_variances]).
309
+ super().__init__()
310
+ self.config = config
311
+
312
+ if self.config.use_vae:
313
+ self.vae_encoder = ACTEncoder(config, is_vae_encoder=True)
314
+ self.vae_encoder_cls_embed = nn.Embedding(1, config.dim_model)
315
+ # Projection layer for joint-space configuration to hidden dimension.
316
+ if self.config.robot_state_feature:
317
+ self.vae_encoder_robot_state_input_proj = nn.Linear(
318
+ self.config.robot_state_feature.shape[0], config.dim_model
319
+ )
320
+ # Projection layer for action (joint-space target) to hidden dimension.
321
+ self.vae_encoder_action_input_proj = nn.Linear(
322
+ self.config.action_feature.shape[0],
323
+ config.dim_model,
324
+ )
325
+ # Projection layer from the VAE encoder's output to the latent distribution's parameter space.
326
+ self.vae_encoder_latent_output_proj = nn.Linear(config.dim_model, config.latent_dim * 2)
327
+ # Fixed sinusoidal positional embedding for the input to the VAE encoder. Unsqueeze for batch
328
+ # dimension.
329
+ num_input_token_encoder = 1 + config.chunk_size
330
+ if self.config.robot_state_feature:
331
+ num_input_token_encoder += 1
332
+ self.register_buffer(
333
+ "vae_encoder_pos_enc",
334
+ create_sinusoidal_pos_embedding(num_input_token_encoder, config.dim_model).unsqueeze(0),
335
+ )
336
+
337
+ # Backbone for image feature extraction.
338
+ if self.config.image_features:
339
+ backbone_model = getattr(torchvision.models, config.vision_backbone)(
340
+ replace_stride_with_dilation=[False, False, config.replace_final_stride_with_dilation],
341
+ weights=config.pretrained_backbone_weights,
342
+ norm_layer=FrozenBatchNorm2d,
343
+ )
344
+ # Note: The assumption here is that we are using a ResNet model (and hence layer4 is the final
345
+ # feature map).
346
+ # Note: The forward method of this returns a dict: {"feature_map": output}.
347
+ self.backbone = IntermediateLayerGetter(backbone_model, return_layers={"layer4": "feature_map"})
348
+
349
+ # Transformer (acts as VAE decoder when training with the variational objective).
350
+ self.encoder = ACTEncoder(config)
351
+ self.decoder = ACTDecoder(config)
352
+
353
+ # Transformer encoder input projections. The tokens will be structured like
354
+ # [latent, (robot_state), (env_state), (image_feature_map_pixels)].
355
+ if self.config.robot_state_feature:
356
+ self.encoder_robot_state_input_proj = nn.Linear(
357
+ self.config.robot_state_feature.shape[0], config.dim_model
358
+ )
359
+ if self.config.env_state_feature:
360
+ self.encoder_env_state_input_proj = nn.Linear(
361
+ self.config.env_state_feature.shape[0], config.dim_model
362
+ )
363
+ self.encoder_latent_input_proj = nn.Linear(config.latent_dim, config.dim_model)
364
+ if self.config.image_features:
365
+ self.encoder_img_feat_input_proj = nn.Conv2d(
366
+ backbone_model.fc.in_features, config.dim_model, kernel_size=1
367
+ )
368
+ # Transformer encoder positional embeddings.
369
+ n_1d_tokens = 1 # for the latent
370
+ if self.config.robot_state_feature:
371
+ n_1d_tokens += 1
372
+ if self.config.env_state_feature:
373
+ n_1d_tokens += 1
374
+ self.encoder_1d_feature_pos_embed = nn.Embedding(n_1d_tokens, config.dim_model)
375
+ if self.config.image_features:
376
+ self.encoder_cam_feat_pos_embed = ACTSinusoidalPositionEmbedding2d(config.dim_model // 2)
377
+
378
+ # Transformer decoder.
379
+ # Learnable positional embedding for the transformer's decoder (in the style of DETR object queries).
380
+ self.decoder_pos_embed = nn.Embedding(config.chunk_size, config.dim_model)
381
+
382
+ # Final action regression head on the output of the transformer's decoder.
383
+ self.action_head = nn.Linear(config.dim_model, self.config.action_feature.shape[0])
384
+
385
+ self._reset_parameters()
386
+
387
+ def _reset_parameters(self):
388
+ """Xavier-uniform initialization of the transformer parameters as in the original code."""
389
+ for p in chain(self.encoder.parameters(), self.decoder.parameters()):
390
+ if p.dim() > 1:
391
+ nn.init.xavier_uniform_(p)
392
+
393
+ def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, tuple[Tensor, Tensor] | tuple[None, None]]:
394
+ """A forward pass through the Action Chunking Transformer (with optional VAE encoder).
395
+
396
+ `batch` should have the following structure:
397
+ {
398
+ [robot_state_feature] (optional): (B, state_dim) batch of robot states.
399
+
400
+ [image_features]: (B, n_cameras, C, H, W) batch of images.
401
+ AND/OR
402
+ [env_state_feature]: (B, env_dim) batch of environment states.
403
+
404
+ [action_feature] (optional, only if training with VAE): (B, chunk_size, action dim) batch of actions.
405
+ }
406
+
407
+ Returns:
408
+ (B, chunk_size, action_dim) batch of action sequences
409
+ Tuple containing the latent PDF's parameters (mean, log(σ²)) both as (B, L) tensors where L is the
410
+ latent dimension.
411
+ """
412
+ if self.config.use_vae and self.training:
413
+ assert "action" in batch, (
414
+ "actions must be provided when using the variational objective in training mode."
415
+ )
416
+
417
+ if "observation.images" in batch:
418
+ batch_size = batch["observation.images"][0].shape[0]
419
+ else:
420
+ batch_size = batch["observation.environment_state"].shape[0]
421
+
422
+ # Prepare the latent for input to the transformer encoder.
423
+ if self.config.use_vae and "action" in batch and self.training:
424
+ # Prepare the input to the VAE encoder: [cls, *joint_space_configuration, *action_sequence].
425
+ cls_embed = einops.repeat(
426
+ self.vae_encoder_cls_embed.weight, "1 d -> b 1 d", b=batch_size
427
+ ) # (B, 1, D)
428
+ if self.config.robot_state_feature:
429
+ robot_state_embed = self.vae_encoder_robot_state_input_proj(batch["observation.state"])
430
+ robot_state_embed = robot_state_embed.unsqueeze(1) # (B, 1, D)
431
+ action_embed = self.vae_encoder_action_input_proj(batch["action"]) # (B, S, D)
432
+
433
+ if self.config.robot_state_feature:
434
+ vae_encoder_input = [cls_embed, robot_state_embed, action_embed] # (B, S+2, D)
435
+ else:
436
+ vae_encoder_input = [cls_embed, action_embed]
437
+ vae_encoder_input = torch.cat(vae_encoder_input, axis=1)
438
+
439
+ # Prepare fixed positional embedding.
440
+ # Note: detach() shouldn't be necessary but leaving it the same as the original code just in case.
441
+ pos_embed = self.vae_encoder_pos_enc.clone().detach() # (1, S+2, D)
442
+
443
+ # Prepare key padding mask for the transformer encoder. We have 1 or 2 extra tokens at the start of the
444
+ # sequence depending whether we use the input states or not (cls and robot state)
445
+ # False means not a padding token.
446
+ cls_joint_is_pad = torch.full(
447
+ (batch_size, 2 if self.config.robot_state_feature else 1),
448
+ False,
449
+ device=batch["observation.state"].device,
450
+ )
451
+ key_padding_mask = torch.cat(
452
+ [cls_joint_is_pad, batch["action_is_pad"]], axis=1
453
+ ) # (bs, seq+1 or 2)
454
+
455
+ # Forward pass through VAE encoder to get the latent PDF parameters.
456
+ cls_token_out = self.vae_encoder(
457
+ vae_encoder_input.permute(1, 0, 2),
458
+ pos_embed=pos_embed.permute(1, 0, 2),
459
+ key_padding_mask=key_padding_mask,
460
+ )[0] # select the class token, with shape (B, D)
461
+ latent_pdf_params = self.vae_encoder_latent_output_proj(cls_token_out)
462
+ mu = latent_pdf_params[:, : self.config.latent_dim]
463
+ # This is 2log(sigma). Done this way to match the original implementation.
464
+ log_sigma_x2 = latent_pdf_params[:, self.config.latent_dim :]
465
+
466
+ # Sample the latent with the reparameterization trick.
467
+ latent_sample = mu + log_sigma_x2.div(2).exp() * torch.randn_like(mu)
468
+ else:
469
+ # When not using the VAE encoder, we set the latent to be all zeros.
470
+ mu = log_sigma_x2 = None
471
+ # TODO(rcadene, alexander-soare): remove call to `.to` to speedup forward ; precompute and use buffer
472
+ latent_sample = torch.zeros([batch_size, self.config.latent_dim], dtype=torch.float32).to(
473
+ batch["observation.state"].device
474
+ )
475
+
476
+ # Prepare transformer encoder inputs.
477
+ encoder_in_tokens = [self.encoder_latent_input_proj(latent_sample)]
478
+ encoder_in_pos_embed = list(self.encoder_1d_feature_pos_embed.weight.unsqueeze(1))
479
+ # Robot state token.
480
+ if self.config.robot_state_feature:
481
+ encoder_in_tokens.append(self.encoder_robot_state_input_proj(batch["observation.state"]))
482
+ # Environment state token.
483
+ if self.config.env_state_feature:
484
+ encoder_in_tokens.append(
485
+ self.encoder_env_state_input_proj(batch["observation.environment_state"])
486
+ )
487
+
488
+ if self.config.image_features:
489
+ # For a list of images, the H and W may vary but H*W is constant.
490
+ # NOTE: If modifying this section, verify on MPS devices that
491
+ # gradients remain stable (no explosions or NaNs).
492
+ for img in batch["observation.images"]:
493
+ cam_features = self.backbone(img)["feature_map"]
494
+ cam_pos_embed = self.encoder_cam_feat_pos_embed(cam_features).to(dtype=cam_features.dtype)
495
+ cam_features = self.encoder_img_feat_input_proj(cam_features)
496
+
497
+ # Rearrange features to (sequence, batch, dim).
498
+ cam_features = einops.rearrange(cam_features, "b c h w -> (h w) b c")
499
+ cam_pos_embed = einops.rearrange(cam_pos_embed, "b c h w -> (h w) b c")
500
+
501
+ # Extend immediately instead of accumulating and concatenating
502
+ # Convert to list to extend properly
503
+ encoder_in_tokens.extend(list(cam_features))
504
+ encoder_in_pos_embed.extend(list(cam_pos_embed))
505
+
506
+ # Stack all tokens along the sequence dimension.
507
+ encoder_in_tokens = torch.stack(encoder_in_tokens, axis=0)
508
+ encoder_in_pos_embed = torch.stack(encoder_in_pos_embed, axis=0)
509
+
510
+ # Forward pass through the transformer modules.
511
+ encoder_out = self.encoder(encoder_in_tokens, pos_embed=encoder_in_pos_embed)
512
+ # TODO(rcadene, alexander-soare): remove call to `device` ; precompute and use buffer
513
+ decoder_in = torch.zeros(
514
+ (self.config.chunk_size, batch_size, self.config.dim_model),
515
+ dtype=encoder_in_pos_embed.dtype,
516
+ device=encoder_in_pos_embed.device,
517
+ )
518
+ decoder_out = self.decoder(
519
+ decoder_in,
520
+ encoder_out,
521
+ encoder_pos_embed=encoder_in_pos_embed,
522
+ decoder_pos_embed=self.decoder_pos_embed.weight.unsqueeze(1),
523
+ )
524
+
525
+ # Move back to (B, S, C).
526
+ decoder_out = decoder_out.transpose(0, 1)
527
+
528
+ actions = self.action_head(decoder_out)
529
+
530
+ return actions, (mu, log_sigma_x2)
531
+
532
+
533
+ class ACTEncoder(nn.Module):
534
+ """Convenience module for running multiple encoder layers, maybe followed by normalization."""
535
+
536
+ def __init__(self, config: ACTConfig, is_vae_encoder: bool = False):
537
+ super().__init__()
538
+ self.is_vae_encoder = is_vae_encoder
539
+ num_layers = config.n_vae_encoder_layers if self.is_vae_encoder else config.n_encoder_layers
540
+ self.layers = nn.ModuleList([ACTEncoderLayer(config) for _ in range(num_layers)])
541
+ self.norm = nn.LayerNorm(config.dim_model) if config.pre_norm else nn.Identity()
542
+
543
+ def forward(
544
+ self, x: Tensor, pos_embed: Tensor | None = None, key_padding_mask: Tensor | None = None
545
+ ) -> Tensor:
546
+ for layer in self.layers:
547
+ x = layer(x, pos_embed=pos_embed, key_padding_mask=key_padding_mask)
548
+ x = self.norm(x)
549
+ return x
550
+
551
+
552
+ class ACTEncoderLayer(nn.Module):
553
+ def __init__(self, config: ACTConfig):
554
+ super().__init__()
555
+ self.self_attn = nn.MultiheadAttention(config.dim_model, config.n_heads, dropout=config.dropout)
556
+
557
+ # Feed forward layers.
558
+ self.linear1 = nn.Linear(config.dim_model, config.dim_feedforward)
559
+ self.dropout = nn.Dropout(config.dropout)
560
+ self.linear2 = nn.Linear(config.dim_feedforward, config.dim_model)
561
+
562
+ self.norm1 = nn.LayerNorm(config.dim_model)
563
+ self.norm2 = nn.LayerNorm(config.dim_model)
564
+ self.dropout1 = nn.Dropout(config.dropout)
565
+ self.dropout2 = nn.Dropout(config.dropout)
566
+
567
+ self.activation = get_activation_fn(config.feedforward_activation)
568
+ self.pre_norm = config.pre_norm
569
+
570
+ def forward(self, x, pos_embed: Tensor | None = None, key_padding_mask: Tensor | None = None) -> Tensor:
571
+ skip = x
572
+ if self.pre_norm:
573
+ x = self.norm1(x)
574
+ q = k = x if pos_embed is None else x + pos_embed
575
+ x = self.self_attn(q, k, value=x, key_padding_mask=key_padding_mask)
576
+ x = x[0] # note: [0] to select just the output, not the attention weights
577
+ x = skip + self.dropout1(x)
578
+ if self.pre_norm:
579
+ skip = x
580
+ x = self.norm2(x)
581
+ else:
582
+ x = self.norm1(x)
583
+ skip = x
584
+ x = self.linear2(self.dropout(self.activation(self.linear1(x))))
585
+ x = skip + self.dropout2(x)
586
+ if not self.pre_norm:
587
+ x = self.norm2(x)
588
+ return x
589
+
590
+
591
+ class ACTDecoder(nn.Module):
592
+ def __init__(self, config: ACTConfig):
593
+ """Convenience module for running multiple decoder layers followed by normalization."""
594
+ super().__init__()
595
+ self.layers = nn.ModuleList([ACTDecoderLayer(config) for _ in range(config.n_decoder_layers)])
596
+ self.norm = nn.LayerNorm(config.dim_model)
597
+
598
+ def forward(
599
+ self,
600
+ x: Tensor,
601
+ encoder_out: Tensor,
602
+ decoder_pos_embed: Tensor | None = None,
603
+ encoder_pos_embed: Tensor | None = None,
604
+ ) -> Tensor:
605
+ for layer in self.layers:
606
+ x = layer(
607
+ x, encoder_out, decoder_pos_embed=decoder_pos_embed, encoder_pos_embed=encoder_pos_embed
608
+ )
609
+ if self.norm is not None:
610
+ x = self.norm(x)
611
+ return x
612
+
613
+
614
+ class ACTDecoderLayer(nn.Module):
615
+ def __init__(self, config: ACTConfig):
616
+ super().__init__()
617
+ self.self_attn = nn.MultiheadAttention(config.dim_model, config.n_heads, dropout=config.dropout)
618
+ self.multihead_attn = nn.MultiheadAttention(config.dim_model, config.n_heads, dropout=config.dropout)
619
+
620
+ # Feed forward layers.
621
+ self.linear1 = nn.Linear(config.dim_model, config.dim_feedforward)
622
+ self.dropout = nn.Dropout(config.dropout)
623
+ self.linear2 = nn.Linear(config.dim_feedforward, config.dim_model)
624
+
625
+ self.norm1 = nn.LayerNorm(config.dim_model)
626
+ self.norm2 = nn.LayerNorm(config.dim_model)
627
+ self.norm3 = nn.LayerNorm(config.dim_model)
628
+ self.dropout1 = nn.Dropout(config.dropout)
629
+ self.dropout2 = nn.Dropout(config.dropout)
630
+ self.dropout3 = nn.Dropout(config.dropout)
631
+
632
+ self.activation = get_activation_fn(config.feedforward_activation)
633
+ self.pre_norm = config.pre_norm
634
+
635
+ def maybe_add_pos_embed(self, tensor: Tensor, pos_embed: Tensor | None) -> Tensor:
636
+ return tensor if pos_embed is None else tensor + pos_embed
637
+
638
+ def forward(
639
+ self,
640
+ x: Tensor,
641
+ encoder_out: Tensor,
642
+ decoder_pos_embed: Tensor | None = None,
643
+ encoder_pos_embed: Tensor | None = None,
644
+ ) -> Tensor:
645
+ """
646
+ Args:
647
+ x: (Decoder Sequence, Batch, Channel) tensor of input tokens.
648
+ encoder_out: (Encoder Sequence, B, C) output features from the last layer of the encoder we are
649
+ cross-attending with.
650
+ decoder_pos_embed: (ES, 1, C) positional embedding for keys (from the encoder).
651
+ encoder_pos_embed: (DS, 1, C) Positional_embedding for the queries (from the decoder).
652
+ Returns:
653
+ (DS, B, C) tensor of decoder output features.
654
+ """
655
+ skip = x
656
+ if self.pre_norm:
657
+ x = self.norm1(x)
658
+ q = k = self.maybe_add_pos_embed(x, decoder_pos_embed)
659
+ x = self.self_attn(q, k, value=x)[0] # select just the output, not the attention weights
660
+ x = skip + self.dropout1(x)
661
+ if self.pre_norm:
662
+ skip = x
663
+ x = self.norm2(x)
664
+ else:
665
+ x = self.norm1(x)
666
+ skip = x
667
+ x = self.multihead_attn(
668
+ query=self.maybe_add_pos_embed(x, decoder_pos_embed),
669
+ key=self.maybe_add_pos_embed(encoder_out, encoder_pos_embed),
670
+ value=encoder_out,
671
+ )[0] # select just the output, not the attention weights
672
+ x = skip + self.dropout2(x)
673
+ if self.pre_norm:
674
+ skip = x
675
+ x = self.norm3(x)
676
+ else:
677
+ x = self.norm2(x)
678
+ skip = x
679
+ x = self.linear2(self.dropout(self.activation(self.linear1(x))))
680
+ x = skip + self.dropout3(x)
681
+ if not self.pre_norm:
682
+ x = self.norm3(x)
683
+ return x
684
+
685
+
686
+ def create_sinusoidal_pos_embedding(num_positions: int, dimension: int) -> Tensor:
687
+ """1D sinusoidal positional embeddings as in Attention is All You Need.
688
+
689
+ Args:
690
+ num_positions: Number of token positions required.
691
+ Returns: (num_positions, dimension) position embeddings (the first dimension is the batch dimension).
692
+
693
+ """
694
+
695
+ def get_position_angle_vec(position):
696
+ return [position / np.power(10000, 2 * (hid_j // 2) / dimension) for hid_j in range(dimension)]
697
+
698
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(num_positions)])
699
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
700
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
701
+ return torch.from_numpy(sinusoid_table).float()
702
+
703
+
704
+ class ACTSinusoidalPositionEmbedding2d(nn.Module):
705
+ """2D sinusoidal positional embeddings similar to what's presented in Attention Is All You Need.
706
+
707
+ The variation is that the position indices are normalized in [0, 2π] (not quite: the lower bound is 1/H
708
+ for the vertical direction, and 1/W for the horizontal direction.
709
+ """
710
+
711
+ def __init__(self, dimension: int):
712
+ """
713
+ Args:
714
+ dimension: The desired dimension of the embeddings.
715
+ """
716
+ super().__init__()
717
+ self.dimension = dimension
718
+ self._two_pi = 2 * math.pi
719
+ self._eps = 1e-6
720
+ # Inverse "common ratio" for the geometric progression in sinusoid frequencies.
721
+ self._temperature = 10000
722
+
723
+ def forward(self, x: Tensor) -> Tensor:
724
+ """
725
+ Args:
726
+ x: A (B, C, H, W) batch of 2D feature map to generate the embeddings for.
727
+ Returns:
728
+ A (1, C, H, W) batch of corresponding sinusoidal positional embeddings.
729
+ """
730
+ not_mask = torch.ones_like(x[0, :1]) # (1, H, W)
731
+ # Note: These are like range(1, H+1) and range(1, W+1) respectively, but in most implementations
732
+ # they would be range(0, H) and range(0, W). Keeping it at as is to match the original code.
733
+ y_range = not_mask.cumsum(1, dtype=torch.float32)
734
+ x_range = not_mask.cumsum(2, dtype=torch.float32)
735
+
736
+ # "Normalize" the position index such that it ranges in [0, 2π].
737
+ # Note: Adding epsilon on the denominator should not be needed as all values of y_embed and x_range
738
+ # are non-zero by construction. This is an artifact of the original code.
739
+ y_range = y_range / (y_range[:, -1:, :] + self._eps) * self._two_pi
740
+ x_range = x_range / (x_range[:, :, -1:] + self._eps) * self._two_pi
741
+
742
+ inverse_frequency = self._temperature ** (
743
+ 2 * (torch.arange(self.dimension, dtype=torch.float32, device=x.device) // 2) / self.dimension
744
+ )
745
+
746
+ x_range = x_range.unsqueeze(-1) / inverse_frequency # (1, H, W, 1)
747
+ y_range = y_range.unsqueeze(-1) / inverse_frequency # (1, H, W, 1)
748
+
749
+ # Note: this stack then flatten operation results in interleaved sine and cosine terms.
750
+ # pos_embed_x and pos_embed_y are (1, H, W, C // 2).
751
+ pos_embed_x = torch.stack((x_range[..., 0::2].sin(), x_range[..., 1::2].cos()), dim=-1).flatten(3)
752
+ pos_embed_y = torch.stack((y_range[..., 0::2].sin(), y_range[..., 1::2].cos()), dim=-1).flatten(3)
753
+ pos_embed = torch.cat((pos_embed_y, pos_embed_x), dim=3).permute(0, 3, 1, 2) # (1, C, H, W)
754
+
755
+ return pos_embed
756
+
757
+
758
+ def get_activation_fn(activation: str) -> Callable:
759
+ """Return an activation function given a string."""
760
+ if activation == "relu":
761
+ return F.relu
762
+ if activation == "gelu":
763
+ return F.gelu
764
+ if activation == "glu":
765
+ return F.glu
766
+ raise RuntimeError(f"activation should be relu/gelu/glu, not {activation}.")
tools/lerobot_v21_runtime/src/lerobot/policies/diffusion/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ ../../../../docs/source/policy_diffusion_README.md
tools/lerobot_v21_runtime/src/lerobot/policies/diffusion/configuration_diffusion.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 Columbia Artificial Intelligence, Robotics Lab,
4
+ # and The HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ from dataclasses import dataclass, field
18
+
19
+ from lerobot.configs.policies import PreTrainedConfig
20
+ from lerobot.configs.types import NormalizationMode
21
+ from lerobot.optim.optimizers import AdamConfig
22
+ from lerobot.optim.schedulers import DiffuserSchedulerConfig
23
+
24
+
25
+ @PreTrainedConfig.register_subclass("diffusion")
26
+ @dataclass
27
+ class DiffusionConfig(PreTrainedConfig):
28
+ """Configuration class for DiffusionPolicy.
29
+
30
+ Defaults are configured for training with PushT providing proprioceptive and single camera observations.
31
+
32
+ The parameters you will most likely need to change are the ones which depend on the environment / sensors.
33
+ Those are: `input_shapes` and `output_shapes`.
34
+
35
+ Notes on the inputs and outputs:
36
+ - "observation.state" is required as an input key.
37
+ - Either:
38
+ - At least one key starting with "observation.image is required as an input.
39
+ AND/OR
40
+ - The key "observation.environment_state" is required as input.
41
+ - If there are multiple keys beginning with "observation.image" they are treated as multiple camera
42
+ views. Right now we only support all images having the same shape.
43
+ - "action" is required as an output key.
44
+
45
+ Args:
46
+ n_obs_steps: Number of environment steps worth of observations to pass to the policy (takes the
47
+ current step and additional steps going back).
48
+ horizon: Diffusion model action prediction size as detailed in `DiffusionPolicy.select_action`.
49
+ n_action_steps: The number of action steps to run in the environment for one invocation of the policy.
50
+ See `DiffusionPolicy.select_action` for more details.
51
+ input_shapes: A dictionary defining the shapes of the input data for the policy. The key represents
52
+ the input data name, and the value is a list indicating the dimensions of the corresponding data.
53
+ For example, "observation.image" refers to an input from a camera with dimensions [3, 96, 96],
54
+ indicating it has three color channels and 96x96 resolution. Importantly, `input_shapes` doesn't
55
+ include batch dimension or temporal dimension.
56
+ output_shapes: A dictionary defining the shapes of the output data for the policy. The key represents
57
+ the output data name, and the value is a list indicating the dimensions of the corresponding data.
58
+ For example, "action" refers to an output shape of [14], indicating 14-dimensional actions.
59
+ Importantly, `output_shapes` doesn't include batch dimension or temporal dimension.
60
+ input_normalization_modes: A dictionary with key representing the modality (e.g. "observation.state"),
61
+ and the value specifies the normalization mode to apply. The two available modes are "mean_std"
62
+ which subtracts the mean and divides by the standard deviation and "min_max" which rescale in a
63
+ [-1, 1] range.
64
+ output_normalization_modes: Similar dictionary as `normalize_input_modes`, but to unnormalize to the
65
+ original scale. Note that this is also used for normalizing the training targets.
66
+ vision_backbone: Name of the torchvision resnet backbone to use for encoding images.
67
+ crop_shape: (H, W) shape to crop images to as a preprocessing step for the vision backbone. Must fit
68
+ within the image size. If None, no cropping is done.
69
+ crop_is_random: Whether the crop should be random at training time (it's always a center crop in eval
70
+ mode).
71
+ pretrained_backbone_weights: Pretrained weights from torchvision to initialize the backbone.
72
+ `None` means no pretrained weights.
73
+ use_group_norm: Whether to replace batch normalization with group normalization in the backbone.
74
+ The group sizes are set to be about 16 (to be precise, feature_dim // 16).
75
+ spatial_softmax_num_keypoints: Number of keypoints for SpatialSoftmax.
76
+ use_separate_rgb_encoders_per_camera: Whether to use a separate RGB encoder for each camera view.
77
+ down_dims: Feature dimension for each stage of temporal downsampling in the diffusion modeling Unet.
78
+ You may provide a variable number of dimensions, therefore also controlling the degree of
79
+ downsampling.
80
+ kernel_size: The convolutional kernel size of the diffusion modeling Unet.
81
+ n_groups: Number of groups used in the group norm of the Unet's convolutional blocks.
82
+ diffusion_step_embed_dim: The Unet is conditioned on the diffusion timestep via a small non-linear
83
+ network. This is the output dimension of that network, i.e., the embedding dimension.
84
+ use_film_scale_modulation: FiLM (https://huggingface.co/papers/1709.07871) is used for the Unet conditioning.
85
+ Bias modulation is used be default, while this parameter indicates whether to also use scale
86
+ modulation.
87
+ noise_scheduler_type: Name of the noise scheduler to use. Supported options: ["DDPM", "DDIM"].
88
+ num_train_timesteps: Number of diffusion steps for the forward diffusion schedule.
89
+ beta_schedule: Name of the diffusion beta schedule as per DDPMScheduler from Hugging Face diffusers.
90
+ beta_start: Beta value for the first forward-diffusion step.
91
+ beta_end: Beta value for the last forward-diffusion step.
92
+ prediction_type: The type of prediction that the diffusion modeling Unet makes. Choose from "epsilon"
93
+ or "sample". These have equivalent outcomes from a latent variable modeling perspective, but
94
+ "epsilon" has been shown to work better in many deep neural network settings.
95
+ clip_sample: Whether to clip the sample to [-`clip_sample_range`, +`clip_sample_range`] for each
96
+ denoising step at inference time. WARNING: you will need to make sure your action-space is
97
+ normalized to fit within this range.
98
+ clip_sample_range: The magnitude of the clipping range as described above.
99
+ num_inference_steps: Number of reverse diffusion steps to use at inference time (steps are evenly
100
+ spaced). If not provided, this defaults to be the same as `num_train_timesteps`.
101
+ do_mask_loss_for_padding: Whether to mask the loss when there are copy-padded actions. See
102
+ `LeRobotDataset` and `load_previous_and_future_frames` for more information. Note, this defaults
103
+ to False as the original Diffusion Policy implementation does the same.
104
+ """
105
+
106
+ # Inputs / output structure.
107
+ n_obs_steps: int = 2
108
+ horizon: int = 16
109
+ n_action_steps: int = 8
110
+
111
+ normalization_mapping: dict[str, NormalizationMode] = field(
112
+ default_factory=lambda: {
113
+ "VISUAL": NormalizationMode.MEAN_STD,
114
+ "STATE": NormalizationMode.MIN_MAX,
115
+ "ACTION": NormalizationMode.MIN_MAX,
116
+ }
117
+ )
118
+
119
+ # The original implementation doesn't sample frames for the last 7 steps,
120
+ # which avoids excessive padding and leads to improved training results.
121
+ drop_n_last_frames: int = 7 # horizon - n_action_steps - n_obs_steps + 1
122
+
123
+ # Architecture / modeling.
124
+ # Vision backbone.
125
+ vision_backbone: str = "resnet18"
126
+ crop_shape: tuple[int, int] | None = (84, 84)
127
+ crop_is_random: bool = True
128
+ pretrained_backbone_weights: str | None = None
129
+ use_group_norm: bool = True
130
+ spatial_softmax_num_keypoints: int = 32
131
+ use_separate_rgb_encoder_per_camera: bool = False
132
+ # Unet.
133
+ down_dims: tuple[int, ...] = (512, 1024, 2048)
134
+ kernel_size: int = 5
135
+ n_groups: int = 8
136
+ diffusion_step_embed_dim: int = 128
137
+ use_film_scale_modulation: bool = True
138
+ # Noise scheduler.
139
+ noise_scheduler_type: str = "DDPM"
140
+ num_train_timesteps: int = 100
141
+ beta_schedule: str = "squaredcos_cap_v2"
142
+ beta_start: float = 0.0001
143
+ beta_end: float = 0.02
144
+ prediction_type: str = "epsilon"
145
+ clip_sample: bool = True
146
+ clip_sample_range: float = 1.0
147
+
148
+ # Inference
149
+ num_inference_steps: int | None = None
150
+
151
+ # Loss computation
152
+ do_mask_loss_for_padding: bool = False
153
+
154
+ # Training presets
155
+ optimizer_lr: float = 1e-4
156
+ optimizer_betas: tuple = (0.95, 0.999)
157
+ optimizer_eps: float = 1e-8
158
+ optimizer_weight_decay: float = 1e-6
159
+ scheduler_name: str = "cosine"
160
+ scheduler_warmup_steps: int = 500
161
+
162
+ def __post_init__(self):
163
+ super().__post_init__()
164
+
165
+ """Input validation (not exhaustive)."""
166
+ if not self.vision_backbone.startswith("resnet"):
167
+ raise ValueError(
168
+ f"`vision_backbone` must be one of the ResNet variants. Got {self.vision_backbone}."
169
+ )
170
+
171
+ supported_prediction_types = ["epsilon", "sample"]
172
+ if self.prediction_type not in supported_prediction_types:
173
+ raise ValueError(
174
+ f"`prediction_type` must be one of {supported_prediction_types}. Got {self.prediction_type}."
175
+ )
176
+ supported_noise_schedulers = ["DDPM", "DDIM"]
177
+ if self.noise_scheduler_type not in supported_noise_schedulers:
178
+ raise ValueError(
179
+ f"`noise_scheduler_type` must be one of {supported_noise_schedulers}. "
180
+ f"Got {self.noise_scheduler_type}."
181
+ )
182
+
183
+ # Check that the horizon size and U-Net downsampling is compatible.
184
+ # U-Net downsamples by 2 with each stage.
185
+ downsampling_factor = 2 ** len(self.down_dims)
186
+ if self.horizon % downsampling_factor != 0:
187
+ raise ValueError(
188
+ "The horizon should be an integer multiple of the downsampling factor (which is determined "
189
+ f"by `len(down_dims)`). Got {self.horizon=} and {self.down_dims=}"
190
+ )
191
+
192
+ def get_optimizer_preset(self) -> AdamConfig:
193
+ return AdamConfig(
194
+ lr=self.optimizer_lr,
195
+ betas=self.optimizer_betas,
196
+ eps=self.optimizer_eps,
197
+ weight_decay=self.optimizer_weight_decay,
198
+ )
199
+
200
+ def get_scheduler_preset(self) -> DiffuserSchedulerConfig:
201
+ return DiffuserSchedulerConfig(
202
+ name=self.scheduler_name,
203
+ num_warmup_steps=self.scheduler_warmup_steps,
204
+ )
205
+
206
+ def validate_features(self) -> None:
207
+ if len(self.image_features) == 0 and self.env_state_feature is None:
208
+ raise ValueError("You must provide at least one image or the environment state among the inputs.")
209
+
210
+ if self.crop_shape is not None:
211
+ for key, image_ft in self.image_features.items():
212
+ if self.crop_shape[0] > image_ft.shape[1] or self.crop_shape[1] > image_ft.shape[2]:
213
+ raise ValueError(
214
+ f"`crop_shape` should fit within the images shapes. Got {self.crop_shape} "
215
+ f"for `crop_shape` and {image_ft.shape} for "
216
+ f"`{key}`."
217
+ )
218
+
219
+ # Check that all input images have the same shape.
220
+ if len(self.image_features) > 0:
221
+ first_image_key, first_image_ft = next(iter(self.image_features.items()))
222
+ for key, image_ft in self.image_features.items():
223
+ if image_ft.shape != first_image_ft.shape:
224
+ raise ValueError(
225
+ f"`{key}` does not match `{first_image_key}`, but we expect all image shapes to match."
226
+ )
227
+
228
+ @property
229
+ def observation_delta_indices(self) -> list:
230
+ return list(range(1 - self.n_obs_steps, 1))
231
+
232
+ @property
233
+ def action_delta_indices(self) -> list:
234
+ return list(range(1 - self.n_obs_steps, 1 - self.n_obs_steps + self.horizon))
235
+
236
+ @property
237
+ def reward_delta_indices(self) -> None:
238
+ return None
tools/lerobot_v21_runtime/src/lerobot/policies/diffusion/modeling_diffusion.py ADDED
@@ -0,0 +1,771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 Columbia Artificial Intelligence, Robotics Lab,
4
+ # and The HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """Diffusion Policy as per "Diffusion Policy: Visuomotor Policy Learning via Action Diffusion"
18
+
19
+ TODO(alexander-soare):
20
+ - Remove reliance on diffusers for DDPMScheduler and LR scheduler.
21
+ """
22
+
23
+ import math
24
+ from collections import deque
25
+ from collections.abc import Callable
26
+
27
+ import einops
28
+ import numpy as np
29
+ import torch
30
+ import torch.nn.functional as F # noqa: N812
31
+ import torchvision
32
+ from diffusers.schedulers.scheduling_ddim import DDIMScheduler
33
+ from diffusers.schedulers.scheduling_ddpm import DDPMScheduler
34
+ from torch import Tensor, nn
35
+
36
+ from lerobot.constants import ACTION, OBS_ENV_STATE, OBS_IMAGES, OBS_STATE
37
+ from lerobot.policies.diffusion.configuration_diffusion import DiffusionConfig
38
+ from lerobot.policies.normalize import Normalize, Unnormalize
39
+ from lerobot.policies.pretrained import PreTrainedPolicy
40
+ from lerobot.policies.utils import (
41
+ get_device_from_parameters,
42
+ get_dtype_from_parameters,
43
+ get_output_shape,
44
+ populate_queues,
45
+ )
46
+
47
+
48
+ class DiffusionPolicy(PreTrainedPolicy):
49
+ """
50
+ Diffusion Policy as per "Diffusion Policy: Visuomotor Policy Learning via Action Diffusion"
51
+ (paper: https://huggingface.co/papers/2303.04137, code: https://github.com/real-stanford/diffusion_policy).
52
+ """
53
+
54
+ config_class = DiffusionConfig
55
+ name = "diffusion"
56
+
57
+ def __init__(
58
+ self,
59
+ config: DiffusionConfig,
60
+ dataset_stats: dict[str, dict[str, Tensor]] | None = None,
61
+ ):
62
+ """
63
+ Args:
64
+ config: Policy configuration class instance or None, in which case the default instantiation of
65
+ the configuration class is used.
66
+ dataset_stats: Dataset statistics to be used for normalization. If not passed here, it is expected
67
+ that they will be passed with a call to `load_state_dict` before the policy is used.
68
+ """
69
+ super().__init__(config)
70
+ config.validate_features()
71
+ self.config = config
72
+
73
+ self.normalize_inputs = Normalize(config.input_features, config.normalization_mapping, dataset_stats)
74
+ self.normalize_targets = Normalize(
75
+ config.output_features, config.normalization_mapping, dataset_stats
76
+ )
77
+ self.unnormalize_outputs = Unnormalize(
78
+ config.output_features, config.normalization_mapping, dataset_stats
79
+ )
80
+
81
+ # queues are populated during rollout of the policy, they contain the n latest observations and actions
82
+ self._queues = None
83
+
84
+ self.diffusion = DiffusionModel(config)
85
+
86
+ self.reset()
87
+
88
+ def get_optim_params(self) -> dict:
89
+ return self.diffusion.parameters()
90
+
91
+ def reset(self):
92
+ """Clear observation and action queues. Should be called on `env.reset()`"""
93
+ self._queues = {
94
+ "observation.state": deque(maxlen=self.config.n_obs_steps),
95
+ "action": deque(maxlen=self.config.n_action_steps),
96
+ }
97
+ if self.config.image_features:
98
+ self._queues["observation.images"] = deque(maxlen=self.config.n_obs_steps)
99
+ if self.config.env_state_feature:
100
+ self._queues["observation.environment_state"] = deque(maxlen=self.config.n_obs_steps)
101
+
102
+ @torch.no_grad()
103
+ def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor:
104
+ """Predict a chunk of actions given environment observations."""
105
+ # stack n latest observations from the queue
106
+ batch = {k: torch.stack(list(self._queues[k]), dim=1) for k in batch if k in self._queues}
107
+ actions = self.diffusion.generate_actions(batch)
108
+
109
+ # TODO(rcadene): make above methods return output dictionary?
110
+ actions = self.unnormalize_outputs({ACTION: actions})[ACTION]
111
+
112
+ return actions
113
+
114
+ @torch.no_grad()
115
+ def select_action(self, batch: dict[str, Tensor]) -> Tensor:
116
+ """Select a single action given environment observations.
117
+
118
+ This method handles caching a history of observations and an action trajectory generated by the
119
+ underlying diffusion model. Here's how it works:
120
+ - `n_obs_steps` steps worth of observations are cached (for the first steps, the observation is
121
+ copied `n_obs_steps` times to fill the cache).
122
+ - The diffusion model generates `horizon` steps worth of actions.
123
+ - `n_action_steps` worth of actions are actually kept for execution, starting from the current step.
124
+ Schematically this looks like:
125
+ ----------------------------------------------------------------------------------------------
126
+ (legend: o = n_obs_steps, h = horizon, a = n_action_steps)
127
+ |timestep | n-o+1 | n-o+2 | ..... | n | ..... | n+a-1 | n+a | ..... | n-o+h |
128
+ |observation is used | YES | YES | YES | YES | NO | NO | NO | NO | NO |
129
+ |action is generated | YES | YES | YES | YES | YES | YES | YES | YES | YES |
130
+ |action is used | NO | NO | NO | YES | YES | YES | NO | NO | NO |
131
+ ----------------------------------------------------------------------------------------------
132
+ Note that this means we require: `n_action_steps <= horizon - n_obs_steps + 1`. Also, note that
133
+ "horizon" may not the best name to describe what the variable actually means, because this period is
134
+ actually measured from the first observation which (if `n_obs_steps` > 1) happened in the past.
135
+ """
136
+ # NOTE: for offline evaluation, we have action in the batch, so we need to pop it out
137
+ if ACTION in batch:
138
+ batch.pop(ACTION)
139
+
140
+ batch = self.normalize_inputs(batch)
141
+ if self.config.image_features:
142
+ batch = dict(batch) # shallow copy so that adding a key doesn't modify the original
143
+ batch[OBS_IMAGES] = torch.stack([batch[key] for key in self.config.image_features], dim=-4)
144
+ # NOTE: It's important that this happens after stacking the images into a single key.
145
+ self._queues = populate_queues(self._queues, batch)
146
+
147
+ if len(self._queues[ACTION]) == 0:
148
+ actions = self.predict_action_chunk(batch)
149
+ self._queues[ACTION].extend(actions.transpose(0, 1))
150
+
151
+ action = self._queues[ACTION].popleft()
152
+ return action
153
+
154
+ def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, None]:
155
+ """Run the batch through the model and compute the loss for training or validation."""
156
+ batch = self.normalize_inputs(batch)
157
+ if self.config.image_features:
158
+ batch = dict(batch) # shallow copy so that adding a key doesn't modify the original
159
+ batch[OBS_IMAGES] = torch.stack([batch[key] for key in self.config.image_features], dim=-4)
160
+ batch = self.normalize_targets(batch)
161
+ loss = self.diffusion.compute_loss(batch)
162
+ # no output_dict so returning None
163
+ return loss, None
164
+
165
+
166
+ def _make_noise_scheduler(name: str, **kwargs: dict) -> DDPMScheduler | DDIMScheduler:
167
+ """
168
+ Factory for noise scheduler instances of the requested type. All kwargs are passed
169
+ to the scheduler.
170
+ """
171
+ if name == "DDPM":
172
+ return DDPMScheduler(**kwargs)
173
+ elif name == "DDIM":
174
+ return DDIMScheduler(**kwargs)
175
+ else:
176
+ raise ValueError(f"Unsupported noise scheduler type {name}")
177
+
178
+
179
+ class DiffusionModel(nn.Module):
180
+ def __init__(self, config: DiffusionConfig):
181
+ super().__init__()
182
+ self.config = config
183
+
184
+ # Build observation encoders (depending on which observations are provided).
185
+ global_cond_dim = self.config.robot_state_feature.shape[0]
186
+ if self.config.image_features:
187
+ num_images = len(self.config.image_features)
188
+ if self.config.use_separate_rgb_encoder_per_camera:
189
+ encoders = [DiffusionRgbEncoder(config) for _ in range(num_images)]
190
+ self.rgb_encoder = nn.ModuleList(encoders)
191
+ global_cond_dim += encoders[0].feature_dim * num_images
192
+ else:
193
+ self.rgb_encoder = DiffusionRgbEncoder(config)
194
+ global_cond_dim += self.rgb_encoder.feature_dim * num_images
195
+ if self.config.env_state_feature:
196
+ global_cond_dim += self.config.env_state_feature.shape[0]
197
+
198
+ self.unet = DiffusionConditionalUnet1d(config, global_cond_dim=global_cond_dim * config.n_obs_steps)
199
+
200
+ self.noise_scheduler = _make_noise_scheduler(
201
+ config.noise_scheduler_type,
202
+ num_train_timesteps=config.num_train_timesteps,
203
+ beta_start=config.beta_start,
204
+ beta_end=config.beta_end,
205
+ beta_schedule=config.beta_schedule,
206
+ clip_sample=config.clip_sample,
207
+ clip_sample_range=config.clip_sample_range,
208
+ prediction_type=config.prediction_type,
209
+ )
210
+
211
+ if config.num_inference_steps is None:
212
+ self.num_inference_steps = self.noise_scheduler.config.num_train_timesteps
213
+ else:
214
+ self.num_inference_steps = config.num_inference_steps
215
+
216
+ # ========= inference ============
217
+ def conditional_sample(
218
+ self, batch_size: int, global_cond: Tensor | None = None, generator: torch.Generator | None = None
219
+ ) -> Tensor:
220
+ device = get_device_from_parameters(self)
221
+ dtype = get_dtype_from_parameters(self)
222
+
223
+ # Sample prior.
224
+ sample = torch.randn(
225
+ size=(batch_size, self.config.horizon, self.config.action_feature.shape[0]),
226
+ dtype=dtype,
227
+ device=device,
228
+ generator=generator,
229
+ )
230
+
231
+ self.noise_scheduler.set_timesteps(self.num_inference_steps)
232
+
233
+ for t in self.noise_scheduler.timesteps:
234
+ # Predict model output.
235
+ model_output = self.unet(
236
+ sample,
237
+ torch.full(sample.shape[:1], t, dtype=torch.long, device=sample.device),
238
+ global_cond=global_cond,
239
+ )
240
+ # Compute previous image: x_t -> x_t-1
241
+ sample = self.noise_scheduler.step(model_output, t, sample, generator=generator).prev_sample
242
+
243
+ return sample
244
+
245
+ def _prepare_global_conditioning(self, batch: dict[str, Tensor]) -> Tensor:
246
+ """Encode image features and concatenate them all together along with the state vector."""
247
+ batch_size, n_obs_steps = batch[OBS_STATE].shape[:2]
248
+ global_cond_feats = [batch[OBS_STATE]]
249
+ # Extract image features.
250
+ if self.config.image_features:
251
+ if self.config.use_separate_rgb_encoder_per_camera:
252
+ # Combine batch and sequence dims while rearranging to make the camera index dimension first.
253
+ images_per_camera = einops.rearrange(batch["observation.images"], "b s n ... -> n (b s) ...")
254
+ img_features_list = torch.cat(
255
+ [
256
+ encoder(images)
257
+ for encoder, images in zip(self.rgb_encoder, images_per_camera, strict=True)
258
+ ]
259
+ )
260
+ # Separate batch and sequence dims back out. The camera index dim gets absorbed into the
261
+ # feature dim (effectively concatenating the camera features).
262
+ img_features = einops.rearrange(
263
+ img_features_list, "(n b s) ... -> b s (n ...)", b=batch_size, s=n_obs_steps
264
+ )
265
+ else:
266
+ # Combine batch, sequence, and "which camera" dims before passing to shared encoder.
267
+ img_features = self.rgb_encoder(
268
+ einops.rearrange(batch["observation.images"], "b s n ... -> (b s n) ...")
269
+ )
270
+ # Separate batch dim and sequence dim back out. The camera index dim gets absorbed into the
271
+ # feature dim (effectively concatenating the camera features).
272
+ img_features = einops.rearrange(
273
+ img_features, "(b s n) ... -> b s (n ...)", b=batch_size, s=n_obs_steps
274
+ )
275
+ global_cond_feats.append(img_features)
276
+
277
+ if self.config.env_state_feature:
278
+ global_cond_feats.append(batch[OBS_ENV_STATE])
279
+
280
+ # Concatenate features then flatten to (B, global_cond_dim).
281
+ return torch.cat(global_cond_feats, dim=-1).flatten(start_dim=1)
282
+
283
+ def generate_actions(self, batch: dict[str, Tensor]) -> Tensor:
284
+ """
285
+ This function expects `batch` to have:
286
+ {
287
+ "observation.state": (B, n_obs_steps, state_dim)
288
+
289
+ "observation.images": (B, n_obs_steps, num_cameras, C, H, W)
290
+ AND/OR
291
+ "observation.environment_state": (B, n_obs_steps, environment_dim)
292
+ }
293
+ """
294
+ batch_size, n_obs_steps = batch["observation.state"].shape[:2]
295
+ assert n_obs_steps == self.config.n_obs_steps
296
+
297
+ # Encode image features and concatenate them all together along with the state vector.
298
+ global_cond = self._prepare_global_conditioning(batch) # (B, global_cond_dim)
299
+
300
+ # run sampling
301
+ actions = self.conditional_sample(batch_size, global_cond=global_cond)
302
+
303
+ # Extract `n_action_steps` steps worth of actions (from the current observation).
304
+ start = n_obs_steps - 1
305
+ end = start + self.config.n_action_steps
306
+ actions = actions[:, start:end]
307
+
308
+ return actions
309
+
310
+ def compute_loss(self, batch: dict[str, Tensor]) -> Tensor:
311
+ """
312
+ This function expects `batch` to have (at least):
313
+ {
314
+ "observation.state": (B, n_obs_steps, state_dim)
315
+
316
+ "observation.images": (B, n_obs_steps, num_cameras, C, H, W)
317
+ AND/OR
318
+ "observation.environment_state": (B, n_obs_steps, environment_dim)
319
+
320
+ "action": (B, horizon, action_dim)
321
+ "action_is_pad": (B, horizon)
322
+ }
323
+ """
324
+ # Input validation.
325
+ assert set(batch).issuperset({"observation.state", "action", "action_is_pad"})
326
+ assert "observation.images" in batch or "observation.environment_state" in batch
327
+ n_obs_steps = batch["observation.state"].shape[1]
328
+ horizon = batch["action"].shape[1]
329
+ assert horizon == self.config.horizon
330
+ assert n_obs_steps == self.config.n_obs_steps
331
+
332
+ # Encode image features and concatenate them all together along with the state vector.
333
+ global_cond = self._prepare_global_conditioning(batch) # (B, global_cond_dim)
334
+
335
+ # Forward diffusion.
336
+ trajectory = batch["action"]
337
+ # Sample noise to add to the trajectory.
338
+ eps = torch.randn(trajectory.shape, device=trajectory.device)
339
+ # Sample a random noising timestep for each item in the batch.
340
+ timesteps = torch.randint(
341
+ low=0,
342
+ high=self.noise_scheduler.config.num_train_timesteps,
343
+ size=(trajectory.shape[0],),
344
+ device=trajectory.device,
345
+ ).long()
346
+ # Add noise to the clean trajectories according to the noise magnitude at each timestep.
347
+ noisy_trajectory = self.noise_scheduler.add_noise(trajectory, eps, timesteps)
348
+
349
+ # Run the denoising network (that might denoise the trajectory, or attempt to predict the noise).
350
+ pred = self.unet(noisy_trajectory, timesteps, global_cond=global_cond)
351
+
352
+ # Compute the loss.
353
+ # The target is either the original trajectory, or the noise.
354
+ if self.config.prediction_type == "epsilon":
355
+ target = eps
356
+ elif self.config.prediction_type == "sample":
357
+ target = batch["action"]
358
+ else:
359
+ raise ValueError(f"Unsupported prediction type {self.config.prediction_type}")
360
+
361
+ loss = F.mse_loss(pred, target, reduction="none")
362
+
363
+ # Mask loss wherever the action is padded with copies (edges of the dataset trajectory).
364
+ if self.config.do_mask_loss_for_padding:
365
+ if "action_is_pad" not in batch:
366
+ raise ValueError(
367
+ "You need to provide 'action_is_pad' in the batch when "
368
+ f"{self.config.do_mask_loss_for_padding=}."
369
+ )
370
+ in_episode_bound = ~batch["action_is_pad"]
371
+ loss = loss * in_episode_bound.unsqueeze(-1)
372
+
373
+ return loss.mean()
374
+
375
+
376
+ class SpatialSoftmax(nn.Module):
377
+ """
378
+ Spatial Soft Argmax operation described in "Deep Spatial Autoencoders for Visuomotor Learning" by Finn et al.
379
+ (https://huggingface.co/papers/1509.06113). A minimal port of the robomimic implementation.
380
+
381
+ At a high level, this takes 2D feature maps (from a convnet/ViT) and returns the "center of mass"
382
+ of activations of each channel, i.e., keypoints in the image space for the policy to focus on.
383
+
384
+ Example: take feature maps of size (512x10x12). We generate a grid of normalized coordinates (10x12x2):
385
+ -----------------------------------------------------
386
+ | (-1., -1.) | (-0.82, -1.) | ... | (1., -1.) |
387
+ | (-1., -0.78) | (-0.82, -0.78) | ... | (1., -0.78) |
388
+ | ... | ... | ... | ... |
389
+ | (-1., 1.) | (-0.82, 1.) | ... | (1., 1.) |
390
+ -----------------------------------------------------
391
+ This is achieved by applying channel-wise softmax over the activations (512x120) and computing the dot
392
+ product with the coordinates (120x2) to get expected points of maximal activation (512x2).
393
+
394
+ The example above results in 512 keypoints (corresponding to the 512 input channels). We can optionally
395
+ provide num_kp != None to control the number of keypoints. This is achieved by a first applying a learnable
396
+ linear mapping (in_channels, H, W) -> (num_kp, H, W).
397
+ """
398
+
399
+ def __init__(self, input_shape, num_kp=None):
400
+ """
401
+ Args:
402
+ input_shape (list): (C, H, W) input feature map shape.
403
+ num_kp (int): number of keypoints in output. If None, output will have the same number of channels as input.
404
+ """
405
+ super().__init__()
406
+
407
+ assert len(input_shape) == 3
408
+ self._in_c, self._in_h, self._in_w = input_shape
409
+
410
+ if num_kp is not None:
411
+ self.nets = torch.nn.Conv2d(self._in_c, num_kp, kernel_size=1)
412
+ self._out_c = num_kp
413
+ else:
414
+ self.nets = None
415
+ self._out_c = self._in_c
416
+
417
+ # we could use torch.linspace directly but that seems to behave slightly differently than numpy
418
+ # and causes a small degradation in pc_success of pre-trained models.
419
+ pos_x, pos_y = np.meshgrid(np.linspace(-1.0, 1.0, self._in_w), np.linspace(-1.0, 1.0, self._in_h))
420
+ pos_x = torch.from_numpy(pos_x.reshape(self._in_h * self._in_w, 1)).float()
421
+ pos_y = torch.from_numpy(pos_y.reshape(self._in_h * self._in_w, 1)).float()
422
+ # register as buffer so it's moved to the correct device.
423
+ self.register_buffer("pos_grid", torch.cat([pos_x, pos_y], dim=1))
424
+
425
+ def forward(self, features: Tensor) -> Tensor:
426
+ """
427
+ Args:
428
+ features: (B, C, H, W) input feature maps.
429
+ Returns:
430
+ (B, K, 2) image-space coordinates of keypoints.
431
+ """
432
+ if self.nets is not None:
433
+ features = self.nets(features)
434
+
435
+ # [B, K, H, W] -> [B * K, H * W] where K is number of keypoints
436
+ features = features.reshape(-1, self._in_h * self._in_w)
437
+ # 2d softmax normalization
438
+ attention = F.softmax(features, dim=-1)
439
+ # [B * K, H * W] x [H * W, 2] -> [B * K, 2] for spatial coordinate mean in x and y dimensions
440
+ expected_xy = attention @ self.pos_grid
441
+ # reshape to [B, K, 2]
442
+ feature_keypoints = expected_xy.view(-1, self._out_c, 2)
443
+
444
+ return feature_keypoints
445
+
446
+
447
+ class DiffusionRgbEncoder(nn.Module):
448
+ """Encodes an RGB image into a 1D feature vector.
449
+
450
+ Includes the ability to normalize and crop the image first.
451
+ """
452
+
453
+ def __init__(self, config: DiffusionConfig):
454
+ super().__init__()
455
+ # Set up optional preprocessing.
456
+ if config.crop_shape is not None:
457
+ self.do_crop = True
458
+ # Always use center crop for eval
459
+ self.center_crop = torchvision.transforms.CenterCrop(config.crop_shape)
460
+ if config.crop_is_random:
461
+ self.maybe_random_crop = torchvision.transforms.RandomCrop(config.crop_shape)
462
+ else:
463
+ self.maybe_random_crop = self.center_crop
464
+ else:
465
+ self.do_crop = False
466
+
467
+ # Set up backbone.
468
+ backbone_model = getattr(torchvision.models, config.vision_backbone)(
469
+ weights=config.pretrained_backbone_weights
470
+ )
471
+ # Note: This assumes that the layer4 feature map is children()[-3]
472
+ # TODO(alexander-soare): Use a safer alternative.
473
+ self.backbone = nn.Sequential(*(list(backbone_model.children())[:-2]))
474
+ if config.use_group_norm:
475
+ if config.pretrained_backbone_weights:
476
+ raise ValueError(
477
+ "You can't replace BatchNorm in a pretrained model without ruining the weights!"
478
+ )
479
+ self.backbone = _replace_submodules(
480
+ root_module=self.backbone,
481
+ predicate=lambda x: isinstance(x, nn.BatchNorm2d),
482
+ func=lambda x: nn.GroupNorm(num_groups=x.num_features // 16, num_channels=x.num_features),
483
+ )
484
+
485
+ # Set up pooling and final layers.
486
+ # Use a dry run to get the feature map shape.
487
+ # The dummy input should take the number of image channels from `config.image_features` and it should
488
+ # use the height and width from `config.crop_shape` if it is provided, otherwise it should use the
489
+ # height and width from `config.image_features`.
490
+
491
+ # Note: we have a check in the config class to make sure all images have the same shape.
492
+ images_shape = next(iter(config.image_features.values())).shape
493
+ dummy_shape_h_w = config.crop_shape if config.crop_shape is not None else images_shape[1:]
494
+ dummy_shape = (1, images_shape[0], *dummy_shape_h_w)
495
+ feature_map_shape = get_output_shape(self.backbone, dummy_shape)[1:]
496
+
497
+ self.pool = SpatialSoftmax(feature_map_shape, num_kp=config.spatial_softmax_num_keypoints)
498
+ self.feature_dim = config.spatial_softmax_num_keypoints * 2
499
+ self.out = nn.Linear(config.spatial_softmax_num_keypoints * 2, self.feature_dim)
500
+ self.relu = nn.ReLU()
501
+
502
+ def forward(self, x: Tensor) -> Tensor:
503
+ """
504
+ Args:
505
+ x: (B, C, H, W) image tensor with pixel values in [0, 1].
506
+ Returns:
507
+ (B, D) image feature.
508
+ """
509
+ # Preprocess: maybe crop (if it was set up in the __init__).
510
+ if self.do_crop:
511
+ if self.training: # noqa: SIM108
512
+ x = self.maybe_random_crop(x)
513
+ else:
514
+ # Always use center crop for eval.
515
+ x = self.center_crop(x)
516
+ # Extract backbone feature.
517
+ x = torch.flatten(self.pool(self.backbone(x)), start_dim=1)
518
+ # Final linear layer with non-linearity.
519
+ x = self.relu(self.out(x))
520
+ return x
521
+
522
+
523
+ def _replace_submodules(
524
+ root_module: nn.Module, predicate: Callable[[nn.Module], bool], func: Callable[[nn.Module], nn.Module]
525
+ ) -> nn.Module:
526
+ """
527
+ Args:
528
+ root_module: The module for which the submodules need to be replaced
529
+ predicate: Takes a module as an argument and must return True if the that module is to be replaced.
530
+ func: Takes a module as an argument and returns a new module to replace it with.
531
+ Returns:
532
+ The root module with its submodules replaced.
533
+ """
534
+ if predicate(root_module):
535
+ return func(root_module)
536
+
537
+ replace_list = [k.split(".") for k, m in root_module.named_modules(remove_duplicate=True) if predicate(m)]
538
+ for *parents, k in replace_list:
539
+ parent_module = root_module
540
+ if len(parents) > 0:
541
+ parent_module = root_module.get_submodule(".".join(parents))
542
+ if isinstance(parent_module, nn.Sequential):
543
+ src_module = parent_module[int(k)]
544
+ else:
545
+ src_module = getattr(parent_module, k)
546
+ tgt_module = func(src_module)
547
+ if isinstance(parent_module, nn.Sequential):
548
+ parent_module[int(k)] = tgt_module
549
+ else:
550
+ setattr(parent_module, k, tgt_module)
551
+ # verify that all BN are replaced
552
+ assert not any(predicate(m) for _, m in root_module.named_modules(remove_duplicate=True))
553
+ return root_module
554
+
555
+
556
+ class DiffusionSinusoidalPosEmb(nn.Module):
557
+ """1D sinusoidal positional embeddings as in Attention is All You Need."""
558
+
559
+ def __init__(self, dim: int):
560
+ super().__init__()
561
+ self.dim = dim
562
+
563
+ def forward(self, x: Tensor) -> Tensor:
564
+ device = x.device
565
+ half_dim = self.dim // 2
566
+ emb = math.log(10000) / (half_dim - 1)
567
+ emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
568
+ emb = x.unsqueeze(-1) * emb.unsqueeze(0)
569
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
570
+ return emb
571
+
572
+
573
+ class DiffusionConv1dBlock(nn.Module):
574
+ """Conv1d --> GroupNorm --> Mish"""
575
+
576
+ def __init__(self, inp_channels, out_channels, kernel_size, n_groups=8):
577
+ super().__init__()
578
+
579
+ self.block = nn.Sequential(
580
+ nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2),
581
+ nn.GroupNorm(n_groups, out_channels),
582
+ nn.Mish(),
583
+ )
584
+
585
+ def forward(self, x):
586
+ return self.block(x)
587
+
588
+
589
+ class DiffusionConditionalUnet1d(nn.Module):
590
+ """A 1D convolutional UNet with FiLM modulation for conditioning.
591
+
592
+ Note: this removes local conditioning as compared to the original diffusion policy code.
593
+ """
594
+
595
+ def __init__(self, config: DiffusionConfig, global_cond_dim: int):
596
+ super().__init__()
597
+
598
+ self.config = config
599
+
600
+ # Encoder for the diffusion timestep.
601
+ self.diffusion_step_encoder = nn.Sequential(
602
+ DiffusionSinusoidalPosEmb(config.diffusion_step_embed_dim),
603
+ nn.Linear(config.diffusion_step_embed_dim, config.diffusion_step_embed_dim * 4),
604
+ nn.Mish(),
605
+ nn.Linear(config.diffusion_step_embed_dim * 4, config.diffusion_step_embed_dim),
606
+ )
607
+
608
+ # The FiLM conditioning dimension.
609
+ cond_dim = config.diffusion_step_embed_dim + global_cond_dim
610
+
611
+ # In channels / out channels for each downsampling block in the Unet's encoder. For the decoder, we
612
+ # just reverse these.
613
+ in_out = [(config.action_feature.shape[0], config.down_dims[0])] + list(
614
+ zip(config.down_dims[:-1], config.down_dims[1:], strict=True)
615
+ )
616
+
617
+ # Unet encoder.
618
+ common_res_block_kwargs = {
619
+ "cond_dim": cond_dim,
620
+ "kernel_size": config.kernel_size,
621
+ "n_groups": config.n_groups,
622
+ "use_film_scale_modulation": config.use_film_scale_modulation,
623
+ }
624
+ self.down_modules = nn.ModuleList([])
625
+ for ind, (dim_in, dim_out) in enumerate(in_out):
626
+ is_last = ind >= (len(in_out) - 1)
627
+ self.down_modules.append(
628
+ nn.ModuleList(
629
+ [
630
+ DiffusionConditionalResidualBlock1d(dim_in, dim_out, **common_res_block_kwargs),
631
+ DiffusionConditionalResidualBlock1d(dim_out, dim_out, **common_res_block_kwargs),
632
+ # Downsample as long as it is not the last block.
633
+ nn.Conv1d(dim_out, dim_out, 3, 2, 1) if not is_last else nn.Identity(),
634
+ ]
635
+ )
636
+ )
637
+
638
+ # Processing in the middle of the auto-encoder.
639
+ self.mid_modules = nn.ModuleList(
640
+ [
641
+ DiffusionConditionalResidualBlock1d(
642
+ config.down_dims[-1], config.down_dims[-1], **common_res_block_kwargs
643
+ ),
644
+ DiffusionConditionalResidualBlock1d(
645
+ config.down_dims[-1], config.down_dims[-1], **common_res_block_kwargs
646
+ ),
647
+ ]
648
+ )
649
+
650
+ # Unet decoder.
651
+ self.up_modules = nn.ModuleList([])
652
+ for ind, (dim_out, dim_in) in enumerate(reversed(in_out[1:])):
653
+ is_last = ind >= (len(in_out) - 1)
654
+ self.up_modules.append(
655
+ nn.ModuleList(
656
+ [
657
+ # dim_in * 2, because it takes the encoder's skip connection as well
658
+ DiffusionConditionalResidualBlock1d(dim_in * 2, dim_out, **common_res_block_kwargs),
659
+ DiffusionConditionalResidualBlock1d(dim_out, dim_out, **common_res_block_kwargs),
660
+ # Upsample as long as it is not the last block.
661
+ nn.ConvTranspose1d(dim_out, dim_out, 4, 2, 1) if not is_last else nn.Identity(),
662
+ ]
663
+ )
664
+ )
665
+
666
+ self.final_conv = nn.Sequential(
667
+ DiffusionConv1dBlock(config.down_dims[0], config.down_dims[0], kernel_size=config.kernel_size),
668
+ nn.Conv1d(config.down_dims[0], config.action_feature.shape[0], 1),
669
+ )
670
+
671
+ def forward(self, x: Tensor, timestep: Tensor | int, global_cond=None) -> Tensor:
672
+ """
673
+ Args:
674
+ x: (B, T, input_dim) tensor for input to the Unet.
675
+ timestep: (B,) tensor of (timestep_we_are_denoising_from - 1).
676
+ global_cond: (B, global_cond_dim)
677
+ output: (B, T, input_dim)
678
+ Returns:
679
+ (B, T, input_dim) diffusion model prediction.
680
+ """
681
+ # For 1D convolutions we'll need feature dimension first.
682
+ x = einops.rearrange(x, "b t d -> b d t")
683
+
684
+ timesteps_embed = self.diffusion_step_encoder(timestep)
685
+
686
+ # If there is a global conditioning feature, concatenate it to the timestep embedding.
687
+ if global_cond is not None:
688
+ global_feature = torch.cat([timesteps_embed, global_cond], axis=-1)
689
+ else:
690
+ global_feature = timesteps_embed
691
+
692
+ # Run encoder, keeping track of skip features to pass to the decoder.
693
+ encoder_skip_features: list[Tensor] = []
694
+ for resnet, resnet2, downsample in self.down_modules:
695
+ x = resnet(x, global_feature)
696
+ x = resnet2(x, global_feature)
697
+ encoder_skip_features.append(x)
698
+ x = downsample(x)
699
+
700
+ for mid_module in self.mid_modules:
701
+ x = mid_module(x, global_feature)
702
+
703
+ # Run decoder, using the skip features from the encoder.
704
+ for resnet, resnet2, upsample in self.up_modules:
705
+ x = torch.cat((x, encoder_skip_features.pop()), dim=1)
706
+ x = resnet(x, global_feature)
707
+ x = resnet2(x, global_feature)
708
+ x = upsample(x)
709
+
710
+ x = self.final_conv(x)
711
+
712
+ x = einops.rearrange(x, "b d t -> b t d")
713
+ return x
714
+
715
+
716
+ class DiffusionConditionalResidualBlock1d(nn.Module):
717
+ """ResNet style 1D convolutional block with FiLM modulation for conditioning."""
718
+
719
+ def __init__(
720
+ self,
721
+ in_channels: int,
722
+ out_channels: int,
723
+ cond_dim: int,
724
+ kernel_size: int = 3,
725
+ n_groups: int = 8,
726
+ # Set to True to do scale modulation with FiLM as well as bias modulation (defaults to False meaning
727
+ # FiLM just modulates bias).
728
+ use_film_scale_modulation: bool = False,
729
+ ):
730
+ super().__init__()
731
+
732
+ self.use_film_scale_modulation = use_film_scale_modulation
733
+ self.out_channels = out_channels
734
+
735
+ self.conv1 = DiffusionConv1dBlock(in_channels, out_channels, kernel_size, n_groups=n_groups)
736
+
737
+ # FiLM modulation (https://huggingface.co/papers/1709.07871) outputs per-channel bias and (maybe) scale.
738
+ cond_channels = out_channels * 2 if use_film_scale_modulation else out_channels
739
+ self.cond_encoder = nn.Sequential(nn.Mish(), nn.Linear(cond_dim, cond_channels))
740
+
741
+ self.conv2 = DiffusionConv1dBlock(out_channels, out_channels, kernel_size, n_groups=n_groups)
742
+
743
+ # A final convolution for dimension matching the residual (if needed).
744
+ self.residual_conv = (
745
+ nn.Conv1d(in_channels, out_channels, 1) if in_channels != out_channels else nn.Identity()
746
+ )
747
+
748
+ def forward(self, x: Tensor, cond: Tensor) -> Tensor:
749
+ """
750
+ Args:
751
+ x: (B, in_channels, T)
752
+ cond: (B, cond_dim)
753
+ Returns:
754
+ (B, out_channels, T)
755
+ """
756
+ out = self.conv1(x)
757
+
758
+ # Get condition embedding. Unsqueeze for broadcasting to `out`, resulting in (B, out_channels, 1).
759
+ cond_embed = self.cond_encoder(cond).unsqueeze(-1)
760
+ if self.use_film_scale_modulation:
761
+ # Treat the embedding as a list of scales and biases.
762
+ scale = cond_embed[:, : self.out_channels]
763
+ bias = cond_embed[:, self.out_channels :]
764
+ out = scale * out + bias
765
+ else:
766
+ # Treat the embedding as biases.
767
+ out = out + cond_embed
768
+
769
+ out = self.conv2(out)
770
+ out = out + self.residual_conv(x)
771
+ return out
tools/lerobot_v21_runtime/src/lerobot/policies/pi0/configuration_pi0.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dataclasses import dataclass, field
16
+
17
+ from lerobot.configs.policies import PreTrainedConfig
18
+ from lerobot.configs.types import FeatureType, NormalizationMode, PolicyFeature
19
+ from lerobot.optim.optimizers import AdamWConfig
20
+ from lerobot.optim.schedulers import (
21
+ CosineDecayWithWarmupSchedulerConfig,
22
+ )
23
+
24
+
25
+ @PreTrainedConfig.register_subclass("pi0")
26
+ @dataclass
27
+ class PI0Config(PreTrainedConfig):
28
+ # Input / output structure.
29
+ n_obs_steps: int = 1
30
+ chunk_size: int = 50
31
+ n_action_steps: int = 50
32
+
33
+ normalization_mapping: dict[str, NormalizationMode] = field(
34
+ default_factory=lambda: {
35
+ "VISUAL": NormalizationMode.IDENTITY,
36
+ "STATE": NormalizationMode.MEAN_STD,
37
+ "ACTION": NormalizationMode.MEAN_STD,
38
+ }
39
+ )
40
+
41
+ # Shorter state and action vectors will be padded
42
+ max_state_dim: int = 32
43
+ max_action_dim: int = 32
44
+
45
+ # Image preprocessing
46
+ resize_imgs_with_padding: tuple[int, int] = (224, 224)
47
+
48
+ # Add empty images. Used by pi0_aloha_sim which adds the empty
49
+ # left and right wrist cameras in addition to the top camera.
50
+ empty_cameras: int = 0
51
+
52
+ # Converts the joint and gripper values from the standard Aloha space to
53
+ # the space used by the pi internal runtime which was used to train the base model.
54
+ adapt_to_pi_aloha: bool = False
55
+
56
+ # Converts joint dimensions to deltas with respect to the current state before passing to the model.
57
+ # Gripper dimensions will remain in absolute values.
58
+ use_delta_joint_actions_aloha: bool = False
59
+
60
+ # Tokenizer
61
+ tokenizer_max_length: int = 48
62
+
63
+ # Projector
64
+ proj_width: int = 1024
65
+
66
+ # Decoding
67
+ num_steps: int = 10
68
+
69
+ # Attention utils
70
+ use_cache: bool = True
71
+ attention_implementation: str = "eager" # or fa2, flex
72
+
73
+ # Finetuning settings
74
+ freeze_vision_encoder: bool = True
75
+ train_expert_only: bool = False
76
+ train_state_proj: bool = True
77
+
78
+ # Training presets
79
+ optimizer_lr: float = 2.5e-5
80
+ optimizer_betas: tuple[float, float] = (0.9, 0.95)
81
+ optimizer_eps: float = 1e-8
82
+ optimizer_weight_decay: float = 1e-10
83
+
84
+ scheduler_warmup_steps: int = 1_000
85
+ scheduler_decay_steps: int = 30_000
86
+ scheduler_decay_lr: float = 2.5e-6
87
+
88
+ # TODO: Add EMA
89
+
90
+ def __post_init__(self):
91
+ super().__post_init__()
92
+
93
+ # TODO(Steven): Validate device and amp? in all policy configs?
94
+ """Input validation (not exhaustive)."""
95
+ if self.n_action_steps > self.chunk_size:
96
+ raise ValueError(
97
+ f"The chunk size is the upper bound for the number of action steps per model invocation. Got "
98
+ f"{self.n_action_steps} for `n_action_steps` and {self.chunk_size} for `chunk_size`."
99
+ )
100
+ if self.n_obs_steps != 1:
101
+ raise ValueError(
102
+ f"Multiple observation steps not handled yet. Got `nobs_steps={self.n_obs_steps}`"
103
+ )
104
+
105
+ if self.use_delta_joint_actions_aloha:
106
+ raise NotImplementedError(
107
+ "`use_delta_joint_actions_aloha` is used by pi0 for aloha real models. It is not ported yet in LeRobot."
108
+ )
109
+
110
+ def validate_features(self) -> None:
111
+ # TODO: implement value error
112
+ # if not self.image_features and not self.env_state_feature:
113
+ # raise ValueError("You must provide at least one image or the environment state among the inputs.")
114
+
115
+ for i in range(self.empty_cameras):
116
+ key = f"observation.images.empty_camera_{i}"
117
+ empty_camera = PolicyFeature(
118
+ type=FeatureType.VISUAL,
119
+ shape=(3, 480, 640),
120
+ )
121
+ self.input_features[key] = empty_camera
122
+
123
+ def get_optimizer_preset(self) -> AdamWConfig:
124
+ return AdamWConfig(
125
+ lr=self.optimizer_lr,
126
+ betas=self.optimizer_betas,
127
+ eps=self.optimizer_eps,
128
+ weight_decay=self.optimizer_weight_decay,
129
+ )
130
+
131
+ def get_scheduler_preset(self):
132
+ return CosineDecayWithWarmupSchedulerConfig(
133
+ peak_lr=self.optimizer_lr,
134
+ decay_lr=self.scheduler_decay_lr,
135
+ num_warmup_steps=self.scheduler_warmup_steps,
136
+ num_decay_steps=self.scheduler_decay_steps,
137
+ )
138
+
139
+ @property
140
+ def observation_delta_indices(self) -> None:
141
+ return None
142
+
143
+ @property
144
+ def action_delta_indices(self) -> list:
145
+ return list(range(self.chunk_size))
146
+
147
+ @property
148
+ def reward_delta_indices(self) -> None:
149
+ return None
tools/lerobot_v21_runtime/src/lerobot/policies/pi0/conversion_scripts/benchmark.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch
16
+
17
+ from lerobot.configs.policies import PreTrainedConfig
18
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
19
+ from lerobot.policies.factory import make_policy
20
+
21
+ torch.backends.cudnn.benchmark = True
22
+
23
+
24
+ def main():
25
+ device = "cuda"
26
+ dataset_repo_id = "danaaubakirova/koch_test"
27
+ # model_name = "pi0_base"
28
+ # ckpt_torch_dir = Path.home() / f".cache/openpi/openpi-assets/checkpoints/{model_name}_pytorch"
29
+ ckpt_torch_dir = "lerobot/pi0"
30
+
31
+ dataset = LeRobotDataset(dataset_repo_id, episodes=[0])
32
+
33
+ dataloader = torch.utils.data.DataLoader(
34
+ dataset,
35
+ num_workers=0,
36
+ batch_size=1,
37
+ )
38
+
39
+ batch = next(iter(dataloader))
40
+
41
+ # To device
42
+ for k in batch:
43
+ if isinstance(batch[k], torch.Tensor):
44
+ batch[k] = batch[k].to(device=device, dtype=torch.float32)
45
+
46
+ cfg = PreTrainedConfig.from_pretrained(ckpt_torch_dir)
47
+ cfg.pretrained_path = ckpt_torch_dir
48
+ policy = make_policy(cfg, ds_meta=dataset.meta)
49
+
50
+ # policy = torch.compile(policy, mode="reduce-overhead")
51
+
52
+ warmup_iters = 10
53
+ benchmark_iters = 30
54
+
55
+ # Warmup
56
+ for _ in range(warmup_iters):
57
+ torch.cuda.synchronize()
58
+ policy.select_action(batch)
59
+ policy.reset()
60
+ torch.cuda.synchronize()
61
+
62
+ # Benchmark
63
+ start_event = torch.cuda.Event(enable_timing=True)
64
+ end_event = torch.cuda.Event(enable_timing=True)
65
+
66
+ start_event.record()
67
+ for _ in range(benchmark_iters):
68
+ policy.select_action(batch)
69
+ policy.reset()
70
+ end_event.record()
71
+
72
+ # Synchronize and measure time
73
+ torch.cuda.synchronize()
74
+ elapsed_time_ms = start_event.elapsed_time(end_event)
75
+
76
+ avg_time_per_iter = elapsed_time_ms / benchmark_iters
77
+ print(f"Average execution time per iteration: {avg_time_per_iter:.3f} ms")
78
+
79
+
80
+ if __name__ == "__main__":
81
+ with torch.inference_mode():
82
+ main()
tools/lerobot_v21_runtime/src/lerobot/policies/pi0/conversion_scripts/compare_with_jax.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import json
16
+ import pickle
17
+ from pathlib import Path
18
+
19
+ import torch
20
+
21
+ from lerobot.configs.policies import PreTrainedConfig
22
+ from lerobot.datasets.lerobot_dataset import LeRobotDatasetMetadata
23
+ from lerobot.policies.factory import make_policy
24
+
25
+
26
+ def display(tensor: torch.Tensor):
27
+ if tensor.dtype == torch.bool:
28
+ tensor = tensor.float()
29
+ print(f"Shape: {tensor.shape}")
30
+ print(f"Mean: {tensor.mean().item()}")
31
+ print(f"Std: {tensor.std().item()}")
32
+ print(f"Min: {tensor.min().item()}")
33
+ print(f"Max: {tensor.max().item()}")
34
+
35
+
36
+ def main():
37
+ num_motors = 14
38
+ device = "cuda"
39
+ # model_name = "pi0_aloha_towel"
40
+ model_name = "pi0_aloha_sim"
41
+
42
+ if model_name == "pi0_aloha_towel":
43
+ dataset_repo_id = "lerobot/aloha_static_towel"
44
+ else:
45
+ dataset_repo_id = "lerobot/aloha_sim_transfer_cube_human"
46
+
47
+ ckpt_torch_dir = Path.home() / f".cache/openpi/openpi-assets/checkpoints/{model_name}_pytorch"
48
+ ckpt_jax_dir = Path.home() / f".cache/openpi/openpi-assets/checkpoints/{model_name}"
49
+ save_dir = Path(f"../openpi/data/{model_name}/save")
50
+
51
+ with open(save_dir / "example.pkl", "rb") as f:
52
+ example = pickle.load(f)
53
+ with open(save_dir / "outputs.pkl", "rb") as f:
54
+ outputs = pickle.load(f)
55
+ with open(save_dir / "noise.pkl", "rb") as f:
56
+ noise = pickle.load(f)
57
+
58
+ with open(ckpt_jax_dir / "assets/norm_stats.json") as f:
59
+ norm_stats = json.load(f)
60
+
61
+ # Override stats
62
+ dataset_meta = LeRobotDatasetMetadata(dataset_repo_id)
63
+ dataset_meta.stats["observation.state"]["mean"] = torch.tensor(
64
+ norm_stats["norm_stats"]["state"]["mean"][:num_motors], dtype=torch.float32
65
+ )
66
+ dataset_meta.stats["observation.state"]["std"] = torch.tensor(
67
+ norm_stats["norm_stats"]["state"]["std"][:num_motors], dtype=torch.float32
68
+ )
69
+
70
+ # Create LeRobot batch from Jax
71
+ batch = {}
72
+ for cam_key, uint_chw_array in example["images"].items():
73
+ batch[f"observation.images.{cam_key}"] = torch.from_numpy(uint_chw_array) / 255.0
74
+ batch["observation.state"] = torch.from_numpy(example["state"])
75
+ batch["action"] = torch.from_numpy(outputs["actions"])
76
+ batch["task"] = example["prompt"]
77
+
78
+ if model_name == "pi0_aloha_towel":
79
+ del batch["observation.images.cam_low"]
80
+ elif model_name == "pi0_aloha_sim":
81
+ batch["observation.images.top"] = batch["observation.images.cam_high"]
82
+ del batch["observation.images.cam_high"]
83
+
84
+ # Batchify
85
+ for key in batch:
86
+ if isinstance(batch[key], torch.Tensor):
87
+ batch[key] = batch[key].unsqueeze(0)
88
+ elif isinstance(batch[key], str):
89
+ batch[key] = [batch[key]]
90
+ else:
91
+ raise ValueError(f"{key}, {batch[key]}")
92
+
93
+ # To device
94
+ for k in batch:
95
+ if isinstance(batch[k], torch.Tensor):
96
+ batch[k] = batch[k].to(device=device, dtype=torch.float32)
97
+
98
+ noise = torch.from_numpy(noise).to(device=device, dtype=torch.float32)
99
+
100
+ from lerobot import policies # noqa
101
+
102
+ cfg = PreTrainedConfig.from_pretrained(ckpt_torch_dir)
103
+ cfg.pretrained_path = ckpt_torch_dir
104
+ policy = make_policy(cfg, dataset_meta)
105
+
106
+ # loss_dict = policy.forward(batch, noise=noise, time=time_beta)
107
+ # loss_dict["loss"].backward()
108
+ # print("losses")
109
+ # display(loss_dict["losses_after_forward"])
110
+ # print("pi_losses")
111
+ # display(pi_losses)
112
+
113
+ actions = []
114
+ for _ in range(50):
115
+ action = policy.select_action(batch, noise=noise)
116
+ actions.append(action)
117
+
118
+ actions = torch.stack(actions, dim=1)
119
+ pi_actions = batch["action"]
120
+ print("actions")
121
+ display(actions)
122
+ print()
123
+ print("pi_actions")
124
+ display(pi_actions)
125
+ print("atol=3e-2", torch.allclose(actions, pi_actions, atol=3e-2))
126
+ print("atol=2e-2", torch.allclose(actions, pi_actions, atol=2e-2))
127
+ print("atol=1e-2", torch.allclose(actions, pi_actions, atol=1e-2))
128
+
129
+
130
+ if __name__ == "__main__":
131
+ main()
tools/lerobot_v21_runtime/src/lerobot/policies/pi0/conversion_scripts/conversion_utils.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 transformers import GemmaConfig, PaliGemmaConfig
16
+
17
+
18
+ def get_paligemma_config(precision: str):
19
+ config = {
20
+ "image_token_index": None,
21
+ "pad_token_id": 0,
22
+ "bos_token_id": 2,
23
+ "eos_token_id": 1,
24
+ }
25
+
26
+ # image_sizes = {"2b-test": 224, "3b-224px": 224, "3b-448px": 448, "3b-896px": 896}
27
+
28
+ image_size = 224 # image_sizes[variant]
29
+ patch_size = 14
30
+ num_image_tokens = (image_size**2) // (patch_size**2)
31
+
32
+ config["image_token_index"] = 257152
33
+ text_config = {
34
+ "vocab_size": 257152,
35
+ "num_hidden_layers": 18,
36
+ "num_key_value_heads": 1,
37
+ "head_dim": 256,
38
+ "torch_dtype": precision,
39
+ "hidden_size": 2048,
40
+ "hidden_activation": "gelu_pytorch_tanh",
41
+ "num_attention_heads": 8,
42
+ "intermediate_size": 16384,
43
+ "is_encoder_decoder": False,
44
+ }
45
+ vision_config = {
46
+ "torch_dtype": precision,
47
+ "image_size": image_size,
48
+ "patch_size": patch_size,
49
+ "num_image_tokens": num_image_tokens,
50
+ "hidden_size": 1152,
51
+ "intermediate_size": 4304,
52
+ "num_hidden_layers": 27,
53
+ "num_attention_heads": 16,
54
+ "projector_hidden_act": "gelu_fast",
55
+ "vision_use_head": False,
56
+ }
57
+ final_config = PaliGemmaConfig(text_config=text_config, vision_config=vision_config, **config)
58
+ return final_config
59
+
60
+
61
+ def get_gemma_config(precision: str):
62
+ config = {
63
+ "image_token_index": None,
64
+ "pad_token_id": 0,
65
+ "bos_token_id": 2,
66
+ "eos_token_id": 1,
67
+ }
68
+
69
+ config["image_token_index"] = 257152
70
+ text_config = {
71
+ "vocab_size": 257152,
72
+ "num_hidden_layers": 18,
73
+ "num_key_value_heads": 1,
74
+ "head_dim": 256,
75
+ "torch_dtype": precision,
76
+ "hidden_size": 1024,
77
+ "hidden_activation": "gelu_pytorch_tanh",
78
+ "num_attention_heads": 8,
79
+ "intermediate_size": 4096,
80
+ "is_encoder_decoder": False,
81
+ }
82
+ final_config = GemmaConfig()
83
+ final_config.update(text_config)
84
+ return final_config
tools/lerobot_v21_runtime/src/lerobot/policies/pi0/conversion_scripts/convert_pi0_to_hf_lerobot.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
16
+ Convert pi0 parameters from Jax to Pytorch
17
+
18
+ Follow [README of openpi](https://github.com/Physical-Intelligence/openpi) to create a new environment
19
+ and install the required libraries.
20
+
21
+ ```bash
22
+ cd ~/code/openpi
23
+ source .venv/bin/activate
24
+ ```
25
+
26
+ Example downloading parameters:
27
+ ```bash
28
+ python
29
+ >>> import openpi.shared.download as download
30
+ >>> path='s3://openpi-assets/checkpoints/pi0_base/params'
31
+ >>> download.maybe_download(path)
32
+ ```
33
+
34
+ Converting pi0_base:
35
+ ```python
36
+ python -m lerobot.policies.pi0.conversion_scripts.convert_pi0_to_hf_lerobot \
37
+ --checkpoint_dir /home/remi_cadene/.cache/openpi/openpi-assets/checkpoints/pi0_base/params \
38
+ --output_path /home/remi_cadene/.cache/openpi/openpi-assets/checkpoints/pi0_base_pytorch
39
+ ```
40
+
41
+ ```python
42
+ python -m lerobot.policies.pi0.conversion_scripts.convert_pi0_to_hf_lerobot \
43
+ --checkpoint_dir /home/remi_cadene/.cache/openpi/openpi-assets/checkpoints/pi0_aloha_sim/params \
44
+ --output_path /home/remi_cadene/.cache/openpi/openpi-assets/checkpoints/pi0_aloha_sim_pytorch
45
+ ```
46
+ """
47
+
48
+ import argparse
49
+ import pathlib
50
+
51
+ import jax
52
+ import numpy as np
53
+ import orbax.checkpoint as ocp
54
+ import torch
55
+ from jax.sharding import SingleDeviceSharding
56
+
57
+ from lerobot.policies.pi0.configuration_pi0 import PI0Config
58
+ from lerobot.policies.pi0.conversion_scripts.conversion_utils import (
59
+ get_gemma_config,
60
+ get_paligemma_config,
61
+ )
62
+ from lerobot.policies.pi0.modeling_pi0 import PI0Policy
63
+
64
+ PRECISIONS = {"bfloat16": torch.bfloat16, "float32": torch.float32, "float16": torch.float16}
65
+
66
+
67
+ def slice_paligemma_state_dict(state_dict, config):
68
+ suffix = "/value" if "img/embedding/kernel/value" in state_dict else ""
69
+
70
+ # fmt: off
71
+ # patch embeddings
72
+ state_dict["paligemma.vision_tower.vision_model.embeddings.patch_embedding.weight"] = state_dict.pop(f"img/embedding/kernel{suffix}").transpose(
73
+ 3, 2, 0, 1
74
+ )
75
+ state_dict["paligemma.vision_tower.vision_model.embeddings.patch_embedding.bias"] = state_dict.pop(f"img/embedding/bias{suffix}")
76
+ # positional embeddings
77
+ state_dict["paligemma.vision_tower.vision_model.embeddings.position_embedding.weight"] = state_dict.pop(f"img/pos_embedding{suffix}").reshape(
78
+ -1, config.vision_config.hidden_size
79
+ )
80
+
81
+ # extract vision layers to be sliced at index 0. There are 27 layers in the base model.
82
+ encoderblock_layernorm0_scale = state_dict.pop(f"img/Transformer/encoderblock/LayerNorm_0/scale{suffix}")
83
+ encoderblock_layernorm0_bias = state_dict.pop(f"img/Transformer/encoderblock/LayerNorm_0/bias{suffix}")
84
+ encoderblock_layernorm1_scale = state_dict.pop(f"img/Transformer/encoderblock/LayerNorm_1/scale{suffix}")
85
+ encoderblock_layernorm1_bias = state_dict.pop(f"img/Transformer/encoderblock/LayerNorm_1/bias{suffix}")
86
+
87
+ encoderblock_mlp_dense0_kernel= state_dict.pop(f"img/Transformer/encoderblock/MlpBlock_0/Dense_0/kernel{suffix}")
88
+ encoderblock_mlp_dense0_bias= state_dict.pop(f"img/Transformer/encoderblock/MlpBlock_0/Dense_0/bias{suffix}")
89
+ encoderblock_mlp_dense1_kernel= state_dict.pop(f"img/Transformer/encoderblock/MlpBlock_0/Dense_1/kernel{suffix}")
90
+ encoderblock_mlp_dense1_bias= state_dict.pop(f"img/Transformer/encoderblock/MlpBlock_0/Dense_1/bias{suffix}")
91
+
92
+ encoderblock_attention_0_key_kernel = state_dict.pop(f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/key/kernel{suffix}")
93
+ encoderblock_attention_0_key_bias = state_dict.pop(f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/key/bias{suffix}")
94
+ encoderblock_attention_0_value_kernel = state_dict.pop(f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/value/kernel{suffix}")
95
+ encoderblock_attention_0_value_bias = state_dict.pop(f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/value/bias{suffix}")
96
+ encoderblock_attention_0_query_kernel = state_dict.pop(f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/query/kernel{suffix}")
97
+ encoderblock_attention_0_query_bias = state_dict.pop(f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/query/bias{suffix}")
98
+ encoderblock_attention_0_out_kernel = state_dict.pop(f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/out/kernel{suffix}")
99
+ encoderblock_attention_0_out_bias = state_dict.pop(f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/out/bias{suffix}")
100
+
101
+ for i in range(config.vision_config.num_hidden_layers):
102
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.layer_norm1.weight"] = encoderblock_layernorm0_scale[i].transpose()
103
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.layer_norm1.bias"] = encoderblock_layernorm0_bias[i]
104
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.layer_norm2.weight"] = encoderblock_layernorm1_scale[i].transpose()
105
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.layer_norm2.bias"] = encoderblock_layernorm1_bias[i]
106
+
107
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.mlp.fc1.weight"] = encoderblock_mlp_dense0_kernel[i].transpose()
108
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.mlp.fc1.bias"] = encoderblock_mlp_dense0_bias[i]
109
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.mlp.fc2.weight"] = encoderblock_mlp_dense1_kernel[i].transpose()
110
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.mlp.fc2.bias"] = encoderblock_mlp_dense1_bias[i]
111
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.self_attn.k_proj.weight"] = encoderblock_attention_0_key_kernel[i].reshape(-1, config.vision_config.hidden_size).transpose()
112
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.self_attn.k_proj.bias"] = encoderblock_attention_0_key_bias[i].reshape(-1, config.vision_config.hidden_size).reshape(-1)
113
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.self_attn.v_proj.weight"] = encoderblock_attention_0_value_kernel[i].reshape(-1, config.vision_config.hidden_size).transpose()
114
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.self_attn.v_proj.bias"] = encoderblock_attention_0_value_bias[i].reshape(-1, config.vision_config.hidden_size).reshape(-1)
115
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.self_attn.q_proj.weight"] = encoderblock_attention_0_query_kernel[i].reshape(-1, config.vision_config.hidden_size).transpose()
116
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.self_attn.q_proj.bias"] = encoderblock_attention_0_query_bias[i].reshape(-1, config.vision_config.hidden_size).reshape(-1)
117
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.self_attn.out_proj.weight"] = encoderblock_attention_0_out_kernel[i].reshape(-1, config.vision_config.hidden_size).transpose()
118
+ state_dict[f"paligemma.vision_tower.vision_model.encoder.layers.{i}.self_attn.out_proj.bias"] = encoderblock_attention_0_out_bias[i].reshape(-1, config.vision_config.hidden_size).reshape(-1)
119
+
120
+ state_dict["paligemma.vision_tower.vision_model.post_layernorm.weight"] = state_dict.pop(f"img/Transformer/encoder_norm/scale{suffix}").transpose()
121
+ state_dict["paligemma.vision_tower.vision_model.post_layernorm.bias"] = state_dict.pop(f"img/Transformer/encoder_norm/bias{suffix}")
122
+
123
+ # multimodal projector
124
+
125
+ state_dict['paligemma.multi_modal_projector.linear.weight'] = state_dict.pop(f"img/head/kernel{suffix}").transpose()
126
+ state_dict['paligemma.multi_modal_projector.linear.bias'] = state_dict.pop(f"img/head/bias{suffix}")
127
+
128
+ # text decoder (gemma)
129
+ embedding_vector = state_dict.pop(f"llm/embedder/input_embedding{suffix}")
130
+ state_dict["paligemma.language_model.model.embed_tokens.weight"] = embedding_vector
131
+
132
+ # pop the einsum attention + mlp representations. There are 18 layers in gemma-2b.
133
+
134
+ llm_attention_attn_vec_einsum = state_dict.pop(f"llm/layers/attn/attn_vec_einsum/w{suffix}")
135
+ llm_attention_kv_einsum = state_dict.pop(f"llm/layers/attn/kv_einsum/w{suffix}")
136
+ llm_attention_q_einsum = state_dict.pop(f"llm/layers/attn/q_einsum/w{suffix}")
137
+
138
+ llm_mlp_gating_einsum = state_dict.pop(f"llm/layers/mlp/gating_einsum{suffix}")
139
+ llm_mlp_linear = state_dict.pop(f"llm/layers/mlp/linear{suffix}")
140
+ # TODO verify correctness of layer norm loading
141
+
142
+ llm_input_layernorm = state_dict.pop(f"llm/layers/pre_attention_norm/scale{suffix}")
143
+ llm_post_attention_layernorm = state_dict.pop(f"llm/layers/pre_ffw_norm/scale{suffix}")
144
+
145
+ for i in range(config.text_config.num_hidden_layers):
146
+ # llm_attention_q_einsum[i].shape = (8, 2048, 256)
147
+ q_proj_weight_reshaped = llm_attention_q_einsum[i].transpose(0, 2, 1).reshape(config.text_config.num_attention_heads * config.text_config.head_dim, config.text_config.hidden_size)
148
+
149
+ state_dict[f"paligemma.language_model.model.layers.{i}.self_attn.q_proj.weight"] = q_proj_weight_reshaped
150
+
151
+ # llm_attention_kv_einsum[i, 0, 0].shape = (2048, 256)
152
+ k_proj_weight_reshaped = llm_attention_kv_einsum[i, 0, 0].transpose()
153
+ state_dict[f"paligemma.language_model.model.layers.{i}.self_attn.k_proj.weight"] = k_proj_weight_reshaped
154
+ # llm_attention_kv_einsum[i, 1, 0].shape = (2048, 256)
155
+ v_proj_weight_reshaped = llm_attention_kv_einsum[i, 1, 0].transpose()
156
+ state_dict[f"paligemma.language_model.model.layers.{i}.self_attn.v_proj.weight"] = v_proj_weight_reshaped
157
+
158
+ # output projection.
159
+
160
+ # llm_attention_attn_vec_einsum[i].shape = (8, 256, 2048)
161
+ o_proj_weight_reshaped = llm_attention_attn_vec_einsum[i].transpose(2, 0, 1).reshape(config.text_config.num_attention_heads * config.text_config.head_dim, config.text_config.hidden_size)
162
+
163
+ state_dict[f"paligemma.language_model.model.layers.{i}.self_attn.o_proj.weight"] = o_proj_weight_reshaped
164
+ # mlp layers
165
+ gate_proj_weight = llm_mlp_gating_einsum[i, 0]
166
+ state_dict[f"paligemma.language_model.model.layers.{i}.mlp.gate_proj.weight"] = gate_proj_weight.transpose()
167
+ up_proj_weight = llm_mlp_gating_einsum[i, 1]
168
+ state_dict[f"paligemma.language_model.model.layers.{i}.mlp.up_proj.weight"] = up_proj_weight.transpose()
169
+ state_dict[f"paligemma.language_model.model.layers.{i}.mlp.down_proj.weight"] = llm_mlp_linear[i].transpose()
170
+ state_dict[f"paligemma.language_model.model.layers.{i}.input_layernorm.weight"] = llm_input_layernorm[i]
171
+ state_dict[f"paligemma.language_model.model.layers.{i}.post_attention_layernorm.weight"] = llm_post_attention_layernorm[i]
172
+
173
+ state_dict["paligemma.language_model.model.norm.weight"] = state_dict.pop(f"llm/final_norm/scale{suffix}")
174
+ state_dict["paligemma.language_model.lm_head.weight"] = embedding_vector # weights are tied.
175
+
176
+ # fmt: on
177
+ expert_dict = {}
178
+ final_state_dict = {}
179
+ for key, value in state_dict.items():
180
+ if key not in [
181
+ f"llm/final_norm_1/scale{suffix}",
182
+ f"llm/layers/attn/attn_vec_einsum_1/w{suffix}",
183
+ f"llm/layers/attn/kv_einsum_1/w{suffix}",
184
+ f"llm/layers/attn/q_einsum_1/w{suffix}",
185
+ f"llm/layers/mlp_1/gating_einsum{suffix}",
186
+ f"llm/layers/mlp_1/linear{suffix}",
187
+ f"llm/layers/pre_attention_norm_1/scale{suffix}",
188
+ f"llm/layers/pre_ffw_norm_1/scale{suffix}",
189
+ ]:
190
+ final_state_dict[key] = torch.from_numpy(value)
191
+ else:
192
+ expert_dict[key] = value
193
+
194
+ return final_state_dict, expert_dict
195
+
196
+
197
+ def slice_gemma_state_dict(state_dict, config, num_expert=1):
198
+ # fmt: off
199
+ # text decoder (gemma)
200
+ # no embedding vector, the expert just has the decoder layers
201
+
202
+ embedding_vector = torch.zeros([config.vocab_size, config.hidden_size])
203
+ state_dict["gemma_expert.model.embed_tokens.weight"] = embedding_vector
204
+
205
+ # pop the einsum attention + mlp representations. There are 18 layers in gemma-2b.
206
+
207
+ suffix = "/value" if f"llm/layers/attn/attn_vec_einsum_{num_expert}/w/value" in state_dict else ""
208
+
209
+ llm_attention_attn_vec_einsum = state_dict.pop(f"llm/layers/attn/attn_vec_einsum_{num_expert}/w{suffix}")
210
+ llm_attention_kv_einsum = state_dict.pop(f"llm/layers/attn/kv_einsum_{num_expert}/w{suffix}")
211
+ llm_attention_q_einsum = state_dict.pop(f"llm/layers/attn/q_einsum_{num_expert}/w{suffix}")
212
+
213
+ llm_mlp_gating_einsum = state_dict.pop(f"llm/layers/mlp_{num_expert}/gating_einsum{suffix}")
214
+ llm_mlp_linear = state_dict.pop(f"llm/layers/mlp_{num_expert}/linear{suffix}")
215
+ # TODO verify correctness of layer norm loading
216
+
217
+ llm_input_layernorm = state_dict.pop(f"llm/layers/pre_attention_norm_{num_expert}/scale{suffix}")
218
+ llm_post_attention_layernorm = state_dict.pop(f"llm/layers/pre_ffw_norm_{num_expert}/scale{suffix}")
219
+
220
+ for i in range(config.num_hidden_layers):
221
+ q_proj_weight_reshaped = llm_attention_q_einsum[i].transpose(0, 2, 1).reshape(config.num_attention_heads * config.head_dim, config.hidden_size)
222
+
223
+ state_dict[f"gemma_expert.model.layers.{i}.self_attn.q_proj.weight"] = q_proj_weight_reshaped
224
+
225
+ k_proj_weight_reshaped = llm_attention_kv_einsum[i, 0, 0].transpose()
226
+ state_dict[f"gemma_expert.model.layers.{i}.self_attn.k_proj.weight"] = k_proj_weight_reshaped
227
+ v_proj_weight_reshaped = llm_attention_kv_einsum[i, 1, 0].transpose()
228
+ state_dict[f"gemma_expert.model.layers.{i}.self_attn.v_proj.weight"] = v_proj_weight_reshaped
229
+
230
+ # output projection.
231
+
232
+ # llm_attention_attn_vec_einsum[i].shape = (8, 256, 1024)
233
+ o_proj_weight_reshaped = llm_attention_attn_vec_einsum[i].reshape(config.num_attention_heads * config.head_dim, config.hidden_size).transpose(1,0)# .transpose(2, 0, 1).reshape(config.num_attention_heads * config.head_dim, config.hidden_size).transpose(1, 0)
234
+
235
+ state_dict[f"gemma_expert.model.layers.{i}.self_attn.o_proj.weight"] = o_proj_weight_reshaped
236
+ # mlp layers
237
+ gate_proj_weight = llm_mlp_gating_einsum[i, 0]
238
+ state_dict[f"gemma_expert.model.layers.{i}.mlp.gate_proj.weight"] = gate_proj_weight.transpose()
239
+ up_proj_weight = llm_mlp_gating_einsum[i, 1]
240
+ state_dict[f"gemma_expert.model.layers.{i}.mlp.up_proj.weight"] = up_proj_weight.transpose()
241
+ state_dict[f"gemma_expert.model.layers.{i}.mlp.down_proj.weight"] = llm_mlp_linear[i].transpose()
242
+ state_dict[f"gemma_expert.model.layers.{i}.input_layernorm.weight"] = llm_input_layernorm[i]
243
+ state_dict[f"gemma_expert.model.layers.{i}.post_attention_layernorm.weight"] = llm_post_attention_layernorm[i]
244
+
245
+ state_dict["gemma_expert.model.norm.weight"] = state_dict.pop(f"llm/final_norm_{num_expert}/scale{suffix}")
246
+ state_dict["gemma_expert.lm_head.weight"] = embedding_vector # weights are tied. (and zeros here)
247
+
248
+ # fmt: on
249
+ final_state_dict = {}
250
+ for key, value in state_dict.items():
251
+ if not isinstance(value, torch.Tensor):
252
+ final_state_dict[key] = torch.from_numpy(value)
253
+ else:
254
+ final_state_dict[key] = value
255
+ return final_state_dict
256
+
257
+
258
+ def flatten_for_memory(tree, parent_key=""):
259
+ out = {}
260
+ for k, v in tree.items():
261
+ new_key = f"{parent_key}/{k}" if parent_key else k
262
+ if isinstance(v, dict):
263
+ out.update(flatten_for_memory(v, new_key))
264
+ else:
265
+ out[new_key] = np.array(v) # Ensure conversion to np.array for consistency
266
+ return out
267
+
268
+
269
+ def flatten_for_npz(tree, parent_key=""):
270
+ out = {}
271
+ for k, v in tree.items():
272
+ new_key = f"{parent_key}/{k}" if parent_key else k
273
+ if isinstance(v, dict):
274
+ out.update(flatten_for_npz(v, new_key))
275
+ else:
276
+ # bf16/f32 here?
277
+ out[new_key] = np.array(v)
278
+ return out
279
+
280
+
281
+ def slice_initial_orbax_checkpoint(checkpoint_dir: str):
282
+ params_path = pathlib.Path(checkpoint_dir).resolve()
283
+ checkpointer = ocp.PyTreeCheckpointer()
284
+
285
+ metadata = checkpointer.metadata(params_path)
286
+ print("Metadata keys:", list(metadata.keys()))
287
+
288
+ params_name = "params"
289
+
290
+ item = {params_name: metadata[params_name]}
291
+ device = jax.local_devices()[0] # Use the first local device
292
+ sharding = SingleDeviceSharding(device)
293
+ restored = checkpointer.restore(
294
+ params_path,
295
+ ocp.args.PyTreeRestore(
296
+ item=item,
297
+ restore_args=jax.tree_util.tree_map(
298
+ lambda _: ocp.ArrayRestoreArgs(
299
+ restore_type=jax.Array, # or np.ndarray, but bf16 is annoying about it
300
+ sharding=sharding,
301
+ ),
302
+ item,
303
+ ),
304
+ transforms={},
305
+ ),
306
+ )
307
+ params = restored[params_name]
308
+
309
+ # get params for PaliGemma
310
+ pali_params = params["PaliGemma"]
311
+ del params["PaliGemma"]
312
+ pali_params_flat = flatten_for_npz(pali_params)
313
+ return {"paligemma_params": pali_params_flat, "projection_params": params}
314
+
315
+
316
+ def update_keys_with_prefix(d: dict, prefix: str) -> dict:
317
+ """Update dictionary keys by adding a prefix."""
318
+ return {f"{prefix}{key}": value for key, value in d.items()}
319
+
320
+
321
+ def convert_pi0_checkpoint(checkpoint_dir: str, precision: str, tokenizer_id: str, output_path: str):
322
+ # Break down orbax ckpts - they are in OCDBT
323
+ initial_params = slice_initial_orbax_checkpoint(checkpoint_dir=checkpoint_dir)
324
+ # process projection params
325
+ keys = [
326
+ "state_proj",
327
+ "action_in_proj",
328
+ "action_out_proj",
329
+ "action_time_mlp_in",
330
+ "action_time_mlp_out",
331
+ ]
332
+
333
+ projection_params = {}
334
+ for key in keys:
335
+ kernel_params = initial_params["projection_params"][key]["kernel"]
336
+ bias_params = initial_params["projection_params"][key]["bias"]
337
+ if isinstance(kernel_params, dict):
338
+ weight = kernel_params["value"]
339
+ bias = bias_params["value"]
340
+ else:
341
+ weight = kernel_params
342
+ bias = bias_params
343
+ projection_params[f"{key}.weight"] = torch.from_numpy(np.array(weight)).T
344
+ projection_params[f"{key}.bias"] = torch.from_numpy(np.array(bias))
345
+
346
+ # Process PaliGemma weights
347
+ paligemma_config = get_paligemma_config(precision)
348
+ paligemma_params, gemma_raw_dictionary = slice_paligemma_state_dict(
349
+ initial_params["paligemma_params"], paligemma_config
350
+ )
351
+
352
+ # Process Gemma weights (at this stage they are unused)
353
+ gemma_config = get_gemma_config(precision)
354
+ gemma_params = slice_gemma_state_dict(gemma_raw_dictionary, config=gemma_config)
355
+
356
+ # Instantiate model from configs
357
+
358
+ if "pi0_aloha_sim" in checkpoint_dir:
359
+ pi0_config = PI0Config(
360
+ empty_cameras=2,
361
+ adapt_to_pi_aloha=True,
362
+ use_delta_joint_actions_aloha=False,
363
+ )
364
+ elif "pi0_aloha_towel" in checkpoint_dir:
365
+ pi0_config = PI0Config(
366
+ adapt_to_pi_aloha=True,
367
+ use_delta_joint_actions_aloha=True,
368
+ )
369
+ elif "pi0_base" in checkpoint_dir:
370
+ pi0_config = PI0Config(
371
+ empty_cameras=0,
372
+ adapt_to_pi_aloha=False,
373
+ use_delta_joint_actions_aloha=False,
374
+ )
375
+ else:
376
+ raise ValueError()
377
+
378
+ # gemma_config=gemma_config, paligemma_config=paligemma_config)
379
+ pi0_model = PI0Policy(pi0_config)
380
+
381
+ paligemma_params = update_keys_with_prefix(paligemma_params, "model.paligemma_with_expert.")
382
+ gemma_params = update_keys_with_prefix(gemma_params, "model.paligemma_with_expert.")
383
+ projection_params = update_keys_with_prefix(projection_params, "model.")
384
+
385
+ # load state dict
386
+ torch_dtype = PRECISIONS[precision]
387
+ pi0_model.load_state_dict({**paligemma_params, **gemma_params, **projection_params})
388
+ pi0_model = pi0_model.to(torch_dtype)
389
+ # pi0_tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)
390
+
391
+ pi0_model.save_pretrained(output_path, safe_serialization=True)
392
+ # pi0_tokenizer.save_pretrained(output_path, dtype=torch_dtype)
393
+
394
+ # assert that model loads properly
395
+ del pi0_model
396
+ PI0Policy.from_pretrained(output_path)
397
+
398
+
399
+ if __name__ == "__main__":
400
+ parser = argparse.ArgumentParser()
401
+ parser.add_argument(
402
+ "--checkpoint_dir",
403
+ default="/raid/pablo/.cache/openpi/openpi-assets/checkpoints/pi0_aloha_sim/params",
404
+ type=str,
405
+ help="Path to the ocdbt checkpoint",
406
+ )
407
+
408
+ parser.add_argument(
409
+ "--precision",
410
+ choices=["float32", "bfloat16", "float16"],
411
+ default="float32",
412
+ type=str,
413
+ help="Precision identifier for model conversion - should match the base checkpoint precision.",
414
+ )
415
+ # tokenizer is identical to paligemma, it appears
416
+
417
+ parser.add_argument(
418
+ "--tokenizer_hub_id",
419
+ default="google/paligemma-3b-pt-224",
420
+ type=str,
421
+ help="Hub path to the tokenizer to save",
422
+ )
423
+
424
+ parser.add_argument(
425
+ "--output_path",
426
+ required=True,
427
+ type=str,
428
+ help="Path to save converted weights to",
429
+ )
430
+
431
+ args = parser.parse_args()
432
+ convert_pi0_checkpoint(
433
+ checkpoint_dir=args.checkpoint_dir,
434
+ precision=args.precision,
435
+ tokenizer_id=args.tokenizer_hub_id,
436
+ output_path=args.output_path,
437
+ )
tools/lerobot_v21_runtime/src/lerobot/policies/pi0/flex_attention.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch
16
+ import torch.nn.functional as F # noqa: N812
17
+ from packaging.version import Version
18
+
19
+ if Version(torch.__version__) > Version("2.5.0"):
20
+ # Ffex attention is only available from torch 2.5 onwards
21
+ from torch.nn.attention.flex_attention import (
22
+ _mask_mod_signature,
23
+ _round_up_to_multiple,
24
+ create_block_mask,
25
+ create_mask,
26
+ flex_attention,
27
+ )
28
+
29
+
30
+ # @torch.compile(dynamic=False)
31
+ def flex_attention_forward(
32
+ attention_mask: torch.Tensor,
33
+ batch_size: int,
34
+ head_dim: int,
35
+ query_states: torch.Tensor,
36
+ key_states: torch.Tensor,
37
+ value_states: torch.Tensor,
38
+ scaling=None,
39
+ ):
40
+ """
41
+ This is defined out of classes to make compile happy.
42
+ """
43
+
44
+ original_dtype = query_states.dtype
45
+ num_att_heads = 8
46
+ num_key_value_heads = 1
47
+ num_key_value_groups = num_att_heads // num_key_value_heads
48
+
49
+ key_states = key_states[:, :, :, None, :]
50
+ key_states = key_states.expand(
51
+ batch_size, key_states.shape[1], num_key_value_heads, num_key_value_groups, head_dim
52
+ )
53
+ key_states = key_states.reshape(
54
+ batch_size, key_states.shape[1], num_key_value_heads * num_key_value_groups, head_dim
55
+ )
56
+
57
+ value_states = value_states[:, :, :, None, :]
58
+ value_states = value_states.expand(
59
+ batch_size, value_states.shape[1], num_key_value_heads, num_key_value_groups, head_dim
60
+ )
61
+ value_states = value_states.reshape(
62
+ batch_size, value_states.shape[1], num_key_value_heads * num_key_value_groups, head_dim
63
+ )
64
+
65
+ query_states = query_states.transpose(1, 2)
66
+ key_states = key_states.transpose(1, 2)
67
+ value_states = value_states.transpose(1, 2)
68
+
69
+ query_states = query_states.to(torch.float32)
70
+ key_states = key_states.to(torch.float32)
71
+ value_states = value_states.to(torch.float32)
72
+
73
+ causal_mask = attention_mask
74
+ if causal_mask is not None:
75
+ causal_mask = causal_mask[:, None, :, : key_states.shape[2]]
76
+
77
+ if causal_mask.shape[1] == 1 and query_states.shape[1] > 1:
78
+ causal_mask = causal_mask.expand(-1, query_states.shape[1], -1, -1)
79
+
80
+ def precomputed_mask_factory(precomputed_mask: torch.Tensor) -> _mask_mod_signature:
81
+ def mask_mod(b, h, q_idx, kv_idx):
82
+ # Danger zone: if b,h,q_idx,kv_idx exceed the shape, device-side assert occurs.
83
+ return precomputed_mask[b][h][q_idx][kv_idx]
84
+
85
+ return mask_mod
86
+
87
+ b_mask, h_mask, q_len, kv_len = causal_mask.shape # The shape of your mask
88
+
89
+ block_size = 128
90
+ q_len_rounded = _round_up_to_multiple(q_len, block_size)
91
+ kv_len_rounded = _round_up_to_multiple(kv_len, block_size)
92
+
93
+ # *CRITICAL* we do need to expand here, else we get a CUDA index error
94
+
95
+ pad_q = q_len_rounded - q_len
96
+ pad_k = kv_len_rounded - kv_len
97
+
98
+ padded_causal_mask = F.pad(causal_mask, (0, pad_k, 0, pad_q), value=0.0)
99
+ mask_mod_fn_orig = precomputed_mask_factory(padded_causal_mask)
100
+
101
+ mask_4d = create_mask(
102
+ mod_fn=mask_mod_fn_orig,
103
+ B=b_mask,
104
+ H=h_mask,
105
+ Q_LEN=q_len_rounded,
106
+ KV_LEN=kv_len_rounded,
107
+ device=causal_mask.device,
108
+ _compile=False,
109
+ )
110
+
111
+ mask_mod_fn_padded = precomputed_mask_factory(mask_4d)
112
+ block_mask = create_block_mask(
113
+ mask_mod=mask_mod_fn_padded,
114
+ B=b_mask,
115
+ H=h_mask,
116
+ Q_LEN=q_len_rounded,
117
+ KV_LEN=kv_len_rounded,
118
+ BLOCK_SIZE=block_size,
119
+ device=causal_mask.device,
120
+ _compile=False,
121
+ )
122
+
123
+ # mask is applied inside the kernel, ideally more efficiently than score_mod.
124
+ attn_output, attention_weights = flex_attention(
125
+ query_states,
126
+ key_states,
127
+ value_states,
128
+ block_mask=block_mask,
129
+ enable_gqa=True, # because we shaped query/key states for GQA
130
+ scale=head_dim**-0.5 if scaling is None else scaling,
131
+ return_lse=True,
132
+ )
133
+
134
+ attn_output = attn_output.to(dtype=original_dtype)
135
+ attn_output = attn_output.transpose(1, 2).contiguous() # [B, Q_LEN, H, head_dim]
136
+ attn_output = attn_output.reshape(
137
+ batch_size,
138
+ -1,
139
+ attn_output.shape[2] * attn_output.shape[3], # merges [H, head_dim]
140
+ )
141
+ return attn_output
tools/lerobot_v21_runtime/src/lerobot/policies/pi0/modeling_pi0.py ADDED
@@ -0,0 +1,837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2025 Physical Intelligence and 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
+ """
18
+ π0: A Vision-Language-Action Flow Model for General Robot Control
19
+
20
+ [Paper](https://www.physicalintelligence.company/download/pi0.pdf)
21
+ [Jax code](https://github.com/Physical-Intelligence/openpi)
22
+
23
+ Designed by Physical Intelligence. Ported from Jax by Hugging Face.
24
+ Disclaimer: It is not expected to perform as well as the original implementation.
25
+
26
+ Install pi0 extra dependencies:
27
+ ```bash
28
+ pip install -e ".[pi0]"
29
+ ```
30
+
31
+ Example of finetuning the pi0 pretrained model (`pi0_base` in `openpi`):
32
+ ```bash
33
+ python -m lerobot.scripts.train \
34
+ --policy.path=lerobot/pi0 \
35
+ --dataset.repo_id=danaaubakirova/koch_test
36
+ ```
37
+
38
+ Example of finetuning the pi0 neural network with PaliGemma and expert Gemma
39
+ pretrained with VLM default parameters before pi0 finetuning:
40
+ ```bash
41
+ python -m lerobot.scripts.train \
42
+ --policy.type=pi0 \
43
+ --dataset.repo_id=danaaubakirova/koch_test
44
+ ```
45
+
46
+ Example of using the pi0 pretrained model outside LeRobot training framework:
47
+ ```python
48
+ policy = Pi0Policy.from_pretrained("lerobot/pi0")
49
+ ```
50
+
51
+ """
52
+
53
+ import math
54
+ from collections import deque
55
+
56
+ import torch
57
+ import torch.nn.functional as F # noqa: N812
58
+ from torch import Tensor, nn
59
+ from transformers import AutoTokenizer
60
+
61
+ from lerobot.constants import ACTION, OBS_STATE
62
+ from lerobot.policies.normalize import Normalize, Unnormalize
63
+ from lerobot.policies.pi0.configuration_pi0 import PI0Config
64
+ from lerobot.policies.pi0.paligemma_with_expert import (
65
+ PaliGemmaWithExpertConfig,
66
+ PaliGemmaWithExpertModel,
67
+ )
68
+ from lerobot.policies.pretrained import PreTrainedPolicy
69
+ from lerobot.policies.utils import log_model_loading_keys
70
+ from lerobot.utils.utils import get_safe_dtype, init_logging
71
+
72
+
73
+ def create_sinusoidal_pos_embedding(
74
+ time: torch.tensor, dimension: int, min_period: float, max_period: float, device="cpu"
75
+ ) -> Tensor:
76
+ """Computes sine-cosine positional embedding vectors for scalar positions."""
77
+ if dimension % 2 != 0:
78
+ raise ValueError(f"dimension ({dimension}) must be divisible by 2")
79
+
80
+ if time.ndim != 1:
81
+ raise ValueError("The time tensor is expected to be of shape `(batch_size, )`.")
82
+
83
+ dtype = get_safe_dtype(torch.float64, device.type)
84
+ fraction = torch.linspace(0.0, 1.0, dimension // 2, dtype=dtype, device=device)
85
+ period = min_period * (max_period / min_period) ** fraction
86
+
87
+ # Compute the outer product
88
+ scaling_factor = 1.0 / period * 2 * math.pi
89
+ sin_input = scaling_factor[None, :] * time[:, None]
90
+ pos_emb = torch.cat([torch.sin(sin_input), torch.cos(sin_input)], dim=1)
91
+ return pos_emb
92
+
93
+
94
+ def make_att_2d_masks(pad_masks, att_masks):
95
+ """Copied from big_vision.
96
+
97
+ Tokens can attend to valid inputs tokens which have a cumulative mask_ar
98
+ smaller or equal to theirs. This way `mask_ar` int[B, N] can be used to
99
+ setup several types of attention, for example:
100
+
101
+ [[1 1 1 1 1 1]]: pure causal attention.
102
+
103
+ [[0 0 0 1 1 1]]: prefix-lm attention. The first 3 tokens can attend between
104
+ themselves and the last 3 tokens have a causal attention. The first
105
+ entry could also be a 1 without changing behaviour.
106
+
107
+ [[1 0 1 0 1 0 0 1 0 0]]: causal attention between 4 blocks. Tokens of a
108
+ block can attend all previous blocks and all tokens on the same block.
109
+
110
+ Args:
111
+ input_mask: bool[B, N] true if its part of the input, false if padding.
112
+ mask_ar: int32[B, N] mask that's 1 where previous tokens cannot depend on
113
+ it and 0 where it shares the same attention mask as the previous token.
114
+ """
115
+ if att_masks.ndim != 2:
116
+ raise ValueError(att_masks.ndim)
117
+ if pad_masks.ndim != 2:
118
+ raise ValueError(pad_masks.ndim)
119
+
120
+ cumsum = torch.cumsum(att_masks, dim=1)
121
+ att_2d_masks = cumsum[:, None, :] <= cumsum[:, :, None]
122
+ pad_2d_masks = pad_masks[:, None, :] * pad_masks[:, :, None]
123
+ att_2d_masks = att_2d_masks & pad_2d_masks
124
+ return att_2d_masks
125
+
126
+
127
+ def resize_with_pad(img, width, height, pad_value=-1):
128
+ # assume no-op when width height fits already
129
+ if img.ndim != 4:
130
+ raise ValueError(f"(b,c,h,w) expected, but {img.shape}")
131
+
132
+ cur_height, cur_width = img.shape[2:]
133
+
134
+ ratio = max(cur_width / width, cur_height / height)
135
+ resized_height = int(cur_height / ratio)
136
+ resized_width = int(cur_width / ratio)
137
+ resized_img = F.interpolate(
138
+ img, size=(resized_height, resized_width), mode="bilinear", align_corners=False
139
+ )
140
+
141
+ pad_height = max(0, int(height - resized_height))
142
+ pad_width = max(0, int(width - resized_width))
143
+
144
+ # pad on left and top of image
145
+ padded_img = F.pad(resized_img, (pad_width, 0, pad_height, 0), value=pad_value)
146
+ return padded_img
147
+
148
+
149
+ def pad_vector(vector, new_dim):
150
+ """Can be (batch_size x sequence_length x features_dimension)
151
+ or (batch_size x features_dimension)
152
+ """
153
+ if vector.shape[-1] == new_dim:
154
+ return vector
155
+ shape = list(vector.shape)
156
+ current_dim = shape[-1]
157
+ shape[-1] = new_dim
158
+ new_vector = torch.zeros(*shape, dtype=vector.dtype, device=vector.device)
159
+ new_vector[..., :current_dim] = vector
160
+ return new_vector
161
+
162
+
163
+ def normalize(x, min_val, max_val):
164
+ return (x - min_val) / (max_val - min_val)
165
+
166
+
167
+ def unnormalize(x, min_val, max_val):
168
+ return x * (max_val - min_val) + min_val
169
+
170
+
171
+ def safe_arcsin(value):
172
+ # This ensures that the input stays within
173
+ # [−1,1] to avoid invalid values for arcsin
174
+ return torch.arcsin(torch.clamp(value, -1.0, 1.0))
175
+
176
+
177
+ def aloha_gripper_to_angular(value):
178
+ # Aloha transforms the gripper positions into a linear space. The following code
179
+ # reverses this transformation to be consistent with pi0 which is pretrained in
180
+ # angular space.
181
+ #
182
+ # These values are coming from the Aloha code:
183
+ # PUPPET_GRIPPER_POSITION_OPEN, PUPPET_GRIPPER_POSITION_CLOSED
184
+ value = unnormalize(value, min_val=0.01844, max_val=0.05800)
185
+
186
+ # This is the inverse of the angular to linear transformation inside the Interbotix code.
187
+ def linear_to_radian(linear_position, arm_length, horn_radius):
188
+ value = (horn_radius**2 + linear_position**2 - arm_length**2) / (2 * horn_radius * linear_position)
189
+ return safe_arcsin(value)
190
+
191
+ # The constants are taken from the Interbotix code.
192
+ value = linear_to_radian(value, arm_length=0.036, horn_radius=0.022)
193
+
194
+ # Normalize to [0, 1].
195
+ # The values 0.4 and 1.5 were measured on an actual Trossen robot.
196
+ return normalize(value, min_val=0.4, max_val=1.5)
197
+
198
+
199
+ def aloha_gripper_from_angular(value):
200
+ # Convert from the gripper position used by pi0 to the gripper position that is used by Aloha.
201
+ # Note that the units are still angular but the range is different.
202
+
203
+ # The values 0.4 and 1.5 were measured on an actual Trossen robot.
204
+ value = unnormalize(value, min_val=0.4, max_val=1.5)
205
+
206
+ # These values are coming from the Aloha code:
207
+ # PUPPET_GRIPPER_JOINT_OPEN, PUPPET_GRIPPER_JOINT_CLOSE
208
+ return normalize(value, min_val=-0.6213, max_val=1.4910)
209
+
210
+
211
+ def aloha_gripper_from_angular_inv(value):
212
+ # Directly inverts the gripper_from_angular function.
213
+ value = unnormalize(value, min_val=-0.6213, max_val=1.4910)
214
+ return normalize(value, min_val=0.4, max_val=1.5)
215
+
216
+
217
+ class PI0Policy(PreTrainedPolicy):
218
+ """Wrapper class around PI0FlowMatching model to train and run inference within LeRobot."""
219
+
220
+ config_class = PI0Config
221
+ name = "pi0"
222
+
223
+ def __init__(
224
+ self,
225
+ config: PI0Config,
226
+ dataset_stats: dict[str, dict[str, Tensor]] | None = None,
227
+ ):
228
+ """
229
+ Args:
230
+ config: Policy configuration class instance or None, in which case the default instantiation of
231
+ the configuration class is used.
232
+ dataset_stats: Dataset statistics to be used for normalization. If not passed here, it is expected
233
+ that they will be passed with a call to `load_state_dict` before the policy is used.
234
+ """
235
+
236
+ super().__init__(config)
237
+ config.validate_features()
238
+ self.config = config
239
+ self.normalize_inputs = Normalize(config.input_features, config.normalization_mapping, dataset_stats)
240
+ self.normalize_targets = Normalize(
241
+ config.output_features, config.normalization_mapping, dataset_stats
242
+ )
243
+ self.unnormalize_outputs = Unnormalize(
244
+ config.output_features, config.normalization_mapping, dataset_stats
245
+ )
246
+
247
+ self.language_tokenizer = AutoTokenizer.from_pretrained("google/paligemma-3b-pt-224")
248
+ self.model = PI0FlowMatching(config)
249
+
250
+ self.reset()
251
+
252
+ def reset(self):
253
+ """This should be called whenever the environment is reset."""
254
+ self._action_queue = deque([], maxlen=self.config.n_action_steps)
255
+
256
+ @classmethod
257
+ def _transform_state_dict_keys(cls, state_dict: dict) -> dict:
258
+ """
259
+ Transform state dict keys to match expected model structure.
260
+
261
+ Transformations:
262
+ - model.paligemma_with_expert.paligemma.language_model.lm_head ->
263
+ model.paligemma_with_expert.paligemma.lm_head
264
+ - model.paligemma_with_expert.paligemma.language_model.model ->
265
+ model.paligemma_with_expert.paligemma.model.language_model
266
+ - model.paligemma_with_expert.paligemma.vision_tower ->
267
+ model.paligemma_with_expert.paligemma.model.vision_tower
268
+ - model.paligemma_with_expert.paligemma.multi_modal_projector ->
269
+ model.paligemma_with_expert.paligemma.model.multi_modal_projector
270
+
271
+ Also handles tied weights between lm_head.weight and
272
+ embed_tokens.weight.
273
+ """
274
+ import re
275
+
276
+ transformed_dict = {}
277
+
278
+ transformations = [
279
+ (
280
+ re.compile(r"\.paligemma_with_expert\.paligemma\.language_model\.lm_head"),
281
+ ".paligemma_with_expert.paligemma.lm_head",
282
+ ),
283
+ (
284
+ re.compile(r"\.paligemma_with_expert\.paligemma\.language_model\.model"),
285
+ ".paligemma_with_expert.paligemma.model.language_model",
286
+ ),
287
+ (
288
+ re.compile(r"\.paligemma_with_expert\.paligemma\.vision_tower"),
289
+ ".paligemma_with_expert.paligemma.model.vision_tower",
290
+ ),
291
+ (
292
+ re.compile(r"\.paligemma_with_expert\.paligemma\.multi_modal_projector"),
293
+ ".paligemma_with_expert.paligemma.model.multi_modal_projector",
294
+ ),
295
+ ]
296
+
297
+ for key, value in state_dict.items():
298
+ new_key = key
299
+ for pattern, replacement in transformations:
300
+ new_key = pattern.sub(replacement, new_key)
301
+ transformed_dict[new_key] = value
302
+
303
+ # Handle tied weights: lm_head.weight and embed_tokens.weight share memory
304
+ lm_head_key = None
305
+ embed_tokens_key = None
306
+
307
+ for key in transformed_dict:
308
+ if key.endswith(".paligemma_with_expert.paligemma.lm_head.weight"):
309
+ lm_head_key = key
310
+ elif key.endswith(".paligemma_with_expert.paligemma.model.language_model.embed_tokens.weight"):
311
+ embed_tokens_key = key
312
+ if lm_head_key and embed_tokens_key:
313
+ break
314
+
315
+ if lm_head_key and not embed_tokens_key:
316
+ embed_tokens_key = lm_head_key.replace(
317
+ ".lm_head.weight", ".model.language_model.embed_tokens.weight"
318
+ )
319
+ transformed_dict[embed_tokens_key] = transformed_dict[lm_head_key]
320
+ elif embed_tokens_key and not lm_head_key:
321
+ lm_head_key = embed_tokens_key.replace(
322
+ ".model.language_model.embed_tokens.weight", ".lm_head.weight"
323
+ )
324
+ transformed_dict[lm_head_key] = transformed_dict[embed_tokens_key]
325
+
326
+ return transformed_dict
327
+
328
+ @classmethod
329
+ def _load_as_safetensor(
330
+ cls, model: "PI0Policy", model_file: str, map_location: str, strict: bool
331
+ ) -> "PI0Policy":
332
+ """Override to apply key transformations before loading."""
333
+ from safetensors.torch import load_file
334
+
335
+ init_logging()
336
+ # Load the state dict from file safely
337
+ state_dict = load_file(model_file, device=map_location)
338
+
339
+ # Apply key transformations
340
+ transformed_state_dict = cls._transform_state_dict_keys(state_dict)
341
+
342
+ # Load the transformed state dict
343
+ msg = model.load_state_dict(transformed_state_dict, strict=strict)
344
+
345
+ # Log message
346
+ log_model_loading_keys(msg.missing_keys, msg.unexpected_keys)
347
+ return model
348
+
349
+ def get_optim_params(self) -> dict:
350
+ return self.parameters()
351
+
352
+ @classmethod
353
+ def from_pretrained(cls, *args, **kwargs):
354
+ """Override the from_pretrained method to display important disclaimer."""
355
+ print(
356
+ "⚠️ DISCLAIMER: The PI0 model is ported from JAX by the Hugging Face team. \n"
357
+ " It is not expected to perform as well as the original implementation. \n"
358
+ " Original implementation: https://github.com/Physical-Intelligence/openpi"
359
+ )
360
+ return super().from_pretrained(*args, **kwargs)
361
+
362
+ @torch.no_grad()
363
+ def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor:
364
+ """Predict a chunk of actions given environment observations."""
365
+ raise NotImplementedError("Currently not implemented for PI0")
366
+
367
+ @torch.no_grad()
368
+ def select_action(self, batch: dict[str, Tensor], noise: Tensor | None = None) -> Tensor:
369
+ """Select a single action given environment observations.
370
+
371
+ This method wraps `select_actions` in order to return one action at a time for execution in the
372
+ environment. It works by managing the actions in a queue and only calling `select_actions` when the
373
+ queue is empty.
374
+ """
375
+ self.eval()
376
+
377
+ if self.config.adapt_to_pi_aloha:
378
+ batch[OBS_STATE] = self._pi_aloha_decode_state(batch[OBS_STATE])
379
+
380
+ batch = self.normalize_inputs(batch)
381
+
382
+ # Action queue logic for n_action_steps > 1. When the action_queue is depleted, populate it by
383
+ # querying the policy.
384
+ if len(self._action_queue) == 0:
385
+ images, img_masks = self.prepare_images(batch)
386
+ state = self.prepare_state(batch)
387
+ lang_tokens, lang_masks = self.prepare_language(batch)
388
+
389
+ actions = self.model.sample_actions(
390
+ images, img_masks, lang_tokens, lang_masks, state, noise=noise
391
+ )
392
+
393
+ # Unpad actions
394
+ original_action_dim = self.config.action_feature.shape[0]
395
+ actions = actions[:, :, :original_action_dim]
396
+
397
+ actions = self.unnormalize_outputs({"action": actions})["action"]
398
+
399
+ if self.config.adapt_to_pi_aloha:
400
+ actions = self._pi_aloha_encode_actions(actions)
401
+
402
+ # `self.model.forward` returns a (batch_size, n_action_steps, action_dim) tensor, but the queue
403
+ # effectively has shape (n_action_steps, batch_size, *), hence the transpose.
404
+ self._action_queue.extend(actions.transpose(0, 1))
405
+ return self._action_queue.popleft()
406
+
407
+ def forward(self, batch: dict[str, Tensor], noise=None, time=None) -> tuple[Tensor, dict[str, Tensor]]:
408
+ """Do a full training forward pass to compute the loss"""
409
+ if self.config.adapt_to_pi_aloha:
410
+ batch[OBS_STATE] = self._pi_aloha_decode_state(batch[OBS_STATE])
411
+ batch[ACTION] = self._pi_aloha_encode_actions_inv(batch[ACTION])
412
+
413
+ batch = self.normalize_inputs(batch)
414
+ batch = self.normalize_targets(batch)
415
+
416
+ images, img_masks = self.prepare_images(batch)
417
+ state = self.prepare_state(batch)
418
+ lang_tokens, lang_masks = self.prepare_language(batch)
419
+ actions = self.prepare_action(batch)
420
+ actions_is_pad = batch.get("action_is_pad")
421
+
422
+ loss_dict = {}
423
+ losses = self.model.forward(images, img_masks, lang_tokens, lang_masks, state, actions, noise, time)
424
+ loss_dict["losses_after_forward"] = losses.clone()
425
+
426
+ if actions_is_pad is not None:
427
+ in_episode_bound = ~actions_is_pad
428
+ losses = losses * in_episode_bound.unsqueeze(-1)
429
+ loss_dict["losses_after_in_ep_bound"] = losses.clone()
430
+
431
+ # Remove padding
432
+ losses = losses[:, :, : self.config.max_action_dim]
433
+ loss_dict["losses_after_rm_padding"] = losses.clone()
434
+
435
+ # For backward pass
436
+ loss = losses.mean()
437
+ # For logging
438
+ loss_dict["l2_loss"] = loss.item()
439
+
440
+ return loss, loss_dict
441
+
442
+ def prepare_images(self, batch):
443
+ """Apply Pi0 preprocessing to the images, like resizing to 224x224 and padding to keep aspect ratio, and
444
+ convert pixel range from [0.0, 1.0] to [-1.0, 1.0] as requested by SigLIP.
445
+ """
446
+ images = []
447
+ img_masks = []
448
+
449
+ present_img_keys = [key for key in self.config.image_features if key in batch]
450
+ missing_img_keys = [key for key in self.config.image_features if key not in batch]
451
+
452
+ if len(present_img_keys) == 0:
453
+ raise ValueError(
454
+ f"All image features are missing from the batch. At least one expected. (batch: {batch.keys()}) (image_features:{self.config.image_features})"
455
+ )
456
+
457
+ # Preprocess image features present in the batch
458
+ for key in present_img_keys:
459
+ img = batch[key]
460
+
461
+ if self.config.resize_imgs_with_padding is not None:
462
+ img = resize_with_pad(img, *self.config.resize_imgs_with_padding, pad_value=0)
463
+
464
+ # Normalize from range [0,1] to [-1,1] as expected by siglip
465
+ img = img * 2.0 - 1.0
466
+
467
+ bsize = img.shape[0]
468
+ device = img.device
469
+ mask = torch.ones(bsize, dtype=torch.bool, device=device)
470
+ images.append(img)
471
+ img_masks.append(mask)
472
+
473
+ # Create image features not present in the batch
474
+ # as fully 0 padded images.
475
+ for num_empty_cameras in range(len(missing_img_keys)):
476
+ if num_empty_cameras >= self.config.empty_cameras:
477
+ break
478
+ img = torch.ones_like(img) * -1
479
+ mask = torch.zeros_like(mask)
480
+ images.append(img)
481
+ img_masks.append(mask)
482
+
483
+ return images, img_masks
484
+
485
+ def prepare_language(self, batch) -> tuple[Tensor, Tensor]:
486
+ """Tokenize the text input"""
487
+ device = batch[OBS_STATE].device
488
+ tasks = batch["task"]
489
+
490
+ # PaliGemma prompt has to end with a new line
491
+ tasks = [task if task.endswith("\n") else f"{task}\n" for task in tasks]
492
+
493
+ tokenized_prompt = self.language_tokenizer.__call__(
494
+ tasks,
495
+ padding="max_length",
496
+ padding_side="right",
497
+ max_length=self.config.tokenizer_max_length,
498
+ return_tensors="pt",
499
+ )
500
+ lang_tokens = tokenized_prompt["input_ids"].to(device=device)
501
+ lang_masks = tokenized_prompt["attention_mask"].to(device=device, dtype=torch.bool)
502
+
503
+ return lang_tokens, lang_masks
504
+
505
+ def _pi_aloha_decode_state(self, state):
506
+ # Flip the joints.
507
+ for motor_idx in [1, 2, 8, 9]:
508
+ state[:, motor_idx] *= -1
509
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
510
+ for motor_idx in [6, 13]:
511
+ state[:, motor_idx] = aloha_gripper_to_angular(state[:, motor_idx])
512
+ return state
513
+
514
+ def _pi_aloha_encode_actions(self, actions):
515
+ # Flip the joints.
516
+ for motor_idx in [1, 2, 8, 9]:
517
+ actions[:, :, motor_idx] *= -1
518
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
519
+ for motor_idx in [6, 13]:
520
+ actions[:, :, motor_idx] = aloha_gripper_from_angular(actions[:, :, motor_idx])
521
+ return actions
522
+
523
+ def _pi_aloha_encode_actions_inv(self, actions):
524
+ # Flip the joints again.
525
+ for motor_idx in [1, 2, 8, 9]:
526
+ actions[:, :, motor_idx] *= -1
527
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
528
+ for motor_idx in [6, 13]:
529
+ actions[:, :, motor_idx] = aloha_gripper_from_angular_inv(actions[:, :, motor_idx])
530
+ return actions
531
+
532
+ def prepare_state(self, batch):
533
+ """Pad state"""
534
+ state = pad_vector(batch[OBS_STATE], self.config.max_state_dim)
535
+ return state
536
+
537
+ def prepare_action(self, batch):
538
+ """Pad action"""
539
+ actions = pad_vector(batch[ACTION], self.config.max_action_dim)
540
+ return actions
541
+
542
+
543
+ class PI0FlowMatching(nn.Module):
544
+ """
545
+ π0: A Vision-Language-Action Flow Model for General Robot Control
546
+
547
+ [Paper](https://www.physicalintelligence.company/download/pi0.pdf)
548
+ [Jax code](https://github.com/Physical-Intelligence/openpi)
549
+
550
+ Designed by Physical Intelligence. Ported from Jax by Hugging Face.
551
+ ┌──────────────────────────────┐
552
+ │ actions │
553
+ │ ▲ │
554
+ │ ┌┴─────┐ │
555
+ │ kv cache │Gemma │ │
556
+ │ ┌──────────►│Expert│ │
557
+ │ │ │ │ │
558
+ │ ┌┴────────┐ │x 10 │ │
559
+ │ │ │ └▲──▲──┘ │
560
+ │ │PaliGemma│ │ │ │
561
+ │ │ │ │ robot state │
562
+ │ │ │ noise │
563
+ │ └▲──▲─────┘ │
564
+ │ │ │ │
565
+ │ │ image(s) │
566
+ │ language tokens │
567
+ └──────────────────────────────┘
568
+ """
569
+
570
+ def __init__(self, config):
571
+ super().__init__()
572
+ self.config = config
573
+
574
+ paligemma_with_export_config = PaliGemmaWithExpertConfig(
575
+ freeze_vision_encoder=self.config.freeze_vision_encoder,
576
+ train_expert_only=self.config.train_expert_only,
577
+ attention_implementation=self.config.attention_implementation,
578
+ )
579
+ self.paligemma_with_expert = PaliGemmaWithExpertModel(paligemma_with_export_config)
580
+
581
+ # Projections are float32
582
+ self.state_proj = nn.Linear(self.config.max_state_dim, self.config.proj_width)
583
+ self.action_in_proj = nn.Linear(self.config.max_action_dim, self.config.proj_width)
584
+ self.action_out_proj = nn.Linear(self.config.proj_width, self.config.max_action_dim)
585
+
586
+ self.action_time_mlp_in = nn.Linear(self.config.proj_width * 2, self.config.proj_width)
587
+ self.action_time_mlp_out = nn.Linear(self.config.proj_width, self.config.proj_width)
588
+
589
+ self.set_requires_grad()
590
+
591
+ def set_requires_grad(self):
592
+ for params in self.state_proj.parameters():
593
+ params.requires_grad = self.config.train_state_proj
594
+
595
+ def sample_noise(self, shape, device):
596
+ noise = torch.normal(
597
+ mean=0.0,
598
+ std=1.0,
599
+ size=shape,
600
+ dtype=torch.float32,
601
+ device=device,
602
+ )
603
+ return noise
604
+
605
+ def sample_time(self, bsize, device):
606
+ beta_dist = torch.distributions.Beta(concentration1=1.5, concentration0=1.0)
607
+ time_beta = beta_dist.sample((bsize,)).to(device=device, dtype=torch.float32)
608
+ time = time_beta * 0.999 + 0.001
609
+ return time
610
+
611
+ def embed_prefix(
612
+ self, images, img_masks, lang_tokens, lang_masks
613
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
614
+ """Embed images with SigLIP and language tokens with embedding layer to prepare
615
+ for PaliGemma transformer processing.
616
+ """
617
+ # TODO: avoid list in python and torch.cat ; prefer pre-allocation with torch.empty
618
+ embs = []
619
+ pad_masks = []
620
+ att_masks = []
621
+
622
+ # TODO: remove for loop
623
+ for (
624
+ img,
625
+ img_mask,
626
+ ) in zip(images, img_masks, strict=False):
627
+ img_emb = self.paligemma_with_expert.embed_image(img)
628
+ img_emb = img_emb.to(dtype=torch.bfloat16)
629
+
630
+ # Normalize image embeddings
631
+ img_emb_dim = img_emb.shape[-1]
632
+ img_emb = img_emb * torch.tensor(img_emb_dim**0.5, dtype=img_emb.dtype, device=img_emb.device)
633
+
634
+ bsize, num_img_embs = img_emb.shape[:2]
635
+ img_mask = img_mask[:, None].expand(bsize, num_img_embs)
636
+
637
+ embs.append(img_emb)
638
+ pad_masks.append(img_mask)
639
+
640
+ # Create attention masks so that image tokens attend to each other
641
+ att_masks += [0] * num_img_embs
642
+
643
+ lang_emb = self.paligemma_with_expert.embed_language_tokens(lang_tokens)
644
+
645
+ # Normalize language embeddings
646
+ lang_emb_dim = lang_emb.shape[-1]
647
+ lang_emb = lang_emb * math.sqrt(lang_emb_dim)
648
+
649
+ embs.append(lang_emb)
650
+ pad_masks.append(lang_masks)
651
+
652
+ # full attention between image and language inputs
653
+ num_lang_embs = lang_emb.shape[1]
654
+ att_masks += [0] * num_lang_embs
655
+
656
+ embs = torch.cat(embs, dim=1)
657
+ pad_masks = torch.cat(pad_masks, dim=1)
658
+ att_masks = torch.tensor(att_masks, dtype=torch.bool, device=pad_masks.device)
659
+ att_masks = att_masks[None, :].expand(bsize, len(att_masks))
660
+
661
+ return embs, pad_masks, att_masks
662
+
663
+ def embed_suffix(self, state, noisy_actions, timestep):
664
+ """Embed state, noisy_actions, timestep to prepare for Expert Gemma processing."""
665
+ embs = []
666
+ pad_masks = []
667
+ att_masks = []
668
+
669
+ # Embed state
670
+ state_emb = self.state_proj(state)
671
+ state_emb = state_emb.to(dtype=torch.bfloat16)
672
+ embs.append(state_emb[:, None, :])
673
+ bsize = state_emb.shape[0]
674
+ dtype = state_emb.dtype
675
+ device = state_emb.device
676
+
677
+ state_mask = torch.ones(bsize, 1, dtype=torch.bool, device=device)
678
+ pad_masks.append(state_mask)
679
+
680
+ # Set attention masks so that image and language inputs do not attend to state or actions
681
+ att_masks += [1]
682
+
683
+ # Embed timestep using sine-cosine positional encoding with sensitivity in the range [0, 1]
684
+ time_emb = create_sinusoidal_pos_embedding(
685
+ timestep, self.config.proj_width, min_period=4e-3, max_period=4.0, device=device
686
+ )
687
+ time_emb = time_emb.type(dtype=dtype)
688
+
689
+ # Fuse timestep + action information using an MLP
690
+ action_emb = self.action_in_proj(noisy_actions)
691
+
692
+ time_emb = time_emb[:, None, :].expand_as(action_emb)
693
+ action_time_emb = torch.cat([action_emb, time_emb], dim=2)
694
+
695
+ action_time_emb = self.action_time_mlp_in(action_time_emb)
696
+ action_time_emb = F.silu(action_time_emb) # swish == silu
697
+ action_time_emb = self.action_time_mlp_out(action_time_emb)
698
+
699
+ # Add to input tokens
700
+ embs.append(action_time_emb)
701
+
702
+ bsize, action_time_dim = action_time_emb.shape[:2]
703
+ action_time_mask = torch.ones(bsize, action_time_dim, dtype=torch.bool, device=device)
704
+ pad_masks.append(action_time_mask)
705
+
706
+ # Set attention masks so that image, language and state inputs do not attend to action tokens
707
+ att_masks += [1] + ([0] * (self.config.n_action_steps - 1))
708
+
709
+ embs = torch.cat(embs, dim=1)
710
+ pad_masks = torch.cat(pad_masks, dim=1)
711
+ att_masks = torch.tensor(att_masks, dtype=embs.dtype, device=embs.device)
712
+ att_masks = att_masks[None, :].expand(bsize, len(att_masks))
713
+
714
+ return embs, pad_masks, att_masks
715
+
716
+ def forward(
717
+ self, images, img_masks, lang_tokens, lang_masks, state, actions, noise=None, time=None
718
+ ) -> Tensor:
719
+ """Do a full training forward pass and compute the loss (batch_size x num_steps x num_motors)"""
720
+ if noise is None:
721
+ noise = self.sample_noise(actions.shape, actions.device)
722
+
723
+ if time is None:
724
+ time = self.sample_time(actions.shape[0], actions.device)
725
+
726
+ time_expanded = time[:, None, None]
727
+ x_t = time_expanded * noise + (1 - time_expanded) * actions
728
+ u_t = noise - actions
729
+
730
+ prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(
731
+ images, img_masks, lang_tokens, lang_masks
732
+ )
733
+ suffix_embs, suffix_pad_masks, suffix_att_masks = self.embed_suffix(state, x_t, time)
734
+
735
+ pad_masks = torch.cat([prefix_pad_masks, suffix_pad_masks], dim=1)
736
+ att_masks = torch.cat([prefix_att_masks, suffix_att_masks], dim=1)
737
+
738
+ att_2d_masks = make_att_2d_masks(pad_masks, att_masks)
739
+ position_ids = torch.cumsum(pad_masks, dim=1) - 1
740
+
741
+ (_, suffix_out), _ = self.paligemma_with_expert.forward(
742
+ attention_mask=att_2d_masks,
743
+ position_ids=position_ids,
744
+ past_key_values=None,
745
+ inputs_embeds=[prefix_embs, suffix_embs],
746
+ use_cache=False,
747
+ fill_kv_cache=False,
748
+ )
749
+ suffix_out = suffix_out[:, -self.config.n_action_steps :]
750
+ # Original openpi code, upcast attention output
751
+ suffix_out = suffix_out.to(dtype=torch.float32)
752
+ v_t = self.action_out_proj(suffix_out)
753
+
754
+ losses = F.mse_loss(u_t, v_t, reduction="none")
755
+ return losses
756
+
757
+ def sample_actions(self, images, img_masks, lang_tokens, lang_masks, state, noise=None) -> Tensor:
758
+ """Do a full inference forward and compute the action (batch_size x num_steps x num_motors)"""
759
+ bsize = state.shape[0]
760
+ device = state.device
761
+
762
+ if noise is None:
763
+ actions_shape = (bsize, self.config.n_action_steps, self.config.max_action_dim)
764
+ noise = self.sample_noise(actions_shape, device)
765
+
766
+ prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(
767
+ images, img_masks, lang_tokens, lang_masks
768
+ )
769
+ prefix_att_2d_masks = make_att_2d_masks(prefix_pad_masks, prefix_att_masks)
770
+ prefix_position_ids = torch.cumsum(prefix_pad_masks, dim=1) - 1
771
+
772
+ # Compute image and language key value cache
773
+ _, past_key_values = self.paligemma_with_expert.forward(
774
+ attention_mask=prefix_att_2d_masks,
775
+ position_ids=prefix_position_ids,
776
+ past_key_values=None,
777
+ inputs_embeds=[prefix_embs, None],
778
+ use_cache=self.config.use_cache,
779
+ fill_kv_cache=True,
780
+ )
781
+
782
+ dt = -1.0 / self.config.num_steps
783
+ dt = torch.tensor(dt, dtype=torch.float32, device=device)
784
+
785
+ x_t = noise
786
+ time = torch.tensor(1.0, dtype=torch.float32, device=device)
787
+ while time >= -dt / 2:
788
+ expanded_time = time.expand(bsize)
789
+ v_t = self.denoise_step(
790
+ state,
791
+ prefix_pad_masks,
792
+ past_key_values,
793
+ x_t,
794
+ expanded_time,
795
+ )
796
+
797
+ # Euler step
798
+ x_t += dt * v_t
799
+ time += dt
800
+ return x_t
801
+
802
+ def denoise_step(
803
+ self,
804
+ state,
805
+ prefix_pad_masks,
806
+ past_key_values,
807
+ x_t,
808
+ timestep,
809
+ ):
810
+ """Apply one denoising step of the noise `x_t` at a given timestep."""
811
+ suffix_embs, suffix_pad_masks, suffix_att_masks = self.embed_suffix(state, x_t, timestep)
812
+
813
+ suffix_len = suffix_pad_masks.shape[1]
814
+ batch_size = prefix_pad_masks.shape[0]
815
+ prefix_len = prefix_pad_masks.shape[1]
816
+ prefix_pad_2d_masks = prefix_pad_masks[:, None, :].expand(batch_size, suffix_len, prefix_len)
817
+
818
+ suffix_att_2d_masks = make_att_2d_masks(suffix_pad_masks, suffix_att_masks)
819
+
820
+ full_att_2d_masks = torch.cat([prefix_pad_2d_masks, suffix_att_2d_masks], dim=2)
821
+
822
+ prefix_offsets = torch.sum(prefix_pad_masks, dim=-1)[:, None]
823
+ position_ids = prefix_offsets + torch.cumsum(suffix_pad_masks, dim=1) - 1
824
+
825
+ outputs_embeds, _ = self.paligemma_with_expert.forward(
826
+ attention_mask=full_att_2d_masks,
827
+ position_ids=position_ids,
828
+ past_key_values=past_key_values,
829
+ inputs_embeds=[None, suffix_embs],
830
+ use_cache=self.config.use_cache,
831
+ fill_kv_cache=False,
832
+ )
833
+ suffix_out = outputs_embeds[1]
834
+ suffix_out = suffix_out[:, -self.config.n_action_steps :]
835
+ suffix_out = suffix_out.to(dtype=torch.float32)
836
+ v_t = self.action_out_proj(suffix_out)
837
+ return v_t
tools/lerobot_v21_runtime/src/lerobot/policies/pi0/paligemma_with_expert.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ import torch
17
+ import torch.version
18
+ from pytest import Cache
19
+ from torch import nn
20
+ from transformers import (
21
+ AutoConfig,
22
+ GemmaForCausalLM,
23
+ PaliGemmaForConditionalGeneration,
24
+ PretrainedConfig,
25
+ PreTrainedModel,
26
+ )
27
+ from transformers.models.auto import CONFIG_MAPPING
28
+
29
+ from lerobot.policies.pi0.flex_attention import flex_attention_forward
30
+
31
+
32
+ def apply_rope(x, positions, max_wavelength=10_000):
33
+ """
34
+ Applies RoPE positions [B, L] to x [B, L, H, D].
35
+ """
36
+ d_half = x.shape[-1] // 2
37
+ device = x.device
38
+ dtype = x.dtype
39
+ x = x.to(torch.float32)
40
+
41
+ freq_exponents = (2.0 / x.shape[-1]) * torch.arange(d_half, dtype=torch.float32, device=device)
42
+ timescale = max_wavelength**freq_exponents
43
+ radians = positions[..., None].to(torch.float32) / timescale[None, None, :].to(torch.float32)
44
+
45
+ radians = radians[..., None, :]
46
+
47
+ sin = torch.sin(radians) # .to(dtype=dtype)
48
+ cos = torch.cos(radians) # .to(dtype=dtype)
49
+
50
+ x1, x2 = x.split(d_half, dim=-1)
51
+ res = torch.empty_like(x)
52
+ res[..., :d_half] = x1 * cos - x2 * sin
53
+ res[..., d_half:] = x2 * cos + x1 * sin
54
+
55
+ return res.to(dtype)
56
+
57
+
58
+ class PaliGemmaWithExpertConfig(PretrainedConfig):
59
+ model_type = "PaliGemmaWithExpertModel"
60
+ sub_configs = {"paligemma_config": AutoConfig, "gemma_expert_config": AutoConfig}
61
+
62
+ def __init__(
63
+ self,
64
+ paligemma_config: dict | None = None,
65
+ gemma_expert_config: dict | None = None,
66
+ freeze_vision_encoder: bool = True,
67
+ train_expert_only: bool = True,
68
+ attention_implementation: str = "eager",
69
+ **kwargs,
70
+ ):
71
+ self.freeze_vision_encoder = freeze_vision_encoder
72
+ self.train_expert_only = train_expert_only
73
+ self.attention_implementation = attention_implementation
74
+
75
+ if paligemma_config is None:
76
+ # Default config from Pi0
77
+ self.paligemma_config = CONFIG_MAPPING["paligemma"](
78
+ transformers_version="4.48.1",
79
+ _vocab_size=257152,
80
+ bos_token_id=2,
81
+ eos_token_id=1,
82
+ hidden_size=2048,
83
+ image_token_index=257152,
84
+ model_type="paligemma",
85
+ pad_token_id=0,
86
+ projection_dim=2048,
87
+ text_config={
88
+ "hidden_activation": "gelu_pytorch_tanh",
89
+ "hidden_size": 2048,
90
+ "intermediate_size": 16384,
91
+ "model_type": "gemma",
92
+ "num_attention_heads": 8,
93
+ "num_hidden_layers": 18,
94
+ "num_image_tokens": 256,
95
+ "num_key_value_heads": 1,
96
+ "torch_dtype": "float32",
97
+ "vocab_size": 257152,
98
+ },
99
+ vision_config={
100
+ "hidden_size": 1152,
101
+ "intermediate_size": 4304,
102
+ "model_type": "siglip_vision_model",
103
+ "num_attention_heads": 16,
104
+ "num_hidden_layers": 27,
105
+ "num_image_tokens": 256,
106
+ "patch_size": 14,
107
+ "projection_dim": 2048,
108
+ "projector_hidden_act": "gelu_fast",
109
+ "torch_dtype": "float32",
110
+ "vision_use_head": False,
111
+ },
112
+ )
113
+ elif isinstance(self.paligemma_config, dict):
114
+ # Override Pi0 default config for PaliGemma
115
+ if "model_type" not in gemma_expert_config:
116
+ paligemma_config["model_type"] = "paligemma"
117
+
118
+ cfg_cls = CONFIG_MAPPING[paligemma_config["model_type"]]
119
+ self.paligemma_config = cfg_cls(**paligemma_config)
120
+
121
+ if gemma_expert_config is None:
122
+ # Default config from Pi0
123
+ self.gemma_expert_config = CONFIG_MAPPING["gemma"](
124
+ attention_bias=False,
125
+ attention_dropout=0.0,
126
+ bos_token_id=2,
127
+ eos_token_id=1,
128
+ head_dim=256,
129
+ hidden_act="gelu_pytorch_tanh",
130
+ hidden_activation="gelu_pytorch_tanh",
131
+ hidden_size=1024,
132
+ initializer_range=0.02,
133
+ intermediate_size=4096,
134
+ max_position_embeddings=8192,
135
+ model_type="gemma",
136
+ num_attention_heads=8,
137
+ num_hidden_layers=18,
138
+ num_key_value_heads=1,
139
+ pad_token_id=0,
140
+ rms_norm_eps=1e-06,
141
+ rope_theta=10000.0,
142
+ torch_dtype="float32",
143
+ transformers_version="4.48.1",
144
+ use_cache=True,
145
+ vocab_size=257152,
146
+ )
147
+ elif isinstance(self.gemma_expert_config, dict):
148
+ # Override Pi0 default config for Gemma Expert
149
+ if "model_type" not in gemma_expert_config:
150
+ gemma_expert_config["model_type"] = "gemma"
151
+
152
+ cfg_cls = CONFIG_MAPPING[paligemma_config["model_type"]]
153
+ self.gemma_expert_config = cfg_cls(**gemma_expert_config)
154
+
155
+ super().__init__(**kwargs)
156
+
157
+ def __post_init__(self):
158
+ super().__post_init__()
159
+ if self.train_expert_only and not self.freeze_vision_encoder:
160
+ raise ValueError(
161
+ "You set `freeze_vision_encoder=False` and `train_expert_only=True` which are not compatible."
162
+ )
163
+
164
+ if self.attention_implementation not in ["eager", "fa2", "flex"]:
165
+ raise ValueError(
166
+ f"Wrong value provided for `attention_implementation` ({self.attention_implementation}). Expected 'eager', 'fa2' or 'flex'."
167
+ )
168
+
169
+
170
+ class PaliGemmaWithExpertModel(PreTrainedModel):
171
+ config_class = PaliGemmaWithExpertConfig
172
+
173
+ def __init__(self, config: PaliGemmaWithExpertConfig):
174
+ super().__init__(config=config)
175
+ self.config = config
176
+ self.paligemma = PaliGemmaForConditionalGeneration(config=config.paligemma_config)
177
+ self.gemma_expert = GemmaForCausalLM(config=config.gemma_expert_config)
178
+ # Remove unused embed_tokens
179
+ self.gemma_expert.model.embed_tokens = None
180
+
181
+ self.to_bfloat16_like_physical_intelligence()
182
+ self.set_requires_grad()
183
+
184
+ def set_requires_grad(self):
185
+ if self.config.freeze_vision_encoder:
186
+ self.paligemma.vision_tower.eval()
187
+ for params in self.paligemma.vision_tower.parameters():
188
+ params.requires_grad = False
189
+
190
+ if self.config.train_expert_only:
191
+ self.paligemma.eval()
192
+ for params in self.paligemma.parameters():
193
+ params.requires_grad = False
194
+
195
+ def train(self, mode: bool = True):
196
+ super().train(mode)
197
+
198
+ if self.config.freeze_vision_encoder:
199
+ self.paligemma.vision_tower.eval()
200
+
201
+ if self.config.train_expert_only:
202
+ self.paligemma.eval()
203
+
204
+ def to_bfloat16_like_physical_intelligence(self):
205
+ self.paligemma = self.paligemma.to(dtype=torch.bfloat16)
206
+
207
+ params_to_change_dtype = [
208
+ "language_model.model.layers",
209
+ "gemma_expert.model.layers",
210
+ "vision_tower",
211
+ "multi_modal",
212
+ ]
213
+ for name, param in self.named_parameters():
214
+ if any(selector in name for selector in params_to_change_dtype):
215
+ param.data = param.data.to(dtype=torch.bfloat16)
216
+
217
+ def embed_image(self, image: torch.Tensor):
218
+ # Handle different transformers versions
219
+ if hasattr(self.paligemma, "get_image_features"):
220
+ return self.paligemma.get_image_features(image)
221
+ else:
222
+ return self.paligemma.model.get_image_features(image)
223
+
224
+ def embed_language_tokens(self, tokens: torch.Tensor):
225
+ return self.paligemma.language_model.embed_tokens(tokens)
226
+
227
+ # TODO: break down this huge forward into modules or functions
228
+ def forward(
229
+ self,
230
+ attention_mask: torch.Tensor | None = None,
231
+ position_ids: torch.LongTensor | None = None,
232
+ past_key_values: list[torch.FloatTensor] | Cache | None = None,
233
+ inputs_embeds: list[torch.FloatTensor] = None,
234
+ use_cache: bool | None = None,
235
+ fill_kv_cache: bool | None = None,
236
+ ):
237
+ models = [self.paligemma.language_model, self.gemma_expert.model]
238
+
239
+ for hidden_states in inputs_embeds:
240
+ # TODO this is very inefficient
241
+ # dtype is always the same, batch size too (if > 1 len)
242
+ # device could be trickier in multi gpu edge cases but that's it
243
+ if hidden_states is None:
244
+ continue
245
+ batch_size = hidden_states.shape[0]
246
+
247
+ # RMSNorm
248
+ num_layers = self.paligemma.config.text_config.num_hidden_layers
249
+ head_dim = self.paligemma.config.text_config.head_dim
250
+ for layer_idx in range(num_layers):
251
+ query_states = []
252
+ key_states = []
253
+ value_states = []
254
+ for i, hidden_states in enumerate(inputs_embeds):
255
+ if hidden_states is None:
256
+ continue
257
+ layer = models[i].layers[layer_idx]
258
+ # normalizer = torch.tensor(models[i].config.hidden_size**0.5, dtype=hidden_states.dtype)
259
+ # hidden_states = hidden_states * normalizer
260
+ hidden_states = layer.input_layernorm(hidden_states)
261
+
262
+ input_shape = hidden_states.shape[:-1]
263
+ hidden_shape = (*input_shape, -1, layer.self_attn.head_dim)
264
+
265
+ hidden_states = hidden_states.to(dtype=torch.bfloat16)
266
+ query_state = layer.self_attn.q_proj(hidden_states).view(hidden_shape)
267
+ key_state = layer.self_attn.k_proj(hidden_states).view(hidden_shape)
268
+ value_state = layer.self_attn.v_proj(hidden_states).view(hidden_shape)
269
+
270
+ query_states.append(query_state)
271
+ key_states.append(key_state)
272
+ value_states.append(value_state)
273
+
274
+ # B,L,H,D with L sequence length, H number of heads, D head dim
275
+ # concatenate on the number of embeddings/tokens
276
+ query_states = torch.cat(query_states, dim=1)
277
+ key_states = torch.cat(key_states, dim=1)
278
+ value_states = torch.cat(value_states, dim=1)
279
+
280
+ query_states = apply_rope(query_states, position_ids)
281
+ key_states = apply_rope(key_states, position_ids)
282
+
283
+ if use_cache and past_key_values is None:
284
+ past_key_values = {}
285
+
286
+ if use_cache:
287
+ if fill_kv_cache:
288
+ past_key_values[layer_idx] = {
289
+ "key_states": key_states,
290
+ "value_states": value_states,
291
+ }
292
+ else:
293
+ # TODO here, some optimization can be done - similar to a `StaticCache` we can declare the `max_len` before.
294
+ # so we create an empty cache, with just one cuda malloc, and if (in autoregressive case) we reach
295
+ # the max len, then we (for instance) double the cache size. This implementation already exists
296
+ # in `transformers`. (molbap)
297
+ key_states = torch.cat([past_key_values[layer_idx]["key_states"], key_states], dim=1)
298
+ value_states = torch.cat(
299
+ [past_key_values[layer_idx]["value_states"], value_states], dim=1
300
+ )
301
+
302
+ attention_interface = self.get_attention_interface()
303
+ att_output = attention_interface(
304
+ attention_mask, batch_size, head_dim, query_states, key_states, value_states
305
+ )
306
+ att_output = att_output.to(dtype=torch.bfloat16)
307
+
308
+ # first part of att_output is prefix (up to sequence length, [:, 0:prefix_seq_len])
309
+ outputs_embeds = []
310
+ start = 0
311
+ for i, hidden_states in enumerate(inputs_embeds):
312
+ layer = models[i].layers[layer_idx]
313
+
314
+ if hidden_states is not None:
315
+ end = start + hidden_states.shape[1]
316
+
317
+ if att_output.dtype != layer.self_attn.o_proj.weight.dtype:
318
+ att_output = att_output.to(layer.self_attn.o_proj.weight.dtype)
319
+ out_emb = layer.self_attn.o_proj(att_output[:, start:end])
320
+
321
+ # TODO: first dropout (by default 0.0)
322
+
323
+ # first residual
324
+ out_emb += hidden_states
325
+ after_first_residual = out_emb.clone()
326
+
327
+ out_emb = layer.post_attention_layernorm(out_emb)
328
+ out_emb = layer.mlp(out_emb)
329
+
330
+ # TODO: second dropout (by default 0.0)
331
+
332
+ # second residual
333
+ out_emb += after_first_residual
334
+
335
+ outputs_embeds.append(out_emb)
336
+
337
+ start = end
338
+ else:
339
+ outputs_embeds.append(None)
340
+
341
+ inputs_embeds = outputs_embeds
342
+
343
+ # final norm
344
+ outputs_embeds = []
345
+ for i, hidden_states in enumerate(inputs_embeds):
346
+ if hidden_states is not None:
347
+ out_emb = models[i].norm(hidden_states)
348
+ outputs_embeds.append(out_emb)
349
+ else:
350
+ outputs_embeds.append(None)
351
+
352
+ return outputs_embeds, past_key_values
353
+
354
+ def get_attention_interface(self):
355
+ if self.config.attention_implementation == "fa2":
356
+ attention_interface = self.flash_attention_forward
357
+ elif self.config.attention_implementation == "flex":
358
+ attention_interface = flex_attention_forward
359
+ else:
360
+ attention_interface = self.eager_attention_forward
361
+ return attention_interface
362
+
363
+ def flash_attention_forward(
364
+ self, attention_mask, batch_size, head_dim, query_states, key_states, value_states
365
+ ):
366
+ raise NotImplementedError("FA2 is not implemented (yet)")
367
+
368
+ def eager_attention_forward(
369
+ self, attention_mask, batch_size, head_dim, query_states, key_states, value_states
370
+ ):
371
+ num_att_heads = self.config.paligemma_config.text_config.num_attention_heads
372
+ num_key_value_heads = self.config.paligemma_config.text_config.num_key_value_heads
373
+ num_key_value_groups = num_att_heads // num_key_value_heads
374
+
375
+ # query_states: batch_size, sequence_length, num_att_head, head_dim
376
+ # key_states: batch_size, sequence_length, num_key_value_head, head_dim
377
+ # value_states: batch_size, sequence_length, num_key_value_head, head_dim
378
+ sequence_length = key_states.shape[1]
379
+
380
+ key_states = key_states[:, :, :, None, :].expand(
381
+ batch_size, sequence_length, num_key_value_heads, num_key_value_groups, head_dim
382
+ )
383
+ key_states = key_states.reshape(
384
+ batch_size, sequence_length, num_key_value_heads * num_key_value_groups, head_dim
385
+ )
386
+
387
+ value_states = value_states[:, :, :, None, :].expand(
388
+ batch_size, sequence_length, num_key_value_heads, num_key_value_groups, head_dim
389
+ )
390
+ value_states = value_states.reshape(
391
+ batch_size, sequence_length, num_key_value_heads * num_key_value_groups, head_dim
392
+ )
393
+
394
+ # Attention here is upcasted to float32 to match the original eager implementation.
395
+
396
+ query_states = query_states.to(dtype=torch.float32)
397
+ key_states = key_states.to(dtype=torch.float32)
398
+
399
+ query_states = query_states.transpose(1, 2)
400
+ key_states = key_states.transpose(1, 2)
401
+
402
+ att_weights = torch.matmul(query_states, key_states.transpose(2, 3))
403
+ att_weights *= head_dim**-0.5
404
+ big_neg = -2.3819763e38 # See gemma/modules.py
405
+
406
+ masked_att_weights = torch.where(attention_mask[:, None, :, :], att_weights, big_neg)
407
+
408
+ probs = nn.functional.softmax(masked_att_weights, dim=-1)
409
+ probs = probs.to(dtype=value_states.dtype)
410
+
411
+ # probs: batch_size, num_key_value_head, num_att_head, sequence_length, sequence_length
412
+ # value_states: batch_size, sequence_length, num_att_heads, head_dim
413
+
414
+ att_output = torch.matmul(probs, value_states.permute(0, 2, 1, 3))
415
+
416
+ att_output = att_output.permute(0, 2, 1, 3)
417
+ # we use -1 because sequence length can change
418
+ att_output = att_output.reshape(batch_size, -1, num_key_value_heads * num_key_value_groups * head_dim)
419
+
420
+ return att_output
tools/lerobot_v21_runtime/src/lerobot/policies/pi0fast/configuration_pi0fast.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+
3
+ from lerobot.configs.policies import PreTrainedConfig
4
+ from lerobot.configs.types import FeatureType, NormalizationMode, PolicyFeature
5
+ from lerobot.optim.optimizers import AdamWConfig
6
+ from lerobot.optim.schedulers import (
7
+ CosineDecayWithWarmupSchedulerConfig,
8
+ )
9
+
10
+
11
+ @PreTrainedConfig.register_subclass("pi0fast")
12
+ @dataclass
13
+ class PI0FASTConfig(PreTrainedConfig):
14
+ # Input / output structure.
15
+ n_obs_steps: int = 1
16
+ chunk_size: int = 10
17
+ n_action_steps: int = 5
18
+
19
+ normalization_mapping: dict[str, NormalizationMode] = field(
20
+ default_factory=lambda: {
21
+ "VISUAL": NormalizationMode.IDENTITY,
22
+ "STATE": NormalizationMode.MEAN_STD,
23
+ "ACTION": NormalizationMode.MEAN_STD,
24
+ }
25
+ )
26
+
27
+ # Shorter state and action vectors will be padded
28
+ max_state_dim: int = 32 # 32
29
+ max_action_dim: int = 32 # 32
30
+
31
+ # Image preprocessing
32
+ resize_imgs_with_padding: tuple[int, int] = (224, 224)
33
+ interpolate_like_pi: bool = False
34
+
35
+ # Add empty images. Used by pi0_aloha_sim which adds the empty
36
+ # left and right wrist cameras in addition to the top camera.
37
+ empty_cameras: int = 0
38
+
39
+ # Converts the joint and gripper values from the standard Aloha space to
40
+ # the space used by the pi internal runtime which was used to train the base model.
41
+ adapt_to_pi_aloha: bool = False
42
+
43
+ # Converts joint dimensions to deltas with respect to the current state before passing to the model.
44
+ # Gripper dimensions will remain in absolute values.
45
+ use_delta_joint_actions_aloha: bool = False
46
+
47
+ # Tokenizer
48
+ tokenizer_max_length: int = 48
49
+
50
+ # Projector
51
+ proj_width: int = 1024
52
+
53
+ # Decoding
54
+ max_decoding_steps: int = 256
55
+ fast_skip_tokens: int = 128 # Skip last 128 tokens in PaliGemma vocab since they are special tokens
56
+ max_input_seq_len: int = 256 # 512
57
+
58
+ # Utils
59
+ use_cache: bool = True
60
+
61
+ # Frozen parameters
62
+ freeze_vision_encoder: bool = True
63
+ freeze_lm_head: bool = True
64
+
65
+ # Training presets
66
+ optimizer_lr: float = 1e-4
67
+ optimizer_betas: tuple[float, float] = (0.9, 0.95)
68
+ optimizer_eps: float = 1e-8
69
+ optimizer_weight_decay: float = 1e-5
70
+
71
+ scheduler_warmup_steps: int = 1_000
72
+ scheduler_decay_steps: int = 30_000
73
+ scheduler_decay_lr: float = 2.5e-6
74
+
75
+ checkpoint_path: str = None
76
+
77
+ padding_side: str = "right"
78
+
79
+ precision: str = "bfloat16"
80
+ grad_clip_norm: float = 1
81
+
82
+ # Allows padding/truncation of generated action tokens during detokenization to ensure decoding.
83
+ # In the original version, tensors of 0s were generated if shapes didn't match for stable decoding.
84
+ relaxed_action_decoding: bool = True
85
+
86
+ def __post_init__(self):
87
+ super().__post_init__()
88
+
89
+ """Input validation (not exhaustive)."""
90
+ if self.n_action_steps > self.chunk_size:
91
+ raise ValueError(
92
+ f"The chunk size is the upper bound for the number of action steps per model invocation. Got "
93
+ f"{self.n_action_steps} for `n_action_steps` and {self.chunk_size} for `chunk_size`."
94
+ )
95
+ if self.n_obs_steps != 1:
96
+ raise ValueError(
97
+ f"Multiple observation steps not handled yet. Got `nobs_steps={self.n_obs_steps}`"
98
+ )
99
+
100
+ def validate_features(self) -> None:
101
+ for i in range(self.empty_cameras):
102
+ key = f"observation.images.empty_camera_{i}"
103
+ empty_camera = PolicyFeature(
104
+ type=FeatureType.VISUAL,
105
+ shape=(3, 480, 640),
106
+ )
107
+ self.input_features[key] = empty_camera
108
+
109
+ def get_optimizer_preset(self) -> AdamWConfig:
110
+ return AdamWConfig(
111
+ lr=self.optimizer_lr,
112
+ betas=self.optimizer_betas,
113
+ eps=self.optimizer_eps,
114
+ weight_decay=self.optimizer_weight_decay,
115
+ grad_clip_norm=self.grad_clip_norm,
116
+ )
117
+
118
+ def get_scheduler_preset(self):
119
+ return CosineDecayWithWarmupSchedulerConfig(
120
+ peak_lr=self.optimizer_lr,
121
+ decay_lr=self.scheduler_decay_lr,
122
+ num_warmup_steps=self.scheduler_warmup_steps,
123
+ num_decay_steps=self.scheduler_decay_steps,
124
+ )
125
+
126
+ @property
127
+ def observation_delta_indices(self) -> None:
128
+ return None
129
+
130
+ @property
131
+ def action_delta_indices(self) -> list:
132
+ return list(range(self.chunk_size))
133
+
134
+ @property
135
+ def reward_delta_indices(self) -> None:
136
+ return None
tools/lerobot_v21_runtime/src/lerobot/policies/pi0fast/modeling_pi0fast.py ADDED
@@ -0,0 +1,995 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2025 Physical Intelligence and 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
+ """
18
+ π0+FAST: Efficient Action Tokenization for Vision-Language-Action Models
19
+
20
+ [Paper](https://huggingface.co/papers/2501.09747)
21
+ [Jax code](https://github.com/Physical-Intelligence/openpi)
22
+
23
+ Designed by Physical Intelligence. Ported from Jax by Hugging Face.
24
+ Disclaimer: It is not expected to perform as well as the original implementation.
25
+
26
+ Example of finetuning the pi0+FAST pretrained model (`pi0_fast_base` in `openpi`):
27
+ ```bash
28
+ python -m lerobot.scripts.train \
29
+ --policy.path=lerobot/pi0fast_base \
30
+ --dataset.repo_id=danaaubakirova/koch_test
31
+ ```
32
+
33
+ Example of training the pi0+FAST neural network with from scratch:
34
+ ```bash
35
+ python -m lerobot.scripts.train \
36
+ --policy.type=pi0fast \
37
+ --dataset.repo_id=danaaubakirova/koch_test
38
+ ```
39
+
40
+ Example of using the pi0 pretrained model outside LeRobot training framework:
41
+ ```python
42
+ policy = PI0FASTPolicy.from_pretrained("lerobot/pi0fast_base")
43
+ ```
44
+
45
+ """
46
+
47
+ from collections import deque
48
+ from functools import partial
49
+
50
+ import numpy as np
51
+ import torch
52
+ import torch.nn.functional as F # noqa: N812
53
+ from PIL import Image
54
+ from scipy.fft import idct
55
+ from torch import Tensor, nn
56
+ from transformers import AutoProcessor, AutoTokenizer, PaliGemmaForConditionalGeneration
57
+ from transformers.cache_utils import HybridCache, StaticCache
58
+ from transformers.models.auto import CONFIG_MAPPING
59
+
60
+ from lerobot.constants import ACTION, OBS_STATE
61
+ from lerobot.policies.normalize import Normalize, Unnormalize
62
+ from lerobot.policies.pi0fast.configuration_pi0fast import PI0FASTConfig
63
+ from lerobot.policies.pretrained import PreTrainedPolicy
64
+
65
+ PRECISION = {
66
+ "float16": torch.float16,
67
+ "float32": torch.float32,
68
+ "bfloat16": torch.bfloat16,
69
+ }
70
+
71
+
72
+ def normalize(x, min_val, max_val):
73
+ return (x - min_val) / (max_val - min_val)
74
+
75
+
76
+ def unnormalize(x, min_val, max_val):
77
+ return x * (max_val - min_val) + min_val
78
+
79
+
80
+ def safe_arcsin(value):
81
+ # This ensures that the input stays within
82
+ # [−1,1] to avoid invalid values for arcsin
83
+ return torch.arcsin(torch.clamp(value, -1.0, 1.0))
84
+
85
+
86
+ def aloha_gripper_to_angular(value):
87
+ # Aloha transforms the gripper positions into a linear space. The following code
88
+ # reverses this transformation to be consistent with pi0 which is pretrained in
89
+ # angular space.
90
+ #
91
+ # These values are coming from the Aloha code:
92
+ # PUPPET_GRIPPER_POSITION_OPEN, PUPPET_GRIPPER_POSITION_CLOSED
93
+ value = unnormalize(value, min_val=0.01844, max_val=0.05800)
94
+
95
+ # This is the inverse of the angular to linear transformation inside the Interbotix code.
96
+ def linear_to_radian(linear_position, arm_length, horn_radius):
97
+ value = (horn_radius**2 + linear_position**2 - arm_length**2) / (2 * horn_radius * linear_position)
98
+ return safe_arcsin(value)
99
+
100
+ # The constants are taken from the Interbotix code.
101
+ value = linear_to_radian(value, arm_length=0.036, horn_radius=0.022)
102
+
103
+ # Normalize to [0, 1].
104
+ # The values 0.4 and 1.5 were measured on an actual Trossen robot.
105
+ return normalize(value, min_val=0.4, max_val=1.5)
106
+
107
+
108
+ def aloha_gripper_from_angular(value):
109
+ # Convert from the gripper position used by pi0 to the gripper position that is used by Aloha.
110
+ # Note that the units are still angular but the range is different.
111
+
112
+ # The values 0.4 and 1.5 were measured on an actual Trossen robot.
113
+ value = unnormalize(value, min_val=0.4, max_val=1.5)
114
+
115
+ # These values are coming from the Aloha code:
116
+ # PUPPET_GRIPPER_JOINT_OPEN, PUPPET_GRIPPER_JOINT_CLOSE
117
+ return normalize(value, min_val=-0.6213, max_val=1.4910)
118
+
119
+
120
+ def aloha_gripper_from_angular_inv(value):
121
+ # Directly inverts the gripper_from_angular function.
122
+ value = unnormalize(value, min_val=-0.6213, max_val=1.4910)
123
+ return normalize(value, min_val=0.4, max_val=1.5)
124
+
125
+
126
+ class PI0FASTPolicy(PreTrainedPolicy):
127
+ """Wrapper class around PI0FAST tokenizer and model to train and run inference within LeRobot."""
128
+
129
+ config_class = PI0FASTConfig
130
+ name = "pi0fast"
131
+
132
+ def __init__(
133
+ self,
134
+ config: PI0FASTConfig,
135
+ dataset_stats: dict[str, dict[str, Tensor]] | None = None,
136
+ ):
137
+ """
138
+ Args:
139
+ config: Policy configuration class instance or None, in which case the default instantiation of
140
+ the configuration class is used.
141
+ dataset_stats: Dataset statistics to be used for normalization. If not passed here, it is expected
142
+ that they will be passed with a call to `load_state_dict` before the policy is used.
143
+ """
144
+
145
+ super().__init__(config)
146
+ config.validate_features()
147
+ self.config = config
148
+
149
+ self.normalize_inputs = Normalize(config.input_features, config.normalization_mapping, dataset_stats)
150
+ self.normalize_targets = Normalize(
151
+ config.output_features, config.normalization_mapping, dataset_stats
152
+ )
153
+ self.unnormalize_outputs = Unnormalize(
154
+ config.output_features, config.normalization_mapping, dataset_stats
155
+ )
156
+
157
+ self.language_tokenizer = AutoProcessor.from_pretrained("google/paligemma-3b-pt-224")
158
+ self.model = PI0FAST(config)
159
+
160
+ self.reset()
161
+
162
+ def reset(self):
163
+ """This should be called whenever the environment is reset."""
164
+ self._action_queue = deque([], maxlen=self.config.n_action_steps)
165
+
166
+ @classmethod
167
+ def from_pretrained(cls, *args, **kwargs):
168
+ """Override the from_pretrained method to display important disclaimer."""
169
+ print(
170
+ "⚠️ DISCLAIMER: The PI0FAST model is ported from JAX by the Hugging Face team. \n"
171
+ " It is not expected to perform as well as the original implementation. \n"
172
+ " Original implementation: https://github.com/Physical-Intelligence/openpi"
173
+ )
174
+ return super().from_pretrained(*args, **kwargs)
175
+
176
+ def get_optim_params(self) -> dict:
177
+ return self.parameters()
178
+
179
+ def _pi_aloha_decode_state(self, state):
180
+ # Flip the joints.
181
+ for motor_idx in [1, 2, 8, 9]:
182
+ state[:, motor_idx] *= -1
183
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
184
+ for motor_idx in [6, 13]:
185
+ state[:, motor_idx] = aloha_gripper_to_angular(state[:, motor_idx])
186
+ return state
187
+
188
+ def _pi_aloha_encode_actions(self, actions):
189
+ # Flip the joints.
190
+ for motor_idx in [1, 2, 8, 9]:
191
+ actions[:, :, motor_idx] *= -1
192
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
193
+ for motor_idx in [6, 13]:
194
+ actions[:, :, motor_idx] = aloha_gripper_from_angular(actions[:, :, motor_idx])
195
+ return actions
196
+
197
+ def _pi_aloha_encode_actions_inv(self, actions):
198
+ # Flip the joints again.
199
+ for motor_idx in [1, 2, 8, 9]:
200
+ actions[:, :, motor_idx] *= -1
201
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
202
+ for motor_idx in [6, 13]:
203
+ actions[:, :, motor_idx] = aloha_gripper_from_angular_inv(actions[:, :, motor_idx])
204
+ return actions
205
+
206
+ @torch.no_grad()
207
+ def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor:
208
+ """Predict a chunk of actions given environment observations."""
209
+ raise NotImplementedError("Currently not implemented for PI0FAST")
210
+
211
+ @torch.no_grad()
212
+ def select_action(self, batch: dict[str, Tensor]) -> Tensor:
213
+ """Select a single action given environment observations.
214
+
215
+ This method wraps `select_actions` in order to return one action at a time for execution in the
216
+ environment. It works by managing the actions in a queue and only calling `select_actions` when the
217
+ queue is empty.
218
+ """
219
+ self.eval()
220
+
221
+ if self.config.adapt_to_pi_aloha:
222
+ batch[OBS_STATE] = self._pi_aloha_decode_state(batch[OBS_STATE])
223
+
224
+ batch = self.normalize_inputs(batch)
225
+
226
+ # Action queue logic for n_action_steps > 1. When the action_queue is depleted, populate it by
227
+ # querying the policy.
228
+ if len(self._action_queue) == 0:
229
+ actions = self.model.generate_actions(batch)
230
+
231
+ actions = actions[:, : self.config.n_action_steps]
232
+
233
+ original_action_dim = self.config.action_feature.shape[
234
+ 0
235
+ ] # self.config.max_action_dim # self.config.action_feature.shape[0]
236
+ actions = actions[:, :, :original_action_dim]
237
+
238
+ actions = self.unnormalize_outputs({"action": actions})["action"]
239
+
240
+ if self.config.adapt_to_pi_aloha:
241
+ actions = self._pi_aloha_encode_actions(actions)
242
+
243
+ # `self.model.forward` returns a (batch_size, n_action_steps, action_dim) tensor, but the queue
244
+ # effectively has shape (n_action_steps, batch_size, *), hence the transpose.
245
+ self._action_queue.extend(actions.transpose(0, 1))
246
+ return self._action_queue.popleft()
247
+
248
+ def forward(self, batch: dict[str, Tensor]) -> dict[str, Tensor]:
249
+ if self.config.adapt_to_pi_aloha:
250
+ batch[OBS_STATE] = self._pi_aloha_decode_state(batch[OBS_STATE])
251
+ batch[ACTION] = self._pi_aloha_encode_actions_inv(batch[ACTION])
252
+ batch = self.normalize_inputs(batch)
253
+ batch = self.normalize_targets(batch)
254
+ loss_dict = self.model.forward(batch)
255
+ return loss_dict["loss"], loss_dict
256
+
257
+
258
+ def block_causal_update_causal_mask(
259
+ attention_mask,
260
+ token_type_ids=None,
261
+ past_key_values=None,
262
+ cache_position=None,
263
+ input_tensor=None,
264
+ attn_implementation: str = "eager",
265
+ dtype: torch.dtype = "float32",
266
+ ):
267
+ """
268
+ Update the causal mask during training and generation. It can be customized to different attention masks.
269
+ """
270
+ if attn_implementation == "flash_attention_2":
271
+ if attention_mask is not None and 0.0 in attention_mask:
272
+ return attention_mask
273
+ return None
274
+ using_static_cache = isinstance(past_key_values, StaticCache)
275
+ min_dtype = torch.finfo(dtype).min
276
+
277
+ if input_tensor is None:
278
+ input_tensor = attention_mask
279
+
280
+ inputs_lead_dim, sequence_length = input_tensor.shape[:2]
281
+
282
+ if using_static_cache or isinstance(past_key_values, HybridCache):
283
+ target_length = past_key_values.get_max_cache_shape()
284
+ else:
285
+ target_length = (
286
+ attention_mask.shape[-1]
287
+ if isinstance(attention_mask, torch.Tensor)
288
+ else cache_position[0] + sequence_length + 1
289
+ )
290
+
291
+ # Handle precomputed attention masks
292
+ if attention_mask is not None and attention_mask.dim() == 4:
293
+ return attention_mask
294
+
295
+ # Causal mask initialization
296
+ causal_mask = torch.full(
297
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
298
+ )
299
+
300
+ # Standard causal masking (triu ensures tokens can only attend to past)
301
+ if sequence_length != 1:
302
+ causal_mask = torch.triu(causal_mask, diagonal=1)
303
+
304
+ # Apply block causal mask
305
+ if token_type_ids is not None:
306
+ token_type_ids = token_type_ids.to(causal_mask.device).bool()
307
+ cumsum = torch.cumsum(token_type_ids, dim=1)
308
+ block_causal_mask = cumsum[:, None, :] <= cumsum[:, :, None]
309
+
310
+ # Combine causal_mask with block-wise attention mask
311
+ causal_mask = torch.where(block_causal_mask, 0.0, causal_mask)
312
+ causal_mask = causal_mask[:, None, :, :]
313
+ else:
314
+ # Apply past cache position constraint
315
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
316
+ -1, 1
317
+ )
318
+ causal_mask = causal_mask[None, None, :, :].expand(inputs_lead_dim, 1, -1, -1)
319
+ else:
320
+ # Apply past cache position constraint
321
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
322
+ -1, 1
323
+ )
324
+ causal_mask = causal_mask[None, None, :, :].expand(inputs_lead_dim, 1, -1, -1)
325
+
326
+ if attention_mask is not None:
327
+ causal_mask = causal_mask.clone() # Copy to contiguous memory for in-place edits
328
+ mask_length = attention_mask.shape[-1]
329
+
330
+ # Apply padding mask
331
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
332
+ causal_mask.device
333
+ )
334
+ padding_mask = padding_mask == 0
335
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
336
+ padding_mask, min_dtype
337
+ )
338
+
339
+ return causal_mask
340
+
341
+
342
+ def prepare_inputs_for_generation(
343
+ # self,
344
+ input_ids,
345
+ past_key_values=None,
346
+ inputs_embeds=None,
347
+ cache_position=None,
348
+ position_ids=None,
349
+ pixel_values=None,
350
+ attention_mask=None,
351
+ token_type_ids=None,
352
+ use_cache=True,
353
+ num_logits_to_keep=None,
354
+ labels=None,
355
+ self=None,
356
+ **kwargs,
357
+ ):
358
+ # create block causal attention
359
+ if cache_position[0] > 0 and input_ids.shape[1] > 0:
360
+ input_tensor = input_ids[:, -1:]
361
+ new_positions = (
362
+ torch.ones(
363
+ (position_ids.shape[0], input_ids.shape[1]),
364
+ dtype=position_ids.dtype,
365
+ device=position_ids.device,
366
+ ).cumsum(-1)
367
+ + position_ids[:, -1:]
368
+ )
369
+ position_ids = torch.cat([position_ids, new_positions], dim=-1)
370
+ else:
371
+ input_tensor = inputs_embeds
372
+ attention_mask = block_causal_update_causal_mask(
373
+ attention_mask=attention_mask,
374
+ past_key_values=past_key_values,
375
+ cache_position=cache_position,
376
+ input_tensor=input_tensor,
377
+ token_type_ids=token_type_ids,
378
+ dtype=self.dtype,
379
+ attn_implementation=self.config.text_config._attn_implementation,
380
+ )
381
+ # Overwritten -- custom `position_ids` and `pixel_values` handling
382
+ model_inputs = self.language_model.prepare_inputs_for_generation(
383
+ input_ids,
384
+ past_key_values=past_key_values,
385
+ inputs_embeds=inputs_embeds,
386
+ attention_mask=attention_mask,
387
+ position_ids=position_ids,
388
+ cache_position=cache_position,
389
+ use_cache=use_cache,
390
+ num_logits_to_keep=num_logits_to_keep,
391
+ token_type_ids=token_type_ids,
392
+ **kwargs,
393
+ )
394
+
395
+ # Position_ids in Paligemma are 1-indexed
396
+ if model_inputs.get("position_ids") is not None:
397
+ model_inputs["position_ids"] += 1
398
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
399
+ # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
400
+ if cache_position[0] == 0:
401
+ model_inputs["pixel_values"] = pixel_values
402
+ is_training = token_type_ids is not None and labels is not None
403
+ if cache_position[0] == 0 and isinstance(past_key_values, HybridCache):
404
+ input_tensor = inputs_embeds if inputs_embeds is not None else input_ids
405
+ causal_mask = self._update_causal_mask(
406
+ attention_mask, token_type_ids, past_key_values, cache_position, input_tensor, is_training
407
+ )
408
+ model_inputs["attention_mask"] = causal_mask
409
+
410
+ return model_inputs
411
+
412
+
413
+ class PI0FAST(nn.Module):
414
+ def __init__(self, config: PI0FASTConfig):
415
+ super().__init__()
416
+ self.config = config
417
+
418
+ # TODO: move tokenizers in Policy
419
+ fast_tokenizer_path = "physical-intelligence/fast"
420
+ pi0_paligemma_path = "google/paligemma-3b-pt-224"
421
+ self.paligemma_tokenizer = AutoTokenizer.from_pretrained(pi0_paligemma_path)
422
+ self.processor = AutoProcessor.from_pretrained(pi0_paligemma_path)
423
+ self.fast_tokenizer = AutoProcessor.from_pretrained(fast_tokenizer_path, trust_remote_code=True)
424
+ self.fast_skip_tokens = self.config.fast_skip_tokens
425
+ self.max_input_seq_len = self.config.max_input_seq_len
426
+ self.action_horizon = self.config.chunk_size
427
+ self.action_dim = self.config.action_feature.shape[
428
+ 0
429
+ ] # self.config.max_action_dim # self.config.action_feature.shape[0]
430
+ precision = config.precision
431
+ torch_precision = PRECISION.get(precision, torch.float32)
432
+ self.pad_token_id = (
433
+ self.paligemma_tokenizer.pad_token_id
434
+ if hasattr(self.paligemma_tokenizer, "pad_token_id")
435
+ else self.paligemma_tokenizer.eos_token_id
436
+ )
437
+
438
+ paligemma_config = CONFIG_MAPPING["paligemma"](
439
+ transformers_version="4.48.1",
440
+ _vocab_size=257152,
441
+ bos_token_id=2,
442
+ eos_token_id=1,
443
+ hidden_size=2048,
444
+ image_token_index=257152,
445
+ model_type="paligemma",
446
+ pad_token_id=0,
447
+ projection_dim=2048,
448
+ text_config={
449
+ "hidden_activation": "gelu_pytorch_tanh",
450
+ "hidden_size": 2048,
451
+ "intermediate_size": 16384,
452
+ "model_type": "gemma",
453
+ "num_attention_heads": 8,
454
+ "num_hidden_layers": 18,
455
+ "num_image_tokens": 256,
456
+ "num_key_value_heads": 1,
457
+ "torch_dtype": precision,
458
+ "vocab_size": 257152,
459
+ "_attn_implementation": "eager",
460
+ },
461
+ vision_config={
462
+ "hidden_size": 1152,
463
+ "intermediate_size": 4304,
464
+ "model_type": "siglip_vision_model",
465
+ "num_attention_heads": 16,
466
+ "num_hidden_layers": 27,
467
+ "num_image_tokens": 256,
468
+ "patch_size": 14,
469
+ "projection_dim": 2048,
470
+ "projector_hidden_act": "gelu_pytorch_tanh",
471
+ "torch_dtype": precision,
472
+ "vision_use_head": False,
473
+ },
474
+ )
475
+ self.pi0_paligemma = PaliGemmaForConditionalGeneration(config=paligemma_config)
476
+
477
+ self.pi0_paligemma.prepare_inputs_for_generation = partial(
478
+ prepare_inputs_for_generation, self=self.pi0_paligemma
479
+ )
480
+ # change important stuff in bf16
481
+ params_to_change_dtype = [
482
+ "language_model",
483
+ "vision_tower",
484
+ "multi_modal",
485
+ ]
486
+ for name, param in self.pi0_paligemma.named_parameters():
487
+ if any(selector in name for selector in params_to_change_dtype):
488
+ param.data = param.data.to(dtype=torch_precision)
489
+ self.set_requires_grad()
490
+ self.image_keys = self.config.image_features.keys()
491
+ # TODO: Remove this once we bump transformers to >4.52.0 because the attribute will be removed
492
+ # AttributeError: 'PaliGemmaConfig' object has no attribute 'ignore_index'
493
+ self.ignore_index = self.pi0_paligemma.config.ignore_index
494
+ self.padding_side = self.config.padding_side
495
+
496
+ def set_requires_grad(self):
497
+ if self.config.freeze_vision_encoder:
498
+ self.pi0_paligemma.vision_tower.eval()
499
+ for params in self.pi0_paligemma.vision_tower.parameters():
500
+ params.requires_grad = False
501
+ # To avoid unused params issue with distributed training
502
+ if self.config.freeze_lm_head:
503
+ for name, params in self.pi0_paligemma.named_parameters():
504
+ if "embed_tokens" in name: # lm heads and embedding layer are tied
505
+ params.requires_grad = False
506
+
507
+ def embed_tokens(self, tokens: torch.Tensor):
508
+ return self.pi0_paligemma.language_model.model.embed_tokens(tokens)
509
+
510
+ def prepare_inputs_for_generation(self, *args, **kwargs):
511
+ return self.pi0_paligemma.prepare_inputs_for_generation(*args, **kwargs)
512
+
513
+ def prepare_images(self, batch):
514
+ """Preprocess LeRobot batch into Pi0 inputs"""
515
+ images = []
516
+ img_masks = []
517
+ present_img_keys = [key for key in self.image_keys if key in batch]
518
+ if len(present_img_keys) == 0:
519
+ raise ValueError(
520
+ f"All image features are missing from the batch. At least one expected. (batch: {batch.keys()}) (image_features:{self.config.image_features})"
521
+ )
522
+
523
+ # Preprocess image features present in the batch
524
+ num_empty_cameras = 0
525
+ for key in self.image_keys:
526
+ if key in present_img_keys:
527
+ img = batch[key]
528
+
529
+ if self.config.resize_imgs_with_padding is not None:
530
+ img = resize_with_pad(
531
+ img,
532
+ *self.config.resize_imgs_with_padding,
533
+ pad_value=0,
534
+ interpolate_like_pi=self.config.interpolate_like_pi,
535
+ )
536
+
537
+ # Normalize from range [0,1] to [-1,1] as expected by siglip
538
+ img = img * 2.0 - 1.0
539
+
540
+ bsize = img.shape[0]
541
+ device = img.device
542
+ mask = torch.ones(bsize, dtype=torch.bool, device=device)
543
+ else:
544
+ if num_empty_cameras >= self.config.empty_cameras:
545
+ continue
546
+ img = torch.ones_like(img) * -1
547
+ bsize = img.shape[0]
548
+ device = img.device
549
+ mask = torch.ones(bsize, dtype=torch.bool, device=device)
550
+ num_empty_cameras += 1
551
+
552
+ images.append(img)
553
+ img_masks.append(mask)
554
+ return images, img_masks
555
+
556
+ def normalize_actions(self, actions: torch.Tensor) -> torch.Tensor:
557
+ mins = actions.amin(dim=(1, 2), keepdim=True) # [0]
558
+ maxs = actions.amax(dim=(1, 2), keepdim=True) # [0]
559
+ return 2 * (actions - mins) / (maxs - mins + 1e-8) - 1
560
+
561
+ def _act_tokens_to_paligemma_tokens(self, tokens: torch.Tensor) -> torch.Tensor:
562
+ out = self.paligemma_tokenizer.vocab_size - 1 - self.fast_skip_tokens - tokens
563
+ return out
564
+
565
+ def fast_tokenizer_wrapper(self, actions_norm):
566
+ """
567
+ A wrapper for self.fast_tokenizer that ensures batch processing,
568
+ conversion to PyTorch tensors, and returns a dictionary without padding.
569
+ """
570
+ batch_tokens = self.fast_tokenizer(actions_norm)
571
+ fast_out = self.processor.tokenizer.pad({"input_ids": batch_tokens}, return_tensors="pt")
572
+
573
+ return fast_out
574
+
575
+ def create_token_type_ids(self, padded_mask: torch.Tensor, prefix_len: int) -> torch.Tensor:
576
+ token_type_ids = torch.zeros_like(padded_mask, dtype=torch.bool)
577
+ # Compute cumulative sum mask
578
+ cumsum_mask = (padded_mask != 0).cumsum(dim=1)
579
+ # Suffix block (everything after prefix_len)
580
+ suffix_mask = cumsum_mask > prefix_len
581
+ token_type_ids = suffix_mask
582
+ return token_type_ids
583
+
584
+ def create_input_tokens(self, state, lang_text, actions=None):
585
+ bsize = state.shape[0]
586
+ device = state.device
587
+ bins = torch.linspace(-1, 1, 256 + 1, device=device)[:-1]
588
+ discretized = torch.bucketize(state, bins) - 1
589
+ discretized = discretized[:, :32]
590
+
591
+ prefix_texts = []
592
+ state_text = []
593
+ for txt, disc in zip(lang_text, discretized, strict=False):
594
+ cleaned = txt.lower().strip().replace("_", " ")
595
+ state_str = " ".join(str(val.item()) for val in disc)
596
+ prefix_texts.append(f"Task: {cleaned}, State: {state_str};\n")
597
+ state_text.append(f"State: {state_str};\n")
598
+
599
+ prefix_out = self.paligemma_tokenizer(
600
+ prefix_texts, add_special_tokens=True, return_tensors="pt", padding="longest", truncation=False
601
+ )
602
+ prefix_ids = prefix_out["input_ids"].to(device)
603
+ prefix_mask = prefix_out["attention_mask"].to(device)
604
+ prefix_lens = prefix_mask.sum(dim=1)[:, None].cpu()
605
+
606
+ if actions is not None:
607
+ actions_norm = self.normalize_actions(actions)
608
+ actions_pad = F.pad(
609
+ actions_norm, (0, max(0, self.config.max_action_dim - actions_norm.shape[2])), value=0
610
+ )[:, :, : self.config.max_action_dim]
611
+ fast_out = self.fast_tokenizer_wrapper(
612
+ actions_pad.cpu(),
613
+ )
614
+ act_ids = fast_out["input_ids"]
615
+ act_mask = fast_out["attention_mask"].to(device)
616
+
617
+ act_ids = self._act_tokens_to_paligemma_tokens(act_ids).to(device)
618
+ # Replace action with 0 to pad tokens
619
+ act_ids = torch.where(
620
+ act_ids == self.paligemma_tokenizer.vocab_size - 1 - self.fast_skip_tokens,
621
+ self.pad_token_id,
622
+ act_ids,
623
+ )
624
+
625
+ eos_token = torch.tensor(
626
+ [self.paligemma_tokenizer.eos_token_id], dtype=torch.long, device=device
627
+ ).expand(bsize, -1)
628
+ eos_mask = torch.tensor([1], dtype=torch.long, device=device).expand(bsize, -1)
629
+ bos = self.paligemma_tokenizer("Action: ", add_special_tokens=False, return_tensors="pt")
630
+ bos_token = bos["input_ids"].expand(act_ids.shape[0], -1).to(device)
631
+ bos_mask = bos["attention_mask"].expand(act_ids.shape[0], -1).to(device)
632
+ act_ids = torch.cat([bos_token, act_ids, eos_token], dim=1)
633
+ act_mask = torch.cat([bos_mask, act_mask, eos_mask], dim=1)
634
+ act_mask = act_mask.to(device)
635
+ else:
636
+ act_ids = torch.empty(bsize, self.pad_token_id, dtype=torch.long, device=device)
637
+ act_mask = torch.empty(bsize, 0, dtype=torch.long, device=device)
638
+ final_ids = torch.cat([prefix_ids, act_ids], dim=1)
639
+
640
+ final_mask = torch.cat([prefix_mask, act_mask], dim=1)
641
+ batch_inputs = {"input_ids": final_ids.tolist(), "attention_mask": final_mask.tolist()}
642
+
643
+ # Use tokenizer pad function
644
+ padded_output = self.paligemma_tokenizer.pad(
645
+ batch_inputs, padding="longest", max_length=180, return_tensors="pt"
646
+ )
647
+ padded_mask = padded_output["attention_mask"]
648
+
649
+ # define tensor of padding lengths
650
+ att_mask = (padded_mask != 0).cumsum(dim=1) > prefix_lens
651
+
652
+ token_type_ids = self.create_token_type_ids(padded_mask=padded_mask, prefix_len=prefix_lens)
653
+
654
+ padded_output["padded_mask"] = padded_output.pop("attention_mask")
655
+ padded_output["attention_mask"] = att_mask
656
+ # loss is computed not on prefix, and not on padding
657
+ padded_output["loss_mask"] = att_mask & padded_output["padded_mask"]
658
+ padded_output["token_type_ids"] = token_type_ids
659
+ return padded_output
660
+
661
+ def shift_padding_side(
662
+ self,
663
+ tokens: torch.Tensor,
664
+ ar_mask: torch.Tensor,
665
+ padding_mask: torch.Tensor,
666
+ loss_mask: torch.Tensor,
667
+ targets: torch.Tensor,
668
+ token_type_ids: torch.Tensor,
669
+ padding_side: str = "right",
670
+ ) -> tuple[torch.Tensor]:
671
+ if padding_side not in ["right", "left"]:
672
+ return tokens, ar_mask, padding_mask, loss_mask, targets, token_type_ids
673
+
674
+ new_tokens = torch.empty_like(tokens)
675
+ new_ar_masks = torch.empty_like(ar_mask)
676
+ new_padding_mask = torch.empty_like(padding_mask)
677
+ new_loss_mask = torch.empty_like(loss_mask)
678
+ new_targets = torch.empty_like(targets)
679
+ new_token_type_ids = torch.empty_like(token_type_ids)
680
+ batch_size = tokens.shape[0]
681
+ for i in range(batch_size):
682
+ padding_indices = torch.where(padding_mask[i] == 0)[0]
683
+ non_padding_indices = torch.where(padding_mask[i] == 1)[0]
684
+ if padding_side == "left":
685
+ new_indices = torch.cat((padding_indices, non_padding_indices), dim=0)
686
+ else:
687
+ new_indices = torch.cat((non_padding_indices, padding_indices), dim=0)
688
+ new_tokens[i] = tokens[i].index_select(0, new_indices)
689
+ new_ar_masks[i] = ar_mask[i].index_select(0, new_indices)
690
+ new_padding_mask[i] = padding_mask[i].index_select(0, new_indices)
691
+ new_loss_mask[i] = loss_mask[i].index_select(0, new_indices)
692
+ new_targets[i] = targets[i].index_select(0, new_indices)
693
+ new_token_type_ids[i] = token_type_ids[i].index_select(0, new_indices)
694
+
695
+ return new_tokens, new_ar_masks, new_padding_mask, new_loss_mask, new_targets, new_token_type_ids
696
+
697
+ def forward(self, batch: dict[str, Tensor]):
698
+ device = batch[OBS_STATE].device
699
+ # TODO: keep like this or move to the policy .forward
700
+ images, img_masks = self.prepare_images(batch)
701
+
702
+ padded_outs = self.create_input_tokens(
703
+ state=batch[OBS_STATE],
704
+ lang_text=batch["task"],
705
+ actions=batch[ACTION],
706
+ )
707
+
708
+ embs, pad_masks, _, targets, loss_mask, token_type_ids = self.embed_inputs(
709
+ images,
710
+ img_masks,
711
+ padded_outs["input_ids"],
712
+ padded_outs["padded_mask"],
713
+ padded_outs["attention_mask"],
714
+ padded_outs["loss_mask"],
715
+ padded_outs["token_type_ids"],
716
+ padding_side=self.padding_side,
717
+ )
718
+ position_ids = torch.cumsum(pad_masks, dim=1) - 1
719
+ token_type_ids = token_type_ids.to(dtype=torch.int64)
720
+ past_seen_tokens = 0
721
+ cache_position = torch.arange(past_seen_tokens, past_seen_tokens + embs.shape[1], device=embs.device)
722
+ pad_masks = block_causal_update_causal_mask(
723
+ attention_mask=pad_masks,
724
+ past_key_values=None,
725
+ cache_position=cache_position,
726
+ input_tensor=embs,
727
+ token_type_ids=token_type_ids,
728
+ dtype=self.pi0_paligemma.dtype,
729
+ attn_implementation=self.pi0_paligemma.config.text_config._attn_implementation,
730
+ )
731
+ outputs = self.pi0_paligemma.forward(
732
+ input_ids=None,
733
+ token_type_ids=None,
734
+ attention_mask=pad_masks,
735
+ position_ids=position_ids,
736
+ past_key_values=None,
737
+ inputs_embeds=embs,
738
+ use_cache=False,
739
+ labels=None,
740
+ )
741
+
742
+ logits = outputs.logits
743
+
744
+ loss_fct = nn.CrossEntropyLoss(reduction="none")
745
+
746
+ # Shift left for next-step prediction
747
+ logits = logits[:, :-1, :]
748
+ targets = targets[:, 1:].to(device) # Shift targets
749
+ loss_mask = loss_mask[:, 1:].to(device) # Ensure correct shape
750
+
751
+ # Compute per-token loss
752
+ token_loss = loss_fct(logits.reshape(-1, logits.shape[-1]), targets.reshape(-1))
753
+
754
+ # Apply loss mask
755
+ token_loss = token_loss * loss_mask.reshape(-1)
756
+
757
+ # Compute final loss
758
+ loss = token_loss.sum() / torch.clamp(loss_mask.sum(), min=1)
759
+
760
+ # Return loss dictionary
761
+ loss_dict = {"ce_loss": loss.item(), "loss": loss}
762
+ return loss_dict
763
+
764
+ def decode_actions_with_fast(
765
+ self,
766
+ tokens: list[list[int]],
767
+ *,
768
+ time_horizon: int | None = None,
769
+ action_dim: int | None = None,
770
+ relaxed_decoding: bool = True,
771
+ ) -> np.array:
772
+ """
773
+ Adapt original decoding in FAST to always return actions instead of zeros.
774
+ """
775
+ self.time_horizon = (
776
+ time_horizon or self.fast_tokenizer.time_horizon or self.fast_tokenizer.called_time_horizon
777
+ )
778
+ self.action_dim = (
779
+ action_dim or self.fast_tokenizer.action_dim or self.fast_tokenizer.called_action_dim
780
+ )
781
+
782
+ # Cache the time horizon and action dimension for the next call
783
+ self.called_time_horizon = self.time_horizon
784
+ self.called_action_dim = self.action_dim
785
+
786
+ assert self.time_horizon is not None and self.action_dim is not None, (
787
+ "Tokenizer not initialized, call encode() once or pass in time_horizon and action_dim."
788
+ )
789
+
790
+ decoded_actions = []
791
+ for token in tokens:
792
+ try:
793
+ decoded_tokens = self.fast_tokenizer.bpe_tokenizer.decode(token)
794
+ decoded_dct_coeff = np.array(list(map(ord, decoded_tokens))) + self.fast_tokenizer.min_token
795
+ if relaxed_decoding:
796
+ # Expected sequence length
797
+ expected_seq_len = self.time_horizon * self.action_dim
798
+ diff = expected_seq_len - decoded_dct_coeff.shape[0]
799
+ # Apply truncation if too long
800
+ if diff < 0:
801
+ decoded_dct_coeff = decoded_dct_coeff[:expected_seq_len] # Truncate on the right
802
+ # Apply padding if too short
803
+ elif diff > 0:
804
+ decoded_dct_coeff = np.pad(
805
+ decoded_dct_coeff, (0, diff), mode="constant", constant_values=0
806
+ )
807
+
808
+ decoded_dct_coeff = decoded_dct_coeff.reshape(-1, self.action_dim)
809
+ assert decoded_dct_coeff.shape == (
810
+ self.time_horizon,
811
+ self.action_dim,
812
+ ), (
813
+ f"Decoded DCT coefficients have shape {decoded_dct_coeff.shape}, expected ({self.time_horizon}, {self.action_dim})"
814
+ )
815
+ except Exception as e:
816
+ print(f"Error decoding tokens: {e}")
817
+ print(f"Tokens: {token}")
818
+ decoded_dct_coeff = np.zeros((self.time_horizon, self.action_dim))
819
+ decoded_actions.append(idct(decoded_dct_coeff / self.fast_tokenizer.scale, axis=0, norm="ortho"))
820
+ return np.stack(decoded_actions)
821
+
822
+ def extract_actions(self, tokens: torch.Tensor, action_horizon: int, action_dim: int) -> torch.Tensor:
823
+ """
824
+ Extracts actions from predicted output tokens using the FAST model.
825
+
826
+ Args:
827
+ tokens (torch.Tensor): The input tensor of tokenized outputs.
828
+ action_horizon (int): The number of timesteps for actions.
829
+ action_dim (int): The dimensionality of each action.
830
+
831
+ Returns:
832
+ torch.Tensor: The extracted actions as a tensor of shape (action_horizon, action_dim).
833
+ """
834
+ # Decode predicted output tokens
835
+ decoded_tokens = self.paligemma_tokenizer.batch_decode(tokens, skip_special_tokens=True)
836
+ cleaned_tokens = [
837
+ tokens_sequence.replace("Action:", "").replace(":", "").strip().split("|")[0].strip()
838
+ for tokens_sequence in decoded_tokens
839
+ ]
840
+ raw_action_tokens = [
841
+ self.processor.tokenizer.encode(sample_tokens, return_tensors="pt", padding=False)
842
+ for sample_tokens in cleaned_tokens
843
+ ] # something like this should be robust #looks good
844
+ action_tokens = [
845
+ self._act_tokens_to_paligemma_tokens(raw_action_token) for raw_action_token in raw_action_tokens
846
+ ]
847
+ # returns the tensor of decoded actions per sample in a list
848
+ decoded_actions = [
849
+ torch.tensor(
850
+ self.decode_actions_with_fast(
851
+ tok.tolist(),
852
+ time_horizon=action_horizon,
853
+ action_dim=action_dim,
854
+ relaxed_decoding=self.config.relaxed_action_decoding,
855
+ ),
856
+ device=tokens.device,
857
+ ).squeeze(0)
858
+ for tok in action_tokens
859
+ ]
860
+
861
+ return torch.stack(
862
+ decoded_actions,
863
+ dim=0,
864
+ )
865
+
866
+ def generate_actions(self, batch: dict[str, Tensor]):
867
+ # TODO: keep like this or move to the policy .forward
868
+ images, img_masks = self.prepare_images(batch)
869
+
870
+ padded_outs = self.create_input_tokens(state=batch[OBS_STATE], lang_text=batch["task"], actions=None)
871
+ embs, pad_masks, att_masks2, targets, loss_mask, token_type_ids = self.embed_inputs(
872
+ images,
873
+ img_masks,
874
+ padded_outs["input_ids"],
875
+ padded_outs["padded_mask"],
876
+ padded_outs["attention_mask"],
877
+ padded_outs["loss_mask"],
878
+ padded_outs["token_type_ids"],
879
+ padding_side="left",
880
+ )
881
+ token_type_ids = token_type_ids.to(dtype=torch.int64)
882
+ prefix_position_ids = torch.cumsum(pad_masks, dim=1) - 1
883
+ output_tokens = self.pi0_paligemma.generate(
884
+ input_ids=None,
885
+ attention_mask=pad_masks,
886
+ position_ids=prefix_position_ids,
887
+ past_key_values=None,
888
+ inputs_embeds=embs,
889
+ use_cache=self.config.use_cache,
890
+ max_new_tokens=self.config.max_decoding_steps,
891
+ do_sample=False,
892
+ num_beams=1,
893
+ token_type_ids=token_type_ids,
894
+ )
895
+ actions = self.extract_actions(output_tokens, self.action_horizon, self.action_dim)
896
+ return actions
897
+
898
+ def embed_image(self, image: torch.Tensor):
899
+ # Handle different transformers versions
900
+ if hasattr(self.pi0_paligemma, "get_image_features"):
901
+ return self.pi0_paligemma.get_image_features(image)
902
+ else:
903
+ return self.pi0_paligemma.model.get_image_features(image)
904
+
905
+ def embed_inputs(
906
+ self,
907
+ images,
908
+ img_masks,
909
+ tokens,
910
+ pad_mask,
911
+ ar_mask,
912
+ loss_mask,
913
+ token_type_ids,
914
+ padding_side: str = "right",
915
+ ):
916
+ # TODO: avoid list in python and torch.cat ; prefer pre-allocation with torch.empty
917
+ # images are a list of same size
918
+ # vectorizing everything!
919
+ device = images[0].device
920
+ image_embedding_dim = images[0].shape[-1] # TODO should be from self.config
921
+ all_images = torch.stack(images, dim=1).to(device)
922
+ b, n, c, h, w = all_images.shape
923
+ all_images = all_images.view(b * n, c, h, w)
924
+ embedded = self.embed_image(all_images).to(device)
925
+ b_n, p, image_embedding_dim = embedded.shape # Extract current dimensions
926
+ m = b_n // b # Compute the number of images per sample dynamically
927
+
928
+ # Reshape dynamically
929
+ embedded = embedded.view(b, m, p, image_embedding_dim)
930
+ tokens_embs = self.embed_tokens(tokens.to(device))
931
+
932
+ img_masks = torch.stack(img_masks, dim=1).unsqueeze(-1).to(device)
933
+ num_img_emb = embedded.shape[2]
934
+ img_pad_masks = img_masks.repeat(1, 1, num_img_emb).view(b, -1)
935
+ img_att_masks = torch.zeros((b, n, num_img_emb), dtype=torch.long, device=device).reshape(b, -1)
936
+
937
+ image_target_tokens = (
938
+ torch.ones((b, n, num_img_emb), dtype=torch.long, device=device) * self.pad_token_id
939
+ ).reshape(b, -1)
940
+ image_loss_mask = torch.zeros((b, n, num_img_emb), dtype=torch.long, device=device).reshape(b, -1)
941
+
942
+ embedded = embedded.reshape(b, n * num_img_emb, image_embedding_dim) # Shape: (B, N*P, D)
943
+
944
+ embs = torch.cat([embedded, tokens_embs], dim=1).to(device)
945
+ pad_masks = torch.cat([img_pad_masks, pad_mask.to(device)], dim=1)
946
+ att_masks = torch.cat([img_att_masks, ar_mask.to(device)], dim=1)
947
+ loss_masks = torch.cat([image_loss_mask, loss_mask.to(device)], dim=1)
948
+ targets = torch.cat([image_target_tokens, tokens.to(device)], dim=1)
949
+ token_type_ids = torch.cat([img_att_masks, token_type_ids.to(device)], dim=1)
950
+
951
+ # Shift pad tokens to the left (.generate()) or right (.train())
952
+ embs, att_masks, pad_masks, loss_masks, targets, token_type_ids = self.shift_padding_side(
953
+ embs, att_masks, pad_masks, loss_masks, targets, token_type_ids, padding_side=padding_side
954
+ )
955
+
956
+ targets = torch.where(targets == self.pad_token_id, self.ignore_index, targets)
957
+ return embs, pad_masks, att_masks, targets, loss_masks, token_type_ids
958
+
959
+
960
+ def resize_with_pad(img, width, height, pad_value=0, interpolate_like_pi=True):
961
+ # assume no-op when width height fits already
962
+ if img.ndim != 4:
963
+ raise ValueError(f"(b,c,h,w) expected, but {img.shape}")
964
+
965
+ cur_height, cur_width = img.shape[2:]
966
+
967
+ ratio = max(cur_width / width, cur_height / height)
968
+ resized_height = int(cur_height / ratio)
969
+ resized_width = int(cur_width / ratio)
970
+
971
+ if interpolate_like_pi:
972
+ img = (img * 255.0).to(dtype=torch.uint8)
973
+ img = img.permute(0, 2, 3, 1)
974
+ original_device = img.device
975
+ img = img.to(device="cpu").numpy()
976
+ imgs = []
977
+ for sub_img in img:
978
+ sub_img = Image.fromarray(sub_img)
979
+ resized_img = sub_img.resize((resized_width, resized_height), resample=2)
980
+ resized_img = torch.from_numpy(np.array(resized_img))
981
+ imgs.append(resized_img)
982
+ img = torch.stack(imgs, dim=0)
983
+ img = img.permute(0, 3, 1, 2)
984
+ resized_img = img.to(device=original_device, dtype=torch.float32) / 255.0
985
+ else:
986
+ resized_img = F.interpolate(
987
+ img, size=(resized_height, resized_width), mode="bilinear", align_corners=False
988
+ )
989
+
990
+ pad_height = max(0, int(height - resized_height))
991
+ pad_width = max(0, int(width - resized_width))
992
+
993
+ # pad on left and top of image
994
+ padded_img = F.pad(resized_img, (pad_width, 0, pad_height, 0), value=pad_value)
995
+ return padded_img
tools/lerobot_v21_runtime/src/lerobot/policies/sac/configuration_sac.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # !/usr/bin/env python
2
+
3
+ # Copyright 2025 The HuggingFace Inc. team.
4
+ # All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ from dataclasses import dataclass, field
19
+
20
+ from lerobot.configs.policies import PreTrainedConfig
21
+ from lerobot.configs.types import NormalizationMode
22
+ from lerobot.constants import ACTION, OBS_IMAGE, OBS_STATE
23
+ from lerobot.optim.optimizers import MultiAdamConfig
24
+
25
+
26
+ def is_image_feature(key: str) -> bool:
27
+ """Check if a feature key represents an image feature.
28
+
29
+ Args:
30
+ key: The feature key to check
31
+
32
+ Returns:
33
+ True if the key represents an image feature, False otherwise
34
+ """
35
+ return key.startswith(OBS_IMAGE)
36
+
37
+
38
+ @dataclass
39
+ class ConcurrencyConfig:
40
+ """Configuration for the concurrency of the actor and learner.
41
+ Possible values are:
42
+ - "threads": Use threads for the actor and learner.
43
+ - "processes": Use processes for the actor and learner.
44
+ """
45
+
46
+ actor: str = "threads"
47
+ learner: str = "threads"
48
+
49
+
50
+ @dataclass
51
+ class ActorLearnerConfig:
52
+ learner_host: str = "127.0.0.1"
53
+ learner_port: int = 50051
54
+ policy_parameters_push_frequency: int = 4
55
+ queue_get_timeout: float = 2
56
+
57
+
58
+ @dataclass
59
+ class CriticNetworkConfig:
60
+ hidden_dims: list[int] = field(default_factory=lambda: [256, 256])
61
+ activate_final: bool = True
62
+ final_activation: str | None = None
63
+
64
+
65
+ @dataclass
66
+ class ActorNetworkConfig:
67
+ hidden_dims: list[int] = field(default_factory=lambda: [256, 256])
68
+ activate_final: bool = True
69
+
70
+
71
+ @dataclass
72
+ class PolicyConfig:
73
+ use_tanh_squash: bool = True
74
+ std_min: float = 1e-5
75
+ std_max: float = 10.0
76
+ init_final: float = 0.05
77
+
78
+
79
+ @PreTrainedConfig.register_subclass("sac")
80
+ @dataclass
81
+ class SACConfig(PreTrainedConfig):
82
+ """Soft Actor-Critic (SAC) configuration.
83
+
84
+ SAC is an off-policy actor-critic deep RL algorithm based on the maximum entropy
85
+ reinforcement learning framework. It learns a policy and a Q-function simultaneously
86
+ using experience collected from the environment.
87
+
88
+ This configuration class contains all the parameters needed to define a SAC agent,
89
+ including network architectures, optimization settings, and algorithm-specific
90
+ hyperparameters.
91
+ """
92
+
93
+ # Mapping of feature types to normalization modes
94
+ normalization_mapping: dict[str, NormalizationMode] = field(
95
+ default_factory=lambda: {
96
+ "VISUAL": NormalizationMode.MEAN_STD,
97
+ "STATE": NormalizationMode.MIN_MAX,
98
+ "ENV": NormalizationMode.MIN_MAX,
99
+ "ACTION": NormalizationMode.MIN_MAX,
100
+ }
101
+ )
102
+
103
+ # Statistics for normalizing different types of inputs
104
+ dataset_stats: dict[str, dict[str, list[float]]] | None = field(
105
+ default_factory=lambda: {
106
+ OBS_IMAGE: {
107
+ "mean": [0.485, 0.456, 0.406],
108
+ "std": [0.229, 0.224, 0.225],
109
+ },
110
+ OBS_STATE: {
111
+ "min": [0.0, 0.0],
112
+ "max": [1.0, 1.0],
113
+ },
114
+ ACTION: {
115
+ "min": [0.0, 0.0, 0.0],
116
+ "max": [1.0, 1.0, 1.0],
117
+ },
118
+ }
119
+ )
120
+
121
+ # Architecture specifics
122
+ # Device to run the model on (e.g., "cuda", "cpu")
123
+ device: str = "cpu"
124
+ # Device to store the model on
125
+ storage_device: str = "cpu"
126
+ # Name of the vision encoder model (Set to "helper2424/resnet10" for hil serl resnet10)
127
+ vision_encoder_name: str | None = None
128
+ # Whether to freeze the vision encoder during training
129
+ freeze_vision_encoder: bool = True
130
+ # Hidden dimension size for the image encoder
131
+ image_encoder_hidden_dim: int = 32
132
+ # Whether to use a shared encoder for actor and critic
133
+ shared_encoder: bool = True
134
+ # Number of discrete actions, eg for gripper actions
135
+ num_discrete_actions: int | None = None
136
+ # Dimension of the image embedding pooling
137
+ image_embedding_pooling_dim: int = 8
138
+
139
+ # Training parameter
140
+ # Number of steps for online training
141
+ online_steps: int = 1000000
142
+ # Seed for the online environment
143
+ online_env_seed: int = 10000
144
+ # Capacity of the online replay buffer
145
+ online_buffer_capacity: int = 100000
146
+ # Capacity of the offline replay buffer
147
+ offline_buffer_capacity: int = 100000
148
+ # Whether to use asynchronous prefetching for the buffers
149
+ async_prefetch: bool = False
150
+ # Number of steps before learning starts
151
+ online_step_before_learning: int = 100
152
+ # Frequency of policy updates
153
+ policy_update_freq: int = 1
154
+
155
+ # SAC algorithm parameters
156
+ # Discount factor for the SAC algorithm
157
+ discount: float = 0.99
158
+ # Initial temperature value
159
+ temperature_init: float = 1.0
160
+ # Number of critics in the ensemble
161
+ num_critics: int = 2
162
+ # Number of subsampled critics for training
163
+ num_subsample_critics: int | None = None
164
+ # Learning rate for the critic network
165
+ critic_lr: float = 3e-4
166
+ # Learning rate for the actor network
167
+ actor_lr: float = 3e-4
168
+ # Learning rate for the temperature parameter
169
+ temperature_lr: float = 3e-4
170
+ # Weight for the critic target update
171
+ critic_target_update_weight: float = 0.005
172
+ # Update-to-data ratio for the UTD algorithm (If you want enable utd_ratio, you need to set it to >1)
173
+ utd_ratio: int = 1
174
+ # Hidden dimension size for the state encoder
175
+ state_encoder_hidden_dim: int = 256
176
+ # Dimension of the latent space
177
+ latent_dim: int = 256
178
+ # Target entropy for the SAC algorithm
179
+ target_entropy: float | None = None
180
+ # Whether to use backup entropy for the SAC algorithm
181
+ use_backup_entropy: bool = True
182
+ # Gradient clipping norm for the SAC algorithm
183
+ grad_clip_norm: float = 40.0
184
+
185
+ # Network configuration
186
+ # Configuration for the critic network architecture
187
+ critic_network_kwargs: CriticNetworkConfig = field(default_factory=CriticNetworkConfig)
188
+ # Configuration for the actor network architecture
189
+ actor_network_kwargs: ActorNetworkConfig = field(default_factory=ActorNetworkConfig)
190
+ # Configuration for the policy parameters
191
+ policy_kwargs: PolicyConfig = field(default_factory=PolicyConfig)
192
+ # Configuration for the discrete critic network
193
+ discrete_critic_network_kwargs: CriticNetworkConfig = field(default_factory=CriticNetworkConfig)
194
+ # Configuration for actor-learner architecture
195
+ actor_learner_config: ActorLearnerConfig = field(default_factory=ActorLearnerConfig)
196
+ # Configuration for concurrency settings (you can use threads or processes for the actor and learner)
197
+ concurrency: ConcurrencyConfig = field(default_factory=ConcurrencyConfig)
198
+
199
+ # Optimizations
200
+ use_torch_compile: bool = True
201
+
202
+ def __post_init__(self):
203
+ super().__post_init__()
204
+ # Any validation specific to SAC configuration
205
+
206
+ def get_optimizer_preset(self) -> MultiAdamConfig:
207
+ return MultiAdamConfig(
208
+ weight_decay=0.0,
209
+ optimizer_groups={
210
+ "actor": {"lr": self.actor_lr},
211
+ "critic": {"lr": self.critic_lr},
212
+ "temperature": {"lr": self.temperature_lr},
213
+ },
214
+ )
215
+
216
+ def get_scheduler_preset(self) -> None:
217
+ return None
218
+
219
+ def validate_features(self) -> None:
220
+ has_image = any(is_image_feature(key) for key in self.input_features)
221
+ has_state = OBS_STATE in self.input_features
222
+
223
+ if not (has_state or has_image):
224
+ raise ValueError(
225
+ "You must provide either 'observation.state' or an image observation (key starting with 'observation.image') in the input features"
226
+ )
227
+
228
+ if "action" not in self.output_features:
229
+ raise ValueError("You must provide 'action' in the output features")
230
+
231
+ @property
232
+ def image_features(self) -> list[str]:
233
+ return [key for key in self.input_features if is_image_feature(key)]
234
+
235
+ @property
236
+ def observation_delta_indices(self) -> list:
237
+ return None
238
+
239
+ @property
240
+ def action_delta_indices(self) -> list:
241
+ return None # SAC typically predicts one action at a time
242
+
243
+ @property
244
+ def reward_delta_indices(self) -> None:
245
+ return None
tools/lerobot_v21_runtime/src/lerobot/policies/sac/modeling_sac.py ADDED
@@ -0,0 +1,1117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 The HuggingFace Inc. team.
4
+ # All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import math
19
+ from collections.abc import Callable
20
+ from dataclasses import asdict
21
+ from typing import Literal
22
+
23
+ import einops
24
+ import numpy as np
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F # noqa: N812
28
+ from torch import Tensor
29
+ from torch.distributions import MultivariateNormal, TanhTransform, Transform, TransformedDistribution
30
+
31
+ from lerobot.policies.normalize import NormalizeBuffer
32
+ from lerobot.policies.pretrained import PreTrainedPolicy
33
+ from lerobot.policies.sac.configuration_sac import SACConfig, is_image_feature
34
+ from lerobot.policies.utils import get_device_from_parameters
35
+
36
+ DISCRETE_DIMENSION_INDEX = -1 # Gripper is always the last dimension
37
+
38
+
39
+ class SACPolicy(
40
+ PreTrainedPolicy,
41
+ ):
42
+ config_class = SACConfig
43
+ name = "sac"
44
+
45
+ def __init__(
46
+ self,
47
+ config: SACConfig | None = None,
48
+ dataset_stats: dict[str, dict[str, Tensor]] | None = None,
49
+ ):
50
+ super().__init__(config)
51
+ config.validate_features()
52
+ self.config = config
53
+
54
+ # Determine action dimension and initialize all components
55
+ continuous_action_dim = config.output_features["action"].shape[0]
56
+ self._init_normalization(dataset_stats)
57
+ self._init_encoders()
58
+ self._init_critics(continuous_action_dim)
59
+ self._init_actor(continuous_action_dim)
60
+ self._init_temperature()
61
+
62
+ def get_optim_params(self) -> dict:
63
+ optim_params = {
64
+ "actor": [
65
+ p
66
+ for n, p in self.actor.named_parameters()
67
+ if not n.startswith("encoder") or not self.shared_encoder
68
+ ],
69
+ "critic": self.critic_ensemble.parameters(),
70
+ "temperature": self.log_alpha,
71
+ }
72
+ if self.config.num_discrete_actions is not None:
73
+ optim_params["discrete_critic"] = self.discrete_critic.parameters()
74
+ return optim_params
75
+
76
+ def reset(self):
77
+ """Reset the policy"""
78
+ pass
79
+
80
+ @torch.no_grad()
81
+ def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor:
82
+ """Predict a chunk of actions given environment observations."""
83
+ raise NotImplementedError("SACPolicy does not support action chunking. It returns single actions!")
84
+
85
+ @torch.no_grad()
86
+ def select_action(self, batch: dict[str, Tensor]) -> Tensor:
87
+ """Select action for inference/evaluation"""
88
+
89
+ observations_features = None
90
+ if self.shared_encoder and self.actor.encoder.has_images:
91
+ # Cache and normalize image features
92
+ observations_features = self.actor.encoder.get_cached_image_features(batch, normalize=True)
93
+
94
+ actions, _, _ = self.actor(batch, observations_features)
95
+
96
+ if self.config.num_discrete_actions is not None:
97
+ discrete_action_value = self.discrete_critic(batch, observations_features)
98
+ discrete_action = torch.argmax(discrete_action_value, dim=-1, keepdim=True)
99
+ actions = torch.cat([actions, discrete_action], dim=-1)
100
+
101
+ return actions
102
+
103
+ def critic_forward(
104
+ self,
105
+ observations: dict[str, Tensor],
106
+ actions: Tensor,
107
+ use_target: bool = False,
108
+ observation_features: Tensor | None = None,
109
+ ) -> Tensor:
110
+ """Forward pass through a critic network ensemble
111
+
112
+ Args:
113
+ observations: Dictionary of observations
114
+ actions: Action tensor
115
+ use_target: If True, use target critics, otherwise use ensemble critics
116
+
117
+ Returns:
118
+ Tensor of Q-values from all critics
119
+ """
120
+
121
+ critics = self.critic_target if use_target else self.critic_ensemble
122
+ q_values = critics(observations, actions, observation_features)
123
+ return q_values
124
+
125
+ def discrete_critic_forward(
126
+ self, observations, use_target=False, observation_features=None
127
+ ) -> torch.Tensor:
128
+ """Forward pass through a discrete critic network
129
+
130
+ Args:
131
+ observations: Dictionary of observations
132
+ use_target: If True, use target critics, otherwise use ensemble critics
133
+ observation_features: Optional pre-computed observation features to avoid recomputing encoder output
134
+
135
+ Returns:
136
+ Tensor of Q-values from the discrete critic network
137
+ """
138
+ discrete_critic = self.discrete_critic_target if use_target else self.discrete_critic
139
+ q_values = discrete_critic(observations, observation_features)
140
+ return q_values
141
+
142
+ def forward(
143
+ self,
144
+ batch: dict[str, Tensor | dict[str, Tensor]],
145
+ model: Literal["actor", "critic", "temperature", "discrete_critic"] = "critic",
146
+ ) -> dict[str, Tensor]:
147
+ """Compute the loss for the given model
148
+
149
+ Args:
150
+ batch: Dictionary containing:
151
+ - action: Action tensor
152
+ - reward: Reward tensor
153
+ - state: Observations tensor dict
154
+ - next_state: Next observations tensor dict
155
+ - done: Done mask tensor
156
+ - observation_feature: Optional pre-computed observation features
157
+ - next_observation_feature: Optional pre-computed next observation features
158
+ model: Which model to compute the loss for ("actor", "critic", "discrete_critic", or "temperature")
159
+
160
+ Returns:
161
+ The computed loss tensor
162
+ """
163
+ # Extract common components from batch
164
+ actions: Tensor = batch["action"]
165
+ observations: dict[str, Tensor] = batch["state"]
166
+ observation_features: Tensor = batch.get("observation_feature")
167
+
168
+ if model == "critic":
169
+ # Extract critic-specific components
170
+ rewards: Tensor = batch["reward"]
171
+ next_observations: dict[str, Tensor] = batch["next_state"]
172
+ done: Tensor = batch["done"]
173
+ next_observation_features: Tensor = batch.get("next_observation_feature")
174
+
175
+ loss_critic = self.compute_loss_critic(
176
+ observations=observations,
177
+ actions=actions,
178
+ rewards=rewards,
179
+ next_observations=next_observations,
180
+ done=done,
181
+ observation_features=observation_features,
182
+ next_observation_features=next_observation_features,
183
+ )
184
+
185
+ return {"loss_critic": loss_critic}
186
+
187
+ if model == "discrete_critic" and self.config.num_discrete_actions is not None:
188
+ # Extract critic-specific components
189
+ rewards: Tensor = batch["reward"]
190
+ next_observations: dict[str, Tensor] = batch["next_state"]
191
+ done: Tensor = batch["done"]
192
+ next_observation_features: Tensor = batch.get("next_observation_feature")
193
+ complementary_info = batch.get("complementary_info")
194
+ loss_discrete_critic = self.compute_loss_discrete_critic(
195
+ observations=observations,
196
+ actions=actions,
197
+ rewards=rewards,
198
+ next_observations=next_observations,
199
+ done=done,
200
+ observation_features=observation_features,
201
+ next_observation_features=next_observation_features,
202
+ complementary_info=complementary_info,
203
+ )
204
+ return {"loss_discrete_critic": loss_discrete_critic}
205
+ if model == "actor":
206
+ return {
207
+ "loss_actor": self.compute_loss_actor(
208
+ observations=observations,
209
+ observation_features=observation_features,
210
+ )
211
+ }
212
+
213
+ if model == "temperature":
214
+ return {
215
+ "loss_temperature": self.compute_loss_temperature(
216
+ observations=observations,
217
+ observation_features=observation_features,
218
+ )
219
+ }
220
+
221
+ raise ValueError(f"Unknown model type: {model}")
222
+
223
+ def update_target_networks(self):
224
+ """Update target networks with exponential moving average"""
225
+ for target_param, param in zip(
226
+ self.critic_target.parameters(),
227
+ self.critic_ensemble.parameters(),
228
+ strict=True,
229
+ ):
230
+ target_param.data.copy_(
231
+ param.data * self.config.critic_target_update_weight
232
+ + target_param.data * (1.0 - self.config.critic_target_update_weight)
233
+ )
234
+ if self.config.num_discrete_actions is not None:
235
+ for target_param, param in zip(
236
+ self.discrete_critic_target.parameters(),
237
+ self.discrete_critic.parameters(),
238
+ strict=True,
239
+ ):
240
+ target_param.data.copy_(
241
+ param.data * self.config.critic_target_update_weight
242
+ + target_param.data * (1.0 - self.config.critic_target_update_weight)
243
+ )
244
+
245
+ def update_temperature(self):
246
+ self.temperature = self.log_alpha.exp().item()
247
+
248
+ def compute_loss_critic(
249
+ self,
250
+ observations,
251
+ actions,
252
+ rewards,
253
+ next_observations,
254
+ done,
255
+ observation_features: Tensor | None = None,
256
+ next_observation_features: Tensor | None = None,
257
+ ) -> Tensor:
258
+ with torch.no_grad():
259
+ next_action_preds, next_log_probs, _ = self.actor(next_observations, next_observation_features)
260
+
261
+ # 2- compute q targets
262
+ q_targets = self.critic_forward(
263
+ observations=next_observations,
264
+ actions=next_action_preds,
265
+ use_target=True,
266
+ observation_features=next_observation_features,
267
+ )
268
+
269
+ # subsample critics to prevent overfitting if use high UTD (update to date)
270
+ # TODO: Get indices before forward pass to avoid unnecessary computation
271
+ if self.config.num_subsample_critics is not None:
272
+ indices = torch.randperm(self.config.num_critics)
273
+ indices = indices[: self.config.num_subsample_critics]
274
+ q_targets = q_targets[indices]
275
+
276
+ # critics subsample size
277
+ min_q, _ = q_targets.min(dim=0) # Get values from min operation
278
+ if self.config.use_backup_entropy:
279
+ min_q = min_q - (self.temperature * next_log_probs)
280
+
281
+ td_target = rewards + (1 - done) * self.config.discount * min_q
282
+
283
+ # 3- compute predicted qs
284
+ if self.config.num_discrete_actions is not None:
285
+ # NOTE: We only want to keep the continuous action part
286
+ # In the buffer we have the full action space (continuous + discrete)
287
+ # We need to split them before concatenating them in the critic forward
288
+ actions: Tensor = actions[:, :DISCRETE_DIMENSION_INDEX]
289
+ q_preds = self.critic_forward(
290
+ observations=observations,
291
+ actions=actions,
292
+ use_target=False,
293
+ observation_features=observation_features,
294
+ )
295
+
296
+ # 4- Calculate loss
297
+ # Compute state-action value loss (TD loss) for all of the Q functions in the ensemble.
298
+ td_target_duplicate = einops.repeat(td_target, "b -> e b", e=q_preds.shape[0])
299
+ # You compute the mean loss of the batch for each critic and then to compute the final loss you sum them up
300
+ critics_loss = (
301
+ F.mse_loss(
302
+ input=q_preds,
303
+ target=td_target_duplicate,
304
+ reduction="none",
305
+ ).mean(dim=1)
306
+ ).sum()
307
+ return critics_loss
308
+
309
+ def compute_loss_discrete_critic(
310
+ self,
311
+ observations,
312
+ actions,
313
+ rewards,
314
+ next_observations,
315
+ done,
316
+ observation_features=None,
317
+ next_observation_features=None,
318
+ complementary_info=None,
319
+ ):
320
+ # NOTE: We only want to keep the discrete action part
321
+ # In the buffer we have the full action space (continuous + discrete)
322
+ # We need to split them before concatenating them in the critic forward
323
+ actions_discrete: Tensor = actions[:, DISCRETE_DIMENSION_INDEX:].clone()
324
+ actions_discrete = torch.round(actions_discrete)
325
+ actions_discrete = actions_discrete.long()
326
+
327
+ discrete_penalties: Tensor | None = None
328
+ if complementary_info is not None:
329
+ discrete_penalties: Tensor | None = complementary_info.get("discrete_penalty")
330
+
331
+ with torch.no_grad():
332
+ # For DQN, select actions using online network, evaluate with target network
333
+ next_discrete_qs = self.discrete_critic_forward(
334
+ next_observations, use_target=False, observation_features=next_observation_features
335
+ )
336
+ best_next_discrete_action = torch.argmax(next_discrete_qs, dim=-1, keepdim=True)
337
+
338
+ # Get target Q-values from target network
339
+ target_next_discrete_qs = self.discrete_critic_forward(
340
+ observations=next_observations,
341
+ use_target=True,
342
+ observation_features=next_observation_features,
343
+ )
344
+
345
+ # Use gather to select Q-values for best actions
346
+ target_next_discrete_q = torch.gather(
347
+ target_next_discrete_qs, dim=1, index=best_next_discrete_action
348
+ ).squeeze(-1)
349
+
350
+ # Compute target Q-value with Bellman equation
351
+ rewards_discrete = rewards
352
+ if discrete_penalties is not None:
353
+ rewards_discrete = rewards + discrete_penalties
354
+ target_discrete_q = rewards_discrete + (1 - done) * self.config.discount * target_next_discrete_q
355
+
356
+ # Get predicted Q-values for current observations
357
+ predicted_discrete_qs = self.discrete_critic_forward(
358
+ observations=observations, use_target=False, observation_features=observation_features
359
+ )
360
+
361
+ # Use gather to select Q-values for taken actions
362
+ predicted_discrete_q = torch.gather(predicted_discrete_qs, dim=1, index=actions_discrete).squeeze(-1)
363
+
364
+ # Compute MSE loss between predicted and target Q-values
365
+ discrete_critic_loss = F.mse_loss(input=predicted_discrete_q, target=target_discrete_q)
366
+ return discrete_critic_loss
367
+
368
+ def compute_loss_temperature(self, observations, observation_features: Tensor | None = None) -> Tensor:
369
+ """Compute the temperature loss"""
370
+ # calculate temperature loss
371
+ with torch.no_grad():
372
+ _, log_probs, _ = self.actor(observations, observation_features)
373
+ temperature_loss = (-self.log_alpha.exp() * (log_probs + self.target_entropy)).mean()
374
+ return temperature_loss
375
+
376
+ def compute_loss_actor(
377
+ self,
378
+ observations,
379
+ observation_features: Tensor | None = None,
380
+ ) -> Tensor:
381
+ actions_pi, log_probs, _ = self.actor(observations, observation_features)
382
+
383
+ q_preds = self.critic_forward(
384
+ observations=observations,
385
+ actions=actions_pi,
386
+ use_target=False,
387
+ observation_features=observation_features,
388
+ )
389
+ min_q_preds = q_preds.min(dim=0)[0]
390
+
391
+ actor_loss = ((self.temperature * log_probs) - min_q_preds).mean()
392
+ return actor_loss
393
+
394
+ def _init_normalization(self, dataset_stats):
395
+ """Initialize input/output normalization modules."""
396
+ self.normalize_inputs = nn.Identity()
397
+ self.normalize_targets = nn.Identity()
398
+ if self.config.dataset_stats is not None:
399
+ params = _convert_normalization_params_to_tensor(self.config.dataset_stats)
400
+ self.normalize_inputs = NormalizeBuffer(
401
+ self.config.input_features, self.config.normalization_mapping, params
402
+ )
403
+ stats = dataset_stats or params
404
+ self.normalize_targets = NormalizeBuffer(
405
+ self.config.output_features, self.config.normalization_mapping, stats
406
+ )
407
+
408
+ def _init_encoders(self):
409
+ """Initialize shared or separate encoders for actor and critic."""
410
+ self.shared_encoder = self.config.shared_encoder
411
+ self.encoder_critic = SACObservationEncoder(self.config, self.normalize_inputs)
412
+ self.encoder_actor = (
413
+ self.encoder_critic
414
+ if self.shared_encoder
415
+ else SACObservationEncoder(self.config, self.normalize_inputs)
416
+ )
417
+
418
+ def _init_critics(self, continuous_action_dim):
419
+ """Build critic ensemble, targets, and optional discrete critic."""
420
+ heads = [
421
+ CriticHead(
422
+ input_dim=self.encoder_critic.output_dim + continuous_action_dim,
423
+ **asdict(self.config.critic_network_kwargs),
424
+ )
425
+ for _ in range(self.config.num_critics)
426
+ ]
427
+ self.critic_ensemble = CriticEnsemble(
428
+ encoder=self.encoder_critic, ensemble=heads, output_normalization=self.normalize_targets
429
+ )
430
+ target_heads = [
431
+ CriticHead(
432
+ input_dim=self.encoder_critic.output_dim + continuous_action_dim,
433
+ **asdict(self.config.critic_network_kwargs),
434
+ )
435
+ for _ in range(self.config.num_critics)
436
+ ]
437
+ self.critic_target = CriticEnsemble(
438
+ encoder=self.encoder_critic, ensemble=target_heads, output_normalization=self.normalize_targets
439
+ )
440
+ self.critic_target.load_state_dict(self.critic_ensemble.state_dict())
441
+
442
+ if self.config.use_torch_compile:
443
+ self.critic_ensemble = torch.compile(self.critic_ensemble)
444
+ self.critic_target = torch.compile(self.critic_target)
445
+
446
+ if self.config.num_discrete_actions is not None:
447
+ self._init_discrete_critics()
448
+
449
+ def _init_discrete_critics(self):
450
+ """Build discrete discrete critic ensemble and target networks."""
451
+ self.discrete_critic = DiscreteCritic(
452
+ encoder=self.encoder_critic,
453
+ input_dim=self.encoder_critic.output_dim,
454
+ output_dim=self.config.num_discrete_actions,
455
+ **asdict(self.config.discrete_critic_network_kwargs),
456
+ )
457
+ self.discrete_critic_target = DiscreteCritic(
458
+ encoder=self.encoder_critic,
459
+ input_dim=self.encoder_critic.output_dim,
460
+ output_dim=self.config.num_discrete_actions,
461
+ **asdict(self.config.discrete_critic_network_kwargs),
462
+ )
463
+
464
+ # TODO: (maractingi, azouitine) Compile the discrete critic
465
+ self.discrete_critic_target.load_state_dict(self.discrete_critic.state_dict())
466
+
467
+ def _init_actor(self, continuous_action_dim):
468
+ """Initialize policy actor network and default target entropy."""
469
+ # NOTE: The actor select only the continuous action part
470
+ self.actor = Policy(
471
+ encoder=self.encoder_actor,
472
+ network=MLP(input_dim=self.encoder_actor.output_dim, **asdict(self.config.actor_network_kwargs)),
473
+ action_dim=continuous_action_dim,
474
+ encoder_is_shared=self.shared_encoder,
475
+ **asdict(self.config.policy_kwargs),
476
+ )
477
+
478
+ self.target_entropy = self.config.target_entropy
479
+ if self.target_entropy is None:
480
+ dim = continuous_action_dim + (1 if self.config.num_discrete_actions is not None else 0)
481
+ self.target_entropy = -np.prod(dim) / 2
482
+
483
+ def _init_temperature(self):
484
+ """Set up temperature parameter and initial log_alpha."""
485
+ temp_init = self.config.temperature_init
486
+ self.log_alpha = nn.Parameter(torch.tensor([math.log(temp_init)]))
487
+ self.temperature = self.log_alpha.exp().item()
488
+
489
+
490
+ class SACObservationEncoder(nn.Module):
491
+ """Encode image and/or state vector observations."""
492
+
493
+ def __init__(self, config: SACConfig, input_normalizer: nn.Module) -> None:
494
+ super().__init__()
495
+ self.config = config
496
+ self.input_normalization = input_normalizer
497
+ self._init_image_layers()
498
+ self._init_state_layers()
499
+ self._compute_output_dim()
500
+
501
+ def _init_image_layers(self) -> None:
502
+ self.image_keys = [k for k in self.config.input_features if is_image_feature(k)]
503
+ self.has_images = bool(self.image_keys)
504
+ if not self.has_images:
505
+ return
506
+
507
+ if self.config.vision_encoder_name is not None:
508
+ self.image_encoder = PretrainedImageEncoder(self.config)
509
+ else:
510
+ self.image_encoder = DefaultImageEncoder(self.config)
511
+
512
+ if self.config.freeze_vision_encoder:
513
+ freeze_image_encoder(self.image_encoder)
514
+
515
+ dummy = torch.zeros(1, *self.config.input_features[self.image_keys[0]].shape)
516
+ with torch.no_grad():
517
+ _, channels, height, width = self.image_encoder(dummy).shape
518
+
519
+ self.spatial_embeddings = nn.ModuleDict()
520
+ self.post_encoders = nn.ModuleDict()
521
+
522
+ for key in self.image_keys:
523
+ name = key.replace(".", "_")
524
+ self.spatial_embeddings[name] = SpatialLearnedEmbeddings(
525
+ height=height,
526
+ width=width,
527
+ channel=channels,
528
+ num_features=self.config.image_embedding_pooling_dim,
529
+ )
530
+ self.post_encoders[name] = nn.Sequential(
531
+ nn.Dropout(0.1),
532
+ nn.Linear(
533
+ in_features=channels * self.config.image_embedding_pooling_dim,
534
+ out_features=self.config.latent_dim,
535
+ ),
536
+ nn.LayerNorm(normalized_shape=self.config.latent_dim),
537
+ nn.Tanh(),
538
+ )
539
+
540
+ def _init_state_layers(self) -> None:
541
+ self.has_env = "observation.environment_state" in self.config.input_features
542
+ self.has_state = "observation.state" in self.config.input_features
543
+ if self.has_env:
544
+ dim = self.config.input_features["observation.environment_state"].shape[0]
545
+ self.env_encoder = nn.Sequential(
546
+ nn.Linear(dim, self.config.latent_dim),
547
+ nn.LayerNorm(self.config.latent_dim),
548
+ nn.Tanh(),
549
+ )
550
+ if self.has_state:
551
+ dim = self.config.input_features["observation.state"].shape[0]
552
+ self.state_encoder = nn.Sequential(
553
+ nn.Linear(dim, self.config.latent_dim),
554
+ nn.LayerNorm(self.config.latent_dim),
555
+ nn.Tanh(),
556
+ )
557
+
558
+ def _compute_output_dim(self) -> None:
559
+ out = 0
560
+ if self.has_images:
561
+ out += len(self.image_keys) * self.config.latent_dim
562
+ if self.has_env:
563
+ out += self.config.latent_dim
564
+ if self.has_state:
565
+ out += self.config.latent_dim
566
+ self._out_dim = out
567
+
568
+ def forward(
569
+ self, obs: dict[str, Tensor], cache: dict[str, Tensor] | None = None, detach: bool = False
570
+ ) -> Tensor:
571
+ obs = self.input_normalization(obs)
572
+ parts = []
573
+ if self.has_images:
574
+ if cache is None:
575
+ cache = self.get_cached_image_features(obs, normalize=False)
576
+ parts.append(self._encode_images(cache, detach))
577
+ if self.has_env:
578
+ parts.append(self.env_encoder(obs["observation.environment_state"]))
579
+ if self.has_state:
580
+ parts.append(self.state_encoder(obs["observation.state"]))
581
+ if parts:
582
+ return torch.cat(parts, dim=-1)
583
+
584
+ raise ValueError(
585
+ "No parts to concatenate, you should have at least one image or environment state or state"
586
+ )
587
+
588
+ def get_cached_image_features(self, obs: dict[str, Tensor], normalize: bool = False) -> dict[str, Tensor]:
589
+ """Extract and optionally cache image features from observations.
590
+
591
+ This function processes image observations through the vision encoder once and returns
592
+ the resulting features.
593
+ When the image encoder is shared between actor and critics AND frozen, these features can be safely cached and
594
+ reused across policy components (actor, critic, discrete_critic), avoiding redundant forward passes.
595
+
596
+ Performance impact:
597
+ - The vision encoder forward pass is typically the main computational bottleneck during training and inference
598
+ - Caching these features can provide 2-4x speedup in training and inference
599
+
600
+ Normalization behavior:
601
+ - When called from inside forward(): set normalize=False since inputs are already normalized
602
+ - When called from outside forward(): set normalize=True to ensure proper input normalization
603
+
604
+ Usage patterns:
605
+ - Called in select_action() with normalize=True
606
+ - Called in learner.py's get_observation_features() to pre-compute features for all policy components
607
+ - Called internally by forward() with normalize=False
608
+
609
+ Args:
610
+ obs: Dictionary of observation tensors containing image keys
611
+ normalize: Whether to normalize observations before encoding
612
+ Set to True when calling directly from outside the encoder's forward method
613
+ Set to False when calling from within forward() where inputs are already normalized
614
+
615
+ Returns:
616
+ Dictionary mapping image keys to their corresponding encoded features
617
+ """
618
+ if normalize:
619
+ obs = self.input_normalization(obs)
620
+ batched = torch.cat([obs[k] for k in self.image_keys], dim=0)
621
+ out = self.image_encoder(batched)
622
+ chunks = torch.chunk(out, len(self.image_keys), dim=0)
623
+ return dict(zip(self.image_keys, chunks, strict=False))
624
+
625
+ def _encode_images(self, cache: dict[str, Tensor], detach: bool) -> Tensor:
626
+ """Encode image features from cached observations.
627
+
628
+ This function takes pre-encoded image features from the cache and applies spatial embeddings and post-encoders.
629
+ It also supports detaching the encoded features if specified.
630
+
631
+ Args:
632
+ cache (dict[str, Tensor]): The cached image features.
633
+ detach (bool): Usually when the encoder is shared between actor and critics,
634
+ we want to detach the encoded features on the policy side to avoid backprop through the encoder.
635
+ More detail here `https://cdn.aaai.org/ojs/17276/17276-13-20770-1-2-20210518.pdf`
636
+
637
+ Returns:
638
+ Tensor: The encoded image features.
639
+ """
640
+ feats = []
641
+ for k, feat in cache.items():
642
+ safe_key = k.replace(".", "_")
643
+ x = self.spatial_embeddings[safe_key](feat)
644
+ x = self.post_encoders[safe_key](x)
645
+ if detach:
646
+ x = x.detach()
647
+ feats.append(x)
648
+ return torch.cat(feats, dim=-1)
649
+
650
+ @property
651
+ def output_dim(self) -> int:
652
+ return self._out_dim
653
+
654
+
655
+ class MLP(nn.Module):
656
+ """Multi-layer perceptron builder.
657
+
658
+ Dynamically constructs a sequence of layers based on `hidden_dims`:
659
+ 1) Linear (in_dim -> out_dim)
660
+ 2) Optional Dropout if `dropout_rate` > 0 and (not final layer or `activate_final`)
661
+ 3) LayerNorm on the output features
662
+ 4) Activation (standard for intermediate layers, `final_activation` for last layer if `activate_final`)
663
+
664
+ Arguments:
665
+ input_dim (int): Size of input feature dimension.
666
+ hidden_dims (list[int]): Sizes for each hidden layer.
667
+ activations (Callable or str): Activation to apply between layers.
668
+ activate_final (bool): Whether to apply activation at the final layer.
669
+ dropout_rate (Optional[float]): Dropout probability applied before normalization and activation.
670
+ final_activation (Optional[Callable or str]): Activation for the final layer when `activate_final` is True.
671
+
672
+ For each layer, `in_dim` is updated to the previous `out_dim`. All constructed modules are
673
+ stored in `self.net` as an `nn.Sequential` container.
674
+ """
675
+
676
+ def __init__(
677
+ self,
678
+ input_dim: int,
679
+ hidden_dims: list[int],
680
+ activations: Callable[[torch.Tensor], torch.Tensor] | str = nn.SiLU(),
681
+ activate_final: bool = False,
682
+ dropout_rate: float | None = None,
683
+ final_activation: Callable[[torch.Tensor], torch.Tensor] | str | None = None,
684
+ ):
685
+ super().__init__()
686
+ layers: list[nn.Module] = []
687
+ in_dim = input_dim
688
+ total = len(hidden_dims)
689
+
690
+ for idx, out_dim in enumerate(hidden_dims):
691
+ # 1) linear transform
692
+ layers.append(nn.Linear(in_dim, out_dim))
693
+
694
+ is_last = idx == total - 1
695
+ # 2-4) optionally add dropout, normalization, and activation
696
+ if not is_last or activate_final:
697
+ if dropout_rate and dropout_rate > 0:
698
+ layers.append(nn.Dropout(p=dropout_rate))
699
+ layers.append(nn.LayerNorm(out_dim))
700
+ act_cls = final_activation if is_last and final_activation else activations
701
+ act = act_cls if isinstance(act_cls, nn.Module) else getattr(nn, act_cls)()
702
+ layers.append(act)
703
+
704
+ in_dim = out_dim
705
+
706
+ self.net = nn.Sequential(*layers)
707
+
708
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
709
+ return self.net(x)
710
+
711
+
712
+ class CriticHead(nn.Module):
713
+ def __init__(
714
+ self,
715
+ input_dim: int,
716
+ hidden_dims: list[int],
717
+ activations: Callable[[torch.Tensor], torch.Tensor] | str = nn.SiLU(),
718
+ activate_final: bool = False,
719
+ dropout_rate: float | None = None,
720
+ init_final: float | None = None,
721
+ final_activation: Callable[[torch.Tensor], torch.Tensor] | str | None = None,
722
+ ):
723
+ super().__init__()
724
+ self.net = MLP(
725
+ input_dim=input_dim,
726
+ hidden_dims=hidden_dims,
727
+ activations=activations,
728
+ activate_final=activate_final,
729
+ dropout_rate=dropout_rate,
730
+ final_activation=final_activation,
731
+ )
732
+ self.output_layer = nn.Linear(in_features=hidden_dims[-1], out_features=1)
733
+ if init_final is not None:
734
+ nn.init.uniform_(self.output_layer.weight, -init_final, init_final)
735
+ nn.init.uniform_(self.output_layer.bias, -init_final, init_final)
736
+ else:
737
+ orthogonal_init()(self.output_layer.weight)
738
+
739
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
740
+ return self.output_layer(self.net(x))
741
+
742
+
743
+ class CriticEnsemble(nn.Module):
744
+ """
745
+ CriticEnsemble wraps multiple CriticHead modules into an ensemble.
746
+
747
+ Args:
748
+ encoder (SACObservationEncoder): encoder for observations.
749
+ ensemble (List[CriticHead]): list of critic heads.
750
+ output_normalization (nn.Module): normalization layer for actions.
751
+ init_final (float | None): optional initializer scale for final layers.
752
+
753
+ Forward returns a tensor of shape (num_critics, batch_size) containing Q-values.
754
+ """
755
+
756
+ def __init__(
757
+ self,
758
+ encoder: SACObservationEncoder,
759
+ ensemble: list[CriticHead],
760
+ output_normalization: nn.Module,
761
+ init_final: float | None = None,
762
+ ):
763
+ super().__init__()
764
+ self.encoder = encoder
765
+ self.init_final = init_final
766
+ self.output_normalization = output_normalization
767
+ self.critics = nn.ModuleList(ensemble)
768
+
769
+ def forward(
770
+ self,
771
+ observations: dict[str, torch.Tensor],
772
+ actions: torch.Tensor,
773
+ observation_features: torch.Tensor | None = None,
774
+ ) -> torch.Tensor:
775
+ device = get_device_from_parameters(self)
776
+ # Move each tensor in observations to device
777
+ observations = {k: v.to(device) for k, v in observations.items()}
778
+ # NOTE: We normalize actions it helps for sample efficiency
779
+ actions: dict[str, torch.tensor] = {"action": actions}
780
+ # NOTE: Normalization layer took dict in input and outputs a dict that why
781
+ actions = self.output_normalization(actions)["action"]
782
+ actions = actions.to(device)
783
+
784
+ obs_enc = self.encoder(observations, cache=observation_features)
785
+
786
+ inputs = torch.cat([obs_enc, actions], dim=-1)
787
+
788
+ # Loop through critics and collect outputs
789
+ q_values = []
790
+ for critic in self.critics:
791
+ q_values.append(critic(inputs))
792
+
793
+ # Stack outputs to match expected shape [num_critics, batch_size]
794
+ q_values = torch.stack([q.squeeze(-1) for q in q_values], dim=0)
795
+ return q_values
796
+
797
+
798
+ class DiscreteCritic(nn.Module):
799
+ def __init__(
800
+ self,
801
+ encoder: nn.Module,
802
+ input_dim: int,
803
+ hidden_dims: list[int],
804
+ output_dim: int = 3,
805
+ activations: Callable[[torch.Tensor], torch.Tensor] | str = nn.SiLU(),
806
+ activate_final: bool = False,
807
+ dropout_rate: float | None = None,
808
+ init_final: float | None = None,
809
+ final_activation: Callable[[torch.Tensor], torch.Tensor] | str | None = None,
810
+ ):
811
+ super().__init__()
812
+ self.encoder = encoder
813
+ self.output_dim = output_dim
814
+
815
+ self.net = MLP(
816
+ input_dim=input_dim,
817
+ hidden_dims=hidden_dims,
818
+ activations=activations,
819
+ activate_final=activate_final,
820
+ dropout_rate=dropout_rate,
821
+ final_activation=final_activation,
822
+ )
823
+
824
+ self.output_layer = nn.Linear(in_features=hidden_dims[-1], out_features=self.output_dim)
825
+ if init_final is not None:
826
+ nn.init.uniform_(self.output_layer.weight, -init_final, init_final)
827
+ nn.init.uniform_(self.output_layer.bias, -init_final, init_final)
828
+ else:
829
+ orthogonal_init()(self.output_layer.weight)
830
+
831
+ def forward(
832
+ self, observations: torch.Tensor, observation_features: torch.Tensor | None = None
833
+ ) -> torch.Tensor:
834
+ device = get_device_from_parameters(self)
835
+ observations = {k: v.to(device) for k, v in observations.items()}
836
+ obs_enc = self.encoder(observations, cache=observation_features)
837
+ return self.output_layer(self.net(obs_enc))
838
+
839
+
840
+ class Policy(nn.Module):
841
+ def __init__(
842
+ self,
843
+ encoder: SACObservationEncoder,
844
+ network: nn.Module,
845
+ action_dim: int,
846
+ std_min: float = -5,
847
+ std_max: float = 2,
848
+ fixed_std: torch.Tensor | None = None,
849
+ init_final: float | None = None,
850
+ use_tanh_squash: bool = False,
851
+ encoder_is_shared: bool = False,
852
+ ):
853
+ super().__init__()
854
+ self.encoder: SACObservationEncoder = encoder
855
+ self.network = network
856
+ self.action_dim = action_dim
857
+ self.std_min = std_min
858
+ self.std_max = std_max
859
+ self.fixed_std = fixed_std
860
+ self.use_tanh_squash = use_tanh_squash
861
+ self.encoder_is_shared = encoder_is_shared
862
+
863
+ # Find the last Linear layer's output dimension
864
+ for layer in reversed(network.net):
865
+ if isinstance(layer, nn.Linear):
866
+ out_features = layer.out_features
867
+ break
868
+ # Mean layer
869
+ self.mean_layer = nn.Linear(out_features, action_dim)
870
+ if init_final is not None:
871
+ nn.init.uniform_(self.mean_layer.weight, -init_final, init_final)
872
+ nn.init.uniform_(self.mean_layer.bias, -init_final, init_final)
873
+ else:
874
+ orthogonal_init()(self.mean_layer.weight)
875
+
876
+ # Standard deviation layer or parameter
877
+ if fixed_std is None:
878
+ self.std_layer = nn.Linear(out_features, action_dim)
879
+ if init_final is not None:
880
+ nn.init.uniform_(self.std_layer.weight, -init_final, init_final)
881
+ nn.init.uniform_(self.std_layer.bias, -init_final, init_final)
882
+ else:
883
+ orthogonal_init()(self.std_layer.weight)
884
+
885
+ def forward(
886
+ self,
887
+ observations: torch.Tensor,
888
+ observation_features: torch.Tensor | None = None,
889
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
890
+ # We detach the encoder if it is shared to avoid backprop through it
891
+ # This is important to avoid the encoder to be updated through the policy
892
+ obs_enc = self.encoder(observations, cache=observation_features, detach=self.encoder_is_shared)
893
+
894
+ # Get network outputs
895
+ outputs = self.network(obs_enc)
896
+ means = self.mean_layer(outputs)
897
+
898
+ # Compute standard deviations
899
+ if self.fixed_std is None:
900
+ log_std = self.std_layer(outputs)
901
+ std = torch.exp(log_std) # Match JAX "exp"
902
+ std = torch.clamp(std, self.std_min, self.std_max) # Match JAX default clip
903
+ else:
904
+ std = self.fixed_std.expand_as(means)
905
+
906
+ # Build transformed distribution
907
+ dist = TanhMultivariateNormalDiag(loc=means, scale_diag=std)
908
+
909
+ # Sample actions (reparameterized)
910
+ actions = dist.rsample()
911
+
912
+ # Compute log_probs
913
+ log_probs = dist.log_prob(actions)
914
+
915
+ return actions, log_probs, means
916
+
917
+ def get_features(self, observations: torch.Tensor) -> torch.Tensor:
918
+ """Get encoded features from observations"""
919
+ device = get_device_from_parameters(self)
920
+ observations = observations.to(device)
921
+ if self.encoder is not None:
922
+ with torch.inference_mode():
923
+ return self.encoder(observations)
924
+ return observations
925
+
926
+
927
+ class DefaultImageEncoder(nn.Module):
928
+ def __init__(self, config: SACConfig):
929
+ super().__init__()
930
+ image_key = next(key for key in config.input_features if is_image_feature(key))
931
+ self.image_enc_layers = nn.Sequential(
932
+ nn.Conv2d(
933
+ in_channels=config.input_features[image_key].shape[0],
934
+ out_channels=config.image_encoder_hidden_dim,
935
+ kernel_size=7,
936
+ stride=2,
937
+ ),
938
+ nn.ReLU(),
939
+ nn.Conv2d(
940
+ in_channels=config.image_encoder_hidden_dim,
941
+ out_channels=config.image_encoder_hidden_dim,
942
+ kernel_size=5,
943
+ stride=2,
944
+ ),
945
+ nn.ReLU(),
946
+ nn.Conv2d(
947
+ in_channels=config.image_encoder_hidden_dim,
948
+ out_channels=config.image_encoder_hidden_dim,
949
+ kernel_size=3,
950
+ stride=2,
951
+ ),
952
+ nn.ReLU(),
953
+ nn.Conv2d(
954
+ in_channels=config.image_encoder_hidden_dim,
955
+ out_channels=config.image_encoder_hidden_dim,
956
+ kernel_size=3,
957
+ stride=2,
958
+ ),
959
+ nn.ReLU(),
960
+ )
961
+
962
+ def forward(self, x):
963
+ x = self.image_enc_layers(x)
964
+ return x
965
+
966
+
967
+ def freeze_image_encoder(image_encoder: nn.Module):
968
+ """Freeze all parameters in the encoder"""
969
+ for param in image_encoder.parameters():
970
+ param.requires_grad = False
971
+
972
+
973
+ class PretrainedImageEncoder(nn.Module):
974
+ def __init__(self, config: SACConfig):
975
+ super().__init__()
976
+
977
+ self.image_enc_layers, self.image_enc_out_shape = self._load_pretrained_vision_encoder(config)
978
+
979
+ def _load_pretrained_vision_encoder(self, config: SACConfig):
980
+ """Set up CNN encoder"""
981
+ from transformers import AutoModel
982
+
983
+ self.image_enc_layers = AutoModel.from_pretrained(config.vision_encoder_name, trust_remote_code=True)
984
+
985
+ if hasattr(self.image_enc_layers.config, "hidden_sizes"):
986
+ self.image_enc_out_shape = self.image_enc_layers.config.hidden_sizes[-1] # Last channel dimension
987
+ elif hasattr(self.image_enc_layers, "fc"):
988
+ self.image_enc_out_shape = self.image_enc_layers.fc.in_features
989
+ else:
990
+ raise ValueError("Unsupported vision encoder architecture, make sure you are using a CNN")
991
+ return self.image_enc_layers, self.image_enc_out_shape
992
+
993
+ def forward(self, x):
994
+ enc_feat = self.image_enc_layers(x).last_hidden_state
995
+ return enc_feat
996
+
997
+
998
+ def orthogonal_init():
999
+ return lambda x: torch.nn.init.orthogonal_(x, gain=1.0)
1000
+
1001
+
1002
+ class SpatialLearnedEmbeddings(nn.Module):
1003
+ def __init__(self, height, width, channel, num_features=8):
1004
+ """
1005
+ PyTorch implementation of learned spatial embeddings
1006
+
1007
+ Args:
1008
+ height: Spatial height of input features
1009
+ width: Spatial width of input features
1010
+ channel: Number of input channels
1011
+ num_features: Number of output embedding dimensions
1012
+ """
1013
+ super().__init__()
1014
+ self.height = height
1015
+ self.width = width
1016
+ self.channel = channel
1017
+ self.num_features = num_features
1018
+
1019
+ self.kernel = nn.Parameter(torch.empty(channel, height, width, num_features))
1020
+
1021
+ nn.init.kaiming_normal_(self.kernel, mode="fan_in", nonlinearity="linear")
1022
+
1023
+ def forward(self, features):
1024
+ """
1025
+ Forward pass for spatial embedding
1026
+
1027
+ Args:
1028
+ features: Input tensor of shape [B, C, H, W] where B is batch size,
1029
+ C is number of channels, H is height, and W is width
1030
+ Returns:
1031
+ Output tensor of shape [B, C*F] where F is the number of features
1032
+ """
1033
+
1034
+ features_expanded = features.unsqueeze(-1) # [B, C, H, W, 1]
1035
+ kernel_expanded = self.kernel.unsqueeze(0) # [1, C, H, W, F]
1036
+
1037
+ # Element-wise multiplication and spatial reduction
1038
+ output = (features_expanded * kernel_expanded).sum(dim=(2, 3)) # Sum over H,W dimensions
1039
+
1040
+ # Reshape to combine channel and feature dimensions
1041
+ output = output.view(output.size(0), -1) # [B, C*F]
1042
+
1043
+ return output
1044
+
1045
+
1046
+ class RescaleFromTanh(Transform):
1047
+ def __init__(self, low: float = -1, high: float = 1):
1048
+ super().__init__()
1049
+
1050
+ self.low = low
1051
+
1052
+ self.high = high
1053
+
1054
+ def _call(self, x):
1055
+ # Rescale from (-1, 1) to (low, high)
1056
+
1057
+ return 0.5 * (x + 1.0) * (self.high - self.low) + self.low
1058
+
1059
+ def _inverse(self, y):
1060
+ # Rescale from (low, high) back to (-1, 1)
1061
+
1062
+ return 2.0 * (y - self.low) / (self.high - self.low) - 1.0
1063
+
1064
+ def log_abs_det_jacobian(self, x, y):
1065
+ # log|d(rescale)/dx| = sum(log(0.5 * (high - low)))
1066
+
1067
+ scale = 0.5 * (self.high - self.low)
1068
+
1069
+ return torch.sum(torch.log(scale), dim=-1)
1070
+
1071
+
1072
+ class TanhMultivariateNormalDiag(TransformedDistribution):
1073
+ def __init__(self, loc, scale_diag, low=None, high=None):
1074
+ base_dist = MultivariateNormal(loc, torch.diag_embed(scale_diag))
1075
+
1076
+ transforms = [TanhTransform(cache_size=1)]
1077
+
1078
+ if low is not None and high is not None:
1079
+ low = torch.as_tensor(low)
1080
+
1081
+ high = torch.as_tensor(high)
1082
+
1083
+ transforms.insert(0, RescaleFromTanh(low, high))
1084
+
1085
+ super().__init__(base_dist, transforms)
1086
+
1087
+ def mode(self):
1088
+ # Mode is mean of base distribution, passed through transforms
1089
+
1090
+ x = self.base_dist.mean
1091
+
1092
+ for transform in self.transforms:
1093
+ x = transform(x)
1094
+
1095
+ return x
1096
+
1097
+ def stddev(self):
1098
+ std = self.base_dist.stddev
1099
+
1100
+ x = std
1101
+
1102
+ for transform in self.transforms:
1103
+ x = transform(x)
1104
+
1105
+ return x
1106
+
1107
+
1108
+ def _convert_normalization_params_to_tensor(normalization_params: dict) -> dict:
1109
+ converted_params = {}
1110
+ for outer_key, inner_dict in normalization_params.items():
1111
+ converted_params[outer_key] = {}
1112
+ for key, value in inner_dict.items():
1113
+ converted_params[outer_key][key] = torch.tensor(value)
1114
+ if "image" in outer_key:
1115
+ converted_params[outer_key][key] = converted_params[outer_key][key].view(3, 1, 1)
1116
+
1117
+ return converted_params
tools/lerobot_v21_runtime/src/lerobot/policies/sac/reward_model/configuration_classifier.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # !/usr/bin/env python
2
+
3
+ # Copyright 2025 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
+ from dataclasses import dataclass, field
17
+
18
+ from lerobot.configs.policies import PreTrainedConfig
19
+ from lerobot.configs.types import NormalizationMode
20
+ from lerobot.optim.optimizers import AdamWConfig, OptimizerConfig
21
+ from lerobot.optim.schedulers import LRSchedulerConfig
22
+
23
+
24
+ @PreTrainedConfig.register_subclass(name="reward_classifier")
25
+ @dataclass
26
+ class RewardClassifierConfig(PreTrainedConfig):
27
+ """Configuration for the Reward Classifier model."""
28
+
29
+ name: str = "reward_classifier"
30
+ num_classes: int = 2
31
+ hidden_dim: int = 256
32
+ latent_dim: int = 256
33
+ image_embedding_pooling_dim: int = 8
34
+ dropout_rate: float = 0.1
35
+ model_name: str = "helper2424/resnet10"
36
+ device: str = "cpu"
37
+ model_type: str = "cnn" # "transformer" or "cnn"
38
+ num_cameras: int = 2
39
+ learning_rate: float = 1e-4
40
+ weight_decay: float = 0.01
41
+ grad_clip_norm: float = 1.0
42
+ normalization_mapping: dict[str, NormalizationMode] = field(
43
+ default_factory=lambda: {
44
+ "VISUAL": NormalizationMode.MEAN_STD,
45
+ }
46
+ )
47
+
48
+ @property
49
+ def observation_delta_indices(self) -> list | None:
50
+ return None
51
+
52
+ @property
53
+ def action_delta_indices(self) -> list | None:
54
+ return None
55
+
56
+ @property
57
+ def reward_delta_indices(self) -> list | None:
58
+ return None
59
+
60
+ def get_optimizer_preset(self) -> OptimizerConfig:
61
+ return AdamWConfig(
62
+ lr=self.learning_rate,
63
+ weight_decay=self.weight_decay,
64
+ grad_clip_norm=self.grad_clip_norm,
65
+ )
66
+
67
+ def get_scheduler_preset(self) -> LRSchedulerConfig | None:
68
+ return None
69
+
70
+ def validate_features(self) -> None:
71
+ """Validate feature configurations."""
72
+ has_image = any(key.startswith("observation.image") for key in self.input_features)
73
+ if not has_image:
74
+ raise ValueError(
75
+ "You must provide an image observation (key starting with 'observation.image') in the input features"
76
+ )
tools/lerobot_v21_runtime/src/lerobot/policies/sac/reward_model/modeling_classifier.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # !/usr/bin/env python
2
+
3
+ # Copyright 2025 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
+
19
+ import torch
20
+ from torch import Tensor, nn
21
+
22
+ from lerobot.constants import OBS_IMAGE, REWARD
23
+ from lerobot.policies.normalize import Normalize, Unnormalize
24
+ from lerobot.policies.pretrained import PreTrainedPolicy
25
+ from lerobot.policies.sac.reward_model.configuration_classifier import RewardClassifierConfig
26
+
27
+
28
+ class ClassifierOutput:
29
+ """Wrapper for classifier outputs with additional metadata."""
30
+
31
+ def __init__(
32
+ self,
33
+ logits: Tensor,
34
+ probabilities: Tensor | None = None,
35
+ hidden_states: Tensor | None = None,
36
+ ):
37
+ self.logits = logits
38
+ self.probabilities = probabilities
39
+ self.hidden_states = hidden_states
40
+
41
+ def __repr__(self):
42
+ return (
43
+ f"ClassifierOutput(logits={self.logits}, "
44
+ f"probabilities={self.probabilities}, "
45
+ f"hidden_states={self.hidden_states})"
46
+ )
47
+
48
+
49
+ class SpatialLearnedEmbeddings(nn.Module):
50
+ def __init__(self, height, width, channel, num_features=8):
51
+ """
52
+ PyTorch implementation of learned spatial embeddings
53
+
54
+ Args:
55
+ height: Spatial height of input features
56
+ width: Spatial width of input features
57
+ channel: Number of input channels
58
+ num_features: Number of output embedding dimensions
59
+ """
60
+ super().__init__()
61
+ self.height = height
62
+ self.width = width
63
+ self.channel = channel
64
+ self.num_features = num_features
65
+
66
+ self.kernel = nn.Parameter(torch.empty(channel, height, width, num_features))
67
+
68
+ nn.init.kaiming_normal_(self.kernel, mode="fan_in", nonlinearity="linear")
69
+
70
+ def forward(self, features):
71
+ """
72
+ Forward pass for spatial embedding
73
+
74
+ Args:
75
+ features: Input tensor of shape [B, H, W, C] or [H, W, C] if no batch
76
+ Returns:
77
+ Output tensor of shape [B, C*F] or [C*F] if no batch
78
+ """
79
+
80
+ features = features.last_hidden_state
81
+
82
+ original_shape = features.shape
83
+ if features.dim() == 3:
84
+ features = features.unsqueeze(0) # Add batch dim
85
+
86
+ features_expanded = features.unsqueeze(-1) # [B, H, W, C, 1]
87
+ kernel_expanded = self.kernel.unsqueeze(0) # [1, H, W, C, F]
88
+
89
+ # Element-wise multiplication and spatial reduction
90
+ output = (features_expanded * kernel_expanded).sum(dim=(2, 3)) # Sum H,W
91
+
92
+ # Reshape to combine channel and feature dimensions
93
+ output = output.view(output.size(0), -1) # [B, C*F]
94
+
95
+ # Remove batch dim
96
+ if len(original_shape) == 3:
97
+ output = output.squeeze(0)
98
+
99
+ return output
100
+
101
+
102
+ class Classifier(PreTrainedPolicy):
103
+ """Image classifier built on top of a pre-trained encoder."""
104
+
105
+ name = "reward_classifier"
106
+ config_class = RewardClassifierConfig
107
+
108
+ def __init__(
109
+ self,
110
+ config: RewardClassifierConfig,
111
+ dataset_stats: dict[str, dict[str, Tensor]] | None = None,
112
+ ):
113
+ from transformers import AutoModel
114
+
115
+ super().__init__(config)
116
+ self.config = config
117
+
118
+ # Initialize normalization (standardized with the policy framework)
119
+ self.normalize_inputs = Normalize(config.input_features, config.normalization_mapping, dataset_stats)
120
+ self.normalize_targets = Normalize(
121
+ config.output_features, config.normalization_mapping, dataset_stats
122
+ )
123
+ self.unnormalize_outputs = Unnormalize(
124
+ config.output_features, config.normalization_mapping, dataset_stats
125
+ )
126
+
127
+ # Set up encoder
128
+ encoder = AutoModel.from_pretrained(self.config.model_name, trust_remote_code=True)
129
+ # Extract vision model if we're given a multimodal model
130
+ if hasattr(encoder, "vision_model"):
131
+ logging.info("Multimodal model detected - using vision encoder only")
132
+ self.encoder = encoder.vision_model
133
+ self.vision_config = encoder.config.vision_config
134
+ else:
135
+ self.encoder = encoder
136
+ self.vision_config = getattr(encoder, "config", None)
137
+
138
+ # Model type from config
139
+ self.is_cnn = self.config.model_type == "cnn"
140
+
141
+ # For CNNs, initialize backbone
142
+ if self.is_cnn:
143
+ self._setup_cnn_backbone()
144
+
145
+ self._freeze_encoder()
146
+
147
+ # Extract image keys from input_features
148
+ self.image_keys = [
149
+ key.replace(".", "_") for key in config.input_features if key.startswith(OBS_IMAGE)
150
+ ]
151
+
152
+ if self.is_cnn:
153
+ self.encoders = nn.ModuleDict()
154
+ for image_key in self.image_keys:
155
+ encoder = self._create_single_encoder()
156
+ self.encoders[image_key] = encoder
157
+
158
+ self._build_classifier_head()
159
+
160
+ def _setup_cnn_backbone(self):
161
+ """Set up CNN encoder"""
162
+ if hasattr(self.encoder, "fc"):
163
+ self.feature_dim = self.encoder.fc.in_features
164
+ self.encoder = nn.Sequential(*list(self.encoder.children())[:-1])
165
+ elif hasattr(self.encoder.config, "hidden_sizes"):
166
+ self.feature_dim = self.encoder.config.hidden_sizes[-1] # Last channel dimension
167
+ else:
168
+ raise ValueError("Unsupported CNN architecture")
169
+
170
+ def _freeze_encoder(self) -> None:
171
+ """Freeze the encoder parameters."""
172
+ for param in self.encoder.parameters():
173
+ param.requires_grad = False
174
+
175
+ def _create_single_encoder(self):
176
+ encoder = nn.Sequential(
177
+ self.encoder,
178
+ SpatialLearnedEmbeddings(
179
+ height=4,
180
+ width=4,
181
+ channel=self.feature_dim,
182
+ num_features=self.config.image_embedding_pooling_dim,
183
+ ),
184
+ nn.Dropout(self.config.dropout_rate),
185
+ nn.Linear(self.feature_dim * self.config.image_embedding_pooling_dim, self.config.latent_dim),
186
+ nn.LayerNorm(self.config.latent_dim),
187
+ nn.Tanh(),
188
+ )
189
+
190
+ return encoder
191
+
192
+ def _build_classifier_head(self) -> None:
193
+ """Initialize the classifier head architecture."""
194
+ # Get input dimension based on model type
195
+ if self.is_cnn:
196
+ input_dim = self.config.latent_dim
197
+ else: # Transformer models
198
+ if hasattr(self.encoder.config, "hidden_size"):
199
+ input_dim = self.encoder.config.hidden_size
200
+ else:
201
+ raise ValueError("Unsupported transformer architecture since hidden_size is not found")
202
+
203
+ self.classifier_head = nn.Sequential(
204
+ nn.Linear(input_dim * self.config.num_cameras, self.config.hidden_dim),
205
+ nn.Dropout(self.config.dropout_rate),
206
+ nn.LayerNorm(self.config.hidden_dim),
207
+ nn.ReLU(),
208
+ nn.Linear(
209
+ self.config.hidden_dim,
210
+ 1 if self.config.num_classes == 2 else self.config.num_classes,
211
+ ),
212
+ )
213
+
214
+ def _get_encoder_output(self, x: torch.Tensor, image_key: str) -> torch.Tensor:
215
+ """Extract the appropriate output from the encoder."""
216
+ with torch.no_grad():
217
+ if self.is_cnn:
218
+ # The HF ResNet applies pooling internally
219
+ outputs = self.encoders[image_key](x)
220
+ return outputs
221
+ else: # Transformer models
222
+ outputs = self.encoder(x)
223
+ return outputs.last_hidden_state[:, 0, :]
224
+
225
+ def extract_images_and_labels(self, batch: dict[str, Tensor]) -> tuple[list, Tensor]:
226
+ """Extract image tensors and label tensors from batch."""
227
+ # Check for both OBS_IMAGE and OBS_IMAGES prefixes
228
+ images = [batch[key] for key in self.config.input_features if key.startswith(OBS_IMAGE)]
229
+ labels = batch[REWARD]
230
+
231
+ return images, labels
232
+
233
+ def predict(self, xs: list) -> ClassifierOutput:
234
+ """Forward pass of the classifier for inference."""
235
+ encoder_outputs = torch.hstack(
236
+ [self._get_encoder_output(x, img_key) for x, img_key in zip(xs, self.image_keys, strict=True)]
237
+ )
238
+ logits = self.classifier_head(encoder_outputs)
239
+
240
+ if self.config.num_classes == 2:
241
+ logits = logits.squeeze(-1)
242
+ probabilities = torch.sigmoid(logits)
243
+ else:
244
+ probabilities = torch.softmax(logits, dim=-1)
245
+
246
+ return ClassifierOutput(logits=logits, probabilities=probabilities, hidden_states=encoder_outputs)
247
+
248
+ def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, dict[str, Tensor]]:
249
+ """Standard forward pass for training compatible with train.py."""
250
+ # Normalize inputs if needed
251
+ batch = self.normalize_inputs(batch)
252
+ batch = self.normalize_targets(batch)
253
+
254
+ # Extract images and labels
255
+ images, labels = self.extract_images_and_labels(batch)
256
+
257
+ # Get predictions
258
+ outputs = self.predict(images)
259
+
260
+ # Calculate loss
261
+ if self.config.num_classes == 2:
262
+ # Binary classification
263
+ loss = nn.functional.binary_cross_entropy_with_logits(outputs.logits, labels)
264
+ predictions = (torch.sigmoid(outputs.logits) > 0.5).float()
265
+ else:
266
+ # Multi-class classification
267
+ loss = nn.functional.cross_entropy(outputs.logits, labels.long())
268
+ predictions = torch.argmax(outputs.logits, dim=1)
269
+
270
+ # Calculate accuracy for logging
271
+ correct = (predictions == labels).sum().item()
272
+ total = labels.size(0)
273
+ accuracy = 100 * correct / total
274
+
275
+ # Return loss and metrics for logging
276
+ output_dict = {
277
+ "accuracy": accuracy,
278
+ "correct": correct,
279
+ "total": total,
280
+ }
281
+
282
+ return loss, output_dict
283
+
284
+ def predict_reward(self, batch, threshold=0.5):
285
+ """Eval method. Returns predicted reward with the decision threshold as argument."""
286
+ # Check for both OBS_IMAGE and OBS_IMAGES prefixes
287
+ batch = self.normalize_inputs(batch)
288
+ batch = self.normalize_targets(batch)
289
+
290
+ # Extract images from batch dict
291
+ images = [batch[key] for key in self.config.input_features if key.startswith(OBS_IMAGE)]
292
+
293
+ if self.config.num_classes == 2:
294
+ probs = self.predict(images).probabilities
295
+ logging.debug(f"Predicted reward images: {probs}")
296
+ return (probs > threshold).float()
297
+ else:
298
+ return torch.argmax(self.predict(images).probabilities, dim=1)
299
+
300
+ def get_optim_params(self):
301
+ """Return optimizer parameters for the policy."""
302
+ return self.parameters()
303
+
304
+ def select_action(self, batch: dict[str, Tensor]) -> Tensor:
305
+ """
306
+ This method is required by PreTrainedPolicy but not used for reward classifiers.
307
+ The reward classifier is not an actor and does not select actions.
308
+ """
309
+ raise NotImplementedError("Reward classifiers do not select actions")
310
+
311
+ def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor:
312
+ """
313
+ This method is required by PreTrainedPolicy but not used for reward classifiers.
314
+ The reward classifier is not an actor and does not produce action chunks.
315
+ """
316
+ raise NotImplementedError("Reward classifiers do not predict action chunks")
317
+
318
+ def reset(self):
319
+ """
320
+ This method is required by PreTrainedPolicy but not used for reward classifiers.
321
+ The reward classifier is not an actor and does not select actions.
322
+ """
323
+ pass
tools/lerobot_v21_runtime/src/lerobot/policies/smolvla/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ ../../../../docs/source/policy_smolvla_README.md
tools/lerobot_v21_runtime/src/lerobot/policies/smolvla/configuration_smolvla.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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 dataclasses import dataclass, field
16
+
17
+ from lerobot.configs.policies import PreTrainedConfig
18
+ from lerobot.configs.types import FeatureType, NormalizationMode, PolicyFeature
19
+ from lerobot.optim.optimizers import AdamWConfig
20
+ from lerobot.optim.schedulers import (
21
+ CosineDecayWithWarmupSchedulerConfig,
22
+ )
23
+
24
+
25
+ @PreTrainedConfig.register_subclass("smolvla")
26
+ @dataclass
27
+ class SmolVLAConfig(PreTrainedConfig):
28
+ # Input / output structure.
29
+ n_obs_steps: int = 1
30
+ chunk_size: int = 50
31
+ n_action_steps: int = 50
32
+
33
+ normalization_mapping: dict[str, NormalizationMode] = field(
34
+ default_factory=lambda: {
35
+ "VISUAL": NormalizationMode.IDENTITY,
36
+ "STATE": NormalizationMode.MEAN_STD,
37
+ "ACTION": NormalizationMode.MEAN_STD,
38
+ }
39
+ )
40
+
41
+ # Shorter state and action vectors will be padded
42
+ max_state_dim: int = 32
43
+ max_action_dim: int = 32
44
+
45
+ # Image preprocessing
46
+ resize_imgs_with_padding: tuple[int, int] = (512, 512)
47
+
48
+ # Add empty images. Used by smolvla_aloha_sim which adds the empty
49
+ # left and right wrist cameras in addition to the top camera.
50
+ empty_cameras: int = 0
51
+
52
+ # Converts the joint and gripper values from the standard Aloha space to
53
+ # the space used by the pi internal runtime which was used to train the base model.
54
+ adapt_to_pi_aloha: bool = False
55
+
56
+ # Converts joint dimensions to deltas with respect to the current state before passing to the model.
57
+ # Gripper dimensions will remain in absolute values.
58
+ use_delta_joint_actions_aloha: bool = False
59
+
60
+ # Tokenizer
61
+ tokenizer_max_length: int = 48
62
+
63
+ # Decoding
64
+ num_steps: int = 10
65
+
66
+ # Attention utils
67
+ use_cache: bool = True
68
+
69
+ # Finetuning settings
70
+ freeze_vision_encoder: bool = True
71
+ train_expert_only: bool = True
72
+ train_state_proj: bool = True
73
+
74
+ # Training presets
75
+ optimizer_lr: float = 1e-4
76
+ optimizer_betas: tuple[float, float] = (0.9, 0.95)
77
+ optimizer_eps: float = 1e-8
78
+ optimizer_weight_decay: float = 1e-10
79
+ optimizer_grad_clip_norm: float = 10
80
+
81
+ scheduler_warmup_steps: int = 1_000
82
+ scheduler_decay_steps: int = 30_000
83
+ scheduler_decay_lr: float = 2.5e-6
84
+
85
+ vlm_model_name: str = "HuggingFaceTB/SmolVLM2-500M-Video-Instruct" # Select the VLM backbone.
86
+ load_vlm_weights: bool = False # Set to True in case of training the expert from scratch. True when init from pretrained SmolVLA weights
87
+
88
+ add_image_special_tokens: bool = False # Whether to use special image tokens around image features.
89
+
90
+ attention_mode: str = "cross_attn"
91
+
92
+ prefix_length: int = -1
93
+
94
+ pad_language_to: str = "longest" # "max_length"
95
+
96
+ num_expert_layers: int = -1 # Less or equal to 0 is the default where the action expert has the same number of layers of VLM. Otherwise the expert have less layers.
97
+ num_vlm_layers: int = 16 # Number of layers used in the VLM (first num_vlm_layers layers)
98
+ self_attn_every_n_layers: int = 2 # Interleave SA layers each self_attn_every_n_layers
99
+ expert_width_multiplier: float = 0.75 # The action expert hidden size (wrt to the VLM)
100
+
101
+ min_period: float = 4e-3 # sensitivity range for the timestep used in sine-cosine positional encoding
102
+ max_period: float = 4.0
103
+
104
+ def __post_init__(self):
105
+ super().__post_init__()
106
+
107
+ """Input validation (not exhaustive)."""
108
+ if self.n_action_steps > self.chunk_size:
109
+ raise ValueError(
110
+ f"The chunk size is the upper bound for the number of action steps per model invocation. Got "
111
+ f"{self.n_action_steps} for `n_action_steps` and {self.chunk_size} for `chunk_size`."
112
+ )
113
+ if self.use_delta_joint_actions_aloha:
114
+ raise NotImplementedError(
115
+ "`use_delta_joint_actions_aloha` is used by smolvla for aloha real models. It is not ported yet in LeRobot."
116
+ )
117
+
118
+ def validate_features(self) -> None:
119
+ for i in range(self.empty_cameras):
120
+ key = f"observation.images.empty_camera_{i}"
121
+ empty_camera = PolicyFeature(
122
+ type=FeatureType.VISUAL,
123
+ shape=(3, 480, 640),
124
+ )
125
+ self.input_features[key] = empty_camera
126
+
127
+ def get_optimizer_preset(self) -> AdamWConfig:
128
+ return AdamWConfig(
129
+ lr=self.optimizer_lr,
130
+ betas=self.optimizer_betas,
131
+ eps=self.optimizer_eps,
132
+ weight_decay=self.optimizer_weight_decay,
133
+ grad_clip_norm=self.optimizer_grad_clip_norm,
134
+ )
135
+
136
+ def get_scheduler_preset(self):
137
+ return CosineDecayWithWarmupSchedulerConfig(
138
+ peak_lr=self.optimizer_lr,
139
+ decay_lr=self.scheduler_decay_lr,
140
+ num_warmup_steps=self.scheduler_warmup_steps,
141
+ num_decay_steps=self.scheduler_decay_steps,
142
+ )
143
+
144
+ @property
145
+ def observation_delta_indices(self) -> list:
146
+ return [0]
147
+
148
+ @property
149
+ def action_delta_indices(self) -> list:
150
+ return list(range(self.chunk_size))
151
+
152
+ @property
153
+ def reward_delta_indices(self) -> None:
154
+ return None
tools/lerobot_v21_runtime/src/lerobot/policies/smolvla/modeling_smolvla.py ADDED
@@ -0,0 +1,941 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2025 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
+ """
18
+ SmolVLA:
19
+
20
+ [Paper](https://huggingface.co/papers/2506.01844)
21
+
22
+ Designed by Hugging Face.
23
+
24
+ Install smolvla extra dependencies:
25
+ ```bash
26
+ pip install -e ".[smolvla]"
27
+ ```
28
+
29
+ Example of finetuning the smolvla pretrained model (`smolvla_base`):
30
+ ```bash
31
+ python -m lerobot.scripts.train \
32
+ --policy.path=lerobot/smolvla_base \
33
+ --dataset.repo_id=danaaubakirova/svla_so100_task1_v3 \
34
+ --batch_size=64 \
35
+ --steps=200000
36
+ ```
37
+
38
+ Example of finetuning a smolVLA. SmolVLA is composed of a pretrained VLM,
39
+ and an action expert.
40
+ ```bash
41
+ python -m lerobot.scripts.train \
42
+ --policy.type=smolvla \
43
+ --dataset.repo_id=danaaubakirova/svla_so100_task1_v3 \
44
+ --batch_size=64 \
45
+ --steps=200000
46
+ ```
47
+
48
+ Example of using the smolvla pretrained model outside LeRobot training framework:
49
+ ```python
50
+ policy = SmolVLAPolicy.from_pretrained("lerobot/smolvla_base")
51
+ ```
52
+
53
+ """
54
+
55
+ import math
56
+ import os
57
+ import re
58
+ from collections import deque
59
+
60
+ import safetensors
61
+ import torch
62
+ import torch.nn.functional as F # noqa: N812
63
+ from torch import Tensor, nn
64
+ from transformers import AutoProcessor
65
+
66
+ from lerobot.constants import ACTION, OBS_STATE
67
+ from lerobot.policies.normalize import (
68
+ Normalize,
69
+ Unnormalize,
70
+ )
71
+ from lerobot.policies.pretrained import PreTrainedPolicy
72
+ from lerobot.policies.smolvla.configuration_smolvla import SmolVLAConfig
73
+ from lerobot.policies.smolvla.smolvlm_with_expert import SmolVLMWithExpertModel
74
+ from lerobot.policies.utils import (
75
+ populate_queues,
76
+ )
77
+ from lerobot.utils.utils import get_safe_dtype
78
+
79
+ # Matches ".soNNN", optionally followed by "-something", up to the "_buffer_" marker
80
+ _VARIANT_RE = re.compile(r"\.so\d+(?:-[\w]+)?_buffer_")
81
+
82
+
83
+ def canonicalise(k: str) -> str:
84
+ """
85
+ Remove dataset-variant markers like '.so100-blue_' or '.so100_' from a
86
+ normalisation-buffer key.
87
+ """
88
+ return _VARIANT_RE.sub(".buffer_", k)
89
+
90
+
91
+ def standardise_state_dict(
92
+ checkpoint: dict[str, torch.Tensor], ref_keys: set[str], *, verbose: bool = True
93
+ ) -> tuple[dict[str, torch.Tensor], list[str]]:
94
+ """
95
+ • Re-keys `checkpoint ` so that every entry matches the *reference* key set.
96
+ • If several variant keys collapse to the same canonical name we keep the
97
+ first one and log the collision.
98
+ • Returns the new dict + a list of entries that could not be matched.
99
+ """
100
+ out, collisions, unmatched = {}, {}, []
101
+
102
+ for k, v in checkpoint.items():
103
+ canon = canonicalise(k)
104
+ if canon in ref_keys:
105
+ if canon in out: # duplicate after collapsing
106
+ collisions.setdefault(canon, []).append(k)
107
+ else:
108
+ out[canon] = v
109
+ else:
110
+ unmatched.append(k)
111
+
112
+ if verbose:
113
+ for canon, variants in collisions.items():
114
+ print(f"[standardise_state_dict] '{canon}' ← {variants}")
115
+ if unmatched:
116
+ print(f"[standardise_state_dict] kept {len(unmatched)} unmatched keys")
117
+
118
+ out.update({k: checkpoint[k] for k in unmatched})
119
+ return out, unmatched
120
+
121
+
122
+ def rename_checkpoint_keys(checkpoint: dict, rename_str: str):
123
+ """
124
+ Renames keys in a checkpoint dictionary based on the given rename string.
125
+
126
+ Args:
127
+ checkpoint (dict): The checkpoint dictionary.
128
+ rename_str (str): A string specifying key mappings in the format "old1//new1,old2//new2".
129
+
130
+ Returns:
131
+ dict: The modified checkpoint with renamed keys.
132
+ """
133
+
134
+ rename_dict = dict(pair.split("//") for pair in rename_str.split(","))
135
+
136
+ new_checkpoint = {}
137
+ for k, v in checkpoint.items():
138
+ for old_key, new_key in rename_dict.items():
139
+ if old_key in k:
140
+ k = k.replace(old_key, new_key)
141
+ new_checkpoint[k] = v
142
+ return new_checkpoint
143
+
144
+
145
+ def load_smolvla(
146
+ model: torch.nn.Module,
147
+ filename: str | os.PathLike,
148
+ *,
149
+ device: str = "cpu",
150
+ checkpoint_keys_mapping: str = "",
151
+ ) -> torch.nn.Module:
152
+ state_dict = safetensors.torch.load_file(filename, device=device)
153
+
154
+ # Optional user-supplied renames (e.g. "model._orig_mod.//model.")
155
+ if checkpoint_keys_mapping and "//" in checkpoint_keys_mapping:
156
+ state_dict = rename_checkpoint_keys(state_dict, checkpoint_keys_mapping)
157
+
158
+ state_dict, _ = standardise_state_dict(state_dict, set(model.state_dict().keys()))
159
+
160
+ # HACK(aliberts): to not overwrite normalization parameters as they should come from the dataset
161
+ norm_keys = ("normalize_inputs", "normalize_targets", "unnormalize_outputs")
162
+ state_dict = {k: v for k, v in state_dict.items() if not k.startswith(norm_keys)}
163
+
164
+ missing, unexpected = model.load_state_dict(state_dict, strict=False)
165
+
166
+ if not all(key.startswith(norm_keys) for key in missing) or unexpected:
167
+ raise RuntimeError(
168
+ "SmolVLA %d missing / %d unexpected keys",
169
+ len(missing),
170
+ len(unexpected),
171
+ )
172
+
173
+ return model
174
+
175
+
176
+ def create_sinusoidal_pos_embedding(
177
+ time: torch.tensor, dimension: int, min_period: float, max_period: float, device="cpu"
178
+ ) -> Tensor:
179
+ """Computes sine-cosine positional embedding vectors for scalar positions."""
180
+ if dimension % 2 != 0:
181
+ raise ValueError(f"dimension ({dimension}) must be divisible by 2")
182
+
183
+ if time.ndim != 1:
184
+ raise ValueError("The time tensor is expected to be of shape `(batch_size, )`.")
185
+
186
+ dtype = get_safe_dtype(torch.float64, device.type)
187
+ fraction = torch.linspace(0.0, 1.0, dimension // 2, dtype=dtype, device=device)
188
+ period = min_period * (max_period / min_period) ** fraction
189
+
190
+ # Compute the outer product
191
+ scaling_factor = 1.0 / period * 2 * math.pi
192
+ sin_input = scaling_factor[None, :] * time[:, None]
193
+ pos_emb = torch.cat([torch.sin(sin_input), torch.cos(sin_input)], dim=1)
194
+ return pos_emb
195
+
196
+
197
+ def make_att_2d_masks(pad_masks, att_masks):
198
+ """Copied from big_vision.
199
+
200
+ Tokens can attend to valid inputs tokens which have a cumulative mask_ar
201
+ smaller or equal to theirs. This way `mask_ar` int[B, N] can be used to
202
+ setup several types of attention, for example:
203
+
204
+ [[1 1 1 1 1 1]]: pure causal attention.
205
+
206
+ [[0 0 0 1 1 1]]: prefix-lm attention. The first 3 tokens can attend between
207
+ themselves and the last 3 tokens have a causal attention. The first
208
+ entry could also be a 1 without changing behaviour.
209
+
210
+ [[1 0 1 0 1 0 0 1 0 0]]: causal attention between 4 blocks. Tokens of a
211
+ block can attend all previous blocks and all tokens on the same block.
212
+
213
+ Args:
214
+ input_mask: bool[B, N] true if its part of the input, false if padding.
215
+ mask_ar: int32[B, N] mask that's 1 where previous tokens cannot depend on
216
+ it and 0 where it shares the same attention mask as the previous token.
217
+ """
218
+ if att_masks.ndim != 2:
219
+ raise ValueError(att_masks.ndim)
220
+ if pad_masks.ndim != 2:
221
+ raise ValueError(pad_masks.ndim)
222
+
223
+ cumsum = torch.cumsum(att_masks, dim=1)
224
+ att_2d_masks = cumsum[:, None, :] <= cumsum[:, :, None]
225
+ pad_2d_masks = pad_masks[:, None, :] * pad_masks[:, :, None]
226
+ att_2d_masks = att_2d_masks & pad_2d_masks
227
+ return att_2d_masks
228
+
229
+
230
+ def resize_with_pad(img, width, height, pad_value=-1):
231
+ # assume no-op when width height fits already
232
+ if img.ndim != 4:
233
+ raise ValueError(f"(b,c,h,w) expected, but {img.shape}")
234
+
235
+ cur_height, cur_width = img.shape[2:]
236
+
237
+ ratio = max(cur_width / width, cur_height / height)
238
+ resized_height = int(cur_height / ratio)
239
+ resized_width = int(cur_width / ratio)
240
+ resized_img = F.interpolate(
241
+ img, size=(resized_height, resized_width), mode="bilinear", align_corners=False
242
+ )
243
+
244
+ pad_height = max(0, int(height - resized_height))
245
+ pad_width = max(0, int(width - resized_width))
246
+
247
+ # pad on left and top of image
248
+ padded_img = F.pad(resized_img, (pad_width, 0, pad_height, 0), value=pad_value)
249
+ return padded_img
250
+
251
+
252
+ def pad_vector(vector, new_dim):
253
+ """Can be (batch_size x sequence_length x features_dimension)
254
+ or (batch_size x features_dimension)
255
+ """
256
+ if vector.shape[-1] == new_dim:
257
+ return vector
258
+ shape = list(vector.shape)
259
+ current_dim = shape[-1]
260
+ shape[-1] = new_dim
261
+ new_vector = torch.zeros(*shape, dtype=vector.dtype, device=vector.device)
262
+ new_vector[..., :current_dim] = vector
263
+ return new_vector
264
+
265
+
266
+ def normalize(x, min_val, max_val):
267
+ return (x - min_val) / (max_val - min_val)
268
+
269
+
270
+ def unnormalize(x, min_val, max_val):
271
+ return x * (max_val - min_val) + min_val
272
+
273
+
274
+ def safe_arcsin(value):
275
+ # This ensures that the input stays within
276
+ # [−1,1] to avoid invalid values for arcsin
277
+ return torch.arcsin(torch.clamp(value, -1.0, 1.0))
278
+
279
+
280
+ def aloha_gripper_to_angular(value):
281
+ # Aloha transforms the gripper positions into a linear space. The following code
282
+ # reverses this transformation to be consistent with smolvla which is pretrained in
283
+ # angular space.
284
+ #
285
+ # These values are coming from the Aloha code:
286
+ # PUPPET_GRIPPER_POSITION_OPEN, PUPPET_GRIPPER_POSITION_CLOSED
287
+ value = unnormalize(value, min_val=0.01844, max_val=0.05800)
288
+
289
+ # This is the inverse of the angular to linear transformation inside the Interbotix code.
290
+ def linear_to_radian(linear_position, arm_length, horn_radius):
291
+ value = (horn_radius**2 + linear_position**2 - arm_length**2) / (2 * horn_radius * linear_position)
292
+ return safe_arcsin(value)
293
+
294
+ # The constants are taken from the Interbotix code.
295
+ value = linear_to_radian(value, arm_length=0.036, horn_radius=0.022)
296
+
297
+ # Normalize to [0, 1].
298
+ # The values 0.4 and 1.5 were measured on an actual Trossen robot.
299
+ return normalize(value, min_val=0.4, max_val=1.5)
300
+
301
+
302
+ def aloha_gripper_from_angular(value):
303
+ # Convert from the gripper position used by smolvla to the gripper position that is used by Aloha.
304
+ # Note that the units are still angular but the range is different.
305
+
306
+ # The values 0.4 and 1.5 were measured on an actual Trossen robot.
307
+ value = unnormalize(value, min_val=0.4, max_val=1.5)
308
+
309
+ # These values are coming from the Aloha code:
310
+ # PUPPET_GRIPPER_JOINT_OPEN, PUPPET_GRIPPER_JOINT_CLOSE
311
+ return normalize(value, min_val=-0.6213, max_val=1.4910)
312
+
313
+
314
+ def aloha_gripper_from_angular_inv(value):
315
+ # Directly inverts the gripper_from_angular function.
316
+ value = unnormalize(value, min_val=-0.6213, max_val=1.4910)
317
+ return normalize(value, min_val=0.4, max_val=1.5)
318
+
319
+
320
+ class SmolVLAPolicy(PreTrainedPolicy):
321
+ """Wrapper class around VLAFlowMatching model to train and run inference within LeRobot."""
322
+
323
+ config_class = SmolVLAConfig
324
+ name = "smolvla"
325
+
326
+ def __init__(
327
+ self,
328
+ config: SmolVLAConfig,
329
+ dataset_stats: dict[str, dict[str, Tensor]] | None = None,
330
+ ):
331
+ """
332
+ Args:
333
+ config: Policy configuration class instance or None, in which case the default instantiation of
334
+ the configuration class is used.
335
+ dataset_stats: Dataset statistics to be used for normalization. If not passed here, it is expected
336
+ that they will be passed with a call to `load_state_dict` before the policy is used.
337
+ """
338
+
339
+ super().__init__(config)
340
+ config.validate_features()
341
+ self.config = config
342
+ self.normalize_inputs = Normalize(config.input_features, config.normalization_mapping, dataset_stats)
343
+ self.normalize_targets = Normalize(
344
+ config.output_features, config.normalization_mapping, dataset_stats
345
+ )
346
+ self.unnormalize_outputs = Unnormalize(
347
+ config.output_features, config.normalization_mapping, dataset_stats
348
+ )
349
+
350
+ self.language_tokenizer = AutoProcessor.from_pretrained(self.config.vlm_model_name).tokenizer
351
+ self.model = VLAFlowMatching(config)
352
+ self.reset()
353
+
354
+ def reset(self):
355
+ """This should be called whenever the environment is reset."""
356
+ self._queues = {
357
+ ACTION: deque(maxlen=self.config.n_action_steps),
358
+ }
359
+
360
+ # HACK(aliberts, danaaubakirova): we overwrite this classmethod here to fix smolVLA-specific issues
361
+ @classmethod
362
+ def _load_as_safetensor(
363
+ cls,
364
+ model: "SmolVLAPolicy",
365
+ model_file: str,
366
+ map_location: str,
367
+ strict: bool,
368
+ ):
369
+ safetensors.torch.load_model(model, model_file, strict=strict, device=map_location)
370
+ return load_smolvla(
371
+ model,
372
+ model_file,
373
+ device=map_location,
374
+ checkpoint_keys_mapping="model._orig_mod.//model.",
375
+ )
376
+
377
+ def get_optim_params(self) -> dict:
378
+ return self.parameters()
379
+
380
+ def _get_action_chunk(self, batch: dict[str, Tensor], noise: Tensor | None = None) -> Tensor:
381
+ # TODO: Check if this for loop is needed.
382
+ # Context: In fact, self.queues contains only ACTION field, and in inference, we don't have action in the batch
383
+ # In the case of offline inference, we have the action in the batch
384
+ # that why without the k != ACTION check, it will raise an error because we are trying to stack
385
+ # on an empty container.
386
+ for k in batch:
387
+ if k in self._queues and k != ACTION:
388
+ batch[k] = torch.stack(list(self._queues[k]), dim=1)
389
+
390
+ images, img_masks = self.prepare_images(batch)
391
+ state = self.prepare_state(batch)
392
+ lang_tokens, lang_masks = self.prepare_language(batch)
393
+
394
+ actions = self.model.sample_actions(images, img_masks, lang_tokens, lang_masks, state, noise=noise)
395
+
396
+ # Unpad actions
397
+ original_action_dim = self.config.action_feature.shape[0]
398
+ actions = actions[:, :, :original_action_dim]
399
+
400
+ actions = self.unnormalize_outputs({ACTION: actions})[ACTION]
401
+
402
+ if self.config.adapt_to_pi_aloha:
403
+ actions = self._pi_aloha_encode_actions(actions)
404
+
405
+ return actions
406
+
407
+ def _prepare_batch(self, batch: dict[str, Tensor]) -> dict[str, Tensor]:
408
+ if self.config.adapt_to_pi_aloha:
409
+ batch[OBS_STATE] = self._pi_aloha_decode_state(batch[OBS_STATE])
410
+
411
+ batch = self.normalize_inputs(batch)
412
+
413
+ return batch
414
+
415
+ @torch.no_grad()
416
+ def predict_action_chunk(self, batch: dict[str, Tensor], noise: Tensor | None = None) -> Tensor:
417
+ self.eval()
418
+
419
+ batch = self._prepare_batch(batch)
420
+ self._queues = populate_queues(self._queues, batch, exclude_keys=[ACTION])
421
+
422
+ actions = self._get_action_chunk(batch, noise)
423
+ return actions
424
+
425
+ @torch.no_grad()
426
+ def select_action(self, batch: dict[str, Tensor], noise: Tensor | None = None) -> Tensor:
427
+ """Select a single action given environment observations.
428
+
429
+ This method wraps `select_actions` in order to return one action at a time for execution in the
430
+ environment. It works by managing the actions in a queue and only calling `select_actions` when the
431
+ queue is empty.
432
+ """
433
+ self.eval()
434
+ batch = self._prepare_batch(batch)
435
+ self._queues = populate_queues(self._queues, batch, exclude_keys=[ACTION])
436
+
437
+ # Action queue logic for n_action_steps > 1. When the action_queue is depleted, populate it by
438
+ # querying the policy.
439
+ if len(self._queues[ACTION]) == 0:
440
+ actions = self._get_action_chunk(batch, noise)
441
+
442
+ # `self.predict_action_chunk` returns a (batch_size, n_action_steps, action_dim) tensor, but the queue
443
+ # effectively has shape (n_action_steps, batch_size, *), hence the transpose.
444
+ self._queues[ACTION].extend(actions.transpose(0, 1)[: self.config.n_action_steps])
445
+
446
+ return self._queues[ACTION].popleft()
447
+
448
+ def forward(self, batch: dict[str, Tensor], noise=None, time=None) -> dict[str, Tensor]:
449
+ """Do a full training forward pass to compute the loss"""
450
+ if self.config.adapt_to_pi_aloha:
451
+ batch[OBS_STATE] = self._pi_aloha_decode_state(batch[OBS_STATE])
452
+ batch[ACTION] = self._pi_aloha_encode_actions_inv(batch[ACTION])
453
+ batch = self.normalize_inputs(batch)
454
+ batch = self.normalize_targets(batch)
455
+ images, img_masks = self.prepare_images(batch)
456
+ state = self.prepare_state(batch)
457
+ lang_tokens, lang_masks = self.prepare_language(batch)
458
+ actions = self.prepare_action(batch)
459
+ actions_is_pad = batch.get("actions_id_pad")
460
+ loss_dict = {}
461
+ losses = self.model.forward(images, img_masks, lang_tokens, lang_masks, state, actions, noise, time)
462
+ loss_dict["losses_after_forward"] = losses.clone()
463
+
464
+ if actions_is_pad is not None:
465
+ in_episode_bound = ~actions_is_pad
466
+ losses = losses * in_episode_bound.unsqueeze(-1)
467
+ loss_dict["losses_after_in_ep_bound"] = losses.clone()
468
+
469
+ # Remove padding
470
+ losses = losses[:, :, : self.config.max_action_dim]
471
+ loss_dict["losses_after_rm_padding"] = losses.clone()
472
+
473
+ # For backward pass
474
+ loss = losses.mean()
475
+ # For backward pass
476
+ loss_dict["loss"] = loss.item()
477
+ return loss, loss_dict
478
+
479
+ def prepare_images(self, batch):
480
+ """Apply SmolVLA preprocessing to the images, like resizing to 224x224 and padding to keep aspect ratio, and
481
+ convert pixel range from [0.0, 1.0] to [-1.0, 1.0] as requested by SigLIP.
482
+ """
483
+ images = []
484
+ img_masks = []
485
+ present_img_keys = [key for key in self.config.image_features if key in batch]
486
+ missing_img_keys = [key for key in self.config.image_features if key not in batch]
487
+
488
+ if len(present_img_keys) == 0:
489
+ raise ValueError(
490
+ f"All image features are missing from the batch. At least one expected. (batch: {batch.keys()}) (image_features:{self.config.image_features})"
491
+ )
492
+ # Preprocess image features present in the batch
493
+ for key in present_img_keys:
494
+ img = batch[key][:, -1, :, :, :] if batch[key].ndim == 5 else batch[key]
495
+ if self.config.resize_imgs_with_padding is not None:
496
+ img = resize_with_pad(img, *self.config.resize_imgs_with_padding, pad_value=0)
497
+
498
+ # Normalize from range [0,1] to [-1,1] as expacted by siglip
499
+ img = img * 2.0 - 1.0
500
+
501
+ bsize = img.shape[0]
502
+ device = img.device
503
+ if f"{key}_padding_mask" in batch:
504
+ mask = batch[f"{key}_padding_mask"].bool()
505
+ else:
506
+ mask = torch.ones(bsize, dtype=torch.bool, device=device)
507
+ images.append(img)
508
+ img_masks.append(mask)
509
+
510
+ # Create image features not present in the batch
511
+ # as fully 0 padded images.
512
+ for num_empty_cameras in range(len(missing_img_keys)):
513
+ if num_empty_cameras >= self.config.empty_cameras:
514
+ break
515
+ img = torch.ones_like(img) * -1
516
+ mask = torch.zeros_like(mask)
517
+ images.append(img)
518
+ img_masks.append(mask)
519
+ return images, img_masks
520
+
521
+ def prepare_language(self, batch) -> tuple[Tensor, Tensor]:
522
+ """Tokenize the text input"""
523
+ device = batch[OBS_STATE].device
524
+ tasks = batch["task"]
525
+ if isinstance(tasks, str):
526
+ tasks = [tasks]
527
+
528
+ if len(tasks) == 1:
529
+ tasks = [tasks[0] for _ in range(batch[OBS_STATE].shape[0])]
530
+
531
+ tasks = [task if task.endswith("\n") else f"{task}\n" for task in tasks]
532
+
533
+ tokenized_prompt = self.language_tokenizer.__call__(
534
+ tasks,
535
+ padding=self.config.pad_language_to,
536
+ padding_side="right",
537
+ max_length=self.config.tokenizer_max_length,
538
+ return_tensors="pt",
539
+ )
540
+ lang_tokens = tokenized_prompt["input_ids"].to(device=device)
541
+ lang_masks = tokenized_prompt["attention_mask"].to(device=device, dtype=torch.bool)
542
+
543
+ return lang_tokens, lang_masks
544
+
545
+ def _pi_aloha_decode_state(self, state):
546
+ # Flip the joints.
547
+ for motor_idx in [1, 2, 8, 9]:
548
+ state[:, motor_idx] *= -1
549
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
550
+ for motor_idx in [6, 13]:
551
+ state[:, motor_idx] = aloha_gripper_to_angular(state[:, motor_idx])
552
+ return state
553
+
554
+ def _pi_aloha_encode_actions(self, actions):
555
+ # Flip the joints.
556
+ for motor_idx in [1, 2, 8, 9]:
557
+ actions[:, :, motor_idx] *= -1
558
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
559
+ for motor_idx in [6, 13]:
560
+ actions[:, :, motor_idx] = aloha_gripper_from_angular(actions[:, :, motor_idx])
561
+ return actions
562
+
563
+ def _pi_aloha_encode_actions_inv(self, actions):
564
+ # Flip the joints again.
565
+ for motor_idx in [1, 2, 8, 9]:
566
+ actions[:, :, motor_idx] *= -1
567
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
568
+ for motor_idx in [6, 13]:
569
+ actions[:, :, motor_idx] = aloha_gripper_from_angular_inv(actions[:, :, motor_idx])
570
+ return actions
571
+
572
+ def prepare_state(self, batch):
573
+ """Pad state"""
574
+ state = batch[OBS_STATE][:, -1, :] if batch[OBS_STATE].ndim > 2 else batch[OBS_STATE]
575
+ state = pad_vector(state, self.config.max_state_dim)
576
+ return state
577
+
578
+ def prepare_action(self, batch):
579
+ """Pad action"""
580
+ actions = pad_vector(batch[ACTION], self.config.max_action_dim)
581
+ return actions
582
+
583
+
584
+ def pad_tensor(tensor, max_len, pad_value=0):
585
+ """
586
+ Efficiently pads a tensor along sequence dimension to match max_len.
587
+
588
+ Args:
589
+ tensor (torch.Tensor): Shape (B, L, ...) or (B, L).
590
+ max_len (int): Fixed sequence length.
591
+ pad_value (int/float): Value for padding.
592
+
593
+ Returns:
594
+ torch.Tensor: Shape (B, max_len, ...) or (B, max_len).
595
+ """
596
+ b, d = tensor.shape[:2]
597
+
598
+ # Create a padded tensor of max_len and copy the existing values
599
+ padded_tensor = torch.full(
600
+ (b, max_len, *tensor.shape[2:]), pad_value, dtype=tensor.dtype, device=tensor.device
601
+ )
602
+ padded_tensor[:, :d] = tensor # Efficient in-place copy
603
+
604
+ return padded_tensor
605
+
606
+
607
+ class VLAFlowMatching(nn.Module):
608
+ """
609
+ SmolVLA
610
+
611
+ [Paper]()
612
+
613
+ Designed by Hugging Face.
614
+ ┌──────────────────────────────┐
615
+ │ actions │
616
+ │ ▲ │
617
+ │ ┌─────────┐ ┌─|────┐ │
618
+ │ | │────► │ │ │
619
+ │ | │ kv │ │ │
620
+ │ | │────► │Action│ │
621
+ │ | VLM │cache │Expert│ |
622
+ │ │ │────► | │ │
623
+ │ │ │ │ │ │
624
+ │ └▲──▲───▲─┘ └───▲──┘ |
625
+ │ │ | | │ |
626
+ │ | | | noise │
627
+ │ │ │ state │
628
+ │ │ language tokens │
629
+ │ image(s) │
630
+ └──────────────────────────────┘
631
+ """
632
+
633
+ def __init__(self, config: SmolVLAConfig):
634
+ super().__init__()
635
+ self.config = config
636
+
637
+ self.vlm_with_expert = SmolVLMWithExpertModel(
638
+ model_id=self.config.vlm_model_name,
639
+ freeze_vision_encoder=self.config.freeze_vision_encoder,
640
+ train_expert_only=self.config.train_expert_only,
641
+ load_vlm_weights=self.config.load_vlm_weights,
642
+ attention_mode=self.config.attention_mode,
643
+ num_expert_layers=self.config.num_expert_layers,
644
+ num_vlm_layers=self.config.num_vlm_layers,
645
+ self_attn_every_n_layers=self.config.self_attn_every_n_layers,
646
+ expert_width_multiplier=self.config.expert_width_multiplier,
647
+ )
648
+ self.state_proj = nn.Linear(
649
+ self.config.max_state_dim, self.vlm_with_expert.config.text_config.hidden_size
650
+ )
651
+ self.action_in_proj = nn.Linear(self.config.max_action_dim, self.vlm_with_expert.expert_hidden_size)
652
+ self.action_out_proj = nn.Linear(self.vlm_with_expert.expert_hidden_size, self.config.max_action_dim)
653
+
654
+ self.action_time_mlp_in = nn.Linear(
655
+ self.vlm_with_expert.expert_hidden_size * 2, self.vlm_with_expert.expert_hidden_size
656
+ )
657
+ self.action_time_mlp_out = nn.Linear(
658
+ self.vlm_with_expert.expert_hidden_size, self.vlm_with_expert.expert_hidden_size
659
+ )
660
+
661
+ self.set_requires_grad()
662
+ self.fake_image_token = self.vlm_with_expert.processor.tokenizer.fake_image_token_id
663
+ self.global_image_token = self.vlm_with_expert.processor.tokenizer.global_image_token_id
664
+ self.global_image_start_token = torch.tensor(
665
+ [self.fake_image_token, self.global_image_token], dtype=torch.long
666
+ )
667
+
668
+ self.add_image_special_tokens = self.config.add_image_special_tokens
669
+ self.image_end_token = torch.tensor([self.fake_image_token], dtype=torch.long)
670
+ self.prefix_length = self.config.prefix_length
671
+
672
+ def set_requires_grad(self):
673
+ for params in self.state_proj.parameters():
674
+ params.requires_grad = self.config.train_state_proj
675
+
676
+ def sample_noise(self, shape, device):
677
+ noise = torch.normal(
678
+ mean=0.0,
679
+ std=1.0,
680
+ size=shape,
681
+ dtype=torch.float32,
682
+ device=device,
683
+ )
684
+ return noise
685
+
686
+ def sample_time(self, bsize, device):
687
+ beta_dist = torch.distributions.Beta(concentration1=1.5, concentration0=1.0)
688
+ time_beta = beta_dist.sample((bsize,)).to(device=device, dtype=torch.float32)
689
+ time = time_beta * 0.999 + 0.001
690
+ return time
691
+
692
+ def embed_prefix(
693
+ self, images, img_masks, lang_tokens, lang_masks, state: torch.Tensor = None
694
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
695
+ """Embed images with SigLIP and language tokens with embedding layer to prepare
696
+ for SmolVLM transformer processing.
697
+ """
698
+ embs = []
699
+ pad_masks = []
700
+ att_masks = []
701
+ for _img_idx, (
702
+ img,
703
+ img_mask,
704
+ ) in enumerate(zip(images, img_masks, strict=False)):
705
+ if self.add_image_special_tokens:
706
+ image_start_token = (
707
+ self.vlm_with_expert.embed_language_tokens(
708
+ self.global_image_start_token.to(device=self.vlm_with_expert.vlm.device)
709
+ )
710
+ .unsqueeze(0)
711
+ .expand(img.shape[0], -1, -1)
712
+ )
713
+ image_start_mask = torch.ones_like(
714
+ image_start_token[:, :, 0], dtype=torch.bool, device=image_start_token.device
715
+ )
716
+ att_masks += [0] * (image_start_mask.shape[-1])
717
+ embs.append(image_start_token)
718
+ pad_masks.append(image_start_mask)
719
+
720
+ img_emb = self.vlm_with_expert.embed_image(img)
721
+ img_emb = img_emb
722
+
723
+ # Normalize image embeddings
724
+ img_emb_dim = img_emb.shape[-1]
725
+ img_emb = img_emb * torch.tensor(img_emb_dim**0.5, dtype=img_emb.dtype, device=img_emb.device)
726
+
727
+ bsize, num_img_embs = img_emb.shape[:2]
728
+ img_mask = img_mask[:, None].expand(bsize, num_img_embs)
729
+
730
+ embs.append(img_emb)
731
+ pad_masks.append(img_mask)
732
+
733
+ att_masks += [0] * (num_img_embs)
734
+ if self.add_image_special_tokens:
735
+ image_end_token = (
736
+ self.vlm_with_expert.embed_language_tokens(
737
+ self.image_end_token.to(device=self.vlm_with_expert.vlm.device)
738
+ )
739
+ .unsqueeze(0)
740
+ .expand(img.shape[0], -1, -1)
741
+ )
742
+ image_end_mask = torch.ones_like(
743
+ image_end_token[:, :, 0], dtype=torch.bool, device=image_end_token.device
744
+ )
745
+ embs.append(image_end_token)
746
+ pad_masks.append(image_end_mask)
747
+ att_masks += [0] * (image_end_mask.shape[1])
748
+ lang_emb = self.vlm_with_expert.embed_language_tokens(lang_tokens)
749
+ # Normalize language embeddings
750
+ lang_emb_dim = lang_emb.shape[-1]
751
+ lang_emb = lang_emb * math.sqrt(lang_emb_dim)
752
+
753
+ embs.append(lang_emb)
754
+ pad_masks.append(lang_masks)
755
+
756
+ num_lang_embs = lang_emb.shape[1]
757
+ att_masks += [0] * num_lang_embs
758
+
759
+ state_emb = self.state_proj(state)
760
+ state_emb = state_emb[:, None, :] if state_emb.ndim == 2 else state_emb
761
+ embs.append(state_emb)
762
+ bsize = state_emb.shape[0]
763
+ device = state_emb.device
764
+
765
+ states_seq_len = state_emb.shape[1]
766
+ state_mask = torch.ones(bsize, states_seq_len, dtype=torch.bool, device=device)
767
+ pad_masks.append(state_mask)
768
+
769
+ # Set attention masks so that image and language inputs do not attend to state or actions
770
+ att_masks += [1] * (states_seq_len)
771
+ embs = torch.cat(embs, dim=1)
772
+ pad_masks = torch.cat(pad_masks, dim=1)
773
+ att_masks = torch.tensor(att_masks, dtype=torch.bool, device=pad_masks.device)
774
+ att_masks = att_masks[None, :]
775
+
776
+ seq_len = pad_masks.shape[1]
777
+ if seq_len < self.prefix_length:
778
+ embs = pad_tensor(embs, self.prefix_length, pad_value=0)
779
+ pad_masks = pad_tensor(pad_masks, self.prefix_length, pad_value=0)
780
+ att_masks = pad_tensor(att_masks, self.prefix_length, pad_value=0)
781
+
782
+ att_masks = att_masks.expand(bsize, -1)
783
+
784
+ return embs, pad_masks, att_masks
785
+
786
+ def embed_suffix(self, noisy_actions, timestep):
787
+ """Embed state, noisy_actions, timestep to prepare for Expert Gemma processing."""
788
+ embs = []
789
+ pad_masks = []
790
+ att_masks = []
791
+
792
+ # Fuse timestep + action information using an MLP
793
+ action_emb = self.action_in_proj(noisy_actions)
794
+ device = action_emb.device
795
+ bsize = action_emb.shape[0]
796
+ dtype = action_emb.dtype
797
+ # Embed timestep using sine-cosine positional encoding with sensitivity in the range [0, 1]
798
+ time_emb = create_sinusoidal_pos_embedding(
799
+ timestep,
800
+ self.vlm_with_expert.expert_hidden_size,
801
+ self.config.min_period,
802
+ self.config.max_period,
803
+ device=device,
804
+ )
805
+ time_emb = time_emb.type(dtype=dtype)
806
+
807
+ time_emb = time_emb[:, None, :].expand_as(action_emb)
808
+ action_time_emb = torch.cat([action_emb, time_emb], dim=2)
809
+
810
+ action_time_emb = self.action_time_mlp_in(action_time_emb)
811
+ action_time_emb = F.silu(action_time_emb) # swish == silu
812
+ action_time_emb = self.action_time_mlp_out(action_time_emb)
813
+
814
+ # Add to input tokens
815
+ embs.append(action_time_emb)
816
+
817
+ bsize, action_time_dim = action_time_emb.shape[:2]
818
+ action_time_mask = torch.ones(bsize, action_time_dim, dtype=torch.bool, device=device)
819
+ pad_masks.append(action_time_mask)
820
+
821
+ # Set attention masks so that image, language and state inputs do not attend to action tokens
822
+ att_masks += [1] * self.config.chunk_size
823
+ embs = torch.cat(embs, dim=1)
824
+ pad_masks = torch.cat(pad_masks, dim=1)
825
+ att_masks = torch.tensor(att_masks, dtype=embs.dtype, device=embs.device)
826
+ att_masks = att_masks[None, :].expand(bsize, len(att_masks))
827
+ return embs, pad_masks, att_masks
828
+
829
+ def forward(
830
+ self, images, img_masks, lang_tokens, lang_masks, state, actions, noise=None, time=None
831
+ ) -> Tensor:
832
+ """Do a full training forward pass and compute the loss (batch_size x num_steps x num_motors)"""
833
+ if noise is None:
834
+ noise = self.sample_noise(actions.shape, actions.device)
835
+
836
+ if time is None:
837
+ time = self.sample_time(actions.shape[0], actions.device)
838
+
839
+ time_expanded = time[:, None, None]
840
+ x_t = time_expanded * noise + (1 - time_expanded) * actions
841
+ u_t = noise - actions
842
+ prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(
843
+ images, img_masks, lang_tokens, lang_masks, state=state
844
+ )
845
+ suffix_embs, suffix_pad_masks, suffix_att_masks = self.embed_suffix(x_t, time)
846
+
847
+ pad_masks = torch.cat([prefix_pad_masks, suffix_pad_masks], dim=1)
848
+ att_masks = torch.cat([prefix_att_masks, suffix_att_masks], dim=1)
849
+
850
+ att_2d_masks = make_att_2d_masks(pad_masks, att_masks)
851
+ position_ids = torch.cumsum(pad_masks, dim=1) - 1
852
+ (_, suffix_out), _ = self.vlm_with_expert.forward(
853
+ attention_mask=att_2d_masks,
854
+ position_ids=position_ids,
855
+ past_key_values=None,
856
+ inputs_embeds=[prefix_embs, suffix_embs],
857
+ use_cache=False,
858
+ fill_kv_cache=False,
859
+ )
860
+ suffix_out = suffix_out[:, -self.config.chunk_size :]
861
+ # Original openpi code, upcast attention output
862
+ suffix_out = suffix_out.to(dtype=torch.float32)
863
+ v_t = self.action_out_proj(suffix_out)
864
+ losses = F.mse_loss(u_t, v_t, reduction="none")
865
+ return losses
866
+
867
+ def sample_actions(self, images, img_masks, lang_tokens, lang_masks, state, noise=None) -> Tensor:
868
+ """Do a full inference forward and compute the action (batch_size x num_steps x num_motors)"""
869
+ bsize = state.shape[0]
870
+ device = state.device
871
+
872
+ if noise is None:
873
+ actions_shape = (bsize, self.config.chunk_size, self.config.max_action_dim)
874
+ noise = self.sample_noise(actions_shape, device)
875
+
876
+ prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(
877
+ images, img_masks, lang_tokens, lang_masks, state=state
878
+ )
879
+ prefix_att_2d_masks = make_att_2d_masks(prefix_pad_masks, prefix_att_masks)
880
+ prefix_position_ids = torch.cumsum(prefix_pad_masks, dim=1) - 1
881
+ # Compute image and language key value cache
882
+ _, past_key_values = self.vlm_with_expert.forward(
883
+ attention_mask=prefix_att_2d_masks,
884
+ position_ids=prefix_position_ids,
885
+ past_key_values=None,
886
+ inputs_embeds=[prefix_embs, None],
887
+ use_cache=self.config.use_cache,
888
+ fill_kv_cache=True,
889
+ )
890
+ dt = -1.0 / self.config.num_steps
891
+ dt = torch.tensor(dt, dtype=torch.float32, device=device)
892
+
893
+ x_t = noise
894
+ time = torch.tensor(1.0, dtype=torch.float32, device=device)
895
+ while time >= -dt / 2:
896
+ expanded_time = time.expand(bsize)
897
+ v_t = self.denoise_step(
898
+ prefix_pad_masks,
899
+ past_key_values,
900
+ x_t,
901
+ expanded_time,
902
+ )
903
+ # Euler step
904
+ x_t += dt * v_t
905
+ time += dt
906
+ return x_t
907
+
908
+ def denoise_step(
909
+ self,
910
+ prefix_pad_masks,
911
+ past_key_values,
912
+ x_t,
913
+ timestep,
914
+ ):
915
+ """Apply one denoising step of the noise `x_t` at a given timestep."""
916
+ suffix_embs, suffix_pad_masks, suffix_att_masks = self.embed_suffix(x_t, timestep)
917
+
918
+ suffix_len = suffix_pad_masks.shape[1]
919
+ batch_size = prefix_pad_masks.shape[0]
920
+ prefix_len = prefix_pad_masks.shape[1]
921
+ prefix_pad_2d_masks = prefix_pad_masks[:, None, :].expand(batch_size, suffix_len, prefix_len)
922
+
923
+ suffix_att_2d_masks = make_att_2d_masks(suffix_pad_masks, suffix_att_masks)
924
+
925
+ full_att_2d_masks = torch.cat([prefix_pad_2d_masks, suffix_att_2d_masks], dim=2)
926
+ prefix_offsets = torch.sum(prefix_pad_masks, dim=-1)[:, None]
927
+ position_ids = prefix_offsets + torch.cumsum(suffix_pad_masks, dim=1) - 1
928
+
929
+ outputs_embeds, _ = self.vlm_with_expert.forward(
930
+ attention_mask=full_att_2d_masks,
931
+ position_ids=position_ids,
932
+ past_key_values=past_key_values,
933
+ inputs_embeds=[None, suffix_embs],
934
+ use_cache=self.config.use_cache,
935
+ fill_kv_cache=False,
936
+ )
937
+ suffix_out = outputs_embeds[1]
938
+ suffix_out = suffix_out[:, -self.config.chunk_size :]
939
+ suffix_out = suffix_out.to(dtype=torch.float32)
940
+ v_t = self.action_out_proj(suffix_out)
941
+ return v_t
tools/lerobot_v21_runtime/src/lerobot/policies/smolvla/smolvlm_with_expert.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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
+ import copy
16
+
17
+ import torch
18
+ from torch import nn
19
+ from transformers import (
20
+ AutoConfig,
21
+ AutoModel,
22
+ AutoModelForImageTextToText,
23
+ AutoProcessor,
24
+ SmolVLMForConditionalGeneration,
25
+ )
26
+
27
+
28
+ def apply_rope(x, positions, max_wavelength=10_000):
29
+ """
30
+ Applies RoPE positions [B, L] to x [B, L, H, D].
31
+ """
32
+ d_half = x.shape[-1] // 2
33
+ device = x.device
34
+ dtype = x.dtype
35
+ x = x.to(torch.float32)
36
+
37
+ freq_exponents = (2.0 / x.shape[-1]) * torch.arange(d_half, dtype=torch.float32, device=device)
38
+ timescale = max_wavelength**freq_exponents
39
+ radians = positions[..., None].to(torch.float32) / timescale[None, None, :].to(torch.float32)
40
+
41
+ radians = radians[..., None, :]
42
+
43
+ sin = torch.sin(radians) # .to(dtype=dtype)
44
+ cos = torch.cos(radians) # .to(dtype=dtype)
45
+
46
+ x1, x2 = x.split(d_half, dim=-1)
47
+ res = torch.empty_like(x)
48
+ res[..., :d_half] = x1 * cos - x2 * sin
49
+ res[..., d_half:] = x2 * cos + x1 * sin
50
+
51
+ return res.to(dtype)
52
+
53
+
54
+ def get_intermediate_size(hidden_dim, ffn_dim_multiplier=4, multiple_of=256):
55
+ hidden_dim = int(2 * hidden_dim / 3)
56
+ hidden_dim = int(ffn_dim_multiplier * hidden_dim)
57
+ hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
58
+ return hidden_dim
59
+
60
+
61
+ class SmolVLMWithExpertModel(nn.Module):
62
+ def __init__(
63
+ self,
64
+ model_id: str = "HuggingFaceTB/SmolVLM2-500M-Video-Instruct",
65
+ load_vlm_weights: bool = True,
66
+ train_expert_only: bool = True,
67
+ freeze_vision_encoder: bool = False,
68
+ attention_mode: str = "self_attn",
69
+ num_expert_layers: int = -1,
70
+ num_vlm_layers: int = -1,
71
+ self_attn_every_n_layers: int = -1,
72
+ expert_width_multiplier: float = 0.5,
73
+ ):
74
+ super().__init__()
75
+ if load_vlm_weights:
76
+ print(f"Loading {model_id} weights ...")
77
+ self.vlm = AutoModelForImageTextToText.from_pretrained(
78
+ model_id,
79
+ device_map="auto",
80
+ torch_dtype="bfloat16",
81
+ low_cpu_mem_usage=True,
82
+ )
83
+ config = self.vlm.config
84
+ else:
85
+ config = AutoConfig.from_pretrained(model_id)
86
+ self.vlm = SmolVLMForConditionalGeneration(config=config)
87
+ self.processor = AutoProcessor.from_pretrained(model_id)
88
+ if num_vlm_layers > 0:
89
+ print(f"Reducing the number of VLM layers to {num_vlm_layers} ...")
90
+ self.get_vlm_model().text_model.layers = self.get_vlm_model().text_model.layers[:num_vlm_layers]
91
+ self.num_vlm_layers = len(self.get_vlm_model().text_model.layers)
92
+ self.config = config
93
+ # Smaller lm expert
94
+ lm_expert_config = copy.deepcopy(config.text_config)
95
+ hidden_size = lm_expert_config.hidden_size
96
+ lm_expert_config.hidden_size = int(hidden_size * expert_width_multiplier) # hidden_size // 2
97
+ lm_expert_config.intermediate_size = get_intermediate_size(int(hidden_size * expert_width_multiplier))
98
+ lm_expert_config.num_hidden_layers = self.num_vlm_layers
99
+ if num_expert_layers > 0:
100
+ assert len(self.get_vlm_model().text_model.layers) % num_expert_layers == 0, (
101
+ f"Number of layers in the VLM {len(self.get_vlm_model().text_model.layers)} are not multiple of num_expert_layers {num_expert_layers}"
102
+ )
103
+ lm_expert_config.num_hidden_layers = num_expert_layers
104
+ self.lm_expert = AutoModel.from_config(lm_expert_config)
105
+
106
+ self.num_expert_layers = len(self.lm_expert.layers)
107
+ self.self_attn_every_n_layers = self_attn_every_n_layers
108
+ if "cross" in attention_mode:
109
+ # Reshape qkv projections to have the same input dimension as the vlm
110
+ for layer_idx in range(len(self.lm_expert.layers)):
111
+ if self.self_attn_every_n_layers > 0 and layer_idx % self.self_attn_every_n_layers == 0:
112
+ continue
113
+ self.lm_expert.layers[layer_idx].self_attn.k_proj = nn.Linear(
114
+ config.text_config.num_key_value_heads * config.text_config.head_dim,
115
+ lm_expert_config.num_key_value_heads * lm_expert_config.head_dim,
116
+ bias=lm_expert_config.attention_bias,
117
+ )
118
+ self.lm_expert.layers[layer_idx].self_attn.v_proj = nn.Linear(
119
+ config.text_config.num_key_value_heads * config.text_config.head_dim,
120
+ lm_expert_config.num_key_value_heads * lm_expert_config.head_dim,
121
+ bias=lm_expert_config.attention_bias,
122
+ )
123
+ # Remove unused embed_tokens
124
+ self.lm_expert.embed_tokens = None
125
+
126
+ self.num_attention_heads = self.config.text_config.num_attention_heads
127
+ self.num_key_value_heads = self.config.text_config.num_key_value_heads
128
+
129
+ self.freeze_vision_encoder = freeze_vision_encoder
130
+ self.train_expert_only = train_expert_only
131
+ self.attention_mode = attention_mode
132
+ self.expert_hidden_size = lm_expert_config.hidden_size
133
+ self.set_requires_grad()
134
+
135
+ def get_vlm_model(self):
136
+ return self.vlm.model
137
+
138
+ def set_requires_grad(self):
139
+ if self.freeze_vision_encoder:
140
+ self.get_vlm_model().vision_model.eval()
141
+ for params in self.get_vlm_model().vision_model.parameters():
142
+ params.requires_grad = False
143
+ if self.train_expert_only:
144
+ self.vlm.eval()
145
+ for params in self.vlm.parameters():
146
+ params.requires_grad = False
147
+ else:
148
+ # To avoid unused params issue with distributed training
149
+ last_layers = [self.num_vlm_layers - 1]
150
+ if (
151
+ self.num_vlm_layers != self.num_expert_layers
152
+ and self.num_vlm_layers % self.num_expert_layers == 0
153
+ ):
154
+ last_layers.append(self.num_vlm_layers - 2)
155
+ frozen_layers = [
156
+ "lm_head",
157
+ "text_model.model.norm.weight",
158
+ ]
159
+ for layer in last_layers:
160
+ frozen_layers.append(f"text_model.model.layers.{layer}.")
161
+
162
+ for name, params in self.vlm.named_parameters():
163
+ if any(k in name for k in frozen_layers):
164
+ params.requires_grad = False
165
+ # To avoid unused params issue with distributed training
166
+ for name, params in self.lm_expert.named_parameters():
167
+ if "lm_head" in name:
168
+ params.requires_grad = False
169
+
170
+ def train(self, mode: bool = True):
171
+ super().train(mode)
172
+
173
+ if self.freeze_vision_encoder:
174
+ self.get_vlm_model().vision_model.eval()
175
+
176
+ if self.train_expert_only:
177
+ self.vlm.eval()
178
+
179
+ def embed_image(self, image: torch.Tensor):
180
+ patch_attention_mask = None
181
+ # Get sequence from the vision encoder
182
+ image_hidden_states = (
183
+ self.get_vlm_model()
184
+ .vision_model(
185
+ pixel_values=image.to(dtype=self.get_vlm_model().vision_model.dtype),
186
+ patch_attention_mask=patch_attention_mask,
187
+ )
188
+ .last_hidden_state
189
+ )
190
+ # Modality projection & resampling
191
+ image_hidden_states = self.get_vlm_model().connector(image_hidden_states)
192
+ return image_hidden_states
193
+
194
+ def embed_language_tokens(self, tokens: torch.Tensor):
195
+ return self.get_vlm_model().text_model.get_input_embeddings()(tokens)
196
+
197
+ def forward_attn_layer(
198
+ self,
199
+ model_layers,
200
+ inputs_embeds,
201
+ layer_idx,
202
+ position_ids,
203
+ attention_mask,
204
+ batch_size,
205
+ head_dim,
206
+ use_cache: bool = True,
207
+ fill_kv_cache: bool = True,
208
+ past_key_values=None,
209
+ ) -> list[torch.Tensor]:
210
+ query_states = []
211
+ key_states = []
212
+ value_states = []
213
+ for i, hidden_states in enumerate(inputs_embeds):
214
+ layer = model_layers[i][layer_idx]
215
+ if hidden_states is None or layer is None:
216
+ continue
217
+ hidden_states = layer.input_layernorm(hidden_states)
218
+
219
+ input_shape = hidden_states.shape[:-1]
220
+ hidden_shape = (*input_shape, -1, layer.self_attn.head_dim)
221
+
222
+ hidden_states = hidden_states.to(dtype=layer.self_attn.q_proj.weight.dtype)
223
+ query_state = layer.self_attn.q_proj(hidden_states).view(hidden_shape)
224
+ key_state = layer.self_attn.k_proj(hidden_states).view(hidden_shape)
225
+ value_state = layer.self_attn.v_proj(hidden_states).view(hidden_shape)
226
+
227
+ query_states.append(query_state)
228
+ key_states.append(key_state)
229
+ value_states.append(value_state)
230
+
231
+ # B,L,H,D with L sequence length, H number of heads, D head dim
232
+ # concatenate on the number of embeddings/tokens
233
+ query_states = torch.cat(query_states, dim=1)
234
+ key_states = torch.cat(key_states, dim=1)
235
+ value_states = torch.cat(value_states, dim=1)
236
+ seq_len = query_states.shape[1]
237
+ if seq_len < position_ids.shape[1]:
238
+ _position_ids = position_ids[:, :seq_len]
239
+ _attention_mask = attention_mask[:, :seq_len, :seq_len]
240
+ else:
241
+ _position_ids = position_ids
242
+ _attention_mask = attention_mask
243
+
244
+ attention_mask_ = _attention_mask
245
+ position_ids_ = _position_ids
246
+
247
+ query_states = apply_rope(query_states, position_ids_)
248
+ key_states = apply_rope(key_states, position_ids_)
249
+
250
+ if use_cache and past_key_values is None:
251
+ past_key_values = {}
252
+
253
+ if use_cache:
254
+ if fill_kv_cache:
255
+ past_key_values[layer_idx] = {
256
+ "key_states": key_states,
257
+ "value_states": value_states,
258
+ }
259
+ else:
260
+ # TODO here, some optimization can be done - similar to a `StaticCache` we can declare the `max_len` before.
261
+ # so we create an empty cache, with just one cuda malloc, and if (in autoregressive case) we reach
262
+ # the max len, then we (for instance) double the cache size. This implementation already exists
263
+ # in `transformers`. (molbap)
264
+ key_states = torch.cat([past_key_values[layer_idx]["key_states"], key_states], dim=1)
265
+ value_states = torch.cat([past_key_values[layer_idx]["value_states"], value_states], dim=1)
266
+
267
+ attention_interface = self.get_attention_interface()
268
+
269
+ att_output = attention_interface(
270
+ attention_mask_, batch_size, head_dim, query_states, key_states, value_states
271
+ )
272
+ return [att_output], past_key_values
273
+
274
+ def forward_cross_attn_layer(
275
+ self,
276
+ model_layers,
277
+ inputs_embeds,
278
+ layer_idx,
279
+ position_ids,
280
+ attention_mask,
281
+ batch_size,
282
+ head_dim,
283
+ use_cache: bool = True,
284
+ fill_kv_cache: bool = True,
285
+ past_key_values=None,
286
+ ) -> list[torch.Tensor]:
287
+ attention_interface = self.get_attention_interface()
288
+
289
+ att_outputs = []
290
+ assert len(inputs_embeds) == 2 or (use_cache and past_key_values is not None and not fill_kv_cache), (
291
+ f"Both len(inputs_embeds) == {len(inputs_embeds)} and past_key_values is {past_key_values}"
292
+ )
293
+
294
+ if len(inputs_embeds) == 2 and not past_key_values:
295
+ # Prefix attention
296
+ seq_len = inputs_embeds[0].shape[1]
297
+ position_id, expert_position_id = position_ids[:, :seq_len], position_ids[:, seq_len:]
298
+ prefix_attention_mask = attention_mask[:, :seq_len, :seq_len]
299
+
300
+ layer = model_layers[0][layer_idx]
301
+
302
+ hidden_states = layer.input_layernorm(inputs_embeds[0])
303
+
304
+ input_shape = hidden_states.shape[:-1]
305
+ hidden_shape = (*input_shape, -1, layer.self_attn.head_dim)
306
+
307
+ hidden_states = hidden_states.to(dtype=layer.self_attn.q_proj.weight.dtype)
308
+ query_state = layer.self_attn.q_proj(hidden_states).view(hidden_shape)
309
+ key_state = layer.self_attn.k_proj(hidden_states).view(hidden_shape)
310
+ value_states = layer.self_attn.v_proj(hidden_states).view(hidden_shape)
311
+
312
+ # B,L,H,D with L sequence length, H number of heads, D head dim
313
+ query_states = apply_rope(query_state, position_id)
314
+ key_states = apply_rope(key_state, position_id)
315
+
316
+ att_output = attention_interface(
317
+ prefix_attention_mask, batch_size, head_dim, query_states, key_states, value_states
318
+ )
319
+ att_outputs.append(att_output)
320
+ else:
321
+ expert_position_id = position_ids
322
+
323
+ if use_cache and past_key_values is None:
324
+ past_key_values = {}
325
+
326
+ if use_cache:
327
+ if fill_kv_cache:
328
+ past_key_values[layer_idx] = {
329
+ "key_states": key_states,
330
+ "value_states": value_states,
331
+ }
332
+ else:
333
+ # TODO here, some optimization can be done - similar to a `StaticCache` we can declare the `max_len` before.
334
+ # so we create an empty cache, with just one cuda malloc, and if (in autoregressive case) we reach
335
+ # the max len, then we (for instance) double the cache size. This implementation already exists
336
+ # in `transformers`. (molbap)
337
+ key_states = past_key_values[layer_idx]["key_states"]
338
+ value_states = past_key_values[layer_idx]["value_states"]
339
+
340
+ # Expert
341
+ expert_layer = model_layers[1][layer_idx]
342
+ if expert_layer is not None:
343
+ expert_hidden_states = expert_layer.input_layernorm(inputs_embeds[1])
344
+
345
+ expert_input_shape = expert_hidden_states.shape[:-1]
346
+ expert_hidden_shape = (*expert_input_shape, -1, expert_layer.self_attn.head_dim)
347
+
348
+ expert_hidden_states = expert_hidden_states.to(dtype=expert_layer.self_attn.q_proj.weight.dtype)
349
+ expert_query_state = expert_layer.self_attn.q_proj(expert_hidden_states).view(expert_hidden_shape)
350
+
351
+ _key_states = key_states.to(dtype=expert_layer.self_attn.k_proj.weight.dtype).view(
352
+ *key_states.shape[:2], -1
353
+ )
354
+ expert_key_states = expert_layer.self_attn.k_proj(_key_states).view(
355
+ *_key_states.shape[:-1], -1, expert_layer.self_attn.head_dim
356
+ ) # k_proj should have same dim as kv
357
+
358
+ _value_states = value_states.to(dtype=expert_layer.self_attn.v_proj.weight.dtype).view(
359
+ *value_states.shape[:2], -1
360
+ )
361
+ expert_value_states = expert_layer.self_attn.v_proj(_value_states).view(
362
+ *_value_states.shape[:-1], -1, expert_layer.self_attn.head_dim
363
+ )
364
+
365
+ expert_position_id = (
366
+ expert_position_id - torch.min(expert_position_id, dim=1, keepdim=True).values
367
+ ) # start from 0
368
+ expert_attention_mask = attention_mask[
369
+ :, -inputs_embeds[1].shape[1] :, : expert_key_states.shape[1] :
370
+ ] # take into account kv
371
+
372
+ expert_query_states = apply_rope(expert_query_state, expert_position_id)
373
+
374
+ att_output = attention_interface(
375
+ expert_attention_mask,
376
+ batch_size,
377
+ head_dim,
378
+ expert_query_states,
379
+ expert_key_states,
380
+ expert_value_states,
381
+ )
382
+ att_outputs.append(att_output)
383
+ else:
384
+ att_outputs.append(None)
385
+
386
+ # att_output = att_output.to(dtype=models[i].dtype)
387
+ return att_outputs, past_key_values
388
+
389
+ def get_model_layers(self, models: list) -> list:
390
+ vlm_layers = []
391
+ expert_layers = []
392
+ multiple_of = self.num_vlm_layers // self.num_expert_layers
393
+ for i in range(self.num_vlm_layers):
394
+ if multiple_of > 0 and i > 0 and i % multiple_of != 0:
395
+ expert_layer = None
396
+ else:
397
+ expert_layer_index = i // multiple_of if multiple_of > 0 else i
398
+ expert_layer = models[1].layers[expert_layer_index]
399
+ vlm_layers.append(models[0].layers[i])
400
+ expert_layers.append(expert_layer)
401
+ return [vlm_layers, expert_layers]
402
+
403
+ def forward(
404
+ self,
405
+ attention_mask: torch.Tensor | None = None,
406
+ position_ids: torch.LongTensor | None = None,
407
+ past_key_values: list[torch.FloatTensor] | None = None,
408
+ inputs_embeds: list[torch.FloatTensor] = None,
409
+ use_cache: bool | None = None,
410
+ fill_kv_cache: bool | None = None,
411
+ ):
412
+ models = [self.get_vlm_model().text_model, self.lm_expert]
413
+ model_layers = self.get_model_layers(models)
414
+ for hidden_states in inputs_embeds:
415
+ # TODO this is very inefficient
416
+ # dtype is always the same, batch size too (if > 1 len)
417
+ # device could be trickier in multi gpu edge cases but that's it
418
+ if hidden_states is None:
419
+ continue
420
+ batch_size = hidden_states.shape[0]
421
+
422
+ # RMSNorm
423
+ num_layers = self.num_vlm_layers
424
+ head_dim = self.vlm.config.text_config.head_dim
425
+ for layer_idx in range(num_layers):
426
+ if (
427
+ fill_kv_cache
428
+ or "cross" not in self.attention_mode
429
+ or (self.self_attn_every_n_layers > 0 and layer_idx % self.self_attn_every_n_layers == 0)
430
+ ):
431
+ att_outputs, past_key_values = self.forward_attn_layer(
432
+ model_layers,
433
+ inputs_embeds,
434
+ layer_idx,
435
+ position_ids,
436
+ attention_mask,
437
+ batch_size,
438
+ head_dim,
439
+ use_cache=use_cache,
440
+ fill_kv_cache=fill_kv_cache,
441
+ past_key_values=past_key_values,
442
+ )
443
+ else:
444
+ att_outputs, past_key_values = self.forward_cross_attn_layer(
445
+ model_layers,
446
+ inputs_embeds,
447
+ layer_idx,
448
+ position_ids,
449
+ attention_mask,
450
+ batch_size,
451
+ head_dim,
452
+ use_cache=use_cache,
453
+ fill_kv_cache=fill_kv_cache,
454
+ past_key_values=past_key_values,
455
+ )
456
+ outputs_embeds = []
457
+ start = 0
458
+ for i, hidden_states in enumerate(inputs_embeds):
459
+ layer = model_layers[i][layer_idx]
460
+ att_output = (
461
+ att_outputs[i] if i < len(att_outputs) else att_outputs[0]
462
+ ) # in case of self_attn
463
+ if hidden_states is not None:
464
+ if layer is None:
465
+ outputs_embeds.append(hidden_states)
466
+ continue
467
+ end = start + hidden_states.shape[1]
468
+
469
+ if att_output.dtype != layer.self_attn.o_proj.weight.dtype:
470
+ att_output = att_output.to(layer.self_attn.o_proj.weight.dtype)
471
+ att_out = att_output[:, start:end]
472
+ out_emb = layer.self_attn.o_proj(att_out)
473
+
474
+ out_emb += hidden_states
475
+ after_first_residual = out_emb.clone()
476
+
477
+ out_emb = layer.post_attention_layernorm(out_emb)
478
+ out_emb = layer.mlp(out_emb)
479
+
480
+ out_emb += after_first_residual
481
+
482
+ outputs_embeds.append(out_emb)
483
+
484
+ start = end if len(att_outputs) == 1 else 0
485
+ else:
486
+ outputs_embeds.append(None)
487
+
488
+ inputs_embeds = outputs_embeds
489
+
490
+ # final norm
491
+ outputs_embeds = []
492
+ for i, hidden_states in enumerate(inputs_embeds):
493
+ if hidden_states is not None:
494
+ out_emb = models[i].norm(hidden_states)
495
+ outputs_embeds.append(out_emb)
496
+ else:
497
+ outputs_embeds.append(None)
498
+ return outputs_embeds, past_key_values
499
+
500
+ def get_attention_interface(self):
501
+ attention_interface = self.eager_attention_forward
502
+ return attention_interface
503
+
504
+ def eager_attention_forward(
505
+ self, attention_mask, batch_size, head_dim, query_states, key_states, value_states
506
+ ):
507
+ num_att_heads = self.num_attention_heads
508
+ num_key_value_heads = self.num_key_value_heads
509
+ num_key_value_groups = num_att_heads // num_key_value_heads
510
+
511
+ sequence_length = key_states.shape[1]
512
+
513
+ key_states = key_states[:, :, :, None, :].expand(
514
+ batch_size, sequence_length, num_key_value_heads, num_key_value_groups, head_dim
515
+ )
516
+ key_states = key_states.reshape(
517
+ batch_size, sequence_length, num_key_value_heads * num_key_value_groups, head_dim
518
+ )
519
+
520
+ value_states = value_states[:, :, :, None, :].expand(
521
+ batch_size, sequence_length, num_key_value_heads, num_key_value_groups, head_dim
522
+ )
523
+ value_states = value_states.reshape(
524
+ batch_size, sequence_length, num_key_value_heads * num_key_value_groups, head_dim
525
+ )
526
+
527
+ # Attention here is upcasted to float32 to match the original eager implementation.
528
+ query_states = query_states.to(dtype=torch.float32)
529
+ key_states = key_states.to(dtype=torch.float32)
530
+
531
+ query_states = query_states.transpose(1, 2)
532
+ key_states = key_states.transpose(1, 2)
533
+
534
+ att_weights = torch.matmul(query_states, key_states.transpose(2, 3))
535
+ att_weights *= head_dim**-0.5
536
+
537
+ att_weights = att_weights.to(dtype=torch.float32)
538
+ big_neg = torch.finfo(att_weights.dtype).min # -2.3819763e38 # See gemma/modules.py
539
+ masked_att_weights = torch.where(attention_mask[:, None, :, :], att_weights, big_neg)
540
+ probs = nn.functional.softmax(masked_att_weights, dim=-1)
541
+ probs = probs.to(dtype=value_states.dtype)
542
+
543
+ att_output = torch.matmul(probs, value_states.permute(0, 2, 1, 3))
544
+
545
+ att_output = att_output.permute(0, 2, 1, 3)
546
+ # we use -1 because sequence length can change
547
+ att_output = att_output.reshape(batch_size, -1, num_key_value_heads * num_key_value_groups * head_dim)
548
+
549
+ return att_output
tools/lerobot_v21_runtime/src/lerobot/policies/tdmpc/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ ../../../../docs/source/policy_tdmpc_README.md
tools/lerobot_v21_runtime/src/lerobot/policies/tdmpc/configuration_tdmpc.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 Nicklas Hansen, Xiaolong Wang, Hao Su,
4
+ # and The HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ from dataclasses import dataclass, field
18
+
19
+ from lerobot.configs.policies import PreTrainedConfig
20
+ from lerobot.configs.types import NormalizationMode
21
+ from lerobot.optim.optimizers import AdamConfig
22
+
23
+
24
+ @PreTrainedConfig.register_subclass("tdmpc")
25
+ @dataclass
26
+ class TDMPCConfig(PreTrainedConfig):
27
+ """Configuration class for TDMPCPolicy.
28
+
29
+ Defaults are configured for training with xarm_lift_medium_replay providing proprioceptive and single
30
+ camera observations.
31
+
32
+ The parameters you will most likely need to change are the ones which depend on the environment / sensors.
33
+ Those are: `input_shapes`, `output_shapes`, and perhaps `max_random_shift_ratio`.
34
+
35
+ Args:
36
+ n_action_repeats: The number of times to repeat the action returned by the planning. (hint: Google
37
+ action repeats in Q-learning or ask your favorite chatbot)
38
+ horizon: Horizon for model predictive control.
39
+ n_action_steps: Number of action steps to take from the plan given by model predictive control. This
40
+ is an alternative to using action repeats. If this is set to more than 1, then we require
41
+ `n_action_repeats == 1`, `use_mpc == True` and `n_action_steps <= horizon`. Note that this
42
+ approach of using multiple steps from the plan is not in the original implementation.
43
+ input_shapes: A dictionary defining the shapes of the input data for the policy. The key represents
44
+ the input data name, and the value is a list indicating the dimensions of the corresponding data.
45
+ For example, "observation.image" refers to an input from a camera with dimensions [3, 96, 96],
46
+ indicating it has three color channels and 96x96 resolution. Importantly, `input_shapes` doesn't
47
+ include batch dimension or temporal dimension.
48
+ output_shapes: A dictionary defining the shapes of the output data for the policy. The key represents
49
+ the output data name, and the value is a list indicating the dimensions of the corresponding data.
50
+ For example, "action" refers to an output shape of [14], indicating 14-dimensional actions.
51
+ Importantly, `output_shapes` doesn't include batch dimension or temporal dimension.
52
+ input_normalization_modes: A dictionary with key representing the modality (e.g. "observation.state"),
53
+ and the value specifies the normalization mode to apply. The two available modes are "mean_std"
54
+ which subtracts the mean and divides by the standard deviation and "min_max" which rescale in a
55
+ [-1, 1] range. Note that here this defaults to None meaning inputs are not normalized. This is to
56
+ match the original implementation.
57
+ output_normalization_modes: Similar dictionary as `normalize_input_modes`, but to unnormalize to the
58
+ original scale. Note that this is also used for normalizing the training targets. NOTE: Clipping
59
+ to [-1, +1] is used during MPPI/CEM. Therefore, it is recommended that you stick with "min_max"
60
+ normalization mode here.
61
+ image_encoder_hidden_dim: Number of channels for the convolutional layers used for image encoding.
62
+ state_encoder_hidden_dim: Hidden dimension for MLP used for state vector encoding.
63
+ latent_dim: Observation's latent embedding dimension.
64
+ q_ensemble_size: Number of Q function estimators to use in an ensemble for uncertainty estimation.
65
+ mlp_dim: Hidden dimension of MLPs used for modelling the dynamics encoder, reward function, policy
66
+ (π), Q ensemble, and V.
67
+ discount: Discount factor (γ) to use for the reinforcement learning formalism.
68
+ use_mpc: Whether to use model predictive control. The alternative is to just sample the policy model
69
+ (π) for each step.
70
+ cem_iterations: Number of iterations for the MPPI/CEM loop in MPC.
71
+ max_std: Maximum standard deviation for actions sampled from the gaussian PDF in CEM.
72
+ min_std: Minimum standard deviation for noise applied to actions sampled from the policy model (π).
73
+ Doubles up as the minimum standard deviation for actions sampled from the gaussian PDF in CEM.
74
+ n_gaussian_samples: Number of samples to draw from the gaussian distribution every CEM iteration. Must
75
+ be non-zero.
76
+ n_pi_samples: Number of samples to draw from the policy / world model rollout every CEM iteration. Can
77
+ be zero.
78
+ uncertainty_regularizer_coeff: Coefficient for the uncertainty regularization used when estimating
79
+ trajectory values (this is the λ coefficient in eqn 4 of FOWM).
80
+ n_elites: The number of elite samples to use for updating the gaussian parameters every CEM iteration.
81
+ elite_weighting_temperature: The temperature to use for softmax weighting (by trajectory value) of the
82
+ elites, when updating the gaussian parameters for CEM.
83
+ gaussian_mean_momentum: Momentum (α) used for EMA updates of the mean parameter μ of the gaussian
84
+ parameters optimized in CEM. Updates are calculated as μ⁻ ← αμ⁻ + (1-α)μ.
85
+ max_random_shift_ratio: Maximum random shift (as a proportion of the image size) to apply to the
86
+ image(s) (in units of pixels) for training-time augmentation. If set to 0, no such augmentation
87
+ is applied. Note that the input images are assumed to be square for this augmentation.
88
+ reward_coeff: Loss weighting coefficient for the reward regression loss.
89
+ expectile_weight: Weighting (τ) used in expectile regression for the state value function (V).
90
+ v_pred < v_target is weighted by τ and v_pred >= v_target is weighted by (1-τ). τ is expected to
91
+ be in [0, 1]. Setting τ closer to 1 results in a more "optimistic" V. This is sensible to do
92
+ because v_target is obtained by evaluating the learned state-action value functions (Q) with
93
+ in-sample actions that may not be always optimal.
94
+ value_coeff: Loss weighting coefficient for both the state-action value (Q) TD loss, and the state
95
+ value (V) expectile regression loss.
96
+ consistency_coeff: Loss weighting coefficient for the consistency loss.
97
+ advantage_scaling: A factor by which the advantages are scaled prior to exponentiation for advantage
98
+ weighted regression of the policy (π) estimator parameters. Note that the exponentiated advantages
99
+ are clamped at 100.0.
100
+ pi_coeff: Loss weighting coefficient for the action regression loss.
101
+ temporal_decay_coeff: Exponential decay coefficient for decaying the loss coefficient for future time-
102
+ steps. Hint: each loss computation involves `horizon` steps worth of actions starting from the
103
+ current time step.
104
+ target_model_momentum: Momentum (α) used for EMA updates of the target models. Updates are calculated
105
+ as ϕ ← αϕ + (1-α)θ where ϕ are the parameters of the target model and θ are the parameters of the
106
+ model being trained.
107
+ """
108
+
109
+ # Input / output structure.
110
+ n_obs_steps: int = 1
111
+ n_action_repeats: int = 2
112
+ horizon: int = 5
113
+ n_action_steps: int = 1
114
+
115
+ normalization_mapping: dict[str, NormalizationMode] = field(
116
+ default_factory=lambda: {
117
+ "VISUAL": NormalizationMode.IDENTITY,
118
+ "STATE": NormalizationMode.IDENTITY,
119
+ "ENV": NormalizationMode.IDENTITY,
120
+ "ACTION": NormalizationMode.MIN_MAX,
121
+ }
122
+ )
123
+
124
+ # Architecture / modeling.
125
+ # Neural networks.
126
+ image_encoder_hidden_dim: int = 32
127
+ state_encoder_hidden_dim: int = 256
128
+ latent_dim: int = 50
129
+ q_ensemble_size: int = 5
130
+ mlp_dim: int = 512
131
+ # Reinforcement learning.
132
+ discount: float = 0.9
133
+
134
+ # Inference.
135
+ use_mpc: bool = True
136
+ cem_iterations: int = 6
137
+ max_std: float = 2.0
138
+ min_std: float = 0.05
139
+ n_gaussian_samples: int = 512
140
+ n_pi_samples: int = 51
141
+ uncertainty_regularizer_coeff: float = 1.0
142
+ n_elites: int = 50
143
+ elite_weighting_temperature: float = 0.5
144
+ gaussian_mean_momentum: float = 0.1
145
+
146
+ # Training and loss computation.
147
+ max_random_shift_ratio: float = 0.0476
148
+ # Loss coefficients.
149
+ reward_coeff: float = 0.5
150
+ expectile_weight: float = 0.9
151
+ value_coeff: float = 0.1
152
+ consistency_coeff: float = 20.0
153
+ advantage_scaling: float = 3.0
154
+ pi_coeff: float = 0.5
155
+ temporal_decay_coeff: float = 0.5
156
+ # Target model.
157
+ target_model_momentum: float = 0.995
158
+
159
+ # Training presets
160
+ optimizer_lr: float = 3e-4
161
+
162
+ def __post_init__(self):
163
+ super().__post_init__()
164
+
165
+ """Input validation (not exhaustive)."""
166
+ if self.n_gaussian_samples <= 0:
167
+ raise ValueError(
168
+ f"The number of gaussian samples for CEM should be non-zero. Got `{self.n_gaussian_samples=}`"
169
+ )
170
+ if self.normalization_mapping["ACTION"] is not NormalizationMode.MIN_MAX:
171
+ raise ValueError(
172
+ "TD-MPC assumes the action space dimensions to all be in [-1, 1]. Therefore it is strongly "
173
+ f"advised that you stick with the default. See {self.__class__.__name__} docstring for more "
174
+ "information."
175
+ )
176
+ if self.n_obs_steps != 1:
177
+ raise ValueError(
178
+ f"Multiple observation steps not handled yet. Got `nobs_steps={self.n_obs_steps}`"
179
+ )
180
+ if self.n_action_steps > 1:
181
+ if self.n_action_repeats != 1:
182
+ raise ValueError(
183
+ "If `n_action_steps > 1`, `n_action_repeats` must be left to its default value of 1."
184
+ )
185
+ if not self.use_mpc:
186
+ raise ValueError("If `n_action_steps > 1`, `use_mpc` must be set to `True`.")
187
+ if self.n_action_steps > self.horizon:
188
+ raise ValueError("`n_action_steps` must be less than or equal to `horizon`.")
189
+
190
+ def get_optimizer_preset(self) -> AdamConfig:
191
+ return AdamConfig(lr=self.optimizer_lr)
192
+
193
+ def get_scheduler_preset(self) -> None:
194
+ return None
195
+
196
+ def validate_features(self) -> None:
197
+ # There should only be one image key.
198
+ if len(self.image_features) > 1:
199
+ raise ValueError(
200
+ f"{self.__class__.__name__} handles at most one image for now. Got image keys {self.image_features}."
201
+ )
202
+
203
+ if len(self.image_features) > 0:
204
+ image_ft = next(iter(self.image_features.values()))
205
+ if image_ft.shape[-2] != image_ft.shape[-1]:
206
+ # TODO(alexander-soare): This limitation is solely because of code in the random shift
207
+ # augmentation. It should be able to be removed.
208
+ raise ValueError(f"Only square images are handled now. Got image shape {image_ft.shape}.")
209
+
210
+ @property
211
+ def observation_delta_indices(self) -> list:
212
+ return list(range(self.horizon + 1))
213
+
214
+ @property
215
+ def action_delta_indices(self) -> list:
216
+ return list(range(self.horizon))
217
+
218
+ @property
219
+ def reward_delta_indices(self) -> None:
220
+ return list(range(self.horizon))
tools/lerobot_v21_runtime/src/lerobot/policies/tdmpc/modeling_tdmpc.py ADDED
@@ -0,0 +1,839 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 Nicklas Hansen, Xiaolong Wang, Hao Su,
4
+ # and The HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """Implementation of Finetuning Offline World Models in the Real World.
18
+
19
+ The comments in this code may sometimes refer to these references:
20
+ TD-MPC paper: Temporal Difference Learning for Model Predictive Control (https://huggingface.co/papers/2203.04955)
21
+ FOWM paper: Finetuning Offline World Models in the Real World (https://huggingface.co/papers/2310.16029)
22
+ """
23
+
24
+ # ruff: noqa: N806
25
+
26
+ from collections import deque
27
+ from collections.abc import Callable
28
+ from copy import deepcopy
29
+ from functools import partial
30
+
31
+ import einops
32
+ import numpy as np
33
+ import torch
34
+ import torch.nn as nn
35
+ import torch.nn.functional as F # noqa: N812
36
+ from torch import Tensor
37
+
38
+ from lerobot.constants import ACTION, OBS_ENV_STATE, OBS_IMAGE, OBS_STATE, REWARD
39
+ from lerobot.policies.normalize import Normalize, Unnormalize
40
+ from lerobot.policies.pretrained import PreTrainedPolicy
41
+ from lerobot.policies.tdmpc.configuration_tdmpc import TDMPCConfig
42
+ from lerobot.policies.utils import get_device_from_parameters, get_output_shape, populate_queues
43
+
44
+
45
+ class TDMPCPolicy(PreTrainedPolicy):
46
+ """Implementation of TD-MPC learning + inference.
47
+
48
+ Please note several warnings for this policy.
49
+ - Evaluation of pretrained weights created with the original FOWM code
50
+ (https://github.com/fyhMer/fowm) works as expected. To be precise: we trained and evaluated a
51
+ model with the FOWM code for the xarm_lift_medium_replay dataset. We ported the weights across
52
+ to LeRobot, and were able to evaluate with the same success metric. BUT, we had to use inter-
53
+ process communication to use the xarm environment from FOWM. This is because our xarm
54
+ environment uses newer dependencies and does not match the environment in FOWM. See
55
+ https://github.com/huggingface/lerobot/pull/103 for implementation details.
56
+ - We have NOT checked that training on LeRobot reproduces the results from FOWM.
57
+ - Nevertheless, we have verified that we can train TD-MPC for PushT. See
58
+ `lerobot/configs/policy/tdmpc_pusht_keypoints.yaml`.
59
+ - Our current xarm datasets were generated using the environment from FOWM. Therefore they do not
60
+ match our xarm environment.
61
+ """
62
+
63
+ config_class = TDMPCConfig
64
+ name = "tdmpc"
65
+
66
+ def __init__(self, config: TDMPCConfig, dataset_stats: dict[str, dict[str, Tensor]] | None = None):
67
+ """
68
+ Args:
69
+ config: Policy configuration class instance or None, in which case the default instantiation of
70
+ the configuration class is used.
71
+ dataset_stats: Dataset statistics to be used for normalization. If not passed here, it is expected
72
+ that they will be passed with a call to `load_state_dict` before the policy is used.
73
+ """
74
+ super().__init__(config)
75
+ config.validate_features()
76
+ self.config = config
77
+
78
+ self.normalize_inputs = Normalize(config.input_features, config.normalization_mapping, dataset_stats)
79
+ self.normalize_targets = Normalize(
80
+ config.output_features, config.normalization_mapping, dataset_stats
81
+ )
82
+ self.unnormalize_outputs = Unnormalize(
83
+ config.output_features, config.normalization_mapping, dataset_stats
84
+ )
85
+
86
+ self.model = TDMPCTOLD(config)
87
+ self.model_target = deepcopy(self.model)
88
+ for param in self.model_target.parameters():
89
+ param.requires_grad = False
90
+
91
+ self.reset()
92
+
93
+ def get_optim_params(self) -> dict:
94
+ return self.parameters()
95
+
96
+ def reset(self):
97
+ """
98
+ Clear observation and action queues. Clear previous means for warm starting of MPPI/CEM. Should be
99
+ called on `env.reset()`
100
+ """
101
+ self._queues = {
102
+ "observation.state": deque(maxlen=1),
103
+ "action": deque(maxlen=max(self.config.n_action_steps, self.config.n_action_repeats)),
104
+ }
105
+ if self.config.image_features:
106
+ self._queues["observation.image"] = deque(maxlen=1)
107
+ if self.config.env_state_feature:
108
+ self._queues["observation.environment_state"] = deque(maxlen=1)
109
+ # Previous mean obtained from the cross-entropy method (CEM) used during MPC. It is used to warm start
110
+ # CEM for the next step.
111
+ self._prev_mean: torch.Tensor | None = None
112
+
113
+ @torch.no_grad()
114
+ def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor:
115
+ """Predict a chunk of actions given environment observations."""
116
+ batch = {key: torch.stack(list(self._queues[key]), dim=1) for key in batch if key in self._queues}
117
+
118
+ # Remove the time dimensions as it is not handled yet.
119
+ for key in batch:
120
+ assert batch[key].shape[1] == 1
121
+ batch[key] = batch[key][:, 0]
122
+
123
+ # NOTE: Order of observations matters here.
124
+ encode_keys = []
125
+ if self.config.image_features:
126
+ encode_keys.append(OBS_IMAGE)
127
+ if self.config.env_state_feature:
128
+ encode_keys.append(OBS_ENV_STATE)
129
+ encode_keys.append(OBS_STATE)
130
+ z = self.model.encode({k: batch[k] for k in encode_keys})
131
+ if self.config.use_mpc: # noqa: SIM108
132
+ actions = self.plan(z) # (horizon, batch, action_dim)
133
+ else:
134
+ # Plan with the policy (π) alone. This always returns one action so unsqueeze to get a
135
+ # sequence dimension like in the MPC branch.
136
+ actions = self.model.pi(z).unsqueeze(0)
137
+
138
+ actions = torch.clamp(actions, -1, +1)
139
+
140
+ actions = self.unnormalize_outputs({ACTION: actions})[ACTION]
141
+ return actions
142
+
143
+ @torch.no_grad()
144
+ def select_action(self, batch: dict[str, Tensor]) -> Tensor:
145
+ """Select a single action given environment observations."""
146
+ # NOTE: for offline evaluation, we have action in the batch, so we need to pop it out
147
+ if ACTION in batch:
148
+ batch.pop(ACTION)
149
+
150
+ batch = self.normalize_inputs(batch)
151
+
152
+ if self.config.image_features:
153
+ batch = dict(batch) # shallow copy so that adding a key doesn't modify the original
154
+ batch[OBS_IMAGE] = batch[next(iter(self.config.image_features))]
155
+
156
+ self._queues = populate_queues(self._queues, batch)
157
+
158
+ # When the action queue is depleted, populate it again by querying the policy.
159
+ if len(self._queues[ACTION]) == 0:
160
+ actions = self.predict_action_chunk(batch)
161
+
162
+ if self.config.n_action_repeats > 1:
163
+ for _ in range(self.config.n_action_repeats):
164
+ self._queues[ACTION].append(actions[0])
165
+ else:
166
+ # Action queue is (n_action_steps, batch_size, action_dim), so we transpose the action.
167
+ self._queues[ACTION].extend(actions[: self.config.n_action_steps])
168
+
169
+ action = self._queues[ACTION].popleft()
170
+ return action
171
+
172
+ @torch.no_grad()
173
+ def plan(self, z: Tensor) -> Tensor:
174
+ """Plan sequence of actions using TD-MPC inference.
175
+
176
+ Args:
177
+ z: (batch, latent_dim,) tensor for the initial state.
178
+ Returns:
179
+ (horizon, batch, action_dim,) tensor for the planned trajectory of actions.
180
+ """
181
+ device = get_device_from_parameters(self)
182
+
183
+ batch_size = z.shape[0]
184
+
185
+ # Sample Nπ trajectories from the policy.
186
+ pi_actions = torch.empty(
187
+ self.config.horizon,
188
+ self.config.n_pi_samples,
189
+ batch_size,
190
+ self.config.action_feature.shape[0],
191
+ device=device,
192
+ )
193
+ if self.config.n_pi_samples > 0:
194
+ _z = einops.repeat(z, "b d -> n b d", n=self.config.n_pi_samples)
195
+ for t in range(self.config.horizon):
196
+ # Note: Adding a small amount of noise here doesn't hurt during inference and may even be
197
+ # helpful for CEM.
198
+ pi_actions[t] = self.model.pi(_z, self.config.min_std)
199
+ _z = self.model.latent_dynamics(_z, pi_actions[t])
200
+
201
+ # In the CEM loop we will need this for a call to estimate_value with the gaussian sampled
202
+ # trajectories.
203
+ z = einops.repeat(z, "b d -> n b d", n=self.config.n_gaussian_samples + self.config.n_pi_samples)
204
+
205
+ # Model Predictive Path Integral (MPPI) with the cross-entropy method (CEM) as the optimization
206
+ # algorithm.
207
+ # The initial mean and standard deviation for the cross-entropy method (CEM).
208
+ mean = torch.zeros(
209
+ self.config.horizon, batch_size, self.config.action_feature.shape[0], device=device
210
+ )
211
+ # Maybe warm start CEM with the mean from the previous step.
212
+ if self._prev_mean is not None:
213
+ mean[:-1] = self._prev_mean[1:]
214
+ std = self.config.max_std * torch.ones_like(mean)
215
+
216
+ for _ in range(self.config.cem_iterations):
217
+ # Randomly sample action trajectories for the gaussian distribution.
218
+ std_normal_noise = torch.randn(
219
+ self.config.horizon,
220
+ self.config.n_gaussian_samples,
221
+ batch_size,
222
+ self.config.action_feature.shape[0],
223
+ device=std.device,
224
+ )
225
+ gaussian_actions = torch.clamp(mean.unsqueeze(1) + std.unsqueeze(1) * std_normal_noise, -1, 1)
226
+
227
+ # Compute elite actions.
228
+ actions = torch.cat([gaussian_actions, pi_actions], dim=1)
229
+ value = self.estimate_value(z, actions).nan_to_num_(0)
230
+ elite_idxs = torch.topk(value, self.config.n_elites, dim=0).indices # (n_elites, batch)
231
+ elite_value = value.take_along_dim(elite_idxs, dim=0) # (n_elites, batch)
232
+ # (horizon, n_elites, batch, action_dim)
233
+ elite_actions = actions.take_along_dim(einops.rearrange(elite_idxs, "n b -> 1 n b 1"), dim=1)
234
+
235
+ # Update gaussian PDF parameters to be the (weighted) mean and standard deviation of the elites.
236
+ max_value = elite_value.max(0, keepdim=True)[0] # (1, batch)
237
+ # The weighting is a softmax over trajectory values. Note that this is not the same as the usage
238
+ # of Ω in eqn 4 of the TD-MPC paper. Instead it is the normalized version of it: s = Ω/ΣΩ. This
239
+ # makes the equations: μ = Σ(s⋅Γ), σ = Σ(s⋅(Γ-μ)²).
240
+ score = torch.exp(self.config.elite_weighting_temperature * (elite_value - max_value))
241
+ score /= score.sum(axis=0, keepdim=True)
242
+ # (horizon, batch, action_dim)
243
+ _mean = torch.sum(einops.rearrange(score, "n b -> n b 1") * elite_actions, dim=1)
244
+ _std = torch.sqrt(
245
+ torch.sum(
246
+ einops.rearrange(score, "n b -> n b 1")
247
+ * (elite_actions - einops.rearrange(_mean, "h b d -> h 1 b d")) ** 2,
248
+ dim=1,
249
+ )
250
+ )
251
+ # Update mean with an exponential moving average, and std with a direct replacement.
252
+ mean = (
253
+ self.config.gaussian_mean_momentum * mean + (1 - self.config.gaussian_mean_momentum) * _mean
254
+ )
255
+ std = _std.clamp_(self.config.min_std, self.config.max_std)
256
+
257
+ # Keep track of the mean for warm-starting subsequent steps.
258
+ self._prev_mean = mean
259
+
260
+ # Randomly select one of the elite actions from the last iteration of MPPI/CEM using the softmax
261
+ # scores from the last iteration.
262
+ actions = elite_actions[:, torch.multinomial(score.T, 1).squeeze(), torch.arange(batch_size)]
263
+
264
+ return actions
265
+
266
+ @torch.no_grad()
267
+ def estimate_value(self, z: Tensor, actions: Tensor):
268
+ """Estimates the value of a trajectory as per eqn 4 of the FOWM paper.
269
+
270
+ Args:
271
+ z: (batch, latent_dim) tensor of initial latent states.
272
+ actions: (horizon, batch, action_dim) tensor of action trajectories.
273
+ Returns:
274
+ (batch,) tensor of values.
275
+ """
276
+ # Initialize return and running discount factor.
277
+ G, running_discount = 0, 1
278
+ # Iterate over the actions in the trajectory to simulate the trajectory using the latent dynamics
279
+ # model. Keep track of return.
280
+ for t in range(actions.shape[0]):
281
+ # We will compute the reward in a moment. First compute the uncertainty regularizer from eqn 4
282
+ # of the FOWM paper.
283
+ if self.config.uncertainty_regularizer_coeff > 0:
284
+ regularization = -(
285
+ self.config.uncertainty_regularizer_coeff * self.model.Qs(z, actions[t]).std(0)
286
+ )
287
+ else:
288
+ regularization = 0
289
+ # Estimate the next state (latent) and reward.
290
+ z, reward = self.model.latent_dynamics_and_reward(z, actions[t])
291
+ # Update the return and running discount.
292
+ G += running_discount * (reward + regularization)
293
+ running_discount *= self.config.discount
294
+ # Add the estimated value of the final state (using the minimum for a conservative estimate).
295
+ # Do so by predicting the next action, then taking a minimum over the ensemble of state-action value
296
+ # estimators.
297
+ # Note: This small amount of added noise seems to help a bit at inference time as observed by success
298
+ # metrics over 50 episodes of xarm_lift_medium_replay.
299
+ next_action = self.model.pi(z, self.config.min_std) # (batch, action_dim)
300
+ terminal_values = self.model.Qs(z, next_action) # (ensemble, batch)
301
+ # Randomly choose 2 of the Qs for terminal value estimation (as in App C. of the FOWM paper).
302
+ if self.config.q_ensemble_size > 2:
303
+ G += (
304
+ running_discount
305
+ * torch.min(terminal_values[torch.randint(0, self.config.q_ensemble_size, size=(2,))], dim=0)[
306
+ 0
307
+ ]
308
+ )
309
+ else:
310
+ G += running_discount * torch.min(terminal_values, dim=0)[0]
311
+ # Finally, also regularize the terminal value.
312
+ if self.config.uncertainty_regularizer_coeff > 0:
313
+ G -= running_discount * self.config.uncertainty_regularizer_coeff * terminal_values.std(0)
314
+ return G
315
+
316
+ def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, dict]:
317
+ """Run the batch through the model and compute the loss.
318
+
319
+ Returns a dictionary with loss as a tensor, and other information as native floats.
320
+ """
321
+ device = get_device_from_parameters(self)
322
+
323
+ batch = self.normalize_inputs(batch)
324
+ if self.config.image_features:
325
+ batch = dict(batch) # shallow copy so that adding a key doesn't modify the original
326
+ batch[OBS_IMAGE] = batch[next(iter(self.config.image_features))]
327
+ batch = self.normalize_targets(batch)
328
+
329
+ info = {}
330
+
331
+ # (b, t) -> (t, b)
332
+ for key in batch:
333
+ if isinstance(batch[key], torch.Tensor) and batch[key].ndim > 1:
334
+ batch[key] = batch[key].transpose(1, 0)
335
+
336
+ action = batch[ACTION] # (t, b, action_dim)
337
+ reward = batch[REWARD] # (t, b)
338
+ observations = {k: v for k, v in batch.items() if k.startswith("observation.")}
339
+
340
+ # Apply random image augmentations.
341
+ if self.config.image_features and self.config.max_random_shift_ratio > 0:
342
+ observations[OBS_IMAGE] = flatten_forward_unflatten(
343
+ partial(random_shifts_aug, max_random_shift_ratio=self.config.max_random_shift_ratio),
344
+ observations[OBS_IMAGE],
345
+ )
346
+
347
+ # Get the current observation for predicting trajectories, and all future observations for use in
348
+ # the latent consistency loss and TD loss.
349
+ current_observation, next_observations = {}, {}
350
+ for k in observations:
351
+ current_observation[k] = observations[k][0]
352
+ next_observations[k] = observations[k][1:]
353
+ horizon, batch_size = next_observations[
354
+ OBS_IMAGE if self.config.image_features else OBS_ENV_STATE
355
+ ].shape[:2]
356
+
357
+ # Run latent rollout using the latent dynamics model and policy model.
358
+ # Note this has shape `horizon+1` because there are `horizon` actions and a current `z`. Each action
359
+ # gives us a next `z`.
360
+ batch_size = batch["index"].shape[0]
361
+ z_preds = torch.empty(horizon + 1, batch_size, self.config.latent_dim, device=device)
362
+ z_preds[0] = self.model.encode(current_observation)
363
+ reward_preds = torch.empty_like(reward, device=device)
364
+ for t in range(horizon):
365
+ z_preds[t + 1], reward_preds[t] = self.model.latent_dynamics_and_reward(z_preds[t], action[t])
366
+
367
+ # Compute Q and V value predictions based on the latent rollout.
368
+ q_preds_ensemble = self.model.Qs(z_preds[:-1], action) # (ensemble, horizon, batch)
369
+ v_preds = self.model.V(z_preds[:-1])
370
+ info.update({"Q": q_preds_ensemble.mean().item(), "V": v_preds.mean().item()})
371
+
372
+ # Compute various targets with stopgrad.
373
+ with torch.no_grad():
374
+ # Latent state consistency targets.
375
+ z_targets = self.model_target.encode(next_observations)
376
+ # State-action value targets (or TD targets) as in eqn 3 of the FOWM. Unlike TD-MPC which uses the
377
+ # learned state-action value function in conjunction with the learned policy: Q(z, π(z)), FOWM
378
+ # uses a learned state value function: V(z). This means the TD targets only depend on in-sample
379
+ # actions (not actions estimated by π).
380
+ # Note: Here we do not use self.model_target, but self.model. This is to follow the original code
381
+ # and the FOWM paper.
382
+ q_targets = reward + self.config.discount * self.model.V(self.model.encode(next_observations))
383
+ # From eqn 3 of FOWM. These appear as Q(z, a). Here we call them v_targets to emphasize that we
384
+ # are using them to compute loss for V.
385
+ v_targets = self.model_target.Qs(z_preds[:-1].detach(), action, return_min=True)
386
+
387
+ # Compute losses.
388
+ # Exponentially decay the loss weight with respect to the timestep. Steps that are more distant in the
389
+ # future have less impact on the loss. Note: unsqueeze will let us broadcast to (seq, batch).
390
+ temporal_loss_coeffs = torch.pow(
391
+ self.config.temporal_decay_coeff, torch.arange(horizon, device=device)
392
+ ).unsqueeze(-1)
393
+ # Compute consistency loss as MSE loss between latents predicted from the rollout and latents
394
+ # predicted from the (target model's) observation encoder.
395
+ consistency_loss = (
396
+ (
397
+ temporal_loss_coeffs
398
+ * F.mse_loss(z_preds[1:], z_targets, reduction="none").mean(dim=-1)
399
+ # `z_preds` depends on the current observation and the actions.
400
+ * ~batch["observation.state_is_pad"][0]
401
+ * ~batch["action_is_pad"]
402
+ # `z_targets` depends on the next observation.
403
+ * ~batch["observation.state_is_pad"][1:]
404
+ )
405
+ .sum(0)
406
+ .mean()
407
+ )
408
+ # Compute the reward loss as MSE loss between rewards predicted from the rollout and the dataset
409
+ # rewards.
410
+ reward_loss = (
411
+ (
412
+ temporal_loss_coeffs
413
+ * F.mse_loss(reward_preds, reward, reduction="none")
414
+ * ~batch["next.reward_is_pad"]
415
+ # `reward_preds` depends on the current observation and the actions.
416
+ * ~batch["observation.state_is_pad"][0]
417
+ * ~batch["action_is_pad"]
418
+ )
419
+ .sum(0)
420
+ .mean()
421
+ )
422
+ # Compute state-action value loss (TD loss) for all of the Q functions in the ensemble.
423
+ q_value_loss = (
424
+ (
425
+ temporal_loss_coeffs
426
+ * F.mse_loss(
427
+ q_preds_ensemble,
428
+ einops.repeat(q_targets, "t b -> e t b", e=q_preds_ensemble.shape[0]),
429
+ reduction="none",
430
+ ).sum(0) # sum over ensemble
431
+ # `q_preds_ensemble` depends on the first observation and the actions.
432
+ * ~batch["observation.state_is_pad"][0]
433
+ * ~batch["action_is_pad"]
434
+ # q_targets depends on the reward and the next observations.
435
+ * ~batch["next.reward_is_pad"]
436
+ * ~batch["observation.state_is_pad"][1:]
437
+ )
438
+ .sum(0)
439
+ .mean()
440
+ )
441
+ # Compute state value loss as in eqn 3 of FOWM.
442
+ diff = v_targets - v_preds
443
+ # Expectile loss penalizes:
444
+ # - `v_preds < v_targets` with weighting `expectile_weight`
445
+ # - `v_preds >= v_targets` with weighting `1 - expectile_weight`
446
+ raw_v_value_loss = torch.where(
447
+ diff > 0, self.config.expectile_weight, (1 - self.config.expectile_weight)
448
+ ) * (diff**2)
449
+ v_value_loss = (
450
+ (
451
+ temporal_loss_coeffs
452
+ * raw_v_value_loss
453
+ # `v_targets` depends on the first observation and the actions, as does `v_preds`.
454
+ * ~batch["observation.state_is_pad"][0]
455
+ * ~batch["action_is_pad"]
456
+ )
457
+ .sum(0)
458
+ .mean()
459
+ )
460
+
461
+ # Calculate the advantage weighted regression loss for π as detailed in FOWM 3.1.
462
+ # We won't need these gradients again so detach.
463
+ z_preds = z_preds.detach()
464
+ # Use stopgrad for the advantage calculation.
465
+ with torch.no_grad():
466
+ advantage = self.model_target.Qs(z_preds[:-1], action, return_min=True) - self.model.V(
467
+ z_preds[:-1]
468
+ )
469
+ info["advantage"] = advantage[0]
470
+ # (t, b)
471
+ exp_advantage = torch.clamp(torch.exp(advantage * self.config.advantage_scaling), max=100.0)
472
+ action_preds = self.model.pi(z_preds[:-1]) # (t, b, a)
473
+ # Calculate the MSE between the actions and the action predictions.
474
+ # Note: FOWM's original code calculates the log probability (wrt to a unit standard deviation
475
+ # gaussian) and sums over the action dimension. Computing the (negative) log probability amounts to
476
+ # multiplying the MSE by 0.5 and adding a constant offset (the log(2*pi)/2 term, times the action
477
+ # dimension). Here we drop the constant offset as it doesn't change the optimization step, and we drop
478
+ # the 0.5 as we instead make a configuration parameter for it (see below where we compute the total
479
+ # loss).
480
+ mse = F.mse_loss(action_preds, action, reduction="none").sum(-1) # (t, b)
481
+ # NOTE: The original implementation does not take the sum over the temporal dimension like with the
482
+ # other losses.
483
+ # TODO(alexander-soare): Take the sum over the temporal dimension and check that training still works
484
+ # as well as expected.
485
+ pi_loss = (
486
+ exp_advantage
487
+ * mse
488
+ * temporal_loss_coeffs
489
+ # `action_preds` depends on the first observation and the actions.
490
+ * ~batch["observation.state_is_pad"][0]
491
+ * ~batch["action_is_pad"]
492
+ ).mean()
493
+
494
+ loss = (
495
+ self.config.consistency_coeff * consistency_loss
496
+ + self.config.reward_coeff * reward_loss
497
+ + self.config.value_coeff * q_value_loss
498
+ + self.config.value_coeff * v_value_loss
499
+ + self.config.pi_coeff * pi_loss
500
+ )
501
+
502
+ info.update(
503
+ {
504
+ "consistency_loss": consistency_loss.item(),
505
+ "reward_loss": reward_loss.item(),
506
+ "Q_value_loss": q_value_loss.item(),
507
+ "V_value_loss": v_value_loss.item(),
508
+ "pi_loss": pi_loss.item(),
509
+ "sum_loss": loss.item() * self.config.horizon,
510
+ }
511
+ )
512
+
513
+ # Undo (b, t) -> (t, b).
514
+ for key in batch:
515
+ if isinstance(batch[key], torch.Tensor) and batch[key].ndim > 1:
516
+ batch[key] = batch[key].transpose(1, 0)
517
+
518
+ return loss, info
519
+
520
+ def update(self):
521
+ """Update the target model's parameters with an EMA step."""
522
+ # Note a minor variation with respect to the original FOWM code. Here they do this based on an EMA
523
+ # update frequency parameter which is set to 2 (every 2 steps an update is done). To simplify the code
524
+ # we update every step and adjust the decay parameter `alpha` accordingly (0.99 -> 0.995)
525
+ update_ema_parameters(self.model_target, self.model, self.config.target_model_momentum)
526
+
527
+
528
+ class TDMPCTOLD(nn.Module):
529
+ """Task-Oriented Latent Dynamics (TOLD) model used in TD-MPC."""
530
+
531
+ def __init__(self, config: TDMPCConfig):
532
+ super().__init__()
533
+ self.config = config
534
+ self._encoder = TDMPCObservationEncoder(config)
535
+ self._dynamics = nn.Sequential(
536
+ nn.Linear(config.latent_dim + config.action_feature.shape[0], config.mlp_dim),
537
+ nn.LayerNorm(config.mlp_dim),
538
+ nn.Mish(),
539
+ nn.Linear(config.mlp_dim, config.mlp_dim),
540
+ nn.LayerNorm(config.mlp_dim),
541
+ nn.Mish(),
542
+ nn.Linear(config.mlp_dim, config.latent_dim),
543
+ nn.LayerNorm(config.latent_dim),
544
+ nn.Sigmoid(),
545
+ )
546
+ self._reward = nn.Sequential(
547
+ nn.Linear(config.latent_dim + config.action_feature.shape[0], config.mlp_dim),
548
+ nn.LayerNorm(config.mlp_dim),
549
+ nn.Mish(),
550
+ nn.Linear(config.mlp_dim, config.mlp_dim),
551
+ nn.LayerNorm(config.mlp_dim),
552
+ nn.Mish(),
553
+ nn.Linear(config.mlp_dim, 1),
554
+ )
555
+ self._pi = nn.Sequential(
556
+ nn.Linear(config.latent_dim, config.mlp_dim),
557
+ nn.LayerNorm(config.mlp_dim),
558
+ nn.Mish(),
559
+ nn.Linear(config.mlp_dim, config.mlp_dim),
560
+ nn.LayerNorm(config.mlp_dim),
561
+ nn.Mish(),
562
+ nn.Linear(config.mlp_dim, config.action_feature.shape[0]),
563
+ )
564
+ self._Qs = nn.ModuleList(
565
+ [
566
+ nn.Sequential(
567
+ nn.Linear(config.latent_dim + config.action_feature.shape[0], config.mlp_dim),
568
+ nn.LayerNorm(config.mlp_dim),
569
+ nn.Tanh(),
570
+ nn.Linear(config.mlp_dim, config.mlp_dim),
571
+ nn.ELU(),
572
+ nn.Linear(config.mlp_dim, 1),
573
+ )
574
+ for _ in range(config.q_ensemble_size)
575
+ ]
576
+ )
577
+ self._V = nn.Sequential(
578
+ nn.Linear(config.latent_dim, config.mlp_dim),
579
+ nn.LayerNorm(config.mlp_dim),
580
+ nn.Tanh(),
581
+ nn.Linear(config.mlp_dim, config.mlp_dim),
582
+ nn.ELU(),
583
+ nn.Linear(config.mlp_dim, 1),
584
+ )
585
+ self._init_weights()
586
+
587
+ def _init_weights(self):
588
+ """Initialize model weights.
589
+
590
+ Orthogonal initialization for all linear and convolutional layers' weights (apart from final layers
591
+ of reward network and Q networks which get zero initialization).
592
+ Zero initialization for all linear and convolutional layers' biases.
593
+ """
594
+
595
+ def _apply_fn(m):
596
+ if isinstance(m, nn.Linear):
597
+ nn.init.orthogonal_(m.weight.data)
598
+ if m.bias is not None:
599
+ nn.init.zeros_(m.bias)
600
+ elif isinstance(m, nn.Conv2d):
601
+ gain = nn.init.calculate_gain("relu")
602
+ nn.init.orthogonal_(m.weight.data, gain)
603
+ if m.bias is not None:
604
+ nn.init.zeros_(m.bias)
605
+
606
+ self.apply(_apply_fn)
607
+ for m in [self._reward, *self._Qs]:
608
+ assert isinstance(m[-1], nn.Linear), (
609
+ "Sanity check. The last linear layer needs 0 initialization on weights."
610
+ )
611
+ nn.init.zeros_(m[-1].weight)
612
+ nn.init.zeros_(m[-1].bias) # this has already been done, but keep this line here for good measure
613
+
614
+ def encode(self, obs: dict[str, Tensor]) -> Tensor:
615
+ """Encodes an observation into its latent representation."""
616
+ return self._encoder(obs)
617
+
618
+ def latent_dynamics_and_reward(self, z: Tensor, a: Tensor) -> tuple[Tensor, Tensor]:
619
+ """Predict the next state's latent representation and the reward given a current latent and action.
620
+
621
+ Args:
622
+ z: (*, latent_dim) tensor for the current state's latent representation.
623
+ a: (*, action_dim) tensor for the action to be applied.
624
+ Returns:
625
+ A tuple containing:
626
+ - (*, latent_dim) tensor for the next state's latent representation.
627
+ - (*,) tensor for the estimated reward.
628
+ """
629
+ x = torch.cat([z, a], dim=-1)
630
+ return self._dynamics(x), self._reward(x).squeeze(-1)
631
+
632
+ def latent_dynamics(self, z: Tensor, a: Tensor) -> Tensor:
633
+ """Predict the next state's latent representation given a current latent and action.
634
+
635
+ Args:
636
+ z: (*, latent_dim) tensor for the current state's latent representation.
637
+ a: (*, action_dim) tensor for the action to be applied.
638
+ Returns:
639
+ (*, latent_dim) tensor for the next state's latent representation.
640
+ """
641
+ x = torch.cat([z, a], dim=-1)
642
+ return self._dynamics(x)
643
+
644
+ def pi(self, z: Tensor, std: float = 0.0) -> Tensor:
645
+ """Samples an action from the learned policy.
646
+
647
+ The policy can also have added (truncated) Gaussian noise injected for encouraging exploration when
648
+ generating rollouts for online training.
649
+
650
+ Args:
651
+ z: (*, latent_dim) tensor for the current state's latent representation.
652
+ std: The standard deviation of the injected noise.
653
+ Returns:
654
+ (*, action_dim) tensor for the sampled action.
655
+ """
656
+ action = torch.tanh(self._pi(z))
657
+ if std > 0:
658
+ std = torch.ones_like(action) * std
659
+ action += torch.randn_like(action) * std
660
+ return action
661
+
662
+ def V(self, z: Tensor) -> Tensor: # noqa: N802
663
+ """Predict state value (V).
664
+
665
+ Args:
666
+ z: (*, latent_dim) tensor for the current state's latent representation.
667
+ Returns:
668
+ (*,) tensor of estimated state values.
669
+ """
670
+ return self._V(z).squeeze(-1)
671
+
672
+ def Qs(self, z: Tensor, a: Tensor, return_min: bool = False) -> Tensor: # noqa: N802
673
+ """Predict state-action value for all of the learned Q functions.
674
+
675
+ Args:
676
+ z: (*, latent_dim) tensor for the current state's latent representation.
677
+ a: (*, action_dim) tensor for the action to be applied.
678
+ return_min: Set to true for implementing the detail in App. C of the FOWM paper: randomly select
679
+ 2 of the Qs and return the minimum
680
+ Returns:
681
+ (q_ensemble, *) tensor for the value predictions of each learned Q function in the ensemble OR
682
+ (*,) tensor if return_min=True.
683
+ """
684
+ x = torch.cat([z, a], dim=-1)
685
+ if not return_min:
686
+ return torch.stack([q(x).squeeze(-1) for q in self._Qs], dim=0)
687
+ else:
688
+ if len(self._Qs) > 2: # noqa: SIM108
689
+ Qs = [self._Qs[i] for i in np.random.choice(len(self._Qs), size=2)]
690
+ else:
691
+ Qs = self._Qs
692
+ return torch.stack([q(x).squeeze(-1) for q in Qs], dim=0).min(dim=0)[0]
693
+
694
+
695
+ class TDMPCObservationEncoder(nn.Module):
696
+ """Encode image and/or state vector observations."""
697
+
698
+ def __init__(self, config: TDMPCConfig):
699
+ """
700
+ Creates encoders for pixel and/or state modalities.
701
+ TODO(alexander-soare): The original work allows for multiple images by concatenating them along the
702
+ channel dimension. Re-implement this capability.
703
+ """
704
+ super().__init__()
705
+ self.config = config
706
+
707
+ if config.image_features:
708
+ self.image_enc_layers = nn.Sequential(
709
+ nn.Conv2d(
710
+ next(iter(config.image_features.values())).shape[0],
711
+ config.image_encoder_hidden_dim,
712
+ 7,
713
+ stride=2,
714
+ ),
715
+ nn.ReLU(),
716
+ nn.Conv2d(config.image_encoder_hidden_dim, config.image_encoder_hidden_dim, 5, stride=2),
717
+ nn.ReLU(),
718
+ nn.Conv2d(config.image_encoder_hidden_dim, config.image_encoder_hidden_dim, 3, stride=2),
719
+ nn.ReLU(),
720
+ nn.Conv2d(config.image_encoder_hidden_dim, config.image_encoder_hidden_dim, 3, stride=2),
721
+ nn.ReLU(),
722
+ )
723
+ dummy_shape = (1, *next(iter(config.image_features.values())).shape)
724
+ out_shape = get_output_shape(self.image_enc_layers, dummy_shape)[1:]
725
+ self.image_enc_layers.extend(
726
+ nn.Sequential(
727
+ nn.Flatten(),
728
+ nn.Linear(np.prod(out_shape), config.latent_dim),
729
+ nn.LayerNorm(config.latent_dim),
730
+ nn.Sigmoid(),
731
+ )
732
+ )
733
+
734
+ if config.robot_state_feature:
735
+ self.state_enc_layers = nn.Sequential(
736
+ nn.Linear(config.robot_state_feature.shape[0], config.state_encoder_hidden_dim),
737
+ nn.ELU(),
738
+ nn.Linear(config.state_encoder_hidden_dim, config.latent_dim),
739
+ nn.LayerNorm(config.latent_dim),
740
+ nn.Sigmoid(),
741
+ )
742
+
743
+ if config.env_state_feature:
744
+ self.env_state_enc_layers = nn.Sequential(
745
+ nn.Linear(config.env_state_feature.shape[0], config.state_encoder_hidden_dim),
746
+ nn.ELU(),
747
+ nn.Linear(config.state_encoder_hidden_dim, config.latent_dim),
748
+ nn.LayerNorm(config.latent_dim),
749
+ nn.Sigmoid(),
750
+ )
751
+
752
+ def forward(self, obs_dict: dict[str, Tensor]) -> Tensor:
753
+ """Encode the image and/or state vector.
754
+
755
+ Each modality is encoded into a feature vector of size (latent_dim,) and then a uniform mean is taken
756
+ over all features.
757
+ """
758
+ feat = []
759
+ # NOTE: Order of observations matters here.
760
+ if self.config.image_features:
761
+ feat.append(
762
+ flatten_forward_unflatten(
763
+ self.image_enc_layers, obs_dict[next(iter(self.config.image_features))]
764
+ )
765
+ )
766
+ if self.config.env_state_feature:
767
+ feat.append(self.env_state_enc_layers(obs_dict[OBS_ENV_STATE]))
768
+ if self.config.robot_state_feature:
769
+ feat.append(self.state_enc_layers(obs_dict[OBS_STATE]))
770
+ return torch.stack(feat, dim=0).mean(0)
771
+
772
+
773
+ def random_shifts_aug(x: Tensor, max_random_shift_ratio: float) -> Tensor:
774
+ """Randomly shifts images horizontally and vertically.
775
+
776
+ Adapted from https://github.com/facebookresearch/drqv2
777
+ """
778
+ b, _, h, w = x.size()
779
+ assert h == w, "non-square images not handled yet"
780
+ pad = int(round(max_random_shift_ratio * h))
781
+ x = F.pad(x, tuple([pad] * 4), "replicate")
782
+ eps = 1.0 / (h + 2 * pad)
783
+ arange = torch.linspace(
784
+ -1.0 + eps,
785
+ 1.0 - eps,
786
+ h + 2 * pad,
787
+ device=x.device,
788
+ dtype=torch.float32,
789
+ )[:h]
790
+ arange = einops.repeat(arange, "w -> h w 1", h=h)
791
+ base_grid = torch.cat([arange, arange.transpose(1, 0)], dim=2)
792
+ base_grid = einops.repeat(base_grid, "h w c -> b h w c", b=b)
793
+ # A random shift in units of pixels and within the boundaries of the padding.
794
+ shift = torch.randint(
795
+ 0,
796
+ 2 * pad + 1,
797
+ size=(b, 1, 1, 2),
798
+ device=x.device,
799
+ dtype=torch.float32,
800
+ )
801
+ shift *= 2.0 / (h + 2 * pad)
802
+ grid = base_grid + shift
803
+ return F.grid_sample(x, grid, padding_mode="zeros", align_corners=False)
804
+
805
+
806
+ def update_ema_parameters(ema_net: nn.Module, net: nn.Module, alpha: float):
807
+ """Update EMA parameters in place with ema_param <- alpha * ema_param + (1 - alpha) * param."""
808
+ for ema_module, module in zip(ema_net.modules(), net.modules(), strict=True):
809
+ for (n_p_ema, p_ema), (n_p, p) in zip(
810
+ ema_module.named_parameters(recurse=False), module.named_parameters(recurse=False), strict=True
811
+ ):
812
+ assert n_p_ema == n_p, "Parameter names don't match for EMA model update"
813
+ if isinstance(p, dict):
814
+ raise RuntimeError("Dict parameter not supported")
815
+ if isinstance(module, nn.modules.batchnorm._BatchNorm) or not p.requires_grad:
816
+ # Copy BatchNorm parameters, and non-trainable parameters directly.
817
+ p_ema.copy_(p.to(dtype=p_ema.dtype).data)
818
+ with torch.no_grad():
819
+ p_ema.mul_(alpha)
820
+ p_ema.add_(p.to(dtype=p_ema.dtype).data, alpha=1 - alpha)
821
+
822
+
823
+ def flatten_forward_unflatten(fn: Callable[[Tensor], Tensor], image_tensor: Tensor) -> Tensor:
824
+ """Helper to temporarily flatten extra dims at the start of the image tensor.
825
+
826
+ Args:
827
+ fn: Callable that the image tensor will be passed to. It should accept (B, C, H, W) and return
828
+ (B, *), where * is any number of dimensions.
829
+ image_tensor: An image tensor of shape (**, C, H, W), where ** is any number of dimensions, generally
830
+ different from *.
831
+ Returns:
832
+ A return value from the callable reshaped to (**, *).
833
+ """
834
+ if image_tensor.ndim == 4:
835
+ return fn(image_tensor)
836
+ start_dims = image_tensor.shape[:-3]
837
+ inp = torch.flatten(image_tensor, end_dim=-4)
838
+ flat_out = fn(inp)
839
+ return torch.reshape(flat_out, (*start_dims, *flat_out.shape[1:]))
tools/lerobot_v21_runtime/src/lerobot/policies/vqbet/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ ../../../../docs/source/policy_vqbet_README.md
tools/lerobot_v21_runtime/src/lerobot/policies/vqbet/configuration_vqbet.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 Seungjae Lee and Yibin Wang and Haritheja Etukuru
4
+ # and H. Jin Kim and Nur Muhammad Mahi Shafiullah and Lerrel Pinto
5
+ # and The HuggingFace Inc. team. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ from dataclasses import dataclass, field
20
+
21
+ from lerobot.configs.policies import PreTrainedConfig
22
+ from lerobot.configs.types import NormalizationMode
23
+ from lerobot.optim.optimizers import AdamConfig
24
+ from lerobot.optim.schedulers import VQBeTSchedulerConfig
25
+
26
+
27
+ @PreTrainedConfig.register_subclass("vqbet")
28
+ @dataclass
29
+ class VQBeTConfig(PreTrainedConfig):
30
+ """Configuration class for VQ-BeT.
31
+
32
+ Defaults are configured for training with PushT providing proprioceptive and single camera observations.
33
+
34
+ The parameters you will most likely need to change are the ones which depend on the environment / sensors.
35
+ Those are: `input_shapes` and `output_shapes`.
36
+
37
+ Notes on the inputs and outputs:
38
+ - "observation.state" is required as an input key.
39
+ - At least one key starting with "observation.image is required as an input.
40
+ - If there are multiple keys beginning with "observation.image" they are treated as multiple camera
41
+ views. Right now we only support all images having the same shape.
42
+ - "action" is required as an output key.
43
+
44
+ Args:
45
+ n_obs_steps: Number of environment steps worth of observations to pass to the policy (takes the
46
+ current step and additional steps going back).
47
+ n_action_pred_token: Total number of current token and future tokens that VQ-BeT predicts.
48
+ action_chunk_size: Action chunk size of each action prediction token.
49
+ input_shapes: A dictionary defining the shapes of the input data for the policy.
50
+ The key represents the input data name, and the value is a list indicating the dimensions
51
+ of the corresponding data. For example, "observation.image" refers to an input from
52
+ a camera with dimensions [3, 96, 96], indicating it has three color channels and 96x96 resolution.
53
+ Importantly, shapes doesnt include batch dimension or temporal dimension.
54
+ output_shapes: A dictionary defining the shapes of the output data for the policy.
55
+ The key represents the output data name, and the value is a list indicating the dimensions
56
+ of the corresponding data. For example, "action" refers to an output shape of [14], indicating
57
+ 14-dimensional actions. Importantly, shapes doesnt include batch dimension or temporal dimension.
58
+ input_normalization_modes: A dictionary with key representing the modality (e.g. "observation.state"),
59
+ and the value specifies the normalization mode to apply. The two available modes are "mean_std"
60
+ which subtracts the mean and divides by the standard deviation and "min_max" which rescale in a
61
+ [-1, 1] range.
62
+ output_normalization_modes: Similar dictionary as `normalize_input_modes`, but to unnormalize to the
63
+ original scale. Note that this is also used for normalizing the training targets.
64
+ vision_backbone: Name of the torchvision resnet backbone to use for encoding images.
65
+ crop_shape: (H, W) shape to crop images to as a preprocessing step for the vision backbone. Must fit
66
+ within the image size. If None, no cropping is done.
67
+ crop_is_random: Whether the crop should be random at training time (it's always a center crop in eval
68
+ mode).
69
+ pretrained_backbone_weights: Pretrained weights from torchvision to initialize the backbone.
70
+ `None` means no pretrained weights.
71
+ use_group_norm: Whether to replace batch normalization with group normalization in the backbone.
72
+ The group sizes are set to be about 16 (to be precise, feature_dim // 16).
73
+ spatial_softmax_num_keypoints: Number of keypoints for SpatialSoftmax.
74
+ n_vqvae_training_steps: Number of optimization steps for training Residual VQ.
75
+ vqvae_n_embed: Number of embedding vectors in the RVQ dictionary (each layer).
76
+ vqvae_embedding_dim: Dimension of each embedding vector in the RVQ dictionary.
77
+ vqvae_enc_hidden_dim: Size of hidden dimensions of Encoder / Decoder part of Residaul VQ-VAE
78
+ gpt_block_size: Max block size of minGPT (should be larger than the number of input tokens)
79
+ gpt_input_dim: Size of output input of GPT. This is also used as the dimension of observation features.
80
+ gpt_output_dim: Size of output dimension of GPT. This is also used as a input dimension of offset / bin prediction headers.
81
+ gpt_n_layer: Number of layers of GPT
82
+ gpt_n_head: Number of headers of GPT
83
+ gpt_hidden_dim: Size of hidden dimensions of GPT
84
+ dropout: Dropout rate for GPT
85
+ mlp_hidden_dim: Size of hidden dimensions of offset header / bin prediction headers parts of VQ-BeT
86
+ offset_loss_weight: A constant that is multiplied to the offset loss
87
+ primary_code_loss_weight: A constant that is multiplied to the primary code prediction loss
88
+ secondary_code_loss_weight: A constant that is multiplied to the secondary code prediction loss
89
+ bet_softmax_temperature: Sampling temperature of code for rollout with VQ-BeT
90
+ sequentially_select: Whether select code of primary / secondary as sequentially (pick primary code,
91
+ and then select secodnary code), or at the same time.
92
+ """
93
+
94
+ # Inputs / output structure.
95
+ n_obs_steps: int = 5
96
+ n_action_pred_token: int = 3
97
+ action_chunk_size: int = 5
98
+
99
+ normalization_mapping: dict[str, NormalizationMode] = field(
100
+ default_factory=lambda: {
101
+ "VISUAL": NormalizationMode.IDENTITY,
102
+ "STATE": NormalizationMode.MIN_MAX,
103
+ "ACTION": NormalizationMode.MIN_MAX,
104
+ }
105
+ )
106
+
107
+ # Architecture / modeling.
108
+ # Vision backbone.
109
+ vision_backbone: str = "resnet18"
110
+ crop_shape: tuple[int, int] | None = (84, 84)
111
+ crop_is_random: bool = True
112
+ pretrained_backbone_weights: str | None = None
113
+ use_group_norm: bool = True
114
+ spatial_softmax_num_keypoints: int = 32
115
+ # VQ-VAE
116
+ n_vqvae_training_steps: int = 20000
117
+ vqvae_n_embed: int = 16
118
+ vqvae_embedding_dim: int = 256
119
+ vqvae_enc_hidden_dim: int = 128
120
+ # VQ-BeT
121
+ gpt_block_size: int = 500
122
+ gpt_input_dim: int = 512
123
+ gpt_output_dim: int = 512
124
+ gpt_n_layer: int = 8
125
+ gpt_n_head: int = 8
126
+ gpt_hidden_dim: int = 512
127
+ dropout: float = 0.1
128
+ mlp_hidden_dim: int = 1024
129
+ offset_loss_weight: float = 10000.0
130
+ primary_code_loss_weight: float = 5.0
131
+ secondary_code_loss_weight: float = 0.5
132
+ bet_softmax_temperature: float = 0.1
133
+ sequentially_select: bool = False
134
+
135
+ # Training presets
136
+ optimizer_lr: float = 1e-4
137
+ optimizer_betas: tuple = (0.95, 0.999)
138
+ optimizer_eps: float = 1e-8
139
+ optimizer_weight_decay: float = 1e-6
140
+ optimizer_vqvae_lr: float = 1e-3
141
+ optimizer_vqvae_weight_decay: float = 1e-4
142
+ scheduler_warmup_steps: int = 500
143
+
144
+ def __post_init__(self):
145
+ super().__post_init__()
146
+
147
+ """Input validation (not exhaustive)."""
148
+ if not self.vision_backbone.startswith("resnet"):
149
+ raise ValueError(
150
+ f"`vision_backbone` must be one of the ResNet variants. Got {self.vision_backbone}."
151
+ )
152
+
153
+ def get_optimizer_preset(self) -> AdamConfig:
154
+ return AdamConfig(
155
+ lr=self.optimizer_lr,
156
+ betas=self.optimizer_betas,
157
+ eps=self.optimizer_eps,
158
+ weight_decay=self.optimizer_weight_decay,
159
+ )
160
+
161
+ def get_scheduler_preset(self) -> VQBeTSchedulerConfig:
162
+ return VQBeTSchedulerConfig(
163
+ num_warmup_steps=self.scheduler_warmup_steps,
164
+ num_vqvae_training_steps=self.n_vqvae_training_steps,
165
+ )
166
+
167
+ def validate_features(self) -> None:
168
+ # Note: this check was previously performed inside VQBeTRgbEncoder in the form of
169
+ # assert len(image_keys) == 1
170
+ if not len(self.image_features) == 1:
171
+ raise ValueError("You must provide only one image among the inputs.")
172
+
173
+ if self.crop_shape is not None:
174
+ for key, image_ft in self.image_features.items():
175
+ if self.crop_shape[0] > image_ft.shape[1] or self.crop_shape[1] > image_ft.shape[2]:
176
+ raise ValueError(
177
+ f"`crop_shape` should fit within the images shapes. Got {self.crop_shape} "
178
+ f"for `crop_shape` and {image_ft.shape} for "
179
+ f"`{key}`."
180
+ )
181
+
182
+ # Check that all input images have the same shape.
183
+ first_image_key, first_image_ft = next(iter(self.image_features.items()))
184
+ for key, image_ft in self.image_features.items():
185
+ if image_ft.shape != first_image_ft.shape:
186
+ raise ValueError(
187
+ f"`{key}` does not match `{first_image_key}`, but we expect all image shapes to match."
188
+ )
189
+
190
+ @property
191
+ def observation_delta_indices(self) -> list:
192
+ return list(range(1 - self.n_obs_steps, 1))
193
+
194
+ @property
195
+ def action_delta_indices(self) -> list:
196
+ return list(range(1 - self.n_obs_steps, self.n_action_pred_token + self.action_chunk_size - 1))
197
+
198
+ @property
199
+ def reward_delta_indices(self) -> None:
200
+ return None
tools/lerobot_v21_runtime/src/lerobot/policies/vqbet/modeling_vqbet.py ADDED
@@ -0,0 +1,918 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 Seungjae Lee and Yibin Wang and Haritheja Etukuru
4
+ # and H. Jin Kim and Nur Muhammad Mahi Shafiullah and Lerrel Pinto
5
+ # and The HuggingFace Inc. team. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import warnings
20
+ from collections import deque
21
+ from collections.abc import Callable
22
+
23
+ import einops
24
+ import numpy as np
25
+ import torch
26
+ import torch.nn.functional as F # noqa: N812
27
+ import torchvision
28
+ from torch import Tensor, nn
29
+
30
+ from lerobot.constants import ACTION, OBS_IMAGES, OBS_STATE
31
+ from lerobot.policies.normalize import Normalize, Unnormalize
32
+ from lerobot.policies.pretrained import PreTrainedPolicy
33
+ from lerobot.policies.utils import get_device_from_parameters, get_output_shape, populate_queues
34
+ from lerobot.policies.vqbet.configuration_vqbet import VQBeTConfig
35
+ from lerobot.policies.vqbet.vqbet_utils import GPT, ResidualVQ
36
+
37
+ # ruff: noqa: N806
38
+
39
+
40
+ class VQBeTPolicy(PreTrainedPolicy):
41
+ """
42
+ VQ-BeT Policy as per "Behavior Generation with Latent Actions"
43
+ """
44
+
45
+ config_class = VQBeTConfig
46
+ name = "vqbet"
47
+
48
+ def __init__(
49
+ self,
50
+ config: VQBeTConfig | None = None,
51
+ dataset_stats: dict[str, dict[str, Tensor]] | None = None,
52
+ ):
53
+ """
54
+ Args:
55
+ config: Policy configuration class instance or None, in which case the default instantiation of
56
+ the configuration class is used.
57
+ dataset_stats: Dataset statistics to be used for normalization. If not passed here, it is expected
58
+ that they will be passed with a call to `load_state_dict` before the policy is used.
59
+ """
60
+ super().__init__(config)
61
+ config.validate_features()
62
+ self.config = config
63
+
64
+ self.normalize_inputs = Normalize(config.input_features, config.normalization_mapping, dataset_stats)
65
+ self.normalize_targets = Normalize(
66
+ config.output_features, config.normalization_mapping, dataset_stats
67
+ )
68
+ self.unnormalize_outputs = Unnormalize(
69
+ config.output_features, config.normalization_mapping, dataset_stats
70
+ )
71
+
72
+ self.vqbet = VQBeTModel(config)
73
+
74
+ self.reset()
75
+
76
+ def get_optim_params(self) -> dict:
77
+ vqvae_params = (
78
+ list(self.vqbet.action_head.vqvae_model.encoder.parameters())
79
+ + list(self.vqbet.action_head.vqvae_model.decoder.parameters())
80
+ + list(self.vqbet.action_head.vqvae_model.vq_layer.parameters())
81
+ )
82
+ decay_params, no_decay_params = self.vqbet.policy.configure_parameters()
83
+ decay_params = (
84
+ decay_params
85
+ + list(self.vqbet.rgb_encoder.parameters())
86
+ + list(self.vqbet.state_projector.parameters())
87
+ + list(self.vqbet.rgb_feature_projector.parameters())
88
+ + [self.vqbet.action_token]
89
+ + list(self.vqbet.action_head.map_to_cbet_preds_offset.parameters())
90
+ )
91
+
92
+ if self.config.sequentially_select:
93
+ decay_params = (
94
+ decay_params
95
+ + list(self.vqbet.action_head.map_to_cbet_preds_primary_bin.parameters())
96
+ + list(self.vqbet.action_head.map_to_cbet_preds_secondary_bin.parameters())
97
+ )
98
+ else:
99
+ decay_params = decay_params + list(self.vqbet.action_head.map_to_cbet_preds_bin.parameters())
100
+
101
+ return [
102
+ {
103
+ "params": decay_params,
104
+ },
105
+ {
106
+ "params": vqvae_params,
107
+ "weight_decay": self.config.optimizer_vqvae_weight_decay,
108
+ "lr": self.config.optimizer_vqvae_lr,
109
+ },
110
+ {
111
+ "params": no_decay_params,
112
+ "weight_decay": 0.0,
113
+ },
114
+ ]
115
+
116
+ def reset(self):
117
+ """
118
+ Clear observation and action queues. Should be called on `env.reset()`
119
+ queues are populated during rollout of the policy, they contain the n latest observations and actions
120
+ """
121
+ self._queues = {
122
+ OBS_IMAGES: deque(maxlen=self.config.n_obs_steps),
123
+ OBS_STATE: deque(maxlen=self.config.n_obs_steps),
124
+ ACTION: deque(maxlen=self.config.action_chunk_size),
125
+ }
126
+
127
+ @torch.no_grad()
128
+ def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor:
129
+ batch = {k: torch.stack(list(self._queues[k]), dim=1) for k in batch if k in self._queues}
130
+ actions = self.vqbet(batch, rollout=True)[:, : self.config.action_chunk_size]
131
+ actions = self.unnormalize_outputs({ACTION: actions})[ACTION]
132
+ return actions
133
+
134
+ @torch.no_grad()
135
+ def select_action(self, batch: dict[str, Tensor]) -> Tensor:
136
+ """Select a single action given environment observations.
137
+
138
+ This method wraps `select_actions` in order to return one action at a time for execution in the
139
+ environment. It works by managing the actions in a queue and only calling `select_actions` when the
140
+ queue is empty.
141
+ """
142
+ # NOTE: for offline evaluation, we have action in the batch, so we need to pop it out
143
+ if ACTION in batch:
144
+ batch.pop(ACTION)
145
+ batch = self.normalize_inputs(batch)
146
+ batch = dict(batch) # shallow copy so that adding a key doesn't modify the original
147
+ # NOTE: It's important that this happens after stacking the images into a single key.
148
+ batch["observation.images"] = torch.stack([batch[key] for key in self.config.image_features], dim=-4)
149
+
150
+ self._queues = populate_queues(self._queues, batch)
151
+
152
+ if not self.vqbet.action_head.vqvae_model.discretized.item():
153
+ warnings.warn(
154
+ "To evaluate in the environment, your VQ-BeT model should contain a pretrained Residual VQ.",
155
+ stacklevel=1,
156
+ )
157
+
158
+ if len(self._queues[ACTION]) == 0:
159
+ actions = self.predict_action_chunk(batch)
160
+ # since the data in the action queue's dimension is (action_chunk_size, batch_size, action_dim), we transpose the action and fill the queue
161
+ self._queues[ACTION].extend(actions.transpose(0, 1))
162
+
163
+ action = self._queues[ACTION].popleft()
164
+ return action
165
+
166
+ def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, dict]:
167
+ """Run the batch through the model and compute the loss for training or validation."""
168
+ batch = self.normalize_inputs(batch)
169
+ batch = dict(batch) # shallow copy so that adding a key doesn't modify the original
170
+ batch[OBS_IMAGES] = torch.stack([batch[key] for key in self.config.image_features], dim=-4)
171
+ batch = self.normalize_targets(batch)
172
+ # VQ-BeT discretizes action using VQ-VAE before training BeT (please refer to section 3.2 in the VQ-BeT paper https://huggingface.co/papers/2403.03181)
173
+ if not self.vqbet.action_head.vqvae_model.discretized.item():
174
+ # loss: total loss of training RVQ
175
+ # n_different_codes: how many of the total possible VQ codes are being used in single batch (how many of them have at least one encoder embedding as a nearest neighbor). This can be at most `vqvae_n_embed * number of layers of RVQ (=2)`.
176
+ # n_different_combinations: how many different code combinations are being used out of all possible combinations in single batch. This can be at most `vqvae_n_embed ^ number of layers of RVQ (=2)` (hint consider the RVQ as a decision tree).
177
+ loss, n_different_codes, n_different_combinations, recon_l1_error = (
178
+ self.vqbet.action_head.discretize(self.config.n_vqvae_training_steps, batch[ACTION])
179
+ )
180
+ return loss, {
181
+ "n_different_codes": n_different_codes,
182
+ "n_different_combinations": n_different_combinations,
183
+ "recon_l1_error": recon_l1_error,
184
+ }
185
+ # if Residual VQ is already trained, VQ-BeT trains its GPT and bin prediction head / offset prediction head parts.
186
+ _, loss_dict = self.vqbet(batch, rollout=False)
187
+ loss = loss_dict.pop("loss")
188
+
189
+ return loss, loss_dict
190
+
191
+
192
+ class SpatialSoftmax(nn.Module):
193
+ """
194
+ Spatial Soft Argmax operation described in "Deep Spatial Autoencoders for Visuomotor Learning" by Finn et al.
195
+ (https://huggingface.co/papers/1509.06113). A minimal port of the robomimic implementation.
196
+
197
+ At a high level, this takes 2D feature maps (from a convnet/ViT) and returns the "center of mass"
198
+ of activations of each channel, i.e., keypoints in the image space for the policy to focus on.
199
+
200
+ Example: take feature maps of size (512x10x12). We generate a grid of normalized coordinates (10x12x2):
201
+ -----------------------------------------------------
202
+ | (-1., -1.) | (-0.82, -1.) | ... | (1., -1.) |
203
+ | (-1., -0.78) | (-0.82, -0.78) | ... | (1., -0.78) |
204
+ | ... | ... | ... | ... |
205
+ | (-1., 1.) | (-0.82, 1.) | ... | (1., 1.) |
206
+ -----------------------------------------------------
207
+ This is achieved by applying channel-wise softmax over the activations (512x120) and computing the dot
208
+ product with the coordinates (120x2) to get expected points of maximal activation (512x2).
209
+
210
+ The example above results in 512 keypoints (corresponding to the 512 input channels). We can optionally
211
+ provide num_kp != None to control the number of keypoints. This is achieved by a first applying a learnable
212
+ linear mapping (in_channels, H, W) -> (num_kp, H, W).
213
+ """
214
+
215
+ def __init__(self, input_shape, num_kp=None):
216
+ """
217
+ Args:
218
+ input_shape (list): (C, H, W) input feature map shape.
219
+ num_kp (int): number of keypoints in output. If None, output will have the same number of channels as input.
220
+ """
221
+ super().__init__()
222
+
223
+ assert len(input_shape) == 3
224
+ self._in_c, self._in_h, self._in_w = input_shape
225
+
226
+ if num_kp is not None:
227
+ self.nets = torch.nn.Conv2d(self._in_c, num_kp, kernel_size=1)
228
+ self._out_c = num_kp
229
+ else:
230
+ self.nets = None
231
+ self._out_c = self._in_c
232
+
233
+ # we could use torch.linspace directly but that seems to behave slightly differently than numpy
234
+ # and causes a small degradation in pc_success of pre-trained models.
235
+ pos_x, pos_y = np.meshgrid(np.linspace(-1.0, 1.0, self._in_w), np.linspace(-1.0, 1.0, self._in_h))
236
+ pos_x = torch.from_numpy(pos_x.reshape(self._in_h * self._in_w, 1)).float()
237
+ pos_y = torch.from_numpy(pos_y.reshape(self._in_h * self._in_w, 1)).float()
238
+ # register as buffer so it's moved to the correct device.
239
+ self.register_buffer("pos_grid", torch.cat([pos_x, pos_y], dim=1))
240
+
241
+ def forward(self, features: Tensor) -> Tensor:
242
+ """
243
+ Args:
244
+ features: (B, C, H, W) input feature maps.
245
+ Returns:
246
+ (B, K, 2) image-space coordinates of keypoints.
247
+ """
248
+ if self.nets is not None:
249
+ features = self.nets(features)
250
+
251
+ # [B, K, H, W] -> [B * K, H * W] where K is number of keypoints
252
+ features = features.reshape(-1, self._in_h * self._in_w)
253
+ # 2d softmax normalization
254
+ attention = F.softmax(features, dim=-1)
255
+ # [B * K, H * W] x [H * W, 2] -> [B * K, 2] for spatial coordinate mean in x and y dimensions
256
+ expected_xy = attention @ self.pos_grid
257
+ # reshape to [B, K, 2]
258
+ feature_keypoints = expected_xy.view(-1, self._out_c, 2)
259
+
260
+ return feature_keypoints
261
+
262
+
263
+ class VQBeTModel(nn.Module):
264
+ """VQ-BeT: The underlying neural network for VQ-BeT
265
+
266
+ Note: In this code we use the terms `rgb_encoder`, 'policy', `action_head`. The meanings are as follows.
267
+ - The `rgb_encoder` process rgb-style image observations to one-dimensional embedding vectors
268
+ - A `policy` is a minGPT architecture, that takes observation sequences and action query tokens to generate `features`.
269
+ - These `features` pass through the action head, which passes through the code prediction, offset prediction head,
270
+ and finally generates a prediction for the action chunks.
271
+
272
+ -------------------------------** legend **-------------------------------
273
+ │ n = n_obs_steps, p = n_action_pred_token, c = action_chunk_size) │
274
+ │ o_{t} : visual observation at timestep {t} │
275
+ │ s_{t} : state observation at timestep {t} │
276
+ │ a_{t} : action at timestep {t} │
277
+ │ A_Q : action_query_token │
278
+ --------------------------------------------------------------------------
279
+
280
+
281
+ Training Phase 1. Discretize action using Residual VQ (for config.n_vqvae_training_steps steps)
282
+
283
+
284
+ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
285
+ │ │ │ │ │ │
286
+ │ RVQ encoder │ ─► │ Residual │ ─► │ RVQ Decoder │
287
+ │ (a_{t}~a_{t+p}) │ │ Code Quantizer │ │ │
288
+ │ │ │ │ │ │
289
+ └─────────────────┘ └─────────────────┘ └─────────────────┘
290
+
291
+ Training Phase 2.
292
+
293
+ timestep {t-n+1} timestep {t-n+2} timestep {t}
294
+ ┌─────┴─────┐ ┌─────┴─────┐ ┌─────┴─────┐
295
+
296
+ o_{t-n+1} o_{t-n+2} ... o_{t}
297
+ │ │ │
298
+ │ s_{t-n+1} │ s_{t-n+2} ... │ s_{t} p
299
+ │ │ │ │ │ │ ┌───────┴───────┐
300
+ │ │ A_Q │ │ A_Q ... │ │ A_Q ... A_Q
301
+ │ │ │ │ │ │ │ │ │ │
302
+ ┌───▼─────▼─────▼─────��─────▼─────▼─────────────────▼─────▼─────▼───────────────▼───┐
303
+ │ │
304
+ │ GPT │ => policy
305
+ │ │
306
+ └───────────────▼─────────────────▼─────────────────────────────▼───────────────▼───┘
307
+ │ │ │ │
308
+ ┌───┴───┐ ┌───┴───┐ ┌───┴───┐ ┌───┴───┐
309
+ code offset code offset code offset code offset
310
+ ▼ │ ▼ │ ▼ │ ▼ │ => action_head
311
+ RVQ Decoder │ RVQ Decoder │ RVQ Decoder │ RVQ Decoder │
312
+ └── + ──┘ └── + ──┘ └── + ──┘ └── + ──┘
313
+ ▼ ▼ ▼ ▼
314
+ action chunk action chunk action chunk action chunk
315
+ a_{t-n+1} ~ a_{t-n+2} ~ a_{t} ~ ... a_{t+p-1} ~
316
+ a_{t-n+c} a_{t-n+c+1} a_{t+c-1} a_{t+p+c-1}
317
+
318
+ ▼
319
+ ONLY this chunk is used in rollout!
320
+ """
321
+
322
+ def __init__(self, config: VQBeTConfig):
323
+ super().__init__()
324
+ self.config = config
325
+
326
+ self.rgb_encoder = VQBeTRgbEncoder(config)
327
+ self.num_images = len(self.config.image_features)
328
+ # This action query token is used as a prompt for querying action chunks. Please refer to "A_Q" in the image above.
329
+ # Note: During the forward pass, this token is repeated as many times as needed. The authors also experimented with initializing the necessary number of tokens independently and observed inferior results.
330
+ self.action_token = nn.Parameter(torch.randn(1, 1, self.config.gpt_input_dim))
331
+
332
+ # To input state and observation features into GPT layers, we first project the features to fit the shape of input size of GPT.
333
+ self.state_projector = MLP(
334
+ config.robot_state_feature.shape[0], hidden_channels=[self.config.gpt_input_dim]
335
+ )
336
+ self.rgb_feature_projector = MLP(
337
+ self.rgb_encoder.feature_dim, hidden_channels=[self.config.gpt_input_dim]
338
+ )
339
+
340
+ # GPT part of VQ-BeT
341
+ self.policy = GPT(config)
342
+ # bin prediction head / offset prediction head part of VQ-BeT
343
+ self.action_head = VQBeTHead(config)
344
+
345
+ # Action tokens for: each observation step, the current action token, and all future action tokens.
346
+ num_tokens = self.config.n_action_pred_token + self.config.n_obs_steps - 1
347
+ self.register_buffer(
348
+ "select_target_actions_indices",
349
+ torch.row_stack([torch.arange(i, i + self.config.action_chunk_size) for i in range(num_tokens)]),
350
+ )
351
+
352
+ def forward(self, batch: dict[str, Tensor], rollout: bool) -> tuple[dict, dict]:
353
+ # Input validation.
354
+ assert set(batch).issuperset({"observation.state", "observation.images"})
355
+ batch_size, n_obs_steps = batch["observation.state"].shape[:2]
356
+ assert n_obs_steps == self.config.n_obs_steps
357
+
358
+ # Extract image feature (first combine batch and sequence dims).
359
+ img_features = self.rgb_encoder(
360
+ einops.rearrange(batch["observation.images"], "b s n ... -> (b s n) ...")
361
+ )
362
+ # Separate batch and sequence dims.
363
+ img_features = einops.rearrange(
364
+ img_features, "(b s n) ... -> b s n ...", b=batch_size, s=n_obs_steps, n=self.num_images
365
+ )
366
+
367
+ # Arrange prior and current observation step tokens as shown in the class docstring.
368
+ # First project features to token dimension.
369
+ rgb_tokens = self.rgb_feature_projector(
370
+ img_features
371
+ ) # (batch, obs_step, number of different cameras, projection dims)
372
+ input_tokens = [rgb_tokens[:, :, i] for i in range(rgb_tokens.size(2))]
373
+ input_tokens.append(
374
+ self.state_projector(batch["observation.state"])
375
+ ) # (batch, obs_step, projection dims)
376
+ input_tokens.append(einops.repeat(self.action_token, "1 1 d -> b n d", b=batch_size, n=n_obs_steps))
377
+ # Interleave tokens by stacking and rearranging.
378
+ input_tokens = torch.stack(input_tokens, dim=2)
379
+ input_tokens = einops.rearrange(input_tokens, "b n t d -> b (n t) d")
380
+
381
+ len_additional_action_token = self.config.n_action_pred_token - 1
382
+ future_action_tokens = self.action_token.repeat(batch_size, len_additional_action_token, 1)
383
+
384
+ # add additional action query tokens for predicting future action chunks
385
+ input_tokens = torch.cat([input_tokens, future_action_tokens], dim=1)
386
+
387
+ # get action features (pass through GPT)
388
+ features = self.policy(input_tokens)
389
+ # len(self.config.input_features) is the number of different observation modes.
390
+ # this line gets the index of action prompt tokens.
391
+ historical_act_pred_index = np.arange(0, n_obs_steps) * (len(self.config.input_features) + 1) + len(
392
+ self.config.input_features
393
+ )
394
+
395
+ # only extract the output tokens at the position of action query:
396
+ # Behavior Transformer (BeT), and VQ-BeT are both sequence-to-sequence prediction models,
397
+ # mapping sequential observation to sequential action (please refer to section 2.2 in BeT paper https://huggingface.co/papers/2206.11251).
398
+ # Thus, it predicts a historical action sequence, in addition to current and future actions (predicting future actions : optional).
399
+ if len_additional_action_token > 0:
400
+ features = torch.cat(
401
+ [features[:, historical_act_pred_index], features[:, -len_additional_action_token:]], dim=1
402
+ )
403
+ else:
404
+ features = features[:, historical_act_pred_index]
405
+ # pass through action head
406
+ action_head_output = self.action_head(features)
407
+ # if rollout, VQ-BeT don't calculate loss
408
+ if rollout:
409
+ return action_head_output["predicted_action"][:, n_obs_steps - 1, :].reshape(
410
+ batch_size, self.config.action_chunk_size, -1
411
+ )
412
+ # else, it calculate overall loss (bin prediction loss, and offset loss)
413
+ else:
414
+ output = batch[ACTION][:, self.select_target_actions_indices]
415
+ loss = self.action_head.loss_fn(action_head_output, output, reduction="mean")
416
+ return action_head_output, loss
417
+
418
+
419
+ class VQBeTHead(nn.Module):
420
+ def __init__(self, config: VQBeTConfig):
421
+ """
422
+ VQBeTHead takes output of GPT layers, and pass the feature through bin prediction head (`self.map_to_cbet_preds_bin`), and offset prediction head (`self.map_to_cbet_preds_offset`)
423
+
424
+ self.map_to_cbet_preds_bin: outputs probability of each code (for each layer).
425
+ The input dimension of `self.map_to_cbet_preds_bin` is same with the output of GPT,
426
+ and the output dimension of `self.map_to_cbet_preds_bin` is `self.vqvae_model.vqvae_num_layers (=fixed as 2) * self.config.vqvae_n_embed`.
427
+ if the agent select the code sequentially, we use self.map_to_cbet_preds_primary_bin and self.map_to_cbet_preds_secondary_bin instead of self._map_to_cbet_preds_bin.
428
+
429
+ self.map_to_cbet_preds_offset: output the predicted offsets for all the codes in all the layers.
430
+ The input dimension of ` self.map_to_cbet_preds_offset` is same with the output of GPT,
431
+ and the output dimension of ` self.map_to_cbet_preds_offset` is `self.vqvae_model.vqvae_num_layers (=fixed as 2) * self.config.vqvae_n_embed * config.action_chunk_size * config.action_feature.shape[0]`.
432
+ """
433
+
434
+ super().__init__()
435
+ self.config = config
436
+ # init vqvae
437
+ self.vqvae_model = VqVae(config)
438
+ if config.sequentially_select:
439
+ self.map_to_cbet_preds_primary_bin = MLP(
440
+ in_channels=config.gpt_output_dim,
441
+ hidden_channels=[self.config.vqvae_n_embed],
442
+ )
443
+ self.map_to_cbet_preds_secondary_bin = MLP(
444
+ in_channels=config.gpt_output_dim + self.config.vqvae_n_embed,
445
+ hidden_channels=[self.config.vqvae_n_embed],
446
+ )
447
+ else:
448
+ self.map_to_cbet_preds_bin = MLP(
449
+ in_channels=config.gpt_output_dim,
450
+ hidden_channels=[self.vqvae_model.vqvae_num_layers * self.config.vqvae_n_embed],
451
+ )
452
+ self.map_to_cbet_preds_offset = MLP(
453
+ in_channels=config.gpt_output_dim,
454
+ hidden_channels=[
455
+ self.vqvae_model.vqvae_num_layers
456
+ * self.config.vqvae_n_embed
457
+ * config.action_chunk_size
458
+ * config.action_feature.shape[0],
459
+ ],
460
+ )
461
+ # loss
462
+ self._focal_loss_fn = FocalLoss(gamma=2.0)
463
+
464
+ def discretize(self, n_vqvae_training_steps, actions):
465
+ # Resize the action sequence data to fit the action chunk size using a sliding window approach.
466
+ actions = torch.cat(
467
+ [
468
+ actions[:, j : j + self.config.action_chunk_size, :]
469
+ for j in range(actions.shape[1] + 1 - self.config.action_chunk_size)
470
+ ],
471
+ dim=0,
472
+ )
473
+ # `actions` is a tensor of shape (new_batch, action_chunk_size, action_dim) where new_batch is the number of possible chunks created from the original sequences using the sliding window.
474
+
475
+ loss, metric = self.vqvae_model.vqvae_forward(actions)
476
+ n_different_codes = sum(
477
+ [len(torch.unique(metric[2][:, i])) for i in range(self.vqvae_model.vqvae_num_layers)]
478
+ )
479
+ n_different_combinations = len(torch.unique(metric[2], dim=0))
480
+ recon_l1_error = metric[0].detach().cpu().item()
481
+ self.vqvae_model.optimized_steps += 1
482
+ # if we updated RVQ more than `n_vqvae_training_steps` steps, we freeze the RVQ part.
483
+ if self.vqvae_model.optimized_steps >= n_vqvae_training_steps:
484
+ self.vqvae_model.discretized = torch.tensor(True)
485
+ self.vqvae_model.vq_layer.freeze_codebook = torch.tensor(True)
486
+ print("Finished discretizing action data!")
487
+ self.vqvae_model.eval()
488
+ for param in self.vqvae_model.vq_layer.parameters():
489
+ param.requires_grad = False
490
+ return loss, n_different_codes, n_different_combinations, recon_l1_error
491
+
492
+ def forward(self, x, **kwargs) -> dict:
493
+ # N is the batch size, and T is number of action query tokens, which are process through same GPT
494
+ N, T, _ = x.shape
495
+ # we calculate N and T side parallelly. Thus, the dimensions would be
496
+ # (batch size * number of action query tokens, action chunk size, action dimension)
497
+ x = einops.rearrange(x, "N T WA -> (N T) WA")
498
+
499
+ # sample offsets
500
+ cbet_offsets = self.map_to_cbet_preds_offset(x)
501
+ cbet_offsets = einops.rearrange(
502
+ cbet_offsets,
503
+ "(NT) (G C WA) -> (NT) G C WA",
504
+ G=self.vqvae_model.vqvae_num_layers,
505
+ C=self.config.vqvae_n_embed,
506
+ )
507
+ # if self.config.sequentially_select is True, bin prediction head first sample the primary code, and then sample secondary code
508
+ if self.config.sequentially_select:
509
+ cbet_primary_logits = self.map_to_cbet_preds_primary_bin(x)
510
+
511
+ # select primary bin first
512
+ cbet_primary_probs = torch.softmax(
513
+ cbet_primary_logits / self.config.bet_softmax_temperature, dim=-1
514
+ )
515
+ NT, choices = cbet_primary_probs.shape
516
+ sampled_primary_centers = einops.rearrange(
517
+ torch.multinomial(cbet_primary_probs.view(-1, choices), num_samples=1),
518
+ "(NT) 1 -> NT",
519
+ NT=NT,
520
+ )
521
+
522
+ cbet_secondary_logits = self.map_to_cbet_preds_secondary_bin(
523
+ torch.cat(
524
+ (x, F.one_hot(sampled_primary_centers, num_classes=self.config.vqvae_n_embed)),
525
+ axis=1,
526
+ )
527
+ )
528
+ cbet_secondary_probs = torch.softmax(
529
+ cbet_secondary_logits / self.config.bet_softmax_temperature, dim=-1
530
+ )
531
+ sampled_secondary_centers = einops.rearrange(
532
+ torch.multinomial(cbet_secondary_probs.view(-1, choices), num_samples=1),
533
+ "(NT) 1 -> NT",
534
+ NT=NT,
535
+ )
536
+ sampled_centers = torch.stack((sampled_primary_centers, sampled_secondary_centers), axis=1)
537
+ cbet_logits = torch.stack([cbet_primary_logits, cbet_secondary_logits], dim=1)
538
+ # if self.config.sequentially_select is False, bin prediction head samples primary and secondary code at once.
539
+ else:
540
+ cbet_logits = self.map_to_cbet_preds_bin(x)
541
+ cbet_logits = einops.rearrange(
542
+ cbet_logits, "(NT) (G C) -> (NT) G C", G=self.vqvae_model.vqvae_num_layers
543
+ )
544
+ cbet_probs = torch.softmax(cbet_logits / self.config.bet_softmax_temperature, dim=-1)
545
+ NT, G, choices = cbet_probs.shape
546
+ sampled_centers = einops.rearrange(
547
+ torch.multinomial(cbet_probs.view(-1, choices), num_samples=1),
548
+ "(NT G) 1 -> NT G",
549
+ NT=NT,
550
+ )
551
+
552
+ device = get_device_from_parameters(self)
553
+ indices = (
554
+ torch.arange(NT, device=device).unsqueeze(1),
555
+ torch.arange(self.vqvae_model.vqvae_num_layers, device=device).unsqueeze(0),
556
+ sampled_centers,
557
+ )
558
+ # Use advanced indexing to sample the values (Extract the only offsets corresponding to the sampled codes.)
559
+ sampled_offsets = cbet_offsets[indices]
560
+ # Then, sum the offsets over the RVQ layers to get a net offset for the bin prediction
561
+ sampled_offsets = sampled_offsets.sum(dim=1)
562
+ with torch.no_grad():
563
+ # Get the centroids (= vectors corresponding to the codes) of each layer to pass it through RVQ decoder
564
+ return_decoder_input = self.vqvae_model.get_embeddings_from_code(sampled_centers).clone().detach()
565
+ # pass the centroids through decoder to get actions.
566
+ decoded_action = self.vqvae_model.get_action_from_latent(return_decoder_input).clone().detach()
567
+ # reshaped extracted offset to match with decoded centroids
568
+ sampled_offsets = einops.rearrange(
569
+ sampled_offsets, "NT (W A) -> NT W A", W=self.config.action_chunk_size
570
+ )
571
+ # add offset and decoded centroids
572
+ predicted_action = decoded_action + sampled_offsets
573
+ predicted_action = einops.rearrange(
574
+ predicted_action,
575
+ "(N T) W A -> N T (W A)",
576
+ N=N,
577
+ T=T,
578
+ W=self.config.action_chunk_size,
579
+ )
580
+
581
+ return {
582
+ "cbet_logits": cbet_logits,
583
+ "predicted_action": predicted_action,
584
+ "sampled_centers": sampled_centers,
585
+ "decoded_action": decoded_action,
586
+ }
587
+
588
+ def loss_fn(self, pred, target, **kwargs):
589
+ """
590
+ for given ground truth action values (target), and prediction (pred) this function calculates the overall loss.
591
+
592
+ predicted_action: predicted action chunk (offset + decoded centroids)
593
+ sampled_centers: sampled centroids (code of RVQ)
594
+ decoded_action: decoded action, which is produced by passing sampled_centers through RVQ decoder
595
+ NT: batch size * T
596
+ T: number of action query tokens, which are process through same GPT
597
+ cbet_logits: probability of all codes in each layer
598
+ """
599
+ action_seq = target
600
+ predicted_action = pred["predicted_action"]
601
+ sampled_centers = pred["sampled_centers"]
602
+ decoded_action = pred["decoded_action"]
603
+ NT = predicted_action.shape[0] * predicted_action.shape[1]
604
+
605
+ cbet_logits = pred["cbet_logits"]
606
+
607
+ predicted_action = einops.rearrange(
608
+ predicted_action, "N T (W A) -> (N T) W A", W=self.config.action_chunk_size
609
+ )
610
+
611
+ action_seq = einops.rearrange(action_seq, "N T W A -> (N T) W A")
612
+ # Figure out the loss for the actions.
613
+ # First, we need to find the closest cluster center for each ground truth action.
614
+ with torch.no_grad():
615
+ state_vq, action_bins = self.vqvae_model.get_code(action_seq) # action_bins: NT, G
616
+
617
+ # Now we can compute the loss.
618
+
619
+ # offset loss is L1 distance between the predicted action and ground truth action
620
+ offset_loss = F.l1_loss(action_seq, predicted_action)
621
+
622
+ # calculate primary code prediction loss
623
+ cbet_loss1 = self._focal_loss_fn(
624
+ cbet_logits[:, 0, :],
625
+ action_bins[:, 0],
626
+ )
627
+ # calculate secondary code prediction loss
628
+ cbet_loss2 = self._focal_loss_fn(
629
+ cbet_logits[:, 1, :],
630
+ action_bins[:, 1],
631
+ )
632
+ # add all the prediction loss
633
+ cbet_loss = (
634
+ cbet_loss1 * self.config.primary_code_loss_weight
635
+ + cbet_loss2 * self.config.secondary_code_loss_weight
636
+ )
637
+
638
+ equal_primary_code_rate = torch.sum((action_bins[:, 0] == sampled_centers[:, 0]).int()) / (NT)
639
+ equal_secondary_code_rate = torch.sum((action_bins[:, 1] == sampled_centers[:, 1]).int()) / (NT)
640
+
641
+ action_mse_error = torch.mean((action_seq - predicted_action) ** 2)
642
+ vq_action_error = torch.mean(torch.abs(action_seq - decoded_action))
643
+ offset_action_error = torch.mean(torch.abs(action_seq - predicted_action))
644
+ action_error_max = torch.max(torch.abs(action_seq - predicted_action))
645
+
646
+ loss = cbet_loss + self.config.offset_loss_weight * offset_loss
647
+
648
+ loss_dict = {
649
+ "loss": loss,
650
+ "classification_loss": cbet_loss.detach().cpu().item(),
651
+ "offset_loss": offset_loss.detach().cpu().item(),
652
+ "equal_primary_code_rate": equal_primary_code_rate.detach().cpu().item(),
653
+ "equal_secondary_code_rate": equal_secondary_code_rate.detach().cpu().item(),
654
+ "vq_action_error": vq_action_error.detach().cpu().item(),
655
+ "offset_action_error": offset_action_error.detach().cpu().item(),
656
+ "action_error_max": action_error_max.detach().cpu().item(),
657
+ "action_mse_error": action_mse_error.detach().cpu().item(),
658
+ }
659
+ return loss_dict
660
+
661
+
662
+ class VQBeTRgbEncoder(nn.Module):
663
+ """Encode an RGB image into a 1D feature vector.
664
+
665
+ Includes the ability to normalize and crop the image first.
666
+
667
+ Same with DiffusionRgbEncoder from modeling_diffusion.py
668
+ """
669
+
670
+ def __init__(self, config: VQBeTConfig):
671
+ super().__init__()
672
+ # Set up optional preprocessing.
673
+ if config.crop_shape is not None:
674
+ self.do_crop = True
675
+ # Always use center crop for eval
676
+ self.center_crop = torchvision.transforms.CenterCrop(config.crop_shape)
677
+ if config.crop_is_random:
678
+ self.maybe_random_crop = torchvision.transforms.RandomCrop(config.crop_shape)
679
+ else:
680
+ self.maybe_random_crop = self.center_crop
681
+ else:
682
+ self.do_crop = False
683
+
684
+ # Set up backbone.
685
+ backbone_model = getattr(torchvision.models, config.vision_backbone)(
686
+ weights=config.pretrained_backbone_weights
687
+ )
688
+ # Note: This assumes that the layer4 feature map is children()[-3]
689
+ # TODO(alexander-soare): Use a safer alternative.
690
+ self.backbone = nn.Sequential(*(list(backbone_model.children())[:-2]))
691
+ if config.use_group_norm:
692
+ if config.pretrained_backbone_weights:
693
+ raise ValueError(
694
+ "You can't replace BatchNorm in a pretrained model without ruining the weights!"
695
+ )
696
+ self.backbone = _replace_submodules(
697
+ root_module=self.backbone,
698
+ predicate=lambda x: isinstance(x, nn.BatchNorm2d),
699
+ func=lambda x: nn.GroupNorm(num_groups=x.num_features // 16, num_channels=x.num_features),
700
+ )
701
+
702
+ # Set up pooling and final layers.
703
+ # Use a dry run to get the feature map shape.
704
+ # The dummy input should take the number of image channels from `config.image_features` and it should
705
+ # use the height and width from `config.crop_shape` if it is provided, otherwise it should use the
706
+ # height and width from `config.image_features`.
707
+
708
+ images_shape = next(iter(config.image_features.values())).shape
709
+ dummy_shape_h_w = config.crop_shape if config.crop_shape is not None else images_shape[1:]
710
+ dummy_shape = (1, images_shape[0], *dummy_shape_h_w)
711
+ feature_map_shape = get_output_shape(self.backbone, dummy_shape)[1:]
712
+
713
+ self.pool = SpatialSoftmax(feature_map_shape, num_kp=config.spatial_softmax_num_keypoints)
714
+ self.feature_dim = config.spatial_softmax_num_keypoints * 2
715
+ self.out = nn.Linear(config.spatial_softmax_num_keypoints * 2, self.feature_dim)
716
+ self.relu = nn.ReLU()
717
+
718
+ def forward(self, x: Tensor) -> Tensor:
719
+ """
720
+ Args:
721
+ x: (B, C, H, W) image tensor with pixel values in [0, 1].
722
+ Returns:
723
+ (B, D) image feature.
724
+ """
725
+ # Preprocess: maybe crop (if it was set up in the __init__).
726
+ if self.do_crop:
727
+ if self.training: # noqa: SIM108
728
+ x = self.maybe_random_crop(x)
729
+ else:
730
+ # Always use center crop for eval.
731
+ x = self.center_crop(x)
732
+ # Extract backbone feature.
733
+ x = torch.flatten(self.pool(self.backbone(x)), start_dim=1)
734
+ # Final linear layer with non-linearity.
735
+ x = self.relu(self.out(x))
736
+ return x
737
+
738
+
739
+ def _replace_submodules(
740
+ root_module: nn.Module, predicate: Callable[[nn.Module], bool], func: Callable[[nn.Module], nn.Module]
741
+ ) -> nn.Module:
742
+ """
743
+ Args:
744
+ root_module: The module for which the submodules need to be replaced
745
+ predicate: Takes a module as an argument and must return True if the that module is to be replaced.
746
+ func: Takes a module as an argument and returns a new module to replace it with.
747
+ Returns:
748
+ The root module with its submodules replaced.
749
+ """
750
+ if predicate(root_module):
751
+ return func(root_module)
752
+
753
+ replace_list = [k.split(".") for k, m in root_module.named_modules(remove_duplicate=True) if predicate(m)]
754
+ for *parents, k in replace_list:
755
+ parent_module = root_module
756
+ if len(parents) > 0:
757
+ parent_module = root_module.get_submodule(".".join(parents))
758
+ if isinstance(parent_module, nn.Sequential):
759
+ src_module = parent_module[int(k)]
760
+ else:
761
+ src_module = getattr(parent_module, k)
762
+ tgt_module = func(src_module)
763
+ if isinstance(parent_module, nn.Sequential):
764
+ parent_module[int(k)] = tgt_module
765
+ else:
766
+ setattr(parent_module, k, tgt_module)
767
+ # verify that all BN are replaced
768
+ assert not any(predicate(m) for _, m in root_module.named_modules(remove_duplicate=True))
769
+ return root_module
770
+
771
+
772
+ class VqVae(nn.Module):
773
+ def __init__(
774
+ self,
775
+ config: VQBeTConfig,
776
+ ):
777
+ """
778
+ VQ-VAE is composed of three parts: encoder, vq_layer, and decoder.
779
+ Encoder and decoder are MLPs consisting of an input, output layer, and hidden layer, respectively.
780
+ The vq_layer uses residual VQs.
781
+
782
+ This class contains functions for training the encoder and decoder along with the residual VQ layer (for training phase 1),
783
+ as well as functions to help BeT training part in training phase 2.
784
+ """
785
+
786
+ super().__init__()
787
+ self.config = config
788
+ # 'discretized' indicates whether the Residual VQ part is trained or not. (After finishing the training, we set discretized=True)
789
+ self.register_buffer("discretized", torch.tensor(False))
790
+ self.optimized_steps = 0
791
+ # we use the fixed number of layers for Residual VQ across all environments.
792
+ self.vqvae_num_layers = 2
793
+
794
+ self.vq_layer = ResidualVQ(
795
+ dim=config.vqvae_embedding_dim,
796
+ num_quantizers=self.vqvae_num_layers,
797
+ codebook_size=config.vqvae_n_embed,
798
+ )
799
+
800
+ self.encoder = MLP(
801
+ in_channels=self.config.action_feature.shape[0] * self.config.action_chunk_size,
802
+ hidden_channels=[
803
+ config.vqvae_enc_hidden_dim,
804
+ config.vqvae_enc_hidden_dim,
805
+ config.vqvae_embedding_dim,
806
+ ],
807
+ )
808
+ self.decoder = MLP(
809
+ in_channels=config.vqvae_embedding_dim,
810
+ hidden_channels=[
811
+ config.vqvae_enc_hidden_dim,
812
+ config.vqvae_enc_hidden_dim,
813
+ self.config.action_feature.shape[0] * self.config.action_chunk_size,
814
+ ],
815
+ )
816
+
817
+ def get_embeddings_from_code(self, encoding_indices):
818
+ # This function gets code indices as inputs, and outputs embedding vectors corresponding to the code indices.
819
+ with torch.no_grad():
820
+ z_embed = self.vq_layer.get_codebook_vector_from_indices(encoding_indices)
821
+ # since the RVQ has multiple layers, it adds the vectors in the axis of layers to provide a vector for that code combination.
822
+ z_embed = z_embed.sum(dim=0)
823
+ return z_embed
824
+
825
+ def get_action_from_latent(self, latent):
826
+ # given latent vector, this function outputs the decoded action.
827
+ output = self.decoder(latent)
828
+ if self.config.action_chunk_size == 1:
829
+ return einops.rearrange(output, "N (T A) -> N T A", A=self.config.action_feature.shape[0])
830
+ else:
831
+ return einops.rearrange(output, "N (T A) -> N T A", A=self.config.action_feature.shape[0])
832
+
833
+ def get_code(self, state):
834
+ # in phase 2 of VQ-BeT training, we need a `ground truth labels of action data` to calculate the Focal loss for code prediction head. (please refer to section 3.3 in the paper https://huggingface.co/papers/2403.03181)
835
+ # this function outputs the `GT code` of given action using frozen encoder and quantization layers. (please refer to Figure 2. in the paper https://huggingface.co/papers/2403.03181)
836
+ state = einops.rearrange(state, "N T A -> N (T A)")
837
+ with torch.no_grad():
838
+ state_rep = self.encoder(state)
839
+ state_rep_shape = state_rep.shape[:-1]
840
+ state_rep_flat = state_rep.view(state_rep.size(0), -1, state_rep.size(1))
841
+ state_rep_flat, vq_code, vq_loss_state = self.vq_layer(state_rep_flat)
842
+ state_vq = state_rep_flat.view(*state_rep_shape, -1)
843
+ vq_code = vq_code.view(*state_rep_shape, -1)
844
+ vq_loss_state = torch.sum(vq_loss_state)
845
+ return state_vq, vq_code
846
+
847
+ def vqvae_forward(self, state):
848
+ # This function passes the given data through Residual VQ with Encoder and Decoder. Please refer to section 3.2 in the paper https://huggingface.co/papers/2403.03181).
849
+ state = einops.rearrange(state, "N T A -> N (T A)")
850
+ # We start with passing action (or action chunk) at:t+n through the encoder ϕ.
851
+ state_rep = self.encoder(state)
852
+ state_rep_shape = state_rep.shape[:-1]
853
+ state_rep_flat = state_rep.view(state_rep.size(0), -1, state_rep.size(1))
854
+ # The resulting latent embedding vector x = ϕ(at:t+n) is then mapped to an embedding vector in the codebook of the RVQ layers by the nearest neighbor look-up.
855
+ state_rep_flat, vq_code, vq_loss_state = self.vq_layer(state_rep_flat)
856
+ state_vq = state_rep_flat.view(*state_rep_shape, -1)
857
+ vq_code = vq_code.view(*state_rep_shape, -1)
858
+ # since the RVQ has multiple layers, it adds the vectors in the axis of layers to provide a vector for that code combination.
859
+ vq_loss_state = torch.sum(vq_loss_state)
860
+ # Then, the discretized vector zq(x) is reconstructed as ψ(zq(x)) by passing through the decoder ψ.
861
+ dec_out = self.decoder(state_vq)
862
+ # Calculate L1 reconstruction loss
863
+ encoder_loss = (state - dec_out).abs().mean()
864
+ # add encoder reconstruction loss and commitment loss
865
+ rep_loss = encoder_loss + vq_loss_state * 5
866
+
867
+ metric = (
868
+ encoder_loss.clone().detach(),
869
+ vq_loss_state.clone().detach(),
870
+ vq_code,
871
+ rep_loss.item(),
872
+ )
873
+ return rep_loss, metric
874
+
875
+
876
+ class FocalLoss(nn.Module):
877
+ """
878
+ From https://github.com/notmahi/miniBET/blob/main/behavior_transformer/bet.py
879
+ """
880
+
881
+ def __init__(self, gamma: float = 0, size_average: bool = True):
882
+ super().__init__()
883
+ self.gamma = gamma
884
+ self.size_average = size_average
885
+
886
+ def forward(self, input, target):
887
+ if len(input.shape) == 3:
888
+ N, T, _ = input.shape
889
+ logpt = F.log_softmax(input, dim=-1)
890
+ logpt = logpt.gather(-1, target.view(N, T, 1)).view(N, T)
891
+ elif len(input.shape) == 2:
892
+ logpt = F.log_softmax(input, dim=-1)
893
+ logpt = logpt.gather(-1, target.view(-1, 1)).view(-1)
894
+ pt = logpt.exp()
895
+
896
+ loss = -1 * (1 - pt) ** self.gamma * logpt
897
+ if self.size_average:
898
+ return loss.mean()
899
+ else:
900
+ return loss.sum()
901
+
902
+
903
+ class MLP(torch.nn.Sequential):
904
+ def __init__(
905
+ self,
906
+ in_channels: int,
907
+ hidden_channels: list[int],
908
+ ):
909
+ layers = []
910
+ in_dim = in_channels
911
+ for hidden_dim in hidden_channels[:-1]:
912
+ layers.append(torch.nn.Linear(in_dim, hidden_dim))
913
+ layers.append(torch.nn.ReLU())
914
+ in_dim = hidden_dim
915
+
916
+ layers.append(torch.nn.Linear(in_dim, hidden_channels[-1]))
917
+
918
+ super().__init__(*layers)
tools/lerobot_v21_runtime/src/lerobot/policies/vqbet/vqbet_utils.py ADDED
@@ -0,0 +1,1462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright 2024 Seungjae Lee and Yibin Wang and Haritheja Etukuru
4
+ # and H. Jin Kim and Nur Muhammad Mahi Shafiullah and Lerrel Pinto
5
+ # and The HuggingFace Inc. team. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import math
20
+ from collections.abc import Callable
21
+ from functools import partial
22
+ from math import ceil
23
+ from random import randrange
24
+
25
+ import torch
26
+ import torch.distributed as distributed
27
+ import torch.nn.functional as F # noqa: N812
28
+ from einops import pack, rearrange, reduce, repeat, unpack
29
+ from torch import einsum, nn
30
+ from torch.cuda.amp import autocast
31
+ from torch.optim import Optimizer
32
+
33
+ from lerobot.policies.vqbet.configuration_vqbet import VQBeTConfig
34
+
35
+ # ruff: noqa: N806
36
+
37
+ """
38
+ This file is part of a VQ-BeT that utilizes code from the following repositories:
39
+
40
+ - Vector Quantize PyTorch code is licensed under the MIT License:
41
+ Original source: https://github.com/lucidrains/vector-quantize-pytorch
42
+
43
+ - nanoGPT part is an adaptation of Andrej Karpathy's nanoGPT implementation in PyTorch.
44
+ Original source: https://github.com/karpathy/nanoGPT
45
+
46
+ We also made some changes to the original code to adapt it to our needs. The changes are described in the code below.
47
+ """
48
+
49
+ """
50
+ This is a part for nanoGPT that utilizes code from the following repository:
51
+
52
+ - Andrej Karpathy's nanoGPT implementation in PyTorch.
53
+ Original source: https://github.com/karpathy/nanoGPT
54
+
55
+ - The nanoGPT code is licensed under the MIT License:
56
+
57
+ MIT License
58
+
59
+ Copyright (c) 2022 Andrej Karpathy
60
+
61
+ Permission is hereby granted, free of charge, to any person obtaining a copy
62
+ of this software and associated documentation files (the "Software"), to deal
63
+ in the Software without restriction, including without limitation the rights
64
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
65
+ copies of the Software, and to permit persons to whom the Software is
66
+ furnished to do so, subject to the following conditions:
67
+
68
+ The above copyright notice and this permission notice shall be included in all
69
+ copies or substantial portions of the Software.
70
+
71
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
72
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
73
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
74
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
75
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
76
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
77
+ SOFTWARE.
78
+
79
+ - We've made some changes to the original code to adapt it to our needs.
80
+
81
+ Changed variable names:
82
+ - n_head -> gpt_n_head
83
+ - n_embd -> gpt_hidden_dim
84
+ - block_size -> gpt_block_size
85
+ - n_layer -> gpt_n_layer
86
+
87
+
88
+ class GPT(nn.Module):
89
+ - removed unused functions `def generate`, `def estimate_mfu`, and `def from_pretrained`
90
+ - changed the `configure_optimizers` to `def configure_parameters` and made it to return only the parameters of the model: we use an external optimizer in our training loop.
91
+ - in the function `forward`, we removed target loss calculation parts, since it will be calculated in the training loop (after passing through bin prediction and offset prediction heads).
92
+
93
+ """
94
+
95
+
96
+ class CausalSelfAttention(nn.Module):
97
+ def __init__(self, config):
98
+ super().__init__()
99
+ assert config.gpt_hidden_dim % config.gpt_n_head == 0
100
+ # key, query, value projections for all heads, but in a batch
101
+ self.c_attn = nn.Linear(config.gpt_hidden_dim, 3 * config.gpt_hidden_dim)
102
+ # output projection
103
+ self.c_proj = nn.Linear(config.gpt_hidden_dim, config.gpt_hidden_dim)
104
+ # regularization
105
+ self.attn_dropout = nn.Dropout(config.dropout)
106
+ self.resid_dropout = nn.Dropout(config.dropout)
107
+ # causal mask to ensure that attention is only applied to the left in the input sequence
108
+ self.register_buffer(
109
+ "bias",
110
+ torch.tril(torch.ones(config.gpt_block_size, config.gpt_block_size)).view(
111
+ 1, 1, config.gpt_block_size, config.gpt_block_size
112
+ ),
113
+ )
114
+ self.gpt_n_head = config.gpt_n_head
115
+ self.gpt_hidden_dim = config.gpt_hidden_dim
116
+
117
+ def forward(self, x):
118
+ (
119
+ B,
120
+ T,
121
+ C,
122
+ ) = x.size() # batch size, sequence length, embedding dimensionality (gpt_hidden_dim)
123
+
124
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
125
+ q, k, v = self.c_attn(x).split(self.gpt_hidden_dim, dim=2)
126
+ k = k.view(B, T, self.gpt_n_head, C // self.gpt_n_head).transpose(1, 2) # (B, nh, T, hs)
127
+ q = q.view(B, T, self.gpt_n_head, C // self.gpt_n_head).transpose(1, 2) # (B, nh, T, hs)
128
+ v = v.view(B, T, self.gpt_n_head, C // self.gpt_n_head).transpose(1, 2) # (B, nh, T, hs)
129
+
130
+ # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
131
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
132
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float("-inf"))
133
+ att = F.softmax(att, dim=-1)
134
+ att = self.attn_dropout(att)
135
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
136
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
137
+
138
+ # output projection
139
+ y = self.resid_dropout(self.c_proj(y))
140
+ return y
141
+
142
+
143
+ class Block(nn.Module):
144
+ # causual self-attention block for GPT
145
+ def __init__(self, config):
146
+ super().__init__()
147
+ self.ln_1 = nn.LayerNorm(config.gpt_hidden_dim)
148
+ self.attn = CausalSelfAttention(config)
149
+ self.ln_2 = nn.LayerNorm(config.gpt_hidden_dim)
150
+ self.mlp = nn.Sequential(
151
+ nn.Linear(config.gpt_hidden_dim, 4 * config.gpt_hidden_dim),
152
+ nn.GELU(),
153
+ nn.Linear(4 * config.gpt_hidden_dim, config.gpt_hidden_dim),
154
+ nn.Dropout(config.dropout),
155
+ )
156
+
157
+ def forward(self, x):
158
+ x = x + self.attn(self.ln_1(x))
159
+ x = x + self.mlp(self.ln_2(x))
160
+ return x
161
+
162
+
163
+ class GPT(nn.Module):
164
+ """
165
+ Original comments:
166
+ Full definition of a GPT Language Model, all of it in this single file.
167
+ References:
168
+ 1) the official GPT-2 TensorFlow implementation released by OpenAI:
169
+ https://github.com/openai/gpt-2/blob/master/src/model.py
170
+ 2) huggingface/transformers PyTorch implementation:
171
+ https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
172
+ """
173
+
174
+ def __init__(self, config: VQBeTConfig):
175
+ """
176
+ GPT model gets hyperparameters from a config object. Please refer configuration_vqbet.py for more details.
177
+ """
178
+ super().__init__()
179
+ assert config.gpt_output_dim is not None
180
+ assert config.gpt_block_size is not None
181
+ self.config = config
182
+
183
+ self.transformer = nn.ModuleDict(
184
+ {
185
+ "wte": nn.Linear(config.gpt_input_dim, config.gpt_hidden_dim),
186
+ "wpe": nn.Embedding(config.gpt_block_size, config.gpt_hidden_dim),
187
+ "drop": nn.Dropout(config.dropout),
188
+ "h": nn.ModuleList([Block(config) for _ in range(config.gpt_n_layer)]),
189
+ "ln_f": nn.LayerNorm(config.gpt_hidden_dim),
190
+ }
191
+ )
192
+ self.lm_head = nn.Linear(config.gpt_hidden_dim, config.gpt_output_dim, bias=False)
193
+ # init all weights, and apply a special scaled init to the residual projections, per GPT-2 paper
194
+ self.apply(self._init_weights)
195
+ for pn, p in self.named_parameters():
196
+ if pn.endswith("c_proj.weight"):
197
+ torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * config.gpt_n_layer))
198
+
199
+ # report number of parameters
200
+ n_params = sum(p.numel() for p in self.parameters())
201
+ print(f"number of parameters: {n_params / 1e6:.2f}M")
202
+
203
+ def forward(self, input, targets=None):
204
+ device = input.device
205
+ b, t, d = input.size()
206
+ assert t <= self.config.gpt_block_size, (
207
+ f"Cannot forward sequence of length {t}, block size is only {self.config.gpt_block_size}"
208
+ )
209
+
210
+ # positional encodings that are added to the input embeddings
211
+ pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0) # shape (1, t)
212
+
213
+ # forward the GPT model itself
214
+ tok_emb = self.transformer.wte(input) # token embeddings of shape (b, t, gpt_hidden_dim)
215
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (1, t, gpt_hidden_dim)
216
+ x = self.transformer.drop(tok_emb + pos_emb)
217
+ for block in self.transformer.h:
218
+ x = block(x)
219
+ x = self.transformer.ln_f(x)
220
+ logits = self.lm_head(x)
221
+ return logits
222
+
223
+ def _init_weights(self, module):
224
+ if isinstance(module, nn.Linear):
225
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
226
+ if module.bias is not None:
227
+ torch.nn.init.zeros_(module.bias)
228
+ elif isinstance(module, nn.Embedding):
229
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
230
+ elif isinstance(module, nn.LayerNorm):
231
+ torch.nn.init.zeros_(module.bias)
232
+ torch.nn.init.ones_(module.weight)
233
+
234
+ def crop_block_size(self, gpt_block_size):
235
+ # model surgery to decrease the block size if necessary
236
+ # e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
237
+ # but want to use a smaller block size for some smaller, simpler model
238
+ assert gpt_block_size <= self.config.gpt_block_size
239
+ self.config.gpt_block_size = gpt_block_size
240
+ self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:gpt_block_size])
241
+ for block in self.transformer.h:
242
+ block.attn.bias = block.attn.bias[:, :, :gpt_block_size, :gpt_block_size]
243
+
244
+ def configure_parameters(self):
245
+ """
246
+ This long function is unfortunately doing something very simple and is being very defensive:
247
+ We are separating out all parameters of the model into two buckets: those that will experience
248
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
249
+ """
250
+
251
+ # separate out all parameters to those that will and won't experience regularizing weight decay
252
+ decay = set()
253
+ no_decay = set()
254
+ whitelist_weight_modules = (torch.nn.Linear,)
255
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
256
+ for mn, m in self.named_modules():
257
+ for pn, _p in m.named_parameters():
258
+ fpn = f"{mn}.{pn}" if mn else pn # full param name
259
+ if pn.endswith("bias"):
260
+ # all biases will not be decayed
261
+ no_decay.add(fpn)
262
+ elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules):
263
+ # weights of whitelist modules will be weight decayed
264
+ decay.add(fpn)
265
+ elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules):
266
+ # weights of blacklist modules will NOT be weight decayed
267
+ no_decay.add(fpn)
268
+
269
+ # validate that we considered every parameter
270
+ param_dict = dict(self.named_parameters())
271
+ inter_params = decay & no_decay
272
+ union_params = decay | no_decay
273
+ assert len(inter_params) == 0, "parameters {} made it into both decay/no_decay sets!".format(
274
+ str(inter_params)
275
+ )
276
+ assert len(param_dict.keys() - union_params) == 0, (
277
+ "parameters {} were not separated into either decay/no_decay set!".format(
278
+ str(param_dict.keys() - union_params),
279
+ )
280
+ )
281
+
282
+ decay = [param_dict[pn] for pn in sorted(decay)]
283
+ no_decay = [param_dict[pn] for pn in sorted(no_decay)]
284
+ # return the parameters that require weight decay, and the parameters that don't separately.
285
+ return decay, no_decay
286
+
287
+
288
+ """
289
+ This file is a part for Residual Vector Quantization that utilizes code from the following repository:
290
+
291
+ - Phil Wang's vector-quantize-pytorch implementation in PyTorch.
292
+ Original source: https://github.com/lucidrains/vector-quantize-pytorch
293
+
294
+ - The vector-quantize-pytorch code is licensed under the MIT License:
295
+
296
+ MIT License
297
+
298
+ Copyright (c) 2020 Phil Wang
299
+
300
+ Permission is hereby granted, free of charge, to any person obtaining a copy
301
+ of this software and associated documentation files (the "Software"), to deal
302
+ in the Software without restriction, including without limitation the rights
303
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
304
+ copies of the Software, and to permit persons to whom the Software is
305
+ furnished to do so, subject to the following conditions:
306
+
307
+ The above copyright notice and this permission notice shall be included in all
308
+ copies or substantial portions of the Software.
309
+
310
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
311
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
312
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
313
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
314
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
315
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
316
+ SOFTWARE.
317
+
318
+ - We've made some changes to the original code to adapt it to our needs.
319
+
320
+ class ResidualVQ(nn.Module):
321
+ - added `self.register_buffer('freeze_codebook', torch.tensor(False))` to the __init__ method:
322
+ This enables the user to save an indicator whether the codebook is frozen or not.
323
+ - changed the name of function `get_codes_from_indices` → `get_codebook_vector_from_indices`:
324
+ This is to make the function name more descriptive.
325
+
326
+ class VectorQuantize(nn.Module):
327
+ - removed the `use_cosine_sim` and `layernorm_after_project_in` parameters from the __init__ method:
328
+ These parameters are not used in the code.
329
+ - changed the name of function `get_codes_from_indices` → `get_codebook_vector_from_indices`:
330
+ This is to make the function name more descriptive.
331
+
332
+ """
333
+
334
+
335
+ class ResidualVQ(nn.Module):
336
+ """
337
+ Residual VQ is composed of multiple VectorQuantize layers.
338
+
339
+ Follows Algorithm 1. in https://huggingface.co/papers/2107.03312
340
+ "Residual Vector Quantizer (a.k.a. multi-stage vector quantizer [36]) cascades Nq layers of VQ as follows. The unquantized input vector is
341
+ passed through a first VQ and quantization residuals are computed. The residuals are then iteratively quantized by a sequence of additional
342
+ Nq -1 vector quantizers, as described in Algorithm 1."
343
+
344
+
345
+ self.project_in: function for projecting input to codebook dimension
346
+ self.project_out: function for projecting codebook dimension to output dimension
347
+ self.layers: nn.ModuleList of VectorQuantize layers that contains Nq layers of VQ as described in the paper.
348
+ self.freeze_codebook: buffer to save an indicator whether the codebook is frozen or not. VQ-BeT will check this to determine whether to update the codebook or not.
349
+ """
350
+
351
+ def __init__(
352
+ self,
353
+ *,
354
+ dim,
355
+ num_quantizers,
356
+ codebook_dim=None,
357
+ shared_codebook=False,
358
+ heads=1,
359
+ quantize_dropout=False,
360
+ quantize_dropout_cutoff_index=0,
361
+ quantize_dropout_multiple_of=1,
362
+ accept_image_fmap=False,
363
+ **kwargs,
364
+ ):
365
+ super().__init__()
366
+ assert heads == 1, "residual vq is not compatible with multi-headed codes"
367
+ codebook_dim = codebook_dim if (codebook_dim is not None) else dim
368
+ codebook_input_dim = codebook_dim * heads
369
+
370
+ requires_projection = codebook_input_dim != dim
371
+ self.project_in = nn.Linear(dim, codebook_input_dim) if requires_projection else nn.Identity()
372
+ self.project_out = nn.Linear(codebook_input_dim, dim) if requires_projection else nn.Identity()
373
+
374
+ self.num_quantizers = num_quantizers
375
+
376
+ self.accept_image_fmap = accept_image_fmap
377
+ self.layers = nn.ModuleList(
378
+ [
379
+ VectorQuantize(
380
+ dim=codebook_dim, codebook_dim=codebook_dim, accept_image_fmap=accept_image_fmap, **kwargs
381
+ )
382
+ for _ in range(num_quantizers)
383
+ ]
384
+ )
385
+
386
+ self.quantize_dropout = quantize_dropout and num_quantizers > 1
387
+
388
+ assert quantize_dropout_cutoff_index >= 0
389
+
390
+ self.register_buffer("freeze_codebook", torch.tensor(False))
391
+ self.quantize_dropout_cutoff_index = quantize_dropout_cutoff_index
392
+ self.quantize_dropout_multiple_of = quantize_dropout_multiple_of # encodec paper proposes structured dropout, believe this was set to 4
393
+
394
+ if not shared_codebook:
395
+ return
396
+
397
+ first_vq, *rest_vq = self.layers
398
+ codebook = first_vq._codebook
399
+
400
+ for vq in rest_vq:
401
+ vq._codebook = codebook
402
+
403
+ @property
404
+ def codebooks(self):
405
+ codebooks = [layer._codebook.embed for layer in self.layers]
406
+ codebooks = torch.stack(codebooks, dim=0)
407
+ codebooks = rearrange(codebooks, "q 1 c d -> q c d")
408
+ return codebooks
409
+
410
+ def get_codebook_vector_from_indices(self, indices):
411
+ # this function will return the codes from all codebooks across layers corresponding to the indices
412
+ batch, quantize_dim = indices.shape[0], indices.shape[-1]
413
+
414
+ # may also receive indices in the shape of 'b h w q' (accept_image_fmap)
415
+
416
+ indices, ps = pack([indices], "b * q")
417
+
418
+ # because of quantize dropout, one can pass in indices that are coarse
419
+ # and the network should be able to reconstruct
420
+
421
+ if quantize_dim < self.num_quantizers:
422
+ assert self.quantize_dropout > 0.0, (
423
+ "quantize dropout must be greater than 0 if you wish to reconstruct from a signal with less fine quantizations"
424
+ )
425
+ indices = F.pad(indices, (0, self.num_quantizers - quantize_dim), value=-1)
426
+
427
+ # get ready for gathering
428
+
429
+ codebooks = repeat(self.codebooks, "q c d -> q b c d", b=batch)
430
+ gather_indices = repeat(indices, "b n q -> q b n d", d=codebooks.shape[-1])
431
+
432
+ # take care of quantizer dropout
433
+
434
+ mask = gather_indices == -1.0
435
+ gather_indices = gather_indices.masked_fill(
436
+ mask, 0
437
+ ) # have it fetch a dummy code to be masked out later
438
+
439
+ all_codes = codebooks.gather(2, gather_indices) # gather all codes
440
+
441
+ # mask out any codes that were dropout-ed
442
+
443
+ all_codes = all_codes.masked_fill(mask, 0.0)
444
+
445
+ # if (accept_image_fmap = True) then return shape (quantize, batch, height, width, dimension)
446
+
447
+ (all_codes,) = unpack(all_codes, ps, "q b * d")
448
+
449
+ return all_codes
450
+
451
+ def forward(self, x, indices=None, return_all_codes=False, sample_codebook_temp=None):
452
+ """
453
+ For given input tensor x, this function will return the quantized output, the indices of the quantized output, and the loss.
454
+ First, the input tensor x is projected to the codebook dimension. Then, the input tensor x is passed through Nq layers of VectorQuantize.
455
+ The residual value of each layer is fed to the next layer.
456
+ """
457
+ num_quant, quant_dropout_multiple_of, return_loss, device = (
458
+ self.num_quantizers,
459
+ self.quantize_dropout_multiple_of,
460
+ (indices is not None),
461
+ x.device,
462
+ )
463
+
464
+ x = self.project_in(x)
465
+
466
+ assert not (self.accept_image_fmap and (indices is not None))
467
+
468
+ quantized_out = 0.0
469
+ residual = x
470
+
471
+ all_losses = []
472
+ all_indices = []
473
+
474
+ if return_loss:
475
+ assert not torch.any(indices == -1), (
476
+ "some of the residual vq indices were dropped out. please use indices derived when the module is in eval mode to derive cross entropy loss"
477
+ )
478
+ ce_losses = []
479
+
480
+ should_quantize_dropout = self.training and self.quantize_dropout and not return_loss
481
+
482
+ # sample a layer index at which to dropout further residual quantization
483
+ # also prepare null indices and loss
484
+
485
+ if should_quantize_dropout:
486
+ rand_quantize_dropout_index = randrange(self.quantize_dropout_cutoff_index, num_quant)
487
+
488
+ if quant_dropout_multiple_of != 1:
489
+ rand_quantize_dropout_index = (
490
+ ceil((rand_quantize_dropout_index + 1) / quant_dropout_multiple_of)
491
+ * quant_dropout_multiple_of
492
+ - 1
493
+ )
494
+
495
+ null_indices_shape = (x.shape[0], *x.shape[-2:]) if self.accept_image_fmap else tuple(x.shape[:2])
496
+ null_indices = torch.full(null_indices_shape, -1.0, device=device, dtype=torch.long)
497
+ null_loss = torch.full((1,), 0.0, device=device, dtype=x.dtype)
498
+
499
+ # go through the layers
500
+
501
+ for quantizer_index, layer in enumerate(self.layers):
502
+ if should_quantize_dropout and quantizer_index > rand_quantize_dropout_index:
503
+ all_indices.append(null_indices)
504
+ all_losses.append(null_loss)
505
+ continue
506
+
507
+ layer_indices = None
508
+ if return_loss:
509
+ layer_indices = indices[..., quantizer_index]
510
+
511
+ quantized, *rest = layer(
512
+ residual,
513
+ indices=layer_indices,
514
+ sample_codebook_temp=sample_codebook_temp,
515
+ freeze_codebook=self.freeze_codebook,
516
+ )
517
+
518
+ residual = residual - quantized.detach()
519
+ quantized_out = quantized_out + quantized
520
+
521
+ if return_loss:
522
+ ce_loss = rest[0]
523
+ ce_losses.append(ce_loss)
524
+ continue
525
+
526
+ embed_indices, loss = rest
527
+
528
+ all_indices.append(embed_indices)
529
+ all_losses.append(loss)
530
+
531
+ # project out, if needed
532
+
533
+ quantized_out = self.project_out(quantized_out)
534
+
535
+ # whether to early return the cross entropy loss
536
+
537
+ if return_loss:
538
+ return quantized_out, sum(ce_losses)
539
+
540
+ # stack all losses and indices
541
+
542
+ all_losses, all_indices = map(partial(torch.stack, dim=-1), (all_losses, all_indices))
543
+
544
+ ret = (quantized_out, all_indices, all_losses)
545
+
546
+ if return_all_codes:
547
+ # whether to return all codes from all codebooks across layers
548
+ all_codes = self.get_codebook_vector_from_indices(all_indices)
549
+
550
+ # will return all codes in shape (quantizer, batch, sequence length, codebook dimension)
551
+ ret = (*ret, all_codes)
552
+
553
+ return ret
554
+
555
+
556
+ class VectorQuantize(nn.Module):
557
+ def __init__(
558
+ self,
559
+ dim,
560
+ codebook_size,
561
+ codebook_dim=None,
562
+ heads=1,
563
+ separate_codebook_per_head=False,
564
+ decay=0.8,
565
+ eps=1e-5,
566
+ kmeans_init=False,
567
+ kmeans_iters=10,
568
+ sync_kmeans=True,
569
+ threshold_ema_dead_code=0,
570
+ channel_last=True,
571
+ accept_image_fmap=False,
572
+ commitment_weight=1.0,
573
+ commitment_use_cross_entropy_loss=False,
574
+ orthogonal_reg_weight=0.0,
575
+ orthogonal_reg_active_codes_only=False,
576
+ orthogonal_reg_max_codes=None,
577
+ stochastic_sample_codes=False,
578
+ sample_codebook_temp=1.0,
579
+ straight_through=False,
580
+ reinmax=False, # using reinmax for improved straight-through, assuming straight through helps at all
581
+ sync_codebook=None,
582
+ sync_affine_param=False,
583
+ ema_update=True,
584
+ learnable_codebook=False,
585
+ in_place_codebook_optimizer: Callable[
586
+ ..., Optimizer
587
+ ] = None, # Optimizer used to update the codebook embedding if using learnable_codebook
588
+ affine_param=False,
589
+ affine_param_batch_decay=0.99,
590
+ affine_param_codebook_decay=0.9,
591
+ sync_update_v=0.0, # the v that controls optimistic vs pessimistic update for synchronous update rule (21) https://minyoungg.github.io/vqtorch/assets/draft_050523.pdf
592
+ ):
593
+ super().__init__()
594
+ self.dim = dim
595
+ self.heads = heads
596
+ self.separate_codebook_per_head = separate_codebook_per_head
597
+
598
+ codebook_dim = codebook_dim if (codebook_dim is not None) else dim
599
+ codebook_input_dim = codebook_dim * heads
600
+
601
+ requires_projection = codebook_input_dim != dim
602
+ self.project_in = nn.Linear(dim, codebook_input_dim) if requires_projection else nn.Identity()
603
+ self.project_out = nn.Linear(codebook_input_dim, dim) if requires_projection else nn.Identity()
604
+
605
+ self.eps = eps
606
+ self.commitment_weight = commitment_weight
607
+ self.commitment_use_cross_entropy_loss = commitment_use_cross_entropy_loss # whether to use cross entropy loss to codebook as commitment loss
608
+
609
+ self.learnable_codebook = learnable_codebook
610
+
611
+ has_codebook_orthogonal_loss = orthogonal_reg_weight > 0
612
+ self.has_codebook_orthogonal_loss = has_codebook_orthogonal_loss
613
+ self.orthogonal_reg_weight = orthogonal_reg_weight
614
+ self.orthogonal_reg_active_codes_only = orthogonal_reg_active_codes_only
615
+ self.orthogonal_reg_max_codes = orthogonal_reg_max_codes
616
+
617
+ assert not (ema_update and learnable_codebook), "learnable codebook not compatible with EMA update"
618
+
619
+ assert 0 <= sync_update_v <= 1.0
620
+ assert not (sync_update_v > 0.0 and not learnable_codebook), "learnable codebook must be turned on"
621
+
622
+ self.sync_update_v = sync_update_v
623
+
624
+ gumbel_sample_fn = partial(
625
+ gumbel_sample,
626
+ stochastic=stochastic_sample_codes,
627
+ reinmax=reinmax,
628
+ straight_through=straight_through,
629
+ )
630
+
631
+ if sync_codebook is None:
632
+ sync_codebook = distributed.is_initialized() and distributed.get_world_size() > 1
633
+
634
+ codebook_kwargs = {
635
+ "dim": codebook_dim,
636
+ "num_codebooks": heads if separate_codebook_per_head else 1,
637
+ "codebook_size": codebook_size,
638
+ "kmeans_init": kmeans_init,
639
+ "kmeans_iters": kmeans_iters,
640
+ "sync_kmeans": sync_kmeans,
641
+ "decay": decay,
642
+ "eps": eps,
643
+ "threshold_ema_dead_code": threshold_ema_dead_code,
644
+ "use_ddp": sync_codebook,
645
+ "learnable_codebook": has_codebook_orthogonal_loss or learnable_codebook,
646
+ "sample_codebook_temp": sample_codebook_temp,
647
+ "gumbel_sample": gumbel_sample_fn,
648
+ "ema_update": ema_update,
649
+ }
650
+
651
+ if affine_param:
652
+ codebook_kwargs = dict(
653
+ **codebook_kwargs,
654
+ affine_param=True,
655
+ sync_affine_param=sync_affine_param,
656
+ affine_param_batch_decay=affine_param_batch_decay,
657
+ affine_param_codebook_decay=affine_param_codebook_decay,
658
+ )
659
+
660
+ self._codebook = EuclideanCodebook(**codebook_kwargs)
661
+
662
+ self.in_place_codebook_optimizer = (
663
+ in_place_codebook_optimizer(self._codebook.parameters())
664
+ if (in_place_codebook_optimizer is not None)
665
+ else None
666
+ )
667
+
668
+ self.codebook_size = codebook_size
669
+
670
+ self.accept_image_fmap = accept_image_fmap
671
+ self.channel_last = channel_last
672
+
673
+ @property
674
+ def codebook(self):
675
+ codebook = self._codebook.embed
676
+
677
+ if self.separate_codebook_per_head:
678
+ return codebook
679
+
680
+ return rearrange(codebook, "1 ... -> ...")
681
+
682
+ @codebook.setter
683
+ def codebook(self, codes):
684
+ if not self.separate_codebook_per_head:
685
+ codes = rearrange(codes, "... -> 1 ...")
686
+
687
+ self._codebook.embed.copy_(codes)
688
+
689
+ def get_codebook_vector_from_indices(self, indices):
690
+ codebook = self.codebook
691
+ is_multiheaded = codebook.ndim > 2
692
+
693
+ if not is_multiheaded:
694
+ codes = codebook[indices]
695
+ return rearrange(codes, "... h d -> ... (h d)")
696
+
697
+ indices, ps = pack_one(indices, "b * h")
698
+ indices = rearrange(indices, "b n h -> b h n")
699
+
700
+ indices = repeat(indices, "b h n -> b h n d", d=codebook.shape[-1])
701
+ codebook = repeat(codebook, "h n d -> b h n d", b=indices.shape[0])
702
+
703
+ codes = codebook.gather(2, indices)
704
+ codes = rearrange(codes, "b h n d -> b n (h d)")
705
+ codes = unpack_one(codes, ps, "b * d")
706
+ return codes
707
+
708
+ def forward(
709
+ self,
710
+ x,
711
+ indices=None,
712
+ mask=None,
713
+ sample_codebook_temp=None,
714
+ freeze_codebook=False,
715
+ ):
716
+ orig_input = x
717
+
718
+ only_one = x.ndim == 2
719
+
720
+ if only_one:
721
+ assert mask is None
722
+ x = rearrange(x, "b d -> b 1 d")
723
+
724
+ shape, device, heads, is_multiheaded, _codebook_size, return_loss = (
725
+ x.shape,
726
+ x.device,
727
+ self.heads,
728
+ self.heads > 1,
729
+ self.codebook_size,
730
+ (indices is not None),
731
+ )
732
+
733
+ need_transpose = not self.channel_last and not self.accept_image_fmap
734
+ should_inplace_optimize = self.in_place_codebook_optimizer is not None
735
+
736
+ # rearrange inputs
737
+
738
+ if self.accept_image_fmap:
739
+ height, width = x.shape[-2:]
740
+ x = rearrange(x, "b c h w -> b (h w) c")
741
+
742
+ if need_transpose:
743
+ x = rearrange(x, "b d n -> b n d")
744
+
745
+ # project input
746
+
747
+ x = self.project_in(x)
748
+
749
+ # handle multi-headed separate codebooks
750
+
751
+ if is_multiheaded:
752
+ ein_rhs_eq = "h b n d" if self.separate_codebook_per_head else "1 (b h) n d"
753
+ x = rearrange(x, f"b n (h d) -> {ein_rhs_eq}", h=heads)
754
+
755
+ # l2norm for cosine sim, otherwise identity
756
+
757
+ x = self._codebook.transform_input(x)
758
+
759
+ # codebook forward kwargs
760
+
761
+ codebook_forward_kwargs = {
762
+ "sample_codebook_temp": sample_codebook_temp,
763
+ "mask": mask,
764
+ "freeze_codebook": freeze_codebook,
765
+ }
766
+
767
+ # quantize
768
+
769
+ quantize, embed_ind, distances = self._codebook(x, **codebook_forward_kwargs)
770
+
771
+ # one step in-place update
772
+
773
+ if should_inplace_optimize and self.training and not freeze_codebook:
774
+ if mask is not None:
775
+ loss = F.mse_loss(quantize, x.detach(), reduction="none")
776
+
777
+ loss_mask = mask
778
+ if is_multiheaded:
779
+ loss_mask = repeat(
780
+ mask,
781
+ "b n -> c (b h) n",
782
+ c=loss.shape[0],
783
+ h=loss.shape[1] // mask.shape[0],
784
+ )
785
+
786
+ loss = loss[loss_mask].mean()
787
+
788
+ else:
789
+ loss = F.mse_loss(quantize, x.detach())
790
+
791
+ loss.backward()
792
+ self.in_place_codebook_optimizer.step()
793
+ self.in_place_codebook_optimizer.zero_grad()
794
+
795
+ # quantize again
796
+
797
+ quantize, embed_ind, distances = self._codebook(x, **codebook_forward_kwargs)
798
+
799
+ if self.training:
800
+ # determine code to use for commitment loss
801
+ maybe_detach = torch.detach if not self.learnable_codebook or freeze_codebook else identity
802
+
803
+ commit_quantize = maybe_detach(quantize)
804
+
805
+ # straight through
806
+
807
+ quantize = x + (quantize - x).detach()
808
+
809
+ if self.sync_update_v > 0.0:
810
+ # (21) in https://minyoungg.github.io/vqtorch/assets/draft_050523.pdf
811
+ quantize = quantize + self.sync_update_v * (quantize - quantize.detach())
812
+
813
+ # function for calculating cross entropy loss to distance matrix
814
+ # used for (1) naturalspeech2 training residual vq latents to be close to the correct codes and (2) cross-entropy based commitment loss
815
+
816
+ def calculate_ce_loss(codes):
817
+ if not is_multiheaded:
818
+ dist_einops_eq = "1 b n l -> b l n"
819
+ elif self.separate_codebook_per_head:
820
+ dist_einops_eq = "c b n l -> b l n c"
821
+ else:
822
+ dist_einops_eq = "1 (b h) n l -> b l n h"
823
+
824
+ ce_loss = F.cross_entropy(
825
+ rearrange(distances, dist_einops_eq, b=shape[0]), codes, ignore_index=-1
826
+ )
827
+
828
+ return ce_loss
829
+
830
+ # if returning cross entropy loss on codes that were passed in
831
+
832
+ if return_loss:
833
+ return quantize, calculate_ce_loss(indices)
834
+
835
+ # transform embedding indices
836
+
837
+ if is_multiheaded:
838
+ if self.separate_codebook_per_head:
839
+ embed_ind = rearrange(embed_ind, "h b n -> b n h", h=heads)
840
+ else:
841
+ embed_ind = rearrange(embed_ind, "1 (b h) n -> b n h", h=heads)
842
+
843
+ if self.accept_image_fmap:
844
+ embed_ind = rearrange(embed_ind, "b (h w) ... -> b h w ...", h=height, w=width)
845
+
846
+ if only_one:
847
+ embed_ind = rearrange(embed_ind, "b 1 -> b")
848
+
849
+ # aggregate loss
850
+
851
+ loss = torch.tensor([0.0], device=device, requires_grad=self.training)
852
+
853
+ if self.training:
854
+ if self.commitment_weight > 0:
855
+ if self.commitment_use_cross_entropy_loss:
856
+ if mask is not None:
857
+ ce_loss_mask = mask
858
+ if is_multiheaded:
859
+ ce_loss_mask = repeat(ce_loss_mask, "b n -> b n h", h=heads)
860
+
861
+ embed_ind.masked_fill_(~ce_loss_mask, -1)
862
+
863
+ commit_loss = calculate_ce_loss(embed_ind)
864
+ else:
865
+ if mask is not None:
866
+ # with variable lengthed sequences
867
+ commit_loss = F.mse_loss(commit_quantize, x, reduction="none")
868
+
869
+ loss_mask = mask
870
+ if is_multiheaded:
871
+ loss_mask = repeat(
872
+ loss_mask,
873
+ "b n -> c (b h) n",
874
+ c=commit_loss.shape[0],
875
+ h=commit_loss.shape[1] // mask.shape[0],
876
+ )
877
+
878
+ commit_loss = commit_loss[loss_mask].mean()
879
+ else:
880
+ commit_loss = F.mse_loss(commit_quantize, x)
881
+
882
+ loss = loss + commit_loss * self.commitment_weight
883
+
884
+ if self.has_codebook_orthogonal_loss:
885
+ codebook = self._codebook.embed
886
+
887
+ # only calculate orthogonal loss for the activated codes for this batch
888
+
889
+ if self.orthogonal_reg_active_codes_only:
890
+ assert not (is_multiheaded and self.separate_codebook_per_head), (
891
+ "orthogonal regularization for only active codes not compatible with multi-headed with separate codebooks yet"
892
+ )
893
+ unique_code_ids = torch.unique(embed_ind)
894
+ codebook = codebook[:, unique_code_ids]
895
+
896
+ num_codes = codebook.shape[-2]
897
+
898
+ if (self.orthogonal_reg_max_codes is not None) and num_codes > self.orthogonal_reg_max_codes:
899
+ rand_ids = torch.randperm(num_codes, device=device)[: self.orthogonal_reg_max_codes]
900
+ codebook = codebook[:, rand_ids]
901
+
902
+ orthogonal_reg_loss = orthogonal_loss_fn(codebook)
903
+ loss = loss + orthogonal_reg_loss * self.orthogonal_reg_weight
904
+
905
+ # handle multi-headed quantized embeddings
906
+
907
+ if is_multiheaded:
908
+ if self.separate_codebook_per_head:
909
+ quantize = rearrange(quantize, "h b n d -> b n (h d)", h=heads)
910
+ else:
911
+ quantize = rearrange(quantize, "1 (b h) n d -> b n (h d)", h=heads)
912
+
913
+ # project out
914
+
915
+ quantize = self.project_out(quantize)
916
+
917
+ # rearrange quantized embeddings
918
+
919
+ if need_transpose:
920
+ quantize = rearrange(quantize, "b n d -> b d n")
921
+
922
+ if self.accept_image_fmap:
923
+ quantize = rearrange(quantize, "b (h w) c -> b c h w", h=height, w=width)
924
+
925
+ if only_one:
926
+ quantize = rearrange(quantize, "b 1 d -> b d")
927
+
928
+ # if masking, only return quantized for where mask has True
929
+
930
+ if mask is not None:
931
+ quantize = torch.where(rearrange(mask, "... -> ... 1"), quantize, orig_input)
932
+
933
+ return quantize, embed_ind, loss
934
+
935
+
936
+ def noop(*args, **kwargs):
937
+ pass
938
+
939
+
940
+ def identity(t):
941
+ return t
942
+
943
+
944
+ def cdist(x, y):
945
+ x2 = reduce(x**2, "b n d -> b n", "sum")
946
+ y2 = reduce(y**2, "b n d -> b n", "sum")
947
+ xy = einsum("b i d, b j d -> b i j", x, y) * -2
948
+ return (rearrange(x2, "b i -> b i 1") + rearrange(y2, "b j -> b 1 j") + xy).sqrt()
949
+
950
+
951
+ def log(t, eps=1e-20):
952
+ return torch.log(t.clamp(min=eps))
953
+
954
+
955
+ def ema_inplace(old, new, decay):
956
+ is_mps = str(old.device).startswith("mps:")
957
+
958
+ if not is_mps:
959
+ old.lerp_(new, 1 - decay)
960
+ else:
961
+ old.mul_(decay).add_(new * (1 - decay))
962
+
963
+
964
+ def pack_one(t, pattern):
965
+ return pack([t], pattern)
966
+
967
+
968
+ def unpack_one(t, ps, pattern):
969
+ return unpack(t, ps, pattern)[0]
970
+
971
+
972
+ def uniform_init(*shape):
973
+ t = torch.empty(shape)
974
+ nn.init.kaiming_uniform_(t)
975
+ return t
976
+
977
+
978
+ def gumbel_noise(t):
979
+ noise = torch.zeros_like(t).uniform_(0, 1)
980
+ return -log(-log(noise))
981
+
982
+
983
+ def gumbel_sample(
984
+ logits,
985
+ temperature=1.0,
986
+ stochastic=False,
987
+ straight_through=False,
988
+ reinmax=False,
989
+ dim=-1,
990
+ training=True,
991
+ ):
992
+ dtype, size = logits.dtype, logits.shape[dim]
993
+
994
+ if training and stochastic and temperature > 0:
995
+ sampling_logits = (logits / temperature) + gumbel_noise(logits)
996
+ else:
997
+ sampling_logits = logits
998
+
999
+ ind = sampling_logits.argmax(dim=dim)
1000
+ one_hot = F.one_hot(ind, size).type(dtype)
1001
+
1002
+ assert not (reinmax and not straight_through), (
1003
+ "reinmax can only be turned on if using straight through gumbel softmax"
1004
+ )
1005
+
1006
+ if not straight_through or temperature <= 0.0 or not training:
1007
+ return ind, one_hot
1008
+
1009
+ # use reinmax for better second-order accuracy - https://huggingface.co/papers/2304.08612
1010
+ # algorithm 2
1011
+
1012
+ if reinmax:
1013
+ π0 = logits.softmax(dim=dim)
1014
+ π1 = (one_hot + (logits / temperature).softmax(dim=dim)) / 2
1015
+ π1 = ((log(π1) - logits).detach() + logits).softmax(dim=1)
1016
+ π2 = 2 * π1 - 0.5 * π0
1017
+ one_hot = π2 - π2.detach() + one_hot
1018
+ else:
1019
+ π1 = (logits / temperature).softmax(dim=dim)
1020
+ one_hot = one_hot + π1 - π1.detach()
1021
+
1022
+ return ind, one_hot
1023
+
1024
+
1025
+ def laplace_smoothing(x, n_categories, eps=1e-5, dim=-1):
1026
+ denom = x.sum(dim=dim, keepdim=True)
1027
+ return (x + eps) / (denom + n_categories * eps)
1028
+
1029
+
1030
+ def sample_vectors(samples, num):
1031
+ num_samples, device = samples.shape[0], samples.device
1032
+ if num_samples >= num:
1033
+ indices = torch.randperm(num_samples, device=device)[:num]
1034
+ else:
1035
+ indices = torch.randint(0, num_samples, (num,), device=device)
1036
+
1037
+ return samples[indices]
1038
+
1039
+
1040
+ def batched_sample_vectors(samples, num):
1041
+ return torch.stack([sample_vectors(sample, num) for sample in samples.unbind(dim=0)], dim=0)
1042
+
1043
+
1044
+ def pad_shape(shape, size, dim=0):
1045
+ return [size if i == dim else s for i, s in enumerate(shape)]
1046
+
1047
+
1048
+ def sample_multinomial(total_count, probs):
1049
+ device = probs.device
1050
+ probs = probs.cpu()
1051
+
1052
+ total_count = probs.new_full((), total_count)
1053
+ remainder = probs.new_ones(())
1054
+ sample = torch.empty_like(probs, dtype=torch.long)
1055
+
1056
+ for i, p in enumerate(probs):
1057
+ s = torch.binomial(total_count, p / remainder)
1058
+ sample[i] = s
1059
+ total_count -= s
1060
+ remainder -= p
1061
+
1062
+ return sample.to(device)
1063
+
1064
+
1065
+ def all_gather_sizes(x, dim):
1066
+ size = torch.tensor(x.shape[dim], dtype=torch.long, device=x.device)
1067
+ all_sizes = [torch.empty_like(size) for _ in range(distributed.get_world_size())]
1068
+ distributed.all_gather(all_sizes, size)
1069
+ return torch.stack(all_sizes)
1070
+
1071
+
1072
+ def all_gather_variably_sized(x, sizes, dim=0):
1073
+ rank = distributed.get_rank()
1074
+ all_x = []
1075
+
1076
+ for i, size in enumerate(sizes):
1077
+ t = x if i == rank else x.new_empty(pad_shape(x.shape, size, dim))
1078
+ distributed.broadcast(t, src=i, async_op=True)
1079
+ all_x.append(t)
1080
+
1081
+ distributed.barrier()
1082
+ return all_x
1083
+
1084
+
1085
+ def sample_vectors_distributed(local_samples, num):
1086
+ local_samples = rearrange(local_samples, "1 ... -> ...")
1087
+
1088
+ rank = distributed.get_rank()
1089
+ all_num_samples = all_gather_sizes(local_samples, dim=0)
1090
+
1091
+ if rank == 0:
1092
+ samples_per_rank = sample_multinomial(num, all_num_samples / all_num_samples.sum())
1093
+ else:
1094
+ samples_per_rank = torch.empty_like(all_num_samples)
1095
+
1096
+ distributed.broadcast(samples_per_rank, src=0)
1097
+ samples_per_rank = samples_per_rank.tolist()
1098
+
1099
+ local_samples = sample_vectors(local_samples, samples_per_rank[rank])
1100
+ all_samples = all_gather_variably_sized(local_samples, samples_per_rank, dim=0)
1101
+ out = torch.cat(all_samples, dim=0)
1102
+
1103
+ return rearrange(out, "... -> 1 ...")
1104
+
1105
+
1106
+ def batched_bincount(x, *, minlength):
1107
+ batch, dtype, device = x.shape[0], x.dtype, x.device
1108
+ target = torch.zeros(batch, minlength, dtype=dtype, device=device)
1109
+ values = torch.ones_like(x)
1110
+ target.scatter_add_(-1, x, values)
1111
+ return target
1112
+
1113
+
1114
+ def kmeans(
1115
+ samples,
1116
+ num_clusters,
1117
+ num_iters=10,
1118
+ sample_fn=batched_sample_vectors,
1119
+ all_reduce_fn=noop,
1120
+ ):
1121
+ num_codebooks, dim, dtype, _device = (
1122
+ samples.shape[0],
1123
+ samples.shape[-1],
1124
+ samples.dtype,
1125
+ samples.device,
1126
+ )
1127
+
1128
+ means = sample_fn(samples, num_clusters)
1129
+
1130
+ for _ in range(num_iters):
1131
+ dists = -torch.cdist(samples, means, p=2)
1132
+
1133
+ buckets = torch.argmax(dists, dim=-1)
1134
+ bins = batched_bincount(buckets, minlength=num_clusters)
1135
+ all_reduce_fn(bins)
1136
+
1137
+ zero_mask = bins == 0
1138
+ bins_min_clamped = bins.masked_fill(zero_mask, 1)
1139
+
1140
+ new_means = buckets.new_zeros(num_codebooks, num_clusters, dim, dtype=dtype)
1141
+
1142
+ new_means.scatter_add_(1, repeat(buckets, "h n -> h n d", d=dim), samples)
1143
+ new_means = new_means / rearrange(bins_min_clamped, "... -> ... 1")
1144
+ all_reduce_fn(new_means)
1145
+
1146
+ means = torch.where(rearrange(zero_mask, "... -> ... 1"), means, new_means)
1147
+
1148
+ return means, bins
1149
+
1150
+
1151
+ def batched_embedding(indices, embeds):
1152
+ batch, dim = indices.shape[1], embeds.shape[-1]
1153
+ indices = repeat(indices, "h b n -> h b n d", d=dim)
1154
+ embeds = repeat(embeds, "h c d -> h b c d", b=batch)
1155
+ return embeds.gather(2, indices)
1156
+
1157
+
1158
+ def orthogonal_loss_fn(t):
1159
+ # eq (2) from https://huggingface.co/papers/2112.00384
1160
+ h, n = t.shape[:2]
1161
+ normed_codes = F.normalize(t, p=2, dim=-1)
1162
+ cosine_sim = einsum("h i d, h j d -> h i j", normed_codes, normed_codes)
1163
+ return (cosine_sim**2).sum() / (h * n**2) - (1 / n)
1164
+
1165
+
1166
+ class EuclideanCodebook(nn.Module):
1167
+ def __init__(
1168
+ self,
1169
+ dim,
1170
+ codebook_size,
1171
+ num_codebooks=1,
1172
+ kmeans_init=False,
1173
+ kmeans_iters=10,
1174
+ sync_kmeans=True,
1175
+ decay=0.8,
1176
+ eps=1e-5,
1177
+ threshold_ema_dead_code=2,
1178
+ reset_cluster_size=None,
1179
+ use_ddp=False,
1180
+ learnable_codebook=False,
1181
+ gumbel_sample=gumbel_sample,
1182
+ sample_codebook_temp=1.0,
1183
+ ema_update=True,
1184
+ affine_param=False,
1185
+ sync_affine_param=False,
1186
+ affine_param_batch_decay=0.99,
1187
+ affine_param_codebook_decay=0.9,
1188
+ ):
1189
+ super().__init__()
1190
+ self.transform_input = identity
1191
+
1192
+ self.decay = decay
1193
+ self.ema_update = ema_update
1194
+
1195
+ init_fn = uniform_init if not kmeans_init else torch.zeros
1196
+ embed = init_fn(num_codebooks, codebook_size, dim)
1197
+
1198
+ self.codebook_size = codebook_size
1199
+ self.num_codebooks = num_codebooks
1200
+
1201
+ self.kmeans_iters = kmeans_iters
1202
+ self.eps = eps
1203
+ self.threshold_ema_dead_code = threshold_ema_dead_code
1204
+ self.reset_cluster_size = (
1205
+ reset_cluster_size if (reset_cluster_size is not None) else threshold_ema_dead_code
1206
+ )
1207
+
1208
+ assert callable(gumbel_sample)
1209
+ self.gumbel_sample = gumbel_sample
1210
+ self.sample_codebook_temp = sample_codebook_temp
1211
+
1212
+ assert not (use_ddp and num_codebooks > 1 and kmeans_init), (
1213
+ "kmeans init is not compatible with multiple codebooks in distributed environment for now"
1214
+ )
1215
+
1216
+ self.sample_fn = sample_vectors_distributed if use_ddp and sync_kmeans else batched_sample_vectors
1217
+ self.kmeans_all_reduce_fn = distributed.all_reduce if use_ddp and sync_kmeans else noop
1218
+ self.all_reduce_fn = distributed.all_reduce if use_ddp else noop
1219
+
1220
+ self.register_buffer("initted", torch.Tensor([not kmeans_init]))
1221
+ self.register_buffer("cluster_size", torch.zeros(num_codebooks, codebook_size))
1222
+ self.register_buffer("embed_avg", embed.clone())
1223
+
1224
+ self.learnable_codebook = learnable_codebook
1225
+ if learnable_codebook:
1226
+ self.embed = nn.Parameter(embed)
1227
+ else:
1228
+ self.register_buffer("embed", embed)
1229
+
1230
+ # affine related params
1231
+
1232
+ self.affine_param = affine_param
1233
+ self.sync_affine_param = sync_affine_param
1234
+
1235
+ if not affine_param:
1236
+ return
1237
+
1238
+ self.affine_param_batch_decay = affine_param_batch_decay
1239
+ self.affine_param_codebook_decay = affine_param_codebook_decay
1240
+
1241
+ self.register_buffer("batch_mean", None)
1242
+ self.register_buffer("batch_variance", None)
1243
+
1244
+ self.register_buffer("codebook_mean_needs_init", torch.Tensor([True]))
1245
+ self.register_buffer("codebook_mean", torch.empty(num_codebooks, 1, dim))
1246
+ self.register_buffer("codebook_variance_needs_init", torch.Tensor([True]))
1247
+ self.register_buffer("codebook_variance", torch.empty(num_codebooks, 1, dim))
1248
+
1249
+ @torch.jit.ignore
1250
+ def init_embed_(self, data, mask=None):
1251
+ if self.initted:
1252
+ return
1253
+
1254
+ if mask is not None:
1255
+ c = data.shape[0]
1256
+ data = rearrange(data[mask], "(c n) d -> c n d", c=c)
1257
+
1258
+ embed, cluster_size = kmeans(
1259
+ data,
1260
+ self.codebook_size,
1261
+ self.kmeans_iters,
1262
+ sample_fn=self.sample_fn,
1263
+ all_reduce_fn=self.kmeans_all_reduce_fn,
1264
+ )
1265
+
1266
+ embed_sum = embed * rearrange(cluster_size, "... -> ... 1")
1267
+
1268
+ self.embed.data.copy_(embed)
1269
+ self.embed_avg.data.copy_(embed_sum)
1270
+ self.cluster_size.data.copy_(cluster_size)
1271
+ self.initted.data.copy_(torch.Tensor([True]))
1272
+
1273
+ @torch.jit.ignore
1274
+ def update_with_decay(self, buffer_name, new_value, decay):
1275
+ old_value = getattr(self, buffer_name)
1276
+
1277
+ needs_init = getattr(self, buffer_name + "_needs_init", False)
1278
+
1279
+ if needs_init:
1280
+ self.register_buffer(buffer_name + "_needs_init", torch.Tensor([False]))
1281
+
1282
+ if not (old_value is not None) or needs_init:
1283
+ self.register_buffer(buffer_name, new_value.detach())
1284
+
1285
+ return
1286
+
1287
+ value = old_value * decay + new_value.detach() * (1 - decay)
1288
+ self.register_buffer(buffer_name, value)
1289
+
1290
+ @torch.jit.ignore
1291
+ def update_affine(self, data, embed, mask=None):
1292
+ assert self.affine_param
1293
+
1294
+ var_fn = partial(torch.var, unbiased=False)
1295
+
1296
+ # calculate codebook mean and variance
1297
+
1298
+ embed = rearrange(embed, "h ... d -> h (...) d")
1299
+
1300
+ if self.training:
1301
+ self.update_with_decay(
1302
+ "codebook_mean",
1303
+ reduce(embed, "h n d -> h 1 d", "mean"),
1304
+ self.affine_param_codebook_decay,
1305
+ )
1306
+ self.update_with_decay(
1307
+ "codebook_variance",
1308
+ reduce(embed, "h n d -> h 1 d", var_fn),
1309
+ self.affine_param_codebook_decay,
1310
+ )
1311
+
1312
+ # prepare batch data, which depends on whether it has masking
1313
+
1314
+ data = rearrange(data, "h ... d -> h (...) d")
1315
+
1316
+ if mask is not None:
1317
+ c = data.shape[0]
1318
+ data = rearrange(data[mask], "(c n) d -> c n d", c=c)
1319
+
1320
+ # calculate batch mean and variance
1321
+
1322
+ if not self.sync_affine_param:
1323
+ self.update_with_decay(
1324
+ "batch_mean",
1325
+ reduce(data, "h n d -> h 1 d", "mean"),
1326
+ self.affine_param_batch_decay,
1327
+ )
1328
+ self.update_with_decay(
1329
+ "batch_variance",
1330
+ reduce(data, "h n d -> h 1 d", var_fn),
1331
+ self.affine_param_batch_decay,
1332
+ )
1333
+ return
1334
+
1335
+ num_vectors, device, dtype = data.shape[-2], data.device, data.dtype
1336
+
1337
+ # number of vectors, for denominator
1338
+
1339
+ num_vectors = torch.tensor([num_vectors], device=device, dtype=dtype)
1340
+ distributed.all_reduce(num_vectors)
1341
+
1342
+ # calculate distributed mean
1343
+
1344
+ batch_sum = reduce(data, "h n d -> h 1 d", "sum")
1345
+ distributed.all_reduce(batch_sum)
1346
+ batch_mean = batch_sum / num_vectors
1347
+
1348
+ self.update_with_decay("batch_mean", batch_mean, self.affine_param_batch_decay)
1349
+
1350
+ # calculate distributed variance
1351
+
1352
+ variance_number = reduce((data - batch_mean) ** 2, "h n d -> h 1 d", "sum")
1353
+ distributed.all_reduce(variance_number)
1354
+ batch_variance = variance_number / num_vectors
1355
+
1356
+ self.update_with_decay("batch_variance", batch_variance, self.affine_param_batch_decay)
1357
+
1358
+ def replace(self, batch_samples, batch_mask):
1359
+ for ind, (samples, mask) in enumerate(
1360
+ zip(batch_samples.unbind(dim=0), batch_mask.unbind(dim=0), strict=False)
1361
+ ):
1362
+ if not torch.any(mask):
1363
+ continue
1364
+
1365
+ sampled = self.sample_fn(rearrange(samples, "... -> 1 ..."), mask.sum().item())
1366
+ sampled = rearrange(sampled, "1 ... -> ...")
1367
+
1368
+ self.embed.data[ind][mask] = sampled
1369
+
1370
+ self.cluster_size.data[ind][mask] = self.reset_cluster_size
1371
+ self.embed_avg.data[ind][mask] = sampled * self.reset_cluster_size
1372
+
1373
+ def expire_codes_(self, batch_samples):
1374
+ if self.threshold_ema_dead_code == 0:
1375
+ return
1376
+
1377
+ expired_codes = self.cluster_size < self.threshold_ema_dead_code
1378
+
1379
+ if not torch.any(expired_codes):
1380
+ return
1381
+
1382
+ batch_samples = rearrange(batch_samples, "h ... d -> h (...) d")
1383
+ self.replace(batch_samples, batch_mask=expired_codes)
1384
+
1385
+ @autocast(enabled=False)
1386
+ def forward(self, x, sample_codebook_temp=None, mask=None, freeze_codebook=False):
1387
+ needs_codebook_dim = x.ndim < 4
1388
+ sample_codebook_temp = (
1389
+ sample_codebook_temp if (sample_codebook_temp is not None) else self.sample_codebook_temp
1390
+ )
1391
+
1392
+ x = x.float()
1393
+
1394
+ if needs_codebook_dim:
1395
+ x = rearrange(x, "... -> 1 ...")
1396
+
1397
+ flatten, ps = pack_one(x, "h * d")
1398
+
1399
+ if mask is not None:
1400
+ mask = repeat(
1401
+ mask,
1402
+ "b n -> c (b h n)",
1403
+ c=flatten.shape[0],
1404
+ h=flatten.shape[-2] // (mask.shape[0] * mask.shape[1]),
1405
+ )
1406
+
1407
+ self.init_embed_(flatten, mask=mask)
1408
+
1409
+ if self.affine_param:
1410
+ self.update_affine(flatten, self.embed, mask=mask)
1411
+
1412
+ embed = self.embed if self.learnable_codebook else self.embed.detach()
1413
+
1414
+ if self.affine_param:
1415
+ codebook_std = self.codebook_variance.clamp(min=1e-5).sqrt()
1416
+ batch_std = self.batch_variance.clamp(min=1e-5).sqrt()
1417
+ embed = (embed - self.codebook_mean) * (batch_std / codebook_std) + self.batch_mean
1418
+
1419
+ dist = -cdist(flatten, embed)
1420
+
1421
+ embed_ind, embed_onehot = self.gumbel_sample(
1422
+ dist, dim=-1, temperature=sample_codebook_temp, training=self.training
1423
+ )
1424
+
1425
+ embed_ind = unpack_one(embed_ind, ps, "h *")
1426
+
1427
+ if self.training:
1428
+ unpacked_onehot = unpack_one(embed_onehot, ps, "h * c")
1429
+ quantize = einsum("h b n c, h c d -> h b n d", unpacked_onehot, embed)
1430
+ else:
1431
+ quantize = batched_embedding(embed_ind, embed)
1432
+
1433
+ if self.training and self.ema_update and not freeze_codebook:
1434
+ if self.affine_param:
1435
+ flatten = (flatten - self.batch_mean) * (codebook_std / batch_std) + self.codebook_mean
1436
+
1437
+ if mask is not None:
1438
+ embed_onehot[~mask] = 0.0
1439
+
1440
+ cluster_size = embed_onehot.sum(dim=1)
1441
+
1442
+ self.all_reduce_fn(cluster_size)
1443
+ ema_inplace(self.cluster_size.data, cluster_size, self.decay)
1444
+
1445
+ embed_sum = einsum("h n d, h n c -> h c d", flatten, embed_onehot)
1446
+ self.all_reduce_fn(embed_sum.contiguous())
1447
+ ema_inplace(self.embed_avg.data, embed_sum, self.decay)
1448
+
1449
+ cluster_size = laplace_smoothing(
1450
+ self.cluster_size, self.codebook_size, self.eps
1451
+ ) * self.cluster_size.sum(dim=-1, keepdim=True)
1452
+
1453
+ embed_normalized = self.embed_avg / rearrange(cluster_size, "... -> ... 1")
1454
+ self.embed.data.copy_(embed_normalized)
1455
+ self.expire_codes_(x)
1456
+
1457
+ if needs_codebook_dim:
1458
+ quantize, embed_ind = tuple(rearrange(t, "1 ... -> ...") for t in (quantize, embed_ind))
1459
+
1460
+ dist = unpack_one(dist, ps, "h * d")
1461
+
1462
+ return quantize, embed_ind, dist