diff --git a/lerobot/docs/source/act.mdx b/lerobot/docs/source/act.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..0867ebe2f31a02736dcb8c3bb4173a82ef3fb530
--- /dev/null
+++ b/lerobot/docs/source/act.mdx
@@ -0,0 +1,92 @@
+# ACT (Action Chunking with Transformers)
+
+ACT is a **lightweight and efficient policy for imitation learning**, especially well-suited for fine-grained manipulation tasks. It's the **first model we recommend when you're starting out** with LeRobot due to its fast training time, low computational requirements, and strong performance.
+
+
+
+
+
+_Watch this tutorial from the LeRobot team to learn how ACT works: [LeRobot ACT Tutorial](https://www.youtube.com/watch?v=ft73x0LfGpM)_
+
+## Model Overview
+
+Action Chunking with Transformers (ACT) was introduced in the paper [Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardware](https://arxiv.org/abs/2304.13705) by Zhao et al. The policy was designed to enable precise, contact-rich manipulation tasks using affordable hardware and minimal demonstration data.
+
+### Why ACT is Great for Beginners
+
+ACT stands out as an excellent starting point for several reasons:
+
+- **Fast Training**: Trains in a few hours on a single GPU
+- **Lightweight**: Only ~80M parameters, making it efficient and easy to work with
+- **Data Efficient**: Often achieves high success rates with just 50 demonstrations
+
+### Architecture
+
+ACT uses a transformer-based architecture with three main components:
+
+1. **Vision Backbone**: ResNet-18 processes images from multiple camera viewpoints
+2. **Transformer Encoder**: Synthesizes information from camera features, joint positions, and a learned latent variable
+3. **Transformer Decoder**: Generates coherent action sequences using cross-attention
+
+The policy takes as input:
+
+- Multiple RGB images (e.g., from wrist cameras, front/top cameras)
+- Current robot joint positions
+- A latent style variable `z` (learned during training, set to zero during inference)
+
+And outputs a chunk of `k` future action sequences.
+
+## Installation Requirements
+
+1. Install LeRobot by following our [Installation Guide](./installation).
+2. ACT is included in the base LeRobot installation, so no additional dependencies are needed!
+
+## Training ACT
+
+ACT works seamlessly with the standard LeRobot training pipeline. Here's a complete example for training ACT on your dataset:
+
+```bash
+lerobot-train \
+ --dataset.repo_id=${HF_USER}/your_dataset \
+ --policy.type=act \
+ --output_dir=outputs/train/act_your_dataset \
+ --job_name=act_your_dataset \
+ --policy.device=cuda \
+ --wandb.enable=true \
+ --policy.repo_id=${HF_USER}/act_policy
+```
+
+### Training Tips
+
+1. **Start with defaults**: ACT's default hyperparameters work well for most tasks
+2. **Training duration**: Expect a few hours for 100k training steps on a single GPU
+3. **Batch size**: Start with batch size 8 and adjust based on your GPU memory
+
+### Train using Google Colab
+
+If your local computer doesn't have a powerful GPU, you can utilize Google Colab to train your model by following the [ACT training notebook](./notebooks#training-act).
+
+## Evaluating ACT
+
+Once training is complete, you can evaluate your ACT policy using the `lerobot-record` command with your trained policy. This will run inference and record evaluation episodes:
+
+```bash
+lerobot-record \
+ --robot.type=so100_follower \
+ --robot.port=/dev/ttyACM0 \
+ --robot.id=my_robot \
+ --robot.cameras="{ front: {type: opencv, index_or_path: 0, width: 640, height: 480, fps: 30}}" \
+ --display_data=true \
+ --dataset.repo_id=${HF_USER}/eval_act_your_dataset \
+ --dataset.num_episodes=10 \
+ --dataset.single_task="Your task description" \
+ --policy.path=${HF_USER}/act_policy
+```
diff --git a/lerobot/docs/source/async.mdx b/lerobot/docs/source/async.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..732041a19299f5c96c888bb06a8c49e4fd41703e
--- /dev/null
+++ b/lerobot/docs/source/async.mdx
@@ -0,0 +1,312 @@
+# Asynchronous Inference
+
+With our [SmolVLA](https://huggingface.co/papers/2506.01844) we introduced a new way to run inference on real-world robots, **decoupling action prediction from action execution**.
+In this tutorial, we'll show how to use asynchronous inference (_async inference_) using a finetuned version of SmolVLA, and all the policies supported by LeRobot.
+**Try async inference with all the policies** supported by LeRobot!
+
+**What you'll learn:**
+
+1. Why asynchronous inference matters and how it compares to, more traditional, sequential inference.
+2. How to spin-up a `PolicyServer` and connect a `RobotClient` from the same machine, and even over the network.
+3. How to tune key parameters (`actions_per_chunk`, `chunk_size_threshold`) for your robot and policy.
+
+If you get stuck, hop into our [Discord community](https://discord.gg/s3KuuzsPFb)!
+
+In a nutshell: with _async inference_, your robot keeps acting while the policy server is already busy computing the next chunk of actions---eliminating "wait-for-inference" lags and unlocking smoother, more reactive behaviours.
+This is fundamentally different from synchronous inference (sync), where the robot stays idle while the policy computes the next chunk of actions.
+
+---
+
+## Getting started with async inference
+
+You can read more information on asynchronous inference in our [blogpost](https://huggingface.co/blog/async-robot-inference). This guide is designed to help you quickly set up and run asynchronous inference in your environment.
+
+First, install `lerobot` with the `async` tag, to install the extra dependencies required to run async inference.
+
+```shell
+pip install -e ".[async]"
+```
+
+Then, spin up a policy server (in one terminal, or in a separate machine) specifying the host address and port for the client to connect to.
+You can spin up a policy server running:
+
+```shell
+python -m lerobot.async_inference.policy_server \
+ --host=127.0.0.1 \
+ --port=8080
+```
+
+This will start a policy server listening on `127.0.0.1:8080` (`localhost`, port 8080). At this stage, the policy server is empty, as all information related to which policy to run and with which parameters are specified during the first handshake with the client. Spin up a client with:
+
+```shell
+python -m lerobot.async_inference.robot_client \
+ --server_address=127.0.0.1:8080 \ # SERVER: the host address and port of the policy server
+ --robot.type=so100_follower \ # ROBOT: your robot type
+ --robot.port=/dev/tty.usbmodem585A0076841 \ # ROBOT: your robot port
+ --robot.id=follower_so100 \ # ROBOT: your robot id, to load calibration file
+ --robot.cameras="{ laptop: {type: opencv, index_or_path: 0, width: 1920, height: 1080, fps: 30}, phone: {type: opencv, index_or_path: 0, width: 1920, height: 1080, fps: 30}}" \ # POLICY: the cameras used to acquire frames, with keys matching the keys expected by the policy
+ --task="dummy" \ # POLICY: The task to run the policy on (`Fold my t-shirt`). Not necessarily defined for all policies, such as `act`
+ --policy_type=your_policy_type \ # POLICY: the type of policy to run (smolvla, act, etc)
+ --pretrained_name_or_path=user/model \ # POLICY: the model name/path on server to the checkpoint to run (e.g., lerobot/smolvla_base)
+ --policy_device=mps \ # POLICY: the device to run the policy on, on the server
+ --actions_per_chunk=50 \ # POLICY: the number of actions to output at once
+ --chunk_size_threshold=0.5 \ # CLIENT: the threshold for the chunk size before sending a new observation to the server
+ --aggregate_fn_name=weighted_average \ # CLIENT: the function to aggregate actions on overlapping portions
+ --debug_visualize_queue_size=True # CLIENT: whether to visualize the queue size at runtime
+```
+
+In summary, you need to specify instructions for:
+
+- `SERVER`: the address and port of the policy server
+- `ROBOT`: the type of robot to connect to, the port to connect to, and the local `id` of the robot
+- `POLICY`: the type of policy to run, and the model name/path on server to the checkpoint to run. You also need to specify which device should the sever be using, and how many actions to output at once (capped at the policy max actions value).
+- `CLIENT`: the threshold for the chunk size before sending a new observation to the server, and the function to aggregate actions on overlapping portions. Optionally, you can also visualize the queue size at runtime, to help you tune the `CLIENT` parameters.
+
+Importantly,
+
+- `actions_per_chunk` and `chunk_size_threshold` are key parameters to tune for your setup.
+- `aggregate_fn_name` is the function to aggregate actions on overlapping portions. You can either add a new one to a registry of functions, or add your own in `robot_client.py` (see [here](NOTE:addlinktoLOC))
+- `debug_visualize_queue_size` is a useful tool to tune the `CLIENT` parameters.
+
+## Done! You should see your robot moving around by now π
+
+## Async vs. synchronous inference
+
+Synchronous inference relies on interleaving action chunk prediction and action execution. This inherently results in _idle frames_, frames where the robot awaits idle the policy's output: a new action chunk.
+In turn, inference is plagued by evident real-time lags, where the robot simply stops acting due to the lack of available actions.
+With robotics models increasing in size, this problem risks becoming only more severe.
+
+
+
+
+
+ Synchronous inference makes the robot idle while the policy is
+ computing the next chunk of actions.
+
+
+To overcome this, we design async inference, a paradigm where action planning and execution are decoupled, resulting in (1) higher adaptability and, most importantly, (2) no idle frames.
+Crucially, with async inference, the next action chunk is computed _before_ the current one is exhausted, resulting in no idleness.
+Higher adaptability is ensured by aggregating the different action chunks on overlapping portions, obtaining an up-to-date plan and a tighter control loop.
+
+
+
+
+
+ Asynchronous inference results in no idleness because the next chunk is
+ computed before the current chunk is exhausted.
+
+
+---
+
+## Start the Policy Server
+
+Policy servers are wrappers around a `PreTrainedPolicy` interfacing them with observations coming from a robot client.
+Policy servers are initialized as empty containers which are populated with the requested policy specified in the initial handshake between the robot client and the policy server.
+As such, spinning up a policy server is as easy as specifying the host address and port. If you're running the policy server on the same machine as the robot client, you can use `localhost` as the host address.
+
+
+
+```bash
+python -m lerobot.async_inference.policy_server \
+ --host=127.0.0.1 \
+ --port=8080
+```
+
+
+
+
+```python
+from lerobot.async_inference.configs import PolicyServerConfig
+from lerobot.async_inference.policy_server import serve
+
+config = PolicyServerConfig(
+ host="localhost",
+ port=8080,
+)
+serve(config)
+```
+
+
+
+
+
+This listens on `localhost:8080` for an incoming connection from the associated`RobotClient`, which will communicate which policy to run during the first client-server handshake.
+
+---
+
+## Launch the Robot Client
+
+`RobotClient` is a wrapper around a `Robot` instance, which `RobotClient` connects to the (possibly remote) `PolicyServer`.
+The `RobotClient` streams observations to the `PolicyServer`, and receives action chunks obtained running inference on the server (which we assume to have better computational resources than the robot controller).
+
+
+
+```bash
+python -m lerobot.async_inference.robot_client \
+ --server_address=127.0.0.1:8080 \ # SERVER: the host address and port of the policy server
+ --robot.type=so100_follower \ # ROBOT: your robot type
+ --robot.port=/dev/tty.usbmodem585A0076841 \ # ROBOT: your robot port
+ --robot.id=follower_so100 \ # ROBOT: your robot id, to load calibration file
+ --robot.cameras="{ laptop: {type: opencv, index_or_path: 0, width: 1920, height: 1080, fps: 30}, phone: {type: opencv, index_or_path: 0, width: 1920, height: 1080, fps: 30}}" \ # POLICY: the cameras used to acquire frames, with keys matching the keys expected by the policy
+ --task="dummy" \ # POLICY: The task to run the policy on (`Fold my t-shirt`). Not necessarily defined for all policies, such as `act`
+ --policy_type=your_policy_type \ # POLICY: the type of policy to run (smolvla, act, etc)
+ --pretrained_name_or_path=user/model \ # POLICY: the model name/path on server to the checkpoint to run (e.g., lerobot/smolvla_base)
+ --policy_device=mps \ # POLICY: the device to run the policy on, on the server
+ --actions_per_chunk=50 \ # POLICY: the number of actions to output at once
+ --chunk_size_threshold=0.5 \ # CLIENT: the threshold for the chunk size before sending a new observation to the server
+ --aggregate_fn_name=weighted_average \ # CLIENT: the function to aggregate actions on overlapping portions
+ --debug_visualize_queue_size=True # CLIENT: whether to visualize the queue size at runtime
+```
+
+
+
+
+```python
+import threading
+from lerobot.robots.so_follower import SO100FollowerConfig
+from lerobot.cameras.opencv.configuration_opencv import OpenCVCameraConfig
+from lerobot.async_inference.configs import RobotClientConfig
+from lerobot.async_inference.robot_client import RobotClient
+from lerobot.async_inference.helpers import visualize_action_queue_size
+
+# 1. Create the robot instance
+"""Check out the cameras available in your setup by running `python lerobot/find_cameras.py`"""
+# these cameras must match the ones expected by the policy
+# check the config.json on the Hub for the policy you are using
+camera_cfg = {
+ "top": OpenCVCameraConfig(index_or_path=0, width=640, height=480, fps=30),
+ "side": OpenCVCameraConfig(index_or_path=1, width=640, height=480, fps=30)
+}
+
+robot_cfg = SO100FollowerConfig(
+ port="/dev/tty.usbmodem585A0076841",
+ id="follower_so100",
+ cameras=camera_cfg
+)
+
+# 3. Create client configuration
+client_cfg = RobotClientConfig(
+ robot=robot_cfg,
+ server_address="localhost:8080",
+ policy_device="mps",
+ policy_type="smolvla",
+ pretrained_name_or_path="/smolvla_async",
+ chunk_size_threshold=0.5,
+ actions_per_chunk=50, # make sure this is less than the max actions of the policy
+)
+
+# 4. Create and start client
+client = RobotClient(client_cfg)
+
+# 5. Specify the task
+task = "Don't do anything, stay still"
+
+if client.start():
+ # Start action receiver thread
+ action_receiver_thread = threading.Thread(target=client.receive_actions, daemon=True)
+ action_receiver_thread.start()
+
+ try:
+ # Run the control loop
+ client.control_loop(task)
+ except KeyboardInterrupt:
+ client.stop()
+ action_receiver_thread.join()
+ # (Optionally) plot the action queue size
+ visualize_action_queue_size(client.action_queue_size)
+```
+
+
+
+
+
+The following two parameters are key in every setup:
+
+
+
+
+
Hyperparameter
+
Default
+
What it does
+
+
+
+
+
+ actions_per_chunk
+
+
50
+
+ How many actions the policy outputs at once. Typical values: 10-50.
+
+
+
+
+ chunk_size_threshold
+
+
0.7
+
+ When the queue is β€ 50% full, the client sends a fresh observation.
+ Value in [0, 1].
+
+
+
+
+
+
+ Different values of `actions_per_chunk` and `chunk_size_threshold` do result
+ in different behaviours.
+
+
+On the one hand, increasing the value of `actions_per_chunk` will result in reducing the likelihood of ending up with no actions to execute, as more actions will be available when the new chunk is computed.
+However, larger values of `actions_per_chunk` might also result in less precise actions, due to the compounding errors consequent to predicting actions over longer timespans.
+
+On the other hand, increasing the value of `chunk_size_threshold` will result in sending out to the `PolicyServer` observations for inference more often, resulting in a larger number of updates action chunks, overlapping on significant portions. This results in high adaptability, in the limit predicting one action chunk for each observation, which is in turn only marginally consumed while a new one is produced.
+This option does also put more pressure on the inference pipeline, as a consequence of the many requests. Conversely, values of `chunk_size_threshold` close to 0.0 collapse to the synchronous edge case, whereby new observations are only sent out whenever the current chunk is exhausted.
+
+We found the default values of `actions_per_chunk` and `chunk_size_threshold` to work well in the experiments we developed for the [SmolVLA paper](https://huggingface.co/papers/2506.01844), but recommend experimenting with different values to find the best fit for your setup.
+
+### Tuning async inference for your setup
+
+1. **Choose your computational resources carefully.** [PI0](https://huggingface.co/lerobot/pi0) occupies 14GB of memory at inference time, while [SmolVLA](https://huggingface.co/lerobot/smolvla_base) requires only ~2GB. You should identify the best computational resource for your use case keeping in mind smaller policies require less computational resources. The combination of policy and device used (CPU-intensive, using MPS, or the number of CUDA cores on a given NVIDIA GPU) directly impacts the average inference latency you should expect.
+2. **Adjust your `fps` based on inference latency.** While the server generates a new action chunk, the client is not idle and is stepping through its current action queue. If the two processes happen at fundamentally different speeds, the client might end up with an empty queue. As such, you should reduce your fps if you consistently run out of actions in queue.
+3. **Adjust `chunk_size_threshold`**.
+ - Values closer to `0.0` result in almost sequential behavior. Values closer to `1.0` β send observation every step (more bandwidth, relies on good world-model).
+ - We found values around 0.5-0.6 to work well. If you want to tweak this, spin up a `RobotClient` setting the `--debug_visualize_queue_size` to `True`. This will plot the action queue size evolution at runtime, and you can use it to find the value of `chunk_size_threshold` that works best for your setup.
+
+
+
+
+
+
+ The action queue size is plotted at runtime when the
+ `--debug_visualize_queue_size` flag is passed, for various levels of
+ `chunk_size_threshold` (`g` in the SmolVLA paper).
+
+
+
+---
+
+## Conclusion
+
+Asynchronous inference represents a significant advancement in real-time robotics control, addressing the fundamental challenge of inference latency that has long plagued robotics applications. Through this tutorial, you've learned how to implement a complete async inference pipeline that eliminates idle frames and enables smoother, more reactive robot behaviors.
+
+**Key Takeaways:**
+
+- **Paradigm Shift**: Async inference decouples action prediction from execution, allowing robots to continue acting while new action chunks are computed in parallel
+- **Performance Benefits**: Eliminates "wait-for-inference" lags that are inherent in synchronous approaches, becoming increasingly important as policy models grow larger
+- **Flexible Architecture**: The server-client design enables distributed computing, where inference can run on powerful remote hardware while maintaining real-time robot control
+- **Tunable Parameters**: Success depends on properly configuring `actions_per_chunk` and `chunk_size_threshold` for your specific hardware, policy, and task requirements
+- **Universal Compatibility**: Works with all LeRobot-supported policies, from lightweight ACT models to vision-language models like SmolVLA
+
+Start experimenting with the default parameters, monitor your action queue sizes, and iteratively refine your setup to achieve optimal performance for your specific use case.
+If you want to discuss this further, hop into our [Discord community](https://discord.gg/s3KuuzsPFb), or open an issue on our [GitHub repository](https://github.com/lerobot/lerobot/issues).
diff --git a/lerobot/docs/source/backwardcomp.mdx b/lerobot/docs/source/backwardcomp.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..a0546eee722d123bcb7ab8ebaeedcd27b936f6f6
--- /dev/null
+++ b/lerobot/docs/source/backwardcomp.mdx
@@ -0,0 +1,151 @@
+# Backward compatibility
+
+## Policy Normalization Migration (PR #1452)
+
+**Breaking Change**: LeRobot policies no longer have built-in normalization layers embedded in their weights. Normalization is now handled by external `PolicyProcessorPipeline` components.
+
+### What changed?
+
+| | Before PR #1452 | After PR #1452 |
+| -------------------------- | ------------------------------------------------ | ------------------------------------------------------------ |
+| **Normalization Location** | Embedded in model weights (`normalize_inputs.*`) | External `PolicyProcessorPipeline` components |
+| **Model State Dict** | Contains normalization statistics | **Clean weights only** - no normalization parameters |
+| **Usage** | `policy(batch)` handles everything | `preprocessor(batch)` β `policy(...)` β `postprocessor(...)` |
+
+### Impact on existing models
+
+- Models trained **before** PR #1452 have normalization embedded in their weights
+- These models need migration to work with the new `PolicyProcessorPipeline` system
+- The migration extracts normalization statistics and creates separate processor pipelines
+
+### Migrating old models
+
+Use the migration script to convert models with embedded normalization:
+
+```shell
+python src/lerobot/processor/migrate_policy_normalization.py \
+ --pretrained-path lerobot/act_aloha_sim_transfer_cube_human \
+ --push-to-hub \
+ --branch migrated
+```
+
+The script:
+
+1. **Extracts** normalization statistics from model weights
+2. **Creates** external preprocessor and postprocessor pipelines
+3. **Removes** normalization layers from model weights
+4. **Saves** clean model + processor pipelines
+5. **Pushes** to Hub with automatic PR creation
+
+### Using migrated models
+
+```python
+# New usage pattern (after migration)
+from lerobot.policies.factory import make_policy, make_pre_post_processors
+
+# Load model and processors separately
+policy = make_policy(config, ds_meta=dataset.meta)
+preprocessor, postprocessor = make_pre_post_processors(
+ policy_cfg=config,
+ dataset_stats=dataset.meta.stats
+)
+
+# Process data through pipeline
+processed_batch = preprocessor(raw_batch)
+action = policy.select_action(processed_batch)
+final_action = postprocessor(action)
+```
+
+## Hardware API redesign
+
+PR [#777](https://github.com/huggingface/lerobot/pull/777) improves the LeRobot calibration but is **not backward-compatible**. Below is a overview of what changed and how you can continue to work with datasets created before this pull request.
+
+### What changed?
+
+| | Before PR #777 | After PR #777 |
+| --------------------------------- | ------------------------------------------------- | ------------------------------------------------------------ |
+| **Joint range** | Degrees `-180...180Β°` | **Normalised range** Joints: `β100...100` Gripper: `0...100` |
+| **Zero position (SO100 / SO101)** | Arm fully extended horizontally | **In middle of the range for each joint** |
+| **Boundary handling** | Software safeguards to detect Β±180 Β° wrap-arounds | No wrap-around logic needed due to mid-range zero |
+
+---
+
+### Impact on existing datasets
+
+- Recorded trajectories created **before** PR #777 will replay incorrectly if loaded directly:
+ - Joint angles are offset and incorrectly normalized.
+- Any models directly finetuned or trained on the old data will need their inputs and outputs converted.
+
+### Using datasets made with the previous calibration system
+
+We provide a migration example script for replaying an episode recorded with the previous calibration here: `examples/backward_compatibility/replay.py`.
+Below we take you through the modifications that are done in the example script to make the previous calibration datasets work.
+
+```diff
++ key = f"{name.removeprefix('main_')}.pos"
+ action[key] = action_array[i].item()
++ action["shoulder_lift.pos"] = -(action["shoulder_lift.pos"] - 90)
++ action["elbow_flex.pos"] -= 90
+```
+
+Let's break this down.
+New codebase uses `.pos` suffix for the position observations and we have removed `main_` prefix:
+
+
+```python
+key = f"{name.removeprefix('main_')}.pos"
+```
+
+
+For `"shoulder_lift"` (id = 2), the 0 position is changed by -90 degrees and the direction is reversed compared to old calibration/code.
+
+
+```python
+action["shoulder_lift.pos"] = -(action["shoulder_lift.pos"] - 90)
+```
+
+
+For `"elbow_flex"` (id = 3), the 0 position is changed by -90 degrees compared to old calibration/code.
+
+
+```python
+action["elbow_flex.pos"] -= 90
+```
+
+
+To use degrees normalization we then set the `--robot.use_degrees` option to `true`.
+
+```diff
+python examples/backward_compatibility/replay.py \
+ --robot.type=so101_follower \
+ --robot.port=/dev/tty.usbmodem5A460814411 \
+ --robot.id=blue \
++ --robot.use_degrees=true \
+ --dataset.repo_id=my_dataset_id \
+ --dataset.episode=0
+```
+
+### Using policies trained with the previous calibration system
+
+Policies output actions in the same format as the datasets (`torch.Tensors`). Therefore, the same transformations should be applied.
+
+To find these transformations, we recommend to first try and and replay an episode of the dataset your policy was trained on using the section above.
+Then, add these same transformations on your inference script (shown here in the `record.py` script):
+
+```diff
+action_values = predict_action(
+ observation_frame,
+ policy,
+ get_safe_torch_device(policy.config.device),
+ policy.config.use_amp,
+ task=single_task,
+ robot_type=robot.robot_type,
+ )
+ action = {key: action_values[i].item() for i, key in enumerate(robot.action_features)}
+
++ action["shoulder_lift.pos"] = -(action["shoulder_lift.pos"] - 90)
++ action["elbow_flex.pos"] -= 90
+ robot.send_action(action)
+```
+
+If you have questions or run into migration issues, feel free to ask them on [Discord](https://discord.gg/s3KuuzsPFb)
diff --git a/lerobot/docs/source/bring_your_own_policies.mdx b/lerobot/docs/source/bring_your_own_policies.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..df1401fac82dccb9f7d4d5c3f13dbf7cf4ae0b82
--- /dev/null
+++ b/lerobot/docs/source/bring_your_own_policies.mdx
@@ -0,0 +1,175 @@
+# Bring Your Own Policies
+
+This tutorial explains how to integrate your own custom policy implementations into the LeRobot ecosystem, allowing you to leverage all LeRobot tools for training, evaluation, and deployment while using your own algorithms.
+
+## Step 1: Create a Policy Package
+
+Your custom policy should be organized as an installable Python package following LeRobot's plugin conventions.
+
+### Package Structure
+
+Create a package with the prefix `lerobot_policy_` (IMPORTANT!) followed by your policy name:
+
+```bash
+lerobot_policy_my_custom_policy/
+βββ pyproject.toml
+βββ src/
+ βββ lerobot_policy_my_custom_policy/
+ βββ __init__.py
+ βββ configuration_my_custom_policy.py
+ βββ modeling_my_custom_policy.py
+ βββ processor_my_custom_policy.py
+```
+
+### Package Configuration
+
+Set up your `pyproject.toml`:
+
+```toml
+[project]
+name = "lerobot_policy_my_custom_policy"
+version = "0.1.0"
+dependencies = [
+ # your policy-specific dependencies
+]
+requires-python = ">= 3.11"
+
+[build-system]
+build-backend = # your-build-backend
+requires = # your-build-system
+```
+
+## Step 2: Define the Policy Configuration
+
+Create a configuration class that inherits from `PreTrainedConfig` and registers your policy type:
+
+```python
+# configuration_my_custom_policy.py
+from dataclasses import dataclass, field
+from lerobot.configs.policies import PreTrainedConfig
+from lerobot.configs.types import NormalizationMode
+
+@PreTrainedConfig.register_subclass("my_custom_policy")
+@dataclass
+class MyCustomPolicyConfig(PreTrainedConfig):
+ """Configuration class for MyCustomPolicy.
+
+ Args:
+ n_obs_steps: Number of observation steps to use as input
+ horizon: Action prediction horizon
+ n_action_steps: Number of action steps to execute
+ hidden_dim: Hidden dimension for the policy network
+ # Add your policy-specific parameters here
+ """
+ # ...PreTrainedConfig fields...
+ pass
+
+ def __post_init__(self):
+ super().__post_init__()
+ # Add any validation logic here
+
+ def validate_features(self) -> None:
+ """Validate input/output feature compatibility."""
+ # Implement validation logic for your policy's requirements
+ pass
+```
+
+## Step 3: Implement the Policy Class
+
+Create your policy implementation by inheriting from LeRobot's base `PreTrainedPolicy` class:
+
+```python
+# modeling_my_custom_policy.py
+import torch
+import torch.nn as nn
+from typing import Dict, Any
+
+from lerobot.policies.pretrained import PreTrainedPolicy
+from .configuration_my_custom_policy import MyCustomPolicyConfig
+
+class MyCustomPolicy(PreTrainedPolicy):
+ config_class = MyCustomPolicyConfig
+ name = "my_custom_policy"
+
+ def __init__(self, config: MyCustomPolicyConfig, dataset_stats: Dict[str, Any] = None):
+ super().__init__(config, dataset_stats)
+ ...
+```
+
+## Step 4: Add Data Processors
+
+Create processor functions:
+
+```python
+# processor_my_custom_policy.py
+from typing import Dict, Any
+import torch
+
+
+def make_my_custom_policy_pre_post_processors(
+ config,
+) -> tuple[
+ PolicyProcessorPipeline[dict[str, Any], dict[str, Any]],
+ PolicyProcessorPipeline[PolicyAction, PolicyAction],
+]:
+ """Create preprocessing and postprocessing functions for your policy."""
+ pass # Define your preprocessing and postprocessing logic here
+
+```
+
+## Step 5: Package Initialization
+
+Expose your classes in the package's `__init__.py`:
+
+```python
+# __init__.py
+"""Custom policy package for LeRobot."""
+
+try:
+ import lerobot # noqa: F401
+except ImportError:
+ raise ImportError(
+ "lerobot is not installed. Please install lerobot to use this policy package."
+ )
+
+from .configuration_my_custom_policy import MyCustomPolicyConfig
+from .modeling_my_custom_policy import MyCustomPolicy
+from .processor_my_custom_policy import make_my_custom_policy_pre_post_processors
+
+__all__ = [
+ "MyCustomPolicyConfig",
+ "MyCustomPolicy",
+ "make_my_custom_policy_pre_post_processors",
+]
+```
+
+## Step 6: Installation and Usage
+
+### Install Your Policy Package
+
+```bash
+cd lerobot_policy_my_custom_policy
+pip install -e .
+
+# Or install from PyPI if published
+pip install lerobot_policy_my_custom_policy
+```
+
+### Use Your Policy
+
+Once installed, your policy automatically integrates with LeRobot's training and evaluation tools:
+
+```bash
+lerobot-train \
+ --policy.type my_custom_policy \
+ --env.type pusht \
+ --steps 200000
+```
+
+## Examples and Community Contributions
+
+Check out these example policy implementations:
+
+- [DiTFlow Policy](https://github.com/danielsanjosepro/lerobot_policy_ditflow) - Diffusion Transformer policy with flow-matching objective. Try it out in this example: [DiTFlow Example](https://github.com/danielsanjosepro/test_lerobot_policy_ditflow)
+
+Share your policy implementations with the community! π€
diff --git a/lerobot/docs/source/cameras.mdx b/lerobot/docs/source/cameras.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..98205ce105bb2191f67da993cc6d85e0f7873b42
--- /dev/null
+++ b/lerobot/docs/source/cameras.mdx
@@ -0,0 +1,206 @@
+# Cameras
+
+LeRobot offers multiple options for video capture, including phone cameras, built-in laptop cameras, external webcams, and Intel RealSense cameras. To efficiently record frames from most cameras, you can use either the `OpenCVCamera` or `RealSenseCamera` class. For additional compatibility details on the `OpenCVCamera` class, refer to the [Video I/O with OpenCV Overview](https://docs.opencv.org/4.x/d0/da7/videoio_overview.html).
+
+### Finding your camera
+
+To instantiate a camera, you need a camera identifier. This identifier might change if you reboot your computer or re-plug your camera, a behavior mostly dependant on your operating system.
+
+To find the camera indices of the cameras plugged into your system, run the following script:
+
+```bash
+lerobot-find-cameras opencv # or realsense for Intel Realsense cameras
+```
+
+The output will look something like this if you have two cameras connected:
+
+```
+--- Detected Cameras ---
+Camera #0:
+ Name: OpenCV Camera @ 0
+ Type: OpenCV
+ Id: 0
+ Backend api: AVFOUNDATION
+ Default stream profile:
+ Format: 16.0
+ Width: 1920
+ Height: 1080
+ Fps: 15.0
+--------------------
+(more cameras ...)
+```
+
+> [!WARNING]
+> When using Intel RealSense cameras in `macOS`, you could get this [error](https://github.com/IntelRealSense/librealsense/issues/12307): `Error finding RealSense cameras: failed to set power state`, this can be solved by running the same command with `sudo` permissions. Note that using RealSense cameras in `macOS` is unstable.
+
+## Use Cameras
+
+Below are two examples, demonstrating how to work with the API.
+
+- **Asynchronous frame capture** using an OpenCV-based camera
+- **Color and depth capture** using an Intel RealSense camera
+
+
+
+
+
+```python
+from lerobot.cameras.opencv.configuration_opencv import OpenCVCameraConfig
+from lerobot.cameras.opencv.camera_opencv import OpenCVCamera
+from lerobot.cameras.configs import ColorMode, Cv2Rotation
+
+# Construct an `OpenCVCameraConfig` with your desired FPS, resolution, color mode, and rotation.
+config = OpenCVCameraConfig(
+ index_or_path=0,
+ fps=15,
+ width=1920,
+ height=1080,
+ color_mode=ColorMode.RGB,
+ rotation=Cv2Rotation.NO_ROTATION
+)
+
+# Instantiate and connect an `OpenCVCamera`, performing a warm-up read (default).
+camera = OpenCVCamera(config)
+camera.connect()
+
+# Read frames asynchronously in a loop via `async_read(timeout_ms)`
+try:
+ for i in range(10):
+ frame = camera.async_read(timeout_ms=200)
+ print(f"Async frame {i} shape:", frame.shape)
+finally:
+ camera.disconnect()
+```
+
+
+
+
+
+
+```python
+from lerobot.cameras.realsense.configuration_realsense import RealSenseCameraConfig
+from lerobot.cameras.realsense.camera_realsense import RealSenseCamera
+from lerobot.cameras.configs import ColorMode, Cv2Rotation
+
+# Create a `RealSenseCameraConfig` specifying your cameraβs serial number and enabling depth.
+config = RealSenseCameraConfig(
+ serial_number_or_name="233522074606",
+ fps=15,
+ width=640,
+ height=480,
+ color_mode=ColorMode.RGB,
+ use_depth=True,
+ rotation=Cv2Rotation.NO_ROTATION
+)
+
+# Instantiate and connect a `RealSenseCamera` with warm-up read (default).
+camera = RealSenseCamera(config)
+camera.connect()
+
+# Capture a color frame via `read()` and a depth map via `read_depth()`.
+try:
+ color_frame = camera.read()
+ depth_map = camera.read_depth()
+ print("Color frame shape:", color_frame.shape)
+ print("Depth map shape:", depth_map.shape)
+finally:
+ camera.disconnect()
+```
+
+
+
+
+
+## Use your phone
+
+
+
+
+To use your iPhone as a camera on macOS, enable the Continuity Camera feature:
+
+- Ensure your Mac is running macOS 13 or later, and your iPhone is on iOS 16 or later.
+- Sign in both devices with the same Apple ID.
+- Connect your devices with a USB cable or turn on Wi-Fi and Bluetooth for a wireless connection.
+
+For more details, visit [Apple support](https://support.apple.com/en-gb/guide/mac-help/mchl77879b8a/mac).
+
+Your iPhone should be detected automatically when running the camera setup script in the next section.
+
+
+
+
+If you want to use your phone as a camera on Linux, follow these steps to set up a virtual camera
+
+1. _Install `v4l2loopback-dkms` and `v4l-utils`_. Those packages are required to create virtual camera devices (`v4l2loopback`) and verify their settings with the `v4l2-ctl` utility from `v4l-utils`. Install them using:
+
+
+```python
+sudo apt install v4l2loopback-dkms v4l-utils
+```
+
+
+2. _Install [DroidCam](https://droidcam.app) on your phone_. This app is available for both iOS and Android.
+3. _Install [OBS Studio](https://obsproject.com)_. This software will help you manage the camera feed. Install it using [Flatpak](https://flatpak.org):
+
+
+```python
+flatpak install flathub com.obsproject.Studio
+```
+
+
+4. _Install the DroidCam OBS plugin_. This plugin integrates DroidCam with OBS Studio. Install it with:
+
+
+```python
+flatpak install flathub com.obsproject.Studio.Plugin.DroidCam
+```
+
+
+5. _Start OBS Studio_. Launch with:
+
+
+```python
+flatpak run com.obsproject.Studio
+```
+
+
+6. _Add your phone as a source_. Follow the instructions [here](https://droidcam.app/obs/usage). Be sure to set the resolution to `640x480`.
+7. _Adjust resolution settings_. In OBS Studio, go to `File > Settings > Video`. Change the `Base(Canvas) Resolution` and the `Output(Scaled) Resolution` to `640x480` by manually typing it in.
+8. _Start virtual camera_. In OBS Studio, follow the instructions [here](https://obsproject.com/kb/virtual-camera-guide).
+9. _Verify the virtual camera setup_. Use `v4l2-ctl` to list the devices:
+
+
+```python
+v4l2-ctl --list-devices
+```
+
+
+You should see an entry like:
+
+```
+VirtualCam (platform:v4l2loopback-000):
+/dev/video1
+```
+
+10. _Check the camera resolution_. Use `v4l2-ctl` to ensure that the virtual camera output resolution is `640x480`. Change `/dev/video1` to the port of your virtual camera from the output of `v4l2-ctl --list-devices`.
+
+
+```python
+v4l2-ctl -d /dev/video1 --get-fmt-video
+```
+
+
+You should see an entry like:
+
+```
+>>> Format Video Capture:
+>>> Width/Height : 640/480
+>>> Pixel Format : 'YUYV' (YUYV 4:2:2)
+```
+
+Troubleshooting: If the resolution is not correct you will have to delete the Virtual Camera port and try again as it cannot be changed.
+
+If everything is set up correctly, you can proceed with the rest of the tutorial.
+
+
+
diff --git a/lerobot/docs/source/contributing.md b/lerobot/docs/source/contributing.md
new file mode 100644
index 0000000000000000000000000000000000000000..f939e75f21a8badb5c40f527abd0e098fe9bc472
--- /dev/null
+++ b/lerobot/docs/source/contributing.md
@@ -0,0 +1 @@
+../../CONTRIBUTING.md
\ No newline at end of file
diff --git a/lerobot/docs/source/debug_processor_pipeline.mdx b/lerobot/docs/source/debug_processor_pipeline.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..d39eda92c2405ea51cfe20fbb0acf8e3f1f71049
--- /dev/null
+++ b/lerobot/docs/source/debug_processor_pipeline.mdx
@@ -0,0 +1,299 @@
+# Debug Your Processor Pipeline
+
+Processor pipelines can be complex, especially when chaining multiple transformation steps.
+Unlike simple function calls, pipelines lack natural observability, you can't easily see what happens
+between each step or where things go wrong.
+This guide provides debugging tools and techniques specifically designed to address these challenges
+and help you understand data flow through your pipelines.
+
+We'll explore three complementary debugging approaches: **hooks** for runtime monitoring, **step-through debugging** for detailed inspection, and **feature validation** for catching structural mismatches. Each serves a different purpose and together they provide complete visibility into your pipeline's behavior.
+
+## Understanding Hooks
+
+Hooks are functions that get called at specific points during pipeline execution.
+They provide a way to inspect, monitor, or modify data without changing your pipeline code.
+Think of them as "event listeners" for your pipeline.
+
+### What is a Hook?
+
+A hook is a callback function that gets automatically invoked at specific moments during pipeline execution.
+The concept comes from event-driven programming, imagine you could "hook into" the pipeline's execution flow to observe or react to what's happening.
+
+Think of hooks like inserting checkpoints into your pipeline. Every time the pipeline reaches one of these checkpoints, it pauses briefly to call your hook function, giving you a chance to inspect the current state, log information, and validate data.
+
+A hook is simply a function that accepts two parameters:
+
+- `step_idx: int` - The index of the current processing step (0, 1, 2, etc.)
+- `transition: EnvTransition` - The data transition at that point in the pipeline
+
+The beauty of hooks is their non-invasive nature: you can add monitoring, validation, or debugging logic without changing a single line of your pipeline code. The pipeline remains clean and focused on its core logic, while hooks handle the cross-cutting concerns like logging, monitoring, and debugging.
+
+### Before vs After Hooks
+
+The pipeline supports two types of hooks:
+
+- **Before hooks** (`register_before_step_hook`) - Called before each step executes
+- **After hooks** (`register_after_step_hook`) - Called after each step completes
+
+```python
+def before_hook(step_idx: int, transition: EnvTransition):
+ """Called before step processes the transition."""
+ print(f"About to execute step {step_idx}")
+ # Useful for: logging, validation, setup
+
+def after_hook(step_idx: int, transition: EnvTransition):
+ """Called after step has processed the transition."""
+ print(f"Completed step {step_idx}")
+ # Useful for: monitoring results, cleanup, debugging
+
+processor.register_before_step_hook(before_hook)
+processor.register_after_step_hook(after_hook)
+```
+
+### Implementing a NaN Detection Hook
+
+Here's a practical example of a hook that detects NaN values:
+
+```python
+def check_nans(step_idx: int, transition: EnvTransition):
+ """Check for NaN values in observations."""
+ obs = transition.get(TransitionKey.OBSERVATION)
+ if obs:
+ for key, value in obs.items():
+ if isinstance(value, torch.Tensor) and torch.isnan(value).any():
+ print(f"NaN detected in {key} at step {step_idx}")
+
+# Register the hook to run after each step
+processor.register_after_step_hook(check_nans)
+
+# Process your data - the hook will be called automatically
+output = processor(input_data)
+
+# Remove the hook when done debugging
+processor.unregister_after_step_hook(check_nans)
+```
+
+### How Hooks Work Internally
+
+Understanding the internal mechanism helps you use hooks more effectively. The pipeline maintains two separate lists: one for before-step hooks and another for after-step hooks. When you register a hook, it's simply appended to the appropriate list.
+
+During execution, the pipeline follows a strict sequence: for each processing step, it first calls all before-hooks in registration order, then executes the actual step transformation, and finally calls all after-hooks in registration order. This creates a predictable, sandwich-like structure around each step.
+
+The key insight is that hooks don't change the core pipeline logicβthey're purely additive. The pipeline's `_forward` method orchestrates this dance between hooks and processing steps, ensuring that your debugging or monitoring code runs at exactly the right moments without interfering with the main data flow.
+
+Here's a simplified view of how the pipeline executes hooks:
+
+```python
+class DataProcessorPipeline:
+ def __init__(self):
+ self.steps = [...]
+ self.before_step_hooks = [] # List of before hooks
+ self.after_step_hooks = [] # List of after hooks
+
+ def _forward(self, transition):
+ """Internal method that processes the transition through all steps."""
+ for step_idx, processor_step in enumerate(self.steps):
+ # 1. Call all BEFORE hooks
+ for hook in self.before_step_hooks:
+ hook(step_idx, transition)
+
+ # 2. Execute the actual processing step
+ transition = processor_step(transition)
+
+ # 3. Call all AFTER hooks
+ for hook in self.after_step_hooks:
+ hook(step_idx, transition)
+
+ return transition
+
+ def register_before_step_hook(self, hook_fn):
+ self.before_step_hooks.append(hook_fn)
+
+ def register_after_step_hook(self, hook_fn):
+ self.after_step_hooks.append(hook_fn)
+```
+
+### Execution Flow
+
+The execution flow looks like this:
+
+```
+Input β Before Hook β Step 0 β After Hook β Before Hook β Step 1 β After Hook β ... β Output
+```
+
+For example, with 3 steps and both hook types:
+
+```python
+def timing_before(step_idx, transition):
+ print(f"β±οΈ Starting step {step_idx}")
+
+def validation_after(step_idx, transition):
+ print(f"β Completed step {step_idx}")
+
+processor.register_before_step_hook(timing_before)
+processor.register_after_step_hook(validation_after)
+
+# This will output:
+# β±οΈ Starting step 0
+# β Completed step 0
+# β±οΈ Starting step 1
+# β Completed step 1
+# β±οΈ Starting step 2
+# β Completed step 2
+```
+
+### Multiple Hooks
+
+You can register multiple hooks of the same type - they execute in the order registered:
+
+```python
+def log_shapes(step_idx: int, transition: EnvTransition):
+ obs = transition.get(TransitionKey.OBSERVATION)
+ if obs:
+ print(f"Step {step_idx} observation shapes:")
+ for key, value in obs.items():
+ if isinstance(value, torch.Tensor):
+ print(f" {key}: {value.shape}")
+
+processor.register_after_step_hook(check_nans) # Executes first
+processor.register_after_step_hook(log_shapes) # Executes second
+
+# Both hooks will be called after each step in registration order
+output = processor(input_data)
+```
+
+While hooks are excellent for monitoring specific issues (like NaN detection) or gathering metrics during normal pipeline execution, sometimes you need to dive deeper. When you want to understand exactly what happens at each step or debug complex transformation logic, step-through debugging provides the detailed inspection you need.
+
+## Step-Through Debugging
+
+Step-through debugging is like having a slow-motion replay for your pipeline. Instead of watching your data get transformed in one quick blur from input to output, you can pause and examine what happens after each individual step.
+
+This approach is particularly valuable when you're trying to understand a complex pipeline, debug unexpected behavior, or verify that each transformation is working as expected. Unlike hooks, which are great for automated monitoring, step-through debugging gives you manual, interactive control over the inspection process.
+
+The `step_through()` method is a generator that yields the transition state after each processing step, allowing you to inspect intermediate results. Think of it as creating a series of snapshots of your data as it flows through the pipelineβeach snapshot shows you exactly what your data looks like after one more transformation has been applied.
+
+### How Step-Through Works
+
+The `step_through()` method fundamentally changes how the pipeline executes. Instead of running all steps in sequence and only returning the final result, it transforms the pipeline into an iterator that yields intermediate results.
+
+Here's what happens internally: the method starts by converting your input data into the pipeline's internal transition format, then yields this initial state. Next, it applies the first processing step and yields the result. Then it applies the second step to that result and yields again, and so on. Each `yield` gives you a complete snapshot of the transition at that point.
+
+This generator pattern is powerful because it's lazyβthe pipeline only computes the next step when you ask for it. This means you can stop at any point, inspect the current state thoroughly, and decide whether to continue. You're not forced to run the entire pipeline just to debug one problematic step.
+
+Instead of running the entire pipeline and only seeing the final result, `step_through()` pauses after each step and gives you the intermediate transition:
+
+```python
+# This creates a generator that yields intermediate states
+for i, intermediate_result in enumerate(processor.step_through(input_data)):
+ print(f"=== After step {i} ===")
+
+ # Inspect the observation at this stage
+ obs = intermediate_result.get(TransitionKey.OBSERVATION)
+ if obs:
+ for key, value in obs.items():
+ if isinstance(value, torch.Tensor):
+ print(f"{key}: shape={value.shape}, dtype={value.dtype}")
+```
+
+### Interactive Debugging with Breakpoints
+
+You can add breakpoints in the step-through loop to interactively debug:
+
+```python
+# Step through the pipeline with debugging
+for i, intermediate in enumerate(processor.step_through(data)):
+ print(f"Step {i}: {processor.steps[i].__class__.__name__}")
+
+ # Set a breakpoint to inspect the current state
+ breakpoint() # Debugger will pause here
+
+ # You can now inspect 'intermediate' in the debugger:
+ # - Check tensor shapes and values
+ # - Verify expected transformations
+ # - Look for unexpected changes
+```
+
+During the debugger session, you can:
+
+- Examine `intermediate[TransitionKey.OBSERVATION]` to see observation data
+- Check `intermediate[TransitionKey.ACTION]` for action transformations
+- Inspect any part of the transition to understand what each step does
+
+Step-through debugging is perfect for understanding the _data_ transformations, but what about the _structure_ of that data? While hooks and step-through help you debug runtime behavior, you also need to ensure your pipeline produces data in the format expected by downstream components. This is where feature contract validation comes in.
+
+## Validating Feature Contracts
+
+Feature contracts define what data structure your pipeline expects as input and produces as output.
+Validating these contracts helps catch mismatches early.
+
+### Understanding Feature Contracts
+
+Each processor step has a `transform_features()` method that describes how it changes the data structure:
+
+```python
+# Get the expected output features from your pipeline
+initial_features = {
+ PipelineFeatureType.OBSERVATION: {
+ "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(7,)),
+ "observation.image": PolicyFeature(type=FeatureType.IMAGE, shape=(3, 224, 224))
+ },
+ PipelineFeatureType.ACTION: {
+ "action": PolicyFeature(type=FeatureType.ACTION, shape=(4,))
+ }
+}
+
+# Check what your pipeline will output
+output_features = processor.transform_features(initial_features)
+
+print("Input features:")
+for feature_type, features in initial_features.items():
+ print(f" {feature_type}:")
+ for key, feature in features.items():
+ print(f" {key}: {feature.type.value}, shape={feature.shape}")
+
+print("\nOutput features:")
+for feature_type, features in output_features.items():
+ print(f" {feature_type}:")
+ for key, feature in features.items():
+ print(f" {key}: {feature.type.value}, shape={feature.shape}")
+```
+
+### Verifying Expected Features
+
+Check that your pipeline produces the features you expect:
+
+```python
+# Define what features you expect the pipeline to produce
+expected_keys = ["observation.state", "observation.image", "action"]
+
+print("Validating feature contract...")
+for expected_key in expected_keys:
+ found = False
+ for feature_type, features in output_features.items():
+ if expected_key in features:
+ feature = features[expected_key]
+ print(f"β {expected_key}: {feature.type.value}, shape={feature.shape}")
+ found = True
+ break
+
+ if not found:
+ print(f"β Missing expected feature: {expected_key}")
+```
+
+This validation helps ensure your pipeline will work correctly with downstream components that expect specific data structures.
+
+## Summary
+
+Now that you understand the three debugging approaches, you can tackle any pipeline issue systematically:
+
+1. **Hooks** - For runtime monitoring and validation without modifying pipeline code
+2. **Step-through** - For inspecting intermediate states and understanding transformations
+3. **Feature validation** - For ensuring data structure contracts are met
+
+**When to use each approach:**
+
+- Start with **step-through debugging** when you need to understand what your pipeline does or when something unexpected happens
+- Add **hooks** for continuous monitoring during development and production to catch issues automatically
+- Use **feature validation** before deployment to ensure your pipeline works with downstream components
+
+These three tools work together to give you the complete observability that complex pipelines naturally lack. With hooks watching for issues, step-through helping you understand behavior, and feature validation ensuring compatibility, you'll be able to debug any pipeline confidently and efficiently.
diff --git a/lerobot/docs/source/earthrover_mini_plus.mdx b/lerobot/docs/source/earthrover_mini_plus.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..a05ec46f6c29d929c612c23b0d109de49f68ae6f
--- /dev/null
+++ b/lerobot/docs/source/earthrover_mini_plus.mdx
@@ -0,0 +1,225 @@
+# EarthRover Mini Plus
+
+The EarthRover Mini Plus is a fully open source mobile robot that connects through the cloud using the Frodobots SDK. This lets you control the robot and record datasets for training AI models.
+
+## What You Need
+
+### Hardware
+
+- EarthRover Mini robot
+- Computer with Python 3.10 or newer
+- Internet connection
+
+### Setting Up the Frodobots SDK
+
+The robot needs the [Frodobots SDK](https://github.com/frodobots-org/earth-rovers-sdk) running on your computer. Here's how:
+
+1. Download and install the SDK:
+
+```bash
+git clone https://github.com/frodobots-org/earth-rovers-sdk.git
+cd earth-rovers-sdk
+pip install -r requirements.txt
+```
+
+2. Save Credentials:
+
+Write your .env variables with the SDK API key and bot name provided by the Frodobots team.
+
+```bash
+SDK_API_TOKEN=your_sdk_api_token_here
+BOT_SLUG=your_bot_slug_here
+CHROME_EXECUTABLE_PATH=/path/to/chrome_or_chromium
+# Default value is MAP_ZOOM_LEVEL=18 https://wiki.openstreetmap.org/wiki/Zoom_levels
+MAP_ZOOM_LEVEL=18
+MISSION_SLUG=your_mission_slug_here
+# Image quality between 0.1 and 1.0 (default: 0.8)
+# Recommended: 0.8 for better performance
+IMAGE_QUALITY=0.8
+# Image format: jpeg, png or webp (default: png)
+# Recommended: jpeg for better performance and lower bandwidth usage
+IMAGE_FORMAT=jpeg
+```
+
+3. Start the SDK:
+
+```bash
+hypercorn main:app --reload
+```
+
+4. Open your web browser and go to `http://localhost:8000`, then click "Join"
+
+The SDK gives you:
+
+- Live video from front and rear cameras
+
+> [!IMPORTANT]
+> The SDK must be running before you can use the robot.
+
+## Install LeRobot
+
+Follow our [Installation Guide](./installation) to install LeRobot.
+
+In addition to the base installation, install the EarthRover Mini dependencies:
+
+```bash
+pip install -e .
+```
+
+## How It Works
+
+The robot uses the internet to communicate:
+
+- **Movement commands**: Sent through the SDK
+- **Camera video**: Received from the SDK
+- **Robot info**: Battery, location, speed from the SDK
+
+You don't need to plug anything in - it all works through the SDK.
+
+## Calibration
+
+No calibration needed! The robot is ready to use as soon as the SDK is running.
+
+## Controlling the Robot
+
+You control the robot using your keyboard - just like playing a video game with WASD keys.
+
+### Keyboard Controls
+
+| Key | Action |
+| --- | -------------------------------- |
+| W | Move forward |
+| S | Move backward |
+| A | Turn left (with forward motion) |
+| D | Turn right (with forward motion) |
+| Q | Rotate left in place |
+| E | Rotate right in place |
+| X | Stop all movement |
+| +/= | Increase speed |
+| - | Decrease speed |
+| ESC | Disconnect |
+
+### Speed Settings
+
+You can adjust how fast the robot moves:
+
+- **Forward/backward speed**: Default is full speed (1.0)
+- **Turning speed**: Default is full speed (1.0)
+- **Speed changes**: Use +/- keys to adjust by 0.1 each time
+
+### Try It Out
+
+Test driving the robot before recording data:
+
+```python
+from lerobot.robots.earthrover_mini_plus import EarthRoverMiniPlus, EarthRoverMiniPlusConfig
+from lerobot.teleoperators.keyboard import KeyboardRoverTeleop, KeyboardRoverTeleopConfig
+
+# Initialize robot
+robot_config = EarthRoverMiniPlusConfig()
+robot = EarthRoverMiniPlus(robot_config)
+
+# Initialize teleoperator
+teleop_config = KeyboardRoverTeleopConfig(
+ linear_speed=1.0,
+ angular_speed=1.0,
+ speed_increment=0.1
+)
+teleop = KeyboardRoverTeleop(teleop_config)
+
+# Connect
+robot.connect()
+teleop.connect()
+
+# Teleoperate (use keyboard controls)
+try:
+ while True:
+ action = teleop.get_action()
+ robot.send_action(action)
+except KeyboardInterrupt:
+ pass
+finally:
+ robot.disconnect()
+ teleop.disconnect()
+```
+
+> [!TIP]
+> If you're using a Mac, you might need to give Terminal permission to access your keyboard for teleoperation. Go to System Preferences > Security & Privacy > Input Monitoring and check the box for Terminal.
+
+## Recording Data
+
+Once you can drive the robot well, you can start recording data to train AI models. The system records:
+
+- **What you do**: How you move the robot (forward, backward, turning)
+- **What the robot sees**:
+ - Videos from both cameras
+ - Robot speed and direction
+ - Battery level and location
+ - GPS position and signal
+ - Other sensor data
+- **When it happened**: Timestamps for everything
+
+### Setting Up Hugging Face
+
+We use Hugging Face to store your data online. First, log in with your token from [Hugging Face settings](https://huggingface.co/settings/tokens):
+
+```bash
+huggingface-cli login --token ${HUGGINGFACE_TOKEN} --add-to-git-credential
+```
+
+Store your Hugging Face username:
+
+```bash
+HF_USER=$(huggingface-cli whoami | head -n 1)
+echo $HF_USER
+```
+
+### Start Recording
+
+Use the standard recording command:
+
+```bash
+python src/lerobot/scripts/lerobot_record.py \
+ --robot.type=earthrover_mini_plus \
+ --teleop.type=keyboard_rover \
+ --dataset.repo_id=your_username/dataset_name \
+ --dataset.num_episodes=2 \
+ --dataset.fps=10 \
+ --dataset.single_task="Navigate around obstacles" \
+ --display_data=true
+```
+
+Replace `your_username/dataset_name` with your Hugging Face username and a name for your dataset.
+
+### What Gets Saved
+
+Your dataset includes:
+
+**Your Actions (2 things)**:
+
+- How much you moved forward/backward
+- How much you turned left/right
+
+**Robot Observations (12 things)**:
+
+- Front camera video
+- Rear camera video
+- Current speed
+- Battery level
+- Which way the robot is facing
+- GPS location (latitude, longitude, signal strength)
+- Network signal strength
+- Vibration level
+- Lamp status (on/off)
+
+### Where Your Data Goes
+
+On your computer: `~/.cache/huggingface/lerobot/{repo-id}`
+
+After recording, your data automatically uploads to your Hugging Face page:
+
+```bash
+echo https://huggingface.co/datasets/${HF_USER}/earthrover-navigation
+```
+
+Your dataset will be tagged with `LeRobot` for community discovery.
diff --git a/lerobot/docs/source/env_processor.mdx b/lerobot/docs/source/env_processor.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..7f5cee2832b1311f70fa6833b4d15a2effbce904
--- /dev/null
+++ b/lerobot/docs/source/env_processor.mdx
@@ -0,0 +1,418 @@
+# Environment Processors
+
+Environment processors are a critical layer in LeRobot's data processing architecture that handle **environment-specific** transformations, separate from policy-specific processing. This separation of concerns enables cleaner code, better modularity, and easier experimentation with different environments and policies.
+
+## Why Environment Processors?
+
+When working with different robot environments (LIBERO, MetaWorld, Aloha, etc.), each environment often has unique data formats, coordinate systems, and conventions that need standardization **before** policy processing. Without environment processors, these transformations would be:
+
+1. **Hardcoded in environment code** - Making it difficult to experiment with different state representations
+2. **Duplicated across policies** - Each policy would need to handle environment-specific quirks
+3. **Mixed with policy logic** - Violating separation of concerns and making debugging harder
+
+Environment processors solve this by providing a **dedicated processing layer** between raw environment observations and policy inputs.
+
+## The Processing Pipeline
+
+Here's how data flows through the complete processing pipeline during evaluation:
+
+```python
+# In lerobot_eval.py rollout() function:
+
+# 1. Raw environment observation (numpy arrays, various formats)
+raw_observation = env.step(action)
+
+# 2. Convert numpy to torch, normalize images [0,1]
+observation = preprocess_observation(raw_observation)
+
+# 3. Add task metadata (for multi-task environments)
+observation = add_envs_task(env, observation)
+
+# 4. ENVIRONMENT-SPECIFIC preprocessing (NEW!)
+# - Flatten robot states
+# - Rotate images to match dataset conventions
+# - Handle environment-specific coordinate systems
+observation = env_preprocessor(observation)
+
+# 5. POLICY-SPECIFIC preprocessing
+# - Normalize with dataset statistics
+# - Add batch dimensions
+# - Move to GPU
+# - Tokenize language instructions
+observation = preprocessor(observation)
+
+# 6. Policy inference
+action = policy.select_action(observation)
+
+# 7. POLICY-SPECIFIC postprocessing
+# - Unnormalize actions
+# - Remove batch dimensions
+action = postprocessor(action)
+
+# 8. ENVIRONMENT-SPECIFIC postprocessing (NEW!)
+# - Convert action formats if needed
+# - Apply environment-specific constraints
+action_transition = {"action": action}
+action_transition = env_postprocessor(action_transition)
+action = action_transition["action"]
+
+# 9. Execute in environment
+env.step(action)
+```
+
+## The Benefits
+
+### 1. **Separation of Concerns**
+
+Environment processors handle transformations specific to the **environment's data format**, while policy processors handle transformations specific to the **model's requirements**.
+
+```python
+# β Before: Mixed concerns
+class LiberoVLAPolicy:
+ def preprocess(self, obs):
+ # Environment-specific: Flatten robot state (shouldn't be in policy!)
+ state = self._flatten_robot_state(obs["robot_state"])
+ # Policy-specific: Normalize with dataset stats
+ state = self.normalizer(state)
+ return state
+
+# β After: Clear separation
+# Environment processor: Handles LIBERO's nested robot state
+env_preprocessor = LiberoProcessorStep() # Flattens robot_state
+
+# Policy processor: Handles model requirements
+policy_preprocessor = NormalizerProcessorStep(stats=dataset_stats)
+```
+
+### 2. **Flexibility and Reusability**
+
+The same policy can work with different environment processors, and the same environment processor can work with different policies:
+
+```python
+# Use SmolVLA policy with LIBERO environment
+libero_preprocessor, libero_postprocessor = make_env_pre_post_processors(libero_cfg)
+smolvla_preprocessor, smolvla_postprocessor = make_pre_post_processors(smolvla_cfg)
+
+# Or use ACT policy with the same LIBERO environment
+libero_preprocessor, libero_postprocessor = make_env_pre_post_processors(libero_cfg)
+act_preprocessor, act_postprocessor = make_pre_post_processors(act_cfg)
+```
+
+### 3. **Easier Experimentation**
+
+Want to try different state representations for LIBERO? Just create a new processor:
+
+```python
+# Original: 8D state (pos + quatβaxisangle + gripper)
+@ProcessorStepRegistry.register("libero_processor")
+class LiberoProcessorStep(ObservationProcessorStep):
+ def _process_observation(self, obs):
+ eef_pos = robot_state["eef"]["pos"] # 3D
+ eef_axisangle = quat2axisangle(quat) # 3D
+ gripper = robot_state["gripper"]["qpos"] # 2D
+ state = torch.cat([eef_pos, eef_axisangle, gripper], dim=-1) # 8D
+ return state
+
+# Experiment: Add velocity for better control
+@ProcessorStepRegistry.register("libero_velocity_processor")
+class LiberoVelocityProcessorStep(ObservationProcessorStep):
+ def _process_observation(self, obs):
+ # Include velocities for 14D state
+ eef_pos = robot_state["eef"]["pos"] # 3D
+ eef_axisangle = quat2axisangle(quat) # 3D
+ eef_vel = robot_state["eef"]["vel"] # 3D (NEW)
+ gripper_pos = robot_state["gripper"]["qpos"] # 2D
+ gripper_vel = robot_state["gripper"]["qvel"] # 3D (NEW)
+ state = torch.cat([eef_pos, eef_axisangle, eef_vel,
+ gripper_pos, gripper_vel], dim=-1) # 14D
+ return state
+```
+
+### 4. **Cleaner Environment Code**
+
+Environments expose **all available data** without needing to know what downstream models will use:
+
+```python
+# LIBERO environment exposes full robot state
+observation = {
+ "pixels": {"image": img, "image2": img2},
+ "robot_state": {
+ "eef": {"pos": ..., "quat": ..., "vel": ..., "mat": ..., "axisangle": ...},
+ "gripper": {"qpos": ..., "qvel": ...},
+ "joints": {"pos": ..., "vel": ...}
+ }
+}
+
+# Environment processor decides what to use
+# Policy processor handles model-specific transformations
+```
+
+## Using Environment Processors
+
+### Factory Function
+
+The `make_env_pre_post_processors` function follows the same pattern as `make_pre_post_processors` for policies:
+
+```python
+from lerobot.envs.factory import make_env_pre_post_processors
+from lerobot.envs.configs import LiberoEnv, PushtEnv
+
+# For LIBERO: Returns LiberoProcessorStep in preprocessor
+libero_cfg = LiberoEnv(task="libero_spatial", camera_name=["agentview"])
+env_preprocessor, env_postprocessor = make_env_pre_post_processors(libero_cfg)
+
+# For other environments: Returns identity processors (no-op)
+pusht_cfg = PushtEnv()
+env_preprocessor, env_postprocessor = make_env_pre_post_processors(pusht_cfg)
+```
+
+### Implementation in `envs/factory.py`
+
+```python
+def make_env_pre_post_processors(
+ env_cfg: EnvConfig,
+) -> tuple[
+ PolicyProcessorPipeline[dict[str, Any], dict[str, Any]],
+ PolicyProcessorPipeline[dict[str, Any], dict[str, Any]],
+]:
+ """
+ Create preprocessor and postprocessor pipelines for environment observations.
+
+ Args:
+ env_cfg: The configuration of the environment.
+
+ Returns:
+ A tuple containing:
+ - preprocessor: Pipeline that processes environment observations
+ - postprocessor: Pipeline that processes environment outputs
+ """
+ # For LIBERO environments, add the LiberoProcessorStep to preprocessor
+ if isinstance(env_cfg, LiberoEnv) or "libero" in env_cfg.type:
+ preprocessor = PolicyProcessorPipeline(steps=[LiberoProcessorStep()])
+ else:
+ # For all other environments, return an identity preprocessor
+ preprocessor = PolicyProcessorPipeline(steps=[])
+
+ # Postprocessor is currently identity for all environments
+ # Future: Could add environment-specific action transformations
+ postprocessor = PolicyProcessorPipeline(steps=[])
+
+ return preprocessor, postprocessor
+```
+
+### Integration in Evaluation
+
+In `lerobot_eval.py`, the environment processors are created once and used throughout:
+
+```python
+def eval_main(cfg: EvalPipelineConfig):
+ # Create environment
+ envs = make_env(cfg.env, n_envs=cfg.eval.batch_size)
+
+ # Create policy
+ policy = make_policy(cfg=cfg.policy, env_cfg=cfg.env)
+
+ # Create policy processors
+ preprocessor, postprocessor = make_pre_post_processors(
+ policy_cfg=cfg.policy,
+ pretrained_path=cfg.policy.pretrained_path,
+ )
+
+ # Create environment processors (NEW!)
+ env_preprocessor, env_postprocessor = make_env_pre_post_processors(env_cfg=cfg.env)
+
+ # Run evaluation with both processor types
+ eval_policy_all(
+ envs=envs,
+ policy=policy,
+ env_preprocessor=env_preprocessor, # Environment-specific
+ env_postprocessor=env_postprocessor, # Environment-specific
+ preprocessor=preprocessor, # Policy-specific
+ postprocessor=postprocessor, # Policy-specific
+ n_episodes=cfg.eval.n_episodes,
+ )
+```
+
+## Example: LIBERO Environment Processor
+
+The `LiberoProcessorStep` demonstrates a real-world environment processor:
+
+```python
+from lerobot.processor.pipeline import ObservationProcessorStep
+
+@dataclass
+@ProcessorStepRegistry.register(name="libero_processor")
+class LiberoProcessorStep(ObservationProcessorStep):
+ """
+ Processes LIBERO observations into the LeRobot format.
+
+ **State Processing:**
+ - Extracts end-effector position (3D)
+ - Converts quaternion to axis-angle representation (3D)
+ - Extracts gripper joint positions (2D)
+ - Concatenates into 8D state vector
+
+ **Image Processing:**
+ - Rotates images 180Β° to match HuggingFaceVLA/libero convention
+ """
+
+ def _process_observation(self, observation):
+ processed_obs = observation.copy()
+
+ # Process images: Flip 180Β° for camera convention
+ for key in list(processed_obs.keys()):
+ if key.startswith("observation.images."):
+ img = processed_obs[key]
+ img = torch.flip(img, dims=[2, 3]) # Flip H and W
+ processed_obs[key] = img
+
+ # Process robot_state: Flatten to 8D vector
+ if "observation.robot_state" in processed_obs:
+ robot_state = processed_obs.pop("observation.robot_state")
+
+ eef_pos = robot_state["eef"]["pos"] # (B, 3)
+ eef_quat = robot_state["eef"]["quat"] # (B, 4)
+ gripper_qpos = robot_state["gripper"]["qpos"] # (B, 2)
+
+ # Convert quaternion to axis-angle
+ eef_axisangle = self._quat2axisangle(eef_quat) # (B, 3)
+
+ # Concatenate into single state vector
+ state = torch.cat((eef_pos, eef_axisangle, gripper_qpos), dim=-1)
+ state = state.float()
+
+ processed_obs["observation.state"] = state
+
+ return processed_obs
+```
+
+### Why These Transformations?
+
+1. **Image Rotation**: The HuggingFaceVLA/libero dataset has images rotated 180Β° from the raw LIBERO simulator. The processor handles this convention mismatch so policies trained on the dataset work seamlessly.
+
+2. **State Flattening**: The raw LIBERO environment exposes nested dictionaries with all available state information (position, quaternion, velocity, matrix representation, etc.). The processor:
+ - Selects the relevant components (pos, quat, gripper)
+ - Converts quaternion to axis-angle (more suitable for learning)
+ - Flattens to a single 8D vector that policies expect
+
+3. **Flexibility**: The environment still exposes **all** raw data. If you want to try different state representations (e.g., including velocities, using matrix representation instead of axis-angle), you can create a new processor without modifying the environment code.
+
+## Adding Environment Processors for New Environments
+
+To add environment processors for a new environment:
+
+### 1. Create the Processor Step
+
+```python
+# In src/lerobot/processor/env_processor.py
+
+@dataclass
+@ProcessorStepRegistry.register(name="myenv_processor")
+class MyEnvProcessorStep(ObservationProcessorStep):
+ """Process observations from MyEnv."""
+
+ def _process_observation(self, observation):
+ processed = observation.copy()
+
+ # Your environment-specific transformations
+ if "myenv.specific.state" in processed:
+ state = processed.pop("myenv.specific.state")
+ # Transform to standard format
+ processed["observation.state"] = self._transform_state(state)
+
+ return processed
+```
+
+### 2. Update the Factory
+
+```python
+# In src/lerobot/envs/factory.py
+
+def make_env_pre_post_processors(env_cfg: EnvConfig):
+ if isinstance(env_cfg, LiberoEnv) or "libero" in env_cfg.type:
+ preprocessor = PolicyProcessorPipeline(steps=[LiberoProcessorStep()])
+ elif isinstance(env_cfg, MyEnvConfig) or "myenv" in env_cfg.type:
+ preprocessor = PolicyProcessorPipeline(steps=[MyEnvProcessorStep()])
+ else:
+ preprocessor = PolicyProcessorPipeline(steps=[])
+
+ postprocessor = PolicyProcessorPipeline(steps=[])
+ return preprocessor, postprocessor
+```
+
+### 3. Use in Evaluation
+
+No changes needed! The evaluation script automatically uses the appropriate processor:
+
+```bash
+lerobot-eval \
+ --policy.path=lerobot/my_policy \
+ --env.type=myenv \ # Automatically uses MyEnvProcessorStep
+ --eval.n_episodes=10
+```
+
+## Future: Environment Postprocessors
+
+Currently, postprocessors are identity (no-op) for all environments. Future use cases include:
+
+### Action Space Transformations
+
+```python
+@dataclass
+class MyEnvActionPostprocessor(ProcessorStep):
+ """Convert policy actions to environment-specific format."""
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ action = transition["action"]
+
+ # Example: Convert from Cartesian to joint space
+ if self.action_space == "joint":
+ action = self.ik_solver(action)
+
+ # Example: Apply environment-specific safety limits
+ action = torch.clamp(action, self.min_action, self.max_action)
+
+ transition["action"] = action
+ return transition
+```
+
+### Coordinate System Conversions
+
+```python
+@dataclass
+class CoordinateTransformPostprocessor(ProcessorStep):
+ """Transform actions between coordinate systems."""
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ action = transition["action"]
+
+ # Example: Policy outputs in world frame, env expects base frame
+ action = self.world_to_base_transform(action)
+
+ transition["action"] = action
+ return transition
+```
+
+## Best Practices
+
+1. **Keep environment processors simple**: They should only handle environment-specific data format issues, not complex learning-related transformations.
+
+2. **Use policy processors for model requirements**: Normalization, batching, device placement, and tokenization belong in policy processors.
+
+3. **Expose all data from environments**: Let processors decide what to use rather than hardcoding choices in the environment.
+
+4. **Document conventions**: Clearly document any coordinate system conventions, camera orientations, or data formats that your processor handles.
+
+5. **Test independently**: Environment processors should be testable without loading full policies or environments.
+
+## Summary
+
+Environment processors provide a **clean separation** between environment-specific data transformations and policy-specific model requirements. This architecture:
+
+- β Enables easy experimentation with different state representations
+- β Allows policies to work seamlessly across different environments
+- β Keeps environment code focused on simulation/hardware interface
+- β Makes processor pipelines more maintainable and debuggable
+- β Follows the single responsibility principle
+
+The key insight: **Environments define data formats, processors standardize them, policies consume standardized data.** Each layer has a clear, focused responsibility.
diff --git a/lerobot/docs/source/envhub.mdx b/lerobot/docs/source/envhub.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..f19aef6c67ac036a98b65005531976a211864833
--- /dev/null
+++ b/lerobot/docs/source/envhub.mdx
@@ -0,0 +1,431 @@
+# Loading Environments from the Hub
+
+The **EnvHub** feature allows you to load simulation environments directly from the Hugging Face Hub with a single line of code. This unlocks a powerful new model for collaboration: instead of environments being locked away inside monolithic libraries, anyone can publish custom environments and share them with the community.
+
+## What is EnvHub?
+
+EnvHub lets you create custom robotics simulation environments with your own robot models and scenarios, and make them easily usable by anyone through the LeRobot framework.
+
+EnvHub packages are stored on the Hugging Face Hub, and can be seamlessly pulled and used in your AI robotics projects through LeRobot with a single line of code.
+
+Thanks to EnvHub, you can:
+
+1. **Create and publish environments** to the Hugging Face Hub as Git repositories, and distribute complex physics simulations without packaging hassles
+2. **Load environments** dynamically, without installing them as packages
+3. **Version and track** environment changes using Git semantics
+4. **Discover** new simulation tasks shared by the community
+
+This design means you can go from discovering an interesting environment on the Hub to running experiments in seconds, or create your own custom robot and environment without worrying about dependency conflicts or complex installation procedures.
+
+When you create an EnvHub package, you can build anything you want inside it and use any simulation tool you like: this is your own space to play with. The only requirement is that the package contains an `env.py` file that defines the environment and allows LeRobot to load and use your EnvHub package.
+
+This `env.py` file needs to expose a small API so LeRobot can load and run it. In particular, you must provide a `make_env(n_envs: int = 1, use_async_envs: bool = False)` or `make_env(n_envs: int = 1, use_async_envs: bool = False, cfg: EnvConfig)` function, which is the main entry point for LeRobot. It should return one of:
+
+- A `gym.vector.VectorEnv` (most common)
+- A single `gym.Env` (will be automatically wrapped)
+- A dict mapping `{suite_name: {task_id: VectorEnv}}` (for multi-task benchmarks)
+
+You can also pass an `EnvConfig` object to `make_env` to configure the environment (e.g. the number of environments, task, camera name, initial states, control mode, episode length, etc.).
+
+Finally, your environment must implement the standard `gym.vector.VectorEnv` interface so it works with LeRobot, including methods like `reset` and `step`.
+
+## Quick Start
+
+Loading an environment from the Hub is as simple as:
+
+```python
+from lerobot.envs.factory import make_env
+
+# Load a hub environment (requires explicit consent to run remote code)
+env = make_env("lerobot/cartpole-env", trust_remote_code=True)
+```
+
+
+ **Security Notice**: Loading environments from the Hub executes Python code
+ from third-party repositories. Only use `trust_remote_code=True` with
+ repositories you trust. We strongly recommend pinning to a specific commit
+ hash for reproducibility and security.
+
+
+## Repository Structure
+
+To make your environment loadable from the Hub, your repository must contain at minimum:
+
+### Required Files
+
+**`env.py`** (or custom Python file)
+
+- Must expose a `make_env(n_envs: int, use_async_envs: bool)` function
+- This function should return one of:
+ - A `gym.vector.VectorEnv` (most common)
+ - A single `gym.Env` (will be automatically wrapped)
+ - A dict mapping `{suite_name: {task_id: VectorEnv}}` (for multi-task benchmarks)
+
+### Optional Files
+
+**`requirements.txt`**
+
+- List any additional dependencies your environment needs
+- Users will need to install these manually before loading your environment
+
+**`README.md`**
+
+- Document your environment: what task it implements, observation/action spaces, rewards, etc.
+- Include usage examples and any special setup instructions
+
+**`.gitignore`**
+
+- Exclude unnecessary files from your repository
+
+### Example Repository Structure
+
+```
+my-environment-repo/
+βββ env.py # Main environment definition (required)
+βββ requirements.txt # Dependencies (optional)
+βββ README.md # Documentation (recommended)
+βββ assets/ # Images, videos, etc. (optional)
+β βββ demo.gif
+βββ configs/ # Config files if needed (optional)
+ βββ task_config.yaml
+```
+
+## Creating Your Environment Repository
+
+### Step 1: Define Your Environment
+
+Create an `env.py` file with a `make_env` function:
+
+```python
+# env.py
+import gymnasium as gym
+
+def make_env(n_envs: int = 1, use_async_envs: bool = False):
+ """
+ Create vectorized environments for your custom task.
+
+ Args:
+ n_envs: Number of parallel environments
+ use_async_envs: Whether to use AsyncVectorEnv or SyncVectorEnv
+
+ Returns:
+ gym.vector.VectorEnv or dict mapping suite names to vectorized envs
+ """
+ def _make_single_env():
+ # Create your custom environment
+ return gym.make("CartPole-v1")
+
+ # Choose vector environment type
+ env_cls = gym.vector.AsyncVectorEnv if use_async_envs else gym.vector.SyncVectorEnv
+
+ # Create vectorized environment
+ vec_env = env_cls([_make_single_env for _ in range(n_envs)])
+
+ return vec_env
+```
+
+### Step 2: Test Locally
+
+Before uploading, test your environment locally:
+
+```python
+from lerobot.envs.utils import _load_module_from_path, _call_make_env, _normalize_hub_result
+
+# Load your module
+module = _load_module_from_path("./env.py")
+
+# Test the make_env function
+result = _call_make_env(module, n_envs=2, use_async_envs=False)
+normalized = _normalize_hub_result(result)
+
+# Verify it works
+suite_name = next(iter(normalized))
+env = normalized[suite_name][0]
+obs, info = env.reset()
+print(f"Observation shape: {obs.shape if hasattr(obs, 'shape') else type(obs)}")
+env.close()
+```
+
+### Step 3: Upload to the Hub
+
+Upload your repository to Hugging Face:
+
+```bash
+# Install huggingface_hub if needed
+pip install huggingface_hub
+
+# Login to Hugging Face
+huggingface-cli login
+
+# Create a new repository
+huggingface-cli repo create my-custom-env --type space --org my-org
+
+# Initialize git and push
+git init
+git add .
+git commit -m "Initial environment implementation"
+git remote add origin https://huggingface.co/my-org/my-custom-env
+git push -u origin main
+```
+
+Alternatively, use the `huggingface_hub` Python API:
+
+```python
+from huggingface_hub import HfApi
+
+api = HfApi()
+
+# Create repository
+api.create_repo("my-custom-env", repo_type="space")
+
+# Upload files
+api.upload_folder(
+ folder_path="./my-env-folder",
+ repo_id="username/my-custom-env",
+ repo_type="space",
+)
+```
+
+## Loading Environments from the Hub
+
+### Basic Usage
+
+```python
+from lerobot.envs.factory import make_env
+
+# Load from the hub
+envs_dict = make_env(
+ "username/my-custom-env",
+ n_envs=4,
+ trust_remote_code=True
+)
+
+# Access the environment
+suite_name = next(iter(envs_dict))
+env = envs_dict[suite_name][0]
+
+# Use it like any gym environment
+obs, info = env.reset()
+action = env.action_space.sample()
+obs, reward, terminated, truncated, info = env.step(action)
+```
+
+### Advanced: Pinning to Specific Versions
+
+For reproducibility and security, pin to a specific Git revision:
+
+```python
+# Pin to a specific branch
+env = make_env("username/my-env@main", trust_remote_code=True)
+
+# Pin to a specific commit (recommended for papers/experiments)
+env = make_env("username/my-env@abc123def456", trust_remote_code=True)
+
+# Pin to a tag
+env = make_env("username/my-env@v1.0.0", trust_remote_code=True)
+```
+
+### Custom File Paths
+
+If your environment definition is not in `env.py`:
+
+```python
+# Load from a custom file
+env = make_env("username/my-env:custom_env.py", trust_remote_code=True)
+
+# Combine with version pinning
+env = make_env("username/my-env@v1.0:envs/task_a.py", trust_remote_code=True)
+```
+
+### Async Environments
+
+For better performance with multiple environments:
+
+```python
+envs_dict = make_env(
+ "username/my-env",
+ n_envs=8,
+ use_async_envs=True, # Use AsyncVectorEnv for parallel execution
+ trust_remote_code=True
+)
+```
+
+## URL Format Reference
+
+The hub URL format supports several patterns:
+
+| Pattern | Description | Example |
+| -------------------- | ------------------------------ | -------------------------------------- |
+| `user/repo` | Load `env.py` from main branch | `make_env("lerobot/pusht-env")` |
+| `user/repo@revision` | Load from specific revision | `make_env("lerobot/pusht-env@main")` |
+| `user/repo:path` | Load custom file | `make_env("lerobot/envs:pusht.py")` |
+| `user/repo@rev:path` | Revision + custom file | `make_env("lerobot/envs@v1:pusht.py")` |
+
+## Multi-Task Environments
+
+For benchmarks with multiple tasks (like LIBERO), return a nested dictionary:
+
+```python
+def make_env(n_envs: int = 1, use_async_envs: bool = False):
+ env_cls = gym.vector.AsyncVectorEnv if use_async_envs else gym.vector.SyncVectorEnv
+
+ # Return dict: {suite_name: {task_id: VectorEnv}}
+ return {
+ "suite_1": {
+ 0: env_cls([lambda: gym.make("Task1-v0") for _ in range(n_envs)]),
+ 1: env_cls([lambda: gym.make("Task2-v0") for _ in range(n_envs)]),
+ },
+ "suite_2": {
+ 0: env_cls([lambda: gym.make("Task3-v0") for _ in range(n_envs)]),
+ }
+ }
+```
+
+## Security Considerations
+
+
+ **Important**: The `trust_remote_code=True` flag is required to execute
+ environment code from the Hub. This is by design for security.
+
+
+When loading environments from the Hub:
+
+1. **Review the code first**: Visit the repository and inspect `env.py` before loading
+2. **Pin to commits**: Use specific commit hashes for reproducibility
+3. **Check dependencies**: Review `requirements.txt` for suspicious packages
+4. **Use trusted sources**: Prefer official organizations or well-known researchers
+5. **Sandbox if needed**: Run untrusted code in isolated environments (containers, VMs)
+
+Example of safe usage:
+
+```python
+# β BAD: Loading without inspection
+env = make_env("random-user/untrusted-env", trust_remote_code=True)
+
+# β GOOD: Review code, then pin to specific commit
+# 1. Visit https://huggingface.co/trusted-org/verified-env
+# 2. Review the env.py file
+# 3. Copy the commit hash
+env = make_env("trusted-org/verified-env@a1b2c3d4", trust_remote_code=True)
+```
+
+## Example: CartPole from the Hub
+
+Here's a complete example using the reference CartPole environment:
+
+```python
+from lerobot.envs.factory import make_env
+import numpy as np
+
+# Load the environment
+envs_dict = make_env("lerobot/cartpole-env", n_envs=4, trust_remote_code=True)
+
+# Get the vectorized environment
+suite_name = next(iter(envs_dict))
+env = envs_dict[suite_name][0]
+
+# Run a simple episode
+obs, info = env.reset()
+done = np.zeros(env.num_envs, dtype=bool)
+total_reward = np.zeros(env.num_envs)
+
+while not done.all():
+ # Random policy
+ action = env.action_space.sample()
+ obs, reward, terminated, truncated, info = env.step(action)
+ total_reward += reward
+ done = terminated | truncated
+
+print(f"Average reward: {total_reward.mean():.2f}")
+env.close()
+```
+
+## Benefits of EnvHub
+
+### For Environment Authors
+
+- **Easy distribution**: No PyPI packaging required
+- **Version control**: Use Git for environment versioning
+- **Rapid iteration**: Push updates instantly
+- **Documentation**: Hub README renders beautifully
+- **Community**: Reach LeRobot users directly
+
+### For Researchers
+
+- **Quick experiments**: Load any environment in one line
+- **Reproducibility**: Pin to specific commits
+- **Discovery**: Browse environments on the Hub
+- **No conflicts**: No need to install conflicting packages
+
+### For the Community
+
+- **Growing ecosystem**: More diverse simulation tasks
+- **Standardization**: Common `make_env` API
+- **Collaboration**: Fork and improve existing environments
+- **Accessibility**: Lower barrier to sharing research
+
+## Troubleshooting
+
+### "Refusing to execute remote code"
+
+You must explicitly pass `trust_remote_code=True`:
+
+```python
+env = make_env("user/repo", trust_remote_code=True)
+```
+
+### "Module X not found"
+
+The hub environment has dependencies you need to install:
+
+```bash
+# Check the repo's requirements.txt and install dependencies
+pip install gymnasium numpy
+```
+
+### "make_env not found in module"
+
+Your `env.py` must expose a `make_env` function:
+
+```python
+def make_env(n_envs: int, use_async_envs: bool):
+ # Your implementation
+ pass
+```
+
+### Environment returns wrong type
+
+The `make_env` function must return:
+
+- A `gym.vector.VectorEnv`, or
+- A single `gym.Env`, or
+- A dict `{suite_name: {task_id: VectorEnv}}`
+
+## Best Practices
+
+1. **Document your environment**: Include observation/action space descriptions, reward structure, and termination conditions in your README
+2. **Add requirements.txt**: List all dependencies with versions
+3. **Test thoroughly**: Verify your environment works locally before pushing
+4. **Use semantic versioning**: Tag releases with version numbers
+5. **Add examples**: Include usage examples in your README
+6. **Keep it simple**: Minimize dependencies when possible
+7. **License your work**: Add a LICENSE file to clarify usage terms
+
+## Future Directions
+
+The EnvHub ecosystem enables exciting possibilities:
+
+- **GPU-accelerated physics**: Share Isaac Gym or Brax environments
+- **Photorealistic rendering**: Distribute environments with advanced graphics
+- **Multi-agent scenarios**: Complex interaction tasks
+- **Real-world simulators**: Digital twins of physical setups
+- **Procedural generation**: Infinite task variations
+- **Domain randomization**: Pre-configured DR pipelines
+
+As more researchers and developers contribute, the diversity and quality of available environments will grow, benefiting the entire robotics learning community.
+
+## See Also
+
+- [Hugging Face Hub Documentation](https://huggingface.co/docs/hub/en/index)
+- [Gymnasium Documentation](https://gymnasium.farama.org/index.html)
+- [Example Hub Environment](https://huggingface.co/lerobot/cartpole-env)
diff --git a/lerobot/docs/source/envhub_isaaclab_arena.mdx b/lerobot/docs/source/envhub_isaaclab_arena.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..efeec2bd10c65bc6dc9a034208fd9435b7807214
--- /dev/null
+++ b/lerobot/docs/source/envhub_isaaclab_arena.mdx
@@ -0,0 +1,510 @@
+# NVIDIA IsaacLab Arena & LeRobot
+
+LeRobot EnvHub now supports **GPU-accelerated simulation** with IsaacLab Arena for policy evaluation at scale.
+Train and evaluate imitation learning policies with high-fidelity simulation β all integrated into the LeRobot ecosystem.
+
+
+
+[IsaacLab Arena](https://github.com/isaac-sim/IsaacLab-Arena) integrates with NVIDIA IsaacLab to provide:
+
+- π€ **Humanoid embodiments**: GR1, G1, Galileo with various configurations
+- π― **Manipulation & loco-manipulation tasks**: Door opening, pick-and-place, button pressing, and more
+- β‘ **GPU-accelerated rollouts**: Parallel environment execution on NVIDIA GPUs
+- πΌοΈ **RTX Rendering**: Evaluate vision-based policies with realistic rendering, reflections and refractions
+- π¦ **LeRobot-compatible datasets**: Ready for training with GR00T N1x, PI0, SmolVLA, ACT, and Diffusion policies
+- π **EnvHub integration**: Load environments from HuggingFace EnvHub with one line
+
+## Installation
+
+### Prerequisites
+
+Hardware requirements are shared with Isaac Sim, and are detailed in [Isaac Sim Requirements](https://docs.isaacsim.omniverse.nvidia.com/5.1.0/installation/requirements.html).
+
+- NVIDIA GPU with CUDA support
+- NVIDIA driver compatible with IsaacSim 5.1.0
+- Linux (Ubuntu 22.04 / 24.04)
+
+### Setup
+
+```bash
+# 1. Create conda environment
+conda create -y -n lerobot-arena python=3.11
+conda activate lerobot-arena
+conda install -y -c conda-forge ffmpeg=7.1.1
+
+# 2. Install Isaac Sim 5.1.0
+pip install "isaacsim[all,extscache]==5.1.0" --extra-index-url https://pypi.nvidia.com
+
+# Accept NVIDIA EULA (required)
+export ACCEPT_EULA=Y
+export PRIVACY_CONSENT=Y
+
+# 3. Install IsaacLab 2.3.0
+git clone https://github.com/isaac-sim/IsaacLab.git
+cd IsaacLab
+git checkout v2.3.0
+./isaaclab.sh -i
+cd ..
+
+# 4. Install IsaacLab Arena
+git clone https://github.com/isaac-sim/IsaacLab-Arena.git
+cd IsaacLab-Arena
+git checkout release/0.1.1
+pip install -e .
+cd ..
+
+
+# 5. Install LeRobot
+git clone https://github.com/huggingface/lerobot.git
+cd lerobot
+pip install -e .
+cd ..
+
+
+# 6. Install additional dependencies
+pip install onnxruntime==1.23.2 lightwheel-sdk==1.0.1 vuer[all]==0.0.70 qpsolvers==4.8.1
+pip install numpy==1.26.0 # Isaac Sim 5.1 depends on numpy==1.26.0, this will be fixed in next release
+```
+
+## Evaluating Policies
+
+### Pre-trained Policies
+
+The following trained policies are available:
+
+| Policy | Architecture | Task | Link |
+| :-------------------------- | :----------- | :------------ | :----------------------------------------------------------------------- |
+| pi05-arena-gr1-microwave | PI0.5 | GR1 Microwave | [HuggingFace](https://huggingface.co/nvidia/pi05-arena-gr1-microwave) |
+| smolvla-arena-gr1-microwave | SmolVLA | GR1 Microwave | [HuggingFace](https://huggingface.co/nvidia/smolvla-arena-gr1-microwave) |
+
+### Evaluate SmolVLA
+
+```bash
+pip install -e ".[smolvla]"
+pip install numpy==1.26.0 # revert numpy to version 1.26
+```
+
+```bash
+lerobot-eval \
+ --policy.path=nvidia/smolvla-arena-gr1-microwave \
+ --env.type=isaaclab_arena \
+ --env.hub_path=nvidia/isaaclab-arena-envs \
+ --rename_map='{"observation.images.robot_pov_cam_rgb": "observation.images.robot_pov_cam"}' \
+ --policy.device=cuda \
+ --env.environment=gr1_microwave \
+ --env.embodiment=gr1_pink \
+ --env.object=mustard_bottle \
+ --env.headless=false \
+ --env.enable_cameras=true \
+ --env.video=true \
+ --env.video_length=10 \
+ --env.video_interval=15 \
+ --env.state_keys=robot_joint_pos \
+ --env.camera_keys=robot_pov_cam_rgb \
+ --trust_remote_code=True \
+ --eval.batch_size=1
+```
+
+### Evaluate PI0.5
+
+```bash
+pip install -e ".[pi]"
+pip install numpy==1.26.0 # revert numpy to version 1.26
+```
+
+PI0.5 requires disabling torch compile for evaluation:
+
+```bash
+TORCH_COMPILE_DISABLE=1 TORCHINDUCTOR_DISABLE=1 lerobot-eval \
+ --policy.path=nvidia/pi05-arena-gr1-microwave \
+ --env.type=isaaclab_arena \
+ --env.hub_path=nvidia/isaaclab-arena-envs \
+ --rename_map='{"observation.images.robot_pov_cam_rgb": "observation.images.robot_pov_cam"}' \
+ --policy.device=cuda \
+ --env.environment=gr1_microwave \
+ --env.embodiment=gr1_pink \
+ --env.object=mustard_bottle \
+ --env.headless=false \
+ --env.enable_cameras=true \
+ --env.video=true \
+ --env.video_length=15 \
+ --env.video_interval=15 \
+ --env.state_keys=robot_joint_pos \
+ --env.camera_keys=robot_pov_cam_rgb \
+ --trust_remote_code=True \
+ --eval.batch_size=1
+```
+
+
+ To change the number of parallel environments, use the ```--eval.batch_size```
+ flag.
+
+
+### What to Expect
+
+During evaluation, you will see a progress bar showing the running success rate:
+
+```
+Stepping through eval batches: 8%|βββββββ | 4/50 [00:45<08:06, 10.58s/it, running_success_rate=25.0%]
+```
+
+### Video Recording
+
+To enable video recording during evaluation, add the following flags to your command:
+
+```bash
+--env.video=true \
+--env.video_length=15 \
+--env.video_interval=15
+```
+
+For more details on video recording, see the [IsaacLab Recording Documentation](https://isaac-sim.github.io/IsaacLab/main/source/how-to/record_video.html).
+
+
+When running headless with `--env.headless=true`, you must also enable cameras explicitly for camera enabled environments:
+
+```bash
+--env.headless=true --env.enable_cameras=true
+```
+
+
+
+### Output Directory
+
+Evaluation videos are saved to the output directory with the following structure:
+
+```
+outputs/eval//__/videos/_/eval_episode_.mp4
+```
+
+For example:
+
+```
+outputs/eval/2026-01-02/14-38-01_isaaclab_arena_smolvla/videos/gr1_microwave_0/eval_episode_0.mp4
+```
+
+## Training Policies
+
+To learn more about training policies with LeRobot, please refer to the training documentation:
+
+- [SmolVLA](./smolvla)
+- [Pi0.5](./pi05)
+- [GR00T N1.5](./groot)
+
+Sample IsaacLab Arena datasets are available on HuggingFace Hub for experimentation:
+
+| Dataset | Description | Frames |
+| :-------------------------------------------------------------------------------------------------------- | :------------------------- | :----- |
+| [Arena-GR1-Manipulation-Task](https://huggingface.co/datasets/nvidia/Arena-GR1-Manipulation-Task-v3) | GR1 microwave manipulation | ~4K |
+| [Arena-G1-Loco-Manipulation-Task](https://huggingface.co/datasets/nvidia/Arena-G1-Loco-Manipulation-Task) | G1 loco-manipulation | ~4K |
+
+## Environment Configuration
+
+### Full Configuration Options
+
+```python
+from lerobot.envs.configs import IsaaclabArenaEnv
+
+config = IsaaclabArenaEnv(
+ # Environment selection
+ environment="gr1_microwave", # Task environment
+ embodiment="gr1_pink", # Robot embodiment
+ object="power_drill", # Object to manipulate
+
+ # Simulation settings
+ episode_length=300, # Max steps per episode
+ headless=True, # Run without GUI
+ device="cuda:0", # GPU device
+ seed=42, # Random seed
+
+ # Observation configuration
+ state_keys="robot_joint_pos", # State observation keys (comma-separated)
+ camera_keys="robot_pov_cam_rgb", # Camera observation keys (comma-separated)
+ state_dim=54, # Expected state dimension
+ action_dim=36, # Expected action dimension
+ camera_height=512, # Camera image height
+ camera_width=512, # Camera image width
+ enable_cameras=True, # Enable camera observations
+
+ # Video recording
+ video=False, # Enable video recording
+ video_length=100, # Frames per video
+ video_interval=200, # Steps between recordings
+
+ # Advanced
+ mimic=False, # Enable mimic mode
+ teleop_device=None, # Teleoperation device
+ disable_fabric=False, # Disable fabric optimization
+ enable_pinocchio=True, # Enable Pinocchio for IK
+)
+```
+
+### Using Environment Hub directly for advanced usage
+
+Create a file called `test_env_load_arena.py` or [download from the EnvHub](https://huggingface.co/nvidia/isaaclab-arena-envs/blob/main/tests/test_env_load_arena.py):
+
+```python
+import logging
+from dataclasses import asdict
+from pprint import pformat
+import torch
+import tqdm
+from lerobot.configs import parser
+from lerobot.configs.eval import EvalPipelineConfig
+
+
+@parser.wrap()
+def main(cfg: EvalPipelineConfig):
+ """Run random action rollout for IsaacLab Arena environment."""
+ logging.info(pformat(asdict(cfg)))
+
+ from lerobot.envs.factory import make_env
+
+ env_dict = make_env(
+ cfg.env,
+ n_envs=cfg.env.num_envs,
+ trust_remote_code=True,
+ )
+ env = next(iter(env_dict.values()))[0]
+ env.reset()
+ for _ in tqdm.tqdm(range(cfg.env.episode_length)):
+ with torch.inference_mode():
+ actions = env.action_space.sample()
+ obs, rewards, terminated, truncated, info = env.step(actions)
+ if terminated.any() or truncated.any():
+ obs, info = env.reset()
+ env.close()
+
+
+if __name__ == "__main__":
+ main()
+```
+
+Run with:
+
+```bash
+python test_env_load_arena.py \
+ --env.environment=g1_locomanip_pnp \
+ --env.embodiment=gr1_pink \
+ --env.object=cracker_box \
+ --env.num_envs=4 \
+ --env.enable_cameras=true \
+ --env.seed=1000 \
+ --env.video=true \
+ --env.video_length=10 \
+ --env.video_interval=15 \
+ --env.headless=false \
+ --env.hub_path=nvidia/isaaclab-arena-envs \
+ --env.type=isaaclab_arena
+```
+
+## Creating New Environments
+
+First create a new IsaacLab Arena environment by following the [IsaacLab Arena Documentation](https://isaac-sim.github.io/IsaacLab-Arena/release/0.1.1/index.html).
+
+Clone our EnvHub repo:
+
+```bash
+git clone https://huggingface.co/nvidia/isaaclab-arena-envs
+```
+
+Modify the `example_envs.yaml` file based on your new environment.
+[Upload](./envhub#step-3-upload-to-the-hub) your modified repo to HuggingFace EnvHub.
+
+
+ Your IsaacLab Arena environment code must be locally available during
+ evaluation. Users can clone your environment repository separately, or you can
+ bundle the environment code and assets directly in your EnvHub repo.
+
+
+Then, when evaluating, use your new environment:
+
+```bash
+lerobot-eval \
+ --env.hub_path=/isaaclab-arena-envs \
+ --env.environment= \
+ ...other flags...
+```
+
+We look forward to your contributions!
+
+## Troubleshooting
+
+### CUDA out of memory
+
+Reduce `batch_size` or use a GPU with more VRAM:
+
+```bash
+--eval.batch_size=1
+```
+
+### EULA not accepted
+
+Set environment variables before running:
+
+```bash
+export ACCEPT_EULA=Y
+export PRIVACY_CONSENT=Y
+```
+
+### Video recording not working
+
+Enable cameras when running headless:
+
+```bash
+--env.video=true --env.enable_cameras=true --env.headless=true
+```
+
+### Policy output dimension mismatch
+
+Ensure `action_dim` matches your policy:
+
+```bash
+--env.action_dim=36
+```
+
+### libGLU.so.1 Errors during Isaac Sim initialization
+
+Ensure you have the following dependencies installed, this is likely to happen on headless machines.
+
+```bash
+sudo apt update && sudo apt install -y libglu1-mesa libxt6
+```
+
+## See Also
+
+- [EnvHub Documentation](./envhub.mdx) - General EnvHub usage
+- [IsaacLab Arena GitHub](https://github.com/isaac-sim/IsaacLab-Arena)
+- [IsaacLab Documentation](https://isaac-sim.github.io/IsaacLab/)
+
+## Lightwheel LW-BenchHub
+
+[Lightwheel](https://www.lightwheel.ai) is bringing `Lightwheel-Libero-Tasks` and `Lightwheel-RoboCasa-Tasks` with 268 tasks to the LeRobot ecosystem.
+LW-BenchHub collects and generates large-scale datasets via teleoperation that comply with the LeRobot specification, enabling out-of-the-box training and evaluation workflows.
+With the unified interface provided by EnvHub, developers can quickly build end-to-end experimental pipelines.
+
+### Install
+
+Assuming you followed the [Installation](#installation) steps, you can install LW-BenchHub with:
+
+```bash
+conda install pinocchio -c conda-forge -y
+pip install numpy==1.26.0 # revert numpy to version 1.26
+
+sudo apt-get install git-lfs && git lfs install
+
+git clone https://github.com/LightwheelAI/lw_benchhub
+git lfs pull # Ensure LFS files (e.g., .usd assets) are downloaded
+
+cd lw_benchhub
+pip install -e .
+```
+
+For more detailed instructions, please refer to the [LW-BenchHub Documentation](https://docs.lightwheel.net/lw_benchhub/usage/Installation).
+
+### Lightwheel Tasks Dataset
+
+LW-BenchHub datasets are available on HuggingFace Hub:
+
+| Dataset | Description | Tasks | Frames |
+| :------------------------------------------------------------------------------------------------------------ | :---------------------- | :---- | :----- |
+| [Lightwheel-Tasks-X7S](https://huggingface.co/datasets/LightwheelAI/Lightwheel-Tasks-X7S) | X7S LIBERO and RoboCasa | 117 | ~10.3M |
+| [Lightwheel-Tasks-Double-Piper](https://huggingface.co/datasets/LightwheelAI/Lightwheel-Tasks-Double-Piper) | Double-Piper LIBERO | 130 | ~6.0M |
+| [Lightwheel-Tasks-G1-Controller](https://huggingface.co/datasets/LightwheelAI/Lightwheel-Tasks-G1-Controller) | G1-Controller LIBERO | 62 | ~2.7M |
+| [Lightwheel-Tasks-G1-WBC](https://huggingface.co/datasets/LightwheelAI/Lightwheel-Tasks-G1-WBC) | G1-WBC RoboCasa | 32 | ~1.5M |
+
+For training policies, refer to the [Training Policies](#training-policies) section.
+
+### Evaluating Policies
+
+#### Pre-trained Policies
+
+The following trained policies are available:
+
+| Policy | Architecture | Task | Layout | Robot | Link |
+| :----------------------- | :----------- | :----------------------------- | :--------- | :-------------- | :------------------------------------------------------------------------------------ |
+| smolvla-double-piper-pnp | SmolVLA | L90K1PutTheBlackBowlOnThePlate | libero-1-1 | DoublePiper-Abs | [HuggingFace](https://huggingface.co/LightwheelAI/smolvla-double-piper-pnp/tree/main) |
+
+#### Evaluate SmolVLA
+
+```bash
+lerobot-eval \
+ --policy.path=LightwheelAI/smolvla-double-piper-pnp \
+ --env.type=isaaclab_arena \
+ --rename_map='{"observation.images.left_hand_camera_rgb": "observation.images.left_hand", "observation.images.right_hand_camera_rgb": "observation.images.right_hand", "observation.images.first_person_camera_rgb": "observation.images.first_person"}' \
+ --env.hub_path=LightwheelAI/lw_benchhub_env \
+ --env.kwargs='{"config_path": "configs/envhub/example.yml"}' \
+ --trust_remote_code=true \
+ --env.state_keys=joint_pos \
+ --env.action_dim=12 \
+ --env.camera_keys=left_hand_camera_rgb,right_hand_camera_rgb,first_person_camera_rgb \
+ --policy.device=cuda \
+ --eval.batch_size=10 \
+ --eval.n_episodes=100
+```
+
+### Environment Configuration
+
+Evaluation can be quickly launched by modifying the `robot`, `task`, and `layout` settings in the configuration file.
+
+#### Full Configuration Options
+
+```yml
+# =========================
+# Basic Settings
+# =========================
+disable_fabric: false
+device: cuda:0
+sensitivity: 1.0
+step_hz: 50
+enable_cameras: true
+execute_mode: eval
+episode_length_s: 20.0 # Episode length in seconds, increase if episodes timeout during eval
+
+# =========================
+# Robot Settings
+# =========================
+robot: DoublePiper-Abs # Robot type, DoublePiper-Abs, X7S-Abs, G1-Controller or G1-Controller-DecoupledWBC
+robot_scale: 1.0
+
+# =========================
+# Task & Scene Settings
+# =========================
+task: L90K1PutTheBlackBowlOnThePlate # Task name
+scene_backend: robocasa
+task_backend: robocasa
+debug_assets: null
+layout: libero-1-1 # Layout and style ID
+sources:
+ - objaverse
+ - lightwheel
+ - aigen_objs
+object_projects: []
+usd_simplify: false
+seed: 42
+
+# =========================
+# Object Placement Retry Settings
+# =========================
+max_scene_retry: 4
+max_object_placement_retry: 3
+
+resample_objects_placement_on_reset: true
+resample_robot_placement_on_reset: true
+
+# =========================
+# Replay Configuration Settings
+# =========================
+replay_cfgs:
+ add_camera_to_observation: true
+ render_resolution: [640, 480]
+```
+
+### See Also
+
+- [LW-BenchHub GitHub](https://github.com/LightwheelAI/LW-BenchHub)
+- [LW-BenchHub Documentation](https://docs.lightwheel.net/lw_benchhub/)
diff --git a/lerobot/docs/source/envhub_leisaac.mdx b/lerobot/docs/source/envhub_leisaac.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..f2c6f79d570f1d1f474cf9db4b9930057d75627b
--- /dev/null
+++ b/lerobot/docs/source/envhub_leisaac.mdx
@@ -0,0 +1,302 @@
+# LeIsaac Γ LeRobot EnvHub
+
+LeRobot EnvHub now supports **imitation learning in simulation** with LeIsaac.
+Spin up everyday manipulation tasks, teleoperate the robot, collect demos, push them to the Hub, and train policies in LeRobot β all in one loop.
+
+[LeIsaac](https://github.com/LightwheelAI/leisaac) integrates with IsaacLab and the SO101 Leader/Follower setup to provide:
+
+- πΉοΈ **Teleoperation-first workflows** for data collection
+- π¦ **Built-in data conversion** ready for LeRobot training
+- π€ **Everyday skills** like picking oranges, lifting cubes, cleaning tables, and folding cloth
+- βοΈ **Ongoing upgrades** from [LightWheel](https://lightwheel.ai/): cloud simulation, EnvHub support, Sim2Real tooling, and more
+
+Below youβll find the currently supported LeIsaac tasks exposed through LeRobot EnvHub.
+
+# Available Environments
+
+The following table lists all available tasks and environments in LeIsaac x LeRobot Envhub. You can also get the latest list of environments by running the following command:
+
+```bash
+python scripts/environments/list_envs.py
+```
+
+| Task | Environment ID | Task Description | Related Robot |
+| :-------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------- |
+| | [LeIsaac-SO101-PickOrange-v0](https://github.com/LightwheelAI/leisaac/blob/main/source/leisaac/leisaac/tasks/pick_orange/pick_orange_env_cfg.py)
[LeIsaac-SO101-PickOrange-Direct-v0](https://github.com/LightwheelAI/leisaac/blob/main/source/leisaac/leisaac/tasks/pick_orange/direct/pick_orange_env.py) | Pick three oranges and put them into the plate, then reset the arm to rest state. | Single-Arm SO101 Follower |
+| | [LeIsaac-SO101-LiftCube-v0](https://github.com/LightwheelAI/leisaac/blob/main/source/leisaac/leisaac/tasks/lift_cube/lift_cube_env_cfg.py)
[LeIsaac-SO101-LiftCube-Direct-v0](https://github.com/LightwheelAI/leisaac/blob/main/source/leisaac/leisaac/tasks/lift_cube/direct/lift_cube_env.py) | Lift the red cube up. | Single-Arm SO101 Follower |
+| | [LeIsaac-SO101-CleanToyTable-v0](https://github.com/LightwheelAI/leisaac/blob/main/source/leisaac/leisaac/tasks/clean_toy_table/clean_toy_table_env_cfg.py)
[LeIsaac-SO101-CleanToyTable-BiArm-Direct-v0](https://github.com/LightwheelAI/leisaac/blob/main/source/leisaac/leisaac/tasks/clean_toy_table/direct/clean_toy_table_bi_arm_env.py) | Pick two letter e objects into the box, and reset the arm to rest state. | Single-Arm SO101 Follower
[LeIsaac-SO101-FoldCloth-BiArm-Direct-v0](https://github.com/LightwheelAI/leisaac/blob/main/source/leisaac/leisaac/tasks/fold_cloth/direct/fold_cloth_bi_arm_env.py) | Fold the cloth, and reset the arm to rest state.
_Note: Only the DirectEnv support check_success in this task._ | Bi-Arm SO101 Follower |
+
+# Load LeIsaac directly in LeRobot with one line of code
+
+> EnvHub: Share LeIsaac environments through HuggingFace
+
+[EnvHub](https://huggingface.co/docs/lerobot/envhub) is our reproducible environment hub, spin up a packaged simulation with one line, experiment immediately, and publish your own tasks for the community.
+
+LeIsaac offers EnvHub support so you can consume or share tasks with only a few commands.
+
+
+
+## How to get started, environment Setup
+
+Run the following commands to setup your code environments:
+
+```bash
+# Refer to Getting Started/Installation to install leisaac firstly
+conda create -n leisaac_envhub python=3.11
+conda activate leisaac_envhub
+
+conda install -c "nvidia/label/cuda-12.8.1" cuda-toolkit
+pip install -U torch==2.7.0 torchvision==0.22.0 --index-url https://download.pytorch.org/whl/cu128
+pip install 'leisaac[isaaclab] @ git+https://github.com/LightwheelAI/leisaac.git#subdirectory=source/leisaac' --extra-index-url https://pypi.nvidia.com
+
+# Install lerobot
+pip install lerobot==0.4.1
+
+# Fix numpy version
+pip install numpy==1.26.0
+```
+
+## Usage Example
+
+EnvHub exposes every LeIsaac-supported task in a uniform interface. The examples below load `so101_pick_orange` and demonstrate a random-action rollout and an interactive teleoperation.
+
+### Random Action
+
+
+Click to expand code example
+
+```python
+# envhub_random_action.py
+
+import torch
+from lerobot.envs.factory import make_env
+
+# Load from the hub
+envs_dict = make_env("LightwheelAI/leisaac_env:envs/so101_pick_orange.py", n_envs=1, trust_remote_code=True)
+
+# Access the environment
+suite_name = next(iter(envs_dict))
+sync_vector_env = envs_dict[suite_name][0]
+# retrieve the isaac environment from the sync vector env
+env = sync_vector_env.envs[0].unwrapped
+
+# Use it like any gym environment
+obs, info = env.reset()
+
+while True:
+ action = torch.tensor(env.action_space.sample())
+ obs, reward, terminated, truncated, info = env.step(action)
+ if terminated or truncated:
+ obs, info = env.reset()
+
+env.close()
+```
+
+
+
+```bash
+python envhub_random_action.py
+```
+
+You should see the SO101 arm swinging under purely random commands.
+
+### Teleoperation
+
+LeRobotβs teleoperation stack can drive the simulated arm.
+
+Connect the SO101 Leader controller, run the calibration command below.
+
+```bash
+lerobot-calibrate \
+ --teleop.type=so101_leader \
+ --teleop.port=/dev/ttyACM0 \
+ --teleop.id=leader
+```
+
+And then launch the teleop script.
+
+
+Click to expand code example
+
+```python
+# envhub_teleop_example.py
+
+import logging
+import time
+import gymnasium as gym
+
+from dataclasses import asdict, dataclass
+from pprint import pformat
+
+from lerobot.teleoperators import ( # noqa: F401
+ Teleoperator,
+ TeleoperatorConfig,
+ make_teleoperator_from_config,
+ so_leader,
+ bi_so_leader,
+)
+from lerobot.utils.robot_utils import precise_sleep
+from lerobot.utils.utils import init_logging
+from lerobot.envs.factory import make_env
+
+
+@dataclass
+class TeleoperateConfig:
+ teleop: TeleoperatorConfig
+ env_name: str = "so101_pick_orange"
+ fps: int = 60
+
+
+@dataclass
+class EnvWrap:
+ env: gym.Env
+
+
+def make_env_from_leisaac(env_name: str = "so101_pick_orange"):
+ envs_dict = make_env(
+ f'LightwheelAI/leisaac_env:envs/{env_name}.py',
+ n_envs=1,
+ trust_remote_code=True
+ )
+ suite_name = next(iter(envs_dict))
+ sync_vector_env = envs_dict[suite_name][0]
+ env = sync_vector_env.envs[0].unwrapped
+
+ return env
+
+
+def teleop_loop(teleop: Teleoperator, env: gym.Env, fps: int):
+ from leisaac.devices.action_process import preprocess_device_action
+ from leisaac.assets.robots.lerobot import SO101_FOLLOWER_MOTOR_LIMITS
+ from leisaac.utils.env_utils import dynamic_reset_gripper_effort_limit_sim
+
+ env_wrap = EnvWrap(env=env)
+
+ obs, info = env.reset()
+ while True:
+ loop_start = time.perf_counter()
+ if env.cfg.dynamic_reset_gripper_effort_limit:
+ dynamic_reset_gripper_effort_limit_sim(env, 'so101leader')
+
+ raw_action = teleop.get_action()
+ processed_action = preprocess_device_action(
+ dict(
+ so101_leader=True,
+ joint_state={
+ k.removesuffix(".pos"): v for k, v in raw_action.items()},
+ motor_limits=SO101_FOLLOWER_MOTOR_LIMITS),
+ env_wrap
+ )
+ obs, reward, terminated, truncated, info = env.step(processed_action)
+ if terminated or truncated:
+ obs, info = env.reset()
+
+ dt_s = time.perf_counter() - loop_start
+ precise_sleep(max(1 / fps - dt_s, 0.0))
+ loop_s = time.perf_counter() - loop_start
+ print(f"\ntime: {loop_s * 1e3:.2f}ms ({1 / loop_s:.0f} Hz)")
+
+
+def teleoperate(cfg: TeleoperateConfig):
+ init_logging()
+ logging.info(pformat(asdict(cfg)))
+
+ teleop = make_teleoperator_from_config(cfg.teleop)
+ env = make_env_from_leisaac(cfg.env_name)
+
+ teleop.connect()
+ if hasattr(env, 'initialize'):
+ env.initialize()
+ try:
+ teleop_loop(teleop=teleop, env=env, fps=cfg.fps)
+ except KeyboardInterrupt:
+ pass
+ finally:
+ teleop.disconnect()
+ env.close()
+
+
+def main():
+ teleoperate(TeleoperateConfig(
+ teleop=so_leader.SO101LeaderConfig(
+ port="/dev/ttyACM0",
+ id='leader',
+ use_degrees=False,
+ ),
+ env_name="so101_pick_orange",
+ fps=60,
+ ))
+
+
+if __name__ == "__main__":
+ main()
+
+```
+
+
+
+```bash
+python envhub_teleop_example.py
+```
+
+Running the script lets you operate the simulated arm using the physical Leader device.
+
+## βοΈ Cloud Simulation (No GPU Required)
+
+Donβt have a local GPU or the right drivers? No problem! You can run LeIsaac entirely in the cloud with zero setup.
+LeIsaac works out-of-the-box on **NVIDIA Brev**, giving you a fully configured environment directly in your browser.
+
+π **Start here:** [https://lightwheelai.github.io/leisaac/docs/cloud_simulation/nvidia_brev](https://lightwheelai.github.io/leisaac/docs/cloud_simulation/nvidia_brev)
+
+Once your instance is deployed, simply open the link for **port 80 (HTTP)** to launch **Visual Studio Code Server** (default password: `password`). From there, you can run simulations, edit code, and visualize IsaacLab environments β all from your web browser.
+
+**No GPU, no drivers, no local installation. Just click and run.**
+
+## Additional Notes
+
+We keep EnvHub coverage aligned with the LeIsaac task. Currently supported:
+
+- `so101_pick_orange`
+- `so101_lift_cube`
+- `so101_clean_toytable`
+- `bi_so101_fold_cloth`
+
+Switch tasks by targeting a different script when calling `make_env`, for example:
+
+```python
+envs_dict_pick_orange = make_env("LightwheelAI/leisaac_env:envs/so101_pick_orange.py", n_envs=1, trust_remote_code=True)
+envs_dict_lift_cube = make_env("LightwheelAI/leisaac_env:envs/so101_lift_cube.py", n_envs=1, trust_remote_code=True)
+envs_dict_clean_toytable = make_env("LightwheelAI/leisaac_env:envs/so101_clean_toytable.py", n_envs=1, trust_remote_code=True)
+envs_dict_fold_cloth = make_env("LightwheelAI/leisaac_env:envs/bi_so101_fold_cloth.py", n_envs=1, trust_remote_code=True)
+```
+
+Note: when working with `bi_so101_fold_cloth`, call `initialize()` immediately after retrieving the env before performing any other operations:
+
+
+Click to expand code example
+
+```python
+import torch
+from lerobot.envs.factory import make_env
+
+# Load from the hub
+envs_dict = make_env("LightwheelAI/leisaac_env:envs/bi_so101_fold_cloth.py", n_envs=1, trust_remote_code=True)
+
+# Access the environment
+suite_name = next(iter(envs_dict))
+sync_vector_env = envs_dict[suite_name][0]
+# retrieve the isaac environment from the sync vector env
+env = sync_vector_env.envs[0].unwrapped
+
+# NOTE: initialize() first
+env.initialize()
+
+# other operation with env...
+```
+
+
diff --git a/lerobot/docs/source/feetech.mdx b/lerobot/docs/source/feetech.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..777f8a5093521a93470a1e6a5356c443f45fb0d8
--- /dev/null
+++ b/lerobot/docs/source/feetech.mdx
@@ -0,0 +1,71 @@
+# Feetech Motor Firmware Update
+
+This tutorial guides you through updating the firmware of Feetech motors using the official Feetech software.
+
+## Prerequisites
+
+- Windows computer (Feetech software is only available for Windows)
+- Feetech motor control board
+- USB cable to connect the control board to your computer
+- Feetech motors connected to the control board
+
+## Step 1: Download Feetech Software
+
+1. Visit the official Feetech software download page: [https://www.feetechrc.com/software.html](https://www.feetechrc.com/software.html)
+2. Download the latest version of the Feetech debugging software (FD)
+3. Install the software on your Windows computer
+
+## Step 2: Hardware Setup
+
+1. Connect your Feetech motors to the motor control board
+2. Connect the motor control board to your Windows computer via USB cable
+3. Ensure power is supplied to the motors
+
+## Step 3: Configure Connection
+
+1. Launch the Feetech debugging software
+2. Select the correct COM port from the port dropdown menu
+ - If unsure which port to use, check Windows Device Manager under "Ports (COM & LPT)"
+3. Set the appropriate baud rate (typically 1000000 for most Feetech motors)
+4. Click "Open" to establish communication with the control board
+
+## Step 4: Scan for Motors
+
+1. Once connected, click the "Search" button to detect all connected motors
+2. The software will automatically discover and list all motors on the bus
+3. Each motor will appear with its ID number
+
+## Step 5: Update Firmware
+
+For each motor you want to update:
+
+1. **Select the motor** from the list by clicking on it
+2. **Click on Upgrade tab**:
+3. **Click on Online button**:
+ - If an potential firmware update is found, it will be displayed in the box
+4. **Click on Upgrade button**:
+ - The update progress will be displayed
+
+## Step 6: Verify Update
+
+1. After the update completes, the software should automatically refresh the motor information
+2. Verify that the firmware version has been updated to the expected version
+
+## Important Notes
+
+β οΈ **Warning**: Do not disconnect power or USB during firmware updates, it will potentially brick the motor.
+
+## Bonus: Motor Debugging on Linux/macOS
+
+For debugging purposes only, you can use the open-source Feetech Debug Tool:
+
+- **Repository**: [FT_SCServo_Debug_Qt](https://github.com/CarolinePascal/FT_SCServo_Debug_Qt/tree/fix/port-search-timer)
+
+### Installation Instructions
+
+Follow the instructions in the repository to install the tool, for Ubuntu you can directly install it, for MacOS you need to build it from source.
+
+**Limitations:**
+
+- This tool is for debugging and parameter adjustment only
+- Firmware updates must still be done on Windows with official Feetech software
diff --git a/lerobot/docs/source/groot.mdx b/lerobot/docs/source/groot.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..5022b50b85ef21a55efbcc98b19bf5fac81e73c2
--- /dev/null
+++ b/lerobot/docs/source/groot.mdx
@@ -0,0 +1,131 @@
+# GR00T N1.5 Policy
+
+GR00T N1.5 is an open foundation model from NVIDIA designed for generalized humanoid robot reasoning and skills. It is a cross-embodiment model that accepts multimodal input, including language and images, to perform manipulation tasks in diverse environments.
+
+This document outlines the specifics of its integration and usage within the LeRobot framework.
+
+## Model Overview
+
+NVIDIA Isaac GR00T N1.5 is an upgraded version of the GR00T N1 foundation model. It is built to improve generalization and language-following abilities for humanoid robots.
+
+Developers and researchers can post-train GR00T N1.5 with their own real or synthetic data to adapt it for specific humanoid robots or tasks.
+
+GR00T N1.5 (specifically the GR00T-N1.5-3B model) is built using pre-trained vision and language encoders. It utilizes a flow matching action transformer to model a chunk of actions, conditioned on vision, language, and proprioception.
+
+
+
+Its strong performance comes from being trained on an expansive and diverse humanoid dataset, which includes:
+
+- Real captured data from robots.
+- Synthetic data generated using NVIDIA Isaac GR00T Blueprint.
+- Internet-scale video data.
+
+This approach allows the model to be highly adaptable through post-training for specific embodiments, tasks, and environments.
+
+## Installation Requirements
+
+As of today, GR00T N1.5 requires flash attention for it's internal working.
+
+We are working on making this optional, but in the meantime that means that we require an extra installation step and it can only be used in CUDA enabled devices.
+
+1. Following the Environment Setup of our [Installation Guide](./installation). **Attention** don't install `lerobot` in this step.
+2. Install [Flash Attention](https://github.com/Dao-AILab/flash-attention) by running:
+
+```bash
+# Check https://pytorch.org/get-started/locally/ for your system
+pip install "torch>=2.2.1,<2.8.0" "torchvision>=0.21.0,<0.23.0" # --index-url https://download.pytorch.org/whl/cu1XX
+pip install ninja "packaging>=24.2,<26.0" # flash attention dependencies
+pip install "flash-attn>=2.5.9,<3.0.0" --no-build-isolation
+python -c "import flash_attn; print(f'Flash Attention {flash_attn.__version__} imported successfully')"
+```
+
+3. Install LeRobot by running:
+
+```bash
+pip install lerobot[groot]
+```
+
+## Usage
+
+To use GR00T in your LeRobot configuration, specify the policy type as:
+
+```python
+policy.type=groot
+```
+
+## Training
+
+### Training Command Example
+
+Here's a complete training command for finetuning the base GR00T model on your own dataset:
+
+```bash
+# Using a multi-GPU setup
+accelerate launch \
+ --multi_gpu \
+ --num_processes=$NUM_GPUS \
+ $(which lerobot-train) \
+ --output_dir=$OUTPUT_DIR \
+ --save_checkpoint=true \
+ --batch_size=$BATCH_SIZE \
+ --steps=$NUM_STEPS \
+ --save_freq=$SAVE_FREQ \
+ --log_freq=$LOG_FREQ \
+ --policy.push_to_hub=true \
+ --policy.type=groot \
+ --policy.repo_id=$REPO_ID \
+ --policy.tune_diffusion_model=false \
+ --dataset.repo_id=$DATASET_ID \
+ --wandb.enable=true \
+ --wandb.disable_artifact=true \
+ --job_name=$JOB_NAME
+```
+
+## Performance Results
+
+### Libero Benchmark Results
+
+> [!NOTE]
+> Follow our instructions for Libero usage: [Libero](./libero)
+
+GR00T has demonstrated strong performance on the Libero benchmark suite. To compare and test its LeRobot implementation, we finetuned the GR00T N1.5 model for 30k steps on the Libero dataset and compared the results to the GR00T reference results.
+
+| Benchmark | LeRobot Implementation | GR00T Reference |
+| ------------------ | ---------------------- | --------------- |
+| **Libero Spatial** | 82.0% | 92.0% |
+| **Libero Object** | 99.0% | 92.0% |
+| **Libero Long** | 82.0% | 76.0% |
+| **Average** | 87.0% | 87.0% |
+
+These results demonstrate GR00T's strong generalization capabilities across diverse robotic manipulation tasks. To reproduce these results, you can follow the instructions in the [Libero](https://huggingface.co/docs/lerobot/libero) section.
+
+### Evaluate in your hardware setup
+
+Once you have trained your model using your parameters you can run inference in your downstream task. Follow the instructions in [Imitation Learning for Robots](./il_robots). For example:
+
+```bash
+lerobot-record \
+ --robot.type=bi_so_follower \
+ --robot.left_arm_port=/dev/ttyACM1 \
+ --robot.right_arm_port=/dev/ttyACM0 \
+ --robot.id=bimanual_follower \
+ --robot.cameras='{ right: {"type": "opencv", "index_or_path": 0, "width": 640, "height": 480, "fps": 30},
+ left: {"type": "opencv", "index_or_path": 2, "width": 640, "height": 480, "fps": 30},
+ top: {"type": "opencv", "index_or_path": 4, "width": 640, "height": 480, "fps": 30},
+ }' \
+ --display_data=true \
+ --dataset.repo_id=/eval_groot-bimanual \
+ --dataset.num_episodes=10 \
+ --dataset.single_task="Grab and handover the red cube to the other arm"
+ --policy.path=/groot-bimanual # your trained model
+ --dataset.episode_time_s=30
+ --dataset.reset_time_s=10
+```
+
+## License
+
+This model follows the **Apache 2.0 License**, consistent with the original [GR00T repository](https://github.com/NVIDIA/Isaac-GR00T).
diff --git a/lerobot/docs/source/hilserl.mdx b/lerobot/docs/source/hilserl.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..dacaa960aa73c93460aaaa294fb60d54c594e971
--- /dev/null
+++ b/lerobot/docs/source/hilserl.mdx
@@ -0,0 +1,923 @@
+# HIL-SERL Real Robot Training Workflow Guide
+
+In this tutorial you will go through the full Human-in-the-Loop Sample-Efficient Reinforcement Learning (HIL-SERL) workflow using LeRobot. You will master training a policy with RL on a real robot in just a few hours.
+
+HIL-SERL is a sample-efficient reinforcement learning algorithm that combines human demonstrations with online learning and human interventions. The approach starts from a small set of human demonstrations, uses them to train a reward classifier, and then employs an actor-learner architecture where humans can intervene during policy execution to guide exploration and correct unsafe behaviors. In this tutorial, you'll use a gamepad to provide interventions and control the robot during the learning process.
+
+It combines three key ingredients:
+
+1. **Offline demonstrations & reward classifier:** a handful of human-teleop episodes plus a vision-based success detector give the policy a shaped starting point.
+
+2. **On-robot actor / learner loop with human interventions:** a distributed Soft Actor Critic (SAC) learner updates the policy while an actor explores on the physical robot; the human can jump in at any time to correct dangerous or unproductive behaviour.
+
+3. **Safety & efficiency tools:** joint/end-effector (EE) bounds, crop region of interest (ROI) preprocessing and WandB monitoring keep the data useful and the hardware safe.
+
+Together these elements let HIL-SERL reach near-perfect task success and faster cycle times than imitation-only baselines.
+
+
+
+
+
+
+ HIL-SERL workflow, Luo et al. 2024
+
+
+This guide provides step-by-step instructions for training a robot policy using LeRobot's HilSerl implementation to train on a real robot.
+
+## What do I need?
+
+- A gamepad (recommended) or keyboard to control the robot
+- A Nvidia GPU
+- A real robot with a follower and leader arm (optional if you use the keyboard or the gamepad)
+- A URDF file for the robot for the kinematics package (check `lerobot/model/kinematics.py`)
+
+## What kind of tasks can I train?
+
+One can use HIL-SERL to train on a variety of manipulation tasks. Some recommendations:
+
+- Start with a simple task to understand how the system works.
+ - Push cube to a goal region
+ - Pick and lift cube with the gripper
+- Avoid extremely long horizon tasks. Focus on tasks that can be completed in 5-10 seconds.
+- Once you have a good idea of how the system works, you can try more complex tasks and longer horizons.
+ - Pick and place cube
+ - Bimanual tasks to pick objects with two arms
+ - Hand-over tasks to transfer objects from one arm to another
+ - Go crazy!
+
+## Install LeRobot with HIL-SERL
+
+To install LeRobot with HIL-SERL, you need to install the `hilserl` extra.
+
+```bash
+pip install -e ".[hilserl]"
+```
+
+## Real Robot Training Workflow
+
+### Understanding Configuration
+
+The training process begins with proper configuration for the HILSerl environment. The main configuration class is `GymManipulatorConfig` in `lerobot/rl/gym_manipulator.py`, which contains nested `HILSerlRobotEnvConfig` and `DatasetConfig`. The configuration is organized into focused, nested sub-configs:
+
+
+```python
+class GymManipulatorConfig:
+ env: HILSerlRobotEnvConfig # Environment configuration (nested)
+ dataset: DatasetConfig # Dataset recording/replay configuration (nested)
+ mode: str | None = None # "record", "replay", or None (for training)
+ device: str = "cpu" # Compute device
+
+class HILSerlRobotEnvConfig(EnvConfig):
+ robot: RobotConfig | None = None # Main robot agent (defined in `lerobot/robots`)
+ teleop: TeleoperatorConfig | None = None # Teleoperator agent, e.g., gamepad or leader arm
+ processor: HILSerlProcessorConfig # Processing pipeline configuration (nested)
+ name: str = "real_robot" # Environment name
+ task: str | None = None # Task identifier
+ fps: int = 10 # Control frequency
+
+# Nested processor configuration
+class HILSerlProcessorConfig:
+ control_mode: str = "gamepad" # Control mode
+ observation: ObservationConfig | None = None # Observation processing settings
+ image_preprocessing: ImagePreprocessingConfig | None = None # Image crop/resize settings
+ gripper: GripperConfig | None = None # Gripper control and penalty settings
+ reset: ResetConfig | None = None # Environment reset and timing settings
+ inverse_kinematics: InverseKinematicsConfig | None = None # IK processing settings
+ reward_classifier: RewardClassifierConfig | None = None # Reward classifier settings
+ max_gripper_pos: float | None = 100.0 # Maximum gripper position
+
+# Sub-configuration classes
+class ObservationConfig:
+ add_joint_velocity_to_observation: bool = False # Add joint velocities to state
+ add_current_to_observation: bool = False # Add motor currents to state
+ display_cameras: bool = False # Display camera feeds during execution
+
+class ImagePreprocessingConfig:
+ crop_params_dict: dict[str, tuple[int, int, int, int]] | None = None # Image cropping parameters
+ resize_size: tuple[int, int] | None = None # Target image size
+
+class GripperConfig:
+ use_gripper: bool = True # Enable gripper control
+ gripper_penalty: float = 0.0 # Penalty for inappropriate gripper usage
+
+class ResetConfig:
+ fixed_reset_joint_positions: Any | None = None # Joint positions for reset
+ reset_time_s: float = 5.0 # Time to wait during reset
+ control_time_s: float = 20.0 # Maximum episode duration
+ terminate_on_success: bool = True # Whether to terminate episodes on success detection
+
+class InverseKinematicsConfig:
+ urdf_path: str | None = None # Path to robot URDF file
+ target_frame_name: str | None = None # End-effector frame name
+ end_effector_bounds: dict[str, list[float]] | None = None # EE workspace bounds
+ end_effector_step_sizes: dict[str, float] | None = None # EE step sizes per axis
+
+class RewardClassifierConfig:
+ pretrained_path: str | None = None # Path to pretrained reward classifier
+ success_threshold: float = 0.5 # Success detection threshold
+ success_reward: float = 1.0 # Reward value for successful episodes
+
+# Dataset configuration
+class DatasetConfig:
+ repo_id: str # LeRobot dataset repository ID
+ task: str # Task identifier
+ root: str | None = None # Local dataset root directory
+ num_episodes_to_record: int = 5 # Number of episodes for recording
+ replay_episode: int | None = None # Episode index for replay
+ push_to_hub: bool = False # Whether to push datasets to Hub
+```
+
+
+### Processor Pipeline Architecture
+
+HIL-SERL uses a modular processor pipeline architecture that processes robot observations and actions through a series of composable steps. The pipeline is divided into two main components:
+
+#### Environment Processor Pipeline
+
+The environment processor (`env_processor`) handles incoming observations and environment state:
+
+1. **VanillaObservationProcessorStep**: Converts raw robot observations into standardized format
+2. **JointVelocityProcessorStep** (optional): Adds joint velocity information to observations
+3. **MotorCurrentProcessorStep** (optional): Adds motor current readings to observations
+4. **ForwardKinematicsJointsToEE** (optional): Computes end-effector pose from joint positions
+5. **ImageCropResizeProcessorStep** (optional): Crops and resizes camera images
+6. **TimeLimitProcessorStep** (optional): Enforces episode time limits
+7. **GripperPenaltyProcessorStep** (optional): Applies penalties for inappropriate gripper usage
+8. **RewardClassifierProcessorStep** (optional): Automated reward detection using vision models
+9. **AddBatchDimensionProcessorStep**: Converts data to batch format for neural network processing
+10. **DeviceProcessorStep**: Moves data to the specified compute device (CPU/GPU)
+
+#### Action Processor Pipeline
+
+The action processor (`action_processor`) handles outgoing actions and human interventions:
+
+1. **AddTeleopActionAsComplimentaryDataStep**: Captures teleoperator actions for logging
+2. **AddTeleopEventsAsInfoStep**: Records intervention events and episode control signals
+3. **InterventionActionProcessorStep**: Handles human interventions and episode termination
+4. **Inverse Kinematics Pipeline** (when enabled):
+ - **MapDeltaActionToRobotActionStep**: Converts delta actions to robot action format
+ - **EEReferenceAndDelta**: Computes end-effector reference and delta movements
+ - **EEBoundsAndSafety**: Enforces workspace safety bounds
+ - **InverseKinematicsEEToJoints**: Converts end-effector actions to joint targets
+ - **GripperVelocityToJoint**: Handles gripper control commands
+
+#### Configuration Examples
+
+**Basic Observation Processing**:
+
+```json
+{
+ "env": {
+ "processor": {
+ "observation": {
+ "add_joint_velocity_to_observation": true,
+ "add_current_to_observation": false,
+ "display_cameras": false
+ }
+ }
+ }
+}
+```
+
+**Image Processing**:
+
+```json
+{
+ "env": {
+ "processor": {
+ "image_preprocessing": {
+ "crop_params_dict": {
+ "observation.images.front": [180, 250, 120, 150],
+ "observation.images.side": [180, 207, 180, 200]
+ },
+ "resize_size": [128, 128]
+ }
+ }
+ }
+}
+```
+
+**Inverse Kinematics Setup**:
+
+```json
+{
+ "env": {
+ "processor": {
+ "inverse_kinematics": {
+ "urdf_path": "path/to/robot.urdf",
+ "target_frame_name": "end_effector",
+ "end_effector_bounds": {
+ "min": [0.16, -0.08, 0.03],
+ "max": [0.24, 0.2, 0.1]
+ },
+ "end_effector_step_sizes": {
+ "x": 0.02,
+ "y": 0.02,
+ "z": 0.02
+ }
+ }
+ }
+ }
+}
+```
+
+### Advanced Observation Processing
+
+The HIL-SERL framework supports additional observation processing features that can improve policy learning:
+
+#### Joint Velocity Processing
+
+Enable joint velocity estimation to provide the policy with motion information:
+
+```json
+{
+ "env": {
+ "processor": {
+ "observation": {
+ "add_joint_velocity_to_observation": true
+ }
+ }
+ }
+}
+```
+
+This processor:
+
+- Estimates joint velocities using finite differences between consecutive joint position readings
+- Adds velocity information to the observation state vector
+- Useful for policies that need motion awareness for dynamic tasks
+
+#### Motor Current Processing
+
+Monitor motor currents to detect contact forces and load conditions:
+
+```json
+{
+ "env": {
+ "processor": {
+ "observation": {
+ "add_current_to_observation": true
+ }
+ }
+ }
+}
+```
+
+This processor:
+
+- Reads motor current values from the robot's control system
+- Adds current measurements to the observation state vector
+- Helps detect contact events, object weights, and mechanical resistance
+- Useful for contact-rich manipulation tasks
+
+#### Combined Observation Processing
+
+You can enable multiple observation processing features simultaneously:
+
+```json
+{
+ "env": {
+ "processor": {
+ "observation": {
+ "add_joint_velocity_to_observation": true,
+ "add_current_to_observation": true,
+ "display_cameras": false
+ }
+ }
+ }
+}
+```
+
+**Note**: Enabling additional observation features increases the state space dimensionality, which may require adjusting your policy network architecture and potentially collecting more training data.
+
+### Finding Robot Workspace Bounds
+
+Before collecting demonstrations, you need to determine the appropriate operational bounds for your robot.
+
+This helps simplify the problem of learning on the real robot in two ways: 1) by limiting the robot's operational space to a specific region that solves the task and avoids unnecessary or unsafe exploration, and 2) by allowing training in end-effector space rather than joint space. Empirically, learning in joint space for reinforcement learning in manipulation is often a harder problem - some tasks are nearly impossible to learn in joint space but become learnable when the action space is transformed to end-effector coordinates.
+
+**Using lerobot-find-joint-limits**
+
+This script helps you find the safe operational bounds for your robot's end-effector. Given that you have a follower and leader arm, you can use the script to find the bounds for the follower arm that will be applied during training.
+Bounding the action space will reduce the redundant exploration of the agent and guarantees safety.
+
+```bash
+lerobot-find-joint-limits \
+ --robot.type=so100_follower \
+ --robot.port=/dev/tty.usbmodem58760431541 \
+ --robot.id=black \
+ --teleop.type=so100_leader \
+ --teleop.port=/dev/tty.usbmodem58760431551 \
+ --teleop.id=blue
+```
+
+**Workflow**
+
+1. Run the script and move the robot through the space that solves the task
+2. The script will record the minimum and maximum end-effector positions and the joint angles and prints them to the console, for example:
+ ```
+ Max ee position [0.2417 0.2012 0.1027]
+ Min ee position [0.1663 -0.0823 0.0336]
+ Max joint positions [-20.0, -20.0, -20.0, -20.0, -20.0, -20.0]
+ Min joint positions [50.0, 50.0, 50.0, 50.0, 50.0, 50.0]
+ ```
+3. Use these values in the configuration of your teleoperation device (TeleoperatorConfig) under the `end_effector_bounds` field
+
+**Example Configuration**
+
+```json
+"end_effector_bounds": {
+ "max": [0.24, 0.20, 0.10],
+ "min": [0.16, -0.08, 0.03]
+}
+```
+
+### Collecting Demonstrations
+
+With the bounds defined, you can safely collect demonstrations for training. Training RL with off-policy algorithm allows us to use offline datasets collected in order to improve the efficiency of the learning process.
+
+**Setting Up Record Mode**
+
+Create a configuration file for recording demonstrations (or edit an existing one like [env_config.json](https://huggingface.co/datasets/lerobot/config_examples/resolve/main/rl/env_config.json)):
+
+1. Set `mode` to `"record"` at the root level
+2. Specify a unique `repo_id` for your dataset in the `dataset` section (e.g., "username/task_name")
+3. Set `num_episodes_to_record` in the `dataset` section to the number of demonstrations you want to collect
+4. Set `env.processor.image_preprocessing.crop_params_dict` to `{}` initially (we'll determine crops later)
+5. Configure `env.robot`, `env.teleop`, and other hardware settings in the `env` section
+
+Example configuration section:
+
+```json
+{
+ "env": {
+ "type": "gym_manipulator",
+ "name": "real_robot",
+ "fps": 10,
+ "processor": {
+ "control_mode": "gamepad",
+ "observation": {
+ "display_cameras": false
+ },
+ "image_preprocessing": {
+ "crop_params_dict": {},
+ "resize_size": [128, 128]
+ },
+ "gripper": {
+ "use_gripper": true,
+ "gripper_penalty": 0.0
+ },
+ "reset": {
+ "reset_time_s": 5.0,
+ "control_time_s": 20.0
+ }
+ },
+ "robot": {
+ // ... robot configuration ...
+ },
+ "teleop": {
+ // ... teleoperator configuration ...
+ }
+ },
+ "dataset": {
+ "repo_id": "username/pick_lift_cube",
+ "root": null,
+ "task": "pick_and_lift",
+ "num_episodes_to_record": 15,
+ "replay_episode": 0,
+ "push_to_hub": true
+ },
+ "mode": "record",
+ "device": "cpu"
+}
+```
+
+### Using a Teleoperation Device
+
+Along with your robot, you will need a teleoperation device to control it in order to collect datasets of your task and perform interventions during the online training.
+We support using a gamepad or a keyboard or the leader arm of the robot.
+
+HIL-Serl learns actions in the end-effector space of the robot. Therefore, the teleoperation will control the end-effector's x,y,z displacements.
+
+For that we need to define a version of the robot that takes actions in the end-effector space. Check the robot class `SO100FollowerEndEffector` and its configuration `SO100FollowerEndEffectorConfig` for the default parameters related to the end-effector space.
+
+
+```python
+class SO100FollowerEndEffectorConfig(SO100FollowerConfig):
+ """Configuration for the SO100FollowerEndEffector robot."""
+
+ # Default bounds for the end-effector position (in meters)
+ end_effector_bounds: dict[str, list[float]] = field( # bounds for the end-effector in x,y,z direction
+ default_factory=lambda: {
+ "min": [-1.0, -1.0, -1.0], # min x, y, z
+ "max": [1.0, 1.0, 1.0], # max x, y, z
+ }
+ )
+
+ max_gripper_pos: float = 50 # maximum gripper position that the gripper will be open at
+
+ end_effector_step_sizes: dict[str, float] = field( # maximum step size for the end-effector in x,y,z direction
+ default_factory=lambda: {
+ "x": 0.02,
+ "y": 0.02,
+ "z": 0.02,
+ }
+ )
+```
+
+
+The `Teleoperator` defines the teleoperation device. You can check the list of available teleoperators in `lerobot/teleoperators`.
+
+**Setting up the Gamepad**
+
+The gamepad provides a very convenient way to control the robot and the episode state.
+
+To setup the gamepad, you need to set the `control_mode` to `"gamepad"` and define the `teleop` section in the configuration file.
+
+```json
+{
+ "env": {
+ "teleop": {
+ "type": "gamepad",
+ "use_gripper": true
+ },
+ "processor": {
+ "control_mode": "gamepad",
+ "gripper": {
+ "use_gripper": true
+ }
+ }
+ }
+}
+```
+
+
+
+
+
+ Gamepad button mapping for robot control and episode management
+
+
+**Setting up the SO101 leader**
+
+The SO101 leader arm has reduced gears that allows it to move and track the follower arm during exploration. Therefore, taking over is much smoother than the gearless SO100.
+
+To setup the SO101 leader, you need to set the `control_mode` to `"leader"` and define the `teleop` section in the configuration file.
+
+```json
+{
+ "env": {
+ "teleop": {
+ "type": "so101_leader",
+ "port": "/dev/tty.usbmodem585A0077921",
+ "use_degrees": true
+ },
+ "processor": {
+ "control_mode": "leader",
+ "gripper": {
+ "use_gripper": true
+ }
+ }
+ }
+}
+```
+
+In order to annotate the success/failure of the episode, **you will need** to use a keyboard to press `s` for success, `esc` for failure.
+During the online training, press `space` to take over the policy and `space` again to give the control back to the policy.
+
+
+Video: SO101 leader teleoperation
+
+
+
+
+
+
SO101 leader teleoperation example, the leader tracks the follower, press `space` to intervene
+
+
+**Recording Demonstrations**
+
+Start the recording process, an example of the config file can be found [here](https://huggingface.co/datasets/aractingi/lerobot-example-config-files/blob/main/env_config_so100.json):
+
+```bash
+python -m lerobot.rl.gym_manipulator --config_path src/lerobot/configs/env_config_so100.json
+```
+
+During recording:
+
+1. The robot will reset to the initial position defined in the configuration file `env.processor.reset.fixed_reset_joint_positions`
+2. Complete the task successfully
+3. The episode ends with a reward of 1 when you press the "success" button
+4. If the time limit is reached, or the fail button is pressed, the episode ends with a reward of 0
+5. You can rerecord an episode by pressing the "rerecord" button
+6. The process automatically continues to the next episode
+7. After recording all episodes, the dataset is pushed to the Hugging Face Hub (optional) and saved locally
+
+### Processing the Dataset
+
+After collecting demonstrations, process them to determine optimal camera crops.
+Reinforcement learning is sensitive to background distractions, so it is important to crop the images to the relevant workspace area.
+
+Visual RL algorithms learn directly from pixel inputs, making them vulnerable to irrelevant visual information. Background elements like changing lighting, shadows, people moving, or objects outside the workspace can confuse the learning process. Good ROI selection should:
+
+- Include only the essential workspace where the task happens
+- Capture the robot's end-effector and all objects involved in the task
+- Exclude unnecessary background elements and distractions
+
+Note: If you already know the crop parameters, you can skip this step and just set the `crop_params_dict` in the configuration file during recording.
+
+**Determining Crop Parameters**
+
+Use the `crop_dataset_roi.py` script to interactively select regions of interest in your camera images:
+
+```bash
+python -m lerobot.rl.crop_dataset_roi --repo-id username/pick_lift_cube
+```
+
+1. For each camera view, the script will display the first frame
+2. Draw a rectangle around the relevant workspace area
+3. Press 'c' to confirm the selection
+4. Repeat for all camera views
+5. The script outputs cropping parameters and creates a new cropped dataset
+
+Example output:
+
+```
+Selected Rectangular Regions of Interest (top, left, height, width):
+observation.images.side: [180, 207, 180, 200]
+observation.images.front: [180, 250, 120, 150]
+```
+
+
+
+
+
+
+ Interactive cropping tool for selecting regions of interest
+
+
+**Updating Configuration**
+
+Add these crop parameters to your training configuration:
+
+```json
+{
+ "env": {
+ "processor": {
+ "image_preprocessing": {
+ "crop_params_dict": {
+ "observation.images.side": [180, 207, 180, 200],
+ "observation.images.front": [180, 250, 120, 150]
+ },
+ "resize_size": [128, 128]
+ }
+ }
+ }
+}
+```
+
+**Recommended image resolution**
+
+Most vision-based policies have been validated on square inputs of either **128Γ128** (default) or **64Γ64** pixels. We therefore advise setting the resize_size parameter to [128, 128] β or [64, 64] if you need to save GPU memory and bandwidth. Other resolutions are possible but have not been extensively tested.
+
+### Training a Reward Classifier
+
+The reward classifier plays an important role in the HIL-SERL workflow by automating reward assignment and automatically detecting episode success. Instead of manually defining reward functions or relying on human feedback for every timestep, the reward classifier learns to predict success/failure from visual observations. This enables the RL algorithm to learn efficiently by providing consistent and automated reward signals based on the robot's camera inputs.
+
+This guide explains how to train a reward classifier for human-in-the-loop reinforcement learning implementation of LeRobot. Reward classifiers learn to predict the reward value given a state which can be used in an RL setup to train a policy.
+
+**Note**: Training a reward classifier is optional. You can start the first round of RL experiments by annotating the success manually with your gamepad or keyboard device.
+
+The reward classifier implementation in `modeling_classifier.py` uses a pretrained vision model to process the images. It can output either a single value for binary rewards to predict success/fail cases or multiple values for multi-class settings.
+
+**Collecting a Dataset for the reward classifier**
+
+Before training, you need to collect a dataset with labeled examples. The `record_dataset` function in `gym_manipulator.py` enables the process of collecting a dataset of observations, actions, and rewards.
+
+To collect a dataset, you need to modify some parameters in the environment configuration based on HILSerlRobotEnvConfig.
+
+```bash
+python -m lerobot.rl.gym_manipulator --config_path src/lerobot/configs/reward_classifier_train_config.json
+```
+
+**Key Parameters for Data Collection**
+
+- **mode**: set it to `"record"` to collect a dataset (at root level)
+- **dataset.repo_id**: `"hf_username/dataset_name"`, name of the dataset and repo on the hub
+- **dataset.num_episodes_to_record**: Number of episodes to record
+- **env.processor.reset.terminate_on_success**: Whether to automatically terminate episodes when success is detected (default: `true`)
+- **env.fps**: Number of frames per second to record
+- **dataset.push_to_hub**: Whether to push the dataset to the hub
+
+The `env.processor.reset.terminate_on_success` parameter allows you to control episode termination behavior. When set to `false`, episodes will continue even after success is detected, allowing you to collect more positive examples with the reward=1 label. This is crucial for training reward classifiers as it provides more success state examples in your dataset. When set to `true` (default), episodes terminate immediately upon success detection.
+
+**Important**: For reward classifier training, set `terminate_on_success: false` to collect sufficient positive examples. For regular HIL-SERL training, keep it as `true` to enable automatic episode termination when the task is completed successfully.
+
+Example configuration section for data collection:
+
+```json
+{
+ "env": {
+ "type": "gym_manipulator",
+ "name": "real_robot",
+ "fps": 10,
+ "processor": {
+ "reset": {
+ "reset_time_s": 5.0,
+ "control_time_s": 20.0,
+ "terminate_on_success": false
+ },
+ "gripper": {
+ "use_gripper": true
+ }
+ },
+ "robot": {
+ // ... robot configuration ...
+ },
+ "teleop": {
+ // ... teleoperator configuration ...
+ }
+ },
+ "dataset": {
+ "repo_id": "hf_username/dataset_name",
+ "dataset_root": "data/your_dataset",
+ "task": "reward_classifier_task",
+ "num_episodes_to_record": 20,
+ "replay_episode": null,
+ "push_to_hub": true
+ },
+ "mode": "record",
+ "device": "cpu"
+}
+```
+
+**Reward Classifier Configuration**
+
+The reward classifier is configured using `configuration_classifier.py`. Here are the key parameters:
+
+- **model_name**: Base model architecture (e.g., we mainly use `"helper2424/resnet10"`)
+- **model_type**: `"cnn"` or `"transformer"`
+- **num_cameras**: Number of camera inputs
+- **num_classes**: Number of output classes (typically 2 for binary success/failure)
+- **hidden_dim**: Size of hidden representation
+- **dropout_rate**: Regularization parameter
+- **learning_rate**: Learning rate for optimizer
+
+Example configuration for training the [reward classifier](https://huggingface.co/datasets/aractingi/lerobot-example-config-files/blob/main/reward_classifier_train_config.json):
+
+```json
+{
+ "policy": {
+ "type": "reward_classifier",
+ "model_name": "helper2424/resnet10",
+ "model_type": "cnn",
+ "num_cameras": 2,
+ "num_classes": 2,
+ "hidden_dim": 256,
+ "dropout_rate": 0.1,
+ "learning_rate": 1e-4,
+ "device": "cuda",
+ "use_amp": true,
+ "input_features": {
+ "observation.images.front": {
+ "type": "VISUAL",
+ "shape": [3, 128, 128]
+ },
+ "observation.images.side": {
+ "type": "VISUAL",
+ "shape": [3, 128, 128]
+ }
+ }
+ }
+}
+```
+
+**Training the Classifier**
+
+To train the classifier, use the `train.py` script with your configuration:
+
+```bash
+lerobot-train --config_path path/to/reward_classifier_train_config.json
+```
+
+**Deploying and Testing the Model**
+
+To use your trained reward classifier, configure the `HILSerlRobotEnvConfig` to use your model:
+
+
+```python
+config = GymManipulatorConfig(
+ env=HILSerlRobotEnvConfig(
+ processor=HILSerlProcessorConfig(
+ reward_classifier=RewardClassifierConfig(
+ pretrained_path="path_to_your_pretrained_trained_model"
+ )
+ ),
+ # Other environment parameters
+ ),
+ dataset=DatasetConfig(...),
+ mode=None # For training
+)
+```
+
+
+or set the argument in the json config file.
+
+```json
+{
+ "env": {
+ "processor": {
+ "reward_classifier": {
+ "pretrained_path": "path_to_your_pretrained_model",
+ "success_threshold": 0.7,
+ "success_reward": 1.0
+ },
+ "reset": {
+ "terminate_on_success": true
+ }
+ }
+ }
+}
+```
+
+Run `gym_manipulator.py` to test the model.
+
+```bash
+python -m lerobot.rl.gym_manipulator --config_path path/to/env_config.json
+```
+
+The reward classifier will automatically provide rewards based on the visual input from the robot's cameras.
+
+**Example Workflow for training the reward classifier**
+
+1. **Create the configuration files**:
+ Create the necessary json configuration files for the reward classifier and the environment. Check the examples [here](https://huggingface.co/datasets/lerobot/config_examples/resolve/main/reward_classifier/config.json).
+
+2. **Collect a dataset**:
+
+ ```bash
+ python -m lerobot.rl.gym_manipulator --config_path src/lerobot/configs/env_config.json
+ ```
+
+3. **Train the classifier**:
+
+ ```bash
+ lerobot-train --config_path src/lerobot/configs/reward_classifier_train_config.json
+ ```
+
+4. **Test the classifier**:
+ ```bash
+ python -m lerobot.rl.gym_manipulator --config_path src/lerobot/configs/env_config.json
+ ```
+
+### Training with Actor-Learner
+
+The LeRobot system uses a distributed actor-learner architecture for training. This architecture decouples robot interactions from the learning process, allowing them to run concurrently without blocking each other. The actor server handles robot observations and actions, sending interaction data to the learner server. The learner server performs gradient descent and periodically updates the actor's policy weights. You will need to start two processes: a learner and an actor.
+
+**Configuration Setup**
+
+Create a training configuration file (example available [here](https://huggingface.co/datasets/lerobot/config_examples/resolve/main/rl/train_config.json)). The training config is based on the main `TrainRLServerPipelineConfig` class in `lerobot/configs/train.py`.
+
+1. Configure the policy settings (`type="sac"`, `device`, etc.)
+2. Set `dataset` to your cropped dataset
+3. Configure environment settings with crop parameters
+4. Check the other parameters related to SAC in [configuration_sac.py](https://github.com/huggingface/lerobot/blob/main/src/lerobot/policies/sac/configuration_sac.py#L79).
+5. Verify that the `policy` config is correct with the right `input_features` and `output_features` for your task.
+
+**Starting the Learner**
+
+First, start the learner server process:
+
+```bash
+python -m lerobot.rl.learner --config_path src/lerobot/configs/train_config_hilserl_so100.json
+```
+
+The learner:
+
+- Initializes the policy network
+- Prepares replay buffers
+- Opens a `gRPC` server to communicate with actors
+- Processes transitions and updates the policy
+
+**Starting the Actor**
+
+In a separate terminal, start the actor process with the same configuration:
+
+```bash
+python -m lerobot.rl.actor --config_path src/lerobot/configs/train_config_hilserl_so100.json
+```
+
+The actor:
+
+- Connects to the learner via `gRPC`
+- Initializes the environment
+- Execute rollouts of the policy to collect experience
+- Sends transitions to the learner
+- Receives updated policy parameters
+
+**Training Flow**
+
+The training proceeds automatically:
+
+1. The actor executes the policy in the environment
+2. Transitions are collected and sent to the learner
+3. The learner updates the policy based on these transitions
+4. Updated policy parameters are sent back to the actor
+5. The process continues until the specified step limit is reached
+
+**Human in the Loop**
+
+- The key to learning efficiently is to have human interventions to provide corrective feedback and completing the task to aide the policy learning and exploration.
+- To perform human interventions, you can press the upper right trigger button on the gamepad (or the `space` key on the keyboard). This will pause the policy actions and allow you to take over.
+- A successful experiment is one where the human has to intervene at the start but then reduces the amount of interventions as the policy improves. You can monitor the intervention rate in the `wandb` dashboard.
+
+
+
+
+
+
+
+ Example showing how human interventions help guide policy learning over time
+
+
+
+- The figure shows the plot of the episodic reward over interaction step. The figure shows the effect of human interventions on the policy learning.
+- The orange curve is an experiment without any human interventions. While the pink and blue curves are experiments with human interventions.
+- We can observe that the number of steps where the policy starts achieving the maximum reward is cut by a quarter when human interventions are present.
+
+**Monitoring and Debugging**
+
+If you have `wandb.enable` set to `true` in your configuration, you can monitor training progress in real-time through the [Weights & Biases](https://wandb.ai/site/) dashboard.
+
+### Guide to Human Interventions
+
+The learning process is very sensitive to the intervention strategy. It will takes a few runs to understand how to intervene effectively. Some tips and hints:
+
+- Allow the policy to explore for a few episodes at the start of training.
+- Avoid intervening for long periods of time. Try to intervene in situation to correct the robot's behaviour when it goes off track.
+- Once the policy starts achieving the task, even if its not perfect, you can limit your interventions to simple quick actions like a simple grasping commands.
+
+The ideal behaviour is that your intervention rate should drop gradually during training as shown in the figure below.
+
+
+
+
+
+
+
+ Plot of the intervention rate during a training run on a pick and lift cube
+ task
+
+
+
+### Key hyperparameters to tune
+
+Some configuration values have a disproportionate impact on training stability and speed:
+
+- **`temperature_init`** (`policy.temperature_init`) β initial entropy temperature in SAC. Higher values encourage more exploration; lower values make the policy more deterministic early on. A good starting point is `1e-2`. We observed that setting it too high can make human interventions ineffective and slow down learning.
+- **`policy_parameters_push_frequency`** (`policy.actor_learner_config.policy_parameters_push_frequency`) β interval in _seconds_ between two weight pushes from the learner to the actor. The default is `4 s`. Decrease to **1-2 s** to provide fresher weights (at the cost of more network traffic); increase only if your connection is slow, as this will reduce sample efficiency.
+- **`storage_device`** (`policy.storage_device`) β device on which the learner keeps the policy parameters. If you have spare GPU memory, set this to `"cuda"` (instead of the default `"cpu"`). Keeping the weights on-GPU removes CPUβGPU transfer overhead and can significantly increase the number of learner updates per second.
+
+Congrats π, you have finished this tutorial!
+
+> [!TIP]
+> If you have any questions or need help, please reach out on [Discord](https://discord.com/invite/s3KuuzsPFb).
+
+Paper citation:
+
+```
+@article{luo2024precise,
+ title={Precise and Dexterous Robotic Manipulation via Human-in-the-Loop Reinforcement Learning},
+ author={Luo, Jianlan and Xu, Charles and Wu, Jeffrey and Levine, Sergey},
+ journal={arXiv preprint arXiv:2410.21845},
+ year={2024}
+}
+```
diff --git a/lerobot/docs/source/hilserl_sim.mdx b/lerobot/docs/source/hilserl_sim.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..3af01f55a333e8e28468d0757bf1c1c658cbb659
--- /dev/null
+++ b/lerobot/docs/source/hilserl_sim.mdx
@@ -0,0 +1,154 @@
+# Train RL in Simulation
+
+This guide explains how to use the `gym_hil` simulation environments as an alternative to real robots when working with the LeRobot framework for Human-In-the-Loop (HIL) reinforcement learning.
+
+`gym_hil` is a package that provides Gymnasium-compatible simulation environments specifically designed for Human-In-the-Loop reinforcement learning. These environments allow you to:
+
+- Train policies in simulation to test the RL stack before training on real robots
+
+- Collect demonstrations in sim using external devices like gamepads or keyboards
+- Perform human interventions during policy learning
+
+Currently, the main environment is a Franka Panda robot simulation based on MuJoCo, with tasks like picking up a cube.
+
+## Installation
+
+First, install the `gym_hil` package within the LeRobot environment:
+
+```bash
+pip install -e ".[hilserl]"
+```
+
+## What do I need?
+
+- A gamepad or keyboard to control the robot
+- A Nvidia GPU
+
+## Configuration
+
+To use `gym_hil` with LeRobot, you need to create a configuration file. An example is provided [here](https://huggingface.co/datasets/lerobot/config_examples/resolve/main/rl/gym_hil/env_config.json). Key configuration sections include:
+
+### Environment Type and Task
+
+```json
+{
+ "env": {
+ "type": "gym_manipulator",
+ "name": "gym_hil",
+ "task": "PandaPickCubeGamepad-v0",
+ "fps": 10
+ },
+ "device": "cuda"
+}
+```
+
+Available tasks:
+
+- `PandaPickCubeBase-v0`: Basic environment
+- `PandaPickCubeGamepad-v0`: With gamepad control
+- `PandaPickCubeKeyboard-v0`: With keyboard control
+
+### Processor Configuration
+
+```json
+{
+ "env": {
+ "processor": {
+ "control_mode": "gamepad",
+ "gripper": {
+ "use_gripper": true,
+ "gripper_penalty": -0.02
+ },
+ "reset": {
+ "control_time_s": 15.0,
+ "fixed_reset_joint_positions": [
+ 0.0, 0.195, 0.0, -2.43, 0.0, 2.62, 0.785
+ ]
+ },
+ "inverse_kinematics": {
+ "end_effector_step_sizes": {
+ "x": 0.025,
+ "y": 0.025,
+ "z": 0.025
+ }
+ }
+ }
+ }
+}
+```
+
+Important parameters:
+
+- `gripper.gripper_penalty`: Penalty for excessive gripper movement
+- `gripper.use_gripper`: Whether to enable gripper control
+- `inverse_kinematics.end_effector_step_sizes`: Size of the steps in the x,y,z axes of the end-effector
+- `control_mode`: Set to `"gamepad"` to use a gamepad controller
+
+## Running with HIL RL of LeRobot
+
+### Basic Usage
+
+To run the environment, set mode to null:
+
+```bash
+python -m lerobot.rl.gym_manipulator --config_path path/to/gym_hil_env.json
+```
+
+### Recording a Dataset
+
+To collect a dataset, set the mode to `record` whilst defining the repo_id and number of episodes to record:
+
+```json
+{
+ "env": {
+ "type": "gym_manipulator",
+ "name": "gym_hil",
+ "task": "PandaPickCubeGamepad-v0"
+ },
+ "dataset": {
+ "repo_id": "username/sim_dataset",
+ "root": null,
+ "task": "pick_cube",
+ "num_episodes_to_record": 10,
+ "replay_episode": null,
+ "push_to_hub": true
+ },
+ "mode": "record"
+}
+```
+
+```bash
+python -m lerobot.rl.gym_manipulator --config_path path/to/gym_hil_env.json
+```
+
+### Training a Policy
+
+To train a policy, checkout the configuration example available [here](https://huggingface.co/datasets/lerobot/config_examples/resolve/main/rl/gym_hil/train_config.json) and run the actor and learner servers:
+
+```bash
+python -m lerobot.rl.actor --config_path path/to/train_gym_hil_env.json
+```
+
+In a different terminal, run the learner server:
+
+```bash
+python -m lerobot.rl.learner --config_path path/to/train_gym_hil_env.json
+```
+
+The simulation environment provides a safe and repeatable way to develop and test your Human-In-the-Loop reinforcement learning components before deploying to real robots.
+
+Congrats π, you have finished this tutorial!
+
+> [!TIP]
+> If you have any questions or need help, please reach out on [Discord](https://discord.com/invite/s3KuuzsPFb).
+
+Paper citation:
+
+```
+@article{luo2024precise,
+ title={Precise and Dexterous Robotic Manipulation via Human-in-the-Loop Reinforcement Learning},
+ author={Luo, Jianlan and Xu, Charles and Wu, Jeffrey and Levine, Sergey},
+ journal={arXiv preprint arXiv:2410.21845},
+ year={2024}
+}
+```
diff --git a/lerobot/docs/source/hope_jr.mdx b/lerobot/docs/source/hope_jr.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..91e4e608d3e05c4a885d5aacbd694882a4de8ba8
--- /dev/null
+++ b/lerobot/docs/source/hope_jr.mdx
@@ -0,0 +1,277 @@
+# HopeJR
+
+## Prerequisites
+
+- [Hardware Setup](https://github.com/TheRobotStudio/HOPEJr)
+
+## Install LeRobot
+
+Follow the [installation instructions](https://github.com/huggingface/lerobot#installation) to install LeRobot.
+
+Install LeRobot with HopeJR dependencies:
+
+```bash
+pip install -e ".[hopejr]"
+```
+
+## Device Configuration
+
+Before starting calibration and operation, you need to identify the USB ports for each HopeJR component. Run this script to find the USB ports for the arm, hand, glove, and exoskeleton:
+
+```bash
+lerobot-find-port
+```
+
+This will display the available USB ports and their associated devices. Make note of the port paths (e.g., `/dev/tty.usbmodem58760433331`, `/dev/tty.usbmodem11301`) as you'll need to specify them in the `--robot.port` and `--teleop.port` parameters when recording data, replaying episodes, or running teleoperation scripts.
+
+## Step 1: Calibration
+
+Before performing teleoperation, HopeJR's limbs need to be calibrated. Calibration files will be saved in `~/.cache/huggingface/lerobot/calibration`
+
+### 1.1 Calibrate Robot Hand
+
+```bash
+lerobot-calibrate \
+ --robot.type=hope_jr_hand \
+ --robot.port=/dev/tty.usbmodem58760432281 \
+ --robot.id=blue \
+ --robot.side=right
+```
+
+When running the calibration script, a calibration GUI will pop up. Finger joints are named as follows:
+
+**Thumb**:
+
+- **CMC**: base joint connecting thumb to hand
+- **MCP**: knuckle joint
+- **PIP**: first finger joint
+- **DIP** : fingertip joint
+
+**Index, Middle, Ring, and Pinky fingers**:
+
+- **Radial flexor**: Moves base of finger towards the thumb
+- **Ulnar flexor**: Moves base of finger towards the pinky
+- **PIP/DIP**: Flexes the distal and proximal phalanx of the finger
+
+Each one of these will need to be calibrated individually via the GUI.
+Note that ulnar and radial flexors should have ranges of the same size (but with different offsets) in order to get symmetric movement.
+
+
+
+
+
+Use the calibration interface to set the range boundaries for each joint as shown above.
+
+
+
+
+
+Once you have set the appropriate boundaries for all joints, click "Save" to save the calibration values to the motors.
+
+### 1.2 Calibrate Teleoperator Glove
+
+```bash
+lerobot-calibrate \
+ --teleop.type=homunculus_glove \
+ --teleop.port=/dev/tty.usbmodem11201 \
+ --teleop.id=red \
+ --teleop.side=right
+```
+
+Move each finger through its full range of motion, starting from the thumb.
+
+```
+Move thumb through its entire range of motion.
+Recording positions. Press ENTER to stop...
+
+-------------------------------------------
+NAME | MIN | POS | MAX
+thumb_cmc | 1790 | 1831 | 1853
+thumb_mcp | 1497 | 1514 | 1528
+thumb_pip | 1466 | 1496 | 1515
+thumb_dip | 1463 | 1484 | 1514
+```
+
+Continue with each finger:
+
+```
+Move middle through its entire range of motion.
+Recording positions. Press ENTER to stop...
+
+-------------------------------------------
+NAME | MIN | POS | MAX
+middle_mcp_abduction | 1598 | 1718 | 1820
+middle_mcp_flexion | 1512 | 1658 | 2136
+middle_dip | 1484 | 1500 | 1547
+```
+
+Once calibration is complete, the system will save the calibration to `/Users/your_username/.cache/huggingface/lerobot/calibration/teleoperators/homunculus_glove/red.json`
+
+### 1.3 Calibrate Robot Arm
+
+```bash
+lerobot-calibrate \
+ --robot.type=hope_jr_arm \
+ --robot.port=/dev/tty.usbserial-1110 \
+ --robot.id=white
+```
+
+This will open a calibration GUI where you can set the range limits for each motor. The arm motions are organized as follows:
+
+- **Shoulder**: pitch, yaw, and roll
+- **Elbow**: flex
+- **Wrist**: pitch, yaw, and roll
+
+
+
+
+
+Use the calibration interface to set the range boundaries for each joint. Move each joint through its full range of motion and adjust the minimum and maximum values accordingly. Once you have set the appropriate boundaries for all joints, save the calibration.
+
+### 1.4 Calibrate Teleoperator Exoskeleton
+
+```bash
+lerobot-calibrate \
+ --teleop.type=homunculus_arm \
+ --teleop.port=/dev/tty.usbmodem11201 \
+ --teleop.id=black
+```
+
+The exoskeleton allows one to control the robot arm. During calibration, you'll be prompted to move all joints through their full range of motion:
+
+```
+Move all joints through their entire range of motion.
+Recording positions. Press ENTER to stop...
+
+-------------------------------------------
+-------------------------------------------
+NAME | MIN | POS | MAX
+shoulder_pitch | 586 | 736 | 895
+shoulder_yaw | 1257 | 1374 | 1390
+shoulder_roll | 449 | 1034 | 2564
+elbow_flex | 3023 | 3117 | 3134
+wrist_roll | 3073 | 3096 | 3147
+wrist_yaw | 2143 | 2171 | 2185
+wrist_pitch | 1975 | 1993 | 2074
+Calibration saved to /Users/your_username/.cache/huggingface/lerobot/calibration/teleoperators/homunculus_arm/black.json
+```
+
+## Step 2: Teleoperation
+
+Due to global variable conflicts in the Feetech middleware, teleoperation for arm and hand must run in separate shell sessions:
+
+### Hand
+
+```bash
+lerobot-teleoperate \
+ --robot.type=hope_jr_hand \
+ --robot.port=/dev/tty.usbmodem58760432281 \
+ --robot.id=blue \
+ --robot.side=right \
+ --teleop.type=homunculus_glove \
+ --teleop.port=/dev/tty.usbmodem11201 \
+ --teleop.id=red \
+ --teleop.side=right \
+ --display_data=true \
+ --fps=30
+```
+
+### Arm
+
+```bash
+lerobot-teleoperate \
+ --robot.type=hope_jr_arm \
+ --robot.port=/dev/tty.usbserial-1110 \
+ --robot.id=white \
+ --teleop.type=homunculus_arm \
+ --teleop.port=/dev/tty.usbmodem11201 \
+ --teleop.id=black \
+ --display_data=true \
+ --fps=30
+```
+
+## Step 3: Record, Replay, Train
+
+Record, Replay and Train with Hope-JR is still experimental.
+
+### Record
+
+This step records the dataset, which can be seen as an example [here](https://huggingface.co/datasets/nepyope/hand_record_test_with_video_data/settings).
+
+```bash
+lerobot-record \
+ --robot.type=hope_jr_hand \
+ --robot.port=/dev/tty.usbmodem58760432281 \
+ --robot.id=right \
+ --robot.side=right \
+ --robot.cameras='{"main": {"type": "opencv", "index_or_path": 0, "width": 640, "height": 480, "fps": 30}}' \
+ --teleop.type=homunculus_glove \
+ --teleop.port=/dev/tty.usbmodem1201 \
+ --teleop.id=right \
+ --teleop.side=right \
+ --dataset.repo_id=nepyope/hand_record_test_with_video_data \
+ --dataset.single_task="Hand recording test with video data" \
+ --dataset.num_episodes=1 \
+ --dataset.episode_time_s=5 \
+ --dataset.push_to_hub=true \
+ --dataset.private=true \
+ --display_data=true
+```
+
+### Replay
+
+```bash
+lerobot-replay \
+ --robot.type=hope_jr_hand \
+ --robot.port=/dev/tty.usbmodem58760432281 \
+ --robot.id=right \
+ --robot.side=right \
+ --dataset.repo_id=nepyope/hand_record_test_with_camera \
+ --dataset.episode=0
+```
+
+### Train
+
+```bash
+lerobot-train \
+ --dataset.repo_id=nepyope/hand_record_test_with_video_data \
+ --policy.type=act \
+ --output_dir=outputs/train/hopejr_hand \
+ --job_name=hopejr \
+ --policy.device=mps \
+ --wandb.enable=true \
+ --policy.repo_id=nepyope/hand_test_policy
+```
+
+### Evaluate
+
+This training run can be viewed as an example [here](https://wandb.ai/tino/lerobot/runs/rp0k8zvw?nw=nwusertino).
+
+```bash
+lerobot-record \
+ --robot.type=hope_jr_hand \
+ --robot.port=/dev/tty.usbmodem58760432281 \
+ --robot.id=right \
+ --robot.side=right \
+ --robot.cameras='{"main": {"type": "opencv", "index_or_path": 0, "width": 640, "height": 480, "fps": 30}}' \
+ --display_data=false \
+ --dataset.repo_id=nepyope/eval_hopejr \
+ --dataset.single_task="Evaluate hopejr hand policy" \
+ --dataset.num_episodes=10 \
+ --policy.path=outputs/train/hopejr_hand/checkpoints/last/pretrained_model
+```
diff --git a/lerobot/docs/source/il_robots.mdx b/lerobot/docs/source/il_robots.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..c977616f6f84bb9a491d849c0e3d54a7531221ae
--- /dev/null
+++ b/lerobot/docs/source/il_robots.mdx
@@ -0,0 +1,620 @@
+# Imitation Learning on Real-World Robots
+
+This tutorial will explain how to train a neural network to control a real robot autonomously.
+
+**You'll learn:**
+
+1. How to record and visualize your dataset.
+2. How to train a policy using your data and prepare it for evaluation.
+3. How to evaluate your policy and visualize the results.
+
+By following these steps, you'll be able to replicate tasks, such as picking up a Lego block and placing it in a bin with a high success rate, as shown in the video below.
+
+
+Video: pickup lego block task
+
+
+
+
+
+
+
+This tutorial isnβt tied to a specific robot: we walk you through the commands and API snippets you can adapt for any supported platform.
+
+During data collection, youβll use a βteloperationβ device, such as a leader arm or keyboard to teleoperate the robot and record its motion trajectories.
+
+Once youβve gathered enough trajectories, youβll train a neural network to imitate these trajectories and deploy the trained model so your robot can perform the task autonomously.
+
+If you run into any issues at any point, jump into our [Discord community](https://discord.com/invite/s3KuuzsPFb) for support.
+
+## Set up and Calibrate
+
+If you haven't yet set up and calibrated your robot and teleop device, please do so by following the robot-specific tutorial.
+
+## Teleoperate
+
+In this example, weβll demonstrate how to teleoperate the SO101 robot. For each command, we also provide a corresponding API example.
+
+Note that the `id` associated with a robot is used to store the calibration file. It's important to use the same `id` when teleoperating, recording, and evaluating when using the same setup.
+
+
+
+```bash
+lerobot-teleoperate \
+ --robot.type=so101_follower \
+ --robot.port=/dev/tty.usbmodem58760431541 \
+ --robot.id=my_awesome_follower_arm \
+ --teleop.type=so101_leader \
+ --teleop.port=/dev/tty.usbmodem58760431551 \
+ --teleop.id=my_awesome_leader_arm
+```
+
+
+
+
+```python
+from lerobot.teleoperators.so_leader import SO101LeaderConfig, SO101Leader
+from lerobot.robots.so_follower import SO101FollowerConfig, SO101Follower
+
+robot_config = SO101FollowerConfig(
+ port="/dev/tty.usbmodem58760431541",
+ id="my_red_robot_arm",
+)
+
+teleop_config = SO101LeaderConfig(
+ port="/dev/tty.usbmodem58760431551",
+ id="my_blue_leader_arm",
+)
+
+robot = SO101Follower(robot_config)
+teleop_device = SO101Leader(teleop_config)
+robot.connect()
+teleop_device.connect()
+
+while True:
+ action = teleop_device.get_action()
+ robot.send_action(action)
+```
+
+
+
+
+
+The teleoperate command will automatically:
+
+1. Identify any missing calibrations and initiate the calibration procedure.
+2. Connect the robot and teleop device and start teleoperation.
+
+## Cameras
+
+To add cameras to your setup, follow this [Guide](./cameras#setup-cameras).
+
+## Teleoperate with cameras
+
+With `rerun`, you can teleoperate again while simultaneously visualizing the camera feeds and joint positions. In this example, weβre using the Koch arm.
+
+
+
+```bash
+lerobot-teleoperate \
+ --robot.type=koch_follower \
+ --robot.port=/dev/tty.usbmodem58760431541 \
+ --robot.id=my_awesome_follower_arm \
+ --robot.cameras="{ front: {type: opencv, index_or_path: 0, width: 1920, height: 1080, fps: 30}}" \
+ --teleop.type=koch_leader \
+ --teleop.port=/dev/tty.usbmodem58760431551 \
+ --teleop.id=my_awesome_leader_arm \
+ --display_data=true
+```
+
+
+
+
+```python
+from lerobot.cameras.opencv.configuration_opencv import OpenCVCameraConfig
+from lerobot.teleoperators.koch_leader import KochLeaderConfig, KochLeader
+from lerobot.robots.koch_follower import KochFollowerConfig, KochFollower
+
+camera_config = {
+ "front": OpenCVCameraConfig(index_or_path=0, width=1920, height=1080, fps=30)
+}
+
+robot_config = KochFollowerConfig(
+ port="/dev/tty.usbmodem585A0076841",
+ id="my_red_robot_arm",
+ cameras=camera_config
+)
+
+teleop_config = KochLeaderConfig(
+ port="/dev/tty.usbmodem58760431551",
+ id="my_blue_leader_arm",
+)
+
+robot = KochFollower(robot_config)
+teleop_device = KochLeader(teleop_config)
+robot.connect()
+teleop_device.connect()
+
+while True:
+ observation = robot.get_observation()
+ action = teleop_device.get_action()
+ robot.send_action(action)
+```
+
+
+
+
+
+## Record a dataset
+
+Once you're familiar with teleoperation, you can record your first dataset.
+
+We use the Hugging Face hub features for uploading your dataset. If you haven't previously used the Hub, make sure you can login via the cli using a write-access token, this token can be generated from the [Hugging Face settings](https://huggingface.co/settings/tokens).
+
+Add your token to the CLI by running this command:
+
+```bash
+huggingface-cli login --token ${HUGGINGFACE_TOKEN} --add-to-git-credential
+```
+
+Then store your Hugging Face repository name in a variable:
+
+```bash
+HF_USER=$(hf auth whoami | head -n 1)
+echo $HF_USER
+```
+
+Now you can record a dataset. To record 5 episodes and upload your dataset to the hub, adapt the code below for your robot and execute the command or API example.
+
+
+
+```bash
+lerobot-record \
+ --robot.type=so101_follower \
+ --robot.port=/dev/tty.usbmodem585A0076841 \
+ --robot.id=my_awesome_follower_arm \
+ --robot.cameras="{ front: {type: opencv, index_or_path: 0, width: 1920, height: 1080, fps: 30}}" \
+ --teleop.type=so101_leader \
+ --teleop.port=/dev/tty.usbmodem58760431551 \
+ --teleop.id=my_awesome_leader_arm \
+ --display_data=true \
+ --dataset.repo_id=${HF_USER}/record-test \
+ --dataset.num_episodes=5 \
+ --dataset.single_task="Grab the black cube"
+```
+
+
+
+
+```python
+from lerobot.cameras.opencv.configuration_opencv import OpenCVCameraConfig
+from lerobot.datasets.lerobot_dataset import LeRobotDataset
+from lerobot.datasets.utils import hw_to_dataset_features
+from lerobot.robots.so_follower import SO100Follower, SO100FollowerConfig
+from lerobot.teleoperators.so_leader.config_so100_leader import SO100LeaderConfig
+from lerobot.teleoperators.so_leader.so100_leader import SO100Leader
+from lerobot.utils.control_utils import init_keyboard_listener
+from lerobot.utils.utils import log_say
+from lerobot.utils.visualization_utils import init_rerun
+from lerobot.scripts.lerobot_record import record_loop
+from lerobot.processor import make_default_processors
+
+NUM_EPISODES = 5
+FPS = 30
+EPISODE_TIME_SEC = 60
+RESET_TIME_SEC = 10
+TASK_DESCRIPTION = "My task description"
+
+# Create robot configuration
+robot_config = SO100FollowerConfig(
+ id="my_awesome_follower_arm",
+ cameras={
+ "front": OpenCVCameraConfig(index_or_path=0, width=640, height=480, fps=FPS) # Optional: fourcc="MJPG" for troubleshooting OpenCV async error.
+ },
+ port="/dev/tty.usbmodem58760434471",
+)
+
+teleop_config = SO100LeaderConfig(
+ id="my_awesome_leader_arm",
+ port="/dev/tty.usbmodem585A0077581",
+)
+
+# Initialize the robot and teleoperator
+robot = SO100Follower(robot_config)
+teleop = SO100Leader(teleop_config)
+
+# Configure the dataset features
+action_features = hw_to_dataset_features(robot.action_features, "action")
+obs_features = hw_to_dataset_features(robot.observation_features, "observation")
+dataset_features = {**action_features, **obs_features}
+
+# Create the dataset
+dataset = LeRobotDataset.create(
+ repo_id="/",
+ fps=FPS,
+ features=dataset_features,
+ robot_type=robot.name,
+ use_videos=True,
+ image_writer_threads=4,
+)
+
+# Initialize the keyboard listener and rerun visualization
+_, events = init_keyboard_listener()
+init_rerun(session_name="recording")
+
+# Connect the robot and teleoperator
+robot.connect()
+teleop.connect()
+
+# Create the required processors
+teleop_action_processor, robot_action_processor, robot_observation_processor = make_default_processors()
+
+episode_idx = 0
+while episode_idx < NUM_EPISODES and not events["stop_recording"]:
+ log_say(f"Recording episode {episode_idx + 1} of {NUM_EPISODES}")
+
+ record_loop(
+ robot=robot,
+ events=events,
+ fps=FPS,
+ teleop_action_processor=teleop_action_processor,
+ robot_action_processor=robot_action_processor,
+ robot_observation_processor=robot_observation_processor,
+ teleop=teleop,
+ dataset=dataset,
+ control_time_s=EPISODE_TIME_SEC,
+ single_task=TASK_DESCRIPTION,
+ display_data=True,
+ )
+
+ # Reset the environment if not stopping or re-recording
+ if not events["stop_recording"] and (episode_idx < NUM_EPISODES - 1 or events["rerecord_episode"]):
+ log_say("Reset the environment")
+ record_loop(
+ robot=robot,
+ events=events,
+ fps=FPS,
+ teleop_action_processor=teleop_action_processor,
+ robot_action_processor=robot_action_processor,
+ robot_observation_processor=robot_observation_processor,
+ teleop=teleop,
+ control_time_s=RESET_TIME_SEC,
+ single_task=TASK_DESCRIPTION,
+ display_data=True,
+ )
+
+ if events["rerecord_episode"]:
+ log_say("Re-recording episode")
+ events["rerecord_episode"] = False
+ events["exit_early"] = False
+ dataset.clear_episode_buffer()
+ continue
+
+ dataset.save_episode()
+ episode_idx += 1
+
+# Clean up
+log_say("Stop recording")
+robot.disconnect()
+teleop.disconnect()
+dataset.push_to_hub()
+```
+
+
+
+
+
+#### Dataset upload
+
+Locally, your dataset is stored in this folder: `~/.cache/huggingface/lerobot/{repo-id}`. At the end of data recording, your dataset will be uploaded on your Hugging Face page (e.g. `https://huggingface.co/datasets/${HF_USER}/so101_test`) that you can obtain by running:
+
+```bash
+echo https://huggingface.co/datasets/${HF_USER}/so101_test
+```
+
+Your dataset will be automatically tagged with `LeRobot` for the community to find it easily, and you can also add custom tags (in this case `tutorial` for example).
+
+You can look for other LeRobot datasets on the hub by searching for `LeRobot` [tags](https://huggingface.co/datasets?other=LeRobot).
+
+You can also push your local dataset to the Hub manually, running:
+
+```bash
+huggingface-cli upload ${HF_USER}/record-test ~/.cache/huggingface/lerobot/{repo-id} --repo-type dataset
+```
+
+#### Record function
+
+The `record` function provides a suite of tools for capturing and managing data during robot operation:
+
+##### 1. Data Storage
+
+- Data is stored using the `LeRobotDataset` format and is stored on disk during recording.
+- By default, the dataset is pushed to your Hugging Face page after recording.
+ - To disable uploading, use `--dataset.push_to_hub=False`.
+
+##### 2. Checkpointing and Resuming
+
+- Checkpoints are automatically created during recording.
+- If an issue occurs, you can resume by re-running the same command with `--resume=true`. When resuming a recording, `--dataset.num_episodes` must be set to the **number of additional episodes to be recorded**, and not to the targeted total number of episodes in the dataset !
+- To start recording from scratch, **manually delete** the dataset directory.
+
+##### 3. Recording Parameters
+
+Set the flow of data recording using command-line arguments:
+
+- `--dataset.episode_time_s=60`
+ Duration of each data recording episode (default: **60 seconds**).
+- `--dataset.reset_time_s=60`
+ Duration for resetting the environment after each episode (default: **60 seconds**).
+- `--dataset.num_episodes=50`
+ Total number of episodes to record (default: **50**).
+
+##### 4. Keyboard Controls During Recording
+
+Control the data recording flow using keyboard shortcuts:
+
+- Press **Right Arrow (`β`)**: Early stop the current episode or reset time and move to the next.
+- Press **Left Arrow (`β`)**: Cancel the current episode and re-record it.
+- Press **Escape (`ESC`)**: Immediately stop the session, encode videos, and upload the dataset.
+
+#### Tips for gathering data
+
+Once you're comfortable with data recording, you can create a larger dataset for training. A good starting task is grasping an object at different locations and placing it in a bin. We suggest recording at least 50 episodes, with 10 episodes per location. Keep the cameras fixed and maintain consistent grasping behavior throughout the recordings. Also make sure the object you are manipulating is visible on the camera's. A good rule of thumb is you should be able to do the task yourself by only looking at the camera images.
+
+In the following sections, youβll train your neural network. After achieving reliable grasping performance, you can start introducing more variations during data collection, such as additional grasp locations, different grasping techniques, and altering camera positions.
+
+Avoid adding too much variation too quickly, as it may hinder your results.
+
+If you want to dive deeper into this important topic, you can check out the [blog post](https://huggingface.co/blog/lerobot-datasets#what-makes-a-good-dataset) we wrote on what makes a good dataset.
+
+#### Troubleshooting:
+
+- On Linux, if the left and right arrow keys and escape key don't have any effect during data recording, make sure you've set the `$DISPLAY` environment variable. See [pynput limitations](https://pynput.readthedocs.io/en/latest/limitations.html#linux).
+
+## Visualize a dataset
+
+If you uploaded your dataset to the hub with `--control.push_to_hub=true`, you can [visualize your dataset online](https://huggingface.co/spaces/lerobot/visualize_dataset) by copy pasting your repo id given by:
+
+```bash
+echo ${HF_USER}/so101_test
+```
+
+## Replay an episode
+
+A useful feature is the `replay` function, which allows you to replay any episode that you've recorded or episodes from any dataset out there. This function helps you test the repeatability of your robot's actions and assess transferability across robots of the same model.
+
+You can replay the first episode on your robot with either the command below or with the API example:
+
+
+
+```bash
+lerobot-replay \
+ --robot.type=so101_follower \
+ --robot.port=/dev/tty.usbmodem58760431541 \
+ --robot.id=my_awesome_follower_arm \
+ --dataset.repo_id=${HF_USER}/record-test \
+ --dataset.episode=0 # choose the episode you want to replay
+```
+
+
+
+
+```python
+import time
+
+from lerobot.datasets.lerobot_dataset import LeRobotDataset
+from lerobot.robots.so_follower.config_so100_follower import SO100FollowerConfig
+from lerobot.robots.so_follower.so100_follower import SO100Follower
+from lerobot.utils.robot_utils import precise_sleep
+from lerobot.utils.utils import log_say
+
+episode_idx = 0
+
+robot_config = SO100FollowerConfig(port="/dev/tty.usbmodem58760434471", id="my_awesome_follower_arm")
+
+robot = SO100Follower(robot_config)
+robot.connect()
+
+dataset = LeRobotDataset("/", episodes=[episode_idx])
+actions = dataset.hf_dataset.select_columns("action")
+
+log_say(f"Replaying episode {episode_idx}")
+for idx in range(dataset.num_frames):
+ t0 = time.perf_counter()
+
+ action = {
+ name: float(actions[idx]["action"][i]) for i, name in enumerate(dataset.features["action"]["names"])
+ }
+ robot.send_action(action)
+
+ precise_sleep(max(1.0 / dataset.fps - (time.perf_counter() - t0), 0.0))
+
+robot.disconnect()
+```
+
+
+
+
+
+Your robot should replicate movements similar to those you recorded. For example, check out [this video](https://x.com/RemiCadene/status/1793654950905680090) where we use `replay` on a Aloha robot from [Trossen Robotics](https://www.trossenrobotics.com).
+
+## Train a policy
+
+To train a policy to control your robot, use the [`lerobot-train`](https://github.com/huggingface/lerobot/blob/main/src/lerobot/scripts/lerobot_train.py) script. A few arguments are required. Here is an example command:
+
+```bash
+lerobot-train \
+ --dataset.repo_id=${HF_USER}/so101_test \
+ --policy.type=act \
+ --output_dir=outputs/train/act_so101_test \
+ --job_name=act_so101_test \
+ --policy.device=cuda \
+ --wandb.enable=true \
+ --policy.repo_id=${HF_USER}/my_policy
+```
+
+Let's explain the command:
+
+1. We provided the dataset as argument with `--dataset.repo_id=${HF_USER}/so101_test`.
+2. We provided the policy with `policy.type=act`. This loads configurations from [`configuration_act.py`](https://github.com/huggingface/lerobot/blob/main/src/lerobot/policies/act/configuration_act.py). Importantly, this policy will automatically adapt to the number of motor states, motor actions and cameras of your robot (e.g. `laptop` and `phone`) which have been saved in your dataset.
+3. We provided `policy.device=cuda` since we are training on a Nvidia GPU, but you could use `policy.device=mps` to train on Apple silicon.
+4. We provided `wandb.enable=true` to use [Weights and Biases](https://docs.wandb.ai/quickstart) for visualizing training plots. This is optional but if you use it, make sure you are logged in by running `wandb login`.
+
+Training should take several hours. You will find checkpoints in `outputs/train/act_so101_test/checkpoints`.
+
+To resume training from a checkpoint, below is an example command to resume from `last` checkpoint of the `act_so101_test` policy:
+
+```bash
+lerobot-train \
+ --config_path=outputs/train/act_so101_test/checkpoints/last/pretrained_model/train_config.json \
+ --resume=true
+```
+
+If you do not want to push your model to the hub after training use `--policy.push_to_hub=false`.
+
+Additionally you can provide extra `tags` or specify a `license` for your model or make the model repo `private` by adding this: `--policy.private=true --policy.tags=\[ppo,rl\] --policy.license=mit`
+
+#### Train using Google Colab
+
+If your local computer doesn't have a powerful GPU you could utilize Google Colab to train your model by following the [ACT training notebook](./notebooks#training-act).
+
+#### Upload policy checkpoints
+
+Once training is done, upload the latest checkpoint with:
+
+```bash
+huggingface-cli upload ${HF_USER}/act_so101_test \
+ outputs/train/act_so101_test/checkpoints/last/pretrained_model
+```
+
+You can also upload intermediate checkpoints with:
+
+```bash
+CKPT=010000
+huggingface-cli upload ${HF_USER}/act_so101_test${CKPT} \
+ outputs/train/act_so101_test/checkpoints/${CKPT}/pretrained_model
+```
+
+## Run inference and evaluate your policy
+
+You can use the `record` script from [`lerobot-record`](https://github.com/huggingface/lerobot/blob/main/src/lerobot/scripts/lerobot_record.py) with a policy checkpoint as input, to run inference and evaluate your policy. For instance, run this command or API example to run inference and record 10 evaluation episodes:
+
+
+
+```bash
+lerobot-record \
+ --robot.type=so100_follower \
+ --robot.port=/dev/ttyACM1 \
+ --robot.cameras="{ up: {type: opencv, index_or_path: /dev/video10, width: 640, height: 480, fps: 30}, side: {type: intelrealsense, serial_number_or_name: 233522074606, width: 640, height: 480, fps: 30}}" \
+ --robot.id=my_awesome_follower_arm \
+ --display_data=false \
+ --dataset.repo_id=${HF_USER}/eval_so100 \
+ --dataset.single_task="Put lego brick into the transparent box" \
+ # <- Teleop optional if you want to teleoperate in between episodes \
+ # --teleop.type=so100_leader \
+ # --teleop.port=/dev/ttyACM0 \
+ # --teleop.id=my_awesome_leader_arm \
+ --policy.path=${HF_USER}/my_policy
+```
+
+
+
+
+```python
+from lerobot.cameras.opencv.configuration_opencv import OpenCVCameraConfig
+from lerobot.datasets.lerobot_dataset import LeRobotDataset
+from lerobot.datasets.utils import hw_to_dataset_features
+from lerobot.policies.act.modeling_act import ACTPolicy
+from lerobot.policies.factory import make_pre_post_processors
+from lerobot.robots.so_follower.config_so100_follower import SO100FollowerConfig
+from lerobot.robots.so_follower.so100_follower import SO100Follower
+from lerobot.scripts.lerobot_record import record_loop
+from lerobot.utils.control_utils import init_keyboard_listener
+from lerobot.utils.utils import log_say
+from lerobot.utils.visualization_utils import init_rerun
+
+
+NUM_EPISODES = 5
+FPS = 30
+EPISODE_TIME_SEC = 60
+TASK_DESCRIPTION = "My task description"
+HF_MODEL_ID = "/"
+HF_DATASET_ID = "/"
+
+# Create the robot configuration
+camera_config = {"front": OpenCVCameraConfig(index_or_path=0, width=640, height=480, fps=FPS)}
+robot_config = SO100FollowerConfig(
+ port="/dev/tty.usbmodem58760434471", id="my_awesome_follower_arm", cameras=camera_config
+)
+
+# Initialize the robot
+robot = SO100Follower(robot_config)
+
+# Initialize the policy
+policy = ACTPolicy.from_pretrained(HF_MODEL_ID)
+
+# Configure the dataset features
+action_features = hw_to_dataset_features(robot.action_features, "action")
+obs_features = hw_to_dataset_features(robot.observation_features, "observation")
+dataset_features = {**action_features, **obs_features}
+
+# Create the dataset
+dataset = LeRobotDataset.create(
+ repo_id=HF_DATASET_ID,
+ fps=FPS,
+ features=dataset_features,
+ robot_type=robot.name,
+ use_videos=True,
+ image_writer_threads=4,
+)
+
+# Initialize the keyboard listener and rerun visualization
+_, events = init_keyboard_listener()
+init_rerun(session_name="recording")
+
+# Connect the robot
+robot.connect()
+
+preprocessor, postprocessor = make_pre_post_processors(
+ policy_cfg=policy,
+ pretrained_path=HF_MODEL_ID,
+ dataset_stats=dataset.meta.stats,
+)
+
+for episode_idx in range(NUM_EPISODES):
+ log_say(f"Running inference, recording eval episode {episode_idx + 1} of {NUM_EPISODES}")
+
+ # Run the policy inference loop
+ record_loop(
+ robot=robot,
+ events=events,
+ fps=FPS,
+ policy=policy,
+ preprocessor=preprocessor,
+ postprocessor=postprocessor,
+ dataset=dataset,
+ control_time_s=EPISODE_TIME_SEC,
+ single_task=TASK_DESCRIPTION,
+ display_data=True,
+ )
+
+ dataset.save_episode()
+
+# Clean up
+robot.disconnect()
+dataset.push_to_hub()
+```
+
+
+
+
+
+As you can see, it's almost the same command as previously used to record your training dataset. Two things changed:
+
+1. There is an additional `--control.policy.path` argument which indicates the path to your policy checkpoint with (e.g. `outputs/train/eval_act_so101_test/checkpoints/last/pretrained_model`). You can also use the model repository if you uploaded a model checkpoint to the hub (e.g. `${HF_USER}/act_so101_test`).
+2. The name of dataset begins by `eval` to reflect that you are running inference (e.g. `${HF_USER}/eval_act_so101_test`).
diff --git a/lerobot/docs/source/implement_your_own_processor.mdx b/lerobot/docs/source/implement_your_own_processor.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..f59ff3f0bf3c5f383b894088f6e5e3da6b17df22
--- /dev/null
+++ b/lerobot/docs/source/implement_your_own_processor.mdx
@@ -0,0 +1,273 @@
+# Implement your own Robot Processor
+
+In this tutorial, you'll learn how to implement your own Robot Processor.
+It begins by exploring the need for a custom processor, then uses the `NormalizerProcessorStep` as the running example to explain how to implement, configure, and serialize a processor. Finally, it lists all helper processors that ship with LeRobot.
+
+## Why would you need a custom processor?
+
+In most cases, when reading raw data from sensors or when models output actions, you need to process this data to make it compatible with your target system. For example, a common need is normalizing data ranges to make them suitable for neural networks.
+
+LeRobot's `NormalizerProcessorStep` handles this crucial task:
+
+```python
+# Input: raw joint positions in [0, 180] degrees
+raw_action = torch.tensor([90.0, 45.0, 135.0])
+
+# After processing: normalized to [-1, 1] range for model training
+normalizer = NormalizerProcessorStep(features=features, norm_map=norm_map, stats=dataset_stats)
+normalized_result = normalizer(transition)
+# ...
+```
+
+Other common processing needs include:
+
+- **Device placement**: Moving tensors between CPU/GPU and converting data types
+- **Format conversion**: Transforming between different data structures
+- **Batching**: Adding/removing batch dimensions for model compatibility
+- **Safety constraints**: Applying limits to robot commands
+
+```python
+# Example pipeline combining multiple processors
+pipeline = PolicyProcessorPipeline([
+ RenameObservationsProcessorStep(rename_map={}),
+ AddBatchDimensionProcessorStep(),
+ NormalizerProcessorStep(features=features, stats=stats),
+ DeviceProcessorStep(device="cuda"),
+ # ...
+])
+```
+
+LeRobot provides a pipeline mechanism to implement sequences of processing steps for both input data and output actions, making it easy to compose these transformations in the right order for optimal performance.
+
+## How to implement your own processor?
+
+We'll use the `NormalizerProcessorStep` as our main example because it demonstrates essential processor patterns including state management, configuration serialization, and tensor handling that you'll commonly need.
+
+Prepare the sequence of processing steps necessary for your problem. A processor step is a class that implements the following methods:
+
+- `__call__`: implements the processing step for the input transition.
+- `get_config`: gets the configuration of the processor step.
+- `state_dict`: gets the state of the processor step.
+- `load_state_dict`: loads the state of the processor step.
+- `reset`: resets the state of the processor step.
+- `feature_contract`: displays the modification to the feature space during the processor step.
+
+### Implement the `__call__` method
+
+The `__call__` method is the core of your processor step. It takes an `EnvTransition` and returns a modified `EnvTransition`. Here's how the `NormalizerProcessorStep` works:
+
+```python
+@dataclass
+@ProcessorStepRegistry.register("normalizer_processor")
+class NormalizerProcessorStep(ProcessorStep):
+ """Normalize observations/actions using dataset statistics."""
+
+ features: dict[str, PolicyFeature]
+ norm_map: dict[FeatureType, NormalizationMode]
+ stats: dict[str, dict[str, Any]] | None = None
+ eps: float = 1e-8
+ _tensor_stats: dict = field(default_factory=dict, init=False, repr=False)
+
+ def __post_init__(self):
+ """Convert stats to tensors for efficient computation."""
+ self.stats = self.stats or {}
+ self._tensor_stats = to_tensor(self.stats, device=self.device, dtype=torch.float32)
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ new_transition = transition.copy()
+ # Normalize observations
+ # ...
+ # Normalize action
+ # ...
+ return new_transition
+
+```
+
+See the full implementation in `src/lerobot/processor/normalize_processor.py` for complete details.
+
+**Key principles:**
+
+- **Always use `transition.copy()`** to avoid side effects
+- **Handle both observations and actions** consistently
+- **Separate config from state**: `get_config()` returns JSON-serializable params, `state_dict()` returns tensors
+- **Convert stats to tensors** in `__post_init__()` for efficient computation
+
+### Configuration and State Management
+
+Processors support serialization through three methods that separate configuration from tensor state. The `NormalizerProcessorStep` demonstrates this perfectly - it carries dataset statistics (tensors) in its state, and hyperparameters in its config:
+
+```python
+# Continuing the NormalizerProcessorStep example...
+
+def get_config(self) -> dict[str, Any]:
+ """JSON-serializable configuration (no tensors)."""
+ return {
+ "eps": self.eps,
+ "features": {k: {"type": v.type.value, "shape": v.shape} for k, v in self.features.items()},
+ "norm_map": {ft.value: nm.value for ft, nm in self.norm_map.items()},
+ # ...
+ }
+
+def state_dict(self) -> dict[str, torch.Tensor]:
+ """Tensor state only (e.g., dataset statistics)."""
+ flat: dict[str, torch.Tensor] = {}
+ for key, sub in self._tensor_stats.items():
+ for stat_name, tensor in sub.items():
+ flat[f"{key}.{stat_name}"] = tensor.cpu() # Always save to CPU
+ return flat
+
+def load_state_dict(self, state: dict[str, torch.Tensor]) -> None:
+ """Restore tensor state at runtime."""
+ self._tensor_stats.clear()
+ for flat_key, tensor in state.items():
+ key, stat_name = flat_key.rsplit(".", 1)
+ # Load to processor's configured device
+ self._tensor_stats.setdefault(key, {})[stat_name] = tensor.to(
+ dtype=torch.float32, device=self.device
+ )
+ # ...
+```
+
+**Usage:**
+
+```python
+# Save (e.g., inside a policy)
+config = normalizer.get_config()
+tensors = normalizer.state_dict()
+
+# Restore (e.g., loading a pretrained policy)
+new_normalizer = NormalizerProcessorStep(**config)
+new_normalizer.load_state_dict(tensors)
+# Now new_normalizer has the same stats and configuration
+```
+
+### Transform features
+
+The `transform_features` method defines how your processor transforms feature names and shapes. This is crucial for policy configuration and debugging.
+
+For `NormalizerProcessorStep`, features are typically preserved unchanged since normalization doesn't alter keys or shapes:
+
+```python
+def transform_features(self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """Normalization preserves all feature definitions."""
+ return features # No changes to feature structure
+ # ...
+```
+
+When your processor renames or reshapes data, implement this method to reflect the mapping for downstream components. For example, a simple rename processor:
+
+```python
+def transform_features(self, features: dict[str, PolicyFeature]) -> dict[str, PolicyFeature]:
+ # Simple renaming
+ if "pixels" in features:
+ features["observation.image"] = features.pop("pixels")
+
+ # Pattern-based renaming
+ for key in list(features.keys()):
+ if key.startswith("env_state."):
+ suffix = key[len("env_state."):]
+ features[f"observation.{suffix}"] = features.pop(key)
+ # ...
+
+ return features
+```
+
+**Key principles:**
+
+- Use `features.pop(old_key)` to remove and get the old feature
+- Use `features[new_key] = old_feature` to add the renamed feature
+- Always return the modified features dictionary
+- Document transformations clearly in the docstring
+
+### Using overrides
+
+You can override step parameters at load-time using `overrides`. This is handy for non-serializable objects or site-specific settings. It works both in policy factories and with `DataProcessorPipeline.from_pretrained(...)`.
+
+**Foundational model adaptation**: This is particularly useful when working with foundational pretrained policies where you rarely have access to the original training statistics. You can inject your own dataset statistics to adapt the normalizer to your specific robot or environment data.
+
+Example: during policy evaluation on the robot, override the device and rename map.
+Use this to run a policy trained on CUDA on a CPU-only robot, or to remap camera keys when the robot uses different names than the dataset.
+
+Direct usage with `from_pretrained`:
+
+```python
+from lerobot.processor import RobotProcessorPipeline
+
+# Load a foundational policy trained on diverse robot data
+# but adapt normalization to your specific robot/environment
+new_stats = LeRobotDataset(repo_id="username/my-dataset").meta.stats
+processor = RobotProcessorPipeline.from_pretrained(
+ "huggingface/foundational-robot-policy", # Pretrained foundation model
+ overrides={
+ "normalizer_processor": {"stats": new_stats}, # Inject your robot's statistics
+ "device_processor": {"device": "cuda:0"}, # registry name for registered steps
+ "rename_processor": {"rename_map": robot_key_map}, # Map your robot's observation keys
+ # ...
+ },
+)
+```
+
+## Best Practices
+
+Based on analysis of all LeRobot processor implementations, here are the key patterns and practices:
+
+### 1. **Safe Data Handling**
+
+Always create copies of input data to avoid unintended side effects. Use `transition.copy()` and `observation.copy()` rather than modifying data in-place. This prevents your processor from accidentally affecting other components in the pipeline.
+
+Check for required data before processing and handle missing data gracefully. If your processor expects certain keys (like `"pixels"` for image processing), validate their presence first. For optional data, use safe access patterns like `transition.get()` and handle `None` values appropriately.
+
+When data validation fails, provide clear, actionable error messages that help users understand what went wrong and how to fix it.
+
+### 2. **Choose Appropriate Base Classes**
+
+LeRobot provides specialized base classes that reduce boilerplate code and ensure consistency. Use `ObservationProcessorStep` when you only need to modify observations, `ActionProcessorStep` for action-only processing, and `RobotActionProcessorStep` specifically for dictionary-based robot actions.
+
+Only inherit directly from `ProcessorStep` when you need full control over the entire transition or when processing multiple transition components simultaneously. The specialized base classes handle the transition management for you and provide type safety.
+
+### 3. **Registration and Naming**
+
+Register your processors with descriptive, namespaced names using `@ProcessorStepRegistry.register()`. Use organization prefixes like `"robotics_lab/safety_clipper"` or `"acme_corp/vision_enhancer"` to avoid naming conflicts. Avoid generic names like `"processor"` or `"step"` that could clash with other implementations.
+
+Good registration makes your processors discoverable and enables clean serialization/deserialization when saving and loading pipelines.
+
+### 4. **State Management Patterns**
+
+Distinguish between configuration parameters (JSON-serializable values) and internal state (tensors, buffers). Use dataclass fields with `init=False, repr=False` for internal state that shouldn't appear in the constructor or string representation.
+
+Implement the `reset()` method to clear internal state between episodes. This is crucial for stateful processors that accumulate data over time, like moving averages or temporal filters.
+
+Remember that `get_config()` should only return JSON-serializable configuration, while `state_dict()` handles tensor state separately.
+
+### 5. **Input Validation and Error Handling**
+
+Validate input types and shapes before processing. Check tensor properties like `dtype` and dimensions to ensure compatibility with your algorithms. For robot actions, verify that required pose components or joint values are present and within expected ranges.
+
+Use early returns for edge cases where no processing is needed. Provide clear, descriptive error messages that include the expected vs. actual data types or shapes. This makes debugging much easier for users.
+
+### 6. **Device and Dtype Awareness**
+
+Design your processors to automatically adapt to the device and dtype of input tensors. Internal tensors (like normalization statistics) should match the input tensor's device and dtype to ensure compatibility with multi-GPU training, mixed precision, and distributed setups.
+
+Implement a `to()` method that moves your processor's internal state to the specified device. Check device/dtype compatibility at runtime and automatically migrate internal state when needed. This pattern enables seamless operation across different hardware configurations without manual intervention.
+
+## Conclusion
+
+You now have all the tools to implement custom processors in LeRobot! The key steps are:
+
+1. **Define your processor** as a dataclass with the required methods (`__call__`, `get_config`, `state_dict`, `load_state_dict`, `reset`, `transform_features`)
+2. **Register it** using `@ProcessorStepRegistry.register("name")` for discoverability
+3. **Integrate it** into a `DataProcessorPipeline` with other processing steps
+4. **Use base classes** like `ObservationProcessorStep` when possible to reduce boilerplate
+5. **Implement device/dtype awareness** to support multi-GPU and mixed precision setups
+
+The processor system is designed to be modular and composable, allowing you to build complex data processing pipelines from simple, focused components. Whether you're preprocessing sensor data for training or post-processing model outputs for robot execution, custom processors give you the flexibility to handle any data transformation your robotics application requires.
+
+Key principles for robust processors:
+
+- **Device/dtype adaptation**: Internal tensors should match input tensors
+- **Clear error messages**: Help users understand what went wrong
+- **Base class usage**: Leverage specialized base classes to reduce boilerplate
+- **Feature contracts**: Declare data structure changes with `transform_features()`
+
+Start simple, test thoroughly, and ensure your processors work seamlessly across different hardware configurations!
diff --git a/lerobot/docs/source/index.mdx b/lerobot/docs/source/index.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..5f214f9a2dcca17df60ba56842e0556d08737cfb
--- /dev/null
+++ b/lerobot/docs/source/index.mdx
@@ -0,0 +1,23 @@
+
+
+# LeRobot
+
+**State-of-the-art machine learning for real-world robotics**
+
+π€ LeRobot aims to provide models, datasets, and tools for real-world robotics in PyTorch. The goal is to lower the barrier for entry to robotics so that everyone can contribute and benefit from sharing datasets and pretrained models.
+
+π€ LeRobot contains state-of-the-art approaches that have been shown to transfer to the real-world with a focus on imitation learning and reinforcement learning.
+
+π€ LeRobot already provides a set of pretrained models, datasets with human collected demonstrations, and simulated environments so that everyone can get started.
+
+π€ LeRobot hosts pretrained models and datasets on the LeRobot HuggingFace page.
+
+Join the LeRobot community on [Discord](https://discord.gg/s3KuuzsPFb)
diff --git a/lerobot/docs/source/installation.mdx b/lerobot/docs/source/installation.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..3506466af9e289631962fb1f897f5e761cc0a418
--- /dev/null
+++ b/lerobot/docs/source/installation.mdx
@@ -0,0 +1,127 @@
+# Installation
+
+## Install [`miniforge`](https://conda-forge.org/download/)
+
+```bash
+wget "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
+bash Miniforge3-$(uname)-$(uname -m).sh
+```
+
+## Environment Setup
+
+Create a virtual environment with Python 3.10, using conda:
+
+```bash
+conda create -y -n lerobot python=3.10
+```
+
+Then activate your conda environment, you have to do this each time you open a shell to use lerobot:
+
+```bash
+conda activate lerobot
+```
+
+When using `conda`, install `ffmpeg` in your environment:
+
+```bash
+conda install ffmpeg -c conda-forge
+```
+
+> [!TIP]
+> This usually installs `ffmpeg 7.X` for your platform compiled with the `libsvtav1` encoder. If `libsvtav1` is not supported (check supported encoders with `ffmpeg -encoders`), you can:
+>
+> - _[On any platform]_ Explicitly install `ffmpeg 7.X` using:
+>
+> ```bash
+> conda install ffmpeg=7.1.1 -c conda-forge
+> ```
+>
+> - _[On Linux only]_ If you want to bring your own ffmpeg: Install [ffmpeg build dependencies](https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu#GettheDependencies) and [compile ffmpeg from source with libsvtav1](https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu#libsvtav1), and make sure you use the corresponding ffmpeg binary to your install with `which ffmpeg`.
+
+## Install LeRobot π€
+
+### From Source
+
+First, clone the repository and navigate into the directory:
+
+```bash
+git clone https://github.com/huggingface/lerobot.git
+cd lerobot
+```
+
+Then, install the library in editable mode. This is useful if you plan to contribute to the code.
+
+```bash
+pip install -e .
+```
+
+### Installation from PyPI
+
+**Core Library:**
+Install the base package with:
+
+```bash
+pip install lerobot
+```
+
+_This installs only the default dependencies._
+
+**Extra Features:**
+To install additional functionality, use one of the following:
+
+```bash
+pip install 'lerobot[all]' # All available features
+pip install 'lerobot[aloha,pusht]' # Specific features (Aloha & Pusht)
+pip install 'lerobot[feetech]' # Feetech motor support
+```
+
+_Replace `[...]` with your desired features._
+
+**Available Tags:**
+For a full list of optional dependencies, see:
+https://pypi.org/project/lerobot/
+
+> [!NOTE]
+> For lerobot 0.4.0, if you want to install pi, you will have to do: `pip install "lerobot[pi]@git+https://github.com/huggingface/lerobot.git"`
+
+### Troubleshooting
+
+If you encounter build errors, you may need to install additional dependencies: `cmake`, `build-essential`, and `ffmpeg libs`.
+To install these for linux run:
+
+```bash
+sudo apt-get install cmake build-essential python3-dev pkg-config libavformat-dev libavcodec-dev libavdevice-dev libavutil-dev libswscale-dev libswresample-dev libavfilter-dev
+```
+
+For other systems, see: [Compiling PyAV](https://pyav.org/docs/develop/overview/installation.html#bring-your-own-ffmpeg)
+
+## Optional dependencies
+
+LeRobot provides optional extras for specific functionalities. Multiple extras can be combined (e.g., `.[aloha,feetech]`). For all available extras, refer to `pyproject.toml`.
+
+### Simulations
+
+Install environment packages: `aloha` ([gym-aloha](https://github.com/huggingface/gym-aloha)), or `pusht` ([gym-pusht](https://github.com/huggingface/gym-pusht))
+Example:
+
+```bash
+pip install -e ".[aloha]" # or "[pusht]" for example
+```
+
+### Motor Control
+
+For Koch v1.1 install the Dynamixel SDK, for SO100/SO101/Moss install the Feetech SDK.
+
+```bash
+pip install -e ".[feetech]" # or "[dynamixel]" for example
+```
+
+### Experiment Tracking
+
+To use [Weights and Biases](https://docs.wandb.ai/quickstart) for experiment tracking, log in with
+
+```bash
+wandb login
+```
+
+You can now assemble your robot if it's not ready yet, look for your robot type on the left. Then follow the link below to use Lerobot with your robot.
diff --git a/lerobot/docs/source/integrate_hardware.mdx b/lerobot/docs/source/integrate_hardware.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..c37c96612402c998dd07df1d000edf0a8a9a952d
--- /dev/null
+++ b/lerobot/docs/source/integrate_hardware.mdx
@@ -0,0 +1,476 @@
+# Bring Your Own Hardware
+
+This tutorial will explain how to integrate your own robot design into the LeRobot ecosystem and have it access all of our tools (data collection, control pipelines, policy training and inference).
+
+To that end, we provide the [`Robot`](https://github.com/huggingface/lerobot/blob/main/src/lerobot/robots/robot.py) base class in the LeRobot which specifies a standard interface for physical robot integration. Let's see how to implement it.
+
+## Prerequisites
+
+- Your own robot which exposes a communication interface (e.g. serial, CAN, TCP)
+- A way to read sensor data and send motor commands programmatically, e.g. manufacturer's SDK or API, or your own protocol implementation.
+- LeRobot installed in your environment. Follow our [Installation Guide](./installation).
+
+## Choose your motors
+
+If you're using Feetech or Dynamixel motors, LeRobot provides built-in bus interfaces:
+
+- [`FeetechMotorsBus`](https://github.com/huggingface/lerobot/blob/main/src/lerobot/motors/feetech/feetech.py) β for controlling Feetech servos
+- [`DynamixelMotorsBus`](https://github.com/huggingface/lerobot/blob/main/src/lerobot/motors/dynamixel/dynamixel.py) β for controlling Dynamixel servos
+
+Please refer to the [`MotorsBus`](https://github.com/huggingface/lerobot/blob/main/src/lerobot/motors/motors_bus.py) abstract class to learn about its API.
+For a good example of how it can be used, you can have a look at our own [SO101 follower implementation](https://github.com/huggingface/lerobot/blob/main/src/lerobot/robots/so_follower/so101_follower/so101_follower.py)
+
+Use these if compatible. Otherwise, you'll need to find or write a Python interface (not covered in this tutorial):
+
+- Find an existing SDK in Python (or use bindings to C/C++)
+- Or implement a basic communication wrapper (e.g., via pyserial, socket, or CANopen)
+
+You're not aloneβmany community contributions use custom boards or firmware!
+
+For Feetech and Dynamixel, we currently support these servos: - Feetech: - STS & SMS series (protocol 0): `sts3215`, `sts3250`, `sm8512bl` - SCS series (protocol 1): `scs0009` - Dynamixel (protocol 2.0 only): `xl330-m077`, `xl330-m288`, `xl430-w250`, `xm430-w350`, `xm540-w270`, `xc430-w150`
+
+If you are using Feetech or Dynamixel servos that are not in this list, you can add those in the [Feetech table](https://github.com/huggingface/lerobot/blob/main/src/lerobot/motors/feetech/tables.py) or [Dynamixel table](https://github.com/huggingface/lerobot/blob/main/src/lerobot/motors/dynamixel/tables.py). Depending on the model, this will require you to add model-specific information. In most cases though, there shouldn't be a lot of additions to do.
+
+In the next sections, we'll use a `FeetechMotorsBus` as the motors interface for the examples. Replace it and adapt to your motors if necessary.
+
+## Step 1: Subclass the `Robot` Interface
+
+Youβll first need to specify the config class and a string identifier (`name`) for your robot. If your robot has special needs that you'd like to be able to change easily, it should go here (e.g. port/address, baudrate).
+
+Here, we'll add the port name and one camera by default for our robot:
+
+
+```python
+from dataclasses import dataclass, field
+
+from lerobot.cameras import CameraConfig
+from lerobot.cameras.opencv import OpenCVCameraConfig
+from lerobot.robots import RobotConfig
+
+
+@RobotConfig.register_subclass("my_cool_robot")
+@dataclass
+class MyCoolRobotConfig(RobotConfig):
+ port: str
+ cameras: dict[str, CameraConfig] = field(
+ default_factory={
+ "cam_1": OpenCVCameraConfig(
+ index_or_path=2,
+ fps=30,
+ width=480,
+ height=640,
+ ),
+ }
+ )
+```
+
+
+[Cameras tutorial](./cameras) to understand how to detect and add your camera.
+
+Next, we'll create our actual robot class which inherits from `Robot`. This abstract class defines a contract you must follow for your robot to be usable with the rest of the LeRobot tools.
+
+Here we'll create a simple 5-DoF robot with one camera. It could be a simple arm but notice that the `Robot` abstract class does not assume anything on your robot's form factor. You can let you imagination run wild when designing new robots!
+
+
+```python
+from lerobot.cameras import make_cameras_from_configs
+from lerobot.motors import Motor, MotorNormMode
+from lerobot.motors.feetech import FeetechMotorsBus
+from lerobot.robots import Robot
+
+class MyCoolRobot(Robot):
+ config_class = MyCoolRobotConfig
+ name = "my_cool_robot"
+
+ def __init__(self, config: MyCoolRobotConfig):
+ super().__init__(config)
+ self.bus = FeetechMotorsBus(
+ port=self.config.port,
+ motors={
+ "joint_1": Motor(1, "sts3250", MotorNormMode.RANGE_M100_100),
+ "joint_2": Motor(2, "sts3215", MotorNormMode.RANGE_M100_100),
+ "joint_3": Motor(3, "sts3215", MotorNormMode.RANGE_M100_100),
+ "joint_4": Motor(4, "sts3215", MotorNormMode.RANGE_M100_100),
+ "joint_5": Motor(5, "sts3215", MotorNormMode.RANGE_M100_100),
+ },
+ calibration=self.calibration,
+ )
+ self.cameras = make_cameras_from_configs(config.cameras)
+```
+
+
+## Step 2: Define Observation and Action Features
+
+These two properties define the _interface contract_ between your robot and tools that consume it (such as data collection or learning pipelines).
+
+> [!WARNING]
+> Note that these properties must be callable even if the robot is not yet connected, so avoid relying on runtime hardware state to define them.
+
+### `observation_features`
+
+This property should return a dictionary describing the structure of sensor outputs from your robot. The keys match what `get_observation()` returns, and the values describe either the shape (for arrays/images) or the type (for simple values).
+
+Example for our 5-DoF arm with one camera:
+
+
+```python
+@property
+def _motors_ft(self) -> dict[str, type]:
+ return {
+ "joint_1.pos": float,
+ "joint_2.pos": float,
+ "joint_3.pos": float,
+ "joint_4.pos": float,
+ "joint_5.pos": float,
+ }
+
+@property
+def _cameras_ft(self) -> dict[str, tuple]:
+ return {
+ cam: (self.cameras[cam].height, self.cameras[cam].width, 3) for cam in self.cameras
+ }
+
+@property
+def observation_features(self) -> dict:
+ return {**self._motors_ft, **self._cameras_ft}
+```
+
+
+In this case, observations consist of a simple dict storing each motor's position and a camera image.
+
+### `action_features`
+
+This property describes the commands your robot expects via `send_action()`. Again, keys must match the expected input format, and values define the shape/type of each command.
+
+Here, we simply use the same joints proprioceptive features (`self._motors_ft`) as with `observation_features`: the action sent will simply the goal position for each motor.
+
+
+```python
+def action_features(self) -> dict:
+ return self._motors_ft
+```
+
+
+## Step 3: Handle Connection and Disconnection
+
+These methods should handle opening and closing communication with your hardware (e.g. serial ports, CAN interfaces, USB devices, cameras).
+
+### `is_connected`
+
+This property should simply reflect that communication with the robot's hardware is established. When this property is `True`, it should be possible to read and write to the hardware using `get_observation()` and `send_action()`.
+
+
+```python
+@property
+def is_connected(self) -> bool:
+ return self.bus.is_connected and all(cam.is_connected for cam in self.cameras.values())
+```
+
+
+### `connect()`
+
+This method should establish communication with the hardware. Moreover, if your robot needs calibration and is not calibrated, it should start a calibration procedure by default. If your robot needs some specific configuration, this should also be called here.
+
+
+```python
+def connect(self, calibrate: bool = True) -> None:
+ self.bus.connect()
+ if not self.is_calibrated and calibrate:
+ self.calibrate()
+
+ for cam in self.cameras.values():
+ cam.connect()
+
+ self.configure()
+```
+
+
+### `disconnect()`
+
+This method should gracefully terminate communication with the hardware: free any related resources (threads or processes), close ports, etc.
+
+Here, we already handle this in our `MotorsBus` and `Camera` classes so we just need to call their own `disconnect()` methods:
+
+
+```python
+def disconnect(self) -> None:
+ self.bus.disconnect()
+ for cam in self.cameras.values():
+ cam.disconnect()
+```
+
+
+## Step 4: Support Calibration and Configuration
+
+LeRobot supports saving and loading calibration data automatically. This is useful for joint offsets, zero positions, or sensor alignment.
+
+> Note that depending on your hardware, this may not apply. If that's the case, you can simply leave these methods as no-ops:
+
+
+```python
+@property
+def is_calibrated(self) -> bool:
+ return True
+
+def calibrate(self) -> None:
+ pass
+```
+
+
+### `is_calibrated`
+
+This should reflect whether your robot has the required calibration loaded.
+
+
+```python
+@property
+def is_calibrated(self) -> bool:
+ return self.bus.is_calibrated
+```
+
+
+### `calibrate()`
+
+The goal of the calibration is twofold:
+
+- Know the physical range of motion of each motors in order to only send commands within this range.
+- Normalize raw motors positions to sensible continuous values (e.g. percentages, degrees) instead of arbitrary discrete value dependant on the specific motor used that will not replicate elsewhere.
+
+It should implement the logic for calibration (if relevant) and update the `self.calibration` dictionary. If you are using Feetech or Dynamixel motors, our bus interfaces already include methods to help with this.
+
+
+```python
+def calibrate(self) -> None:
+ self.bus.disable_torque()
+ for motor in self.bus.motors:
+ self.bus.write("Operating_Mode", motor, OperatingMode.POSITION.value)
+
+ input(f"Move {self} to the middle of its range of motion and press ENTER....")
+ homing_offsets = self.bus.set_half_turn_homings()
+
+ print(
+ "Move all joints sequentially through their entire ranges "
+ "of motion.\nRecording positions. Press ENTER to stop..."
+ )
+ range_mins, range_maxes = self.bus.record_ranges_of_motion()
+
+ self.calibration = {}
+ for motor, m in self.bus.motors.items():
+ self.calibration[motor] = MotorCalibration(
+ id=m.id,
+ drive_mode=0,
+ homing_offset=homing_offsets[motor],
+ range_min=range_mins[motor],
+ range_max=range_maxes[motor],
+ )
+
+ self.bus.write_calibration(self.calibration)
+ self._save_calibration()
+ print("Calibration saved to", self.calibration_fpath)
+```
+
+
+### `configure()`
+
+Use this to set up any configuration for your hardware (servos control modes, controller gains, etc.). This should usually be run at connection time and be idempotent.
+
+
+```python
+def configure(self) -> None:
+ with self.bus.torque_disabled():
+ self.bus.configure_motors()
+ for motor in self.bus.motors:
+ self.bus.write("Operating_Mode", motor, OperatingMode.POSITION.value)
+ self.bus.write("P_Coefficient", motor, 16)
+ self.bus.write("I_Coefficient", motor, 0)
+ self.bus.write("D_Coefficient", motor, 32)
+```
+
+
+## Step 5: Implement Sensors Reading and Action Sending
+
+These are the most important runtime functions: the core I/O loop.
+
+### `get_observation()`
+
+Returns a dictionary of sensor values from the robot. These typically include motor states, camera frames, various sensors, etc. In the LeRobot framework, these observations are what will be fed to a policy in order to predict the actions to take. The dictionary keys and structure must match `observation_features`.
+
+
+```python
+def get_observation(self) -> dict[str, Any]:
+ if not self.is_connected:
+ raise ConnectionError(f"{self} is not connected.")
+
+ # Read arm position
+ obs_dict = self.bus.sync_read("Present_Position")
+ obs_dict = {f"{motor}.pos": val for motor, val in obs_dict.items()}
+
+ # Capture images from cameras
+ for cam_key, cam in self.cameras.items():
+ obs_dict[cam_key] = cam.async_read()
+
+ return obs_dict
+```
+
+
+### `send_action()`
+
+Takes a dictionary that matches `action_features`, and sends it to your hardware. You can add safety limits (clipping, smoothing) and return what was actually sent.
+
+For simplicity, we won't be adding any modification of the actions in our example here.
+
+
+```python
+def send_action(self, action: dict[str, Any]) -> dict[str, Any]:
+ goal_pos = {key.removesuffix(".pos"): val for key, val in action.items()}
+
+ # Send goal position to the arm
+ self.bus.sync_write("Goal_Position", goal_pos)
+
+ return action
+```
+
+
+## Adding a Teleoperator
+
+For implementing teleoperation devices, we also provide a [`Teleoperator`](https://github.com/huggingface/lerobot/blob/main/src/lerobot/teleoperators/teleoperator.py) base class. This class is very similar to the `Robot` base class and also doesn't assume anything on form factor.
+
+The main differences are in the I/O functions: a teleoperator allows you to produce action via `get_action` and can receive feedback actions via `send_feedback`. Feedback could be anything controllable on the teleoperation device that could help the person controlling it understand the consequences of the actions sent. Think motion/force feedback on a leader arm, vibrations on a gamepad controller for example. To implement a teleoperator, you can follow this same tutorial and adapt it for these two methods.
+
+## Using Your Own `LeRobot` Devices π
+
+You can easily extend `lerobot` with your own custom hardwareβbe it a camera, robot, or teleoperation deviceβby creating a separate, installable Python package. If you follow a few simple conventions, the `lerobot` command-line tools (like `lerobot-teleop` and `lerobot-record`) will **automatically discover and integrate your creations** without requiring any changes to the `lerobot` source code.
+
+This guide outlines the conventions your plugin must follow.
+
+### The 4 Core Conventions
+
+To ensure your custom device is discoverable, you must adhere to the following four rules.
+
+#### 1\. Create an Installable Package with a Specific Prefix
+
+Your project must be a standard, installable Python package. Crucially, the name of your package (as defined in `pyproject.toml` or `setup.py`) must begin with one of these prefixes:
+
+- `lerobot_robot_` for a robot.
+- `lerobot_camera_` for a camera.
+- `lerobot_teleoperator_` for a teleoperation device.
+
+This prefix system is how `lerobot` automatically finds your plugin in the Python environment.
+
+#### 2\. Follow the `SomethingConfig`/`Something` Naming Pattern
+
+Your device's implementation class must be named after its configuration class, simply by removing the `Config` suffix.
+
+- **Config Class:** `MyAwesomeTeleopConfig`
+- **Device Class:** `MyAwesomeTeleop`
+
+#### 3\. Place Your Files in a Predictable Structure
+
+The device class (`MyAwesomeTeleop`) must be located in a predictable module relative to its configuration class (`MyAwesomeTeleopConfig`). `lerobot` will automatically search in these locations:
+
+- In the **same module** as the config class.
+- In a **submodule named after the device** (e.g., `my_awesome_teleop.py`).
+
+The recommended and simplest structure is to place them in separate, clearly named files within the same directory.
+
+#### 4\. Expose Classes in `__init__.py`
+
+Your package's `__init__.py` file should import and expose both the configuration and the device classes, making them easily accessible.
+
+### Putting It All Together: A Complete Example
+
+Let's create a new teleoperator called `my_awesome_teleop`.
+
+#### Directory Structure
+
+Here is what the project folder should look like. The package name, `lerobot_teleoperator_my_awesome_teleop`, follows **Convention \#1**.
+
+```
+lerobot_teleoperator_my_awesome_teleop/
+βββ pyproject.toml # (or setup.py) lists lerobot as a dependency
+βββ lerobot_teleoperator_my_awesome_teleop/
+ βββ __init__.py
+ βββ config_my_awesome_teleop.py
+ βββ my_awesome_teleop.py
+```
+
+#### File Contents
+
+- **`config_my_awesome_teleop.py`**: Defines the configuration class. Note the `Config` suffix (**Convention \#2**).
+
+ ```python
+ from dataclasses import dataclass
+
+ from lerobot.teleoperators.config import TeleoperatorConfig
+
+ @TeleoperatorConfig.register_subclass("my_awesome_teleop")
+ @dataclass
+ class MyAwesomeTeleopConfig(TeleoperatorConfig):
+ # Your configuration fields go here
+ port: str = "192.168.1.1"
+ ```
+
+- **`my_awesome_teleop.py`**: Implements the device. The class name `MyAwesomeTeleop` matches its config class name (**Convention \#2**). This file structure adheres to **Convention \#3**.
+
+ ```python
+ from lerobot.teleoperators.teleoperator import Teleoperator
+
+ from .config_my_awesome_teleop import MyAwesomeTeleopConfig
+
+ class MyAwesomeTeleop(Teleoperator):
+ config_class = MyAwesomeTeleopConfig
+ name = "my_awesome_teleop"
+
+ def __init__(self, config: MyAwesomeTeleopConfig):
+ super().__init__(config)
+ self.config = config
+
+ # Your device logic (e.g., connect) goes here
+ ```
+
+- **`__init__.py`**: Exposes the key classes (**Convention \#4**).
+
+ ```python
+ from .config_my_awesome_teleop import MyAwesomeTeleopConfig
+ from .my_awesome_teleop import MyAwesomeTeleop
+ ```
+
+### Installation and Usage
+
+1. **Install your new plugin in your Python environment.** You can install your local plugin package using `pip`'s editable mode or from PyPi.
+
+ ```bash
+ # Locally
+ # Navigate to your plugin's root directory and install it
+ cd lerobot_teleoperator_my_awesome_teleop
+ pip install -e .
+
+ # From PyPi
+ pip install lerobot_teleoperator_my_awesome_teleop
+ ```
+
+2. **Use it directly from the command line.** Now, you can use your custom device by referencing its type.
+
+ ```bash
+ lerobot-teleoperate --teleop.type=my_awesome_teleop \
+ # other arguments
+ ```
+
+And that's it\! Your custom device is now fully integrated.
+
+### Looking for an example ?
+
+Check out these two packages from the community:
+
+- https://github.com/SpesRobotics/lerobot-robot-xarm
+- https://github.com/SpesRobotics/lerobot-teleoperator-teleop
+
+## Wrapping Up
+
+Once your robot class is complete, you can leverage the LeRobot ecosystem:
+
+- Control your robot with available teleoperators or integrate directly your teleoperating device
+- Record training data and visualize it
+- Integrate it into RL or imitation learning pipelines
+
+Don't hesitate to reach out to the community for help on our [Discord](https://discord.gg/s3KuuzsPFb) π€
diff --git a/lerobot/docs/source/introduction_processors.mdx b/lerobot/docs/source/introduction_processors.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..cd579b22d150c57fda0ef3303a60e08067d11f03
--- /dev/null
+++ b/lerobot/docs/source/introduction_processors.mdx
@@ -0,0 +1,314 @@
+# Introduction to Processors
+
+In robotics, there's a fundamental mismatch between the data that robots and humans produce and what machine learning models expect.
+Robots output raw sensor data like camera images and joint positions that need normalization, batching, and device placement before models can process them.
+Language instructions from humans must be tokenized into numerical representations, and different robots use different coordinate systems that need standardization.
+
+The challenge extends to model outputs as well.
+Models might output end-effector positions while robots need joint-space commands, or teleoperators produce relative movements while robots expect absolute commands.
+Model predictions are often normalized and need conversion back to real-world scales.
+
+Cross-domain translation adds another layer of complexity.
+Training data from one robot setup needs adaptation for deployment on different hardware, models trained with specific camera configurations must work with new arrangements, and datasets with different naming conventions need harmonization.
+
+**That's where processors come in.** They serve as universal translators that bridge these gaps, ensuring seamless data flow from sensors to models to actuators.
+Processors handle all the preprocessing and postprocessing steps needed to convert raw environment data into model-ready inputs and vice versa.
+
+This means that your favorite policy can be used like this:
+
+```python
+import torch
+
+from lerobot.datasets.lerobot_dataset import LeRobotDataset
+from lerobot.policies.factory import make_pre_post_processors
+from lerobot.policies.your_policy import YourPolicy
+from lerobot.processor.pipeline import RobotProcessorPipeline, PolicyProcessorPipeline
+dataset = LeRobotDataset("hf_user/dataset", episodes=[0])
+sample = dataset[10]
+
+model = YourPolicy.from_pretrained(
+ "hf_user/model",
+)
+model.eval()
+model.to("cuda")
+preprocessor, postprocessor = make_pre_post_processors(model.config, pretrained_path="hf_user/model", dataset_stats=dataset.meta.stats)
+
+preprocessed_sample = preprocessor(sample)
+action = model.select_action(preprocessed_sample)
+postprocessed_action = postprocessor(action)
+```
+
+## What are Processors?
+
+In robotics, data comes in many forms: images from cameras, joint positions from sensors, text instructions from users, and more. Each type of data requires specific transformations before a model can use it effectively. Models need this data to be:
+
+- **Normalized**: Scaled to appropriate ranges for neural network processing
+- **Batched**: Organized with proper dimensions for batch processing
+- **Tokenized**: Text converted to numerical representations
+- **Device-placed**: Moved to the right hardware (CPU/GPU)
+- **Type-converted**: Cast to appropriate data types
+
+Processors handle these transformations through composable, reusable steps that can be chained together into pipelines. Think of them as a modular assembly line where each station performs a specific transformation on your data.
+
+## Core Concepts
+
+### EnvTransition: The Universal Data Container
+
+The `EnvTransition` is the fundamental data structure that flows through all processors.
+It's a typed dictionary that represents a complete robot-environment interaction:
+
+- **OBSERVATION**: All sensor data (images, states, proprioception)
+- **ACTION**: The action to execute or that was executed
+- **REWARD**: Reinforcement learning signal
+- **DONE/TRUNCATED**: Episode boundary indicators
+- **INFO**: Arbitrary metadata
+- **COMPLEMENTARY_DATA**: Task descriptions, indices, padding flags, inter-step data
+
+### ProcessorStep: The Building Block
+
+A `ProcessorStep` is a single transformation unit that processes transitions. It's an abstract base class with two required methods:
+
+```python
+from lerobot.processor import ProcessorStep, EnvTransition
+
+class MyProcessorStep(ProcessorStep):
+ """Example processor step - inherit and implement abstract methods."""
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Transform the transition - REQUIRED abstract method."""
+ # Your processing logic here
+ return transition
+
+ def transform_features(self, features):
+ """Declare how this step transforms feature shapes/types - REQUIRED abstract method."""
+ return features # Most processors return features unchanged
+```
+
+`__call__` is the core of your processor step. It takes an `EnvTransition` and returns a modified `EnvTransition`.
+
+`transform_features` is used to declare how this step transforms feature shapes/types.
+
+### DataProcessorPipeline: The Generic Orchestrator
+
+The `DataProcessorPipeline[TInput, TOutput]` chains multiple `ProcessorStep` instances together:
+
+```python
+from lerobot.processor import RobotProcessorPipeline, PolicyProcessorPipeline
+
+# For robot hardware (unbatched data)
+robot_processor = RobotProcessorPipeline[RobotAction, RobotAction](
+ steps=[step1, step2, step3],
+ name="robot_pipeline"
+)
+
+# For model training/inference (batched data)
+policy_processor = PolicyProcessorPipeline[dict[str, Any], dict[str, Any]](
+ steps=[step1, step2, step3],
+ name="policy_pipeline"
+)
+```
+
+## RobotProcessorPipeline vs PolicyProcessorPipeline
+
+The key distinction is in the data structures they handle:
+
+| Aspect | RobotProcessorPipeline | PolicyProcessorPipeline |
+| --------------- | -------------------------------------------- | ---------------------------------------- |
+| **Input** | `dict[str, Any]` - Individual robot values | `dict[str, Any]` - Batched tensors |
+| **Output** | `dict[str, Any]` - Individual robot commands | `torch.Tensor` - Policy predictions |
+| **Use Case** | Real-time robot control | Model training/inference |
+| **Data Format** | Unbatched, heterogeneous | Batched, homogeneous |
+| **Examples** | `{"joint_1": 0.5}` | `{"observation.state": tensor([[0.5]])}` |
+
+**Use `RobotProcessorPipeline`** for robot hardware interfaces:
+
+```python
+# Robot data structures: dict[str, Any] for observations and actions
+robot_obs: dict[str, Any] = {
+ "joint_1": 0.5, # Individual joint values
+ "joint_2": -0.3,
+ "camera_0": image_array # Raw camera data
+}
+
+robot_action: dict[str, Any] = {
+ "joint_1": 0.2, # Target joint positions
+ "joint_2": 0.1,
+ "gripper": 0.8
+}
+```
+
+**Use `PolicyProcessorPipeline`** for model training and batch processing:
+
+```python
+# Policy data structures: batch dicts and tensors
+policy_batch: dict[str, Any] = {
+ "observation.state": torch.tensor([[0.5, -0.3]]), # Batched states
+ "observation.images.camera0": torch.tensor(...), # Batched images
+ "action": torch.tensor([[0.2, 0.1, 0.8]]) # Batched actions
+}
+
+policy_action: torch.Tensor = torch.tensor([[0.2, 0.1, 0.8]]) # Model output tensor
+```
+
+## Converter Functions
+
+LeRobot provides converter functions to bridge different data formats in `lerobot.processor.converters`. These functions handle the crucial translations between robot hardware data structures, policy model formats, and the internal `EnvTransition` representation that flows through processor pipelines.
+
+| Category | Function | Description |
+| ------------------------------ | ----------------------------- | ------------------------------- |
+| **Robot Hardware Converters** | `robot_action_to_transition` | Robot dict β EnvTransition |
+| | `observation_to_transition` | Robot obs β EnvTransition |
+| | `transition_to_robot_action` | EnvTransition β Robot dict |
+| **Policy/Training Converters** | `batch_to_transition` | Batch dict β EnvTransition |
+| | `transition_to_batch` | EnvTransition β Batch dict |
+| | `policy_action_to_transition` | Policy tensor β EnvTransition |
+| | `transition_to_policy_action` | EnvTransition β Policy tensor |
+| **Utilities** | `create_transition` | Build transitions with defaults |
+| | `identity_transition` | Pass-through converter |
+
+The key insight is that **robot hardware converters** work with individual values and dictionaries, while **policy/training converters** work with batched tensors and model outputs. The converter functions automatically handle the structural differences, so your processor steps can focus on the core transformations without worrying about data format compatibility.
+
+## Processor Examples
+
+The following examples demonstrate real-world processor configurations for policy training and inference.
+
+Here is an example processor for policy training and inference:
+
+```python
+# Training data preprocessing (optimized order for GPU performance)
+training_preprocessor = PolicyProcessorPipeline[dict[str, Any], dict[str, Any]](
+ steps=[
+ RenameObservationsProcessorStep(rename_map={}), # Standardize keys
+ AddBatchDimensionProcessorStep(), # Add batch dims
+ TokenizerProcessorStep(tokenizer_name="...", ...), # Tokenize language
+ DeviceProcessorStep(device="cuda"), # Move to GPU first
+ NormalizerProcessorStep(features=..., stats=...), # Normalize on GPU
+ ]
+)
+
+# Model output postprocessing
+training_postprocessor = PolicyProcessorPipeline[torch.Tensor, torch.Tensor](
+ steps=[
+ DeviceProcessorStep(device="cpu"), # Move to CPU
+ UnnormalizerProcessorStep(features=..., stats=...), # Denormalize
+ ]
+ to_transition=policy_action_to_transition,
+ to_output=transition_to_policy_action,
+)
+```
+
+### An interaction between a robot and a policy with processors
+
+The most common real-world scenario combines both pipeline types robot hardware generates observations that need policy processing, and policy outputs need robot-compatible postprocessing:
+
+```python
+# Real deployment: Robot sensors β Model β Robot commands
+with torch.no_grad():
+ while not done:
+ raw_obs = robot.get_observation() # dict[str, Any]
+
+ # Add your robot observation to policy observation processor
+
+ policy_input = policy_preprocessor(raw_obs) # Batched dict
+
+ policy_output = policy.select_action(policy_input) # Policy tensor
+
+ policy_action = policy_postprocessor(policy_output)
+
+ # Add your robot action to policy action processor
+
+ robot.send_action(policy_action)
+```
+
+## Feature Contracts: Shape and Type Transformation
+
+Processors don't just transform data - they can also **change the data structure itself**. The `transform_features()` method declares these changes, which is crucial for dataset recording and policy creation.
+
+### Why Feature Contracts Matter
+
+When building datasets or policies, LeRobot needs to know:
+
+- **What data fields will exist** after processing
+- **What shapes and types** each field will have
+- **How to configure models** for the expected data structure
+
+```python
+# Example: A processor that adds velocity to observations
+class VelocityProcessor(ObservationProcessorStep):
+ def observation(self, obs):
+ new_obs = obs.copy()
+ if "observation.state" in obs:
+ # concatenate computed velocity field to the state
+ new_obs["observation.state"] = self._compute_velocity(obs["observation.state"])
+ return new_obs
+
+ def transform_features(self, features):
+ """Declare the new velocity field we're adding."""
+ state_feature = features[PipelineFeatureType.OBSERVATION].get("observation.state")
+ if state_feature:
+ double_shape = (state_feature.shape[0] * 2,) if state_feature.shape else (2,)
+ features[PipelineFeatureType.OBSERVATION]["observation.state"] = PolicyFeature(
+ type=FeatureType.STATE, shape=double_shape
+ )
+ return features
+```
+
+### Feature Specification Functions
+
+`create_initial_features()` and `aggregate_pipeline_dataset_features()` solve a critical dataset creation problem: determining the exact final data structure before any data is processed.
+Since processor pipelines can add new features (like velocity fields), change tensor shapes (like cropping images), or rename keys, datasets need to know the complete output specification upfront to allocate proper storage and define schemas.
+These functions work together by starting with robot hardware specifications (`create_initial_features()`) then simulating the entire pipeline transformation (`aggregate_pipeline_dataset_features()`) to compute the final feature dictionary that gets passed to `LeRobotDataset.create()`, ensuring perfect alignment between what processors output and what datasets expect to store.
+
+```python
+from lerobot.datasets.pipeline_features import aggregate_pipeline_dataset_features
+
+# Start with robot's raw features
+initial_features = create_initial_features(
+ observation=robot.observation_features, # {"joint_1.pos": float, "camera_0": (480,640,3)}
+ action=robot.action_features # {"joint_1.pos": float, "gripper.pos": float}
+)
+
+# Apply processor pipeline to compute final features
+final_features = aggregate_pipeline_dataset_features(
+ pipeline=my_processor_pipeline,
+ initial_features=initial_features,
+ use_videos=True
+)
+
+# Use for dataset creation
+dataset = LeRobotDataset.create(
+ repo_id="my_dataset",
+ features=final_features, # Knows exactly what data to expect
+ ...
+)
+```
+
+## Common Processor Steps
+
+LeRobot provides many registered processor steps. Here are the most commonly used core processors:
+
+### Essential Processors
+
+- **`normalizer_processor`**: Normalize observations/actions using dataset statistics (mean/std or min/max)
+- **`device_processor`**: Move tensors to CPU/GPU with optional dtype conversion
+- **`to_batch_processor`**: Add batch dimensions to transitions for model compatibility
+- **`rename_observations_processor`**: Rename observation keys using mapping dictionaries
+- **`tokenizer_processor`**: Tokenize natural language task descriptions into tokens and attention masks
+
+### Next Steps
+
+- **[Implement Your Own Processor](./implement_your_own_processor)** - Create custom processor steps
+- **[Debug Your Pipeline](./debug_processor_pipeline)** - Troubleshoot and optimize pipelines
+- **[Processors for Robots and Teleoperators](./processors_robots_teleop)** - Real-world integration patterns
+
+## Summary
+
+Processors solve the data translation problem in robotics by providing:
+
+- **Modular transformations**: Composable, reusable processing steps
+- **Type safety**: Generic pipelines with compile-time checking
+- **Performance optimization**: GPU-accelerated operations
+- **Robot/Policy distinction**: Separate pipelines for different data structures
+- **Comprehensive ecosystem**: 30+ registered processors for common tasks
+
+The key insight: `RobotProcessorPipeline` handles unbatched robot hardware data, while `PolicyProcessorPipeline` handles batched model data. Choose the right tool for your data structure!
diff --git a/lerobot/docs/source/koch.mdx b/lerobot/docs/source/koch.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..b31e0b100007f2eb70c428f5ca0e4017b769d725
--- /dev/null
+++ b/lerobot/docs/source/koch.mdx
@@ -0,0 +1,283 @@
+# Koch v1.1
+
+In the steps below, we explain how to assemble the Koch v1.1 robot.
+
+## Order and assemble the parts
+
+Follow the sourcing and assembling instructions provided in this [README](https://github.com/jess-moss/koch-v1-1). This will guide you through setting up both the follower and leader arms, as shown in the image below.
+
+For a visual walkthrough of the assembly process, you can refer to [this video tutorial](https://youtu.be/8nQIg9BwwTk).
+
+> [!WARNING]
+> Since the production of this video, we simplified the configuration phase. Because of this, two things differ from the instructions in that video:
+>
+> - Don't plug in all the motor cables right away and wait to be instructed to do so in [Configure the motors](#configure-the-motors).
+> - Don't screw in the controller board (PCB) to the base right away and wait for being instructed to do so in [Configure the motors](#configure-the-motors).
+
+## Install LeRobot π€
+
+To install LeRobot follow, our [Installation Guide](./installation)
+
+In addition to these instructions, you need to install the Dynamixel SDK:
+
+```bash
+pip install -e ".[dynamixel]"
+```
+
+## Configure the motors
+
+### 1. Find the USB ports associated with each arm
+
+To find the port for each bus servo adapter, run this script:
+
+```bash
+lerobot-find-port
+```
+
+
+
+
+Example output:
+
+```
+Finding all available ports for the MotorBus.
+['/dev/tty.usbmodem575E0032081', '/dev/tty.usbmodem575E0031751']
+Remove the USB cable from your MotorsBus and press Enter when done.
+
+[...Disconnect corresponding leader or follower arm and press Enter...]
+
+The port of this MotorsBus is /dev/tty.usbmodem575E0032081
+Reconnect the USB cable.
+```
+
+Where the found port is: `/dev/tty.usbmodem575E0032081` corresponding to your leader or follower arm.
+
+
+
+
+On Linux, you might need to give access to the USB ports by running:
+
+```bash
+sudo chmod 666 /dev/ttyACM0
+sudo chmod 666 /dev/ttyACM1
+```
+
+Example output:
+
+```
+Finding all available ports for the MotorBus.
+['/dev/ttyACM0', '/dev/ttyACM1']
+Remove the usb cable from your MotorsBus and press Enter when done.
+
+[...Disconnect corresponding leader or follower arm and press Enter...]
+
+The port of this MotorsBus is /dev/ttyACM1
+Reconnect the USB cable.
+```
+
+Where the found port is: `/dev/ttyACM1` corresponding to your leader or follower arm.
+
+
+
+
+### 2. Set the motors ids and baudrates
+
+Each motor is identified by a unique id on the bus. When brand new, motors usually come with a default id of `1`. For the communication to work properly between the motors and the controller, we first need to set a unique, different id to each motor. Additionally, the speed at which data is transmitted on the bus is determined by the baudrate. In order to talk to each other, the controller and all the motors need to be configured with the same baudrate.
+
+To that end, we first need to connect to each motor individually with the controller in order to set these. Since we will write these parameters in the non-volatile section of the motors' internal memory (EEPROM), we'll only need to do this once.
+
+If you are repurposing motors from another robot, you will probably also need to perform this step, as the ids and baudrate likely won't match.
+
+#### Follower
+
+Connect the usb cable from your computer and the 5V power supply to the follower arm's controller board. Then, run the following command or run the API example with the port you got from the previous step. You'll also need to give your leader arm a name with the `id` parameter.
+
+For a visual reference on how to set the motor ids please refer to [this video](https://huggingface.co/docs/lerobot/en/so101#setup-motors-video) where we follow the process for the SO101 arm.
+
+
+
+
+```bash
+lerobot-setup-motors \
+ --robot.type=koch_follower \
+ --robot.port=/dev/tty.usbmodem575E0031751 # <- paste here the port found at previous step
+```
+
+
+
+
+
+```python
+from lerobot.robots.koch_follower import KochFollower, KochFollowerConfig
+
+config = KochFollowerConfig(
+ port="/dev/tty.usbmodem575E0031751",
+ id="my_awesome_follower_arm",
+)
+follower = KochFollower(config)
+follower.setup_motors()
+```
+
+
+
+
+
+You should see the following instruction.
+
+```
+Connect the controller board to the 'gripper' motor only and press enter.
+```
+
+As instructed, plug the gripper's motor. Make sure it's the only motor connected to the board, and that the motor itself is not yet daisy-chained to any other motor. As you press `[Enter]`, the script will automatically set the id and baudrate for that motor.
+
+
+Troubleshooting
+
+If you get an error at that point, check your cables and make sure they are plugged in properly:
+
+
+
Power supply
+
USB cable between your computer and the controller board
+
The 3-pin cable from the controller board to the motor
+
+
+If you are using a Waveshare controller board, make sure that the two jumpers are set on the `B` channel (USB).
+
+
+
+You should then see the following message:
+
+```
+'gripper' motor id set to 6
+```
+
+Followed by the next instruction:
+
+```
+Connect the controller board to the 'wrist_roll' motor only and press enter.
+```
+
+You can disconnect the 3-pin cable from the controller board but you can leave it connected to the gripper motor on the other end as it will already be in the right place. Now, plug in another 3-pin cable to the wrist roll motor and connect it to the controller board. As with the previous motor, make sure it is the only motor connected to the board and that the motor itself isn't connected to any other one.
+
+Repeat the operation for each motor as instructed.
+
+> [!TIP]
+> Check your cabling at each step before pressing Enter. For instance, the power supply cable might disconnect as you manipulate the board.
+
+When you are done, the script will simply finish, at which point the motors are ready to be used. You can now plug the 3-pin cable from each motor to the next one, and the cable from the first motor (the 'shoulder pan' with id=1) to the controller board, which can now be attached to the base of the arm.
+
+#### Leader
+
+Do the same steps for the leader arm but modify the command or script accordingly.
+
+
+
+
+```bash
+lerobot-setup-motors \
+ --teleop.type=koch_leader \
+ --teleop.port=/dev/tty.usbmodem575E0031751 \ # <- paste here the port found at previous step
+```
+
+
+
+
+
+```python
+from lerobot.teleoperators.koch_leader import KochLeader, KochLeaderConfig
+
+config = KochLeaderConfig(
+ port="/dev/tty.usbmodem575E0031751",
+ id="my_awesome_leader_arm",
+)
+leader = KochLeader(config)
+leader.setup_motors()
+```
+
+
+
+
+
+## Calibrate
+
+Next, you'll need to calibrate your robot to ensure that the leader and follower arms have the same position values when they are in the same physical position.
+The calibration process is very important because it allows a neural network trained on one robot to work on another.
+
+#### Follower
+
+Run the following command or API example to calibrate the follower arm:
+
+
+
+
+```bash
+lerobot-calibrate \
+ --robot.type=koch_follower \
+ --robot.port=/dev/tty.usbmodem58760431551 \ # <- The port of your robot
+ --robot.id=my_awesome_follower_arm # <- Give the robot a unique name
+```
+
+
+
+
+
+```python
+from lerobot.robots.koch_follower import KochFollowerConfig, KochFollower
+
+config = KochFollowerConfig(
+ port="/dev/tty.usbmodem585A0076891",
+ id="my_awesome_follower_arm",
+)
+
+follower = KochFollower(config)
+follower.connect(calibrate=False)
+follower.calibrate()
+follower.disconnect()
+```
+
+
+
+
+
+We unified the calibration method for most robots. Thus, the calibration steps for this Koch arm are the same as the steps for the SO100 and SO101. First, we have to move the robot to the position where each joint is in the middle of its range, then we press `Enter`. Secondly, we move all joints through their full range of motion. A video of this same process for the SO101 as reference can be found [here](https://huggingface.co/docs/lerobot/en/so101#calibration-video).
+
+#### Leader
+
+Do the same steps to calibrate the leader arm, run the following command or API example:
+
+
+
+
+```bash
+lerobot-calibrate \
+ --teleop.type=koch_leader \
+ --teleop.port=/dev/tty.usbmodem58760431551 \ # <- The port of your robot
+ --teleop.id=my_awesome_leader_arm # <- Give the robot a unique name
+```
+
+
+
+
+
+```python
+from lerobot.teleoperators.koch_leader import KochLeaderConfig, KochLeader
+
+config = KochLeaderConfig(
+ port="/dev/tty.usbmodem575E0031751",
+ id="my_awesome_leader_arm",
+)
+
+leader = KochLeader(config)
+leader.connect(calibrate=False)
+leader.calibrate()
+leader.disconnect()
+```
+
+
+
+
+
+Congrats π, your robot is all set to learn a task on its own. Start training it by following this tutorial: [Getting started with real-world robots](./il_robots)
+
+> [!TIP]
+> If you have any questions or need help, please reach out on [Discord](https://discord.com/invite/s3KuuzsPFb).
diff --git a/lerobot/docs/source/lekiwi.mdx b/lerobot/docs/source/lekiwi.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..43f7c4596bb9a4e27c0877de948e9f75ff76300e
--- /dev/null
+++ b/lerobot/docs/source/lekiwi.mdx
@@ -0,0 +1,337 @@
+# LeKiwi
+
+In the steps below, we explain how to assemble the LeKiwi mobile robot.
+
+## Source the parts
+
+Follow this [README](https://github.com/SIGRobotics-UIUC/LeKiwi). It contains the bill of materials, with a link to source the parts, as well as the instructions to 3D print the parts.
+And advise if it's your first time printing or if you don't own a 3D printer.
+
+### Wired version
+
+If you have the **wired** LeKiwi version, you can skip the installation of the Raspberry Pi and setting up SSH. You can also run all commands directly on your PC for both the LeKiwi scripts and the leader arm scripts for teleoperating.
+
+## Install software on Pi
+
+Now we have to set up the remote PC that will run on the LeKiwi Robot. This is normally a Raspberry Pi, but can be any PC that can run on 5V and has enough usb ports (2 or more) for the cameras and motor control board.
+
+### Install OS
+
+For setting up the Raspberry Pi and its SD-card see: [Setup PI](https://www.raspberrypi.com/documentation/computers/getting-started.html). Here is explained how to download the [Imager](https://www.raspberrypi.com/software/) to install Raspberry Pi OS or Ubuntu.
+
+### Setup SSH
+
+After setting up your Pi, you should enable and set up [SSH](https://www.raspberrypi.com/news/coding-on-raspberry-pi-remotely-with-visual-studio-code/) (Secure Shell Protocol) so you can log in to the Pi from your laptop without requiring a screen, keyboard, and mouse on the Pi. A great tutorial on how to do this can be found [here](https://www.raspberrypi.com/documentation/computers/remote-access.html#ssh). Logging into your Pi can be done in your Command Prompt (cmd) or, if you use VSCode you can use [this](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh) extension.
+
+### Install LeRobot on Pi π€
+
+On your Raspberry Pi install LeRobot using our [Installation Guide](./installation)
+
+In addition to these instructions, you need to install the Feetech SDK & ZeroMQ on your Pi:
+
+```bash
+pip install -e ".[lekiwi]"
+```
+
+## Install LeRobot locally
+
+If you already have installed LeRobot on your laptop/pc you can skip this step; otherwise, please follow along as we do the same steps we did on the Pi.
+
+Follow our [Installation Guide](./installation)
+
+In addition to these instructions, you need to install the Feetech SDK & ZeroMQ on your laptop/pc:
+
+```bash
+pip install -e ".[lekiwi]"
+```
+
+Great :hugs:! You are now done installing LeRobot, and we can begin assembling the SO100/SO101 arms and the mobile base :robot:.
+Every time you now want to use LeRobot, you can go to the `~/lerobot` folder where we installed LeRobot and run one of the commands.
+
+# Step-by-Step Assembly Instructions
+
+First, we will assemble the two SO100/SO101 arms. One to attach to the mobile base and one for teleoperation. Then we will assemble the mobile base. The instructions for assembling can be found on these two pages:
+
+- [Assemble SO101](./so101#step-by-step-assembly-instructions)
+- [Assemble LeKiwi](https://github.com/SIGRobotics-UIUC/LeKiwi/blob/main/Assembly.md)
+
+### Find the USB ports associated with motor board
+
+To find the port for each bus servo adapter, run this script:
+
+```bash
+lerobot-find-port
+```
+
+
+
+
+Example output:
+
+```
+Finding all available ports for the MotorBus.
+['/dev/tty.usbmodem575E0032081']
+Remove the USB cable from your MotorsBus and press Enter when done.
+
+[...Disconnect corresponding leader or follower arm and press Enter...]
+
+The port of this MotorsBus is /dev/tty.usbmodem575E0032081
+Reconnect the USB cable.
+```
+
+Where the found port is: `/dev/tty.usbmodem575E0032081` corresponding to your board.
+
+
+
+
+On Linux, you might need to give access to the USB ports by running:
+
+```bash
+sudo chmod 666 /dev/ttyACM0
+sudo chmod 666 /dev/ttyACM1
+```
+
+Example output:
+
+```
+Finding all available ports for the MotorBus.
+['/dev/ttyACM0']
+Remove the usb cable from your MotorsBus and press Enter when done.
+
+[...Disconnect corresponding leader or follower arm and press Enter...]
+
+The port of this MotorsBus is /dev/ttyACM0
+Reconnect the USB cable.
+```
+
+Where the found port is: `/dev/ttyACM0` corresponding to your board.
+
+
+
+
+### Configure motors
+
+The instructions for configuring the motors can be found in the SO101 [docs](./so101#configure-the-motors). Besides the ids for the arm motors, we also need to set the motor ids for the mobile base. These need to be in a specific order to work. Below an image of the motor ids and motor mounting positions for the mobile base. Note that we only use one Motor Control board on LeKiwi. This means the motor ids for the wheels are 7, 8 and 9.
+
+You can run this command to setup motors for LeKiwi. It will first setup the motors for arm (id 6..1) and then setup motors for wheels (9,8,7)
+
+```bash
+lerobot-setup-motors \
+ --robot.type=lekiwi \
+ --robot.port=/dev/tty.usbmodem58760431551 # <- paste here the port found at previous step
+```
+
+
+
+### Troubleshoot communication
+
+If you are having trouble connecting to the Mobile SO100, follow these steps to diagnose and resolve the issue.
+
+#### 1. Verify IP Address Configuration
+
+Make sure that the correct IP for the Pi is used in the commands or in your code. To check the Raspberry Pi's IP address, run (on the Pi command line):
+
+```bash
+hostname -I
+```
+
+#### 2. Check if Pi is reachable from laptop/pc
+
+Try pinging the Raspberry Pi from your laptop:
+
+```bach
+ping
+```
+
+If the ping fails:
+
+- Ensure the Pi is powered on and connected to the same network.
+- Check if SSH is enabled on the Pi.
+
+#### 3. Try SSH connection
+
+If you can't SSH into the Pi, it might not be properly connected. Use:
+
+```bash
+ssh @
+```
+
+If you get a connection error:
+
+- Ensure SSH is enabled on the Pi by running:
+ ```bash
+ sudo raspi-config
+ ```
+ Then navigate to: **Interfacing Options -> SSH** and enable it.
+
+### Calibration
+
+Now we have to calibrate the leader arm and the follower arm. The wheel motors don't have to be calibrated.
+The calibration process is very important because it allows a neural network trained on one robot to work on another.
+
+### Calibrate follower arm (on mobile base)
+
+Make sure the arm is connected to the Raspberry Pi and run this script or API example (on the Raspberry Pi via SSH) to launch calibration of the follower arm:
+
+```bash
+lerobot-calibrate \
+ --robot.type=lekiwi \
+ --robot.id=my_awesome_kiwi # <- Give the robot a unique name
+```
+
+We unified the calibration method for most robots, thus, the calibration steps for this SO100 arm are the same as the steps for the Koch and SO101. First, we have to move the robot to the position where each joint is in the middle of its range, then we press `Enter`. Secondly, we move all joints through their full range of motion. A video of this same process for the SO101 as reference can be found [here](https://huggingface.co/docs/lerobot/en/so101#calibration-video).
+
+### Wired version
+
+If you have the **wired** LeKiwi version, please run all commands on your laptop.
+
+### Calibrate leader arm
+
+Then, to calibrate the leader arm (which is attached to the laptop/pc). Run the following command of API example on your laptop:
+
+
+
+
+```bash
+lerobot-calibrate \
+ --teleop.type=so100_leader \
+ --teleop.port=/dev/tty.usbmodem58760431551 \ # <- The port of your robot
+ --teleop.id=my_awesome_leader_arm # <- Give the robot a unique name
+```
+
+
+
+
+
+```python
+from lerobot.teleoperators.so_leader import SO100LeaderConfig, SO100Leader
+
+config = SO100LeaderConfig(
+ port="/dev/tty.usbmodem58760431551",
+ id="my_awesome_leader_arm",
+)
+
+leader = SO100Leader(config)
+leader.connect(calibrate=False)
+leader.calibrate()
+leader.disconnect()
+```
+
+
+
+
+
+## Teleoperate LeKiwi
+
+> [!TIP]
+> If you're using a Mac, you might need to give Terminal permission to access your keyboard for teleoperation. Go to System Preferences > Security & Privacy > Input Monitoring and check the box for Terminal.
+
+To teleoperate, SSH into your Raspberry Pi, and run `conda activate lerobot` and this command:
+
+```bash
+python -m lerobot.robots.lekiwi.lekiwi_host --robot.id=my_awesome_kiwi
+```
+
+Then on your laptop, also run `conda activate lerobot` and run the API example, make sure you set the correct `remote_ip` and `port` in `examples/lekiwi/teleoperate.py`.
+
+```bash
+python examples/lekiwi/teleoperate.py
+```
+
+You should see on your laptop something like this: `[INFO] Connected to remote robot at tcp://172.17.133.91:5555 and video stream at tcp://172.17.133.91:5556.` Now you can move the leader arm and use the keyboard (w,a,s,d) to drive forward, left, backwards, right. And use (z,x) to turn left or turn right. You can use (r,f) to increase and decrease the speed of the mobile robot. There are three speed modes, see the table below:
+
+| Speed Mode | Linear Speed (m/s) | Rotation Speed (deg/s) |
+| ---------- | ------------------ | ---------------------- |
+| Fast | 0.4 | 90 |
+| Medium | 0.25 | 60 |
+| Slow | 0.1 | 30 |
+
+| Key | Action |
+| --- | -------------- |
+| W | Move forward |
+| A | Move left |
+| S | Move backward |
+| D | Move right |
+| Z | Turn left |
+| X | Turn right |
+| R | Increase speed |
+| F | Decrease speed |
+
+> [!TIP]
+> If you use a different keyboard, you can change the keys for each command in the [`LeKiwiClientConfig`](https://github.com/huggingface/lerobot/blob/main/src/lerobot/robots/lekiwi/config_lekiwi.py).
+
+### Wired version
+
+If you have the **wired** LeKiwi version, please run all commands on your laptop.
+
+## Record a dataset
+
+Once you're familiar with teleoperation, you can record your first dataset.
+
+We use the Hugging Face hub features for uploading your dataset. If you haven't previously used the Hub, make sure you can login via the cli using a write-access token, this token can be generated from the [Hugging Face settings](https://huggingface.co/settings/tokens).
+
+Add your token to the CLI by running this command:
+
+```bash
+huggingface-cli login --token ${HUGGINGFACE_TOKEN} --add-to-git-credential
+```
+
+Then store your Hugging Face repository name in a variable:
+
+```bash
+HF_USER=$(huggingface-cli whoami | head -n 1)
+echo $HF_USER
+```
+
+Now you can record a dataset. To record episodes and upload your dataset to the hub, execute this API example tailored for LeKiwi. Make sure to first adapt the `remote_ip`, `repo_id`, `port` and `task` in the script. If you would like to run the script for longer you can increase `NB_CYCLES_CLIENT_CONNECTION`.
+
+```bash
+python examples/lekiwi/record.py
+```
+
+#### Dataset upload
+
+Locally, your dataset is stored in this folder: `~/.cache/huggingface/lerobot/{repo-id}`. At the end of data recording, your dataset will be uploaded on your Hugging Face page (e.g. https://huggingface.co/datasets/cadene/so101_test) that you can obtain by running:
+
+```bash
+echo https://huggingface.co/datasets/${HF_USER}/so101_test
+```
+
+Your dataset will be automatically tagged with `LeRobot` for the community to find it easily, and you can also add custom tags (in this case `tutorial` for example).
+
+You can look for other LeRobot datasets on the hub by searching for `LeRobot` [tags](https://huggingface.co/datasets?other=LeRobot).
+
+#### Tips for gathering data
+
+Once you're comfortable with data recording, you can create a larger dataset for training. A good starting task is grasping an object at different locations and placing it in a bin. We suggest recording at least 50 episodes, with 10 episodes per location. Keep the cameras fixed and maintain consistent grasping behavior throughout the recordings. Also make sure the object you are manipulating is visible on the camera's. A good rule of thumb is you should be able to do the task yourself by only looking at the camera images.
+
+In the following sections, youβll train your neural network. After achieving reliable grasping performance, you can start introducing more variations during data collection, such as additional grasp locations, different grasping techniques, and altering camera positions.
+
+Avoid adding too much variation too quickly, as it may hinder your results.
+
+If you want to dive deeper into this important topic, you can check out the [blog post](https://huggingface.co/blog/lerobot-datasets#what-makes-a-good-dataset) we wrote on what makes a good dataset.
+
+#### Troubleshooting:
+
+- On Linux, if the left and right arrow keys and escape key don't have any effect during data recording, make sure you've set the `$DISPLAY` environment variable. See [pynput limitations](https://pynput.readthedocs.io/en/latest/limitations.html#linux).
+
+## Replay an episode
+
+To replay an episode run the API example below, make sure to change `remote_ip`, `port`, LeRobotDatasetId and episode index.
+
+```bash
+python examples/lekiwi/replay.py
+```
+
+Congrats π, your robot is all set to learn a task on its own. Start training it by the training part of this tutorial: [Getting started with real-world robots](./il_robots)
+
+## Evaluate your policy
+
+To evaluate your policy run the `evaluate.py` API example, make sure to change `remote_ip`, `port`, model..
+
+```bash
+python examples/lekiwi/evaluate.py
+```
+
+> [!TIP]
+> If you have any questions or need help, please reach out on [Discord](https://discord.com/invite/s3KuuzsPFb).
diff --git a/lerobot/docs/source/lerobot-dataset-v3.mdx b/lerobot/docs/source/lerobot-dataset-v3.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..1071074381c35f062d139980948bf0621c8b26ed
--- /dev/null
+++ b/lerobot/docs/source/lerobot-dataset-v3.mdx
@@ -0,0 +1,314 @@
+# LeRobotDataset v3.0
+
+`LeRobotDataset v3.0` is a standardized format for robot learning data. It provides unified access to multi-modal time-series data, sensorimotor signals and multiβcamera video, as well as rich metadata for indexing, search, and visualization on the Hugging Face Hub.
+
+This docs will guide you to:
+
+- Understand the v3.0 design and directory layout
+- Record a dataset and push it to the Hub
+- Load datasets for training with `LeRobotDataset`
+- Stream datasets without downloading using `StreamingLeRobotDataset`
+- Apply image transforms for data augmentation during training
+- Migrate existing `v2.1` datasets to `v3.0`
+
+## Whatβs new in `v3`
+
+- **File-based storage**: Many episodes per Parquet/MP4 file (v2 used one file per episode).
+- **Relational metadata**: Episode boundaries and lookups are resolved through metadata, not filenames.
+- **Hub-native streaming**: Consume datasets directly from the Hub with `StreamingLeRobotDataset`.
+- **Lower file-system pressure**: Fewer, larger files β faster initialization and fewer issues at scale.
+- **Unified organization**: Clean directory layout with consistent path templates across data and videos.
+
+## Installation
+
+`LeRobotDataset v3.0` will be included in `lerobot >= 0.4.0`.
+
+Until that stable release, you can use the main branch by following the [build from source instructions](./installation#from-source).
+
+## Record a dataset
+
+Run the command below to record a dataset with the SO-101 and push to the Hub:
+
+```bash
+lerobot-record \
+ --robot.type=so101_follower \
+ --robot.port=/dev/tty.usbmodem585A0076841 \
+ --robot.id=my_awesome_follower_arm \
+ --robot.cameras="{ front: {type: opencv, index_or_path: 0, width: 1920, height: 1080, fps: 30}}" \
+ --teleop.type=so101_leader \
+ --teleop.port=/dev/tty.usbmodem58760431551 \
+ --teleop.id=my_awesome_leader_arm \
+ --display_data=true \
+ --dataset.repo_id=${HF_USER}/record-test \
+ --dataset.num_episodes=5 \
+ --dataset.single_task="Grab the black cube"
+```
+
+See the [recording guide](./il_robots#record-a-dataset) for more details.
+
+## Format design
+
+A core v3 principle is **decoupling storage from the user API**: data is stored efficiently (few large files), while the public API exposes intuitive episode-level access.
+
+`v3` has three pillars:
+
+1. **Tabular data**: Lowβdimensional, highβfrequency signals (states, actions, timestamps) stored in **Apache Parquet**. Access is memoryβmapped or streamed via the `datasets` stack.
+2. **Visual data**: Camera frames concatenated and encoded into **MP4**. Frames from the same episode are grouped; videos are sharded per camera for practical sizes.
+3. **Metadata**: JSON/Parquet records describing schema (feature names, dtypes, shapes), frame rates, normalization stats, and **episode segmentation** (start/end offsets into shared Parquet/MP4 files).
+
+> To scale to millions of episodes, tabular rows and video frames from multiple episodes are **concatenated** into larger files. Episodeβspecific views are reconstructed **via metadata**, not file boundaries.
+
+
+
+
+
+ From episodeβbased to fileβbased datasets
+
+
+
+
+### Directory layout (simplified)
+
+- **`meta/info.json`**: canonical schema (features, shapes/dtypes), FPS, codebase version, and **path templates** to locate data/video shards.
+- **`meta/stats.json`**: global feature statistics (mean/std/min/max) used for normalization; exposed as `dataset.meta.stats`.
+- **`meta/tasks.jsonl`**: naturalβlanguage task descriptions mapped to integer IDs for taskβconditioned policies.
+- **`meta/episodes/`**: perβepisode records (lengths, tasks, offsets) stored as **chunked Parquet** for scalability.
+- **`data/`**: frameβbyβframe **Parquet** shards; each file typically contains **many episodes**.
+- **`videos/`**: **MP4** shards per camera; each file typically contains **many episodes**.
+
+## Load a dataset for training
+
+`LeRobotDataset` returns Python dictionaries of PyTorch tensors and integrates with `torch.utils.data.DataLoader`. Here is a code example showing its use:
+
+```python
+import torch
+from lerobot.datasets.lerobot_dataset import LeRobotDataset
+
+repo_id = "yaak-ai/L2D-v3"
+
+# 1) Load from the Hub (cached locally)
+dataset = LeRobotDataset(repo_id)
+
+# 2) Random access by index
+sample = dataset[100]
+print(sample)
+# {
+# 'observation.state': tensor([...]),
+# 'action': tensor([...]),
+# 'observation.images.front_left': tensor([C, H, W]),
+# 'timestamp': tensor(1.234),
+# ...
+# }
+
+# 3) Temporal windows via delta_timestamps (seconds relative to t)
+delta_timestamps = {
+ "observation.images.front_left": [-0.2, -0.1, 0.0] # 0.2s and 0.1s before current frame
+}
+
+dataset = LeRobotDataset(repo_id, delta_timestamps=delta_timestamps)
+
+# Accessing an index now returns a stack for the specified key(s)
+sample = dataset[100]
+print(sample["observation.images.front_left"].shape) # [T, C, H, W], where T=3
+
+# 4) Wrap with a DataLoader for training
+batch_size = 16
+data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size)
+
+device = "cuda" if torch.cuda.is_available() else "cpu"
+for batch in data_loader:
+ observations = batch["observation.state"].to(device)
+ actions = batch["action"].to(device)
+ images = batch["observation.images.front_left"].to(device)
+ # model.forward(batch)
+```
+
+## Stream a dataset (no downloads)
+
+Use `StreamingLeRobotDataset` to iterate directly from the Hub without local copies. This allows to stream large datasets without the need to downloading them onto disk or loading them onto memory, and is a key feature of the new dataset format.
+
+```python
+from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset
+
+repo_id = "yaak-ai/L2D-v3"
+dataset = StreamingLeRobotDataset(repo_id) # streams directly from the Hub
+```
+
+
+
+
+
+ Stream directly from the Hub for onβtheβfly training.
+
+
+
+
+## Image transforms
+
+Image transforms are data augmentations applied to camera frames during training to improve model robustness and generalization. LeRobot supports various transforms including brightness, contrast, saturation, hue, and sharpness adjustments.
+
+### Using transforms during dataset creation/recording
+
+Currently, transforms are applied during **training time only**, not during recording. When you create or record a dataset, the raw images are stored without transforms. This allows you to experiment with different augmentations later without re-recording data.
+
+### Adding transforms to existing datasets (API)
+
+Use the `image_transforms` parameter when loading a dataset for training:
+
+```python
+from lerobot.datasets.lerobot_dataset import LeRobotDataset
+from lerobot.datasets.transforms import ImageTransforms, ImageTransformsConfig, ImageTransformConfig
+
+# Option 1: Use default transform configuration (disabled by default)
+transforms_config = ImageTransformsConfig(
+ enable=True, # Enable transforms
+ max_num_transforms=3, # Apply up to 3 transforms per frame
+ random_order=False, # Apply in standard order
+)
+transforms = ImageTransforms(transforms_config)
+
+dataset = LeRobotDataset(
+ repo_id="your-username/your-dataset",
+ image_transforms=transforms
+)
+
+# Option 2: Create custom transform configuration
+custom_transforms_config = ImageTransformsConfig(
+ enable=True,
+ max_num_transforms=2,
+ random_order=True,
+ tfs={
+ "brightness": ImageTransformConfig(
+ weight=1.0,
+ type="ColorJitter",
+ kwargs={"brightness": (0.7, 1.3)} # Adjust brightness range
+ ),
+ "contrast": ImageTransformConfig(
+ weight=2.0, # Higher weight = more likely to be selected
+ type="ColorJitter",
+ kwargs={"contrast": (0.8, 1.2)}
+ ),
+ "sharpness": ImageTransformConfig(
+ weight=0.5, # Lower weight = less likely to be selected
+ type="SharpnessJitter",
+ kwargs={"sharpness": (0.3, 2.0)}
+ ),
+ }
+)
+
+dataset = LeRobotDataset(
+ repo_id="your-username/your-dataset",
+ image_transforms=ImageTransforms(custom_transforms_config)
+)
+
+# Option 3: Use pure torchvision transforms
+from torchvision.transforms import v2
+
+torchvision_transforms = v2.Compose([
+ v2.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
+ v2.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0)),
+])
+
+dataset = LeRobotDataset(
+ repo_id="your-username/your-dataset",
+ image_transforms=torchvision_transforms
+)
+```
+
+### Available transform types
+
+LeRobot provides several transform types:
+
+- **`ColorJitter`**: Adjusts brightness, contrast, saturation, and hue
+- **`SharpnessJitter`**: Randomly adjusts image sharpness
+- **`Identity`**: No transformation (useful for testing)
+
+You can also use any `torchvision.transforms.v2` transform by passing it directly to the `image_transforms` parameter.
+
+### Configuration options
+
+- **`enable`**: Enable/disable transforms (default: `False`)
+- **`max_num_transforms`**: Maximum number of transforms applied per frame (default: `3`)
+- **`random_order`**: Apply transforms in random order vs. standard order (default: `False`)
+- **`weight`**: Sampling probability for each transform (higher = more likely, if sum of weights is not 1, they will be normalized)
+- **`kwargs`**: Transform-specific parameters (e.g., brightness range)
+
+### Visualizing transforms
+
+Use the visualization script to preview how transforms affect your data:
+
+```bash
+lerobot-imgtransform-viz \
+ --repo-id=your-username/your-dataset \
+ --output-dir=./transform_examples \
+ --n-examples=5
+```
+
+This saves example images showing the effect of each transform, helping you tune parameters.
+
+### Best practices
+
+- **Start conservative**: Begin with small ranges (e.g., brightness 0.9-1.1) and increase gradually
+- **Test first**: Use the visualization script to ensure transforms look reasonable
+- **Monitor training**: Strong augmentations can hurt performance if too aggressive
+- **Match your domain**: If your robot operates in varying lighting, use brightness/contrast transforms
+- **Combine wisely**: Using too many transforms simultaneously can make training unstable
+
+## Migrate `v2.1` β `v3.0`
+
+A converter aggregates perβepisode files into larger shards and writes episode offsets/metadata. Convert your dataset using the instructions below.
+
+```bash
+# Pre-release build with v3 support:
+pip install "https://github.com/huggingface/lerobot/archive/33cad37054c2b594ceba57463e8f11ee374fa93c.zip"
+
+# Convert an existing v2.1 dataset hosted on the Hub:
+python -m lerobot.datasets.v30.convert_dataset_v21_to_v30 --repo-id=
+```
+
+**What it does**
+
+- Aggregates parquet files: `episode-0000.parquet`, `episode-0001.parquet`, β¦ β **`file-0000.parquet`**, β¦
+- Aggregates mp4 files: `episode-0000.mp4`, `episode-0001.mp4`, β¦ β **`file-0000.mp4`**, β¦
+- Updates `meta/episodes/*` (chunked Parquet) with perβepisode lengths, tasks, and byte/frame offsets.
+
+## Common Issues
+
+### Always call `finalize()` before pushing
+
+When creating or recording datasets, you **must** call `dataset.finalize()` to properly close parquet writers. See the [PR #1903](https://github.com/huggingface/lerobot/pull/1903) for more details.
+
+```python
+from lerobot.datasets.lerobot_dataset import LeRobotDataset
+
+# Create dataset and record episodes
+dataset = LeRobotDataset.create(...)
+
+for episode in range(num_episodes):
+ # Record frames
+ for frame in episode_data:
+ dataset.add_frame(frame)
+ dataset.save_episode()
+
+# Call finalize() when done recording and before push_to_hub()
+dataset.finalize() # Closes parquet writers, writes metadata footers
+dataset.push_to_hub()
+```
+
+**Why is this necessary?**
+
+Dataset v3.0 uses incremental parquet writing with buffered metadata for efficiency. The `finalize()` method:
+
+- Flushes any buffered episode metadata to disk
+- Closes parquet writers to write footer metadata, otherwise the parquet files will be corrupt
+- Ensures the dataset is valid for loading
+
+Without calling `finalize()`, your parquet files will be incomplete and the dataset won't load properly.
diff --git a/lerobot/docs/source/libero.mdx b/lerobot/docs/source/libero.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..f900369adaf532e98faf50fe797b6b00bbdcacf7
--- /dev/null
+++ b/lerobot/docs/source/libero.mdx
@@ -0,0 +1,171 @@
+# LIBERO
+
+**LIBERO** is a benchmark designed to study **lifelong robot learning**. The idea is that robots wonβt just be pretrained once in a factory, theyβll need to keep learning and adapting with their human users over time. This ongoing adaptation is called **lifelong learning in decision making (LLDM)**, and itβs a key step toward building robots that become truly personalized helpers.
+
+- π [LIBERO paper](https://arxiv.org/abs/2306.03310)
+- π» [Original LIBERO repo](https://github.com/Lifelong-Robot-Learning/LIBERO)
+
+To make progress on this challenge, LIBERO provides a set of standardized tasks that focus on **knowledge transfer**: how well a robot can apply what it has already learned to new situations. By evaluating on LIBERO, different algorithms can be compared fairly and researchers can build on each otherβs work.
+
+LIBERO includes **five task suites**:
+
+- **LIBERO-Spatial (`libero_spatial`)** β tasks that require reasoning about spatial relations.
+- **LIBERO-Object (`libero_object`)** β tasks centered on manipulating different objects.
+- **LIBERO-Goal (`libero_goal`)** β goal-conditioned tasks where the robot must adapt to changing targets.
+- **LIBERO-90 (`libero_90`)** β 90 short-horizon tasks from the LIBERO-100 collection.
+- **LIBERO-Long (`libero_10`)** β 10 long-horizon tasks from the LIBERO-100 collection.
+
+Together, these suites cover **130 tasks**, ranging from simple object manipulations to complex multi-step scenarios. LIBERO is meant to grow over time, and to serve as a shared benchmark where the community can test and improve lifelong learning algorithms.
+
+
+
+## Evaluating with LIBERO
+
+At **LeRobot**, we ported [LIBERO](https://github.com/Lifelong-Robot-Learning/LIBERO) into our framework and used it mainly to **evaluate [SmolVLA](https://huggingface.co/docs/lerobot/en/smolvla)**, our lightweight Vision-Language-Action model.
+
+LIBERO is now part of our **multi-eval supported simulation**, meaning you can benchmark your policies either on a **single suite of tasks** or across **multiple suites at once** with just a flag.
+
+To Install LIBERO, after following LeRobot official instructions, just do:
+`pip install -e ".[libero]"`
+
+### Single-suite evaluation
+
+Evaluate a policy on one LIBERO suite:
+
+```bash
+lerobot-eval \
+ --policy.path="your-policy-id" \
+ --env.type=libero \
+ --env.task=libero_object \
+ --eval.batch_size=2 \
+ --eval.n_episodes=3
+```
+
+- `--env.task` picks the suite (`libero_object`, `libero_spatial`, etc.).
+- `--eval.batch_size` controls how many environments run in parallel.
+- `--eval.n_episodes` sets how many episodes to run in total.
+
+---
+
+### Multi-suite evaluation
+
+Benchmark a policy across multiple suites at once:
+
+```bash
+lerobot-eval \
+ --policy.path="your-policy-id" \
+ --env.type=libero \
+ --env.task=libero_object,libero_spatial \
+ --eval.batch_size=1 \
+ --eval.n_episodes=2
+```
+
+- Pass a comma-separated list to `--env.task` for multi-suite evaluation.
+
+### Control Mode
+
+LIBERO now supports two control modes: relative and absolute. This matters because different VLA checkpoints are trained with different mode of action to output hence control parameterizations.
+You can switch them with: `env.control_mode = "relative"` and `env.control_mode = "absolute"`
+
+### Policy inputs and outputs
+
+When using LIBERO through LeRobot, policies interact with the environment via **observations** and **actions**:
+
+- **Observations**
+ - `observation.state` β proprioceptive features (agent state).
+ - `observation.images.image` β main camera view (`agentview_image`).
+ - `observation.images.image2` β wrist camera view (`robot0_eye_in_hand_image`).
+
+ β οΈ **Note:** LeRobot enforces the `.images.*` prefix for any multi-modal visual features. Always ensure that your policy config `input_features` use the same naming keys, and that your dataset metadata keys follow this convention during evaluation.
+ If your data contains different keys, you must rename the observations to match what the policy expects, since naming keys are encoded inside the normalization statistics layer.
+ This will be fixed with the upcoming Pipeline PR.
+
+- **Actions**
+ - Continuous control values in a `Box(-1, 1, shape=(7,))` space.
+
+We also provide a notebook for quick testing:
+Training with LIBERO
+
+## Training with LIBERO
+
+When training on LIBERO tasks, make sure your dataset parquet and metadata keys follow the LeRobot convention.
+
+The environment expects:
+
+- `observation.state` β 8-dim agent state
+- `observation.images.image` β main camera (`agentview_image`)
+- `observation.images.image2` β wrist camera (`robot0_eye_in_hand_image`)
+
+β οΈ Cleaning the dataset upfront is **cleaner and more efficient** than remapping keys inside the code.
+To avoid potential mismatches and key errors, we provide a **preprocessed LIBERO dataset** that is fully compatible with the current LeRobot codebase and requires no additional manipulation:
+π [HuggingFaceVLA/libero](https://huggingface.co/datasets/HuggingFaceVLA/libero)
+
+For reference, here is the **original dataset** published by Physical Intelligence:
+π [physical-intelligence/libero](https://huggingface.co/datasets/physical-intelligence/libero)
+
+---
+
+### Example training command
+
+```bash
+lerobot-train \
+ --policy.type=smolvla \
+ --policy.repo_id=${HF_USER}/libero-test \
+ --policy.load_vlm_weights=true \
+ --dataset.repo_id=HuggingFaceVLA/libero \
+ --env.type=libero \
+ --env.task=libero_10 \
+ --output_dir=./outputs/ \
+ --steps=100000 \
+ --batch_size=4 \
+ --eval.batch_size=1 \
+ --eval.n_episodes=1 \
+ --eval_freq=1000 \
+```
+
+---
+
+### Note on rendering
+
+LeRobot uses MuJoCo for simulation. You need to set the rendering backend before training or evaluation:
+
+- `export MUJOCO_GL=egl` β for headless servers (e.g. HPC, cloud)
+
+## Reproducing Οβ.β results
+
+We reproduce the results of Οβ.β on the LIBERO benchmark using the LeRobot implementation. We take the Physical Intelligence LIBERO base model (`pi05_libero`) and finetune for an additional 6k steps in bfloat16, with batch size of 256 on 8 H100 GPUs using the [HuggingFace LIBERO dataset](https://huggingface.co/datasets/HuggingFaceVLA/libero).
+
+The finetuned model can be found here:
+
+- **Οβ.β LIBERO**: [lerobot/pi05_libero_finetuned](https://huggingface.co/lerobot/pi05_libero_finetuned)
+
+We then evaluate the finetuned model using the LeRobot LIBERO implementation, by running the following command:
+
+```bash
+lerobot-eval \
+ --output_dir=/logs/ \
+ --env.type=libero \
+ --env.task=libero_spatial,libero_object,libero_goal,libero_10 \
+ --eval.batch_size=1 \
+ --eval.n_episodes=10 \
+ --policy.path=pi05_libero_finetuned \
+ --policy.n_action_steps=10 \
+ --output_dir=./eval_logs/ \
+ --env.max_parallel_tasks=1
+```
+
+**Note:** We set `n_action_steps=10`, similar to the original OpenPI implementation.
+
+### Results
+
+We obtain the following results on the LIBERO benchmark:
+
+| Model | LIBERO Spatial | LIBERO Object | LIBERO Goal | LIBERO 10 | Average |
+| -------- | -------------- | ------------- | ----------- | --------- | -------- |
+| **Οβ.β ** | 97.0 | 99.0 | 98.0 | 96.0 | **97.5** |
+
+These results are consistent with the original [results](https://github.com/Physical-Intelligence/openpi/tree/main/examples/libero#results) reported by Physical Intelligence:
+
+| Model | LIBERO Spatial | LIBERO Object | LIBERO Goal | LIBERO 10 | Average |
+| -------- | -------------- | ------------- | ----------- | --------- | --------- |
+| **Οβ.β ** | 98.8 | 98.2 | 98.0 | 92.4 | **96.85** |
diff --git a/lerobot/docs/source/metaworld.mdx b/lerobot/docs/source/metaworld.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..205cd6db44e6e7e925fc834c7099f51d8175d9ce
--- /dev/null
+++ b/lerobot/docs/source/metaworld.mdx
@@ -0,0 +1,80 @@
+# Meta-World
+
+Meta-World is a well-designed, open-source simulation benchmark for multi-task and meta reinforcement learning in continuous-control robotic manipulation. It gives researchers a shared, realistic playground to test whether algorithms can _learn many different tasks_ and _generalize quickly to new ones_ β two central challenges for real-world robotics.
+
+- π [MetaWorld paper](https://arxiv.org/pdf/1910.10897)
+- π» [Original MetaWorld repo](https://github.com/Farama-Foundation/Metaworld)
+
+
+
+## Why Meta-World matters
+
+- **Diverse, realistic tasks.** Meta-World bundles a large suite of simulated manipulation tasks (50 in the MT50 suite) using everyday objects and a common tabletop Sawyer arm. This diversity exposes algorithms to a wide variety of dynamics, contacts and goal specifications while keeping a consistent control and observation structure.
+- **Focus on generalization and multi-task learning.** By evaluating across task distributions that share structure but differ in goals and objects, Meta-World reveals whether an agent truly learns transferable skills rather than overfitting to a narrow task.
+- **Standardized evaluation protocol.** It provides clear evaluation modes and difficulty splits, so different methods can be compared fairly across easy, medium, hard and very-hard regimes.
+- **Empirical insight.** Past evaluations on Meta-World show impressive progress on some fronts, but also highlight that current multi-task and meta-RL methods still struggle with large, diverse task sets. That gap points to important research directions.
+
+## What it enables in LeRobot
+
+In LeRobot, you can evaluate any policy or vision-language-action (VLA) model on Meta-World tasks and get a clear success-rate measure. The integration is designed to be straightforward:
+
+- We provide a LeRobot-ready dataset for Meta-World (MT50) on the HF Hub: `https://huggingface.co/datasets/lerobot/metaworld_mt50`.
+ - This dataset is formatted for the MT50 evaluation that uses all 50 tasks (the most challenging multi-task setting).
+ - MT50 gives the policy a one-hot task vector and uses fixed object/goal positions for consistency.
+
+- Task descriptions and the exact keys required for evaluation are available in the repo/dataset β use these to ensure your policy outputs the right success signals.
+
+## Quick start, train a SmolVLA policy on Meta-World
+
+Example command to train a SmolVLA policy on a subset of tasks:
+
+```bash
+lerobot-train \
+ --policy.type=smolvla \
+ --policy.repo_id=${HF_USER}/metaworld-test \
+ --policy.load_vlm_weights=true \
+ --dataset.repo_id=lerobot/metaworld_mt50 \
+ --env.type=metaworld \
+ --env.task=assembly-v3,dial-turn-v3,handle-press-side-v3 \
+ --output_dir=./outputs/ \
+ --steps=100000 \
+ --batch_size=4 \
+ --eval.batch_size=1 \
+ --eval.n_episodes=1 \
+ --eval_freq=1000
+```
+
+Notes:
+
+- `--env.task` accepts explicit task lists (comma separated) or difficulty groups (e.g., `env.task="hard"`).
+- Adjust `batch_size`, `steps`, and `eval_freq` to match your compute budget.
+- **Gymnasium Assertion Error**: if you encounter an error like
+ `AssertionError: ['human', 'rgb_array', 'depth_array']` when running MetaWorld environments, this comes from a mismatch between MetaWorld and your Gymnasium version.
+ We recommend using:
+
+```bash
+ pip install "gymnasium==1.1.0"
+```
+
+to ensure proper compatibility.
+
+## Quick start β evaluate a trained policy
+
+To evaluate a trained policy on the Meta-World medium difficulty split:
+
+```bash
+lerobot-eval \
+ --policy.path="your-policy-id" \
+ --env.type=metaworld \
+ --env.task=medium \
+ --eval.batch_size=1 \
+ --eval.n_episodes=2
+```
+
+This will run episodes and return per-task success rates using the standard Meta-World evaluation keys.
+
+## Practical tips
+
+- If you care about generalization, run on the full MT50 suite β itβs intentionally challenging and reveals strengths/weaknesses better than a few narrow tasks.
+- Use the one-hot task conditioning for multi-task training (MT10 / MT50 conventions) so policies have explicit task context.
+- Inspect the dataset task descriptions and the `info["is_success"]` keys when writing post-processing or logging so your success metrics line up with the benchmark.
diff --git a/lerobot/docs/source/multi_gpu_training.mdx b/lerobot/docs/source/multi_gpu_training.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..af89a4a188d53987f8beee626a96e99530c2928e
--- /dev/null
+++ b/lerobot/docs/source/multi_gpu_training.mdx
@@ -0,0 +1,125 @@
+# Multi-GPU Training
+
+This guide shows you how to train policies on multiple GPUs using [Hugging Face Accelerate](https://huggingface.co/docs/accelerate).
+
+## Installation
+
+First, ensure you have accelerate installed:
+
+```bash
+pip install accelerate
+```
+
+## Training with Multiple GPUs
+
+You can launch training in two ways:
+
+### Option 1: Without config (specify parameters directly)
+
+You can specify all parameters directly in the command without running `accelerate config`:
+
+```bash
+accelerate launch \
+ --multi_gpu \
+ --num_processes=2 \
+ $(which lerobot-train) \
+ --dataset.repo_id=${HF_USER}/my_dataset \
+ --policy.type=act \
+ --policy.repo_id=${HF_USER}/my_trained_policy \
+ --output_dir=outputs/train/act_multi_gpu \
+ --job_name=act_multi_gpu \
+ --wandb.enable=true
+```
+
+**Key accelerate parameters:**
+
+- `--multi_gpu`: Enable multi-GPU training
+- `--num_processes=2`: Number of GPUs to use
+- `--mixed_precision=fp16`: Use fp16 mixed precision (or `bf16` if supported)
+
+### Option 2: Using accelerate config
+
+If you prefer to save your configuration, you can optionally configure accelerate for your hardware setup by running:
+
+```bash
+accelerate config
+```
+
+This interactive setup will ask you questions about your training environment (number of GPUs, mixed precision settings, etc.) and saves the configuration for future use. For a simple multi-GPU setup on a single machine, you can use these recommended settings:
+
+- Compute environment: This machine
+- Number of machines: 1
+- Number of processes: (number of GPUs you want to use)
+- GPU ids to use: (leave empty to use all)
+- Mixed precision: fp16 or bf16 (recommended for faster training)
+
+Then launch training with:
+
+```bash
+accelerate launch $(which lerobot-train) \
+ --dataset.repo_id=${HF_USER}/my_dataset \
+ --policy.type=act \
+ --policy.repo_id=${HF_USER}/my_trained_policy \
+ --output_dir=outputs/train/act_multi_gpu \
+ --job_name=act_multi_gpu \
+ --wandb.enable=true
+```
+
+## How It Works
+
+When you launch training with accelerate:
+
+1. **Automatic detection**: LeRobot automatically detects if it's running under accelerate
+2. **Data distribution**: Your batch is automatically split across GPUs
+3. **Gradient synchronization**: Gradients are synchronized across GPUs during backpropagation
+4. **Single process logging**: Only the main process logs to wandb and saves checkpoints
+
+## Learning Rate and Training Steps Scaling
+
+**Important:** LeRobot does **NOT** automatically scale learning rates or training steps based on the number of GPUs. This gives you full control over your training hyperparameters.
+
+### Why No Automatic Scaling?
+
+Many distributed training frameworks automatically scale the learning rate by the number of GPUs (e.g., `lr = base_lr Γ num_gpus`).
+However, LeRobot keeps the learning rate exactly as you specify it.
+
+### When and How to Scale
+
+If you want to scale your hyperparameters when using multiple GPUs, you should do it manually:
+
+**Learning Rate Scaling:**
+
+```bash
+# Example: 2 GPUs with linear LR scaling
+# Base LR: 1e-4, with 2 GPUs -> 2e-4
+accelerate launch --num_processes=2 $(which lerobot-train) \
+ --optimizer.lr=2e-4 \
+ --dataset.repo_id=lerobot/pusht \
+ --policy=act
+```
+
+**Training Steps Scaling:**
+
+Since the effective batch size `bs` increases with multiple GPUs (batch_size Γ num_gpus), you may want to reduce the number of training steps proportionally:
+
+```bash
+# Example: 2 GPUs with effective batch size 2x larger
+# Original: batch_size=8, steps=100000
+# With 2 GPUs: batch_size=8 (16 in total), steps=50000
+accelerate launch --num_processes=2 $(which lerobot-train) \
+ --batch_size=8 \
+ --steps=50000 \
+ --dataset.repo_id=lerobot/pusht \
+ --policy=act
+```
+
+## Notes
+
+- The `--policy.use_amp` flag in `lerobot-train` is only used when **not** running with accelerate. When using accelerate, mixed precision is controlled by accelerate's configuration.
+- Training logs, checkpoints, and hub uploads are only done by the main process to avoid conflicts. Non-main processes have console logging disabled to prevent duplicate output.
+- The effective batch size is `batch_size Γ num_gpus`. If you use 4 GPUs with `--batch_size=8`, your effective batch size is 32.
+- Learning rate scheduling is handled correctly across multiple processesβLeRobot sets `step_scheduler_with_optimizer=False` to prevent accelerate from adjusting scheduler steps based on the number of processes.
+- When saving or pushing models, LeRobot automatically unwraps the model from accelerate's distributed wrapper to ensure compatibility.
+- WandB integration automatically initializes only on the main process, preventing multiple runs from being created.
+
+For more advanced configurations and troubleshooting, see the [Accelerate documentation](https://huggingface.co/docs/accelerate). If you want to learn more about how to train on a large number of GPUs, checkout this awesome guide: [Ultrascale Playbook](https://huggingface.co/spaces/nanotron/ultrascale-playbook).
diff --git a/lerobot/docs/source/notebooks.mdx b/lerobot/docs/source/notebooks.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..34b45f80f2d83391b033082e5cb609ca7ed666ec
--- /dev/null
+++ b/lerobot/docs/source/notebooks.mdx
@@ -0,0 +1,29 @@
+# π€ LeRobot Notebooks
+
+This repository contains example notebooks for using LeRobot. These notebooks demonstrate how to train policies on real or simulation datasets using standardized policies.
+
+---
+
+### Training ACT
+
+[ACT](https://huggingface.co/papers/2304.13705) (Action Chunking Transformer) is a transformer-based policy architecture for imitation learning that processes robot states and camera inputs to generate smooth, chunked action sequences.
+
+We provide a ready-to-run Google Colab notebook to help you train ACT policies using datasets from the Hugging Face Hub, with optional logging to Weights & Biases.
+
+| Notebook | Colab |
+| :------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [Train ACT with LeRobot](https://github.com/huggingface/notebooks/blob/main/lerobot/training-act.ipynb) | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/lerobot/training-act.ipynb) |
+
+Expected training time for 100k steps: ~1.5 hours on an NVIDIA A100 GPU with batch size of `64`.
+
+### Training SmolVLA
+
+[SmolVLA](https://huggingface.co/papers/2506.01844) is a small but efficient Vision-Language-Action model. It is compact in size with 450 M-parameter and is developed by Hugging Face.
+
+We provide a ready-to-run Google Colab notebook to help you train SmolVLA policies using datasets from the Hugging Face Hub, with optional logging to Weights & Biases.
+
+| Notebook | Colab |
+| :-------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| [Train SmolVLA with LeRobot](https://github.com/huggingface/notebooks/blob/main/lerobot/training-smolvla.ipynb) | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/lerobot/training-smolvla.ipynb) |
+
+Expected training time for 20k steps: ~5 hours on an NVIDIA A100 GPU with batch size of `64`.
diff --git a/lerobot/docs/source/peft_training.mdx b/lerobot/docs/source/peft_training.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..e0d249731a68931a927c92659d8510163070f0ba
--- /dev/null
+++ b/lerobot/docs/source/peft_training.mdx
@@ -0,0 +1,62 @@
+# Parameter efficient fine-tuning with π€ PEFT
+
+[π€ PEFT](https://github.com/huggingface/peft) (Parameter-Efficient Fine-Tuning) is a library for efficiently adapting
+large pretrained models such as pre-trained policies (e.g., SmolVLA, Οβ, ...) to new tasks without training all
+of the model's parameters while yielding comparable performance.
+
+Install the `lerobot[peft]` optional package to enable PEFT support.
+
+To read about all the possible methods of adaption, please refer to the [π€ PEFT docs](https://huggingface.co/docs/peft/index).
+
+## Training SmolVLA
+
+In this section we'll show you how to train a pre-trained SmolVLA policy with PEFT on the libero dataset.
+For brevity we're only training on the `libero_spatial` subset. We will use `lerobot/smolvla_base` as the model
+to parameter efficiently fine-tune:
+
+```
+lerobot-train \
+ --policy.path=lerobot/smolvla_base \
+ --policy.repo_id=your_hub_name/my_libero_smolvla \
+ --dataset.repo_id=HuggingFaceVLA/libero \
+ --policy.output_features=null \
+ --policy.input_features=null \
+ --policy.optimizer_lr=1e-3 \
+ --policy.scheduler_decay_lr=1e-4 \
+ --env.type=libero \
+ --env.task=libero_spatial \
+ --steps=100000 \
+ --batch_size=32 \
+ --peft.method_type=LORA \
+ --peft.r=64
+```
+
+Note the `--peft.method_type` parameter that let's you select which PEFT method to use. Here we use
+[LoRA](https://huggingface.co/docs/peft/main/en/package_reference/lora) (Low-Rank Adapter) which is probably the most
+popular fine-tuning method to date. Low-rank adaption means that we only fine-tune a matrix with comparably low rank
+instead of the full weight matrix. This rank can be specified using the `--peft.r` parameter. The higher the rank
+the closer you get to full fine-tuning
+
+There are more complex methods that have more parameters. These are not yet supported, feel free to raise an issue
+if you want to see a specific PEFT method supported.
+
+By default, PEFT will target the `q_proj` and `v_proj` layers of the LM expert in SmolVLA. It will also target the
+state and action projection matrices as they are most likely task-dependent. If you need to target different layers
+you can use `--peft.target_modules` to specify which layers to target. You can refer to the respective PEFT method's
+documentation to see what inputs are supported, (e.g., [LoRA's target_modules documentation](https://huggingface.co/docs/peft/main/en/package_reference/lora#peft.LoraConfig.target_modules)).
+Usually a list of suffixes or a regex are supported. For example, to target the MLPs of the `lm_expert` instead of
+the `q` and `v` projections, use:
+
+```
+--peft.target_modules='(model\.vlm_with_expert\.lm_expert\..*\.(down|gate|up)_proj|.*\.(state_proj|action_in_proj|action_out_proj|action_time_mlp_in|action_time_mlp_out))'
+```
+
+In case you need to fully fine-tune a layer instead of just adapting it, you can supply a list of layer suffixes
+to the `--peft.full_training_modules` parameter:
+
+```
+--peft.full_training_modules=["state_proj"]
+```
+
+The learning rate and the scheduled target learning rate can usually be scaled by a factor of 10 compared to the
+learning rate used for full fine-tuning (e.g., 1e-4 normal, so 1e-3 using LoRA).
diff --git a/lerobot/docs/source/phone_teleop.mdx b/lerobot/docs/source/phone_teleop.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..f4850faa9d213524e449f477ef5c733bd203b2db
--- /dev/null
+++ b/lerobot/docs/source/phone_teleop.mdx
@@ -0,0 +1,191 @@
+# Phone
+
+Use your phone (iOS or Android) to control your robot.
+
+**In this guide you'll learn:**
+
+- How to connect an iOS/Android phone
+- How phone pose is mapped to robot endβeffector (EE) targets
+- How to tweak safety limits, gripper control, and IK settings
+
+To use phone to control your robot, install the relevant dependencies with:
+
+```bash
+pip install lerobot[phone]
+```
+
+## Get started
+
+### Supported platforms
+
+- iOS: Uses the HEBI Mobile I/O app (ARKit pose + buttons). Download the app first, open it and the examples will discover it on your network and stream the phone pose and inputs.
+- Android: Uses the `teleop` package (WebXR). When you start the Python process, it prints a local URL. Open the link on your phone, tap Start, then use Move to stream pose.
+
+Links:
+
+- Android WebXR library: [`teleop` on PyPI](https://pypi.org/project/teleop/)
+- iOS app: [HEBI Mobile I/O](https://docs.hebi.us/tools.html#mobile-io)
+
+### Phone orientation and controls
+
+- Orientation: hold the phone with the screen facing up and the top edge pointing in the same direction as the robot gripper. This ensures calibration aligns the phoneβs frame with the robot frame so motion feels natural, see the image below for reference.
+- Enable/disable:
+ - iOS: Hold `B1` to enable teleoperation, release to stop. The first press captures a reference pose.
+ - Android: Press and hold the `Move` button, release to stop. The first press captures a reference pose.
+- Gripper control:
+ - iOS: Analog input `A3` controls the gripper as velocity input.
+ - Android: Buttons `A` and `B` act like increment/decrement (A opens, B closes). You can tune velocity in the `GripperVelocityToJoint` step.
+
+
+
+### Step 1: Choose the platform
+
+Modify the examples to use `PhoneOS.IOS` or `PhoneOS.ANDROID` in `PhoneConfig`. The API is identical across platforms, only the input source differs. All examples are under `examples/` and have `phone_so100_*.py` variants.
+
+Teleoperation example:
+
+```python
+from lerobot.teleoperators.phone.config_phone import PhoneConfig, PhoneOS
+
+teleop_config = PhoneConfig(phone_os=PhoneOS.IOS) # or PhoneOS.ANDROID
+teleop_device = Phone(teleop_config)
+```
+
+### Step 2: Connect and calibrate
+
+When `Phone(teleop_config)` is created and `connect()` is called, calibration is prompted automatically. Hold the phone in the orientation described above, then:
+
+- iOS: press and hold `B1` to capture the reference pose.
+- Android: press `Move` button on the WebXR page to capture the reference pose.
+
+Why calibrate? We capture the current pose so subsequent poses are expressed in a robot aligned frame. When you again press the button to enable control, the position is recaptured to avoid drift when your phone is repositioned while it was disabled.
+
+### Step 3: Run an example
+
+Run on of the examples scripts to teleoperate, record a dataset, replay a dataset or evaluate a policy.
+
+All scripts assume you configured your robot (e.g., SO-100 follower) and set the correct serial port.
+
+Additionally you need to **copy the urdf of the robot to the examples folder**. For the examples in this tutorial (Using SO100/SO101) it is highly recommended to use the urdf in the [SO-ARM100 repo](https://github.com/TheRobotStudio/SO-ARM100/blob/main/Simulation/SO101/so101_new_calib.urdf)
+
+- Run this example to teleoperate:
+
+ ```bash
+ python examples/phone_to_so100/teleoperate.py
+ ```
+
+After running the example:
+
+- Android: after starting the script, open the printed local URL on your phone, tap Start, then press and hold Move.
+- iOS: open HEBI Mobile I/O first; B1 enables motion. A3 controls the gripper.
+
+Additionally you can customize mapping or safety limits by editing the processor steps shown in the examples. You can also remap inputs (e.g., use a different analog input) or adapt the pipeline to other robots (e.g., LeKiwi) by modifying the input and kinematics steps. More about this in the [Processors for Robots and Teleoperators](./processors_robots_teleop) guide.
+
+- Run this example to record a dataset, which saves absolute end effector observations and actions:
+
+ ```bash
+ python examples/phone_to_so100/record.py
+ ```
+
+- Run this example to replay recorded episodes:
+
+ ```bash
+ python examples/phone_to_so100/replay.py
+ ```
+
+- Run this example to evaluate a pretrained policy:
+
+ ```bash
+ python examples/phone_to_so100/evaluate.py
+ ```
+
+### Important pipeline steps and options
+
+- Kinematics are used in multiple steps. We use [Placo](https://github.com/Rhoban/placo) which is a wrapper around Pinocchio for handling our kinematics. We construct the kinematics object by passing the robot's URDF and target frame. We set `target_frame_name` to the gripper frame.
+
+ ```python
+ kinematics_solver = RobotKinematics(
+ urdf_path="./SO101/so101_new_calib.urdf",
+ target_frame_name="gripper_frame_link",
+ joint_names=list(robot.bus.motors.keys()),
+ )
+
+ ```
+
+- The `MapPhoneActionToRobotAction` step converts the calibrated phone pose and inputs into target deltas and gripper commands, below is shown what the step outputs.
+
+ ```python
+ action["enabled"] = enabled
+ action["target_x"] = -pos[1] if enabled else 0.0
+ action["target_y"] = pos[0] if enabled else 0.0
+ action["target_z"] = pos[2] if enabled else 0.0
+ action["target_wx"] = rotvec[1] if enabled else 0.0
+ action["target_wy"] = rotvec[0] if enabled else 0.0
+ action["target_wz"] = -rotvec[2] if enabled else 0.0
+ action["gripper_vel"] = gripper_vel # Still send gripper action when disabled
+ ```
+
+- The `EEReferenceAndDelta` step converts target deltas to an absolute desired EE pose, storing a reference on enable, the `end_effector_step_sizes` are the step sizes for the EE pose and can be modified to change the motion speed.
+
+ ```python
+ EEReferenceAndDelta(
+ kinematics=kinematics_solver,
+ end_effector_step_sizes={"x": 0.5, "y": 0.5, "z": 0.5},
+ motor_names=list(robot.bus.motors.keys()),
+ use_latched_reference=True,
+ ),
+ ```
+
+- The `EEBoundsAndSafety` step clamps EE motion to a workspace and checks for large ee step jumps to ensure safety. The `end_effector_bounds` are the bounds for the EE pose and can be modified to change the workspace. The `max_ee_step_m` are the step limits for the EE pose and can be modified to change the safety limits.
+
+ ```python
+ EEBoundsAndSafety(
+ end_effector_bounds={"min": [-1.0, -1.0, -1.0], "max": [1.0, 1.0, 1.0]},
+ max_ee_step_m=0.10,
+ )
+ ```
+
+- The `GripperVelocityToJoint` step turns a velocityβlike gripper input into absolute gripper position using the current measured state. The `speed_factor` is the factor by which the velocity is multiplied.
+
+ ```python
+ GripperVelocityToJoint(speed_factor=20.0)
+ ```
+
+#### Different IK initial guesses
+
+We use different IK initial guesses in the kinematic steps. As initial guess either the current measured joints or the previous IK solution is used.
+
+- Closed loop (used in record/eval): sets `initial_guess_current_joints=True` so IK starts from the measured joints each frame.
+
+ ```python
+ InverseKinematicsEEToJoints(
+ kinematics=kinematics_solver,
+ motor_names=list(robot.bus.motors.keys()),
+ initial_guess_current_joints=True, # closed loop
+ )
+ ```
+
+- Open loop (used in replay): sets `initial_guess_current_joints=False` so IK continues from the previous IK solution rather than the measured state. This preserves action stability when we replay without feedback.
+
+ ```python
+ InverseKinematicsEEToJoints(
+ kinematics=kinematics_solver,
+ motor_names=list(robot.bus.motors.keys()),
+ initial_guess_current_joints=False, # open loop
+ )
+ ```
+
+### Pipeline steps explained
+
+- MapPhoneActionToRobotAction: converts calibrated phone pose and inputs into target deltas and a gripper command. Motion is gated by an enable signal (B1 on iOS, Move on Android).
+- EEReferenceAndDelta: latches a reference EE pose on enable and combines it with target deltas to produce an absolute desired EE pose each frame. When disabled, it keeps sending the last commanded pose.
+- EEBoundsAndSafety: clamps the EE pose to a workspace and rateβlimits jumps for safety. Also declares `action.ee.*` features.
+- InverseKinematicsEEToJoints: turns an EE pose into joint positions with IK. `initial_guess_current_joints=True` is recommended for closedβloop control; set `False` for openβloop replay for stability.
+- GripperVelocityToJoint: integrates a velocityβlike gripper input into an absolute gripper position using the current measured state.
+- ForwardKinematicsJointsToEE: computes `observation.state.ee.*` from observed joints for logging and training on EE state.
+
+### Troubleshooting
+
+- iOS not discovered: ensure HEBI Mobile I/O is open and your laptop/phone are on the same network.
+- Android URL not reachable: check local you used `https` instead of `http`, use the exact IP printed by the script and allow your browser to enter and ignore the certificate issue.
+- Motion feels inverted: adjust the sign flips in `MapPhoneActionToRobotAction` or swap axes to match your setup.
diff --git a/lerobot/docs/source/pi0.mdx b/lerobot/docs/source/pi0.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..16dfa822dbf495c1b5c83f2211faaf59ccd3bd8a
--- /dev/null
+++ b/lerobot/docs/source/pi0.mdx
@@ -0,0 +1,101 @@
+# Οβ (Pi0)
+
+Οβ is a **Vision-Language-Action model for general robot control**, from Physical Intelligence. The LeRobot implementation is adapted from their open source [OpenPI](https://github.com/Physical-Intelligence/openpi) repository.
+
+## Model Overview
+
+Οβ represents a breakthrough in robotics as the first general-purpose robot foundation model developed by [Physical Intelligence](https://www.physicalintelligence.company/blog/pi0). Unlike traditional robot programs that are narrow specialists programmed for repetitive motions, Οβ is designed to be a generalist policy that can understand visual inputs, interpret natural language instructions, and control a variety of different robots across diverse tasks.
+
+
+
+### The Vision for Physical Intelligence
+
+As described by Physical Intelligence, while AI has achieved remarkable success in digital domains, from chess-playing to drug discovery, human intelligence still dramatically outpaces AI in the physical world. To paraphrase Moravec's paradox, winning a game of chess represents an "easy" problem for AI, but folding a shirt or cleaning up a table requires solving some of the most difficult engineering problems ever conceived. Οβ represents a first step toward developing artificial physical intelligence that enables users to simply ask robots to perform any task they want, just like they can with large language models.
+
+### Architecture and Approach
+
+Οβ combines several key innovations:
+
+- **Flow Matching**: Uses a novel method to augment pre-trained VLMs with continuous action outputs via flow matching (a variant of diffusion models)
+- **Cross-Embodiment Training**: Trained on data from 8 distinct robot platforms including UR5e, Bimanual UR5e, Franka, Bimanual Trossen, Bimanual ARX, Mobile Trossen, and Mobile Fibocom
+- **Internet-Scale Pre-training**: Inherits semantic knowledge from a pre-trained 3B parameter Vision-Language Model
+- **High-Frequency Control**: Outputs motor commands at up to 50 Hz for real-time dexterous manipulation
+
+## Installation Requirements
+
+1. Install LeRobot by following our [Installation Guide](./installation).
+2. Install Pi0 dependencies by running:
+
+ ```bash
+ pip install -e ".[pi]"
+ ```
+
+ > [!NOTE]
+ > For lerobot 0.4.0, if you want to install pi tag, you will have to do: `pip install "lerobot[pi]@git+https://github.com/huggingface/lerobot.git"`.
+ >
+ > This will be solved in the next patch release
+
+## Training Data and Capabilities
+
+Οβ is trained on the largest robot interaction dataset to date, combining three key data sources:
+
+1. **Internet-Scale Pre-training**: Vision-language data from the web for semantic understanding
+2. **Open X-Embodiment Dataset**: Open-source robot manipulation datasets
+3. **Physical Intelligence Dataset**: Large and diverse dataset of dexterous tasks across 8 distinct robots
+
+## Usage
+
+To use Οβ in LeRobot, specify the policy type as:
+
+```python
+policy.type=pi0
+```
+
+## Training
+
+For training Οβ, you can use the standard LeRobot training script with the appropriate configuration:
+
+```bash
+python src/lerobot/scripts/lerobot_train.py \
+ --dataset.repo_id=your_dataset \
+ --policy.type=pi0 \
+ --output_dir=./outputs/pi0_training \
+ --job_name=pi0_training \
+ --policy.pretrained_path=lerobot/pi0_base \
+ --policy.repo_id=your_repo_id \
+ --policy.compile_model=true \
+ --policy.gradient_checkpointing=true \
+ --policy.dtype=bfloat16 \
+ --policy.freeze_vision_encoder=false \
+ --policy.train_expert_only=false \
+ --steps=3000 \
+ --policy.device=cuda \
+ --batch_size=32
+```
+
+### Key Training Parameters
+
+- **`--policy.compile_model=true`**: Enables model compilation for faster training
+- **`--policy.gradient_checkpointing=true`**: Reduces memory usage significantly during training
+- **`--policy.dtype=bfloat16`**: Use mixed precision training for efficiency
+- **`--batch_size=32`**: Batch size for training, adapt this based on your GPU memory
+- **`--policy.pretrained_path=lerobot/pi0_base`**: The base Οβ model you want to finetune, options are:
+ - [lerobot/pi0_base](https://huggingface.co/lerobot/pi0_base)
+ - [lerobot/pi0_libero](https://huggingface.co/lerobot/pi0_libero) (specifically trained on the Libero dataset)
+
+### Training Parameters Explained
+
+| Parameter | Default | Description |
+| ----------------------- | ------- | ------------------------------------------- |
+| `freeze_vision_encoder` | `false` | Do not freeze the vision encoder |
+| `train_expert_only` | `false` | Do not freeze the VLM, train all parameters |
+
+**π‘ Tip**: Setting `train_expert_only=true` freezes the VLM and trains only the action expert and projections, allowing finetuning with reduced memory usage.
+
+## License
+
+This model follows the **Apache 2.0 License**, consistent with the original [OpenPI repository](https://github.com/Physical-Intelligence/openpi).
diff --git a/lerobot/docs/source/pi05.mdx b/lerobot/docs/source/pi05.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..36193a512391a4e438ee5935a12468a06c440f12
--- /dev/null
+++ b/lerobot/docs/source/pi05.mdx
@@ -0,0 +1,123 @@
+# Οβ.β (Pi05) Policy
+
+Οβ.β is a **Vision-Language-Action model with open-world generalization**, from Physical Intelligence. The LeRobot implementation is adapted from their open source [OpenPI](https://github.com/Physical-Intelligence/openpi) repository.
+
+## Model Overview
+
+Οβ.β represents a significant evolution from Οβ, developed by [Physical Intelligence](https://www.physicalintelligence.company/blog/pi05) to address a big challenge in robotics: **open-world generalization**. While robots can perform impressive tasks in controlled environments, Οβ.β is designed to generalize to entirely new environments and situations that were never seen during training.
+
+### The Generalization Challenge
+
+As Physical Intelligence explains, the fundamental challenge isn't performing tasks of agility or dexterity, but generalization, the ability to correctly perform tasks in new settings with new objects. Consider a robot cleaning different homes: each home has different objects in different places. Generalization must occur at multiple levels:
+
+- **Physical Level**: Understanding how to pick up a spoon (by the handle) or plate (by the edge), even with unseen objects in cluttered environments
+- **Semantic Level**: Understanding task semantics, where to put clothes and shoes (laundry hamper, not on the bed), and what tools are appropriate for cleaning spills
+- **Environmental Level**: Adapting to "messy" real-world environments like homes, grocery stores, offices, and hospitals
+
+### Co-Training on Heterogeneous Data
+
+The breakthrough innovation in Οβ.β is **co-training on heterogeneous data sources**. The model learns from:
+
+1. **Multimodal Web Data**: Image captioning, visual question answering, object detection
+2. **Verbal Instructions**: Humans coaching robots through complex tasks step-by-step
+3. **Subtask Commands**: High-level semantic behavior labels (e.g., "pick up the pillow" for an unmade bed)
+4. **Cross-Embodiment Robot Data**: Data from various robot platforms with different capabilities
+5. **Multi-Environment Data**: Static robots deployed across many different homes
+6. **Mobile Manipulation Data**: ~400 hours of mobile robot demonstrations
+
+This diverse training mixture creates a "curriculum" that enables generalization across physical, visual, and semantic levels simultaneously.
+
+## Installation Requirements
+
+1. Install LeRobot by following our [Installation Guide](./installation).
+2. Install Pi0.5 dependencies by running:
+
+ ```bash
+ pip install -e ".[pi]"
+ ```
+
+ > [!NOTE]
+ > For lerobot 0.4.0, if you want to install pi tag, you will have to do: `pip install "lerobot[pi]@git+https://github.com/huggingface/lerobot.git"`.
+ >
+ > This will be solved in the next patch release
+
+## Usage
+
+To use Οβ.β in your LeRobot configuration, specify the policy type as:
+
+```python
+policy.type=pi05
+```
+
+## Training
+
+### Training Command Example
+
+Here's a complete training command for finetuning the base Οβ.β model on your own dataset:
+
+```bash
+python src/lerobot/scripts/lerobot_train.py\
+ --dataset.repo_id=your_dataset \
+ --policy.type=pi05 \
+ --output_dir=./outputs/pi05_training \
+ --job_name=pi05_training \
+ --policy.repo_id=your_repo_id \
+ --policy.pretrained_path=lerobot/pi05_base \
+ --policy.compile_model=true \
+ --policy.gradient_checkpointing=true \
+ --wandb.enable=true \
+ --policy.dtype=bfloat16 \
+ --policy.freeze_vision_encoder=false \
+ --policy.train_expert_only=false \
+ --steps=3000 \
+ --policy.device=cuda \
+ --batch_size=32
+```
+
+### Key Training Parameters
+
+- **`--policy.compile_model=true`**: Enables model compilation for faster training
+- **`--policy.gradient_checkpointing=true`**: Reduces memory usage significantly during training
+- **`--policy.dtype=bfloat16`**: Use mixed precision training for efficiency
+- **`--batch_size=32`**: Batch size for training, adapt this based on your GPU memory
+- **`--policy.pretrained_path=lerobot/pi05_base`**: The base Οβ.β model you want to finetune, options are:
+ - [lerobot/pi05_base](https://huggingface.co/lerobot/pi05_base)
+ - [lerobot/pi05_libero](https://huggingface.co/lerobot/pi05_libero) (specifically trained on the Libero dataset)
+
+### Training Parameters Explained
+
+| Parameter | Default | Description |
+| ----------------------- | ------- | ------------------------------------------- |
+| `freeze_vision_encoder` | `false` | Do not freeze the vision encoder |
+| `train_expert_only` | `false` | Do not freeze the VLM, train all parameters |
+
+**π‘ Tip**: Setting `train_expert_only=true` freezes the VLM and trains only the action expert and projections, allowing finetuning with reduced memory usage.
+
+If your dataset is not converted with `quantiles`, you can convert it with the following command:
+
+```bash
+python src/lerobot/datasets/v30/augment_dataset_quantile_stats.py \
+ --repo-id=your_dataset \
+```
+
+Or train pi05 with this normalization mapping: `--policy.normalization_mapping='{"ACTION": "MEAN_STD", "STATE": "MEAN_STD", "VISUAL": "IDENTITY"}'`
+
+## Performance Results
+
+### Libero Benchmark Results
+
+Οβ.β has demonstrated strong performance on the Libero benchmark suite. To compare and test its LeRobot implementation, we finetuned the libero base model for an additional 6k steps on the Libero dataset and compared the results to the OpenPI reference results.
+
+| Benchmark | LeRobot Implementation | OpenPI Reference |
+| ------------------ | ---------------------- | ---------------- |
+| **Libero Spatial** | 97.0% | 98.8% |
+| **Libero Object** | 99.0% | 98.2% |
+| **Libero Goal** | 98.0% | 98.0% |
+| **Libero 10** | 96.0% | 92.4% |
+| **Average** | 97.5% | 96.85% |
+
+These results demonstrate Οβ.β 's strong generalization capabilities across diverse robotic manipulation tasks. To reproduce these results, you can follow the instructions in the [Libero](https://huggingface.co/docs/lerobot/libero) section.
+
+## License
+
+This model follows the **Apache 2.0 License**, consistent with the original [OpenPI repository](https://github.com/Physical-Intelligence/openpi).
diff --git a/lerobot/docs/source/pi0fast.mdx b/lerobot/docs/source/pi0fast.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..d69e79977d034d6278cef1a647f7a0ae0f82419a
--- /dev/null
+++ b/lerobot/docs/source/pi0fast.mdx
@@ -0,0 +1,246 @@
+# Οβ-FAST (Pi0-FAST)
+
+Οβ-FAST is a **Vision-Language-Action model for general robot control** that uses autoregressive next-token prediction to model continuous robot actions.
+
+## Model Overview
+
+Οβ-FAST combines the power of Vision-Language Models with a novel action tokenization approach called **FAST (Frequency-space Action Sequence Tokenization)**. This enables training autoregressive VLAs on highly dexterous tasks that are impossible with standard binning-based discretization, while training **up to 5x faster** than diffusion-based approaches like Οβ.
+
+
+
+### Why FAST?
+
+Standard approaches for robot action tokenization use simple per-dimension, per-timestep binning schemes. While passable for simple behaviors, this rapidly breaks down for complex and dexterous skills that require precision and high-frequency control.
+
+FAST solves this by compressing action sequences using signal processing techniques, resulting in a dense sequence of action tokens that can be predicted autoregressivelyβjust like language tokens.
+
+### How FAST Tokenization Works
+
+The FAST tokenizer compresses action sequences through the following steps:
+
+1. **Normalize**: Take a continuous action chunk of shape `(H, D)` where `H` is the horizon and `D` is the action dimension. Normalize using one of the supported normalization methods (Quantiles recommended to handle outliers).
+
+2. **Discrete Cosine Transform (DCT)**: Apply DCT (via scipy) to each action dimension separately. DCT is a compression algorithm commonly used in image and audio codecs (JPEG, MP3).
+
+3. **Quantization**: Round and remove insignificant coefficients for each action dimension, producing a sparse frequency matrix.
+
+4. **Flatten**: Flatten the matrix into a 1D vector, with low-frequency components first.
+
+5. **Byte Pair Encoding (BPE)**: Train a BPE tokenizer to compress the DCT coefficients into dense action tokens, typically achieving **10x compression** over prior tokenization approaches.
+
+This approach can transform **any existing VLM** into a VLA by training it to predict these FAST tokens.
+
+## Installation Requirements
+
+1. Install LeRobot by following our [Installation Guide](./installation).
+2. Install Οβ-FAST dependencies by running:
+
+ ```bash
+ pip install -e ".[pi]"
+ ```
+
+ > [!NOTE]
+ > For lerobot 0.4.0, if you want to install the pi tag, you will have to do: `pip install "lerobot[pi]@git+https://github.com/huggingface/lerobot.git"`.
+ >
+ > This will be solved in the next patch release
+
+## Training a Custom FAST Tokenizer
+
+You have two options for the FAST tokenizer:
+
+1. **Use the pre-trained tokenizer**: The `physical-intelligence/fast` tokenizer was trained on 1M+ real robot action sequences and works as a general-purpose tokenizer.
+
+2. **Train your own tokenizer**: For maximum performance on your specific dataset, you can finetune the tokenizer on your own data.
+
+### Training Your Own Tokenizer
+
+```bash
+lerobot-train-tokenizer \
+ --repo_id "user/my-lerobot-dataset" \
+ --action_horizon 10 \
+ --encoded_dims "0:6" \
+ --vocab_size 1024 \
+ --scale 10.0 \
+ --normalization_mode QUANTILES \
+ --output_dir "./my_fast_tokenizer" \
+ --push_to_hub \
+ --hub_repo_id "username/my-action-tokenizer"
+```
+
+### Key Tokenizer Parameters
+
+| Parameter | Description | Default |
+| ---------------------- | --------------------------------------------------------------------------------- | ------------ |
+| `--repo_id` | LeRobot dataset repository ID | Required |
+| `--action_horizon` | Number of future actions in each chunk | `10` |
+| `--encoded_dims` | Comma-separated dimension ranges to encode (e.g., `"0:6,7:23"`) | `"0:6,7:23"` |
+| `--vocab_size` | BPE vocabulary size | `1024` |
+| `--scale` | DCT scaling factor for quantization | `10.0` |
+| `--normalization_mode` | Normalization mode (`MEAN_STD`, `MIN_MAX`, `QUANTILES`, `QUANTILE10`, `IDENTITY`) | `QUANTILES` |
+| `--sample_fraction` | Fraction of chunks to sample per episode | `0.1` |
+
+## Usage
+
+To use Οβ-FAST in LeRobot, specify the policy type as:
+
+```python
+policy.type=pi0_fast
+```
+
+## Training
+
+For training Οβ-FAST, you can use the LeRobot training script:
+
+```bash
+lerobot-train \
+ --dataset.repo_id=your_dataset \
+ --policy.type=pi0_fast \
+ --output_dir=./outputs/pi0fast_training \
+ --job_name=pi0fast_training \
+ --policy.pretrained_path=lerobot/pi0_fast_base \
+ --policy.dtype=bfloat16 \
+ --policy.gradient_checkpointing=true \
+ --policy.chunk_size=10 \
+ --policy.n_action_steps=10 \
+ --policy.max_action_tokens=256 \
+ --steps=100000 \
+ --batch_size=4 \
+ --policy.device=cuda
+```
+
+### Key Training Parameters
+
+| Parameter | Description | Default |
+| -------------------------------------- | -------------------------------------------------- | ---------------------------- |
+| `--policy.gradient_checkpointing=true` | Reduces memory usage significantly during training | `false` |
+| `--policy.dtype=bfloat16` | Use mixed precision training for efficiency | `float32` |
+| `--policy.chunk_size` | Number of action steps to predict (action horizon) | `50` |
+| `--policy.n_action_steps` | Number of action steps to execute | `50` |
+| `--policy.max_action_tokens` | Maximum number of FAST tokens per action chunk | `256` |
+| `--policy.action_tokenizer_name` | FAST tokenizer to use | `physical-intelligence/fast` |
+| `--policy.compile_model=true` | Enable torch.compile for faster training | `false` |
+
+## Inference
+
+### KV-Caching for Fast Inference
+
+Οβ-FAST supports **KV-caching**, a widely used optimization in LLM inference. This caches the key-value pairs from the attention mechanism, avoiding redundant computation during autoregressive decoding.
+
+```python
+# KV-caching is enabled by default
+policy.use_kv_cache=true
+```
+
+### Inference Example
+
+```python
+from lerobot.policies.pi0_fast import PI0FastPolicy, PI0FastConfig
+
+# Load the policy
+policy = PI0FastPolicy.from_pretrained("your-model-path")
+
+# During inference
+actions = policy.predict_action_chunk(batch)
+```
+
+## Model Architecture
+
+Οβ-FAST uses a PaliGemma-based architecture:
+
+- **Vision Encoder**: SigLIP vision tower for image understanding
+- **Language Model**: Gemma 2B for processing language instructions and predicting action tokens
+
+The model takes images, text instructions, and robot state as input, and outputs discrete FAST tokens that are decoded back to continuous actions.
+
+## Configuration Options
+
+| Parameter | Description | Default |
+| -------------------- | ----------------------------------------------- | ---------- |
+| `paligemma_variant` | VLM backbone variant (`gemma_300m`, `gemma_2b`) | `gemma_2b` |
+| `max_state_dim` | Maximum state vector dimension (padded) | `32` |
+| `max_action_dim` | Maximum action vector dimension (padded) | `32` |
+| `temperature` | Sampling temperature (0.0 for greedy) | `0.0` |
+| `max_decoding_steps` | Maximum decoding steps | `256` |
+| `use_kv_cache` | Enable KV caching for faster inference | `true` |
+
+## Comparison with Οβ
+
+| Feature | Οβ | Οβ-FAST |
+| --------------------- | ------------------------- | ---------------------------- |
+| Action Representation | Flow Matching (Diffusion) | Autoregressive Tokens (FAST) |
+| Training Speed | 1x | **5x faster** |
+| Dexterity | High | High |
+| Inference Method | Iterative Denoising | Autoregressive Decoding |
+| KV-Caching | N/A | Supported |
+
+## Reproducing ΟβFast results
+
+We reproduce the results of ΟβFast on the LIBERO benchmark using the LeRobot implementation. We take the LeRobot PiFast base model [lerobot/pi0fast-base](https://huggingface.co/lerobot/pi0fast-base) and finetune for an additional 40kk steps in bfloat16, with batch size of 256 on 8 H100 GPUs using the [HuggingFace LIBERO dataset](https://huggingface.co/datasets/HuggingFaceVLA/libero).
+
+The finetuned model can be found here:
+
+- **ΟβFast LIBERO**: [lerobot/pi0fast-libero](https://huggingface.co/lerobot/pi0fast-libero)
+
+With the following training command:
+
+```bash
+lerobot-train \
+ --dataset.repo_id=lerobot/libero \
+ --output_dir=outputs/libero_pi0fast \
+ --job_name=libero_pi0fast \
+ --policy.path=lerobot/pi0fast_base \
+ --policy.dtype=bfloat16 \
+ --steps=100000 \
+ --save_freq=20000 \
+ --batch_size=4 \
+ --policy.device=cuda \
+ --policy.scheduler_warmup_steps=4000 \
+ --policy.scheduler_decay_steps=100000 \
+ --policy.scheduler_decay_lr=1e-5 \
+ --policy.gradient_checkpointing=true \
+ --policy.chunk_size=10 \
+ --policy.n_action_steps=10 \
+ --policy.max_action_tokens=256 \
+ --policy.empty_cameras=1 \
+```
+
+We then evaluate the finetuned model using the LeRobot LIBERO implementation, by running the following command:
+
+```bash
+tasks="libero_object,libero_spatial,libero_goal,libero_10"
+lerobot-eval \
+ --policy.path=lerobot/pi0fast-libero \
+ --policy.max_action_tokens=256 \
+ --env.type=libero \
+ --policy.gradient_checkpointing=false \
+ --env.task=${tasks} \
+ --eval.batch_size=1 \
+ --eval.n_episodes=1 \
+ --rename_map='{"observation.images.image":"observation.images.base_0_rgb","observation.images.image2":"observation.images.left_wrist_0_rgb"}'
+```
+
+**Note:** We set `n_action_steps=10`, similar to the original OpenPI implementation.
+
+### Results
+
+We obtain the following results on the LIBERO benchmark:
+
+| Model | LIBERO Spatial | LIBERO Object | LIBERO Goal | LIBERO 10 | Average |
+| ----------- | -------------- | ------------- | ----------- | --------- | -------- |
+| **Οβ-fast** | 70.0 | 100.0 | 100.0 | 60.0 | **82.5** |
+
+The full evaluation output folder, including videos, is available [here](https://drive.google.com/drive/folders/1HXpwPTRm4hx6g1sF2P7OOqGG0TwPU7LQ?usp=sharing)
+
+## License
+
+This model follows the **Apache 2.0 License**, consistent with the original [OpenPI repository](https://github.com/Physical-Intelligence/openpi).
+
+## References
+
+- [FAST: Efficient Robot Action Tokenization](https://www.physicalintelligence.company/research/fast) - Physical Intelligence Blog
+- [OpenPI Repository](https://github.com/Physical-Intelligence/openpi) - Original implementation
+- [FAST Tokenizer on Hugging Face](https://huggingface.co/physical-intelligence/fast) - Pre-trained tokenizer
diff --git a/lerobot/docs/source/policy_act_README.md b/lerobot/docs/source/policy_act_README.md
new file mode 100644
index 0000000000000000000000000000000000000000..ed884402c4c1094c69308aeeeed2ceb577e94628
--- /dev/null
+++ b/lerobot/docs/source/policy_act_README.md
@@ -0,0 +1,14 @@
+## Paper
+
+https://tonyzhaozh.github.io/aloha
+
+## Citation
+
+```bibtex
+@article{zhao2023learning,
+ title={Learning fine-grained bimanual manipulation with low-cost hardware},
+ author={Zhao, Tony Z and Kumar, Vikash and Levine, Sergey and Finn, Chelsea},
+ journal={arXiv preprint arXiv:2304.13705},
+ year={2023}
+}
+```
diff --git a/lerobot/docs/source/policy_diffusion_README.md b/lerobot/docs/source/policy_diffusion_README.md
new file mode 100644
index 0000000000000000000000000000000000000000..b8493afe0dbb363f69cd813f69150b77fc3f44d7
--- /dev/null
+++ b/lerobot/docs/source/policy_diffusion_README.md
@@ -0,0 +1,14 @@
+## Paper
+
+https://diffusion-policy.cs.columbia.edu
+
+## Citation
+
+```bibtex
+@article{chi2024diffusionpolicy,
+ author = {Cheng Chi and Zhenjia Xu and Siyuan Feng and Eric Cousineau and Yilun Du and Benjamin Burchfiel and Russ Tedrake and Shuran Song},
+ title ={Diffusion Policy: Visuomotor Policy Learning via Action Diffusion},
+ journal = {The International Journal of Robotics Research},
+ year = {2024},
+}
+```
diff --git a/lerobot/docs/source/policy_groot_README.md b/lerobot/docs/source/policy_groot_README.md
new file mode 100644
index 0000000000000000000000000000000000000000..c2e435d9e7a91c6644cb0e626947ae60f7cf888c
--- /dev/null
+++ b/lerobot/docs/source/policy_groot_README.md
@@ -0,0 +1,27 @@
+## Research Paper
+
+Paper: https://research.nvidia.com/labs/gear/gr00t-n1_5/
+
+## Repository
+
+Code: https://github.com/NVIDIA/Isaac-GR00T
+
+## Citation
+
+```bibtex
+@inproceedings{gr00tn1_2025,
+ archivePrefix = {arxiv},
+ eprint = {2503.14734},
+ title = {{GR00T} {N1}: An Open Foundation Model for Generalist Humanoid Robots},
+ author = {NVIDIA and Johan Bjorck andFernando CastaΓ±eda, Nikita Cherniadev and Xingye Da and Runyu Ding and Linxi "Jim" Fan and Yu Fang and Dieter Fox and Fengyuan Hu and Spencer Huang and Joel Jang and Zhenyu Jiang and Jan Kautz and Kaushil Kundalia and Lawrence Lao and Zhiqi Li and Zongyu Lin and Kevin Lin and Guilin Liu and Edith Llontop and Loic Magne and Ajay Mandlekar and Avnish Narayan and Soroush Nasiriany and Scott Reed and You Liang Tan and Guanzhi Wang and Zu Wang and Jing Wang and Qi Wang and Jiannan Xiang and Yuqi Xie and Yinzhen Xu and Zhenjia Xu and Seonghyeon Ye and Zhiding Yu and Ao Zhang and Hao Zhang and Yizhou Zhao and Ruijie Zheng and Yuke Zhu},
+ month = {March},
+ year = {2025},
+ booktitle = {ArXiv Preprint},
+}
+```
+
+## Additional Resources
+
+Blog: https://developer.nvidia.com/isaac/gr00t
+
+Hugging Face Model: https://huggingface.co/nvidia/GR00T-N1.5-3B
diff --git a/lerobot/docs/source/policy_smolvla_README.md b/lerobot/docs/source/policy_smolvla_README.md
new file mode 100644
index 0000000000000000000000000000000000000000..2e83a080c19b5c23aa48f80b254cbb28191f3a99
--- /dev/null
+++ b/lerobot/docs/source/policy_smolvla_README.md
@@ -0,0 +1,14 @@
+## Paper
+
+https://arxiv.org/abs/2506.01844
+
+## Citation
+
+```bibtex
+@article{shukor2025smolvla,
+ title={SmolVLA: A Vision-Language-Action Model for Affordable and Efficient Robotics},
+ author={Shukor, Mustafa and Aubakirova, Dana and Capuano, Francesco and Kooijmans, Pepijn and Palma, Steven and Zouitine, Adil and Aractingi, Michel and Pascal, Caroline and Russi, Martino and Marafioti, Andres and Alibert, Simon and Cord, Matthieu and Wolf, Thomas and Cadene, Remi},
+ journal={arXiv preprint arXiv:2506.01844},
+ year={2025}
+}
+```
diff --git a/lerobot/docs/source/policy_tdmpc_README.md b/lerobot/docs/source/policy_tdmpc_README.md
new file mode 100644
index 0000000000000000000000000000000000000000..6a9eb295a3ac08f166aeae96209bdf1c7b0c3995
--- /dev/null
+++ b/lerobot/docs/source/policy_tdmpc_README.md
@@ -0,0 +1,14 @@
+## Paper
+
+https://www.nicklashansen.com/td-mpc/
+
+## Citation
+
+```bibtex
+@inproceedings{Hansen2022tdmpc,
+ title={Temporal Difference Learning for Model Predictive Control},
+ author={Nicklas Hansen and Xiaolong Wang and Hao Su},
+ booktitle={ICML},
+ year={2022}
+}
+```
diff --git a/lerobot/docs/source/policy_vqbet_README.md b/lerobot/docs/source/policy_vqbet_README.md
new file mode 100644
index 0000000000000000000000000000000000000000..1d1aa29aa65590c3465543aad288a7705151caab
--- /dev/null
+++ b/lerobot/docs/source/policy_vqbet_README.md
@@ -0,0 +1,14 @@
+## Paper
+
+https://sjlee.cc/vq-bet/
+
+## Citation
+
+```bibtex
+@article{lee2024behavior,
+ title={Behavior generation with latent actions},
+ author={Lee, Seungjae and Wang, Yibin and Etukuru, Haritheja and Kim, H Jin and Shafiullah, Nur Muhammad Mahi and Pinto, Lerrel},
+ journal={arXiv preprint arXiv:2403.03181},
+ year={2024}
+}
+```
diff --git a/lerobot/docs/source/policy_walloss_README.md b/lerobot/docs/source/policy_walloss_README.md
new file mode 100644
index 0000000000000000000000000000000000000000..26e9d122a261cfb69c40eb3adcafa4f7117cb115
--- /dev/null
+++ b/lerobot/docs/source/policy_walloss_README.md
@@ -0,0 +1,45 @@
+# WALL-OSS
+
+This repository contains the Hugging Face port of [**WALL-OSS**](https://x2robot.com/en/research/68bc2cde8497d7f238dde690), a Vision-Language-Action model for cross-embodiment robotic control based on Qwen2.5-VL with flow matching/FAST action prediction.
+
+---
+
+## Model Overview
+
+| Feature | Description |
+| ------------------ | ----------------------------------------------------- |
+| Base Model | Qwen2.5-VL (Vision-Language Model) |
+| Action Prediction | Flow Matching (diffusion) or FAST (discrete tokens) |
+| Architecture | Mixture of Experts (MoE) with action-specific routing |
+| Multi-Modal Inputs | Vision (images/videos), Language, Proprioception |
+
+---
+
+## Additional Resources
+
+Paper: https://arxiv.org/pdf/2509.11766
+
+Official Repository: https://github.com/X-Square-Robot/wall-x
+
+Hugging Face: https://huggingface.co/x-square-robot
+
+---
+
+## Citation
+
+If you use this work, please cite:
+
+```bibtex
+@article{zhai2025igniting,
+ title = {Igniting VLMs Toward the Embodied Space},
+ author = {Zhai, Andy and Liu, Brae and Fang, Bruno and Cai, Chalse and Ma, Ellie and Yin, Ethan and Wang, Hao and Zhou, Hugo and Wang, James and Shi, Lights and Liang, Lucy and Wang, Make and Wang, Qian and Gan, Roy and Yu, Ryan and Li, Shalfun and Liu, Starrick and Chen, Sylas and Chen, Vincent and Xu, Zach},
+ journal = {arXiv preprint arXiv:2509.11766},
+ year = {2025}
+}
+```
+
+---
+
+## License
+
+This model follows the **Apache 2.0 License**, consistent with the original [WallX repository](https://github.com/X-Square-Robot/wall-x).
diff --git a/lerobot/docs/source/porting_datasets_v3.mdx b/lerobot/docs/source/porting_datasets_v3.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..ff5088e2d702e2b2f6de69b0fb0e98ae4dff524d
--- /dev/null
+++ b/lerobot/docs/source/porting_datasets_v3.mdx
@@ -0,0 +1,321 @@
+# Porting Large Datasets to LeRobot Dataset v3.0
+
+This tutorial explains how to port large-scale robotic datasets to the LeRobot Dataset v3.0 format. We'll use the **DROID 1.0.1** dataset as our primary example, which demonstrates handling multi-terabyte datasets with thousands of shards across SLURM clusters.
+
+## File Organization: v2.1 vs v3.0
+
+Dataset v3.0 fundamentally changes how data is organized and stored:
+
+**v2.1 Structure (Episode-based)**:
+
+```
+dataset/
+βββ data/chunk-000/episode_000000.parquet
+βββ data/chunk-000/episode_000001.parquet
+βββ videos/chunk-000/camera/episode_000000.mp4
+βββ meta/episodes.jsonl
+```
+
+**v3.0 Structure (File-based)**:
+
+```
+dataset/
+βββ data/chunk-000/file-000.parquet # Multiple episodes per file
+βββ videos/camera/chunk-000/file-000.mp4 # Consolidated video chunks
+βββ meta/episodes/chunk-000/file-000.parquet # Structured metadata
+```
+
+This transition from individual episode files to file-based chunks dramatically improves performance and reduces storage overhead.
+
+## What's New in Dataset v3.0
+
+Dataset v3.0 introduces significant improvements for handling large datasets:
+
+### ποΈ **Enhanced File Organization**
+
+- **File-based structure**: Episodes are now grouped into chunked files rather than individual episode files
+- **Configurable file sizes**: for data and video files
+- **Improved storage efficiency**: Better compression and reduced overhead
+
+### π **Modern Metadata Management**
+
+- **Parquet-based metadata**: Replaced JSON Lines with efficient parquet format
+- **Structured episode access**: Direct pandas DataFrame access via `dataset.meta.episodes`
+- **Per-episode statistics**: Enhanced statistics tracking at episode level
+
+### π **Performance Enhancements**
+
+- **Memory-mapped access**: Improved RAM usage through PyArrow memory mapping
+- **Faster loading**: Significantly reduced dataset initialization time
+- **Better scalability**: Designed for datasets with millions of episodes
+
+## Prerequisites
+
+Before porting large datasets, ensure you have:
+
+- **LeRobot installed** with v3.0 support. Follow our [Installation Guide](./installation).
+- **Sufficient storage**: Raw datasets can be very large (e.g., DROID requires 2TB)
+- **Cluster access** (recommended for large datasets): SLURM or similar job scheduler
+- **Dataset-specific dependencies**: For DROID, you'll need TensorFlow Dataset utilities
+
+## Understanding the DROID Dataset
+
+[DROID 1.0.1](https://droid-dataset.github.io/droid/the-droid-dataset) is an excellent example of a large-scale robotic dataset:
+
+- **Size**: 1.7TB (RLDS format), 8.7TB (raw data)
+- **Structure**: 2048 pre-defined TensorFlow dataset shards
+- **Content**: 76,000+ robot manipulation trajectories from Franka Emika Panda robots
+- **Scope**: Real-world manipulation tasks across multiple environments and objects
+- **Format**: Originally in TensorFlow Records/RLDS format, requiring conversion to LeRobot format
+- **Hosting**: Google Cloud Storage with public access via `gsutil`
+
+The dataset contains diverse manipulation demonstrations with:
+
+- Multiple camera views (wrist camera, exterior cameras)
+- Natural language task descriptions
+- Robot proprioceptive state and actions
+- Success/failure annotations
+
+### DROID Features Schema
+
+```python
+DROID_FEATURES = {
+ # Episode markers
+ "is_first": {"dtype": "bool", "shape": (1,)},
+ "is_last": {"dtype": "bool", "shape": (1,)},
+ "is_terminal": {"dtype": "bool", "shape": (1,)},
+
+ # Language instructions
+ "language_instruction": {"dtype": "string", "shape": (1,)},
+ "language_instruction_2": {"dtype": "string", "shape": (1,)},
+ "language_instruction_3": {"dtype": "string", "shape": (1,)},
+
+ # Robot state
+ "observation.state.gripper_position": {"dtype": "float32", "shape": (1,)},
+ "observation.state.cartesian_position": {"dtype": "float32", "shape": (6,)},
+ "observation.state.joint_position": {"dtype": "float32", "shape": (7,)},
+
+ # Camera observations
+ "observation.images.wrist_left": {"dtype": "image"},
+ "observation.images.exterior_1_left": {"dtype": "image"},
+ "observation.images.exterior_2_left": {"dtype": "image"},
+
+ # Actions
+ "action.gripper_position": {"dtype": "float32", "shape": (1,)},
+ "action.cartesian_position": {"dtype": "float32", "shape": (6,)},
+ "action.joint_position": {"dtype": "float32", "shape": (7,)},
+
+ # Standard LeRobot format
+ "observation.state": {"dtype": "float32", "shape": (8,)}, # joints + gripper
+ "action": {"dtype": "float32", "shape": (8,)}, # joints + gripper
+}
+```
+
+## Approach 1: Single Computer Porting
+
+### Step 1: Install Dependencies
+
+For DROID specifically:
+
+```bash
+pip install tensorflow
+pip install tensorflow_datasets
+```
+
+For other datasets, install the appropriate readers for your source format.
+
+### Step 2: Download Raw Data
+
+Download DROID from Google Cloud Storage using `gsutil`:
+
+```bash
+# Install Google Cloud SDK if not already installed
+# https://cloud.google.com/sdk/docs/install
+
+# Download the full RLDS dataset (1.7TB)
+gsutil -m cp -r gs://gresearch/robotics/droid/1.0.1 /your/data/
+
+# Or download just the 100-episode sample (2GB) for testing
+gsutil -m cp -r gs://gresearch/robotics/droid_100 /your/data/
+```
+
+> [!WARNING]
+> Large datasets require substantial time and storage:
+>
+> - **Full DROID (1.7TB)**: Several days to download depending on bandwidth
+> - **Processing time**: 7+ days for local porting of full dataset
+> - **Upload time**: 3+ days to push to Hugging Face Hub
+> - **Local storage**: ~400GB for processed LeRobot format
+
+### Step 3: Port the Dataset
+
+```bash
+python examples/port_datasets/port_droid.py \
+ --raw-dir /your/data/droid/1.0.1 \
+ --repo-id your_id/droid_1.0.1 \
+ --push-to-hub
+```
+
+### Development and Testing
+
+For development, you can port a single shard:
+
+```bash
+python examples/port_datasets/port_droid.py \
+ --raw-dir /your/data/droid/1.0.1 \
+ --repo-id your_id/droid_1.0.1_test \
+ --num-shards 2048 \
+ --shard-index 0
+```
+
+This approach works for smaller datasets or testing, but large datasets require cluster computing.
+
+## Approach 2: SLURM Cluster Porting (Recommended)
+
+For large datasets like DROID, parallel processing across multiple nodes dramatically reduces processing time.
+
+### Step 1: Install Cluster Dependencies
+
+```bash
+pip install datatrove # Hugging Face's distributed processing library
+```
+
+### Step 2: Configure Your SLURM Environment
+
+Find your partition information:
+
+```bash
+sinfo --format="%R" # List available partitions
+sinfo -N -p your_partition -h -o "%N cpus=%c mem=%m" # Check resources
+```
+
+Choose a **CPU partition** - no GPU needed for dataset porting.
+
+### Step 3: Launch Parallel Porting Jobs
+
+```bash
+python examples/port_datasets/slurm_port_shards.py \
+ --raw-dir /your/data/droid/1.0.1 \
+ --repo-id your_id/droid_1.0.1 \
+ --logs-dir /your/logs \
+ --job-name port_droid \
+ --partition your_partition \
+ --workers 2048 \
+ --cpus-per-task 8 \
+ --mem-per-cpu 1950M
+```
+
+#### Parameter Guidelines
+
+- **`--workers`**: Number of parallel jobs (max 2048 for DROID's shard count)
+- **`--cpus-per-task`**: 8 CPUs recommended for frame encoding parallelization
+- **`--mem-per-cpu`**: ~16GB total RAM (8Γ1950M) for loading raw frames
+
+> [!TIP]
+> Start with fewer workers (e.g., 100) to test your cluster configuration before launching thousands of jobs.
+
+### Step 4: Monitor Progress
+
+Check running jobs:
+
+```bash
+squeue -u $USER
+```
+
+Monitor overall progress:
+
+```bash
+jobs_status /your/logs
+```
+
+Inspect individual job logs:
+
+```bash
+less /your/logs/port_droid/slurm_jobs/JOB_ID_WORKER_ID.out
+```
+
+Debug failed jobs:
+
+```bash
+failed_logs /your/logs/port_droid
+```
+
+### Step 5: Aggregate Shards
+
+Once all porting jobs complete:
+
+```bash
+python examples/port_datasets/slurm_aggregate_shards.py \
+ --repo-id your_id/droid_1.0.1 \
+ --logs-dir /your/logs \
+ --job-name aggr_droid \
+ --partition your_partition \
+ --workers 2048 \
+ --cpus-per-task 8 \
+ --mem-per-cpu 1950M
+```
+
+### Step 6: Upload to Hub
+
+```bash
+python examples/port_datasets/slurm_upload.py \
+ --repo-id your_id/droid_1.0.1 \
+ --logs-dir /your/logs \
+ --job-name upload_droid \
+ --partition your_partition \
+ --workers 50 \
+ --cpus-per-task 4 \
+ --mem-per-cpu 1950M
+```
+
+> [!NOTE]
+> Upload uses fewer workers (50) since it's network-bound rather than compute-bound.
+
+## Dataset v3.0 File Structure
+
+Your completed dataset will have this modern structure:
+
+```
+dataset/
+βββ meta/
+β βββ episodes/
+β β βββ chunk-000/
+β β βββ file-000.parquet # Episode metadata
+β βββ tasks.parquet # Task definitions
+β βββ stats.json # Aggregated statistics
+β βββ info.json # Dataset information
+βββ data/
+β βββ chunk-000/
+β βββ file-000.parquet # Consolidated episode data
+βββ videos/
+ βββ camera_key/
+ βββ chunk-000/
+ βββ file-000.mp4 # Consolidated video files
+```
+
+This replaces the old episode-per-file structure with efficient, optimally-sized chunks.
+
+## Migrating from Dataset v2.1
+
+If you have existing datasets in v2.1 format, use the migration tool:
+
+```bash
+python src/lerobot/datasets/v30/convert_dataset_v21_to_v30.py \
+ --repo-id your_id/existing_dataset
+```
+
+This automatically:
+
+- Converts file structure to v3.0 format
+- Migrates metadata from JSON Lines to parquet
+- Aggregates statistics and creates per-episode stats
+- Updates version information
+
+## Performance Benefits
+
+Dataset v3.0 provides significant improvements for large datasets:
+
+- **Faster loading**: 3-5x reduction in initialization time
+- **Memory efficiency**: Better RAM usage through memory mapping
+- **Scalable processing**: Handles millions of episodes efficiently
+- **Storage optimization**: Reduced file count and improved compression
diff --git a/lerobot/docs/source/processors_robots_teleop.mdx b/lerobot/docs/source/processors_robots_teleop.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..a033d03484890d02cecccc25b79d5653e125fea2
--- /dev/null
+++ b/lerobot/docs/source/processors_robots_teleop.mdx
@@ -0,0 +1,151 @@
+# Processors for Robots and Teleoperators
+
+This guide shows how to build and modify processing pipelines that connect teleoperators (e.g., phone) to robots and datasets. Pipelines standardize conversions between different action/observation spaces so you can swap teleops and robots without rewriting glue code.
+
+We use the Phone to SOβ100 follower examples for concreteness, but the same patterns apply to other robots.
+
+**What you'll learn**
+
+- Absolute vs. relative EE control: What each means, tradeβoffs, and how to choose for your task.
+- Three-pipeline pattern: How to map teleop actions β dataset actions β robot commands, and robot observations β dataset observations.
+- Adapters (`to_transition` / `to_output`): How these convert raw dicts to `EnvTransition` and back to reduce boilerplate.
+- Dataset feature contracts: How steps declare features via `transform_features(...)`, and how to aggregate/merge them for recording.
+- Choosing a representation: When to store joints, absolute EE poses, or relative EE deltasβand how that affects training.
+- Pipeline customization guidance: How to swap robots/URDFs safely and tune bounds, step sizes, and options like IK initialization.
+
+### Absolute vs relative EE control
+
+The examples in this guide use absolute end effector (EE) poses because they are easy to reason about. In practice, relative EE deltas or joint position are often preferred as learning features.
+
+With processors, you choose the learning features you want to use for your policy. This could be joints positions/velocities, absolute EE, or relative EE positions. You can also choose to store other features, such as joint torques, motor currents, etc.
+
+## Three pipelines
+
+We often compose three pipelines. Depending on your setup, some can be empty if action and observation spaces already match.
+Each of these pipelines handle different conversions between different action and observation spaces. Below is a quick explanation of each pipeline.
+
+1. Pipeline 1: Teleop action space β dataset action space (phone pose β EE targets)
+2. Pipeline 2: Dataset action space β robot command space (EE targets β joints)
+3. Pipeline 3: Robot observation space β dataset observation space (joints β EE pose)
+
+Below is an example of the three pipelines that we use in the phone to SO-100 follower examples:
+
+```python
+phone_to_robot_ee_pose_processor = RobotProcessorPipeline[RobotAction, RobotAction]( # teleop -> dataset action
+ steps=[
+ MapPhoneActionToRobotAction(platform=teleop_config.phone_os),
+ EEReferenceAndDelta(
+ kinematics=kinematics_solver, end_effector_step_sizes={"x": 0.5, "y": 0.5, "z": 0.5}, motor_names=list(robot.bus.motors.keys()),
+ ),
+ EEBoundsAndSafety(
+ end_effector_bounds={"min": [-1.0, -1.0, -1.0], "max": [1.0, 1.0, 1.0]}, max_ee_step_m=0.20,
+ ),
+ GripperVelocityToJoint(),
+ ],
+ to_transition=robot_action_to_transition,
+ to_output=transition_to_robot_action,
+)
+
+robot_ee_to_joints_processor = RobotProcessorPipeline[RobotAction, RobotAction]( # dataset action -> robot
+ steps=[
+ InverseKinematicsEEToJoints(
+ kinematics=kinematics_solver, motor_names=list(robot.bus.motors.keys()), initial_guess_current_joints=True,
+ ),
+ ],
+ to_transition=robot_action_to_transition,
+ to_output=transition_to_robot_action,
+)
+
+robot_joints_to_ee_pose = RobotProcessorPipeline[RobotObservation, RobotObservation]( # robot obs -> dataset obs
+ steps=[
+ ForwardKinematicsJointsToEE(kinematics=kinematics_solver, motor_names=list(robot.bus.motors.keys()))
+ ],
+ to_transition=observation_to_transition,
+ to_output=transition_to_observation,
+)
+```
+
+## Why to_transition / to_output
+
+To convert from robot/teleoperator to pipeline and back, we use the `to_transition` and `to_output` pipeline adapters.
+They standardize conversions to reduce boilerplate code, and form the bridge between the robot and teleoperators raw dictionaries and the pipelineβs `EnvTransition` format.
+In the phone to SO-100 follower examples we use the following adapters:
+
+- `robot_action_to_transition`: transforms the teleop action dict to a pipeline transition.
+- `transition_to_robot_action`: transforms the pipeline transition to a robot action dict.
+- `observation_to_transition`: transforms the robot observation dict to a pipeline transition.
+- `transition_to_observation`: transforms the pipeline transition to a observation dict.
+
+Checkout [src/lerobot/processor/converters.py](https://github.com/huggingface/lerobot/blob/main/src/lerobot/processor/converters.py) for more details.
+
+## Dataset feature contracts
+
+Dataset features are determined by the keys saved in the dataset. Each step can declare what features it modifies in a contract called `transform_features(...)`. Once you build a processor, the processor can then aggregate all of these features with `aggregate_pipeline_dataset_features()` and merge multiple feature dicts with `combine_feature_dicts(...)`.
+
+Below is and example of how we declare features with the `transform_features` method in the phone to SO-100 follower examples:
+
+```python
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ # We only use the ee pose in the dataset, so we don't need the joint positions
+ for n in self.motor_names:
+ features[PipelineFeatureType.ACTION].pop(f"{n}.pos", None)
+ # We specify the dataset features of this step that we want to be stored in the dataset
+ for k in ["x", "y", "z", "wx", "wy", "wz", "gripper_pos"]:
+ features[PipelineFeatureType.ACTION][f"ee.{k}"] = PolicyFeature(
+ type=FeatureType.STATE, shape=(1,)
+ )
+ return features
+```
+
+Here we declare what PolicyFeatures we modify in this step, so we know what features we can expect when we run the processor. These features can then be aggregated and used to create the dataset features.
+
+Below is an example of how we aggregate and merge features in the phone to SO-100 record example:
+
+```python
+features=combine_feature_dicts(
+ # Run the feature contract of the pipelines
+ # This tells you how the features would look like after the pipeline steps
+ aggregate_pipeline_dataset_features(
+ pipeline=phone_to_robot_ee_pose_processor,
+ initial_features=create_initial_features(action=phone.action_features), # <- Action features we can expect, these come from our teleop device (phone) and action processor
+ use_videos=True,
+ ),
+ aggregate_pipeline_dataset_features(
+ pipeline=robot_joints_to_ee_pose,
+ initial_features=create_initial_features(observation=robot.observation_features), # <- Observation features we can expect, these come from our robot and observation processor
+ use_videos=True,
+ patterns=["observation.state.ee"], # <- Here you could optionally filter the features we want to store in the dataset, with a specific pattern
+
+ ),
+ ),
+```
+
+How it works:
+
+- `aggregate_pipeline_dataset_features(...)`: applies `transform_features` across the pipeline and filters by patterns (images included when `use_videos=True`, and state features included when `patterns` is specified).
+- `combine_feature_dicts(...)`: combine multiple feature dicts.
+- Recording with `record_loop(...)` uses `build_dataset_frame(...)` to build frames consistent with `dataset.features` before we call `add_frame(...)` to add the frame to the dataset.
+
+## Guidance when customizing robot pipelines
+
+You can store any of the following features as your action/observation space:
+
+- Joint positions
+- Absolute EE poses
+- Relative EE deltas
+- Other features: joint velocity, torques, etc.
+
+Pick what you want to use for your policy action and observation space and configure/modify the pipelines and steps accordingly.
+
+### Different robots
+
+- You can easily reuse pipelines, for example to use another robot with phone teleop, modify the examples and swap the robot `RobotKinematics` (URDF) and `motor_names` to use your own robot with Phone teleop. Additionally you should ensure `target_frame_name` points to your gripper/wrist.
+
+### Safety first
+
+- When changing pipelines, start with tight bounds, implement safety steps when working with real robots.
+- Its advised to start with simulation first and then move to real robots.
+
+Thats it! We hope this guide helps you get started with customizing your robot pipelines, If you run into any issues at any point, jump into our [Discord community](https://discord.com/invite/s3KuuzsPFb) for support.
diff --git a/lerobot/docs/source/reachy2.mdx b/lerobot/docs/source/reachy2.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..031934e6f7e3b430fe6ab531b46a97a71f3aa155
--- /dev/null
+++ b/lerobot/docs/source/reachy2.mdx
@@ -0,0 +1,303 @@
+# Reachy 2
+
+Reachy 2 is an open-source humanoid robot made by Pollen Robotics, specifically designed for the development of embodied AI and real-world applications.
+Check out [Pollen Robotics website](https://www.pollen-robotics.com/reachy/), or access [Reachy 2 documentation](https://docs.pollen-robotics.com/) for more information on the platform!
+
+## Teleoperate Reachy 2
+
+Currently, there are two ways to teleoperate Reachy 2:
+
+- Pollen Roboticsβ VR teleoperation (not included in LeRobot).
+- Robot-to-robot teleoperation (use one Reachy 2 to control another).
+
+## Reachy 2 Simulation
+
+**(Linux only)** You can run Reachy 2 in simulation (Gazebo or MuJoCo) using the provided [Docker image](https://hub.docker.com/r/pollenrobotics/reachy2_core).
+
+1. Install [Docker Engine](https://docs.docker.com/engine/).
+2. Run (for MuJoCo):
+
+```
+docker run --rm -it \
+ --name reachy \
+ --privileged \
+ --network host \
+ --ipc host \
+ --device-cgroup-rule='c 189:* rwm' \
+ --group-add audio \
+ -e ROS_DOMAIN_ID="$ROS_DOMAIN_ID" \
+ -e DISPLAY="$DISPLAY" \
+ -e RCUTILS_CONSOLE_OUTPUT_FORMAT="[{severity}]: {message}" \
+ -e REACHY2_CORE_SERVICE_FAKE="${REACHY2_CORE_SERVICE_FAKE:-true}" \
+ -v /dev:/dev \
+ -v "$HOME/.reachy_config":/home/reachy/.reachy_config_override \
+ -v "$HOME/.reachy.log":/home/reachy/.ros/log \
+ -v /usr/lib/x86_64-linux-gnu:/opt/host-libs \
+ --entrypoint /package/launch.sh \
+ pollenrobotics/reachy2_core:1.7.5.9_deploy \
+ start_rviz:=true start_sdk_server:=true mujoco:=true
+```
+
+> [!NOTE]
+> If MuJoCo runs slowly (low simulation frequency), append `-e LD_LIBRARY_PATH="/opt/host-libs:$LD_LIBRARY_PATH" \` to the previous command to improve performance:
+>
+> ```
+> docker run --rm -it \
+> --name reachy \
+> --privileged \
+> --network host \
+> --ipc host \
+> --device-cgroup-rule='c 189:* rwm' \
+> --group-add audio \
+> -e ROS_DOMAIN_ID="$ROS_DOMAIN_ID" \
+> -e DISPLAY="$DISPLAY" \
+> -e RCUTILS_CONSOLE_OUTPUT_FORMAT="[{severity}]: {message}" \
+> -e REACHY2_CORE_SERVICE_FAKE="${REACHY2_CORE_SERVICE_FAKE:-true}" \
+> -e LD_LIBRARY_PATH="/opt/host-libs:$LD_LIBRARY_PATH" \
+> -v /dev:/dev \
+> -v "$HOME/.reachy_config":/home/reachy/.reachy_config_override \
+> -v "$HOME/.reachy.log":/home/reachy/.ros/log \
+> -v /usr/lib/x86_64-linux-gnu:/opt/host-libs \
+> --entrypoint /package/launch.sh \
+> pollenrobotics/reachy2_core:1.7.5.9_deploy \
+> start_rviz:=true start_sdk_server:=true mujoco:=true
+> ```
+
+## Setup
+
+### Prerequisites
+
+- On your robot, check the **service images** meet the minimum versions:
+ - **reachy2-core >= 1.7.5.2**
+ - **webrtc >= 2.0.1.1**
+
+Then, if you want to use VR teleoperation:
+
+- Install the [Reachy 2 teleoperation application](https://docs.pollen-robotics.com/teleoperation/teleoperation-introduction/discover-teleoperation/).
+ Use version **>=v1.2.0**
+
+We recommend using two computers: one for teleoperation (Windows required) and another for recording with LeRobot.
+
+### Install LeRobot
+
+Follow the [installation instructions](https://github.com/huggingface/lerobot#installation) to install LeRobot.
+
+Install LeRobot with Reachy 2 dependencies:
+
+```bash
+pip install -e ".[reachy2]"
+```
+
+### (Optional but recommended) Install pollen_data_acquisition_server
+
+How you manage Reachy 2 recording sessions is up to you, but the **easiest** way is to use this server so you can control sessions directly from the VR teleoperation app.
+
+> **Note:** Currently, only the VR teleoperation application works as a client for this server, so this step primarily targets teleoperation. Youβre free to develop custom clients to manage sessions to your needs.
+
+In your LeRobot environment, install the server from source:
+
+```bash
+git clone https://github.com/pollen-robotics/pollen_data_acquisition_server.git
+cd pollen_data_acquisition_server
+pip install -e .
+```
+
+Find the [pollen_data_acquisition_server documentation here](https://github.com/pollen-robotics/pollen_data_acquisition_server).
+
+## Step 1: Recording
+
+### Get Reachy 2 IP address
+
+Before starting teleoperation and data recording, find the [robot's IP address](https://docs.pollen-robotics.com/getting-started/setup-reachy2/connect-reachy2/).
+We strongly recommend connecting all devices (PC and robot) via **Ethernet**.
+
+### Launch recording
+
+There are two ways to manage recording sessions when using the Reachy 2 VR teleoperation application:
+
+- **Using the data acquisition server (recommended for VR teleop)**: The VR app orchestrates sessions (via the server it tells LeRobot when to create datasets, start/stop episodes) while also controlling the robotβs motions.
+- **Using LeRobotβs record script**: LeRobot owns session control and decides when to start/stop episodes. If you also use the VR teleop app, itβs only for motion control.
+
+### Option 1: Using Pollen data acquisition server (recommended for VR teleop)
+
+Make sure you have installed pollen_data_acquisition_server, as explained in the Setup section.
+
+Launch the data acquisition server to be able to manage your session directly from the teleoperation application:
+
+```bash
+python -m pollen_data_acquisition_server.server
+```
+
+Then get into the teleoperation application and choose "Data acquisition session".
+You can finally setup your session by following the screens displayed.
+
+> Even without the VR app, you can use the `pollen_data_acquisition_server` with your own client implementation.
+
+### Option 2: Using lerobot.record
+
+Reachy 2 is fully supported by LeRobotβs recording features.
+If you choose this option but still want to use the VR teleoperation application, select "Standard session" in the app.
+
+**Example: start a recording without the mobile base:**
+First add reachy2 and reachy2_teleoperator to the imports of the record script. Then you can use the following command:
+
+```bash
+lerobot-record \
+ --robot.type=reachy2 \
+ --robot.ip_address=192.168.0.200 \
+ --robot.id=r2-0000 \
+ --robot.use_external_commands=true \
+ --robot.with_mobile_base=false \
+ --teleop.type=reachy2_teleoperator \
+ --teleop.ip_address=192.168.0.200 \
+ --teleop.with_mobile_base=false \
+ --robot.with_torso_camera=true \
+ --dataset.repo_id=pollen_robotics/record_test \
+ --dataset.single_task="Reachy 2 recording test" \
+ --dataset.num_episodes=1 \
+ --dataset.episode_time_s=5 \
+ --dataset.fps=15 \
+ --dataset.push_to_hub=true \
+ --dataset.private=true \
+ --display_data=true
+```
+
+#### Specific Options
+
+**Extended setup overview (all options included):**
+
+```bash
+lerobot-record \
+ --robot.type=reachy2 \
+ --robot.ip_address=192.168.0.200 \
+ --robot.use_external_commands=true \
+ --robot.with_mobile_base=true \
+ --robot.with_l_arm=true \
+ --robot.with_r_arm=true \
+ --robot.with_neck=true \
+ --robot.with_antennas=true \
+ --robot.with_left_teleop_camera=true \
+ --robot.with_right_teleop_camera=true \
+ --robot.with_torso_camera=false \
+ --robot.camera_width=640 \
+ --robot.camera_height=480 \
+ --robot.disable_torque_on_disconnect=false \
+ --robot.max_relative_target=5.0 \
+ --teleop.type=reachy2_teleoperator \
+ --teleop.ip_address=192.168.0.200 \
+ --teleop.use_present_position=false \
+ --teleop.with_mobile_base=false \
+ --teleop.with_l_arm=true \
+ --teleop.with_r_arm=true \
+ --teleop.with_neck=true \
+ --teleop.with_antennas=true \
+ --dataset.repo_id=pollen_robotics/record_test \
+ --dataset.single_task="Reachy 2 recording test" \
+ --dataset.num_episodes=1 \
+ --dataset.episode_time_s=5 \
+ --dataset.fps=15 \
+ --dataset.push_to_hub=true \
+ --dataset.private=true \
+ --display_data=true
+```
+
+##### `--robot.use_external_commands`
+
+Determine whether LeRobot robot.send_action() sends commands to the robot.
+**Must** be set to false while using the VR teleoperation application, as the app already sends commands.
+
+##### `--teleop.use_present_position`
+
+Determine whether the teleoperator reads the goal or present position of the robot.
+Must be set to true if a compliant Reachy 2 is used to control another one.
+
+##### Use the relevant parts
+
+From our initial tests, recording **all** joints when only some are moving can reduce model quality with certain policies.
+To avoid this, you can exclude specific parts from recording and replay using:
+
+```bash
+--robot.with_=false
+```
+
+with `` being one of : `mobile_base`, `l_arm`, `r_arm", `neck`, `antennas`.
+It determine whether the corresponding part is recorded in the observations. True if not set.
+
+By default, **all parts are recorded**.
+
+The same per-part mechanism is available in `reachy2_teleoperator` as well.
+
+```bash
+--teleop.with\_
+```
+
+with `` being one of : `mobile_base`, `l_arm`, `r_arm", `neck`, `antennas`.
+Determine whether the corresponding part is recorded in the actions. True if not set.
+
+> **Important:** In a given session, the **enabled parts must match** on both the robot and the teleoperator.
+> For example, if the robot runs with `--robot.with_mobile_base=false`, the teleoperator must disable the same part `--teleoperator.with_mobile_base=false`.
+
+##### Use the relevant cameras
+
+You can do the same for **cameras**. Enable or disable each camera with default parameters using:
+
+```bash
+--robot.with_left_teleop_camera= \
+--robot.with_right_teleop_camera= \
+--robot.with_torso_camera=
+```
+
+By default, no camera is recorded, all camera arguments are set to `false`.
+If you want to, you can use custom `width` and `height` parameters for Reachy 2's cameras using the `--robot.camera_width` & `--robot.camera_height` argument:
+
+```bash
+--robot.camera_width=1920 \
+--robot.camera_height=1080
+```
+
+This will change the resolution of all 3 default robot cameras (enabled by the above bool arguments).
+
+If you want, you can add additional cameras other than the ones in the robot as usual with:
+
+```bash
+--robot.cameras="{ extra: {type: opencv, index_or_path: 42, width: 640, height: 480, fps: 30}}" \
+```
+
+## Step 2: Replay
+
+Make sure the robot is configured with the same parts as the dataset:
+
+```bash
+lerobot-replay \
+ --robot.type=reachy2 \
+ --robot.ip_address=192.168.0.200 \
+ --robot.use_external_commands=false \
+ --robot.with_mobile_base=false \
+ --dataset.repo_id=pollen_robotics/record_test \
+ --dataset.episode=0
+```
+
+## Step 3: Train
+
+```bash
+lerobot-train \
+ --dataset.repo_id=pollen_robotics/record_test \
+ --policy.type=act \
+ --output_dir=outputs/train/reachy2_test \
+ --job_name=reachy2 \
+ --policy.device=mps \
+ --wandb.enable=true \
+ --policy.repo_id=pollen_robotics/record_test_policy
+```
+
+## Step 4: Evaluate
+
+```bash
+lerobot-eval \
+ --robot.type=reachy2 \
+ --robot.ip_address=192.168.0.200 \
+ --dataset.repo_id=pollen_robotics/eval_record_test \
+ --dataset.single_task="Evaluate reachy2 policy" \
+ --dataset.num_episodes=10 \
+ --policy.path=outputs/train/reachy2_test/checkpoints/last/pretrained_model
+```
diff --git a/lerobot/docs/source/rtc.mdx b/lerobot/docs/source/rtc.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..729519768032534d3599719a7191709bf63cb08e
--- /dev/null
+++ b/lerobot/docs/source/rtc.mdx
@@ -0,0 +1,188 @@
+# Real-Time Chunking (RTC)
+
+Real-Time Chunking (RTC) is an inference-time method that allows large, flow-matching based robotic policies, such as [Pi0](./pi0), [Pi0.5](./pi05), and [SmolVLA](./smolvla), to produce smooth, continuous, and reactive motion despite having high inference latency.
+
+These policies generate chunks of future actions (e.g., 50 steps at a time) instead of single actions.
+Because the models are large, producing each chunk takes longer than the time it takes the robot to execute it.
+Naively executing chunks leads to problems such as pauses, jerky transitions, or sudden changes in strategy whenever the next chunk arrives late or disagrees with the previously executed actions.
+
+RTC solves this by asynchronously generating the next chunk while the robot continues executing the current one, and by guiding the new chunk so it aligns smoothly with the portion of the previous chunk that has already been executed.
+
+## How RTC Works (simplified)
+
+RTC lets the robot think ahead while itβs still moving. When the robot is carrying out one chunk of actions, RTC starts creating the next chunk early.
+But since the robot has already moved a bit by the time the new chunk is ready, RTC has to make sure the new chunk still lines up smoothly with what the robot is currently doing.
+
+To do this, RTC treats the beginning of the new chunk like an inpainting or βfill-in-the-gapsβ problem:
+it gently adjusts the first part of the new chunk so it blends naturally with the robotβs ongoing motion. The result is no pauses, no sudden jumps.
+
+In technical terms, RTC adds a guidance term to the flow-matching denoising process that forces the overlapping timesteps of the new chunk to stay close to the executed portion of the previous chunk, typically using a soft transition mask.
+
+## Quick Start
+
+### Installation
+
+RTC is built into LeRobot. Just install the policy dependencies you need:
+
+```bash
+# For Pi0 or Pi0.5
+pip install -e ".[pi]"
+
+# For SmolVLA
+pip install -e ".[smolvla]"
+```
+
+### Using RTC with Pi0
+
+You can find a complete reference implementation in [eval_with_real_robot.py](examples/rtc/eval_with_real_robot.py).
+The snippet below provides a simplified pseudo-example of how RTC operates with Pi0 in your pipeline:
+
+```python
+from lerobot.policies.pi0 import PI0Policy, PI0Config
+from lerobot.configs.types import RTCAttentionSchedule
+from lerobot.policies.rtc.configuration_rtc import RTCConfig
+from lerobot.policies.rtc.action_queue import ActionQueue
+
+# Load Pi0 with RTC enabled
+policy_cfg = PI0Config()
+
+# Enable RTC
+policy_cfg.rtc_config = RTCConfig(
+ enabled=True,
+ execution_horizon=10, # How many steps to blend with previous chunk
+ max_guidance_weight=10.0, # How strongly to enforce consistency
+ prefix_attention_schedule=RTCAttentionSchedule.EXP, # Exponential blend
+)
+
+# Load the policy
+policy = PI0Policy.from_pretrained("lerobot/pi0_base", policy_cfg=policy_cfg, device="cuda")
+
+# Now use predict_action_chunk with RTC parameters
+inference_delay = 4 # How many steps of inference latency, this values should be calculated based on the inference latency of the policy
+
+# Initialize the action queue
+action_queue = ActionQueue(policy_cfg.rtc_config)
+
+# Start in a separate thread with the following function
+def get_actions():
+ while True:
+ if should_get_actions:
+
+ prev_actions = action_queue.get_left_over()
+ obs = get_robot_observations(robot)
+
+ # Generate actions WITH RTC
+ actions = policy.predict_action_chunk(
+ obs,
+ inference_delay=inference_delay,
+ prev_chunk_left_over=prev_actions,
+ )
+
+ action_queue.merge(
+ actions, actions, inference_delay
+ )
+
+for step in range(num_steps):
+ action = action_queue.get()
+
+ # Execute the first N actions
+ execute_actions(action)
+```
+
+## Key Parameters
+
+`RTCConfig` has the following parameters to tune:
+
+**`execution_horizon`**: How many timesteps from the previous chunk to maintain consistency with. Higher values mean smoother transitions but potentially less reactivity.
+
+Typical values: 8-12 steps
+
+```python
+RTCConfig(execution_horizon=10)
+```
+
+**`max_guidance_weight`**: How strongly to enforce consistency with the previous chunk. This is a hyperparameter that can be tuned to balance the smoothness of the transitions and the reactivity of the policy. For 10 steps flow matching (SmolVLA, Pi0, Pi0.5), a value of 10.0 is a optimal value.
+
+**`prefix_attention_schedule`**: How to weight consistency across the overlap region.
+
+- `LINEAR`: Linear decay from inference_delay to execution_horizon
+- `EXP`: Exponential decay (recommended for getting started)
+- `ONES`: Full weight across entire execution_horizon
+- `ZEROS`: Binary (full weight up to inference_delay, then zero)
+
+**`inference_delay`**: How many timesteps of inference latency your system has. This is passed to `predict_action_chunk()` rather than the config, since it may vary at runtime.
+
+## Testing RTC Offline
+
+Before running on a real robot, test RTC with dataset samples to visualize how it works:
+
+```bash
+python examples/rtc/eval_dataset.py \
+ --policy.path=lerobot/pi0_libero_finetuned \
+ --dataset.repo_id=HuggingFaceVLA/libero \
+ --rtc.execution_horizon=10 \
+ --rtc.max_guidance_weight=10.0 \
+ --device=cuda
+```
+
+The script generates a visualization of the denoising process, comparing standard generation (left) with RTC (right). In the RTC plots, you can see how the first few steps (blue/purple lines) are guided to match the red ground truth trajectory (previous chunk's tail), ensuring a smooth transition between chunks.
+
+
+
+
+
+## Testing RTC with a Real Robot
+
+```bash
+python examples/rtc/eval_with_real_robot.py \
+ --policy.path=${HF_USERNAME}/policy_repo_id \
+ --robot.type=so100_follower \
+ --robot.port=/dev/tty.usbmodem58FA0834591 \
+ --robot.cameras="{ gripper: {type: opencv, index_or_path: 1, width: 640, height: 480, fps: 30}, front: {type: opencv, index_or_path: 0, width: 640, height: 480, fps: 30}}" \
+ --task="Move green small object into the purple platform" \
+ --duration=120 \
+ --device=cuda
+```
+
+## How It Differs from the Async Inference in LeRobot
+
+Both RTC and [async inference](./async) improve real-time robot control, but they solve different problems.
+
+| Aspect | Async Inference | RTC |
+| ------------- | -------------------------------------------------------------------------- | --------------------------------------------------- |
+| **Problem** | Idle frames while waiting for inference | Discontinuities between action chunks |
+| **Solution** | Decouple prediction from execution | Guide new chunks to continue smoothly from previous |
+| **Benefit** | No waiting, continuous action | Smooth transitions, natural motion |
+| **Best Used** | Async inference is best used with large models with high inference latency | Flow-matching based policies |
+
+**Use both together** for maximum smoothness and reactivity!
+
+## Advanced: Debug Tracking
+
+RTC includes built-in debug tracking to help you understand what's happening during inference:
+
+```python
+# Enable debug tracking
+policy_cfg.rtc_config.debug = True
+policy_cfg.rtc_config.debug_maxlen = 100
+
+# After inference, access debug data
+debug_data = policy.rtc_processor.get_debug_data()
+
+# Visualize denoising steps, corrections, etc.
+from lerobot.policies.rtc.debug_visualizer import RTCDebugVisualizer
+visualizer = RTCDebugVisualizer()
+# ... create plots
+```
+
+See `examples/rtc/eval_dataset.py` for a complete example of visualization.
+
+## References
+
+- [Smooth-As-Butter Robot Policies](https://alexander-soare.github.io/robotics/2025/08/05/smooth-as-butter-robot-policies.html) - Excellent technical explanation with real robot results
+- [Physical Intelligence - Real-Time Chunking](https://www.physicalintelligence.company/research/real_time_chunking) - Original paper and research
+- [Kinetix RTC Implementation](https://github.com/Physical-Intelligence/real-time-chunking-kinetix) - Reference implementation from Physical Intelligence
diff --git a/lerobot/docs/source/sarm.mdx b/lerobot/docs/source/sarm.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..81a04d2bd562274a0a237d5d81431948f5afb01e
--- /dev/null
+++ b/lerobot/docs/source/sarm.mdx
@@ -0,0 +1,592 @@
+# SARM: Stage-Aware Reward Modeling
+
+SARM (Stage-Aware Reward Modeling) is a video-based reward modeling framework for long-horizon robot manipulation tasks. This guide covers how to train SARM reward models and optionally use them with Reward-Aligned Behavior Cloning (RA-BC).
+
+**Paper**: [SARM: Stage-Aware Reward Modeling for Long Horizon Robot Manipulation](https://arxiv.org/abs/2509.25358)
+
+
+
+## Why Reward Models?
+
+Standard behavior cloning treats all demonstration frames equally, but real-world robot datasets are messy. They contain hesitations, corrections, and variable-quality trajectories. Reward models solve this by learning a generalizable notion of **task progress** from demonstrations: given video frames and a task description, they predict how close the robot is to completing the task (0β1). This learned "progress signal" can be used in multiple ways, two promising applications are: (1) **weighted imitation learning** (RA-BC), where high-progress frames receive more weight during policy training, and (2) **reinforcement learning**, where the reward model provides dense rewards for online or offline policy improvement.
+
+## Overview
+
+SARM has following features:
+
+1. **Stage-aware architecture**: Jointly predicts the high-level task stage and fine-grained progress within each stage
+2. **Subtask annotations**: Uses natural language subtask annotations to derive consistent progress labels
+3. **Temporal proportions**: Computes dataset-level priors (Ξ±Μ \_k) for each subtask to normalize progress across variable-length demonstrations
+
+SARM trains on a compact **stage+tau** target for each frame:
+
+- **stage**: integer stage index `k β {0, ..., K-1}`
+- **Ο (tau)**: within-stage progress `Ο β [0, 1]`
+- **target encoding**: `y = k + Ο` (this is what the dataset processor produces)
+
+At inference time (and in downstream RA-BC), SARM converts the raw `k + Ο` value into a **normalized progress** in `[0, 1]` using dataset-level **temporal proportions** `Ξ±Μ _k` (stored in `meta/temporal_proportions_*.json`).
+
+This matches **Formula (2)** from the paper:
+
+```
+progress_t = P_{k-1} + Ξ±Μ _k Γ Ο_t
+```
+
+Where:
+
+- `Ο_t = (t - s_k) / (e_k - s_k)` is within-subtask normalized time
+- `P_{k-1}` is cumulative prior (sum of previous subtask proportions)
+- `Ξ±Μ _k` is the temporal proportion for subtask k
+
+This ensures identical task states map to consistent progress values, even across demonstrations of different lengths.
+
+## Inputs and Targets (What the new code expects)
+
+SARM is trained through its processor (`src/lerobot/policies/sarm/processor_sarm.py`), which:
+
+- **Encodes** images and task text with CLIP (ViT-B/32) into `video_features` and `text_features`
+- **Pads/truncates** robot state into `state_features` (up to `max_state_dim`)
+- **Builds targets** as `sparse_targets` (and `dense_targets` in `dense_only`/`dual`) using the stage+tau encoding `y = k + Ο`
+- **Masks rewind frames** using a per-sample `lengths` tensor (rewind is a training-time augmentation)
+
+At minimum, each training sample needs:
+
+- `task` (string): task description
+- `policy.image_key` images and `policy.state_key` states from the dataset
+
+---
+
+## Annotation Modes
+
+You can choose from **3 annotation modes** that determine how progress labels are computed:
+
+| Mode | Annotations Required | Heads | Use Case |
+| -------------- | -------------------- | ---------------------------- | ------------------------------------------------------------ |
+| `single_stage` | None | Sparse only | Simple tasks, quick experiments, no VLM needed |
+| `dense_only` | Dense (VLM) | Dual (sparse auto-generated) | Detailed subtask tracking without defining high-level stages |
+| `dual` | Sparse + Dense (VLM) | Dual | Full SARM paper setup with both granularities |
+
+### Mode Details
+
+
+
+
+**No annotations required.** The entire episode is treated as a single stage called `"task"`, and progress is linear from 0 to 1 over the episode duration.
+
+- **Sparse head**: 1 stage ("task"), linear progress
+- **Dense head**: Not used
+- **Best for**: Simple tasks, quick experiments, or when VLM annotation is not available
+
+## Set Up Your Environment
+
+1. Install LeRobot by following our [Installation Guide](./installation).
+2. Install SARM dependencies by running:
+
+```bash
+pip install -e ".[sarm]"
+```
+
+Workflow:
+
+```
+1. Train SARM β 2. Visualize predictions β 3. (Optional) Train policy with RA-BC
+```
+
+
+
+
+**Only dense (fine-grained) annotations from a VLM.** The sparse head automatically uses a single `"task"` stage covering the full episode, while the dense head learns detailed subtask progression.
+
+- **Sparse head**: 1 stage ("task"), linear progress (auto-generated)
+- **Dense head**: Multiple fine-grained stages from VLM annotations
+- **Best for**: When you want detailed subtask tracking but don't need to define high-level stages
+
+Workflow:
+
+```
+1. Annotate (dense) β 2. Verify β 3. Train SARM β 4. Visualize β 5. (Optional) Train policy with RA-BC
+```
+
+
+
+
+**Both sparse and dense annotations from VLM.** Full dual-head mode as described in the SARM paper, with both high-level (sparse) and fine-grained (dense) stage predictions.
+
+- **Sparse head**: High-level stages from VLM annotations
+- **Dense head**: Fine-grained stages from VLM annotations
+- **Best for**: Complex multi-stage tasks where both granularities are useful
+
+Workflow:
+
+```
+1. Annotate (sparse+dense) β 2. Verify β 3. Train SARM β 4. Visualize β 5. (Optional) Train policy with RA-BC
+```
+
+
+
+
+---
+
+## Step 1: Subtask Annotation
+
+
+
+
+**No annotation required!** Skip this step entirely. The model will use the episode's task description and compute linear progress automatically.
+
+
+
+
+Generate **dense (fine-grained) annotations only** using a VLM. The sparse stage will be auto-generated.
+
+```bash
+python src/lerobot/data_processing/sarm_annotations/subtask_annotation.py \
+ --repo-id your-username/your-dataset \
+ --dense-only \
+ --dense-subtasks "Bring robot arms up from starting position,Grab near side and do 1st fold,Grab side and do 2nd fold,Grab side and do 3rd fold to finish folding" \
+ --video-key observation.images.base \
+ --num-workers 4 \
+ --push-to-hub
+```
+
+**What gets saved:**
+
+- `meta/temporal_proportions_sparse.json` - Auto-generated sparse proportions (`{"task": 1.0}`)
+- `meta/temporal_proportions_dense.json` - Dense temporal proportions
+- Per-episode columns in `episodes/*.parquet`:
+ - `dense_subtask_names`, `dense_subtask_start_frames`, `dense_subtask_end_frames`
+ - (also time-based columns: `dense_subtask_start_times`, `dense_subtask_end_times`)
+
+
+
+
+Generate **both sparse (high-level) and dense (fine-grained) annotations** using a VLM.
+
+```bash
+python src/lerobot/data_processing/sarm_annotations/subtask_annotation.py \
+ --repo-id your-username/your-dataset \
+ --sparse-subtasks "Bring arms up from starting position,Fold the towel (3 folds in total)" \
+ --dense-subtasks "Bring robot arms up from starting position,Grab near side and do 1st fold,Grab side and do 2nd fold,Grab side and do 3rd fold to finish folding" \
+ --video-key observation.images.base \
+ --num-workers 4 \
+ --push-to-hub
+```
+
+**What gets saved:**
+
+- `meta/temporal_proportions_sparse.json` - Sparse temporal proportions
+- `meta/temporal_proportions_dense.json` - Dense temporal proportions
+- Per-episode columns in `episodes/*.parquet`:
+ - `sparse_subtask_names`, `sparse_subtask_start_frames`, `sparse_subtask_end_frames`
+ - `dense_subtask_names`, `dense_subtask_start_frames`, `dense_subtask_end_frames`
+ - (also time-based columns: `*_subtask_start_times`, `*_subtask_end_times`)
+
+
+
+
+### Annotation Arguments
+
+| Argument | Description |
+| ---------------------- | ------------------------------------------------------------------------------- |
+| `--repo-id` | HuggingFace dataset repository ID |
+| `--sparse-subtasks` | Comma-separated list of high-level subtask names |
+| `--dense-subtasks` | Comma-separated list of fine-grained subtask names |
+| `--dense-only` | Generate only dense annotations (auto-creates sparse "task" stage) |
+| `--video-key` | Camera/video key to use (e.g., `observation.images.top`) |
+| `--num-workers` | Number of parallel GPU workers (default: 1) |
+| `--episodes` | Specific episode indices to annotate (default: all) |
+| `--skip-existing` | Skip episodes that already have annotations |
+| `--model` | VLM model (default: `Qwen/Qwen3-VL-30B-A3B-Instruct`) |
+| `--num-visualizations` | Number of episodes to visualize after annotation (default: 5, set to 0 to skip) |
+
+> **Note**: After annotation completes, 5 episodes are automatically visualized by default. Use `--num-visualizations 0` to skip this step.
+
+---
+
+## Step 2: Verify Annotations
+
+
+
+
+**No verification needed!** Skip this step.
+
+
+
+
+Visualize annotations using the `--visualize-only` flag:
+
+```bash
+python src/lerobot/data_processing/sarm_annotations/subtask_annotation.py \
+ --repo-id your-username/your-dataset \
+ --visualize-only \
+ --visualize-type dense \
+ --num-visualizations 5 \
+ --video-key observation.images.base \
+ --output-dir ./subtask_viz
+```
+
+
+
+
+Visualize annotations using the `--visualize-only` flag:
+
+```bash
+python src/lerobot/data_processing/sarm_annotations/subtask_annotation.py \
+ --repo-id your-username/your-dataset \
+ --visualize-only \
+ --visualize-type both \
+ --num-visualizations 5 \
+ --video-key observation.images.base \
+ --output-dir ./subtask_viz
+```
+
+
+
+
+This generates visualizations showing video frames with subtask boundaries overlaid and timeline of subtasks.
+
+### Visualization Arguments
+
+| Argument | Description |
+| ---------------------- | -------------------------------------------------------------- |
+| `--visualize-only` | Only visualize existing annotations (no generation) |
+| `--num-visualizations` | Number of episodes to visualize (default: 5) |
+| `--visualize-type` | Type of annotations to visualize: `sparse`, `dense`, or `both` |
+
+**Tip**: If annotations are inaccurate, adjust your subtask descriptions to be more specific and re-run.
+
+---
+
+## Step 3: Train SARM
+
+
+
+
+Train with **no annotations** - uses linear progress from 0 to 1:
+
+```bash
+python src/lerobot/scripts/lerobot_train.py \
+ --dataset.repo_id=your-username/your-dataset \
+ --policy.type=sarm \
+ --policy.annotation_mode=single_stage \
+ --policy.image_key=observation.images.base \
+ --output_dir=outputs/train/sarm_single \
+ --batch_size=32 \
+ --steps=5000 \
+ --wandb.enable=true \
+ --wandb.project=sarm \
+ --policy.repo_id=your-username/your-model-name
+```
+
+
+
+
+Train with **dense annotations only** (sparse auto-generated):
+
+```bash
+python src/lerobot/scripts/lerobot_train.py \
+ --dataset.repo_id=your-username/your-dataset \
+ --policy.type=sarm \
+ --policy.annotation_mode=dense_only \
+ --policy.image_key=observation.images.base \
+ --output_dir=outputs/train/sarm_dense \
+ --batch_size=32 \
+ --steps=5000 \
+ --wandb.enable=true \
+ --wandb.project=sarm \
+ --policy.repo_id=your-username/your-model-name
+```
+
+
+
+
+Train with **both sparse and dense annotations**:
+
+```bash
+python src/lerobot/scripts/lerobot_train.py \
+ --dataset.repo_id=your-username/your-dataset \
+ --policy.type=sarm \
+ --policy.annotation_mode=dual \
+ --policy.image_key=observation.images.base \
+ --output_dir=outputs/train/sarm_dual \
+ --batch_size=32 \
+ --steps=5000 \
+ --wandb.enable=true \
+ --wandb.project=sarm \
+ --policy.repo_id=your-username/your-model-name
+```
+
+
+
+
+### Multi-GPU Training
+
+Add `accelerate launch --multi_gpu --num_processes=4` to use multiple GPUs for training.
+
+### Training Arguments
+
+| Argument | Description | Default |
+| -------------------------- | ----------------------------------------------------------------- | ------------------------ |
+| `--policy.annotation_mode` | `single_stage`, `dense_only`, or `dual` | `single_stage` |
+| `--policy.image_key` | Camera key for images | `observation.images.top` |
+| `--policy.state_key` | Key for joint states | `observation.state` |
+| `--policy.n_obs_steps` | Observation history steps (total obs frames = `n_obs_steps + 1`) | `8` |
+| `--policy.frame_gap` | Gap (in frames) between sampled observations (at 30 fps: 30 β 1s) | `30` |
+
+---
+
+## Step 4: Visualize Predictions
+
+Use `compute_rabc_weights.py` with `--visualize-only` to visualize model predictions (and, if available, annotation-derived targets) without writing a parquet file.
+
+
+
+
+```bash
+python src/lerobot/policies/sarm/compute_rabc_weights.py \
+ --dataset-repo-id your-username/your-dataset \
+ --reward-model-path your-username/sarm-model \
+ --visualize-only \
+ --num-visualizations 5 \
+ --head-mode sparse \
+ --output-dir ./sarm_viz
+```
+
+
+
+
+```bash
+python src/lerobot/policies/sarm/compute_rabc_weights.py \
+ --dataset-repo-id your-username/your-dataset \
+ --reward-model-path your-username/sarm-model \
+ --visualize-only \
+ --num-visualizations 5 \
+ --head-mode dense \
+ --output-dir ./sarm_viz
+```
+
+
+
+
+```bash
+python src/lerobot/policies/sarm/compute_rabc_weights.py \
+ --dataset-repo-id your-username/your-dataset \
+ --reward-model-path your-username/sarm-model \
+ --visualize-only \
+ --num-visualizations 5 \
+ --head-mode both \
+ --output-dir ./sarm_viz
+```
+
+
+
+
+The visualization shows:
+
+- **Progress plot**: Predicted progress (and optional annotation-derived βGTβ when available and `--stride 1`)
+- **Stage probabilities**: Stacked area plot of predicted stage probabilities
+- **Sample frames**: Key frames from the episode with progress/stage labels
+
+### Visualization Arguments
+
+| Argument | Description |
+| ---------------------- | --------------------------------------------------------- |
+| `--visualize-only` | Only visualize predictions (no RABC computation) |
+| `--num-visualizations` | Number of episodes to visualize (default: 5) |
+| `--head-mode` | SARM head to use: `sparse`, `dense`, or `both` |
+| `--stride` | Compute every N frames, interpolate the rest (default: 1) |
+
+---
+
+## Step 5 (Optional): Train Policy with RA-BC
+
+Reward-Aligned Behavior Cloning (RA-BC) uses the trained SARM model to weight training samples based on predicted progress improvement. This requires two steps:
+
+1. **Precompute progress values** for all frames using the trained SARM model
+2. **Train policy** with RA-BC weighting using the precomputed values
+
+### How RA-BC Works
+
+For each training sample, RA-BC computes the progress delta:
+
+```
+r_i = Ο(o_{t+Ξ}) - Ο(o_t)
+```
+
+Where `Ο` is the SARM progress prediction and `Ξ` is the policy's `chunk_size`. Samples with positive progress (good demonstrations) get higher weights, while samples with negative or zero progress get down-weighted.
+
+The weighting follows **Equations 8-9** from the paper:
+
+- **Soft weight**: `wΜ_i = clip((r_i β (ΞΌ β 2Ο)) / (4Ο + Ξ΅), 0, 1)`
+- **Final weight**: `w_i = π{r_i > ΞΊ} + π{0 β€ r_i β€ ΞΊ} Γ wΜ_i`
+
+### Step 5a: Compute SARM Progress Values
+
+First, run the SARM model on all frames in your dataset to compute progress values:
+
+```bash
+python src/lerobot/policies/sarm/compute_rabc_weights.py \
+ --dataset-repo-id your-username/your-dataset \
+ --reward-model-path your-username/sarm-model \
+ --head-mode sparse \
+ --num-visualizations 5 \
+ --push-to-hub
+```
+
+This script:
+
+- Processes all frames and computes progress values
+- Saves progress values to a parquet file next to the dataset on disk (defaults to `/sarm_progress.parquet`)
+- Generates visualizations of the first N episodes (default: 5)
+
+**Arguments:**
+
+| Argument | Description | Default |
+| ---------------------- | -------------------------------------------------------------- | ---------- |
+| `--reward-model-path` | Path to trained SARM model | (required) |
+| `--head-mode` | SARM head to use: `sparse`, `dense`, or `both` | `sparse` |
+| `--device` | Device for inference | `cuda` |
+| `--visualize-only` | Only visualize predictions (no RA-BC computation) | `false` |
+| `--num-visualizations` | Number of episodes to visualize (default: 5, set to 0 to skip) | `5` |
+
+**Output format** (`sarm_progress.parquet`):
+
+| Column | Description |
+| ----------------- | ---------------------------------------------- |
+| `index` | Global frame index in dataset |
+| `episode_index` | Episode number |
+| `frame_index` | Local frame index within episode |
+| `progress_sparse` | Sparse head progress value [0, 1] |
+| `progress_dense` | Dense head progress value [0, 1] (if computed) |
+
+### Step 5b: Train Policy with RA-BC
+
+Once you have the progress file, train your policy with RA-BC weighting. The progress file is auto-detected from the dataset path (`sarm_progress.parquet`). Currently PI0, PI0.5 and SmolVLA are supported with RA-BC:
+
+```bash
+python src/lerobot/scripts/lerobot_train.py \
+ --dataset.repo_id=your-username/your-dataset \
+ --policy.type=pi0 \
+ --use_rabc=true \
+ --rabc_head_mode=sparse \
+ --rabc_kappa=0.01 \
+ --output_dir=outputs/train/policy_rabc \
+ --batch_size=32 \
+ --steps=40000
+```
+
+The training script automatically:
+
+- Loads the precomputed progress values from the parquet file
+- Uses the policy's `chunk_size` to compute progress deltas (Ξ)
+- Computes sample weights based on progress improvement
+- Applies weighted loss during training
+
+**RA-BC Arguments:**
+
+| Argument | Description | Default |
+| ---------------------- | ---------------------------------------------------------- | ---------------------------------- |
+| `--use_rabc` | Enable RA-BC sample weighting | `false` |
+| `--rabc_progress_path` | Path to progress parquet file (auto-detected from dataset) | `sarm_progress.parquet` in dataset |
+| `--rabc_head_mode` | Which SARM head's progress to use: `sparse` or `dense` | `sparse` |
+| `--rabc_kappa` | Threshold ΞΊ for high-quality samples | `0.01` |
+
+### Tuning RA-BC Kappa
+
+The `kappa` parameter is the threshold that determines which samples get full weight (w=1). Understanding how to tune it is critical for RA-BC to work effectively.
+
+**How the weighting works:**
+
+| Condition | Weight |
+| ------------------- | ----------------------- |
+| `delta > kappa` | 1.0 (hard threshold) |
+| `0 β€ delta β€ kappa` | Soft weight from Eq. 8 |
+| `delta < 0` | 0.0 (negative progress) |
+
+**Diagnosing kappa issues:**
+
+Monitor these WandB metrics during training:
+
+| Metric | Healthy Range | Problem Indicator |
+| ------------------ | ------------- | ------------------------- |
+| `rabc_mean_weight` | 0.3 - 0.8 | β 1.0 means kappa too low |
+| `rabc_delta_mean` | > 0 | Should be positive |
+| `rabc_delta_std` | > 0 | Variance in data quality |
+
+**If `rabc_mean_weight β 1.0`:** Your kappa is too low. Most samples have `delta > kappa` and bypass the soft-weighting entirely. RA-BC becomes equivalent to vanilla BC.
+
+**Setting kappa based on your data:**
+
+The default `kappa=0.01` was tuned for the paper's T-shirt folding task (~90s episodes at 30fps). For your dataset, check the logged `rabc_delta_mean` and `rabc_delta_std`:
+
+```
+# If delta_mean β 0.03 and delta_std β 0.02:
+# Most deltas fall in range [0.01, 0.05]
+
+# Option 1: Set kappa = delta_mean (medium selectivity)
+--rabc_kappa=0.03
+
+# Option 2: Set kappa = delta_mean + delta_std (high selectivity)
+--rabc_kappa=0.05
+
+# Option 3: Set kappa = delta_mean + 2*delta_std (very selective)
+--rabc_kappa=0.07
+```
+
+**When RA-BC may not help:**
+
+If your dataset is already high quality (consistent progress across all demonstrations), RA-BC won't provide much benefit since there's nothing to filter.
+
+### Multi-GPU Training with RA-BC
+
+```bash
+accelerate launch \
+ --multi_gpu \
+ --num_processes=4 \
+ src/lerobot/scripts/lerobot_train.py \
+ --dataset.repo_id=your-username/your-dataset \
+ --policy.type=pi0 \
+ --use_rabc=true \
+ --rabc_kappa=0.01 \
+ --output_dir=outputs/train/policy_rabc \
+ --batch_size=32 \
+ --steps=40000
+```
+
+---
+
+## Tips & Best Practices
+
+### Choosing a Mode
+
+- **Start with `single_stage`** for quick experiments - no annotation overhead
+- Use **`dense_only`** when you want detailed progress tracking but tasks don't have clear high-level stages
+- Use **`dual`** for complex tasks where both coarse and fine-grained progress is meaningful
+
+### Annotation Quality
+
+1. **Be specific with subtask names**: Instead of "fold", use "grab near side and fold toward center"
+2. **Verify with visualization**: Always check a few episodes before training
+3. **Consistent naming**: Use the same subtask names across all episodes
+
+### RA-BC
+
+1. **Train SARM first**: RA-BC quality depends entirely on SARM quality
+2. **Monitor `rabc_mean_weight`**: If it's β 1.0, increase kappa (see [Tuning RA-BC Kappa](#tuning-ra-bc-kappa))
+
+---
+
+## Citation
+
+```bibtex
+@article{chen2025sarm,
+ title={SARM: Stage-Aware Reward Modeling for Long Horizon Robot Manipulation},
+ author={Chen, Qianzhong and Yu, Justin and Schwager, Mac and Abbeel, Pieter and Shentu, Yide and Wu, Philipp},
+ journal={arXiv preprint arXiv:2509.25358},
+ year={2025}
+}
+```
diff --git a/lerobot/docs/source/smolvla.mdx b/lerobot/docs/source/smolvla.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..a9a498d6476b6f46157465ab3c4f5ab1c9ab1c5d
--- /dev/null
+++ b/lerobot/docs/source/smolvla.mdx
@@ -0,0 +1,116 @@
+# SmolVLA
+
+SmolVLA is Hugging Faceβs lightweight foundation model for robotics. Designed for easy fine-tuning on LeRobot datasets, it helps accelerate your development!
+
+
+
+
+
+ Figure 1. SmolVLA takes as input (i) multiple cameras views, (ii) the
+ robotβs current sensorimotor state, and (iii) a natural language
+ instruction, encoded into contextual features used to condition the action
+ expert when generating an action chunk.
+
+
+
+## Set Up Your Environment
+
+1. Install LeRobot by following our [Installation Guide](./installation).
+2. Install SmolVLA dependencies by running:
+
+ ```bash
+ pip install -e ".[smolvla]"
+ ```
+
+## Collect a dataset
+
+SmolVLA is a base model, so fine-tuning on your own data is required for optimal performance in your setup.
+We recommend recording ~50 episodes of your task as a starting point. Follow our guide to get started: [Recording a Dataset](./il_robots)
+
+
+
+In your dataset, make sure to have enough demonstrations per each variation (e.g. the cube position on the table if it is cube pick-place task) you are introducing.
+
+We recommend checking out the dataset linked below for reference that was used in the [SmolVLA paper](https://huggingface.co/papers/2506.01844):
+
+π [SVLA SO100 PickPlace](https://huggingface.co/spaces/lerobot/visualize_dataset?path=%2Flerobot%2Fsvla_so100_pickplace%2Fepisode_0)
+
+In this dataset, we recorded 50 episodes across 5 distinct cube positions. For each position, we collected 10 episodes of pick-and-place interactions. This structure, repeating each variation several times, helped the model generalize better. We tried similar dataset with 25 episodes, and it was not enough leading to a bad performance. So, the data quality and quantity is definitely a key.
+After you have your dataset available on the Hub, you are good to go to use our finetuning script to adapt SmolVLA to your application.
+
+
+
+## Finetune SmolVLA on your data
+
+Use [`smolvla_base`](https://hf.co/lerobot/smolvla_base), our pretrained 450M model, and fine-tune it on your data.
+Training the model for 20k steps will roughly take ~4 hrs on a single A100 GPU. You should tune the number of steps based on performance and your use-case.
+
+If you don't have a gpu device, you can train using our notebook on [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/lerobot/training-smolvla.ipynb)
+
+Pass your dataset to the training script using `--dataset.repo_id`. If you want to test your installation, run the following command where we use one of the datasets we collected for the [SmolVLA Paper](https://huggingface.co/papers/2506.01844).
+
+```bash
+cd lerobot && lerobot-train \
+ --policy.path=lerobot/smolvla_base \
+ --dataset.repo_id=${HF_USER}/mydataset \
+ --batch_size=64 \
+ --steps=20000 \
+ --output_dir=outputs/train/my_smolvla \
+ --job_name=my_smolvla_training \
+ --policy.device=cuda \
+ --wandb.enable=true
+```
+
+
+ You can start with a small batch size and increase it incrementally, if the
+ GPU allows it, as long as loading times remain short.
+
+
+Fine-tuning is an art. For a complete overview of the options for finetuning, run
+
+```bash
+lerobot-train --help
+```
+
+
+
+
+
+ Figure 2: Comparison of SmolVLA across task variations. From left to right:
+ (1) pick-place cube counting, (2) pick-place cube counting, (3) pick-place
+ cube counting under perturbations, and (4) generalization on pick-and-place
+ of the lego block with real-world SO101.
+
+
+
+## Evaluate the finetuned model and run it in real-time
+
+Similarly for when recording an episode, it is recommended that you are logged in to the HuggingFace Hub. You can follow the corresponding steps: [Record a dataset](./il_robots).
+Once you are logged in, you can run inference in your setup by doing:
+
+```bash
+lerobot-record \
+ --robot.type=so101_follower \
+ --robot.port=/dev/ttyACM0 \ # <- Use your port
+ --robot.id=my_blue_follower_arm \ # <- Use your robot id
+ --robot.cameras="{ front: {type: opencv, index_or_path: 8, width: 640, height: 480, fps: 30}}" \ # <- Use your cameras
+ --dataset.single_task="Grasp a lego block and put it in the bin." \ # <- Use the same task description you used in your dataset recording
+ --dataset.repo_id=${HF_USER}/eval_DATASET_NAME_test \ # <- This will be the dataset name on HF Hub
+ --dataset.episode_time_s=50 \
+ --dataset.num_episodes=10 \
+ # <- Teleop optional if you want to teleoperate in between episodes \
+ # --teleop.type=so100_leader \
+ # --teleop.port=/dev/ttyACM0 \
+ # --teleop.id=my_red_leader_arm \
+ --policy.path=HF_USER/FINETUNE_MODEL_NAME # <- Use your fine-tuned model
+```
+
+Depending on your evaluation setup, you can configure the duration and the number of episodes to record for your evaluation suite.
diff --git a/lerobot/docs/source/so100.mdx b/lerobot/docs/source/so100.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..e2df8ef69c83e2f09bda362fa98366513f2bbdc2
--- /dev/null
+++ b/lerobot/docs/source/so100.mdx
@@ -0,0 +1,640 @@
+# SO-100
+
+In the steps below, we explain how to assemble the SO-100 robot.
+
+## Source the parts
+
+Follow this [README](https://github.com/TheRobotStudio/SO-ARM100/blob/main/SO100.md). It contains the bill of materials, with a link to source the parts, as well as the instructions to 3D print the parts. And advise if it's your first time printing or if you don't own a 3D printer.
+
+## Install LeRobot π€
+
+To install LeRobot, follow our [Installation Guide](./installation)
+
+In addition to these instructions, you need to install the Feetech SDK:
+
+```bash
+pip install -e ".[feetech]"
+```
+
+## Configure the motors
+
+**Note:**
+Unlike the SO-101, the motor connectors are not easily accessible once the arm is assembled, so the configuration step must be done beforehand.
+
+### 1. Find the USB ports associated with each arm
+
+To find the port for each bus servo adapter, run this script:
+
+```bash
+lerobot-find-port
+```
+
+
+
+
+Example output:
+
+```
+Finding all available ports for the MotorBus.
+['/dev/tty.usbmodem575E0032081', '/dev/tty.usbmodem575E0031751']
+Remove the USB cable from your MotorsBus and press Enter when done.
+
+[...Disconnect corresponding leader or follower arm and press Enter...]
+
+The port of this MotorsBus is /dev/tty.usbmodem575E0032081
+Reconnect the USB cable.
+```
+
+Where the found port is: `/dev/tty.usbmodem575E0032081` corresponding to your leader or follower arm.
+
+
+
+
+On Linux, you might need to give access to the USB ports by running:
+
+```bash
+sudo chmod 666 /dev/ttyACM0
+sudo chmod 666 /dev/ttyACM1
+```
+
+Example output:
+
+```
+Finding all available ports for the MotorBus.
+['/dev/ttyACM0', '/dev/ttyACM1']
+Remove the usb cable from your MotorsBus and press Enter when done.
+
+[...Disconnect corresponding leader or follower arm and press Enter...]
+
+The port of this MotorsBus is /dev/ttyACM1
+Reconnect the USB cable.
+```
+
+Where the found port is: `/dev/ttyACM1` corresponding to your leader or follower arm.
+
+
+
+
+### 2. Set the motors ids and baudrates
+
+Each motor is identified by a unique id on the bus. When brand new, motors usually come with a default id of `1`. For the communication to work properly between the motors and the controller, we first need to set a unique, different id to each motor. Additionally, the speed at which data is transmitted on the bus is determined by the baudrate. In order to talk to each other, the controller and all the motors need to be configured with the same baudrate.
+
+To that end, we first need to connect to each motor individually with the controller in order to set these. Since we will write these parameters in the non-volatile section of the motors' internal memory (EEPROM), we'll only need to do this once.
+
+If you are repurposing motors from another robot, you will probably also need to perform this step as the ids and baudrate likely won't match.
+
+#### Follower
+
+Connect the usb cable from your computer and the power supply to the follower arm's controller board. Then, run the following command or run the API example with the port you got from the previous step. You'll also need to give your leader arm a name with the `id` parameter.
+
+For a visual reference on how to set the motor ids please refer to [this video](https://huggingface.co/docs/lerobot/en/so101#setup-motors-video) where we follow the process for the SO101 arm.
+
+
+
+
+```bash
+lerobot-setup-motors \
+ --robot.type=so100_follower \
+ --robot.port=/dev/tty.usbmodem585A0076841 # <- paste here the port found at previous step
+```
+
+
+
+
+
+```python
+from lerobot.robots.so_follower import SO100Follower, SO100FollowerConfig
+
+config = SO100FollowerConfig(
+ port="/dev/tty.usbmodem585A0076841",
+ id="my_awesome_follower_arm",
+)
+follower = SO100Follower(config)
+follower.setup_motors()
+```
+
+
+
+
+
+You should see the following instruction
+
+```
+Connect the controller board to the 'gripper' motor only and press enter.
+```
+
+As instructed, plug the gripper's motor. Make sure it's the only motor connected to the board, and that the motor itself is not yet daisy-chained to any other motor. As you press `[Enter]`, the script will automatically set the id and baudrate for that motor.
+
+
+Troubleshooting
+
+If you get an error at that point, check your cables and make sure they are plugged in properly:
+
+
+
Power supply
+
USB cable between your computer and the controller board
+
The 3-pin cable from the controller board to the motor
+
+
+If you are using a Waveshare controller board, make sure that the two jumpers are set on the `B` channel (USB).
+
+
+
+You should then see the following message:
+
+```
+'gripper' motor id set to 6
+```
+
+Followed by the next instruction:
+
+```
+Connect the controller board to the 'wrist_roll' motor only and press enter.
+```
+
+You can disconnect the 3-pin cable from the controller board, but you can leave it connected to the gripper motor on the other end, as it will already be in the right place. Now, plug in another 3-pin cable to the wrist roll motor and connect it to the controller board. As with the previous motor, make sure it is the only motor connected to the board and that the motor itself isn't connected to any other one.
+
+Repeat the operation for each motor as instructed.
+
+> [!TIP]
+> Check your cabling at each step before pressing Enter. For instance, the power supply cable might disconnect as you manipulate the board.
+
+When you are done, the script will simply finish, at which point the motors are ready to be used. You can now plug the 3-pin cable from each motor to the next one, and the cable from the first motor (the 'shoulder pan' with id=1) to the controller board, which can now be attached to the base of the arm.
+
+#### Leader
+
+Do the same steps for the leader arm.
+
+
+
+```bash
+lerobot-setup-motors \
+ --teleop.type=so100_leader \
+ --teleop.port=/dev/tty.usbmodem575E0031751 # <- paste here the port found at previous step
+```
+
+
+
+
+```python
+from lerobot.teleoperators.so_leader import SO100Leader, SO100LeaderConfig
+
+config = SO100LeaderConfig(
+ port="/dev/tty.usbmodem585A0076841",
+ id="my_awesome_leader_arm",
+)
+leader = SO100Leader(config)
+leader.setup_motors()
+```
+
+
+
+
+
+## Step-by-Step Assembly Instructions
+
+## Remove the gears of the 6 leader motors
+
+
+Video removing gears
+
+
+
+
+
+
+
+Follow the video for removing gears. You need to remove the gear for the motors of the leader arm. As a result, you will only use the position encoding of the motor and reduce friction to more easily operate the leader arm.
+
+### Clean Parts
+
+Remove all support material from the 3D-printed parts. The easiest way to do this is using a small screwdriver to get underneath the support material.
+
+### Additional Guidance
+
+
+Video assembling arms
+
+
+
+
+
+
+
+**Note:**
+This video provides visual guidance for assembling the arms, but it doesn't specify when or how to do the wiring. Inserting the cables beforehand is much easier than doing it afterward. The first arm may take a bit more than 1 hour to assemble, but once you get used to it, you can assemble the second arm in under 1 hour.
+
+---
+
+### First Motor
+
+**Step 2: Insert Wires**
+
+- Insert two wires into the first motor.
+
+
+
+**Step 3: Install in Base**
+
+- Place the first motor into the base.
+
+
+
+**Step 4: Secure Motor**
+
+- Fasten the motor with 4 screws. Two from the bottom and two from top.
+
+**Step 5: Attach Motor Holder**
+
+- Slide over the first motor holder and fasten it using two screws (one on each side).
+
+
+
+**Step 6: Attach Motor Horns**
+
+- Install both motor horns, securing the top horn with a screw. Try not to move the motor position when attaching the motor horn, especially for the leader arms, where we removed the gears.
+
+
+
+
+
+ Video adding motor horn
+
+
+
+
+**Step 7: Attach Shoulder Part**
+
+- Route one wire to the back of the robot and the other to the left or towards you (see photo).
+- Attach the shoulder part.
+
+
+
+**Step 8: Secure Shoulder**
+
+- Tighten the shoulder part with 4 screws on top and 4 on the bottom
+ _(access bottom holes by turning the shoulder)._
+
+---
+
+### Second Motor Assembly
+
+**Step 9: Install Motor 2**
+
+- Slide the second motor in from the top and link the wire from motor 1 to motor 2.
+
+
+
+**Step 10: Attach Shoulder Holder**
+
+- Add the shoulder motor holder.
+- Ensure the wire from motor 1 to motor 2 goes behind the holder while the other wire is routed upward (see photo).
+- This part can be tight to assemble, you can use a workbench like the image or a similar setup to push the part around the motor.
+
+
+
+
+
+
+
+**Step 11: Secure Motor 2**
+
+- Fasten the second motor with 4 screws.
+
+**Step 12: Attach Motor Horn**
+
+- Attach both motor horns to motor 2, again use the horn screw.
+
+**Step 13: Attach Base**
+
+- Install the base attachment using 2 screws.
+
+
+
+**Step 14: Attach Upper Arm**
+
+- Attach the upper arm with 4 screws on each side.
+
+
+
+---
+
+### Third Motor Assembly
+
+**Step 15: Install Motor 3**
+
+- Route the motor cable from motor 2 through the cable holder to motor 3, then secure motor 3 with 4 screws.
+
+**Step 16: Attach Motor Horn**
+
+- Attach both motor horns to motor 3 and secure one again with a horn screw.
+
+
+
+**Step 17: Attach Forearm**
+
+- Connect the forearm to motor 3 using 4 screws on each side.
+
+
+
+---
+
+### Fourth Motor Assembly
+
+**Step 18: Install Motor 4**
+
+- Slide in motor 4, attach the cable from motor 3, and secure the cable in its holder with a screw.
+
+
+
+
+
+
+**Step 19: Attach Motor Holder 4**
+
+- Install the fourth motor holder (a tight fit). Ensure one wire is routed upward and the wire from motor 3 is routed downward (see photo).
+
+
+
+**Step 20: Secure Motor 4 & Attach Horn**
+
+- Fasten motor 4 with 4 screws and attach its motor horns, use for one a horn screw.
+
+
+
+---
+
+### Wrist Assembly
+
+**Step 21: Install Motor 5**
+
+- Insert motor 5 into the wrist holder and secure it with 2 front screws.
+
+
+
+**Step 22: Attach Wrist**
+
+- Connect the wire from motor 4 to motor 5. And already insert the other wire for the gripper.
+- Secure the wrist to motor 4 using 4 screws on both sides.
+
+
+
+**Step 23: Attach Wrist Horn**
+
+- Install only one motor horn on the wrist motor and secure it with a horn screw.
+
+
+
+---
+
+### Follower Configuration
+
+**Step 24: Attach Gripper**
+
+- Attach the gripper to motor 5.
+
+
+
+**Step 25: Install Gripper Motor**
+
+- Insert the gripper motor, connect the motor wire from motor 5 to motor 6, and secure it with 3 screws on each side.
+
+
+
+**Step 26: Attach Gripper Horn & Claw**
+
+- Attach the motor horns and again use a horn screw.
+- Install the gripper claw and secure it with 4 screws on both sides.
+
+
+
+**Step 27: Mount Controller**
+
+- Attach the motor controller to the back of the robot.
+
+
+
+
+
+
+_Assembly complete β proceed to Leader arm assembly._
+
+---
+
+### Leader Configuration
+
+For the leader configuration, perform **Steps 1β23**. Make sure that you removed the motor gears from the motors.
+
+**Step 24: Attach Leader Holder**
+
+- Mount the leader holder onto the wrist and secure it with a screw.
+
+
+
+**Step 25: Attach Handle**
+
+- Attach the handle to motor 5 using 4 screws.
+
+
+
+**Step 26: Install Gripper Motor**
+
+- Insert the gripper motor, secure it with 3 screws on each side, attach a motor horn using a horn screw, and connect the motor wire.
+
+
+
+**Step 27: Attach Trigger**
+
+- Attach the follower trigger with 4 screws.
+
+
+
+**Step 28: Mount Controller**
+
+- Attach the motor controller to the back of the robot.
+
+
+
+
+
+
+## Calibrate
+
+Next, you'll need to calibrate your robot to ensure that the leader and follower arms have the same position values when they are in the same physical position.
+The calibration process is very important because it allows a neural network trained on one robot to work on another.
+
+#### Follower
+
+Run the following command or API example to calibrate the follower arm:
+
+
+
+
+```bash
+lerobot-calibrate \
+ --robot.type=so100_follower \
+ --robot.port=/dev/tty.usbmodem58760431551 \ # <- The port of your robot
+ --robot.id=my_awesome_follower_arm # <- Give the robot a unique name
+```
+
+
+
+
+
+```python
+from lerobot.robots.so_follower import SO100FollowerConfig, SO100Follower
+
+config = SO100FollowerConfig(
+ port="/dev/tty.usbmodem585A0076891",
+ id="my_awesome_follower_arm",
+)
+
+follower = SO100Follower(config)
+follower.connect(calibrate=False)
+follower.calibrate()
+follower.disconnect()
+```
+
+
+
+
+
+We unified the calibration method for most robots. Thus, the calibration steps for this SO100 arm are the same as the steps for the Koch and SO101. First, we have to move the robot to the position where each joint is in the middle of its range, then we press `Enter`. Secondly, we move all joints through their full range of motion. A video of this same process for the SO101 as reference can be found [here](https://huggingface.co/docs/lerobot/en/so101#calibration-video)
+
+#### Leader
+
+Do the same steps to calibrate the leader arm, run the following command or API example:
+
+
+
+
+```bash
+lerobot-calibrate \
+ --teleop.type=so100_leader \
+ --teleop.port=/dev/tty.usbmodem58760431551 \ # <- The port of your robot
+ --teleop.id=my_awesome_leader_arm # <- Give the robot a unique name
+```
+
+
+
+
+
+```python
+from lerobot.teleoperators.so_leader import SO100LeaderConfig, SO100Leader
+
+config = SO100LeaderConfig(
+ port="/dev/tty.usbmodem58760431551",
+ id="my_awesome_leader_arm",
+)
+
+leader = SO100Leader(config)
+leader.connect(calibrate=False)
+leader.calibrate()
+leader.disconnect()
+```
+
+
+
+
+
+Congrats π, your robot is all set to learn a task on its own. Start training it by following this tutorial: [Getting started with real-world robots](./il_robots)
+
+> [!TIP]
+> If you have any questions or need help, please reach out on [Discord](https://discord.com/invite/s3KuuzsPFb).
diff --git a/lerobot/docs/source/so101.mdx b/lerobot/docs/source/so101.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..3714a01a65bbdd35d9e70a81c538a27b6ee949bd
--- /dev/null
+++ b/lerobot/docs/source/so101.mdx
@@ -0,0 +1,436 @@
+# SO-101
+
+In the steps below, we explain how to assemble our flagship robot, the SO-101.
+
+## Source the parts
+
+Follow this [README](https://github.com/TheRobotStudio/SO-ARM100). It contains the bill of materials, with a link to source the parts, as well as the instructions to 3D print the parts.
+And advise if it's your first time printing or if you don't own a 3D printer.
+
+## Install LeRobot π€
+
+To install LeRobot, follow our [Installation Guide](./installation)
+
+In addition to these instructions, you need to install the Feetech SDK:
+
+```bash
+pip install -e ".[feetech]"
+```
+
+## Step-by-Step Assembly Instructions
+
+The follower arm uses 6x STS3215 motors with 1/345 gearing. The leader, however, uses three differently geared motors to make sure it can both sustain its own weight and it can be moved without requiring much force. Which motor is needed for which joint is shown in the table below.
+
+| Leader-Arm Axis | Motor | Gear Ratio |
+| ------------------- | :---: | :--------: |
+| Base / Shoulder Pan | 1 | 1 / 191 |
+| Shoulder Lift | 2 | 1 / 345 |
+| Elbow Flex | 3 | 1 / 191 |
+| Wrist Flex | 4 | 1 / 147 |
+| Wrist Roll | 5 | 1 / 147 |
+| Gripper | 6 | 1 / 147 |
+
+## Configure the motors
+
+### 1. Find the USB ports associated with each arm
+
+To find the port for each bus servo adapter, connect MotorBus to your computer via USB and power. Run the following script and disconnect the MotorBus when prompted:
+
+```bash
+lerobot-find-port
+```
+
+
+
+
+Example output:
+
+```
+Finding all available ports for the MotorBus.
+['/dev/tty.usbmodem575E0032081', '/dev/tty.usbmodem575E0031751']
+Remove the USB cable from your MotorsBus and press Enter when done.
+
+[...Disconnect corresponding leader or follower arm and press Enter...]
+
+The port of this MotorsBus is /dev/tty.usbmodem575E0032081
+Reconnect the USB cable.
+```
+
+Where the found port is: `/dev/tty.usbmodem575E0032081` corresponding to your leader or follower arm.
+
+
+
+
+On Linux, you might need to give access to the USB ports by running:
+
+```bash
+sudo chmod 666 /dev/ttyACM0
+sudo chmod 666 /dev/ttyACM1
+```
+
+Example output:
+
+```
+Finding all available ports for the MotorBus.
+['/dev/ttyACM0', '/dev/ttyACM1']
+Remove the usb cable from your MotorsBus and press Enter when done.
+
+[...Disconnect corresponding leader or follower arm and press Enter...]
+
+The port of this MotorsBus is /dev/ttyACM1
+Reconnect the USB cable.
+```
+
+Where the found port is: `/dev/ttyACM1` corresponding to your leader or follower arm.
+
+
+
+
+### 2. Set the motors ids and baudrates
+
+Each motor is identified by a unique id on the bus. When brand new, motors usually come with a default id of `1`. For the communication to work properly between the motors and the controller, we first need to set a unique, different id to each motor. Additionally, the speed at which data is transmitted on the bus is determined by the baudrate. In order to talk to each other, the controller and all the motors need to be configured with the same baudrate.
+
+To that end, we first need to connect to each motor individually with the controller in order to set these. Since we will write these parameters in the non-volatile section of the motors' internal memory (EEPROM), we'll only need to do this once.
+
+If you are repurposing motors from another robot, you will probably also need to perform this step as the ids and baudrate likely won't match.
+
+The video below shows the sequence of steps for setting the motor ids.
+
+##### Setup motors video
+
+
+
+
+
+#### Follower
+
+Connect the usb cable from your computer and the power supply to the follower arm's controller board. Then, run the following command or run the API example with the port you got from the previous step. You'll also need to give your leader arm a name with the `id` parameter.
+
+
+
+
+```bash
+lerobot-setup-motors \
+ --robot.type=so101_follower \
+ --robot.port=/dev/tty.usbmodem585A0076841 # <- paste here the port found at previous step
+```
+
+
+
+
+
+```python
+from lerobot.robots.so_follower import SO101Follower, SO101FollowerConfig
+
+config = SO101FollowerConfig(
+ port="/dev/tty.usbmodem585A0076841",
+ id="my_awesome_follower_arm",
+)
+follower = SO101Follower(config)
+follower.setup_motors()
+```
+
+
+
+
+
+You should see the following instruction
+
+```bash
+Connect the controller board to the 'gripper' motor only and press enter.
+```
+
+As instructed, plug the gripper's motor. Make sure it's the only motor connected to the board, and that the motor itself is not yet daisy-chained to any other motor. As you press `[Enter]`, the script will automatically set the id and baudrate for that motor.
+
+
+Troubleshooting
+
+If you get an error at that point, check your cables and make sure they are plugged in properly:
+
+
+
Power supply
+
USB cable between your computer and the controller board
+
The 3-pin cable from the controller board to the motor
+
+
+If you are using a Waveshare controller board, make sure that the two jumpers are set on the `B` channel (USB).
+
+
+
+You should then see the following message:
+
+```bash
+'gripper' motor id set to 6
+```
+
+Followed by the next instruction:
+
+```bash
+Connect the controller board to the 'wrist_roll' motor only and press enter.
+```
+
+You can disconnect the 3-pin cable from the controller board, but you can leave it connected to the gripper motor on the other end, as it will already be in the right place. Now, plug in another 3-pin cable to the wrist roll motor and connect it to the controller board. As with the previous motor, make sure it is the only motor connected to the board and that the motor itself isn't connected to any other one.
+
+Repeat the operation for each motor as instructed.
+
+> [!TIP]
+> Check your cabling at each step before pressing Enter. For instance, the power supply cable might disconnect as you manipulate the board.
+
+When you are done, the script will simply finish, at which point the motors are ready to be used. You can now plug the 3-pin cable from each motor to the next one, and the cable from the first motor (the 'shoulder pan' with id=1) to the controller board, which can now be attached to the base of the arm.
+
+#### Leader
+
+Do the same steps for the leader arm.
+
+
+
+
+```bash
+lerobot-setup-motors \
+ --teleop.type=so101_leader \
+ --teleop.port=/dev/tty.usbmodem575E0031751 # <- paste here the port found at previous step
+```
+
+
+
+
+
+```python
+from lerobot.teleoperators.so_leader import SO101Leader, SO101LeaderConfig
+
+config = SO101LeaderConfig(
+ port="/dev/tty.usbmodem585A0076841",
+ id="my_awesome_leader_arm",
+)
+leader = SO101Leader(config)
+leader.setup_motors()
+```
+
+
+
+
+
+### Clean Parts
+
+Remove all support material from the 3D-printed parts. The easiest way to do this is using a small screwdriver to get underneath the support material.
+
+It is advisable to install one 3-pin cable in the motor after placing them before continuing assembly.
+
+### Joint 1
+
+- Place the first motor into the base.
+- Fasten the motor with 4 M2x6mm screws (smallest screws). Two from the top and two from the bottom.
+- Slide over the first motor holder and fasten it using two M2x6mm screws (one on each side).
+- Install both motor horns, securing the top horn with a M3x6mm screw.
+- Attach the shoulder part.
+- Tighten the shoulder part with 4 M3x6mm screws on top and 4 M3x6mm screws on the bottom
+- Add the shoulder motor holder.
+
+
+
+
+
+### Joint 2
+
+- Slide the second motor in from the top.
+- Fasten the second motor with 4 M2x6mm screws.
+- Attach both motor horns to motor 2, again use the M3x6mm horn screw.
+- Attach the upper arm with 4 M3x6mm screws on each side.
+
+
+
+
+
+### Joint 3
+
+- Insert motor 3 and fasten using 4 M2x6mm screws
+- Attach both motor horns to motor 3 and secure one again with a M3x6mm horn screw.
+- Connect the forearm to motor 3 using 4 M3x6mm screws on each side.
+
+
+
+
+
+### Joint 4
+
+- Slide over motor holder 4.
+- Slide in motor 4.
+- Fasten motor 4 with 4 M2x6mm screws and attach its motor horns, use a M3x6mm horn screw.
+
+
+
+
+
+### Joint 5
+
+- Insert motor 5 into the wrist holder and secure it with 2 M2x6mm front screws.
+- Install only one motor horn on the wrist motor and secure it with a M3x6mm horn screw.
+- Secure the wrist to motor 4 using 4 M3x6mm screws on both sides.
+
+
+
+
+
+### Gripper / Handle
+
+
+
+
+- Attach the gripper to motor 5, attach it to the motor horn on the wrist using 4 M3x6mm screws.
+- Insert the gripper motor and secure it with 2 M2x6mm screws on each side.
+- Attach the motor horns and again use a M3x6mm horn screw.
+- Install the gripper claw and secure it with 4 M3x6mm screws on both sides.
+
+
+
+
+
+
+
+
+- Mount the leader holder onto the wrist and secure it with 4 M3x6mm screws.
+- Attach the handle to motor 5 using 1 M2x6mm screw.
+- Insert the gripper motor, secure it with 2 M2x6mm screws on each side, attach a motor horn using a M3x6mm horn screw.
+- Attach the follower trigger with 4 M3x6mm screws.
+
+
+
+
+
+
+
+
+## Calibrate
+
+Next, you'll need to calibrate your robot to ensure that the leader and follower arms have the same position values when they are in the same physical position.
+The calibration process is very important because it allows a neural network trained on one robot to work on another.
+
+#### Follower
+
+Run the following command or API example to calibrate the follower arm:
+
+
+
+
+```bash
+lerobot-calibrate \
+ --robot.type=so101_follower \
+ --robot.port=/dev/tty.usbmodem58760431551 \ # <- The port of your robot
+ --robot.id=my_awesome_follower_arm # <- Give the robot a unique name
+```
+
+
+
+
+
+```python
+from lerobot.robots.so_follower import SO101FollowerConfig, SO101Follower
+
+config = SO101FollowerConfig(
+ port="/dev/tty.usbmodem585A0076891",
+ id="my_awesome_follower_arm",
+)
+
+follower = SO101Follower(config)
+follower.connect(calibrate=False)
+follower.calibrate()
+follower.disconnect()
+```
+
+
+
+
+
+The video below shows how to perform the calibration. First you need to move the robot to the position where all joints are in the middle of their ranges. Then after pressing enter you have to move each joint through its full range of motion.
+
+##### Calibration video
+
+
+
+
+
+#### Leader
+
+Do the same steps to calibrate the leader arm, run the following command or API example:
+
+
+
+
+```bash
+lerobot-calibrate \
+ --teleop.type=so101_leader \
+ --teleop.port=/dev/tty.usbmodem58760431551 \ # <- The port of your robot
+ --teleop.id=my_awesome_leader_arm # <- Give the robot a unique name
+```
+
+
+
+
+
+```python
+from lerobot.teleoperators.so_leader import SO101LeaderConfig, SO101Leader
+
+config = SO101LeaderConfig(
+ port="/dev/tty.usbmodem58760431551",
+ id="my_awesome_leader_arm",
+)
+
+leader = SO101Leader(config)
+leader.connect(calibrate=False)
+leader.calibrate()
+leader.disconnect()
+```
+
+
+
+
+
+Congrats π, your robot is all set to learn a task on its own. Start training it by following this tutorial: [Getting started with real-world robots](./il_robots)
+
+> [!TIP]
+> If you have any questions or need help, please reach out on [Discord](https://discord.com/invite/s3KuuzsPFb).
diff --git a/lerobot/docs/source/unitree_g1.mdx b/lerobot/docs/source/unitree_g1.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..d2986fc119350c8e1cc515b8ac10bd1ae8cbfbc0
--- /dev/null
+++ b/lerobot/docs/source/unitree_g1.mdx
@@ -0,0 +1,203 @@
+# Unitree G1
+
+This guide covers the complete setup process for the Unitree G1 humanoid, from initial connection to running gr00t_wbc locomotion.
+
+## About
+
+We support both 29 and 23 DOF G1 EDU version. We introduce:
+
+- **`unitree g1` robot class, handling low level read/write from/to the humanoid**
+- **ZMQ socket bridge** for remote communication and camera streaming, allowing for remote policy deployment over wlan, eth or directly on the robot
+- **Locomotion policies** from NVIDIA gr00t and Amazon FAR Holosoma
+- **Simulation mode** for testing policies without the physical robot in mujoco
+
+---
+
+## Connection guide
+
+### Step 1: Configure Ethernet Interface
+
+Set a static IP on the same subnet as the robot:
+
+```bash
+# Replace 'enp131s0' with your ethernet interface name (check with `ip a`)
+sudo ip addr flush dev enp131s0
+sudo ip addr add 192.168.123.200/24 dev enp131s0
+sudo ip link set enp131s0 up
+```
+
+**Note**: The G1's Ethernet IP is fixed at `192.168.123.164`. Your computer must use `192.168.123.x` with x β 164.
+
+### Step 2: SSH into the Robot
+
+```bash
+ssh unitree@192.168.123.164
+# Password: 123
+```
+
+You should now be connected to the G1's Orin.
+
+---
+
+## Part 2: Enable WiFi on the Robot
+
+Wlan0 is disabled by default on the G1. To enable it:
+
+### Step 1: Enable WiFi Hardware
+
+```bash
+sudo rfkill unblock wifi
+sudo rfkill unblock all
+
+# Bring up wlan0
+sudo ip link set wlan0 up
+
+# Enable NetworkManager control of wlan0
+sudo nmcli radio wifi on
+sudo nmcli device set wlan0 managed yes
+sudo systemctl restart NetworkManager
+```
+
+### Step 2: Enable Internet Forwarding
+
+**On your laptop:**
+
+```bash
+# Enable IP forwarding
+sudo sysctl -w net.ipv4.ip_forward=1
+
+# Set up NAT (replace wlp132s0f0 with your WiFi interface)
+sudo iptables -t nat -A POSTROUTING -o wlp132s0f0 -s 192.168.123.0/24 -j MASQUERADE
+sudo iptables -A FORWARD -i wlp132s0f0 -o enp131s0 -m state --state RELATED,ESTABLISHED -j ACCEPT
+sudo iptables -A FORWARD -i enp131s0 -o wlp132s0f0 -j ACCEPT
+```
+
+**On the G1:**
+
+```bash
+# Add laptop as default gateway
+sudo ip route del default 2>/dev/null || true
+sudo ip route add default via 192.168.123.200 dev eth0
+echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf
+
+# Test connection
+ping -c 3 8.8.8.8
+```
+
+### Step 3: Connect to WiFi Network
+
+```bash
+# List available networks
+nmcli device wifi list
+
+# Connect to your WiFi (example)
+sudo nmcli connection add type wifi ifname wlan0 con-name "YourNetwork" ssid "YourNetwork"
+sudo nmcli connection modify "YourNetwork" wifi-sec.key-mgmt wpa-psk
+sudo nmcli connection modify "YourNetwork" wifi-sec.psk "YourPassword"
+sudo nmcli connection modify "YourNetwork" connection.autoconnect yes
+sudo nmcli connection up "YourNetwork"
+
+# Check WiFi IP address
+ip a show wlan0
+```
+
+### Step 4: SSH Over WiFi
+
+Once connected to WiFi, note the robot's IP address and disconnect the Ethernet cable. You can now SSH over WiFi:
+
+```bash
+ssh unitree@
+# Password: 123
+```
+
+Replace `` with your robot's actual WiFi IP address.
+
+---
+
+## Part 3: Robot Server Setup
+
+### Step 1: Install LeRobot on the Orin
+
+SSH into the robot and install LeRobot:
+
+```bash
+ssh unitree@
+
+conda create -y -n lerobot python=3.10
+conda activate lerobot
+git clone https://github.com/huggingface/lerobot.git
+cd lerobot
+pip install -e '.[unitree_g1]'
+git clone https://github.com/unitreerobotics/unitree_sdk2_python.git
+cd unitree_sdk2_python && pip install -e .
+```
+
+**Note**: The Unitree SDK requires CycloneDDS v0.10.2 to be installed. See the [Unitree SDK documentation](https://github.com/unitreerobotics/unitree_sdk2_python) for details.
+
+### Step 2: Run the Robot Server
+
+On the robot:
+
+```bash
+python src/lerobot/robots/unitree_g1/run_g1_server.py
+```
+
+**Important**: Keep this terminal running. The server must be active for remote control.
+
+---
+
+## Part 4: Controlling the robot
+
+With the robot server running, you can now control the robot remotely. Let's launch a locomotion policy
+
+### Step 1: Install LeRobot on your machine
+
+```bash
+conda create -y -n lerobot python=3.10
+conda activate lerobot
+git clone https://github.com/huggingface/lerobot.git
+cd lerobot
+pip install -e '.[unitree_g1]'
+git clone https://github.com/unitreerobotics/unitree_sdk2_python.git
+cd unitree_sdk2_python && pip install -e .
+```
+
+### Step 2: Update Robot IP in Config
+
+Edit the config file to match your robot's WiFi IP:
+
+```python
+# In src/lerobot/robots/unitree_g1/config_unitree_g1.py
+robot_ip: str = "" # Replace with your robot's WiFi IP.
+```
+
+### Step 3: Run the Locomotion Policy
+
+```bash
+# Run GR00T locomotion controller
+python examples/unitree_g1/gr00t_locomotion.py --repo-id "nepyope/GR00T-WholeBodyControl_g1"
+
+# Run Holosoma locomotion controller
+python examples/unitree_g1/holosoma_locomotion.py
+
+```
+
+Press `Ctrl+C` to stop the policy.
+
+---
+
+## Running in Simulation Mode (MuJoCo)
+
+You can now test policies before unleashing them on the physical robot using MuJoCo. To do so simply set `is_simulation=True` in config.
+
+## Additional Resources
+
+- [Unitree SDK Documentation](https://github.com/unitreerobotics/unitree_sdk2_python)
+- [GR00T-WholeBodyControl](https://github.com/NVlabs/GR00T-WholeBodyControl)
+- [Holosoma](https://github.com/amazon-far/holosoma)
+- [LeRobot Documentation](https://github.com/huggingface/lerobot)
+- [Unitree_IL_Lerobot](https://github.com/unitreerobotics/unitree_IL_lerobot)
+
+---
+
+_Last updated: December 2025_
diff --git a/lerobot/docs/source/using_dataset_tools.mdx b/lerobot/docs/source/using_dataset_tools.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..9b9885abddb78802b4e3ad6b26fe3d84bb958a90
--- /dev/null
+++ b/lerobot/docs/source/using_dataset_tools.mdx
@@ -0,0 +1,203 @@
+# Using Dataset Tools
+
+This guide covers the dataset tools utilities available in LeRobot for modifying and editing existing datasets.
+
+## Overview
+
+LeRobot provides several utilities for manipulating datasets:
+
+1. **Delete Episodes** - Remove specific episodes from a dataset
+2. **Split Dataset** - Divide a dataset into multiple smaller datasets
+3. **Merge Datasets** - Combine multiple datasets into one. The datasets must have identical features, and episodes are concatenated in the order specified in `repo_ids`
+4. **Add Features** - Add new features to a dataset
+5. **Remove Features** - Remove features from a dataset
+6. **Convert to Video** - Convert image-based datasets to video format for efficient storage
+
+The core implementation is in `lerobot.datasets.dataset_tools`.
+An example script detailing how to use the tools API is available in `examples/dataset/use_dataset_tools.py`.
+
+## Command-Line Tool: lerobot-edit-dataset
+
+`lerobot-edit-dataset` is a command-line script for editing datasets. It can be used to delete episodes, split datasets, merge datasets, add features, remove features, and convert image datasets to video format.
+
+Run `lerobot-edit-dataset --help` for more information on the configuration of each operation.
+
+### Usage Examples
+
+#### Delete Episodes
+
+Remove specific episodes from a dataset. This is useful for filtering out undesired data.
+
+```bash
+# Delete episodes 0, 2, and 5 (modifies original dataset)
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht \
+ --operation.type delete_episodes \
+ --operation.episode_indices "[0, 2, 5]"
+
+# Delete episodes and save to a new dataset (preserves original dataset)
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht \
+ --new_repo_id lerobot/pusht_after_deletion \
+ --operation.type delete_episodes \
+ --operation.episode_indices "[0, 2, 5]"
+```
+
+#### Split Dataset
+
+Divide a dataset into multiple subsets.
+
+```bash
+# Split by fractions (e.g. 80% train, 20% test, 20% val)
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht \
+ --operation.type split \
+ --operation.splits '{"train": 0.8, "test": 0.2, "val": 0.2}'
+
+# Split by specific episode indices
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht \
+ --operation.type split \
+ --operation.splits '{"task1": [0, 1, 2, 3], "task2": [4, 5]}'
+```
+
+There are no constraints on the split names, they can be determined by the user. Resulting datasets are saved under the repo id with the split name appended, e.g. `lerobot/pusht_train`, `lerobot/pusht_task1`, `lerobot/pusht_task2`.
+
+#### Merge Datasets
+
+Combine multiple datasets into a single dataset.
+
+```bash
+# Merge train and validation splits back into one dataset
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht_merged \
+ --operation.type merge \
+ --operation.repo_ids "['lerobot/pusht_train', 'lerobot/pusht_val']"
+```
+
+#### Remove Features
+
+Remove features from a dataset.
+
+```bash
+# Remove a camera feature
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht \
+ --operation.type remove_feature \
+ --operation.feature_names "['observation.images.top']"
+```
+
+#### Convert to Video
+
+Convert an image-based dataset to video format, creating a new LeRobotDataset where images are stored as videos. This is useful for reducing storage requirements and improving data loading performance. The new dataset will have the exact same structure as the original, but with images encoded as MP4 videos in the proper LeRobot format.
+
+```bash
+# Local-only: Save to a custom output directory (no hub push)
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht_image \
+ --operation.type convert_to_video \
+ --operation.output_dir /path/to/output/pusht_video
+
+# Save with new repo_id (local storage)
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht_image \
+ --new_repo_id lerobot/pusht_video \
+ --operation.type convert_to_video
+
+# Convert and push to Hugging Face Hub
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht_image \
+ --new_repo_id lerobot/pusht_video \
+ --operation.type convert_to_video \
+ --push_to_hub true
+
+# Convert with custom video codec and quality settings
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht_image \
+ --operation.type convert_to_video \
+ --operation.output_dir outputs/pusht_video \
+ --operation.vcodec libsvtav1 \
+ --operation.pix_fmt yuv420p \
+ --operation.g 2 \
+ --operation.crf 30
+
+# Convert only specific episodes
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht_image \
+ --operation.type convert_to_video \
+ --operation.output_dir outputs/pusht_video \
+ --operation.episode_indices "[0, 1, 2, 5, 10]"
+
+# Convert with multiple workers for parallel processing
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht_image \
+ --operation.type convert_to_video \
+ --operation.output_dir outputs/pusht_video \
+ --operation.num_workers 8
+```
+
+**Parameters:**
+
+- `output_dir`: Custom output directory (optional - by default uses `new_repo_id` or `{repo_id}_video`)
+- `vcodec`: Video codec to use - options: `h264`, `hevc`, `libsvtav1` (default: `libsvtav1`)
+- `pix_fmt`: Pixel format - options: `yuv420p`, `yuv444p` (default: `yuv420p`)
+- `g`: Group of pictures (GOP) size - lower values give better quality but larger files (default: 2)
+- `crf`: Constant rate factor - lower values give better quality but larger files, 0 is lossless (default: 30)
+- `fast_decode`: Fast decode tuning option (default: 0)
+- `episode_indices`: List of specific episodes to convert (default: all episodes)
+- `num_workers`: Number of parallel workers for processing (default: 4)
+
+**Note:** The resulting dataset will be a proper LeRobotDataset with all cameras encoded as videos in the `videos/` directory, with parquet files containing only metadata (no raw image data). All episodes, stats, and tasks are preserved.
+
+### Push to Hub
+
+Add the `--push_to_hub true` flag to any command to automatically upload the resulting dataset to the Hugging Face Hub:
+
+```bash
+lerobot-edit-dataset \
+ --repo_id lerobot/pusht \
+ --new_repo_id lerobot/pusht_after_deletion \
+ --operation.type delete_episodes \
+ --operation.episode_indices "[0, 2, 5]" \
+ --push_to_hub true
+```
+
+There is also a tool for adding features to a dataset that is not yet covered in `lerobot-edit-dataset`.
+
+# Dataset Visualization
+
+## Online Visualization
+
+When you record a dataset using `lerobot`, it automatically uploads to the Hugging Face Hub unless you specify otherwise. To view the dataset online, use our **LeRobot Dataset Visualizer**, available at:
+https://huggingface.co/spaces/lerobot/visualize_dataset
+
+## Local Visualization
+
+You can also visualize episodes from a dataset locally using our command-line tool.
+
+**From the Hugging Face Hub:**
+
+```bash
+lerobot-dataset-viz \
+ --repo-id lerobot/pusht \
+ --episode-index 0
+```
+
+**From a local folder:**
+Add the `--root` option and set `--mode local`. For example, to search in `./my_local_data_dir/lerobot/pusht`:
+
+```bash
+lerobot-dataset-viz \
+ --repo-id lerobot/pusht \
+ --root ./my_local_data_dir \
+ --mode local \
+ --episode-index 0
+```
+
+Once executed, the tool opens `rerun.io` and displays the camera streams, robot states, and actions for the selected episode.
+
+For advanced usageβincluding visualizing datasets stored on a remote serverβrun:
+
+```bash
+lerobot-dataset-viz --help
+```
diff --git a/lerobot/src/lerobot/processor/core.py b/lerobot/src/lerobot/processor/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..393be2af744fb4ccaac9eec4db5b696341f82c09
--- /dev/null
+++ b/lerobot/src/lerobot/processor/core.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+from enum import Enum
+from typing import Any, TypeAlias, TypedDict
+
+import numpy as np
+import torch
+
+
+class TransitionKey(str, Enum):
+ """Keys for accessing EnvTransition dictionary components."""
+
+ # TODO(Steven): Use consts
+ OBSERVATION = "observation"
+ ACTION = "action"
+ REWARD = "reward"
+ DONE = "done"
+ TRUNCATED = "truncated"
+ INFO = "info"
+ COMPLEMENTARY_DATA = "complementary_data"
+
+
+PolicyAction: TypeAlias = torch.Tensor
+RobotAction: TypeAlias = dict[str, Any]
+EnvAction: TypeAlias = np.ndarray
+RobotObservation: TypeAlias = dict[str, Any]
+
+
+EnvTransition = TypedDict(
+ "EnvTransition",
+ {
+ TransitionKey.OBSERVATION.value: RobotObservation | None,
+ TransitionKey.ACTION.value: PolicyAction | RobotAction | EnvAction | None,
+ TransitionKey.REWARD.value: float | torch.Tensor | None,
+ TransitionKey.DONE.value: bool | torch.Tensor | None,
+ TransitionKey.TRUNCATED.value: bool | torch.Tensor | None,
+ TransitionKey.INFO.value: dict[str, Any] | None,
+ TransitionKey.COMPLEMENTARY_DATA.value: dict[str, Any] | None,
+ },
+)
diff --git a/lerobot/src/lerobot/processor/delta_action_processor.py b/lerobot/src/lerobot/processor/delta_action_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..91912ae7da2423421b5226b83e7409c8a9e44edf
--- /dev/null
+++ b/lerobot/src/lerobot/processor/delta_action_processor.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+
+from lerobot.configs.types import FeatureType, PipelineFeatureType, PolicyFeature
+
+from .core import PolicyAction, RobotAction
+from .pipeline import ActionProcessorStep, ProcessorStepRegistry, RobotActionProcessorStep
+
+
+@ProcessorStepRegistry.register("map_tensor_to_delta_action_dict")
+@dataclass
+class MapTensorToDeltaActionDictStep(ActionProcessorStep):
+ """
+ Maps a flat action tensor from a policy to a structured delta action dictionary.
+
+ This step is typically used after a policy outputs a continuous action vector.
+ It decomposes the vector into named components for delta movements of the
+ end-effector (x, y, z) and optionally the gripper.
+
+ Attributes:
+ use_gripper: If True, assumes the 4th element of the tensor is the
+ gripper action.
+ """
+
+ use_gripper: bool = True
+
+ def action(self, action: PolicyAction) -> RobotAction:
+ if not isinstance(action, PolicyAction):
+ raise ValueError("Only PolicyAction is supported for this processor")
+
+ if action.dim() > 1:
+ action = action.squeeze(0)
+
+ # TODO (maractingi): add rotation
+ delta_action = {
+ "delta_x": action[0].item(),
+ "delta_y": action[1].item(),
+ "delta_z": action[2].item(),
+ }
+ if self.use_gripper:
+ delta_action["gripper"] = action[3].item()
+ return delta_action
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ for axis in ["x", "y", "z"]:
+ features[PipelineFeatureType.ACTION][f"delta_{axis}"] = PolicyFeature(
+ type=FeatureType.ACTION, shape=(1,)
+ )
+
+ if self.use_gripper:
+ features[PipelineFeatureType.ACTION]["gripper"] = PolicyFeature(
+ type=FeatureType.ACTION, shape=(1,)
+ )
+ return features
+
+
+@ProcessorStepRegistry.register("map_delta_action_to_robot_action")
+@dataclass
+class MapDeltaActionToRobotActionStep(RobotActionProcessorStep):
+ """
+ Maps delta actions from teleoperators to robot target actions for inverse kinematics.
+
+ This step converts a dictionary of delta movements (e.g., from a gamepad)
+ into a target action format that includes an "enabled" flag and target
+ end-effector positions. It also handles scaling and noise filtering.
+
+ Attributes:
+ position_scale: A factor to scale the delta position inputs.
+ noise_threshold: The magnitude below which delta inputs are considered noise
+ and do not trigger an "enabled" state.
+ """
+
+ # Scale factors for delta movements
+ position_scale: float = 1.0
+ noise_threshold: float = 1e-3 # 1 mm threshold to filter out noise
+
+ def action(self, action: RobotAction) -> RobotAction:
+ # NOTE (maractingi): Action can be a dict from the teleop_devices or a tensor from the policy
+ # TODO (maractingi): changing this target_xyz naming convention from the teleop_devices
+ delta_x = action.pop("delta_x")
+ delta_y = action.pop("delta_y")
+ delta_z = action.pop("delta_z")
+ gripper = action.pop("gripper")
+
+ # Determine if the teleoperator is actively providing input
+ # Consider enabled if any significant movement delta is detected
+ position_magnitude = (delta_x**2 + delta_y**2 + delta_z**2) ** 0.5 # Use Euclidean norm for position
+ enabled = position_magnitude > self.noise_threshold # Small threshold to avoid noise
+
+ # Scale the deltas appropriately
+ scaled_delta_x = delta_x * self.position_scale
+ scaled_delta_y = delta_y * self.position_scale
+ scaled_delta_z = delta_z * self.position_scale
+
+ # For gamepad/keyboard, we don't have rotation input, so set to 0
+ # These could be extended in the future for more sophisticated teleoperators
+ target_wx = 0.0
+ target_wy = 0.0
+ target_wz = 0.0
+
+ # Update action with robot target format
+ action = {
+ "enabled": enabled,
+ "target_x": scaled_delta_x,
+ "target_y": scaled_delta_y,
+ "target_z": scaled_delta_z,
+ "target_wx": target_wx,
+ "target_wy": target_wy,
+ "target_wz": target_wz,
+ "gripper_vel": float(gripper),
+ }
+
+ return action
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ for axis in ["x", "y", "z", "gripper"]:
+ features[PipelineFeatureType.ACTION].pop(f"delta_{axis}", None)
+
+ for feat in ["enabled", "target_x", "target_y", "target_z", "target_wx", "target_wy", "target_wz"]:
+ features[PipelineFeatureType.ACTION][f"{feat}"] = PolicyFeature(
+ type=FeatureType.ACTION, shape=(1,)
+ )
+
+ return features
diff --git a/lerobot/src/lerobot/processor/device_processor.py b/lerobot/src/lerobot/processor/device_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..5042a4379628ee094c0121b9fc0faff42b557e02
--- /dev/null
+++ b/lerobot/src/lerobot/processor/device_processor.py
@@ -0,0 +1,194 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+This script defines a processor step for moving environment transition data to a specific torch device and casting
+its floating-point precision.
+"""
+
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+
+from lerobot.configs.types import PipelineFeatureType, PolicyFeature
+from lerobot.utils.utils import get_safe_torch_device
+
+from .core import EnvTransition, PolicyAction, TransitionKey
+from .pipeline import ProcessorStep, ProcessorStepRegistry
+
+
+@ProcessorStepRegistry.register("device_processor")
+@dataclass
+class DeviceProcessorStep(ProcessorStep):
+ """
+ Processor step to move all tensors within an `EnvTransition` to a specified device and optionally cast their
+ floating-point data type.
+
+ This is crucial for preparing data for model training or inference on hardware like GPUs.
+
+ Attributes:
+ device: The target device for tensors (e.g., "cpu", "cuda", "cuda:0").
+ float_dtype: The target floating-point dtype as a string (e.g., "float32", "float16", "bfloat16").
+ If None, the dtype is not changed.
+ """
+
+ device: str = "cpu"
+ float_dtype: str | None = None
+
+ DTYPE_MAPPING = {
+ "float16": torch.float16,
+ "float32": torch.float32,
+ "float64": torch.float64,
+ "bfloat16": torch.bfloat16,
+ "half": torch.float16,
+ "float": torch.float32,
+ "double": torch.float64,
+ }
+
+ def __post_init__(self):
+ """
+ Initializes the processor by converting string configurations to torch objects.
+
+ This method sets up the `torch.device`, determines if transfers can be non-blocking, and validates the
+ `float_dtype` string, converting it to a `torch.dtype` object.
+ """
+ self.tensor_device: torch.device = get_safe_torch_device(self.device)
+ # Update device string in case a specific GPU was selected (e.g., "cuda" -> "cuda:0")
+ self.device = self.tensor_device.type
+ self.non_blocking = "cuda" in str(self.device)
+
+ # Validate and convert float_dtype string to torch dtype
+ if self.float_dtype is not None:
+ if self.float_dtype not in self.DTYPE_MAPPING:
+ raise ValueError(
+ f"Invalid float_dtype '{self.float_dtype}'. Available options: {list(self.DTYPE_MAPPING.keys())}"
+ )
+ self._target_float_dtype = self.DTYPE_MAPPING[self.float_dtype]
+ else:
+ self._target_float_dtype = None
+
+ def _process_tensor(self, tensor: torch.Tensor) -> torch.Tensor:
+ """
+ Moves a single tensor to the target device and casts its dtype.
+
+ Handles multi-GPU scenarios by not moving a tensor if it's already on a different CUDA device than
+ the target, which is useful when using frameworks like Accelerate.
+
+ Args:
+ tensor: The input torch.Tensor.
+
+ Returns:
+ The processed tensor on the correct device and with the correct dtype.
+ """
+ # Determine target device
+ if tensor.is_cuda and self.tensor_device.type == "cuda":
+ # Both tensor and target are on GPU - preserve tensor's GPU placement.
+ # This handles multi-GPU scenarios where Accelerate has already placed
+ # tensors on the correct GPU for each process.
+ target_device = tensor.device
+ else:
+ # Either tensor is on CPU, or we're configured for CPU.
+ # In both cases, use the configured device.
+ target_device = self.tensor_device
+
+ # MPS workaround: Convert float64 to float32 since MPS doesn't support float64
+ if target_device.type == "mps" and tensor.dtype == torch.float64:
+ tensor = tensor.to(dtype=torch.float32)
+
+ # Only move if necessary
+ if tensor.device != target_device:
+ tensor = tensor.to(target_device, non_blocking=self.non_blocking)
+
+ # Convert float dtype if specified and tensor is floating point
+ if self._target_float_dtype is not None and tensor.is_floating_point():
+ tensor = tensor.to(dtype=self._target_float_dtype)
+
+ return tensor
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """
+ Applies device and dtype conversion to all tensors in an environment transition.
+
+ It iterates through the transition, finds all `torch.Tensor` objects (including those nested in
+ dictionaries like `observation`), and processes them.
+
+ Args:
+ transition: The input `EnvTransition` object.
+
+ Returns:
+ A new `EnvTransition` object with all tensors moved to the target device and dtype.
+ """
+ new_transition = transition.copy()
+ action = new_transition.get(TransitionKey.ACTION)
+
+ if action is not None and not isinstance(action, PolicyAction):
+ raise ValueError(f"If action is not None should be a PolicyAction type got {type(action)}")
+
+ simple_tensor_keys = [
+ TransitionKey.ACTION,
+ TransitionKey.REWARD,
+ TransitionKey.DONE,
+ TransitionKey.TRUNCATED,
+ ]
+
+ dict_tensor_keys = [
+ TransitionKey.OBSERVATION,
+ TransitionKey.COMPLEMENTARY_DATA,
+ ]
+
+ # Process simple, top-level tensors
+ for key in simple_tensor_keys:
+ value = transition.get(key)
+ if isinstance(value, torch.Tensor):
+ new_transition[key] = self._process_tensor(value)
+
+ # Process tensors nested within dictionaries
+ for key in dict_tensor_keys:
+ data_dict = transition.get(key)
+ if data_dict is not None:
+ new_data_dict = {
+ k: self._process_tensor(v) if isinstance(v, torch.Tensor) else v
+ for k, v in data_dict.items()
+ }
+ new_transition[key] = new_data_dict
+
+ return new_transition
+
+ def get_config(self) -> dict[str, Any]:
+ """
+ Returns the serializable configuration of the processor.
+
+ Returns:
+ A dictionary containing the device and float_dtype settings.
+ """
+ return {"device": self.device, "float_dtype": self.float_dtype}
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """
+ Returns the input features unchanged.
+
+ Device and dtype transformations do not alter the fundamental definition of the features (e.g., shape).
+
+ Args:
+ features: A dictionary of policy features.
+
+ Returns:
+ The original dictionary of policy features.
+ """
+ return features
diff --git a/lerobot/src/lerobot/processor/env_processor.py b/lerobot/src/lerobot/processor/env_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..84e5bbf64707adeaa045730509cf69b8402dc41e
--- /dev/null
+++ b/lerobot/src/lerobot/processor/env_processor.py
@@ -0,0 +1,230 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+
+import torch
+
+from lerobot.configs.types import PipelineFeatureType, PolicyFeature
+from lerobot.utils.constants import OBS_IMAGES, OBS_PREFIX, OBS_STATE, OBS_STR
+
+from .pipeline import ObservationProcessorStep, ProcessorStepRegistry
+
+
+@dataclass
+@ProcessorStepRegistry.register(name="libero_processor")
+class LiberoProcessorStep(ObservationProcessorStep):
+ """
+ Processes LIBERO observations into the LeRobot format.
+
+ This step handles the specific observation structure from LIBERO environments,
+ which includes nested robot_state dictionaries and image observations.
+
+ **State Processing:**
+ - Processes the `robot_state` dictionary which contains nested end-effector,
+ gripper, and joint information.
+ - Extracts and concatenates:
+ - End-effector position (3D)
+ - End-effector quaternion converted to axis-angle (3D)
+ - Gripper joint positions (2D)
+ - Maps the concatenated state to `"observation.state"`.
+
+ **Image Processing:**
+ - Rotates images by 180 degrees by flipping both height and width dimensions.
+ - This accounts for the HuggingFaceVLA/libero camera orientation convention.
+ """
+
+ def _process_observation(self, observation):
+ """
+ Processes both image and robot_state observations from LIBERO.
+ """
+ processed_obs = observation.copy()
+ for key in list(processed_obs.keys()):
+ if key.startswith(f"{OBS_IMAGES}."):
+ img = processed_obs[key]
+
+ # Flip both H and W
+ img = torch.flip(img, dims=[2, 3])
+
+ processed_obs[key] = img
+ # Process robot_state into a flat state vector
+ observation_robot_state_str = OBS_PREFIX + "robot_state"
+ if observation_robot_state_str in processed_obs:
+ robot_state = processed_obs.pop(observation_robot_state_str)
+
+ # Extract components
+ eef_pos = robot_state["eef"]["pos"] # (B, 3,)
+ eef_quat = robot_state["eef"]["quat"] # (B, 4,)
+ gripper_qpos = robot_state["gripper"]["qpos"] # (B, 2,)
+
+ # Convert quaternion to axis-angle
+ eef_axisangle = self._quat2axisangle(eef_quat) # (B, 3)
+ # Concatenate into a single state vector
+ state = torch.cat((eef_pos, eef_axisangle, gripper_qpos), dim=-1)
+
+ # ensure float32
+ state = state.float()
+ if state.dim() == 1:
+ state = state.unsqueeze(0)
+
+ processed_obs[OBS_STATE] = state
+ return processed_obs
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """
+ Transforms feature keys from the LIBERO format to the LeRobot standard.
+ """
+ new_features: dict[PipelineFeatureType, dict[str, PolicyFeature]] = {}
+
+ # copy over non-STATE features
+ for ft, feats in features.items():
+ if ft != PipelineFeatureType.STATE:
+ new_features[ft] = feats.copy()
+
+ # rebuild STATE features
+ state_feats = {}
+
+ # add our new flattened state
+ state_feats[OBS_STATE] = PolicyFeature(
+ key=OBS_STATE,
+ shape=(8,), # [eef_pos(3), axis_angle(3), gripper(2)]
+ dtype="float32",
+ description=("Concatenated end-effector position (3), axis-angle (3), and gripper qpos (2)."),
+ )
+
+ new_features[PipelineFeatureType.STATE] = state_feats
+
+ return new_features
+
+ def observation(self, observation):
+ return self._process_observation(observation)
+
+ def _quat2axisangle(self, quat: torch.Tensor) -> torch.Tensor:
+ """
+ Convert batched quaternions to axis-angle format.
+ Only accepts torch tensors of shape (B, 4).
+
+ Args:
+ quat (Tensor): (B, 4) tensor of quaternions in (x, y, z, w) format
+
+ Returns:
+ Tensor: (B, 3) axis-angle vectors
+
+ Raises:
+ TypeError: if input is not a torch tensor
+ ValueError: if shape is not (B, 4)
+ """
+
+ if not isinstance(quat, torch.Tensor):
+ raise TypeError(f"_quat2axisangle expected a torch.Tensor, got {type(quat)}")
+
+ if quat.ndim != 2 or quat.shape[1] != 4:
+ raise ValueError(f"_quat2axisangle expected shape (B, 4), got {tuple(quat.shape)}")
+
+ quat = quat.to(dtype=torch.float32)
+ device = quat.device
+ batch_size = quat.shape[0]
+
+ w = quat[:, 3].clamp(-1.0, 1.0)
+
+ den = torch.sqrt(torch.clamp(1.0 - w * w, min=0.0))
+
+ result = torch.zeros((batch_size, 3), device=device)
+
+ mask = den > 1e-10
+
+ if mask.any():
+ angle = 2.0 * torch.acos(w[mask]) # (M,)
+ axis = quat[mask, :3] / den[mask].unsqueeze(1)
+ result[mask] = axis * angle.unsqueeze(1)
+
+ return result
+
+
+@dataclass
+@ProcessorStepRegistry.register(name="isaaclab_arena_processor")
+class IsaaclabArenaProcessorStep(ObservationProcessorStep):
+ """
+ Processes IsaacLab Arena observations into LeRobot format.
+
+ **State Processing:**
+ - Extracts state components from obs["policy"] based on `state_keys`.
+ - Concatenates into a flat vector mapped to "observation.state".
+
+ **Image Processing:**
+ - Extracts images from obs["camera_obs"] based on `camera_keys`.
+ - Converts from (B, H, W, C) uint8 to (B, C, H, W) float32 [0, 1].
+ - Maps to "observation.images.".
+ """
+
+ # Configurable from IsaacLabEnv config / cli args: --env.state_keys="robot_joint_pos,left_eef_pos"
+ state_keys: tuple[str, ...]
+
+ # Configurable from IsaacLabEnv config / cli args: --env.camera_keys="robot_pov_cam_rgb"
+ camera_keys: tuple[str, ...]
+
+ def _process_observation(self, observation):
+ """
+ Processes both image and policy state observations from IsaacLab Arena.
+ """
+ processed_obs = {}
+
+ if f"{OBS_STR}.camera_obs" in observation:
+ camera_obs = observation[f"{OBS_STR}.camera_obs"]
+
+ for cam_name, img in camera_obs.items():
+ if cam_name not in self.camera_keys:
+ continue
+
+ img = img.permute(0, 3, 1, 2).contiguous()
+ if img.dtype == torch.uint8:
+ img = img.float() / 255.0
+ elif img.dtype != torch.float32:
+ img = img.float()
+
+ processed_obs[f"{OBS_IMAGES}.{cam_name}"] = img
+
+ # Process policy state -> observation.state
+ if f"{OBS_STR}.policy" in observation:
+ policy_obs = observation[f"{OBS_STR}.policy"]
+
+ # Collect state components in order
+ state_components = []
+ for key in self.state_keys:
+ if key in policy_obs:
+ component = policy_obs[key]
+ # Flatten extra dims: (B, N, M) -> (B, N*M)
+ if component.dim() > 2:
+ batch_size = component.shape[0]
+ component = component.view(batch_size, -1)
+ state_components.append(component)
+
+ if state_components:
+ state = torch.cat(state_components, dim=-1)
+ state = state.float()
+ processed_obs[OBS_STATE] = state
+
+ return processed_obs
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """Not used for policy evaluation."""
+ return features
+
+ def observation(self, observation):
+ return self._process_observation(observation)
diff --git a/lerobot/src/lerobot/processor/factory.py b/lerobot/src/lerobot/processor/factory.py
new file mode 100644
index 0000000000000000000000000000000000000000..66860a37548580bddbc9654043e961e5042213de
--- /dev/null
+++ b/lerobot/src/lerobot/processor/factory.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from .converters import (
+ observation_to_transition,
+ robot_action_observation_to_transition,
+ transition_to_observation,
+ transition_to_robot_action,
+)
+from .core import RobotAction, RobotObservation
+from .pipeline import IdentityProcessorStep, RobotProcessorPipeline
+
+
+def make_default_teleop_action_processor() -> RobotProcessorPipeline[
+ tuple[RobotAction, RobotObservation], RobotAction
+]:
+ teleop_action_processor = RobotProcessorPipeline[tuple[RobotAction, RobotObservation], RobotAction](
+ steps=[IdentityProcessorStep()],
+ to_transition=robot_action_observation_to_transition,
+ to_output=transition_to_robot_action,
+ )
+ return teleop_action_processor
+
+
+def make_default_robot_action_processor() -> RobotProcessorPipeline[
+ tuple[RobotAction, RobotObservation], RobotAction
+]:
+ robot_action_processor = RobotProcessorPipeline[tuple[RobotAction, RobotObservation], RobotAction](
+ steps=[IdentityProcessorStep()],
+ to_transition=robot_action_observation_to_transition,
+ to_output=transition_to_robot_action,
+ )
+ return robot_action_processor
+
+
+def make_default_robot_observation_processor() -> RobotProcessorPipeline[RobotObservation, RobotObservation]:
+ robot_observation_processor = RobotProcessorPipeline[RobotObservation, RobotObservation](
+ steps=[IdentityProcessorStep()],
+ to_transition=observation_to_transition,
+ to_output=transition_to_observation,
+ )
+ return robot_observation_processor
+
+
+def make_default_processors():
+ teleop_action_processor = make_default_teleop_action_processor()
+ robot_action_processor = make_default_robot_action_processor()
+ robot_observation_processor = make_default_robot_observation_processor()
+ return (teleop_action_processor, robot_action_processor, robot_observation_processor)
diff --git a/lerobot/src/lerobot/processor/gym_action_processor.py b/lerobot/src/lerobot/processor/gym_action_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..15e0c579f7ff32322c990bc88d44c721d7d93e8a
--- /dev/null
+++ b/lerobot/src/lerobot/processor/gym_action_processor.py
@@ -0,0 +1,97 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+
+from lerobot.configs.types import PipelineFeatureType, PolicyFeature
+
+from .converters import to_tensor
+from .core import EnvAction, EnvTransition, PolicyAction
+from .pipeline import ActionProcessorStep, ProcessorStep, ProcessorStepRegistry
+
+
+@ProcessorStepRegistry.register("torch2numpy_action_processor")
+@dataclass
+class Torch2NumpyActionProcessorStep(ActionProcessorStep):
+ """
+ Converts a PyTorch tensor action to a NumPy array.
+
+ This step is useful when the output of a policy (typically a torch.Tensor)
+ needs to be passed to an environment or component that expects a NumPy array.
+
+ Attributes:
+ squeeze_batch_dim: If True, removes the first dimension of the array
+ if it is of size 1. This is useful for converting a
+ batched action of size (1, D) to a single action of size (D,).
+ """
+
+ squeeze_batch_dim: bool = True
+
+ def action(self, action: PolicyAction) -> EnvAction:
+ if not isinstance(action, PolicyAction):
+ raise TypeError(
+ f"Expected PolicyAction or None, got {type(action).__name__}. "
+ "Use appropriate processor for non-tensor actions."
+ )
+
+ numpy_action = action.detach().cpu().numpy()
+
+ # Remove batch dimensions but preserve action dimensions.
+ # Only squeeze if there's a batch dimension (first dim == 1).
+ if (
+ self.squeeze_batch_dim
+ and numpy_action.shape
+ and len(numpy_action.shape) > 1
+ and numpy_action.shape[0] == 1
+ ):
+ numpy_action = numpy_action.squeeze(0)
+
+ return numpy_action
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
+
+
+@ProcessorStepRegistry.register("numpy2torch_action_processor")
+@dataclass
+class Numpy2TorchActionProcessorStep(ProcessorStep):
+ """Converts a NumPy array action to a PyTorch tensor when action is present."""
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Converts numpy action to torch tensor if action exists, otherwise passes through."""
+ from .core import TransitionKey
+
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ action = new_transition.get(TransitionKey.ACTION)
+ if action is not None:
+ if not isinstance(action, EnvAction):
+ raise TypeError(
+ f"Expected np.ndarray or None, got {type(action).__name__}. "
+ "Use appropriate processor for non-tensor actions."
+ )
+ torch_action = to_tensor(action, dtype=None) # Preserve original dtype
+ new_transition[TransitionKey.ACTION] = torch_action
+
+ return new_transition
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
diff --git a/lerobot/src/lerobot/processor/hil_processor.py b/lerobot/src/lerobot/processor/hil_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e5ad0ef30028c061e5d7c9bec42f2d765024ce5
--- /dev/null
+++ b/lerobot/src/lerobot/processor/hil_processor.py
@@ -0,0 +1,596 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+import time
+from dataclasses import dataclass
+from typing import Any, Protocol, TypeVar, runtime_checkable
+
+import numpy as np
+import torch
+import torchvision.transforms.functional as F # noqa: N812
+
+from lerobot.configs.types import PipelineFeatureType, PolicyFeature
+from lerobot.teleoperators.teleoperator import Teleoperator
+from lerobot.teleoperators.utils import TeleopEvents
+
+from .core import EnvTransition, PolicyAction, TransitionKey
+from .pipeline import (
+ ComplementaryDataProcessorStep,
+ InfoProcessorStep,
+ ObservationProcessorStep,
+ ProcessorStep,
+ ProcessorStepRegistry,
+ TruncatedProcessorStep,
+)
+
+GRIPPER_KEY = "gripper"
+DISCRETE_PENALTY_KEY = "discrete_penalty"
+TELEOP_ACTION_KEY = "teleop_action"
+
+
+@runtime_checkable
+class HasTeleopEvents(Protocol):
+ """
+ Minimal protocol for objects that provide teleoperation events.
+
+ This protocol defines the `get_teleop_events()` method, allowing processor
+ steps to interact with teleoperators that support event-based controls
+ (like episode termination or success flagging) without needing to know the
+ teleoperator's specific class.
+ """
+
+ def get_teleop_events(self) -> dict[str, Any]:
+ """
+ Get extra control events from the teleoperator.
+
+ Returns:
+ A dictionary containing control events such as:
+ - `is_intervention`: bool - Whether the human is currently intervening.
+ - `terminate_episode`: bool - Whether to terminate the current episode.
+ - `success`: bool - Whether the episode was successful.
+ - `rerecord_episode`: bool - Whether to rerecord the episode.
+ """
+ ...
+
+
+# Type variable constrained to Teleoperator subclasses that also implement events
+TeleopWithEvents = TypeVar("TeleopWithEvents", bound=Teleoperator)
+
+
+def _check_teleop_with_events(teleop: Teleoperator) -> None:
+ """
+ Runtime check that a teleoperator implements the `HasTeleopEvents` protocol.
+
+ Args:
+ teleop: The teleoperator instance to check.
+
+ Raises:
+ TypeError: If the teleoperator does not have a `get_teleop_events` method.
+ """
+ if not isinstance(teleop, HasTeleopEvents):
+ raise TypeError(
+ f"Teleoperator {type(teleop).__name__} must implement get_teleop_events() method. "
+ f"Compatible teleoperators: GamepadTeleop, KeyboardEndEffectorTeleop"
+ )
+
+
+@ProcessorStepRegistry.register("add_teleop_action_as_complementary_data")
+@dataclass
+class AddTeleopActionAsComplimentaryDataStep(ComplementaryDataProcessorStep):
+ """
+ Adds the raw action from a teleoperator to the transition's complementary data.
+
+ This is useful for human-in-the-loop scenarios where the human's input needs to
+ be available to downstream processors, for example, to override a policy's action
+ during an intervention.
+
+ Attributes:
+ teleop_device: The teleoperator instance to get the action from.
+ """
+
+ teleop_device: Teleoperator
+
+ def complementary_data(self, complementary_data: dict) -> dict:
+ """
+ Retrieves the teleoperator's action and adds it to the complementary data.
+
+ Args:
+ complementary_data: The incoming complementary data dictionary.
+
+ Returns:
+ A new dictionary with the teleoperator action added under the
+ `teleop_action` key.
+ """
+ new_complementary_data = dict(complementary_data)
+ new_complementary_data[TELEOP_ACTION_KEY] = self.teleop_device.get_action()
+ return new_complementary_data
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
+
+
+@ProcessorStepRegistry.register("add_teleop_action_as_info")
+@dataclass
+class AddTeleopEventsAsInfoStep(InfoProcessorStep):
+ """
+ Adds teleoperator control events (e.g., terminate, success) to the transition's info.
+
+ This step extracts control events from teleoperators that support event-based
+ interaction, making these signals available to other parts of the system.
+
+ Attributes:
+ teleop_device: An instance of a teleoperator that implements the
+ `HasTeleopEvents` protocol.
+ """
+
+ teleop_device: TeleopWithEvents
+
+ def __post_init__(self):
+ """Validates that the provided teleoperator supports events after initialization."""
+ _check_teleop_with_events(self.teleop_device)
+
+ def info(self, info: dict) -> dict:
+ """
+ Retrieves teleoperator events and updates the info dictionary.
+
+ Args:
+ info: The incoming info dictionary.
+
+ Returns:
+ A new dictionary including the teleoperator events.
+ """
+ new_info = dict(info)
+
+ teleop_events = self.teleop_device.get_teleop_events()
+ new_info.update(teleop_events)
+ return new_info
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
+
+
+@ProcessorStepRegistry.register("image_crop_resize_processor")
+@dataclass
+class ImageCropResizeProcessorStep(ObservationProcessorStep):
+ """
+ Crops and/or resizes image observations.
+
+ This step iterates through all image keys in an observation dictionary and applies
+ the specified transformations. It handles device placement, moving tensors to the
+ CPU if necessary for operations not supported on certain accelerators like MPS.
+
+ Attributes:
+ crop_params_dict: A dictionary mapping image keys to cropping parameters
+ (top, left, height, width).
+ resize_size: A tuple (height, width) to resize all images to.
+ """
+
+ crop_params_dict: dict[str, tuple[int, int, int, int]] | None = None
+ resize_size: tuple[int, int] | None = None
+
+ def observation(self, observation: dict) -> dict:
+ """
+ Applies cropping and resizing to all images in the observation dictionary.
+
+ Args:
+ observation: The observation dictionary, potentially containing image tensors.
+
+ Returns:
+ A new observation dictionary with transformed images.
+ """
+ if self.resize_size is None and not self.crop_params_dict:
+ return observation
+
+ new_observation = dict(observation)
+
+ # Process all image keys in the observation
+ for key in observation:
+ if "image" not in key:
+ continue
+
+ image = observation[key]
+ device = image.device
+ # NOTE (maractingi): No mps kernel for crop and resize, so we need to move to cpu
+ if device.type == "mps":
+ image = image.cpu()
+ # Crop if crop params are provided for this key
+ if self.crop_params_dict is not None and key in self.crop_params_dict:
+ crop_params = self.crop_params_dict[key]
+ image = F.crop(image, *crop_params)
+ if self.resize_size is not None:
+ image = F.resize(image, self.resize_size)
+ image = image.clamp(0.0, 1.0)
+ new_observation[key] = image.to(device)
+
+ return new_observation
+
+ def get_config(self) -> dict[str, Any]:
+ """
+ Returns the configuration of the step for serialization.
+
+ Returns:
+ A dictionary with the crop parameters and resize dimensions.
+ """
+ return {
+ "crop_params_dict": self.crop_params_dict,
+ "resize_size": self.resize_size,
+ }
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """
+ Updates the image feature shapes in the policy features dictionary if resizing is applied.
+
+ Args:
+ features: The policy features dictionary.
+
+ Returns:
+ The updated policy features dictionary with new image shapes.
+ """
+ if self.resize_size is None:
+ return features
+ for key in features[PipelineFeatureType.OBSERVATION]:
+ if "image" in key:
+ nb_channel = features[PipelineFeatureType.OBSERVATION][key].shape[0]
+ features[PipelineFeatureType.OBSERVATION][key] = PolicyFeature(
+ type=features[PipelineFeatureType.OBSERVATION][key].type,
+ shape=(nb_channel, *self.resize_size),
+ )
+ return features
+
+
+@dataclass
+@ProcessorStepRegistry.register("time_limit_processor")
+class TimeLimitProcessorStep(TruncatedProcessorStep):
+ """
+ Tracks episode steps and enforces a time limit by truncating the episode.
+
+ Attributes:
+ max_episode_steps: The maximum number of steps allowed per episode.
+ current_step: The current step count for the active episode.
+ """
+
+ max_episode_steps: int
+ current_step: int = 0
+
+ def truncated(self, truncated: bool) -> bool:
+ """
+ Increments the step counter and sets the truncated flag if the time limit is reached.
+
+ Args:
+ truncated: The incoming truncated flag.
+
+ Returns:
+ True if the episode step limit is reached, otherwise the incoming value.
+ """
+ self.current_step += 1
+ if self.current_step >= self.max_episode_steps:
+ truncated = True
+ # TODO (steven): missing an else truncated = False?
+ return truncated
+
+ def get_config(self) -> dict[str, Any]:
+ """
+ Returns the configuration of the step for serialization.
+
+ Returns:
+ A dictionary containing the `max_episode_steps`.
+ """
+ return {
+ "max_episode_steps": self.max_episode_steps,
+ }
+
+ def reset(self) -> None:
+ """Resets the step counter, typically called at the start of a new episode."""
+ self.current_step = 0
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
+
+
+@dataclass
+@ProcessorStepRegistry.register("gripper_penalty_processor")
+class GripperPenaltyProcessorStep(ComplementaryDataProcessorStep):
+ """
+ Applies a penalty for inefficient gripper usage.
+
+ This step penalizes actions that attempt to close an already closed gripper or
+ open an already open one, based on position thresholds.
+
+ Attributes:
+ penalty: The negative reward value to apply.
+ max_gripper_pos: The maximum position value for the gripper, used for normalization.
+ """
+
+ penalty: float = -0.01
+ max_gripper_pos: float = 30.0
+
+ def complementary_data(self, complementary_data: dict) -> dict:
+ """
+ Calculates the gripper penalty and adds it to the complementary data.
+
+ Args:
+ complementary_data: The incoming complementary data, which should contain
+ raw joint positions.
+
+ Returns:
+ A new complementary data dictionary with the `discrete_penalty` key added.
+ """
+ action = self.transition.get(TransitionKey.ACTION)
+
+ raw_joint_positions = complementary_data.get("raw_joint_positions")
+ if raw_joint_positions is None:
+ return complementary_data
+
+ current_gripper_pos = raw_joint_positions.get(GRIPPER_KEY, None)
+ if current_gripper_pos is None:
+ return complementary_data
+
+ # Gripper action is a PolicyAction at this stage
+ gripper_action = action[-1].item()
+ gripper_action_normalized = gripper_action / self.max_gripper_pos
+
+ # Normalize gripper state and action
+ gripper_state_normalized = current_gripper_pos / self.max_gripper_pos
+
+ # Calculate penalty boolean as in original
+ gripper_penalty_bool = (gripper_state_normalized < 0.5 and gripper_action_normalized > 0.5) or (
+ gripper_state_normalized > 0.75 and gripper_action_normalized < 0.5
+ )
+
+ gripper_penalty = self.penalty * int(gripper_penalty_bool)
+
+ # Create new complementary data with penalty info
+ new_complementary_data = dict(complementary_data)
+ new_complementary_data[DISCRETE_PENALTY_KEY] = gripper_penalty
+
+ return new_complementary_data
+
+ def get_config(self) -> dict[str, Any]:
+ """
+ Returns the configuration of the step for serialization.
+
+ Returns:
+ A dictionary containing the penalty value and max gripper position.
+ """
+ return {
+ "penalty": self.penalty,
+ "max_gripper_pos": self.max_gripper_pos,
+ }
+
+ def reset(self) -> None:
+ """Resets the processor's internal state."""
+ pass
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
+
+
+@dataclass
+@ProcessorStepRegistry.register("intervention_action_processor")
+class InterventionActionProcessorStep(ProcessorStep):
+ """
+ Handles human intervention, overriding policy actions and managing episode termination.
+
+ When an intervention is detected (via teleoperator events in the `info` dict),
+ this step replaces the policy's action with the human's teleoperated action.
+ It also processes signals to terminate the episode or flag success.
+
+ Attributes:
+ use_gripper: Whether to include the gripper in the teleoperated action.
+ terminate_on_success: If True, automatically sets the `done` flag when a
+ `success` event is received.
+ """
+
+ use_gripper: bool = False
+ terminate_on_success: bool = True
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """
+ Processes the transition to handle interventions.
+
+ Args:
+ transition: The incoming environment transition.
+
+ Returns:
+ The modified transition, potentially with an overridden action, updated
+ reward, and termination status.
+ """
+ action = transition.get(TransitionKey.ACTION)
+ if not isinstance(action, PolicyAction):
+ raise ValueError(f"Action should be a PolicyAction type got {type(action)}")
+
+ # Get intervention signals from complementary data
+ info = transition.get(TransitionKey.INFO, {})
+ complementary_data = transition.get(TransitionKey.COMPLEMENTARY_DATA, {})
+ teleop_action = complementary_data.get(TELEOP_ACTION_KEY, {})
+ is_intervention = info.get(TeleopEvents.IS_INTERVENTION, False)
+ terminate_episode = info.get(TeleopEvents.TERMINATE_EPISODE, False)
+ success = info.get(TeleopEvents.SUCCESS, False)
+ rerecord_episode = info.get(TeleopEvents.RERECORD_EPISODE, False)
+
+ new_transition = transition.copy()
+
+ # Override action if intervention is active
+ if is_intervention and teleop_action is not None:
+ if isinstance(teleop_action, dict):
+ # Convert teleop_action dict to tensor format
+ action_list = [
+ teleop_action.get("delta_x", 0.0),
+ teleop_action.get("delta_y", 0.0),
+ teleop_action.get("delta_z", 0.0),
+ ]
+ if self.use_gripper:
+ action_list.append(teleop_action.get(GRIPPER_KEY, 1.0))
+ elif isinstance(teleop_action, np.ndarray):
+ action_list = teleop_action.tolist()
+ else:
+ action_list = teleop_action
+
+ teleop_action_tensor = torch.tensor(action_list, dtype=action.dtype, device=action.device)
+ new_transition[TransitionKey.ACTION] = teleop_action_tensor
+
+ # Handle episode termination
+ new_transition[TransitionKey.DONE] = bool(terminate_episode) or (
+ self.terminate_on_success and success
+ )
+ new_transition[TransitionKey.REWARD] = float(success)
+
+ # Update info with intervention metadata
+ info = new_transition.get(TransitionKey.INFO, {})
+ info[TeleopEvents.IS_INTERVENTION] = is_intervention
+ info[TeleopEvents.RERECORD_EPISODE] = rerecord_episode
+ info[TeleopEvents.SUCCESS] = success
+ new_transition[TransitionKey.INFO] = info
+
+ # Update complementary data with teleop action
+ complementary_data = new_transition.get(TransitionKey.COMPLEMENTARY_DATA, {})
+ complementary_data[TELEOP_ACTION_KEY] = new_transition.get(TransitionKey.ACTION)
+ new_transition[TransitionKey.COMPLEMENTARY_DATA] = complementary_data
+
+ return new_transition
+
+ def get_config(self) -> dict[str, Any]:
+ """
+ Returns the configuration of the step for serialization.
+
+ Returns:
+ A dictionary containing the step's configuration attributes.
+ """
+ return {
+ "use_gripper": self.use_gripper,
+ "terminate_on_success": self.terminate_on_success,
+ }
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
+
+
+@dataclass
+@ProcessorStepRegistry.register("reward_classifier_processor")
+class RewardClassifierProcessorStep(ProcessorStep):
+ """
+ Applies a pretrained reward classifier to image observations to predict success.
+
+ This step uses a model to determine if the current state is successful, updating
+ the reward and potentially terminating the episode.
+
+ Attributes:
+ pretrained_path: Path to the pretrained reward classifier model.
+ device: The device to run the classifier on.
+ success_threshold: The probability threshold to consider a prediction as successful.
+ success_reward: The reward value to assign on success.
+ terminate_on_success: If True, terminates the episode upon successful classification.
+ reward_classifier: The loaded classifier model instance.
+ """
+
+ pretrained_path: str | None = None
+ device: str = "cpu"
+ success_threshold: float = 0.5
+ success_reward: float = 1.0
+ terminate_on_success: bool = True
+
+ reward_classifier: Any = None
+
+ def __post_init__(self):
+ """Initializes the reward classifier model after the dataclass is created."""
+ if self.pretrained_path is not None:
+ from lerobot.policies.sac.reward_model.modeling_classifier import Classifier
+
+ self.reward_classifier = Classifier.from_pretrained(self.pretrained_path)
+ self.reward_classifier.to(self.device)
+ self.reward_classifier.eval()
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """
+ Processes a transition, applying the reward classifier to its image observations.
+
+ Args:
+ transition: The incoming environment transition.
+
+ Returns:
+ The modified transition with an updated reward and done flag based on the
+ classifier's prediction.
+ """
+ new_transition = transition.copy()
+ observation = new_transition.get(TransitionKey.OBSERVATION)
+ if observation is None or self.reward_classifier is None:
+ return new_transition
+
+ # Extract images from observation
+ images = {key: value for key, value in observation.items() if "image" in key}
+
+ if not images:
+ return new_transition
+
+ # Run reward classifier
+ start_time = time.perf_counter()
+ with torch.inference_mode():
+ success = self.reward_classifier.predict_reward(images, threshold=self.success_threshold)
+
+ classifier_frequency = 1 / (time.perf_counter() - start_time)
+
+ # Calculate reward and termination
+ reward = new_transition.get(TransitionKey.REWARD, 0.0)
+ terminated = new_transition.get(TransitionKey.DONE, False)
+
+ if math.isclose(success, 1, abs_tol=1e-2):
+ reward = self.success_reward
+ if self.terminate_on_success:
+ terminated = True
+
+ # Update transition
+ new_transition[TransitionKey.REWARD] = reward
+ new_transition[TransitionKey.DONE] = terminated
+
+ # Update info with classifier frequency
+ info = new_transition.get(TransitionKey.INFO, {})
+ info["reward_classifier_frequency"] = classifier_frequency
+ new_transition[TransitionKey.INFO] = info
+
+ return new_transition
+
+ def get_config(self) -> dict[str, Any]:
+ """
+ Returns the configuration of the step for serialization.
+
+ Returns:
+ A dictionary containing the step's configuration attributes.
+ """
+ return {
+ "device": self.device,
+ "success_threshold": self.success_threshold,
+ "success_reward": self.success_reward,
+ "terminate_on_success": self.terminate_on_success,
+ }
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
diff --git a/lerobot/src/lerobot/processor/migrate_policy_normalization.py b/lerobot/src/lerobot/processor/migrate_policy_normalization.py
new file mode 100644
index 0000000000000000000000000000000000000000..b45d96cca1155d60db3727c9598e4cc493c96854
--- /dev/null
+++ b/lerobot/src/lerobot/processor/migrate_policy_normalization.py
@@ -0,0 +1,769 @@
+#!/usr/bin/env python
+
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+A generic script to migrate LeRobot policies with built-in normalization layers to the new
+pipeline-based processor system.
+
+This script performs the following steps:
+1. Loads a pretrained policy model and its configuration from a local path or the
+ Hugging Face Hub.
+2. Scans the model's state dictionary to extract normalization statistics (e.g., mean,
+ std, min, max) for all features.
+3. Creates two new processor pipelines:
+ - A preprocessor that normalizes inputs (observations) and outputs (actions).
+ - A postprocessor that unnormalizes outputs (actions) for inference.
+4. Removes the original normalization layers from the model's state dictionary,
+ creating a "clean" model.
+5. Saves the new clean model, the preprocessor, the postprocessor, and a generated
+ model card to a new directory.
+6. Optionally pushes all the new artifacts to the Hugging Face Hub.
+
+Usage:
+ python src/lerobot/processor/migrate_policy_normalization.py \
+ --pretrained-path lerobot/act_aloha_sim_transfer_cube_human \
+ --push-to-hub \
+ --branch main
+
+Note: This script now uses the modern `make_pre_post_processors` and `make_policy_config`
+factory functions from `lerobot.policies.factory` to create processors and configurations,
+ensuring consistency with the current codebase.
+
+The script extracts normalization statistics from the old model's state_dict, creates clean
+processor pipelines using the factory functions, and saves a migrated model that is compatible
+with the new PolicyProcessorPipeline architecture.
+"""
+
+import argparse
+import json
+import os
+from pathlib import Path
+from typing import Any
+
+import torch
+from huggingface_hub import HfApi, hf_hub_download
+from safetensors.torch import load_file as load_safetensors
+
+from lerobot.configs.types import FeatureType, NormalizationMode, PolicyFeature
+from lerobot.policies.factory import get_policy_class, make_policy_config, make_pre_post_processors
+from lerobot.utils.constants import ACTION
+
+
+def extract_normalization_stats(state_dict: dict[str, torch.Tensor]) -> dict[str, dict[str, torch.Tensor]]:
+ """
+ Scans a model's state_dict to find and extract normalization statistics.
+
+ This function identifies keys corresponding to normalization layers (e.g., those
+ for mean, std, min, max) based on a set of predefined patterns and organizes
+ them into a nested dictionary.
+
+ Args:
+ state_dict: The state dictionary of a pretrained policy model.
+
+ Returns:
+ A nested dictionary where outer keys are feature names (e.g.,
+ 'observation.state') and inner keys are statistic types ('mean', 'std'),
+ mapping to their corresponding tensor values.
+ """
+ stats = {}
+
+ # Define patterns to match and their prefixes to remove
+ normalization_patterns = [
+ "normalize_inputs.buffer_",
+ "unnormalize_outputs.buffer_",
+ "normalize_targets.buffer_",
+ "normalize.", # Must come after normalize_* patterns
+ "unnormalize.", # Must come after unnormalize_* patterns
+ "input_normalizer.",
+ "output_normalizer.",
+ "normalalize_inputs.",
+ "unnormalize_outputs.",
+ "normalize_targets.",
+ "unnormalize_targets.",
+ ]
+
+ # Process each key in state_dict
+ for key, tensor in state_dict.items():
+ # Try each pattern
+ for pattern in normalization_patterns:
+ if key.startswith(pattern):
+ # Extract the remaining part after the pattern
+ remaining = key[len(pattern) :]
+ parts = remaining.split(".")
+
+ # Need at least feature name and stat type
+ if len(parts) >= 2:
+ # Last part is the stat type (mean, std, min, max, etc.)
+ stat_type = parts[-1]
+ # Everything else is the feature name
+ feature_name = ".".join(parts[:-1]).replace("_", ".")
+
+ # Add to stats
+ if feature_name not in stats:
+ stats[feature_name] = {}
+ stats[feature_name][stat_type] = tensor.clone()
+
+ # Only process the first matching pattern
+ break
+
+ return stats
+
+
+def detect_features_and_norm_modes(
+ config: dict[str, Any], stats: dict[str, dict[str, torch.Tensor]]
+) -> tuple[dict[str, PolicyFeature], dict[FeatureType, NormalizationMode]]:
+ """
+ Infers policy features and normalization modes from the model config and stats.
+
+ This function first attempts to find feature definitions and normalization
+ mappings directly from the policy's configuration file. If this information is
+ not present, it infers it from the extracted normalization statistics, using
+ tensor shapes to determine feature shapes and the presence of specific stat
+ keys (e.g., 'mean'/'std' vs 'min'/'max') to determine the normalization mode.
+ It applies sensible defaults if inference is not possible.
+
+ Args:
+ config: The policy's configuration dictionary from `config.json`.
+ stats: The normalization statistics extracted from the model's state_dict.
+
+ Returns:
+ A tuple containing:
+ - A dictionary mapping feature names to `PolicyFeature` objects.
+ - A dictionary mapping `FeatureType` enums to `NormalizationMode` enums.
+ """
+ features = {}
+ norm_modes = {}
+
+ # First, check if there's a normalization_mapping in the config
+ if "normalization_mapping" in config:
+ print(f"Found normalization_mapping in config: {config['normalization_mapping']}")
+ # Extract normalization modes from config
+ for feature_type_str, mode_str in config["normalization_mapping"].items():
+ # Convert string to FeatureType enum
+ try:
+ if feature_type_str == "VISUAL":
+ feature_type = FeatureType.VISUAL
+ elif feature_type_str == "STATE":
+ feature_type = FeatureType.STATE
+ elif feature_type_str == "ACTION":
+ feature_type = FeatureType.ACTION
+ else:
+ print(f"Warning: Unknown feature type '{feature_type_str}', skipping")
+ continue
+ except (AttributeError, ValueError):
+ print(f"Warning: Could not parse feature type '{feature_type_str}', skipping")
+ continue
+
+ # Convert string to NormalizationMode enum
+ try:
+ if mode_str == "MEAN_STD":
+ mode = NormalizationMode.MEAN_STD
+ elif mode_str == "MIN_MAX":
+ mode = NormalizationMode.MIN_MAX
+ elif mode_str == "IDENTITY":
+ mode = NormalizationMode.IDENTITY
+ else:
+ print(
+ f"Warning: Unknown normalization mode '{mode_str}' for feature type '{feature_type_str}'"
+ )
+ continue
+ except (AttributeError, ValueError):
+ print(f"Warning: Could not parse normalization mode '{mode_str}', skipping")
+ continue
+
+ norm_modes[feature_type] = mode
+
+ # Try to extract from config
+ if "features" in config:
+ for key, feature_config in config["features"].items():
+ shape = feature_config.get("shape", feature_config.get("dim"))
+ shape = (shape,) if isinstance(shape, int) else tuple(shape)
+
+ # Determine feature type
+ if "image" in key or "visual" in key:
+ feature_type = FeatureType.VISUAL
+ elif "state" in key:
+ feature_type = FeatureType.STATE
+ elif ACTION in key:
+ feature_type = FeatureType.ACTION
+ else:
+ feature_type = FeatureType.STATE # Default
+
+ features[key] = PolicyFeature(feature_type, shape)
+
+ # If no features in config, infer from stats
+ if not features:
+ for key, stat_dict in stats.items():
+ # Get shape from any stat tensor
+ tensor = next(iter(stat_dict.values()))
+ shape = tuple(tensor.shape)
+
+ # Determine feature type based on key
+ if "image" in key or "visual" in key or "pixels" in key:
+ feature_type = FeatureType.VISUAL
+ elif "state" in key or "joint" in key or "position" in key:
+ feature_type = FeatureType.STATE
+ elif ACTION in key:
+ feature_type = FeatureType.ACTION
+ else:
+ feature_type = FeatureType.STATE
+
+ features[key] = PolicyFeature(feature_type, shape)
+
+ # If normalization modes weren't in config, determine based on available stats
+ if not norm_modes:
+ for key, stat_dict in stats.items():
+ if key in features:
+ if "mean" in stat_dict and "std" in stat_dict:
+ feature_type = features[key].type
+ if feature_type not in norm_modes:
+ norm_modes[feature_type] = NormalizationMode.MEAN_STD
+ elif "min" in stat_dict and "max" in stat_dict:
+ feature_type = features[key].type
+ if feature_type not in norm_modes:
+ norm_modes[feature_type] = NormalizationMode.MIN_MAX
+
+ # Default normalization modes if not detected
+ if FeatureType.VISUAL not in norm_modes:
+ norm_modes[FeatureType.VISUAL] = NormalizationMode.MEAN_STD
+ if FeatureType.STATE not in norm_modes:
+ norm_modes[FeatureType.STATE] = NormalizationMode.MIN_MAX
+ if FeatureType.ACTION not in norm_modes:
+ norm_modes[FeatureType.ACTION] = NormalizationMode.MEAN_STD
+
+ return features, norm_modes
+
+
+def remove_normalization_layers(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
+ """
+ Creates a new state_dict with all normalization-related layers removed.
+
+ This function filters the original state dictionary, excluding any keys that
+ match a set of predefined patterns associated with normalization modules.
+
+ Args:
+ state_dict: The original model state dictionary.
+
+ Returns:
+ A new state dictionary containing only the core model weights, without
+ any normalization parameters.
+ """
+ new_state_dict = {}
+
+ # Patterns to remove
+ remove_patterns = [
+ "normalize_inputs.",
+ "unnormalize_outputs.",
+ "normalize_targets.", # Added pattern for target normalization
+ "normalize.",
+ "unnormalize.",
+ "input_normalizer.",
+ "output_normalizer.",
+ "normalizer.",
+ ]
+
+ for key, tensor in state_dict.items():
+ should_remove = any(pattern in key for pattern in remove_patterns)
+ if not should_remove:
+ new_state_dict[key] = tensor
+
+ return new_state_dict
+
+
+def clean_state_dict(
+ state_dict: dict[str, torch.Tensor], remove_str: str = "._orig_mod"
+) -> dict[str, torch.Tensor]:
+ """
+ Remove a substring (e.g. '._orig_mod') from all keys in a state dict.
+
+ Args:
+ state_dict (dict): The original state dict.
+ remove_str (str): The substring to remove from the keys.
+
+ Returns:
+ dict: A new state dict with cleaned keys.
+ """
+ new_state_dict = {}
+ for k, v in state_dict.items():
+ new_k = k.replace(remove_str, "")
+ new_state_dict[new_k] = v
+ return new_state_dict
+
+
+def load_state_dict_with_missing_key_handling(
+ policy: torch.nn.Module,
+ state_dict: dict[str, torch.Tensor],
+ policy_type: str,
+ known_missing_keys_whitelist: dict[str, list[str]],
+) -> list[str]:
+ """
+ Load state dict into policy with graceful handling of missing keys.
+
+ This function loads the state dict with strict=False, filters out whitelisted
+ missing keys, and provides detailed reporting about any issues found.
+
+ Args:
+ policy: The policy model to load the state dict into.
+ state_dict: The cleaned state dictionary to load.
+ policy_type: The type of policy (used for whitelist lookup).
+ known_missing_keys_whitelist: Dictionary mapping policy types to lists of
+ known acceptable missing keys.
+
+ Returns:
+ List of problematic missing keys that weren't in the whitelist.
+ """
+ # Load the cleaned state dict with strict=False to capture missing/unexpected keys
+ load_result = policy.load_state_dict(state_dict, strict=False)
+
+ # Check for missing keys
+ missing_keys = load_result.missing_keys
+ unexpected_keys = load_result.unexpected_keys
+
+ # Filter out whitelisted missing keys
+ policy_type_lower = policy_type.lower()
+ whitelisted_keys = known_missing_keys_whitelist.get(policy_type_lower, [])
+ problematic_missing_keys = [key for key in missing_keys if key not in whitelisted_keys]
+
+ if missing_keys:
+ if problematic_missing_keys:
+ print(f"WARNING: Found {len(problematic_missing_keys)} unexpected missing keys:")
+ for key in problematic_missing_keys:
+ print(f" - {key}")
+
+ if len(missing_keys) > len(problematic_missing_keys):
+ whitelisted_missing = [key for key in missing_keys if key in whitelisted_keys]
+ print(f"INFO: Found {len(whitelisted_missing)} expected missing keys (whitelisted):")
+ for key in whitelisted_missing:
+ print(f" - {key}")
+
+ if unexpected_keys:
+ print(f"WARNING: Found {len(unexpected_keys)} unexpected keys:")
+ for key in unexpected_keys:
+ print(f" - {key}")
+
+ if not missing_keys and not unexpected_keys:
+ print("Successfully loaded cleaned state dict into policy model (all keys matched)")
+ else:
+ print("State dict loaded with some missing/unexpected keys (see details above)")
+
+ return problematic_missing_keys
+
+
+def convert_features_to_policy_features(features_dict: dict[str, dict]) -> dict[str, PolicyFeature]:
+ """
+ Converts a feature dictionary from the old config format to the new `PolicyFeature` format.
+
+ Args:
+ features_dict: The feature dictionary in the old format, where values are
+ simple dictionaries (e.g., `{"shape": [7]}`).
+
+ Returns:
+ A dictionary mapping feature names to `PolicyFeature` dataclass objects.
+ """
+ converted_features = {}
+
+ for key, feature_dict in features_dict.items():
+ # Determine feature type based on key
+ if "image" in key or "visual" in key:
+ feature_type = FeatureType.VISUAL
+ elif "state" in key:
+ feature_type = FeatureType.STATE
+ elif ACTION in key:
+ feature_type = FeatureType.ACTION
+ else:
+ feature_type = FeatureType.STATE
+
+ # Get shape from feature dict
+ shape = feature_dict.get("shape", feature_dict.get("dim"))
+ shape = (shape,) if isinstance(shape, int) else tuple(shape) if shape is not None else ()
+
+ converted_features[key] = PolicyFeature(feature_type, shape)
+
+ return converted_features
+
+
+def display_migration_summary_with_warnings(problematic_missing_keys: list[str]) -> None:
+ """
+ Display final migration summary with warnings about problematic missing keys.
+
+ Args:
+ problematic_missing_keys: List of missing keys that weren't in the whitelist.
+ """
+ if not problematic_missing_keys:
+ return
+
+ print("\n" + "=" * 60)
+ print("IMPORTANT: MIGRATION COMPLETED WITH WARNINGS")
+ print("=" * 60)
+ print(
+ f"The migration was successful, but {len(problematic_missing_keys)} unexpected missing keys were found:"
+ )
+ print()
+ for key in problematic_missing_keys:
+ print(f" - {key}")
+ print()
+ print("These missing keys may indicate:")
+ print(" β’ The model architecture has changed")
+ print(" β’ Some components were not properly saved in the original model")
+ print(" β’ The migration script needs to be updated for this policy type")
+ print()
+ print("What to do next:")
+ print(" 1. Test your migrated model carefully to ensure it works as expected")
+ print(" 2. If you encounter issues, please open an issue at:")
+ print(" https://github.com/huggingface/lerobot/issues")
+ print(" 3. Include this migration log and the missing keys listed above")
+ print()
+ print("If the model works correctly despite these warnings, the missing keys")
+ print("might be expected for your policy type and can be added to the whitelist.")
+ print("=" * 60)
+
+
+def load_model_from_hub(
+ repo_id: str, revision: str | None = None
+) -> tuple[dict[str, torch.Tensor], dict[str, Any], dict[str, Any] | None]:
+ """
+ Downloads and loads a model's state_dict and configs from the Hugging Face Hub.
+
+ Args:
+ repo_id: The repository ID on the Hub (e.g., 'lerobot/aloha').
+ revision: The specific git revision (branch, tag, or commit hash) to use.
+
+ Returns:
+ A tuple containing the model's state dictionary, the policy configuration,
+ and the training configuration (None if train_config.json is not found).
+ """
+ # Download files.
+ safetensors_path = hf_hub_download(repo_id=repo_id, filename="model.safetensors", revision=revision)
+
+ config_path = hf_hub_download(repo_id=repo_id, filename="config.json", revision=revision)
+
+ # Load state_dict
+ state_dict = load_safetensors(safetensors_path)
+
+ # Load config
+ with open(config_path) as f:
+ config = json.load(f)
+
+ # Try to load train_config (optional)
+ train_config = None
+ try:
+ train_config_path = hf_hub_download(repo_id=repo_id, filename="train_config.json", revision=revision)
+ with open(train_config_path) as f:
+ train_config = json.load(f)
+ except FileNotFoundError:
+ print("train_config.json not found - continuing without training configuration")
+
+ return state_dict, config, train_config
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Migrate policy models with normalization layers to new pipeline system"
+ )
+ parser.add_argument(
+ "--pretrained-path",
+ type=str,
+ required=True,
+ help="Path to pretrained model (hub repo or local directory)",
+ )
+ parser.add_argument(
+ "--output-dir",
+ type=str,
+ default=None,
+ help="Output directory for migrated model (default: same as pretrained-path)",
+ )
+ parser.add_argument("--push-to-hub", action="store_true", help="Push migrated model to hub")
+ parser.add_argument(
+ "--hub-repo-id",
+ type=str,
+ default=None,
+ help="Hub repository ID for pushing (default: same as pretrained-path)",
+ )
+ parser.add_argument("--revision", type=str, default=None, help="Revision of the model to load")
+ parser.add_argument("--private", action="store_true", help="Make the hub repository private")
+ parser.add_argument(
+ "--branch",
+ type=str,
+ default=None,
+ help="Git branch to use when pushing to hub. If specified, a PR will be created automatically (default: push directly to main)",
+ )
+
+ args = parser.parse_args()
+
+ # Load model and config
+ print(f"Loading model from {args.pretrained_path}...")
+ if os.path.isdir(args.pretrained_path):
+ # Local directory
+ state_dict = load_safetensors(os.path.join(args.pretrained_path, "model.safetensors"))
+ with open(os.path.join(args.pretrained_path, "config.json")) as f:
+ config = json.load(f)
+
+ # Try to load train_config (optional)
+ train_config = None
+ train_config_path = os.path.join(args.pretrained_path, "train_config.json")
+ if os.path.exists(train_config_path):
+ with open(train_config_path) as f:
+ train_config = json.load(f)
+ else:
+ print("train_config.json not found - continuing without training configuration")
+ else:
+ # Hub repository
+ state_dict, config, train_config = load_model_from_hub(args.pretrained_path, args.revision)
+
+ # Extract normalization statistics
+ print("Extracting normalization statistics...")
+ stats = extract_normalization_stats(state_dict)
+
+ print(f"Found normalization statistics for: {list(stats.keys())}")
+
+ # Detect input features and normalization modes
+ print("Detecting features and normalization modes...")
+ features, norm_map = detect_features_and_norm_modes(config, stats)
+
+ print(f"Detected features: {list(features.keys())}")
+ print(f"Normalization modes: {norm_map}")
+
+ # Remove normalization layers from state_dict
+ print("Removing normalization layers from model...")
+ new_state_dict = remove_normalization_layers(state_dict)
+ new_state_dict = clean_state_dict(new_state_dict, remove_str="._orig_mod")
+
+ removed_keys = set(state_dict.keys()) - set(new_state_dict.keys())
+ if removed_keys:
+ print(f"Removed {len(removed_keys)} normalization layer keys")
+
+ # Determine output path
+ if args.output_dir:
+ output_dir = Path(args.output_dir)
+ else:
+ if os.path.isdir(args.pretrained_path):
+ output_dir = Path(args.pretrained_path).parent / f"{Path(args.pretrained_path).name}_migrated"
+ else:
+ output_dir = Path(f"./{args.pretrained_path.replace('/', '_')}_migrated")
+
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ # Extract policy type from config
+ if "type" not in config:
+ raise ValueError("Policy type not found in config.json. The config must contain a 'type' field.")
+
+ policy_type = config["type"]
+ print(f"Detected policy type: {policy_type}")
+
+ # Clean up config - remove fields that shouldn't be passed to config constructor
+ cleaned_config = dict(config)
+
+ # Remove fields that are not part of the config class constructors
+ fields_to_remove = ["normalization_mapping", "type"]
+ for field in fields_to_remove:
+ if field in cleaned_config:
+ print(f"Removing '{field}' field from config")
+ del cleaned_config[field]
+
+ # Convert input_features and output_features to PolicyFeature objects if they exist
+ if "input_features" in cleaned_config:
+ cleaned_config["input_features"] = convert_features_to_policy_features(
+ cleaned_config["input_features"]
+ )
+ if "output_features" in cleaned_config:
+ cleaned_config["output_features"] = convert_features_to_policy_features(
+ cleaned_config["output_features"]
+ )
+
+ # Add normalization mapping to config
+ cleaned_config["normalization_mapping"] = norm_map
+
+ # Create policy configuration using the factory
+ print(f"Creating {policy_type} policy configuration...")
+ policy_config = make_policy_config(policy_type, **cleaned_config)
+
+ # Create policy instance using the factory
+ print(f"Instantiating {policy_type} policy...")
+ policy_class = get_policy_class(policy_type)
+ policy = policy_class(policy_config)
+
+ # Define whitelist of known missing keys that are acceptable (for example weight tie) for certain policy types
+ known_missing_keys_whitelist = {
+ "pi0": ["model.paligemma_with_expert.paligemma.model.language_model.embed_tokens.weight"],
+ # Add other policy types and their known missing keys here as needed
+ }
+
+ # Load state dict with graceful missing key handling
+ problematic_missing_keys = load_state_dict_with_missing_key_handling(
+ policy=policy,
+ state_dict=new_state_dict,
+ policy_type=policy_type,
+ known_missing_keys_whitelist=known_missing_keys_whitelist,
+ )
+ policy.to(torch.float32)
+ # Create preprocessor and postprocessor using the factory
+ print("Creating preprocessor and postprocessor using make_pre_post_processors...")
+ preprocessor, postprocessor = make_pre_post_processors(policy_cfg=policy_config, dataset_stats=stats)
+
+ # Determine hub repo ID if pushing to hub
+ hub_repo_id = None
+ if args.push_to_hub:
+ if args.hub_repo_id:
+ hub_repo_id = args.hub_repo_id
+ else:
+ if not os.path.isdir(args.pretrained_path):
+ # Use same repo with "_migrated" suffix
+ hub_repo_id = f"{args.pretrained_path}_migrated"
+ else:
+ raise ValueError("--hub-repo-id must be specified when pushing local model to hub")
+
+ # Save all components to local directory first
+ print(f"Saving preprocessor to {output_dir}...")
+ preprocessor.save_pretrained(output_dir)
+
+ print(f"Saving postprocessor to {output_dir}...")
+ postprocessor.save_pretrained(output_dir)
+
+ print(f"Saving model to {output_dir}...")
+ policy.save_pretrained(output_dir)
+
+ # Generate and save model card
+ print("Generating model card...")
+ # Get metadata from original config
+ dataset_repo_id = "unknown"
+ if train_config is not None:
+ dataset_repo_id = train_config.get("repo_id", "unknown")
+ license = config.get("license", "apache-2.0")
+
+ tags = config.get("tags", ["robotics", "lerobot", policy_type]) or ["robotics", "lerobot", policy_type]
+ tags = set(tags).union({"robotics", "lerobot", policy_type})
+ tags = list(tags)
+
+ # Generate model card
+ card = policy.generate_model_card(
+ dataset_repo_id=dataset_repo_id, model_type=policy_type, license=license, tags=tags
+ )
+
+ # Save model card locally
+ card.save(str(output_dir / "README.md"))
+ print(f"Model card saved to {output_dir / 'README.md'}")
+ # Push all files to hub in a single operation if requested
+ if args.push_to_hub and hub_repo_id:
+ api = HfApi()
+
+ # Determine if we should create a PR (automatically if branch is specified)
+ create_pr = args.branch is not None
+ target_location = f"branch '{args.branch}'" if args.branch else "main branch"
+
+ print(f"Pushing all migrated files to {hub_repo_id} on {target_location}...")
+
+ # Upload all files in a single commit with automatic PR creation if branch specified
+ commit_message = "Migrate policy to PolicyProcessorPipeline system"
+ commit_description = None
+
+ if create_pr:
+ # Separate commit description for PR body
+ commit_description = """**Automated Policy Migration to PolicyProcessorPipeline**
+
+This PR migrates your model to the new LeRobot policy format using the modern PolicyProcessorPipeline architecture.
+
+## What Changed
+
+### **New Architecture - PolicyProcessorPipeline**
+Your model now uses external PolicyProcessorPipeline components for data processing instead of built-in normalization layers. This provides:
+- **Modularity**: Separate preprocessing and postprocessing pipelines
+- **Flexibility**: Easy to swap, configure, and debug processing steps
+- **Compatibility**: Works with the latest LeRobot ecosystem
+
+### **Normalization Extraction**
+We've extracted normalization statistics from your model's state_dict and removed the built-in normalization layers:
+- **Extracted patterns**: `normalize_inputs.*`, `unnormalize_outputs.*`, `normalize.*`, `unnormalize.*`, `input_normalizer.*`, `output_normalizer.*`
+- **Statistics preserved**: Mean, std, min, max values for all features
+- **Clean model**: State dict now contains only core model weights
+
+### **Files Added**
+- **preprocessor_config.json**: Configuration for input preprocessing pipeline
+- **postprocessor_config.json**: Configuration for output postprocessing pipeline
+- **model.safetensors**: Clean model weights without normalization layers
+- **config.json**: Updated model configuration
+- **train_config.json**: Training configuration
+- **README.md**: Updated model card with migration information
+
+### **Benefits**
+- **Backward Compatible**: Your model behavior remains identical
+- **Future Ready**: Compatible with latest LeRobot features and updates
+- **Debuggable**: Easy to inspect and modify processing steps
+- **Portable**: Processors can be shared and reused across models
+
+### **Usage**
+```python
+# Load your migrated model
+from lerobot.policies import get_policy_class
+from lerobot.processor import PolicyProcessorPipeline
+
+# The preprocessor and postprocessor are now external
+preprocessor = PolicyProcessorPipeline.from_pretrained("your-model-repo", config_filename="preprocessor_config.json")
+postprocessor = PolicyProcessorPipeline.from_pretrained("your-model-repo", config_filename="postprocessor_config.json")
+policy = get_policy_class("your-policy-type").from_pretrained("your-model-repo")
+
+# Process data through the pipeline
+processed_batch = preprocessor(raw_batch)
+action = policy(processed_batch)
+final_action = postprocessor(action)
+```
+
+*Generated automatically by the LeRobot policy migration script*"""
+
+ upload_kwargs = {
+ "repo_id": hub_repo_id,
+ "folder_path": output_dir,
+ "repo_type": "model",
+ "commit_message": commit_message,
+ "revision": args.branch,
+ "create_pr": create_pr,
+ "allow_patterns": ["*.json", "*.safetensors", "*.md"],
+ "ignore_patterns": ["*.tmp", "*.log"],
+ }
+
+ # Add commit_description for PR body if creating PR
+ if create_pr and commit_description:
+ upload_kwargs["commit_description"] = commit_description
+
+ api.upload_folder(**upload_kwargs)
+
+ if create_pr:
+ print("All files pushed and pull request created successfully!")
+ else:
+ print("All files pushed to main branch successfully!")
+
+ print("\nMigration complete!")
+ print(f"Migrated model saved to: {output_dir}")
+ if args.push_to_hub and hub_repo_id:
+ if args.branch:
+ print(
+ f"Successfully pushed all files to branch '{args.branch}' and created PR on https://huggingface.co/{hub_repo_id}"
+ )
+ else:
+ print(f"Successfully pushed to https://huggingface.co/{hub_repo_id}")
+ if args.branch:
+ print(f"\nView the branch at: https://huggingface.co/{hub_repo_id}/tree/{args.branch}")
+ print(
+ f"View the PR at: https://huggingface.co/{hub_repo_id}/discussions (look for the most recent PR)"
+ )
+ else:
+ print(f"\nView the changes at: https://huggingface.co/{hub_repo_id}")
+
+ # Display final summary about any problematic missing keys
+ display_migration_summary_with_warnings(problematic_missing_keys)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/lerobot/src/lerobot/processor/normalize_processor.py b/lerobot/src/lerobot/processor/normalize_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..309f8c95463f618a991ede40e13d32f56de37d1b
--- /dev/null
+++ b/lerobot/src/lerobot/processor/normalize_processor.py
@@ -0,0 +1,560 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+from copy import deepcopy
+from dataclasses import dataclass, field
+from typing import Any
+
+import torch
+from torch import Tensor
+
+from lerobot.configs.types import FeatureType, NormalizationMode, PipelineFeatureType, PolicyFeature
+from lerobot.datasets.lerobot_dataset import LeRobotDataset
+from lerobot.utils.constants import ACTION
+
+from .converters import from_tensor_to_numpy, to_tensor
+from .core import EnvTransition, PolicyAction, TransitionKey
+from .pipeline import PolicyProcessorPipeline, ProcessorStep, ProcessorStepRegistry, RobotObservation
+
+
+@dataclass
+class _NormalizationMixin:
+ """
+ A mixin class providing core functionality for normalization and unnormalization.
+
+ This class manages normalization statistics (`stats`), converts them to tensors for
+ efficient computation, handles device placement, and implements the logic for
+ applying normalization transformations (mean/std and min/max). It is designed to
+ be inherited by concrete `ProcessorStep` implementations and should not be used
+ directly.
+
+ **Stats Override Preservation:**
+ When stats are explicitly provided during construction (e.g., via overrides in
+ `DataProcessorPipeline.from_pretrained()`), they are preserved even when
+ `load_state_dict()` is called. This allows users to override normalization
+ statistics from saved models while keeping the rest of the model state intact.
+
+ Examples:
+ ```python
+ # Common use case: Override with dataset stats
+ from lerobot.datasets import LeRobotDataset
+
+ dataset = LeRobotDataset("my_dataset")
+ pipeline = DataProcessorPipeline.from_pretrained(
+ "model_path", overrides={"normalizer_processor": {"stats": dataset.meta.stats}}
+ )
+ # dataset.meta.stats will be used, not the stats from the saved model
+
+ # Custom stats override
+ custom_stats = {"action": {"mean": [0.0], "std": [1.0]}}
+ pipeline = DataProcessorPipeline.from_pretrained(
+ "model_path", overrides={"normalizer_processor": {"stats": custom_stats}}
+ )
+ ```
+
+ Attributes:
+ features: A dictionary mapping feature names to `PolicyFeature` objects, defining
+ the data structure to be processed.
+ norm_map: A dictionary mapping `FeatureType` to `NormalizationMode`, specifying
+ which normalization method to use for each type of feature.
+ stats: A dictionary containing the normalization statistics (e.g., mean, std,
+ min, max) for each feature.
+ device: The PyTorch device on which to store and perform tensor operations.
+ eps: A small epsilon value to prevent division by zero in normalization
+ calculations.
+ normalize_observation_keys: An optional set of keys to selectively apply
+ normalization to specific observation features.
+ _tensor_stats: An internal dictionary holding the normalization statistics as
+ PyTorch tensors.
+ _stats_explicitly_provided: Internal flag tracking whether stats were explicitly
+ provided during construction (used for override preservation).
+ """
+
+ features: dict[str, PolicyFeature]
+ norm_map: dict[FeatureType, NormalizationMode]
+ stats: dict[str, dict[str, Any]] | None = None
+ device: torch.device | str | None = None
+ dtype: torch.dtype | None = None
+ eps: float = 1e-8
+ normalize_observation_keys: set[str] | None = None
+
+ _tensor_stats: dict[str, dict[str, Tensor]] = field(default_factory=dict, init=False, repr=False)
+ _stats_explicitly_provided: bool = field(default=False, init=False, repr=False)
+
+ def __post_init__(self):
+ """
+ Initializes the mixin after dataclass construction.
+
+ This method handles the robust deserialization of `features` and `norm_map`
+ from JSON-compatible formats (where enums become strings and tuples become
+ lists) and converts the provided `stats` dictionary into a dictionary of
+ tensors (`_tensor_stats`) on the specified device.
+ """
+ # Track if stats were explicitly provided (not None and not empty)
+ self._stats_explicitly_provided = self.stats is not None and bool(self.stats)
+ # Robust JSON deserialization handling (guard empty maps).
+ if self.features:
+ first_val = next(iter(self.features.values()))
+ if isinstance(first_val, dict):
+ reconstructed = {}
+ for key, ft_dict in self.features.items():
+ reconstructed[key] = PolicyFeature(
+ type=FeatureType(ft_dict["type"]), shape=tuple(ft_dict["shape"])
+ )
+ self.features = reconstructed
+
+ # if keys are strings (JSON), rebuild enum map
+ if self.norm_map and all(isinstance(k, str) for k in self.norm_map):
+ reconstructed = {}
+ for ft_type_str, norm_mode_str in self.norm_map.items():
+ reconstructed[FeatureType(ft_type_str)] = NormalizationMode(norm_mode_str)
+ self.norm_map = reconstructed
+
+ # Convert stats to tensors and move to the target device once during initialization.
+ self.stats = self.stats or {}
+ if self.dtype is None:
+ self.dtype = torch.float32
+ self._tensor_stats = to_tensor(self.stats, device=self.device, dtype=self.dtype)
+
+ def to(
+ self, device: torch.device | str | None = None, dtype: torch.dtype | None = None
+ ) -> _NormalizationMixin:
+ """
+ Moves the processor's normalization stats to the specified device.
+
+ Args:
+ device: The target PyTorch device.
+
+ Returns:
+ The instance of the class, allowing for method chaining.
+ """
+ if device is not None:
+ self.device = device
+ if dtype is not None:
+ self.dtype = dtype
+ self._tensor_stats = to_tensor(self.stats, device=self.device, dtype=self.dtype)
+ return self
+
+ def state_dict(self) -> dict[str, Tensor]:
+ """
+ Returns the normalization statistics as a flat state dictionary.
+
+ All tensors are moved to the CPU before being returned, which is standard practice
+ for saving state dictionaries.
+
+ Returns:
+ A flat dictionary mapping from `'feature_name.stat_name'` to the
+ corresponding statistics tensor on the CPU.
+ """
+ flat: dict[str, Tensor] = {}
+ for key, sub in self._tensor_stats.items():
+ for stat_name, tensor in sub.items():
+ flat[f"{key}.{stat_name}"] = tensor.cpu() # Always save to CPU
+ return flat
+
+ def load_state_dict(self, state: dict[str, Tensor]) -> None:
+ """
+ Loads normalization statistics from a state dictionary.
+
+ The loaded tensors are moved to the processor's configured device.
+
+ **Stats Override Preservation:**
+ If stats were explicitly provided during construction (e.g., via overrides in
+ `DataProcessorPipeline.from_pretrained()`), they are preserved and the state
+ dictionary is ignored. This allows users to override normalization statistics
+ while still loading the rest of the model state.
+
+ This behavior is crucial for scenarios where users want to adapt a pretrained
+ model to a new dataset with different statistics without retraining the entire
+ model.
+
+ Args:
+ state: A flat state dictionary with keys in the format
+ `'feature_name.stat_name'`.
+
+ Note:
+ When stats are preserved due to explicit provision, only the tensor
+ representation is updated to ensure consistency with the current device
+ and dtype settings.
+ """
+ # If stats were explicitly provided during construction, preserve them
+ if self._stats_explicitly_provided and self.stats is not None:
+ # Don't load from state_dict, keep the explicitly provided stats
+ # But ensure _tensor_stats is properly initialized
+ self._tensor_stats = to_tensor(self.stats, device=self.device, dtype=self.dtype) # type: ignore[assignment]
+ return
+
+ # Normal behavior: load stats from state_dict
+ self._tensor_stats.clear()
+ for flat_key, tensor in state.items():
+ key, stat_name = flat_key.rsplit(".", 1)
+ # Load to the processor's configured device.
+ self._tensor_stats.setdefault(key, {})[stat_name] = tensor.to(
+ dtype=torch.float32, device=self.device
+ )
+
+ # Reconstruct the original stats dict from tensor stats for compatibility with to() method
+ # and other functions that rely on self.stats
+ self.stats = {}
+ for key, tensor_dict in self._tensor_stats.items():
+ self.stats[key] = {}
+ for stat_name, tensor in tensor_dict.items():
+ # Convert tensor back to python/numpy format
+ self.stats[key][stat_name] = from_tensor_to_numpy(tensor)
+
+ def get_config(self) -> dict[str, Any]:
+ """
+ Returns a serializable dictionary of the processor's configuration.
+
+ This method is used when saving the processor to disk, ensuring that its
+ configuration can be reconstructed later.
+
+ Returns:
+ A JSON-serializable dictionary containing the configuration.
+ """
+ config = {
+ "eps": self.eps,
+ "features": {
+ key: {"type": ft.type.value, "shape": ft.shape} for key, ft in self.features.items()
+ },
+ "norm_map": {ft_type.value: norm_mode.value for ft_type, norm_mode in self.norm_map.items()},
+ }
+ if self.normalize_observation_keys is not None:
+ config["normalize_observation_keys"] = sorted(self.normalize_observation_keys)
+ return config
+
+ def _normalize_observation(self, observation: RobotObservation, inverse: bool) -> dict[str, Tensor]:
+ """
+ Applies (un)normalization to all relevant features in an observation dictionary.
+
+ Args:
+ observation: The observation dictionary to process.
+ inverse: If `True`, applies unnormalization; otherwise, applies normalization.
+
+ Returns:
+ A new observation dictionary with the transformed tensor values.
+ """
+ new_observation = dict(observation)
+ for key, feature in self.features.items():
+ if self.normalize_observation_keys is not None and key not in self.normalize_observation_keys:
+ continue
+ if feature.type != FeatureType.ACTION and key in new_observation:
+ # Convert to tensor but preserve original dtype for adaptation logic
+ tensor = torch.as_tensor(new_observation[key])
+ new_observation[key] = self._apply_transform(tensor, key, feature.type, inverse=inverse)
+ return new_observation
+
+ def _normalize_action(self, action: Tensor, inverse: bool) -> Tensor:
+ # Convert to tensor but preserve original dtype for adaptation logic
+ """
+ Applies (un)normalization to an action tensor.
+
+ Args:
+ action: The action tensor to process.
+ inverse: If `True`, applies unnormalization; otherwise, applies normalization.
+
+ Returns:
+ The transformed action tensor.
+ """
+ processed_action = self._apply_transform(action, ACTION, FeatureType.ACTION, inverse=inverse)
+ return processed_action
+
+ def _apply_transform(
+ self, tensor: Tensor, key: str, feature_type: FeatureType, *, inverse: bool = False
+ ) -> Tensor:
+ """
+ Core logic to apply a normalization or unnormalization transformation to a tensor.
+
+ This method selects the appropriate normalization mode based on the feature type
+ and applies the corresponding mathematical operation.
+
+ Normalization Modes:
+ - MEAN_STD: Centers data around zero with unit variance.
+ - MIN_MAX: Scales data to [-1, 1] range using actual min/max values.
+ - QUANTILES: Scales data to [-1, 1] range using 1st and 99th percentiles (q01/q99).
+ - QUANTILE10: Scales data to [-1, 1] range using 10th and 90th percentiles (q10/q90).
+
+ Args:
+ tensor: The input tensor to transform.
+ key: The feature key corresponding to the tensor.
+ feature_type: The `FeatureType` of the tensor.
+ inverse: If `True`, applies the inverse transformation (unnormalization).
+
+ Returns:
+ The transformed tensor.
+
+ Raises:
+ ValueError: If an unsupported normalization mode is encountered.
+ """
+ norm_mode = self.norm_map.get(feature_type, NormalizationMode.IDENTITY)
+ if norm_mode == NormalizationMode.IDENTITY or key not in self._tensor_stats:
+ return tensor
+
+ if norm_mode not in (
+ NormalizationMode.MEAN_STD,
+ NormalizationMode.MIN_MAX,
+ NormalizationMode.QUANTILES,
+ NormalizationMode.QUANTILE10,
+ ):
+ raise ValueError(f"Unsupported normalization mode: {norm_mode}")
+
+ # For Accelerate compatibility: Ensure stats are on the same device and dtype as the input tensor
+ if self._tensor_stats and key in self._tensor_stats:
+ first_stat = next(iter(self._tensor_stats[key].values()))
+ if first_stat.device != tensor.device or first_stat.dtype != tensor.dtype:
+ self.to(device=tensor.device, dtype=tensor.dtype)
+
+ stats = self._tensor_stats[key]
+
+ if norm_mode == NormalizationMode.MEAN_STD:
+ mean = stats.get("mean", None)
+ std = stats.get("std", None)
+ if mean is None or std is None:
+ raise ValueError(
+ "MEAN_STD normalization mode requires mean and std stats, please update the dataset with the correct stats"
+ )
+
+ mean, std = stats["mean"], stats["std"]
+ # Avoid division by zero by adding a small epsilon.
+ denom = std + self.eps
+ if inverse:
+ return tensor * std + mean
+ return (tensor - mean) / denom
+
+ if norm_mode == NormalizationMode.MIN_MAX:
+ min_val = stats.get("min", None)
+ max_val = stats.get("max", None)
+ if min_val is None or max_val is None:
+ raise ValueError(
+ "MIN_MAX normalization mode requires min and max stats, please update the dataset with the correct stats"
+ )
+
+ min_val, max_val = stats["min"], stats["max"]
+ denom = max_val - min_val
+ # When min_val == max_val, substitute the denominator with a small epsilon
+ # to prevent division by zero. This consistently maps an input equal to
+ # min_val to -1, ensuring a stable transformation.
+ denom = torch.where(
+ denom == 0, torch.tensor(self.eps, device=tensor.device, dtype=tensor.dtype), denom
+ )
+ if inverse:
+ # Map from [-1, 1] back to [min, max]
+ return (tensor + 1) / 2 * denom + min_val
+ # Map from [min, max] to [-1, 1]
+ return 2 * (tensor - min_val) / denom - 1
+
+ if norm_mode == NormalizationMode.QUANTILES:
+ q01 = stats.get("q01", None)
+ q99 = stats.get("q99", None)
+ if q01 is None or q99 is None:
+ raise ValueError(
+ "QUANTILES normalization mode requires q01 and q99 stats, please update the dataset with the correct stats using the `augment_dataset_quantile_stats.py` script"
+ )
+
+ denom = q99 - q01
+ # Avoid division by zero by adding epsilon when quantiles are identical
+ denom = torch.where(
+ denom == 0, torch.tensor(self.eps, device=tensor.device, dtype=tensor.dtype), denom
+ )
+ if inverse:
+ return (tensor + 1.0) * denom / 2.0 + q01
+ return 2.0 * (tensor - q01) / denom - 1.0
+
+ if norm_mode == NormalizationMode.QUANTILE10:
+ q10 = stats.get("q10", None)
+ q90 = stats.get("q90", None)
+ if q10 is None or q90 is None:
+ raise ValueError(
+ "QUANTILE10 normalization mode requires q10 and q90 stats, please update the dataset with the correct stats using the `augment_dataset_quantile_stats.py` script"
+ )
+
+ denom = q90 - q10
+ # Avoid division by zero by adding epsilon when quantiles are identical
+ denom = torch.where(
+ denom == 0, torch.tensor(self.eps, device=tensor.device, dtype=tensor.dtype), denom
+ )
+ if inverse:
+ return (tensor + 1.0) * denom / 2.0 + q10
+ return 2.0 * (tensor - q10) / denom - 1.0
+
+ # If necessary stats are missing, return input unchanged.
+ return tensor
+
+
+@dataclass
+@ProcessorStepRegistry.register(name="normalizer_processor")
+class NormalizerProcessorStep(_NormalizationMixin, ProcessorStep):
+ """
+ A processor step that applies normalization to observations and actions in a transition.
+
+ This class uses the logic from `_NormalizationMixin` to perform forward normalization
+ (e.g., scaling data to have zero mean and unit variance, or to the range [-1, 1]).
+ It is typically used in the pre-processing pipeline before feeding data to a policy.
+ """
+
+ @classmethod
+ def from_lerobot_dataset(
+ cls,
+ dataset: LeRobotDataset,
+ features: dict[str, PolicyFeature],
+ norm_map: dict[FeatureType, NormalizationMode],
+ *,
+ normalize_observation_keys: set[str] | None = None,
+ eps: float = 1e-8,
+ device: torch.device | str | None = None,
+ ) -> NormalizerProcessorStep:
+ """
+ Creates a `NormalizerProcessorStep` instance using statistics from a `LeRobotDataset`.
+
+ Args:
+ dataset: The dataset from which to extract normalization statistics.
+ features: The feature definition for the processor.
+ norm_map: The mapping from feature types to normalization modes.
+ normalize_observation_keys: An optional set of observation keys to normalize.
+ eps: A small epsilon value for numerical stability.
+ device: The target device for the processor.
+
+ Returns:
+ A new instance of `NormalizerProcessorStep`.
+ """
+ return cls(
+ features=features,
+ norm_map=norm_map,
+ stats=dataset.meta.stats,
+ normalize_observation_keys=normalize_observation_keys,
+ eps=eps,
+ device=device,
+ )
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ new_transition = transition.copy()
+
+ # Handle observation normalization.
+ observation = new_transition.get(TransitionKey.OBSERVATION)
+ if observation is not None:
+ new_transition[TransitionKey.OBSERVATION] = self._normalize_observation(
+ observation, inverse=False
+ )
+
+ # Handle action normalization.
+ action = new_transition.get(TransitionKey.ACTION)
+
+ if action is None:
+ return new_transition
+
+ if not isinstance(action, PolicyAction):
+ raise ValueError(f"Action should be a PolicyAction type got {type(action)}")
+
+ new_transition[TransitionKey.ACTION] = self._normalize_action(action, inverse=False)
+
+ return new_transition
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
+
+
+@dataclass
+@ProcessorStepRegistry.register(name="unnormalizer_processor")
+class UnnormalizerProcessorStep(_NormalizationMixin, ProcessorStep):
+ """
+ A processor step that applies unnormalization to observations and actions.
+
+ This class inverts the normalization process, scaling data back to its original
+ range. It is typically used in the post-processing pipeline to convert a policy's
+ normalized action output into a format that can be executed by a robot or
+ environment.
+ """
+
+ @classmethod
+ def from_lerobot_dataset(
+ cls,
+ dataset: LeRobotDataset,
+ features: dict[str, PolicyFeature],
+ norm_map: dict[FeatureType, NormalizationMode],
+ *,
+ device: torch.device | str | None = None,
+ ) -> UnnormalizerProcessorStep:
+ """
+ Creates an `UnnormalizerProcessorStep` using statistics from a `LeRobotDataset`.
+
+ Args:
+ dataset: The dataset from which to extract normalization statistics.
+ features: The feature definition for the processor.
+ norm_map: The mapping from feature types to normalization modes.
+ device: The target device for the processor.
+
+ Returns:
+ A new instance of `UnnormalizerProcessorStep`.
+ """
+ return cls(features=features, norm_map=norm_map, stats=dataset.meta.stats, device=device)
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ new_transition = transition.copy()
+
+ # Handle observation unnormalization.
+ observation = new_transition.get(TransitionKey.OBSERVATION)
+ if observation is not None:
+ new_transition[TransitionKey.OBSERVATION] = self._normalize_observation(observation, inverse=True)
+
+ # Handle action unnormalization.
+ action = new_transition.get(TransitionKey.ACTION)
+
+ if action is None:
+ return new_transition
+ if not isinstance(action, PolicyAction):
+ raise ValueError(f"Action should be a PolicyAction type got {type(action)}")
+
+ new_transition[TransitionKey.ACTION] = self._normalize_action(action, inverse=True)
+
+ return new_transition
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ return features
+
+
+def hotswap_stats(
+ policy_processor: PolicyProcessorPipeline, stats: dict[str, dict[str, Any]]
+) -> PolicyProcessorPipeline:
+ """
+ Replaces normalization statistics in an existing `PolicyProcessorPipeline` instance.
+
+ This function creates a deep copy of the provided pipeline and updates the
+ statistics of any `NormalizerProcessorStep` or `UnnormalizerProcessorStep` it
+ contains. This is useful for adapting a trained policy to a new environment or
+ dataset with different data distributions without having to reconstruct the entire
+ pipeline.
+
+ Args:
+ policy_processor: The policy processor pipeline to modify.
+ stats: The new dictionary of normalization statistics to apply.
+
+ Returns:
+ A new `PolicyProcessorPipeline` instance with the updated statistics.
+ """
+ rp = deepcopy(policy_processor)
+ for step in rp.steps:
+ if isinstance(step, _NormalizationMixin):
+ step.stats = stats
+ # Re-initialize tensor_stats on the correct device.
+ step._tensor_stats = to_tensor(stats, device=step.device, dtype=step.dtype) # type: ignore[assignment]
+ return rp
diff --git a/lerobot/src/lerobot/processor/observation_processor.py b/lerobot/src/lerobot/processor/observation_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec893ab041fc2f452a421f2a835851fc849e454c
--- /dev/null
+++ b/lerobot/src/lerobot/processor/observation_processor.py
@@ -0,0 +1,206 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+
+import einops
+import numpy as np
+import torch
+from torch import Tensor
+
+from lerobot.configs.types import PipelineFeatureType, PolicyFeature
+from lerobot.utils.constants import OBS_ENV_STATE, OBS_IMAGE, OBS_IMAGES, OBS_STATE, OBS_STR
+
+from .pipeline import ObservationProcessorStep, ProcessorStepRegistry
+
+
+@dataclass
+@ProcessorStepRegistry.register(name="observation_processor")
+class VanillaObservationProcessorStep(ObservationProcessorStep):
+ """
+ Processes standard Gymnasium observations into the LeRobot format.
+
+ This step handles both image and state data from a typical observation dictionary,
+ preparing it for use in a LeRobot policy.
+
+ **Image Processing:**
+ - Converts channel-last (H, W, C), `uint8` images to channel-first (C, H, W),
+ `float32` tensors.
+ - Normalizes pixel values from the [0, 255] range to [0, 1].
+ - Adds a batch dimension if one is not already present.
+ - Recognizes a single image under the key `"pixels"` and maps it to
+ `"observation.image"`.
+ - Recognizes a dictionary of images under the key `"pixels"` and maps them
+ to `"observation.images.{camera_name}"`.
+
+ **State Processing:**
+ - Maps the `"environment_state"` key to `"observation.environment_state"`.
+ - Maps the `"agent_pos"` key to `"observation.state"`.
+ - Converts NumPy arrays to PyTorch tensors.
+ - Adds a batch dimension if one is not already present.
+ """
+
+ def _process_single_image(self, img: np.ndarray) -> Tensor:
+ """
+ Processes a single NumPy image array into a channel-first, normalized tensor.
+
+ Args:
+ img: A NumPy array representing the image, expected to be in channel-last
+ (H, W, C) format with a `uint8` dtype.
+
+ Returns:
+ A `float32` PyTorch tensor in channel-first (B, C, H, W) format, with
+ pixel values normalized to the [0, 1] range.
+
+ Raises:
+ ValueError: If the input image does not appear to be in channel-last
+ format or is not of `uint8` dtype.
+ """
+ # Convert to tensor
+ img_tensor = torch.from_numpy(img)
+
+ # Add batch dimension if needed
+ if img_tensor.ndim == 3:
+ img_tensor = img_tensor.unsqueeze(0)
+
+ # Validate image format
+ _, h, w, c = img_tensor.shape
+ if not (c < h and c < w):
+ raise ValueError(f"Expected channel-last images, but got shape {img_tensor.shape}")
+
+ if img_tensor.dtype != torch.uint8:
+ raise ValueError(f"Expected torch.uint8 images, but got {img_tensor.dtype}")
+
+ # Convert to channel-first format
+ img_tensor = einops.rearrange(img_tensor, "b h w c -> b c h w").contiguous()
+
+ # Convert to float32 and normalize to [0, 1]
+ img_tensor = img_tensor.type(torch.float32) / 255.0
+
+ return img_tensor
+
+ def _process_observation(self, observation):
+ """
+ Processes both image and state observations.
+ """
+
+ processed_obs = observation.copy()
+
+ if "pixels" in processed_obs:
+ pixels = processed_obs.pop("pixels")
+
+ if isinstance(pixels, dict):
+ imgs = {f"{OBS_IMAGES}.{key}": img for key, img in pixels.items()}
+ else:
+ imgs = {OBS_IMAGE: pixels}
+
+ for imgkey, img in imgs.items():
+ processed_obs[imgkey] = self._process_single_image(img)
+
+ if "environment_state" in processed_obs:
+ env_state_np = processed_obs.pop("environment_state")
+ env_state = torch.from_numpy(env_state_np).float()
+ if env_state.dim() == 1:
+ env_state = env_state.unsqueeze(0)
+ processed_obs[OBS_ENV_STATE] = env_state
+
+ if "agent_pos" in processed_obs:
+ agent_pos_np = processed_obs.pop("agent_pos")
+ agent_pos = torch.from_numpy(agent_pos_np).float()
+ if agent_pos.dim() == 1:
+ agent_pos = agent_pos.unsqueeze(0)
+ processed_obs[OBS_STATE] = agent_pos
+
+ return processed_obs
+
+ def observation(self, observation):
+ return self._process_observation(observation)
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """
+ Transforms feature keys from the Gym standard to the LeRobot standard.
+
+ This method standardizes the feature dictionary by renaming keys according
+ to LeRobot's conventions, ensuring that policies can be constructed correctly.
+ It handles various raw key formats, including those with an "observation." prefix.
+
+ **Renaming Rules:**
+ - `pixels` or `observation.pixels` -> `observation.image`
+ - `pixels.{cam}` or `observation.pixels.{cam}` -> `observation.images.{cam}`
+ - `environment_state` or `observation.environment_state` -> `observation.environment_state`
+ - `agent_pos` or `observation.agent_pos` -> `observation.state`
+
+ Args:
+ features: The policy features dictionary with Gym-style keys.
+
+ Returns:
+ The policy features dictionary with standardized LeRobot keys.
+ """
+ # Build a new features mapping keyed by the same FeatureType buckets
+ # We assume callers already placed features in the correct FeatureType.
+ new_features: dict[PipelineFeatureType, dict[str, PolicyFeature]] = {ft: {} for ft in features}
+
+ exact_pairs = {
+ "pixels": OBS_IMAGE,
+ "environment_state": OBS_ENV_STATE,
+ "agent_pos": OBS_STATE,
+ }
+
+ prefix_pairs = {
+ "pixels.": f"{OBS_IMAGES}.",
+ }
+
+ # Iterate over all incoming feature buckets and normalize/move each entry
+ for src_ft, bucket in features.items():
+ for key, feat in list(bucket.items()):
+ handled = False
+
+ # Prefix-based rules (e.g. pixels.cam1 -> OBS_IMAGES.cam1)
+ for old_prefix, new_prefix in prefix_pairs.items():
+ prefixed_old = f"{OBS_STR}.{old_prefix}"
+ if key.startswith(prefixed_old):
+ suffix = key[len(prefixed_old) :]
+ new_key = f"{new_prefix}{suffix}"
+ new_features[src_ft][new_key] = feat
+ handled = True
+ break
+
+ if key.startswith(old_prefix):
+ suffix = key[len(old_prefix) :]
+ new_key = f"{new_prefix}{suffix}"
+ new_features[src_ft][new_key] = feat
+ handled = True
+ break
+
+ if handled:
+ continue
+
+ # Exact-name rules (pixels, environment_state, agent_pos)
+ for old, new in exact_pairs.items():
+ if key == old or key == f"{OBS_STR}.{old}":
+ new_key = new
+ new_features[src_ft][new_key] = feat
+ handled = True
+ break
+
+ if handled:
+ continue
+
+ # Default: keep key in the same source FeatureType bucket
+ new_features[src_ft][key] = feat
+
+ return new_features
diff --git a/lerobot/src/lerobot/processor/pipeline.py b/lerobot/src/lerobot/processor/pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..37ad25dd7c1e1ad08e051d24ec801afd001b74b9
--- /dev/null
+++ b/lerobot/src/lerobot/processor/pipeline.py
@@ -0,0 +1,1716 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+This module defines a generic, sequential data processing pipeline framework, primarily designed for
+transforming robotics data (observations, actions, rewards, etc.).
+
+The core components are:
+- ProcessorStep: An abstract base class for a single data transformation operation.
+- ProcessorStepRegistry: A mechanism to register and retrieve ProcessorStep classes by name.
+- DataProcessorPipeline: A class that chains multiple ProcessorStep instances together to form a complete
+ data processing workflow. It integrates with the Hugging Face Hub for easy sharing and versioning of
+ pipelines, including their configuration and state.
+- Specialized abstract ProcessorStep subclasses (e.g., ObservationProcessorStep, ActionProcessorStep)
+ to simplify the creation of steps that target specific parts of a data transition.
+"""
+
+from __future__ import annotations
+
+import importlib
+import json
+import os
+import re
+from abc import ABC, abstractmethod
+from collections.abc import Callable, Iterable, Sequence
+from copy import deepcopy
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Generic, TypeAlias, TypedDict, TypeVar, cast
+
+import torch
+from huggingface_hub import hf_hub_download
+from safetensors.torch import load_file, save_file
+
+from lerobot.configs.types import PipelineFeatureType, PolicyFeature
+from lerobot.utils.hub import HubMixin
+
+from .converters import batch_to_transition, create_transition, transition_to_batch
+from .core import EnvAction, EnvTransition, PolicyAction, RobotAction, RobotObservation, TransitionKey
+
+# Generic type variables for pipeline input and output.
+TInput = TypeVar("TInput")
+TOutput = TypeVar("TOutput")
+
+
+class ProcessorStepRegistry:
+ """A registry for ProcessorStep classes to allow instantiation from a string name.
+
+ This class provides a way to map string identifiers to `ProcessorStep` classes,
+ which is useful for deserializing pipelines from configuration files without
+
+ hardcoding class imports.
+ """
+
+ _registry: dict[str, type] = {}
+
+ @classmethod
+ def register(cls, name: str | None = None):
+ """A class decorator to register a ProcessorStep.
+
+ Args:
+ name: The name to register the class under. If None, the class's `__name__` is used.
+
+ Returns:
+ A decorator function that registers the class and returns it.
+
+ Raises:
+ ValueError: If a step with the same name is already registered.
+ """
+
+ def decorator(step_class: type) -> type:
+ """The actual decorator that performs the registration."""
+ registration_name = name if name is not None else step_class.__name__
+
+ if registration_name in cls._registry:
+ raise ValueError(
+ f"Processor step '{registration_name}' is already registered. "
+ f"Use a different name or unregister the existing one first."
+ )
+
+ cls._registry[registration_name] = step_class
+ # Store the registration name on the class for easy lookup during serialization.
+ step_class._registry_name = registration_name
+ return step_class
+
+ return decorator
+
+ @classmethod
+ def get(cls, name: str) -> type:
+ """Retrieves a processor step class from the registry by its name.
+
+ Args:
+ name: The name of the step to retrieve.
+
+ Returns:
+ The processor step class corresponding to the given name.
+
+ Raises:
+ KeyError: If the name is not found in the registry.
+ """
+ if name not in cls._registry:
+ available = list(cls._registry.keys())
+ raise KeyError(
+ f"Processor step '{name}' not found in registry. "
+ f"Available steps: {available}. "
+ f"Make sure the step is registered using @ProcessorStepRegistry.register()"
+ )
+ return cls._registry[name]
+
+ @classmethod
+ def unregister(cls, name: str) -> None:
+ """Removes a processor step from the registry.
+
+ Args:
+ name: The name of the step to unregister.
+ """
+ cls._registry.pop(name, None)
+
+ @classmethod
+ def list(cls) -> list[str]:
+ """Returns a list of all registered processor step names."""
+ return list(cls._registry.keys())
+
+ @classmethod
+ def clear(cls) -> None:
+ """Clears all processor steps from the registry."""
+ cls._registry.clear()
+
+
+class ProcessorStep(ABC):
+ """Abstract base class for a single step in a data processing pipeline.
+
+ Each step must implement the `__call__` method to perform its transformation
+ on a data transition and the `transform_features` method to describe how it
+ alters the shape or type of data features.
+
+ Subclasses can optionally be stateful by implementing `state_dict` and `load_state_dict`.
+ """
+
+ _current_transition: EnvTransition | None = None
+
+ @property
+ def transition(self) -> EnvTransition:
+ """Provides access to the most recent transition being processed.
+
+ This is useful for steps that need to access other parts of the transition
+ data beyond their primary target (e.g., an action processing step that
+ needs to look at the observation).
+
+ Raises:
+ ValueError: If accessed before the step has been called with a transition.
+ """
+ if self._current_transition is None:
+ raise ValueError("Transition is not set. Make sure to call the step with a transition first.")
+ return self._current_transition
+
+ @abstractmethod
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Processes an environment transition.
+
+ This method should contain the core logic of the processing step.
+
+ Args:
+ transition: The input data transition to be processed.
+
+ Returns:
+ The processed transition.
+ """
+ return transition
+
+ def get_config(self) -> dict[str, Any]:
+ """Returns the configuration of the step for serialization.
+
+ Returns:
+ A JSON-serializable dictionary of configuration parameters.
+ """
+ return {}
+
+ def state_dict(self) -> dict[str, torch.Tensor]:
+ """Returns the state of the step (e.g., learned parameters, running means).
+
+ Returns:
+ A dictionary mapping state names to tensors.
+ """
+ return {}
+
+ def load_state_dict(self, state: dict[str, torch.Tensor]) -> None:
+ """Loads the step's state from a state dictionary.
+
+ Args:
+ state: A dictionary of state tensors.
+ """
+ return None
+
+ def reset(self) -> None:
+ """Resets the internal state of the processor step, if any."""
+ return None
+
+ @abstractmethod
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """Defines how this step modifies the description of pipeline features.
+
+ This method is used to track changes in data shapes, dtypes, or modalities
+ as data flows through the pipeline, without needing to process actual data.
+
+ Args:
+ features: A dictionary describing the input features for observations, actions, etc.
+
+ Returns:
+ A dictionary describing the output features after this step's transformation.
+ """
+ return features
+
+
+class ProcessorKwargs(TypedDict, total=False):
+ """A TypedDict for optional keyword arguments used in pipeline construction."""
+
+ to_transition: Callable[[dict[str, Any]], EnvTransition] | None
+ to_output: Callable[[EnvTransition], Any] | None
+ name: str | None
+ before_step_hooks: list[Callable[[int, EnvTransition], None]] | None
+ after_step_hooks: list[Callable[[int, EnvTransition], None]] | None
+
+
+class ProcessorMigrationError(Exception):
+ """Raised when a model needs migration to the processor format"""
+
+ def __init__(self, model_path: str | Path, migration_command: str, original_error: str):
+ self.model_path = model_path
+ self.migration_command = migration_command
+ self.original_error = original_error
+ super().__init__(
+ f"Model '{model_path}' requires migration to processor format. "
+ f"Run: {migration_command}\n\nOriginal error: {original_error}"
+ )
+
+
+@dataclass
+class DataProcessorPipeline(HubMixin, Generic[TInput, TOutput]):
+ """A sequential pipeline for processing data, integrated with the Hugging Face Hub.
+
+ This class chains together multiple `ProcessorStep` instances to form a complete
+ data processing workflow. It's generic, allowing for custom input and output types,
+ which are handled by the `to_transition` and `to_output` converters.
+
+ Attributes:
+ steps: A sequence of `ProcessorStep` objects that make up the pipeline.
+ name: A descriptive name for the pipeline.
+ to_transition: A function to convert raw input data into the standardized `EnvTransition` format.
+ to_output: A function to convert the final `EnvTransition` into the desired output format.
+ before_step_hooks: A list of functions to be called before each step is executed.
+ after_step_hooks: A list of functions to be called after each step is executed.
+ """
+
+ steps: Sequence[ProcessorStep] = field(default_factory=list)
+ name: str = "DataProcessorPipeline"
+
+ to_transition: Callable[[TInput], EnvTransition] = field(
+ default_factory=lambda: cast(Callable[[TInput], EnvTransition], batch_to_transition), repr=False
+ )
+ to_output: Callable[[EnvTransition], TOutput] = field(
+ default_factory=lambda: cast(Callable[[EnvTransition], TOutput], transition_to_batch),
+ repr=False,
+ )
+
+ before_step_hooks: list[Callable[[int, EnvTransition], None]] = field(default_factory=list, repr=False)
+ after_step_hooks: list[Callable[[int, EnvTransition], None]] = field(default_factory=list, repr=False)
+
+ def __call__(self, data: TInput) -> TOutput:
+ """Processes input data through the full pipeline.
+
+ Args:
+ data: The input data to process.
+
+ Returns:
+ The processed data in the specified output format.
+ """
+ transition = self.to_transition(data)
+ transformed_transition = self._forward(transition)
+ return self.to_output(transformed_transition)
+
+ def _forward(self, transition: EnvTransition) -> EnvTransition:
+ """Executes all processing steps and hooks in sequence.
+
+ Args:
+ transition: The initial `EnvTransition` object.
+
+ Returns:
+ The final `EnvTransition` after all steps have been applied.
+ """
+ for idx, processor_step in enumerate(self.steps):
+ # Execute pre-hooks
+ for hook in self.before_step_hooks:
+ hook(idx, transition)
+
+ transition = processor_step(transition)
+
+ # Execute post-hooks
+ for hook in self.after_step_hooks:
+ hook(idx, transition)
+ return transition
+
+ def step_through(self, data: TInput) -> Iterable[EnvTransition]:
+ """Processes data step-by-step, yielding the transition at each stage.
+
+ This is a generator method useful for debugging and inspecting the intermediate
+ state of the data as it passes through the pipeline.
+
+ Args:
+ data: The input data.
+
+ Yields:
+ The `EnvTransition` object, starting with the initial state and then after
+ each processing step.
+ """
+ transition = self.to_transition(data)
+
+ # Yield the initial state before any processing.
+ yield transition
+
+ for processor_step in self.steps:
+ transition = processor_step(transition)
+ yield transition
+
+ def _save_pretrained(self, save_directory: Path, **kwargs):
+ """Internal method to comply with `HubMixin`'s saving mechanism.
+
+ This method does the actual saving work and is called by HubMixin.save_pretrained.
+ """
+ config_filename = kwargs.pop("config_filename", None)
+
+ # Sanitize the pipeline name to create a valid filename prefix.
+ sanitized_name = re.sub(r"[^a-zA-Z0-9_]", "_", self.name.lower())
+
+ if config_filename is None:
+ config_filename = f"{sanitized_name}.json"
+
+ config: dict[str, Any] = {
+ "name": self.name,
+ "steps": [],
+ }
+
+ # Iterate through each step to build its configuration entry.
+ for step_index, processor_step in enumerate(self.steps):
+ registry_name = getattr(processor_step.__class__, "_registry_name", None)
+
+ step_entry: dict[str, Any] = {}
+ # Prefer registry name for portability, otherwise fall back to full class path.
+ if registry_name:
+ step_entry["registry_name"] = registry_name
+ else:
+ step_entry["class"] = (
+ f"{processor_step.__class__.__module__}.{processor_step.__class__.__name__}"
+ )
+
+ # Save step configuration if `get_config` is implemented.
+ if hasattr(processor_step, "get_config"):
+ step_entry["config"] = processor_step.get_config()
+
+ # Save step state if `state_dict` is implemented and returns a non-empty dict.
+ if hasattr(processor_step, "state_dict"):
+ state = processor_step.state_dict()
+ if state:
+ # Clone tensors to avoid modifying the original state.
+ cloned_state = {key: tensor.clone() for key, tensor in state.items()}
+
+ # Create a unique filename for the state file.
+ if registry_name:
+ state_filename = f"{sanitized_name}_step_{step_index}_{registry_name}.safetensors"
+ else:
+ state_filename = f"{sanitized_name}_step_{step_index}.safetensors"
+
+ save_file(cloned_state, os.path.join(str(save_directory), state_filename))
+ step_entry["state_file"] = state_filename
+
+ config["steps"].append(step_entry)
+
+ # Write the main configuration JSON file.
+ with open(os.path.join(str(save_directory), config_filename), "w") as file_pointer:
+ json.dump(config, file_pointer, indent=2)
+
+ def save_pretrained(
+ self,
+ save_directory: str | Path | None = None,
+ *,
+ repo_id: str | None = None,
+ push_to_hub: bool = False,
+ card_kwargs: dict[str, Any] | None = None,
+ config_filename: str | None = None,
+ **push_to_hub_kwargs,
+ ):
+ """Saves the pipeline's configuration and state to a directory.
+
+ This method creates a JSON configuration file that defines the pipeline's structure
+ (name and steps). For each stateful step, it also saves a `.safetensors` file
+ containing its state dictionary.
+
+ Args:
+ save_directory: The directory where the pipeline will be saved. If None, saves to
+ HF_LEROBOT_HOME/processors/{sanitized_pipeline_name}.
+ repo_id: ID of your repository on the Hub. Used only if `push_to_hub=True`.
+ push_to_hub: Whether or not to push your object to the Hugging Face Hub after saving it.
+ card_kwargs: Additional arguments passed to the card template to customize the card.
+ config_filename: The name of the JSON configuration file. If None, a name is
+ generated from the pipeline's `name` attribute.
+ **push_to_hub_kwargs: Additional key word arguments passed along to the push_to_hub method.
+ """
+ if save_directory is None:
+ # Use default directory in HF_LEROBOT_HOME
+ from lerobot.utils.constants import HF_LEROBOT_HOME
+
+ sanitized_name = re.sub(r"[^a-zA-Z0-9_]", "_", self.name.lower())
+ save_directory = HF_LEROBOT_HOME / "processors" / sanitized_name
+
+ # For direct saves (not through hub), handle config_filename
+ if not push_to_hub and config_filename is not None:
+ # Call _save_pretrained directly with config_filename
+ save_directory = Path(save_directory)
+ save_directory.mkdir(parents=True, exist_ok=True)
+ self._save_pretrained(save_directory, config_filename=config_filename)
+ return None
+
+ # Pass config_filename through kwargs for _save_pretrained when using hub
+ if config_filename is not None:
+ push_to_hub_kwargs["config_filename"] = config_filename
+
+ # Call parent's save_pretrained which will call our _save_pretrained
+ return super().save_pretrained(
+ save_directory=save_directory,
+ repo_id=repo_id,
+ push_to_hub=push_to_hub,
+ card_kwargs=card_kwargs,
+ **push_to_hub_kwargs,
+ )
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ pretrained_model_name_or_path: str | Path,
+ config_filename: str,
+ *,
+ force_download: bool = False,
+ resume_download: bool | None = None,
+ proxies: dict[str, str] | None = None,
+ token: str | bool | None = None,
+ cache_dir: str | Path | None = None,
+ local_files_only: bool = False,
+ revision: str | None = None,
+ overrides: dict[str, Any] | None = None,
+ to_transition: Callable[[TInput], EnvTransition] | None = None,
+ to_output: Callable[[EnvTransition], TOutput] | None = None,
+ **kwargs,
+ ) -> DataProcessorPipeline[TInput, TOutput]:
+ """Loads a pipeline from a local directory, single file, or Hugging Face Hub repository.
+
+ This method implements a simplified loading pipeline with intelligent migration detection:
+
+ **Simplified Loading Strategy**:
+ 1. **Config Loading** (_load_config):
+ - **Directory**: Load specified config_filename from directory
+ - **Single file**: Load file directly (config_filename ignored)
+ - **Hub repository**: Download specified config_filename from Hub
+
+ 2. **Config Validation** (_validate_loaded_config):
+ - Format validation: Ensure config is valid processor format
+ - Migration detection: Guide users to migrate old LeRobot models
+ - Clear errors: Provide actionable error messages
+
+ 3. **Step Construction** (_build_steps_with_overrides):
+ - Class resolution: Registry lookup or dynamic imports
+ - Override merging: User parameters override saved config
+ - State loading: Load .safetensors files for stateful steps
+
+ 4. **Override Validation** (_validate_overrides_used):
+ - Ensure all user overrides were applied (catch typos)
+ - Provide helpful error messages with available keys
+
+ **Migration Detection**:
+ - **Smart detection**: Analyzes JSON files to detect old LeRobot models
+ - **Precise targeting**: Avoids false positives on other HuggingFace models
+ - **Clear guidance**: Provides exact migration command to run
+ - **Error mode**: Always raises ProcessorMigrationError for clear user action
+
+ **Loading Examples**:
+ ```python
+ # Directory loading
+ pipeline = DataProcessorPipeline.from_pretrained("/models/my_model", config_filename="processor.json")
+
+ # Single file loading
+ pipeline = DataProcessorPipeline.from_pretrained(
+ "/models/my_model/processor.json", config_filename="processor.json"
+ )
+
+ # Hub loading
+ pipeline = DataProcessorPipeline.from_pretrained("user/repo", config_filename="processor.json")
+
+ # Multiple configs (preprocessor/postprocessor)
+ preprocessor = DataProcessorPipeline.from_pretrained(
+ "model", config_filename="policy_preprocessor.json"
+ )
+ postprocessor = DataProcessorPipeline.from_pretrained(
+ "model", config_filename="policy_postprocessor.json"
+ )
+ ```
+
+ **Override System**:
+ - **Key matching**: Use registry names or class names as override keys
+ - **Config merging**: User overrides take precedence over saved config
+ - **Validation**: Ensure all override keys match actual steps (catch typos)
+ - **Example**: overrides={"NormalizeStep": {"device": "cuda"}}
+
+ Args:
+ pretrained_model_name_or_path: The identifier of the repository on the Hugging Face Hub,
+ a path to a local directory, or a path to a single config file.
+ config_filename: The name of the pipeline's JSON configuration file. Always required
+ to prevent ambiguity when multiple configs exist (e.g., preprocessor vs postprocessor).
+ force_download: Whether to force (re)downloading the files.
+ resume_download: Whether to resume a previously interrupted download.
+ proxies: A dictionary of proxy servers to use.
+ token: The token to use as HTTP bearer authorization for private Hub repositories.
+ cache_dir: The path to a specific cache folder to store downloaded files.
+ local_files_only: If True, avoid downloading files from the Hub.
+ revision: The specific model version to use (e.g., a branch name, tag name, or commit id).
+ overrides: A dictionary to override the configuration of specific steps. Keys should
+ match the step's class name or registry name.
+ to_transition: A custom function to convert input data to `EnvTransition`.
+ to_output: A custom function to convert the final `EnvTransition` to the output format.
+ **kwargs: Additional arguments (not used).
+
+ Returns:
+ An instance of `DataProcessorPipeline` loaded with the specified configuration and state.
+
+ Raises:
+ FileNotFoundError: If the config file cannot be found.
+ ValueError: If configuration is ambiguous or instantiation fails.
+ ImportError: If a step's class cannot be imported.
+ KeyError: If an override key doesn't match any step in the pipeline.
+ ProcessorMigrationError: If the model requires migration to processor format.
+ """
+ model_id = str(pretrained_model_name_or_path)
+ hub_download_kwargs = {
+ "force_download": force_download,
+ "resume_download": resume_download,
+ "proxies": proxies,
+ "token": token,
+ "cache_dir": cache_dir,
+ "local_files_only": local_files_only,
+ "revision": revision,
+ }
+
+ # 1. Load configuration using simplified 3-way logic
+ loaded_config, base_path = cls._load_config(model_id, config_filename, hub_download_kwargs)
+
+ # 2. Validate configuration and handle migration
+ cls._validate_loaded_config(model_id, loaded_config, config_filename)
+
+ # 3. Build steps with overrides
+ steps, validated_overrides = cls._build_steps_with_overrides(
+ loaded_config, overrides or {}, model_id, base_path, hub_download_kwargs
+ )
+
+ # 4. Validate that all overrides were used
+ cls._validate_overrides_used(validated_overrides, loaded_config)
+
+ # 5. Construct and return the final pipeline instance
+ return cls(
+ steps=steps,
+ name=loaded_config.get("name", "DataProcessorPipeline"),
+ to_transition=to_transition or cast(Callable[[TInput], EnvTransition], batch_to_transition),
+ to_output=to_output or cast(Callable[[EnvTransition], TOutput], transition_to_batch),
+ )
+
+ @classmethod
+ def _load_config(
+ cls,
+ model_id: str,
+ config_filename: str,
+ hub_download_kwargs: dict[str, Any],
+ ) -> tuple[dict[str, Any], Path]:
+ """Load configuration from local file or Hugging Face Hub.
+
+ This method implements a super-simplified 3-way loading strategy:
+
+ 1. **Local directory**: Load config_filename from directory
+ - Example: model_id="/models/my_model", config_filename="processor.json"
+ - Loads: "/models/my_model/processor.json"
+
+ 2. **Single file**: Load file directly (ignore config_filename)
+ - Example: model_id="/models/my_model/processor.json"
+ - Loads: "/models/my_model/processor.json" (config_filename ignored)
+
+ 3. **Hub repository**: Download config_filename from Hub
+ - Example: model_id="user/repo", config_filename="processor.json"
+ - Downloads and loads: config_filename from Hub repo
+
+ **Benefits of Explicit config_filename**:
+ - No auto-detection complexity or edge cases
+ - No risk of loading wrong config (preprocessor vs postprocessor)
+ - Consistent behavior across local and Hub usage
+ - Clear, predictable errors
+
+ Args:
+ model_id: The model identifier (Hub repo ID, local directory, or file path)
+ config_filename: The explicit config filename to load (always required)
+ hub_download_kwargs: Parameters for hf_hub_download (tokens, cache, etc.)
+
+ Returns:
+ Tuple of (loaded_config, base_path)
+ - loaded_config: Parsed JSON config dict (always loaded, never None)
+ - base_path: Directory containing config file (for state file resolution)
+
+ Raises:
+ FileNotFoundError: If config file cannot be found locally or on Hub
+ """
+ model_path = Path(model_id)
+
+ if model_path.is_dir():
+ # Directory: load specified config from directory
+ config_path = model_path / config_filename
+ if not config_path.exists():
+ # Check for migration before giving clear error
+ if cls._should_suggest_migration(model_path):
+ cls._suggest_processor_migration(model_id, f"Config file '{config_filename}' not found")
+ raise FileNotFoundError(
+ f"Config file '{config_filename}' not found in directory '{model_id}'"
+ )
+
+ with open(config_path) as f:
+ return json.load(f), model_path
+
+ elif model_path.is_file():
+ # File: load file directly (config_filename is ignored for single files)
+ with open(model_path) as f:
+ return json.load(f), model_path.parent
+
+ else:
+ # Hub: download specified config
+ try:
+ config_path = hf_hub_download(
+ repo_id=model_id,
+ filename=config_filename,
+ repo_type="model",
+ **hub_download_kwargs,
+ )
+
+ with open(config_path) as f:
+ return json.load(f), Path(config_path).parent
+
+ except Exception as e:
+ raise FileNotFoundError(
+ f"Could not find '{config_filename}' on the HuggingFace Hub at '{model_id}'"
+ ) from e
+
+ @classmethod
+ def _validate_loaded_config(
+ cls, model_id: str, loaded_config: dict[str, Any], config_filename: str
+ ) -> None:
+ """Validate that a config was loaded and is a valid processor config.
+
+ This method validates processor config format with intelligent migration detection:
+
+ **Config Format Validation**:
+ - Use _is_processor_config() to validate structure
+ - Must have "steps" field with list of step configurations
+ - Each step needs "class" or "registry_name"
+ - If validation fails AND local directory: Check for migration need
+ - If migration needed: Raise ProcessorMigrationError with command
+ - If no migration: Raise ValueError with helpful error message
+
+ **Migration Detection Logic**:
+ - Only triggered for local directories (not Hub repos)
+ - Analyzes all JSON files in directory to detect old LeRobot models
+ - Provides exact migration command with model path
+
+ Args:
+ model_id: The model identifier (used for migration detection)
+ loaded_config: The loaded config dictionary (guaranteed non-None)
+ config_filename: The config filename that was loaded (for error messages)
+
+ Raises:
+ ValueError: If config format is invalid
+ ProcessorMigrationError: If model needs migration to processor format
+ """
+ # Validate that this is actually a processor config
+ if not cls._is_processor_config(loaded_config):
+ if Path(model_id).is_dir() and cls._should_suggest_migration(Path(model_id)):
+ cls._suggest_processor_migration(
+ model_id,
+ f"Config file '{config_filename}' is not a valid processor configuration",
+ )
+ raise ValueError(
+ f"Config file '{config_filename}' is not a valid processor configuration. "
+ f"Expected a config with 'steps' field, but got: {list(loaded_config.keys())}"
+ )
+
+ @classmethod
+ def _build_steps_with_overrides(
+ cls,
+ loaded_config: dict[str, Any],
+ overrides: dict[str, Any],
+ model_id: str,
+ base_path: Path | None,
+ hub_download_kwargs: dict[str, Any],
+ ) -> tuple[list[ProcessorStep], set[str]]:
+ """Build all processor steps with overrides and state loading.
+
+ This method orchestrates the complete step construction pipeline:
+
+ **For each step in loaded_config["steps"]**:
+
+ 1. **Class Resolution** (via _resolve_step_class):
+ - **If "registry_name" exists**: Look up in ProcessorStepRegistry
+ Example: {"registry_name": "normalize_step"} -> Get registered class
+ - **Else use "class" field**: Dynamic import from full module path
+ Example: {"class": "lerobot.processor.normalize.NormalizeStep"}
+ - **Result**: (step_class, step_key) where step_key is used for overrides
+
+ 2. **Step Instantiation** (via _instantiate_step):
+ - **Merge configs**: saved_config + user_overrides
+ - **Override priority**: User overrides take precedence over saved config
+ - **Example**: saved={"mean": 0.0}, override={"mean": 1.0} -> final={"mean": 1.0}
+ - **Result**: Instantiated ProcessorStep object
+
+ 3. **State Loading** (via _load_step_state):
+ - **If step has "state_file"**: Load tensor state from .safetensors
+ - **Local first**: Check base_path/state_file.safetensors
+ - **Hub fallback**: Download state file if not found locally
+ - **Optional**: Only load if step has load_state_dict method
+
+ 4. **Override Tracking**:
+ - **Track used overrides**: Remove step_key from remaining set
+ - **Purpose**: Validate all user overrides were applied (detect typos)
+
+ **Error Handling**:
+ - Class resolution errors -> ImportError with helpful message
+ - Instantiation errors -> ValueError with config details
+ - State loading errors -> Propagated from load_state_dict
+
+ Args:
+ loaded_config: The loaded processor configuration (must have "steps" field)
+ overrides: User-provided parameter overrides (keyed by class/registry name)
+ model_id: The model identifier (needed for Hub state file downloads)
+ base_path: Local directory path for finding state files
+ hub_download_kwargs: Parameters for hf_hub_download (tokens, cache, etc.)
+
+ Returns:
+ Tuple of (instantiated_steps_list, unused_override_keys)
+ - instantiated_steps_list: List of ready-to-use ProcessorStep instances
+ - unused_override_keys: Override keys that didn't match any step (for validation)
+
+ Raises:
+ ImportError: If a step class cannot be imported or found in registry
+ ValueError: If a step cannot be instantiated with its configuration
+ """
+ steps: list[ProcessorStep] = []
+ override_keys = set(overrides.keys())
+
+ for step_entry in loaded_config["steps"]:
+ # 1. Get step class and key
+ step_class, step_key = cls._resolve_step_class(step_entry)
+
+ # 2. Instantiate step with overrides
+ step_instance = cls._instantiate_step(step_entry, step_class, step_key, overrides)
+
+ # 3. Load step state if available
+ cls._load_step_state(step_instance, step_entry, model_id, base_path, hub_download_kwargs)
+
+ # 4. Track used overrides
+ if step_key in override_keys:
+ override_keys.discard(step_key)
+
+ steps.append(step_instance)
+
+ return steps, override_keys
+
+ @classmethod
+ def _resolve_step_class(cls, step_entry: dict[str, Any]) -> tuple[type[ProcessorStep], str]:
+ """Resolve step class from registry or import path.
+
+ This method implements a two-tier resolution strategy:
+
+ **Tier 1: Registry-based resolution** (preferred):
+ - **If "registry_name" in step_entry**: Look up in ProcessorStepRegistry
+ - **Advantage**: Faster, no imports needed, guaranteed compatibility
+ - **Example**: {"registry_name": "normalize_step"} -> Get pre-registered class
+ - **Error**: KeyError if registry_name not found -> Convert to ImportError
+
+ **Tier 2: Dynamic import fallback**:
+ - **Else use "class" field**: Full module.ClassName import path
+ - **Process**: Split "module.path.ClassName" into module + class parts
+ - **Import**: Use importlib.import_module() + getattr()
+ - **Example**: "lerobot.processor.normalize.NormalizeStep"
+ a. Import module: "lerobot.processor.normalize"
+ b. Get class: getattr(module, "NormalizeStep")
+ - **step_key**: Use class_name ("NormalizeStep") for overrides
+
+ **Override Key Strategy**:
+ - Registry steps: Use registry_name ("normalize_step")
+ - Import steps: Use class_name ("NormalizeStep")
+ - This allows users to override with: {"normalize_step": {...}} or {"NormalizeStep": {...}}
+
+ **Error Handling**:
+ - Registry KeyError -> ImportError with registry context
+ - Import/Attribute errors -> ImportError with helpful suggestions
+ - All errors include troubleshooting guidance
+
+ Args:
+ step_entry: The step configuration dictionary (must have "registry_name" or "class")
+
+ Returns:
+ Tuple of (step_class, step_key)
+ - step_class: The resolved ProcessorStep class (ready for instantiation)
+ - step_key: The key used for user overrides (registry_name or class_name)
+
+ Raises:
+ ImportError: If step class cannot be loaded from registry or import path
+ """
+ if "registry_name" in step_entry:
+ try:
+ step_class = ProcessorStepRegistry.get(step_entry["registry_name"])
+ return step_class, step_entry["registry_name"]
+ except KeyError as e:
+ raise ImportError(f"Failed to load processor step from registry. {str(e)}") from e
+ else:
+ # Fallback to dynamic import using the full class path
+ full_class_path = step_entry["class"]
+ module_path, class_name = full_class_path.rsplit(".", 1)
+
+ try:
+ module = importlib.import_module(module_path)
+ step_class = getattr(module, class_name)
+ return step_class, class_name
+ except (ImportError, AttributeError) as e:
+ raise ImportError(
+ f"Failed to load processor step '{full_class_path}'. "
+ f"Make sure the module '{module_path}' is installed and contains class '{class_name}'. "
+ f"Consider registering the step using @ProcessorStepRegistry.register() for better portability. "
+ f"Error: {str(e)}"
+ ) from e
+
+ @classmethod
+ def _instantiate_step(
+ cls,
+ step_entry: dict[str, Any],
+ step_class: type[ProcessorStep],
+ step_key: str,
+ overrides: dict[str, Any],
+ ) -> ProcessorStep:
+ """Instantiate a single processor step with config overrides.
+
+ This method handles the configuration merging and instantiation logic:
+
+ **Configuration Merging Strategy**:
+ 1. **Extract saved config**: Get step_entry.get("config", {}) from saved pipeline
+ - Example: {"config": {"mean": 0.0, "std": 1.0}}
+ 2. **Extract user overrides**: Get overrides.get(step_key, {}) for this step
+ - Example: overrides = {"NormalizeStep": {"mean": 2.0, "device": "cuda"}}
+ 3. **Merge with priority**: {**saved_cfg, **step_overrides}
+ - **Override priority**: User values override saved values
+ - **Result**: {"mean": 2.0, "std": 1.0, "device": "cuda"}
+
+ **Instantiation Process**:
+ - **Call constructor**: step_class(**merged_cfg)
+ - **Example**: NormalizeStep(mean=2.0, std=1.0, device="cuda")
+
+ **Error Handling**:
+ - **Any exception during instantiation**: Convert to ValueError
+ - **Include context**: step name, attempted config, original error
+ - **Purpose**: Help users debug configuration issues
+ - **Common causes**:
+ a. Invalid parameter types (str instead of float)
+ b. Missing required parameters
+ c. Incompatible parameter combinations
+
+ Args:
+ step_entry: The step configuration from saved config (contains "config" dict)
+ step_class: The step class to instantiate (already resolved)
+ step_key: The key used for overrides ("registry_name" or class name)
+ overrides: User-provided parameter overrides (keyed by step_key)
+
+ Returns:
+ The instantiated processor step (ready for use)
+
+ Raises:
+ ValueError: If step cannot be instantiated, with detailed error context
+ """
+ try:
+ saved_cfg = step_entry.get("config", {})
+ step_overrides = overrides.get(step_key, {})
+ merged_cfg = {**saved_cfg, **step_overrides}
+ return step_class(**merged_cfg)
+ except Exception as e:
+ step_name = step_entry.get("registry_name", step_entry.get("class", "Unknown"))
+ raise ValueError(
+ f"Failed to instantiate processor step '{step_name}' with config: {step_entry.get('config', {})}. "
+ f"Error: {str(e)}"
+ ) from e
+
+ @classmethod
+ def _load_step_state(
+ cls,
+ step_instance: ProcessorStep,
+ step_entry: dict[str, Any],
+ model_id: str,
+ base_path: Path | None,
+ hub_download_kwargs: dict[str, Any],
+ ) -> None:
+ """Load state dictionary for a processor step if available.
+
+ This method implements conditional state loading with local/Hub fallback:
+
+ **Precondition Checks** (early return if not met):
+ 1. **"state_file" in step_entry**: Step config specifies a state file
+ - **If missing**: Step has no saved state (e.g., stateless transforms)
+ 2. **hasattr(step_instance, "load_state_dict")**: Step supports state loading
+ - **If missing**: Step doesn't implement state loading (rare)
+
+ **State File Resolution Strategy**:
+ 1. **Local file priority**: Check base_path/state_filename exists
+ - **Advantage**: Faster, no network calls
+ - **Example**: "/models/my_model/normalize_step_0.safetensors"
+ - **Use case**: Loading from local saved model directory
+
+ 2. **Hub download fallback**: Download state file from repository
+ - **When triggered**: Local file not found or base_path is None
+ - **Process**: Use hf_hub_download with same parameters as config
+ - **Example**: Download "normalize_step_0.safetensors" from "user/repo"
+ - **Result**: Downloaded to local cache, path returned
+
+ **State Loading Process**:
+ - **Load tensors**: Use safetensors.torch.load_file()
+ - **Apply to step**: Call step_instance.load_state_dict(tensor_dict)
+ - **In-place modification**: Updates step's internal tensor state
+
+ **Common state file examples**:
+ - "normalize_step_0.safetensors" - normalization statistics
+ - "custom_step_1.safetensors" - learned parameters
+ - "tokenizer_step_2.safetensors" - vocabulary embeddings
+
+ Args:
+ step_instance: The step instance to load state into (must have load_state_dict)
+ step_entry: The step configuration dictionary (may contain "state_file")
+ model_id: The model identifier (used for Hub downloads if needed)
+ base_path: Local directory path for finding state files (None for Hub-only)
+ hub_download_kwargs: Parameters for hf_hub_download (tokens, cache, etc.)
+
+ Note:
+ This method modifies step_instance in-place and returns None.
+ If state loading fails, exceptions from load_state_dict propagate.
+ """
+ if "state_file" not in step_entry or not hasattr(step_instance, "load_state_dict"):
+ return
+
+ state_filename = step_entry["state_file"]
+
+ # Try local file first
+ if base_path and (base_path / state_filename).exists():
+ state_path = str(base_path / state_filename)
+ else:
+ # Download from Hub
+ state_path = hf_hub_download(
+ repo_id=model_id,
+ filename=state_filename,
+ repo_type="model",
+ **hub_download_kwargs,
+ )
+
+ step_instance.load_state_dict(load_file(state_path))
+
+ @classmethod
+ def _validate_overrides_used(
+ cls, remaining_override_keys: set[str], loaded_config: dict[str, Any]
+ ) -> None:
+ """Validate that all provided overrides were used.
+
+ This method ensures user overrides are valid to catch typos and configuration errors:
+
+ **Validation Logic**:
+ 1. **If remaining_override_keys is empty**: All overrides were used -> Success
+ - **Early return**: No validation needed
+ - **Normal case**: User provided correct override keys
+
+ 2. **If remaining_override_keys has entries**: Some overrides unused -> Error
+ - **Root cause**: User provided keys that don't match any step
+ - **Common issues**:
+ a. Typos in step names ("NormalizStep" vs "NormalizeStep")
+ b. Using wrong key type (class name vs registry name)
+ c. Step doesn't exist in saved pipeline
+
+ **Helpful Error Generation**:
+ - **Extract available keys**: Build list of valid override keys from config
+ a. **Registry steps**: Use "registry_name" directly
+ b. **Import steps**: Extract class name from "class" field
+ - Example: "lerobot.processor.normalize.NormalizeStep" -> "NormalizeStep"
+ - **Error message includes**:
+ a. Invalid keys provided by user
+ b. List of valid keys they can use
+ c. Guidance about registry vs class names
+
+ **Override Key Resolution Rules**:
+ - Steps with "registry_name": Use registry_name for overrides
+ - Steps with "class": Use final class name for overrides
+ - Users must match these exact keys in their overrides dict
+
+ Args:
+ remaining_override_keys: Override keys that weren't matched to any step
+ loaded_config: The loaded processor configuration (contains "steps" list)
+
+ Raises:
+ KeyError: If any override keys were not used, with helpful error message
+ """
+ if not remaining_override_keys:
+ return
+
+ available_keys = [
+ step.get("registry_name") or step["class"].rsplit(".", 1)[1] for step in loaded_config["steps"]
+ ]
+
+ raise KeyError(
+ f"Override keys {list(remaining_override_keys)} do not match any step in the saved configuration. "
+ f"Available step keys: {available_keys}. "
+ f"Make sure override keys match exact step class names or registry names."
+ )
+
+ @classmethod
+ def _should_suggest_migration(cls, model_path: Path) -> bool:
+ """Check if directory has JSON files but no processor configs.
+
+ This method implements smart migration detection to avoid false positives:
+
+ **Decision Logic**:
+ 1. **No JSON files found**: Return False
+ - **Reason**: Empty directory or only non-config files
+ - **Example**: Directory with only .safetensors, .md files
+ - **Action**: No migration needed
+
+ 2. **JSON files exist**: Analyze each file
+ - **Goal**: Determine if ANY file is a valid processor config
+ - **Process**:
+ a. Try to parse each .json file
+ b. Skip files with JSON parse errors (malformed)
+ c. Check if parsed config passes _is_processor_config()
+ - **If ANY valid processor found**: Return False (no migration)
+ - **If NO valid processors found**: Return True (migration needed)
+
+ **Examples**:
+ - **No migration**: ["processor.json", "config.json"] where processor.json is valid
+ - **Migration needed**: ["config.json", "train.json"] where both are model configs
+ - **No migration**: [] (empty directory)
+ - **Migration needed**: ["old_model_config.json"] with old LeRobot format
+
+ **Why this works**:
+ - **Precise detection**: Only suggests migration for actual old LeRobot models
+ - **Avoids false positives**: Won't trigger on other HuggingFace model types
+ - **Graceful handling**: Ignores malformed JSON files
+
+ Args:
+ model_path: Path to local directory to analyze
+
+ Returns:
+ True if directory has JSON configs but none are processor configs (migration needed)
+ False if no JSON files or at least one valid processor config exists
+ """
+ json_files = list(model_path.glob("*.json"))
+ if len(json_files) == 0:
+ return False
+
+ # Check if any JSON file is a processor config
+ for json_file in json_files:
+ try:
+ with open(json_file) as f:
+ config = json.load(f)
+
+ if cls._is_processor_config(config):
+ return False # Found at least one processor config, no migration needed
+
+ except (json.JSONDecodeError, OSError):
+ # Skip files that can't be parsed as JSON
+ continue
+
+ # Have JSON files but no processor configs - suggest migration
+ return True
+
+ @classmethod
+ def _is_processor_config(cls, config: dict) -> bool:
+ """Check if config follows DataProcessorPipeline format.
+
+ This method validates the processor configuration structure:
+
+ **Required Structure Validation**:
+ 1. **"steps" field existence**: Must have top-level "steps" key
+ - **If missing**: Not a processor config (e.g., model config, train config)
+ - **Example invalid**: {"type": "act", "hidden_dim": 256}
+
+ 2. **"steps" field type**: Must be a list, not other types
+ - **If not list**: Invalid format
+ - **Example invalid**: {"steps": "some_string"} or {"steps": {"key": "value"}}
+
+ 3. **Empty steps validation**: Empty list is valid
+ - **If len(steps) == 0**: Return True immediately
+ - **Use case**: Empty processor pipeline (no-op)
+ - **Example valid**: {"name": "EmptyProcessor", "steps": []}
+
+ **Individual Step Validation** (for non-empty steps):
+ For each step in the steps list:
+ 1. **Step type**: Must be a dictionary
+ - **If not dict**: Invalid step format
+ - **Example invalid**: ["string_step", 123, true]
+
+ 2. **Step identifier**: Must have either "class" OR "registry_name"
+ - **"registry_name"**: Registered step (preferred)
+ Example: {"registry_name": "normalize_step", "config": {...}}
+ - **"class"**: Full import path
+ Example: {"class": "lerobot.processor.normalize.NormalizeStep"}
+ - **If neither**: Invalid step (can't resolve class)
+ - **If both**: Also valid (registry_name takes precedence)
+
+ **Valid Processor Config Examples**:
+ - {"steps": []} - Empty processor
+ - {"steps": [{"registry_name": "normalize"}]} - Registry step
+ - {"steps": [{"class": "my.module.Step"}]} - Import step
+ - {"name": "MyProcessor", "steps": [...]} - With name
+
+ **Invalid Config Examples**:
+ - {"type": "act"} - Missing "steps"
+ - {"steps": "normalize"} - Steps not a list
+ - {"steps": [{}]} - Step missing class/registry_name
+ - {"steps": ["string"]} - Step not a dict
+
+ Args:
+ config: The configuration dictionary to validate
+
+ Returns:
+ True if config follows valid DataProcessorPipeline format, False otherwise
+ """
+ # Must have a "steps" field with a list of step configurations
+ if not isinstance(config.get("steps"), list):
+ return False
+
+ steps = config["steps"]
+ if len(steps) == 0:
+ return True # Empty processor is valid
+
+ # Each step must be a dict with either "class" or "registry_name"
+ for step in steps:
+ if not isinstance(step, dict):
+ return False
+ if not ("class" in step or "registry_name" in step):
+ return False
+
+ return True
+
+ @classmethod
+ def _suggest_processor_migration(cls, model_path: str | Path, original_error: str) -> None:
+ """Raise migration error when we detect JSON files but no processor configs.
+
+ This method is called when migration detection determines that a model
+ directory contains configuration files but none are valid processor configs.
+ This typically indicates an old LeRobot model that needs migration.
+
+ **When this is called**:
+ - User tries to load DataProcessorPipeline from local directory
+ - Directory contains JSON configuration files
+ - None of the JSON files follow processor config format
+ - _should_suggest_migration() returned True
+
+ **Migration Command Generation**:
+ - Constructs exact command user needs to run
+ - Uses the migration script: migrate_policy_normalization.py
+ - Includes the model path automatically
+ - Example: "python src/lerobot/processor/migrate_policy_normalization.py --pretrained-path /models/old_model"
+
+ **Error Structure**:
+ - **Always raises**: ProcessorMigrationError (never returns)
+ - **Includes**: model_path, migration_command, original_error
+ - **Purpose**: Force user attention to migration need
+ - **User experience**: Clear actionable error with exact command to run
+
+ **Migration Process**:
+ The suggested command will:
+ 1. Extract normalization stats from old model
+ 2. Create new processor configs (preprocessor + postprocessor)
+ 3. Remove normalization layers from model
+ 4. Save migrated model with processor pipeline
+
+ Args:
+ model_path: Path to the model directory needing migration
+ original_error: The error that triggered migration detection (for context)
+
+ Raises:
+ ProcessorMigrationError: Always raised (this method never returns normally)
+ """
+ migration_command = (
+ f"python src/lerobot/processor/migrate_policy_normalization.py --pretrained-path {model_path}"
+ )
+
+ raise ProcessorMigrationError(model_path, migration_command, original_error)
+
+ def __len__(self) -> int:
+ """Returns the number of steps in the pipeline."""
+ return len(self.steps)
+
+ def __getitem__(self, idx: int | slice) -> ProcessorStep | DataProcessorPipeline[TInput, TOutput]:
+ """Retrieves a step or a sub-pipeline by index or slice.
+
+ Args:
+ idx: An integer index or a slice object.
+
+ Returns:
+ A `ProcessorStep` if `idx` is an integer, or a new `DataProcessorPipeline`
+ containing the sliced steps.
+ """
+ if isinstance(idx, slice):
+ # Return a new pipeline instance with the sliced steps.
+ return DataProcessorPipeline(
+ steps=self.steps[idx],
+ name=self.name,
+ to_transition=self.to_transition,
+ to_output=self.to_output,
+ before_step_hooks=self.before_step_hooks.copy(),
+ after_step_hooks=self.after_step_hooks.copy(),
+ )
+ return self.steps[idx]
+
+ def register_before_step_hook(self, fn: Callable[[int, EnvTransition], None]):
+ """Registers a function to be called before each step.
+
+ Args:
+ fn: A callable that accepts the step index and the current transition.
+ """
+ self.before_step_hooks.append(fn)
+
+ def unregister_before_step_hook(self, fn: Callable[[int, EnvTransition], None]):
+ """Unregisters a 'before_step' hook.
+
+ Args:
+ fn: The exact function object that was previously registered.
+
+ Raises:
+ ValueError: If the hook is not found in the list.
+ """
+ try:
+ self.before_step_hooks.remove(fn)
+ except ValueError:
+ raise ValueError(
+ f"Hook {fn} not found in before_step_hooks. Make sure to pass the exact same function reference."
+ ) from None
+
+ def register_after_step_hook(self, fn: Callable[[int, EnvTransition], None]):
+ """Registers a function to be called after each step.
+
+ Args:
+ fn: A callable that accepts the step index and the current transition.
+ """
+ self.after_step_hooks.append(fn)
+
+ def unregister_after_step_hook(self, fn: Callable[[int, EnvTransition], None]):
+ """Unregisters an 'after_step' hook.
+
+ Args:
+ fn: The exact function object that was previously registered.
+
+ Raises:
+ ValueError: If the hook is not found in the list.
+ """
+ try:
+ self.after_step_hooks.remove(fn)
+ except ValueError:
+ raise ValueError(
+ f"Hook {fn} not found in after_step_hooks. Make sure to pass the exact same function reference."
+ ) from None
+
+ def reset(self):
+ """Resets the state of all stateful steps in the pipeline."""
+ for step in self.steps:
+ if hasattr(step, "reset"):
+ step.reset()
+
+ def __repr__(self) -> str:
+ """Provides a concise string representation of the pipeline."""
+ step_names = [step.__class__.__name__ for step in self.steps]
+
+ if not step_names:
+ steps_repr = "steps=0: []"
+ elif len(step_names) <= 3:
+ steps_repr = f"steps={len(step_names)}: [{', '.join(step_names)}]"
+ else:
+ # For long pipelines, show the first, second, and last steps.
+ displayed = f"{step_names[0]}, {step_names[1]}, ..., {step_names[-1]}"
+ steps_repr = f"steps={len(step_names)}: [{displayed}]"
+
+ parts = [f"name='{self.name}'", steps_repr]
+
+ return f"DataProcessorPipeline({', '.join(parts)})"
+
+ def __post_init__(self):
+ """Validates that all provided steps are instances of `ProcessorStep`."""
+ for i, step in enumerate(self.steps):
+ if not isinstance(step, ProcessorStep):
+ raise TypeError(f"Step {i} ({type(step).__name__}) must inherit from ProcessorStep")
+
+ def transform_features(
+ self, initial_features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """Applies feature transformations from all steps sequentially.
+
+ This method propagates a feature description dictionary through each step's
+ `transform_features` method, allowing the pipeline to statically determine
+ the output feature specification without processing any real data.
+
+ Args:
+ initial_features: A dictionary describing the initial features.
+
+ Returns:
+ The final feature description after all transformations.
+ """
+ features: dict[PipelineFeatureType, dict[str, PolicyFeature]] = deepcopy(initial_features)
+
+ for _, step in enumerate(self.steps):
+ out = step.transform_features(features)
+ features = out
+ return features
+
+ # Convenience methods for processing individual parts of a transition.
+ def process_observation(self, observation: RobotObservation) -> RobotObservation:
+ """Processes only the observation part of a transition through the pipeline.
+
+ Args:
+ observation: The observation dictionary.
+
+ Returns:
+ The processed observation dictionary.
+ """
+ transition: EnvTransition = create_transition(observation=observation)
+ transformed_transition = self._forward(transition)
+ return transformed_transition[TransitionKey.OBSERVATION]
+
+ def process_action(
+ self, action: PolicyAction | RobotAction | EnvAction
+ ) -> PolicyAction | RobotAction | EnvAction:
+ """Processes only the action part of a transition through the pipeline.
+
+ Args:
+ action: The action data.
+
+ Returns:
+ The processed action.
+ """
+ transition: EnvTransition = create_transition(action=action)
+ transformed_transition = self._forward(transition)
+ return transformed_transition[TransitionKey.ACTION]
+
+ def process_reward(self, reward: float | torch.Tensor) -> float | torch.Tensor:
+ """Processes only the reward part of a transition through the pipeline.
+
+ Args:
+ reward: The reward value.
+
+ Returns:
+ The processed reward.
+ """
+ transition: EnvTransition = create_transition(reward=reward)
+ transformed_transition = self._forward(transition)
+ return transformed_transition[TransitionKey.REWARD]
+
+ def process_done(self, done: bool | torch.Tensor) -> bool | torch.Tensor:
+ """Processes only the done flag of a transition through the pipeline.
+
+ Args:
+ done: The done flag.
+
+ Returns:
+ The processed done flag.
+ """
+ transition: EnvTransition = create_transition(done=done)
+ transformed_transition = self._forward(transition)
+ return transformed_transition[TransitionKey.DONE]
+
+ def process_truncated(self, truncated: bool | torch.Tensor) -> bool | torch.Tensor:
+ """Processes only the truncated flag of a transition through the pipeline.
+
+ Args:
+ truncated: The truncated flag.
+
+ Returns:
+ The processed truncated flag.
+ """
+ transition: EnvTransition = create_transition(truncated=truncated)
+ transformed_transition = self._forward(transition)
+ return transformed_transition[TransitionKey.TRUNCATED]
+
+ def process_info(self, info: dict[str, Any]) -> dict[str, Any]:
+ """Processes only the info dictionary of a transition through the pipeline.
+
+ Args:
+ info: The info dictionary.
+
+ Returns:
+ The processed info dictionary.
+ """
+ transition: EnvTransition = create_transition(info=info)
+ transformed_transition = self._forward(transition)
+ return transformed_transition[TransitionKey.INFO]
+
+ def process_complementary_data(self, complementary_data: dict[str, Any]) -> dict[str, Any]:
+ """Processes only the complementary data part of a transition through the pipeline.
+
+ Args:
+ complementary_data: The complementary data dictionary.
+
+ Returns:
+ The processed complementary data dictionary.
+ """
+ transition: EnvTransition = create_transition(complementary_data=complementary_data)
+ transformed_transition = self._forward(transition)
+ return transformed_transition[TransitionKey.COMPLEMENTARY_DATA]
+
+
+# Type aliases for semantic clarity.
+RobotProcessorPipeline: TypeAlias = DataProcessorPipeline[TInput, TOutput]
+PolicyProcessorPipeline: TypeAlias = DataProcessorPipeline[TInput, TOutput]
+
+
+class ObservationProcessorStep(ProcessorStep, ABC):
+ """An abstract `ProcessorStep` that specifically targets the observation in a transition."""
+
+ @abstractmethod
+ def observation(self, observation: RobotObservation) -> RobotObservation:
+ """Processes an observation dictionary. Subclasses must implement this method.
+
+ Args:
+ observation: The input observation dictionary from the transition.
+
+ Returns:
+ The processed observation dictionary.
+ """
+ ...
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Applies the `observation` method to the transition's observation."""
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ observation = new_transition.get(TransitionKey.OBSERVATION)
+ if observation is None or not isinstance(observation, dict):
+ raise ValueError("ObservationProcessorStep requires an observation in the transition.")
+
+ processed_observation = self.observation(observation.copy())
+ new_transition[TransitionKey.OBSERVATION] = processed_observation
+ return new_transition
+
+
+class ActionProcessorStep(ProcessorStep, ABC):
+ """An abstract `ProcessorStep` that specifically targets the action in a transition."""
+
+ @abstractmethod
+ def action(
+ self, action: PolicyAction | RobotAction | EnvAction
+ ) -> PolicyAction | RobotAction | EnvAction:
+ """Processes an action. Subclasses must implement this method.
+
+ Args:
+ action: The input action from the transition.
+
+ Returns:
+ The processed action.
+ """
+ ...
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Applies the `action` method to the transition's action."""
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ action = new_transition.get(TransitionKey.ACTION)
+ if action is None:
+ raise ValueError("ActionProcessorStep requires an action in the transition.")
+
+ processed_action = self.action(action)
+ new_transition[TransitionKey.ACTION] = processed_action
+ return new_transition
+
+
+class RobotActionProcessorStep(ProcessorStep, ABC):
+ """An abstract `ProcessorStep` for processing a `RobotAction` (a dictionary)."""
+
+ @abstractmethod
+ def action(self, action: RobotAction) -> RobotAction:
+ """Processes a `RobotAction`. Subclasses must implement this method.
+
+ Args:
+ action: The input `RobotAction` dictionary.
+
+ Returns:
+ The processed `RobotAction`.
+ """
+ ...
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Applies the `action` method to the transition's action, ensuring it's a `RobotAction`."""
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ action = new_transition.get(TransitionKey.ACTION)
+ if action is None or not isinstance(action, dict):
+ raise ValueError(f"Action should be a RobotAction type (dict), but got {type(action)}")
+
+ processed_action = self.action(action.copy())
+ new_transition[TransitionKey.ACTION] = processed_action
+ return new_transition
+
+
+class PolicyActionProcessorStep(ProcessorStep, ABC):
+ """An abstract `ProcessorStep` for processing a `PolicyAction` (a tensor or dict of tensors)."""
+
+ @abstractmethod
+ def action(self, action: PolicyAction) -> PolicyAction:
+ """Processes a `PolicyAction`. Subclasses must implement this method.
+
+ Args:
+ action: The input `PolicyAction`.
+
+ Returns:
+ The processed `PolicyAction`.
+ """
+ ...
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Applies the `action` method to the transition's action, ensuring it's a `PolicyAction`."""
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ action = new_transition.get(TransitionKey.ACTION)
+ if not isinstance(action, PolicyAction):
+ raise ValueError(f"Action should be a PolicyAction type (tensor), but got {type(action)}")
+
+ processed_action = self.action(action)
+ new_transition[TransitionKey.ACTION] = processed_action
+ return new_transition
+
+
+class RewardProcessorStep(ProcessorStep, ABC):
+ """An abstract `ProcessorStep` that specifically targets the reward in a transition."""
+
+ @abstractmethod
+ def reward(self, reward) -> float | torch.Tensor:
+ """Processes a reward. Subclasses must implement this method.
+
+ Args:
+ reward: The input reward from the transition.
+
+ Returns:
+ The processed reward.
+ """
+ ...
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Applies the `reward` method to the transition's reward."""
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ reward = new_transition.get(TransitionKey.REWARD)
+ if reward is None:
+ raise ValueError("RewardProcessorStep requires a reward in the transition.")
+
+ processed_reward = self.reward(reward)
+ new_transition[TransitionKey.REWARD] = processed_reward
+ return new_transition
+
+
+class DoneProcessorStep(ProcessorStep, ABC):
+ """An abstract `ProcessorStep` that specifically targets the 'done' flag in a transition."""
+
+ @abstractmethod
+ def done(self, done) -> bool | torch.Tensor:
+ """Processes a 'done' flag. Subclasses must implement this method.
+
+ Args:
+ done: The input 'done' flag from the transition.
+
+ Returns:
+ The processed 'done' flag.
+ """
+ ...
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Applies the `done` method to the transition's 'done' flag."""
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ done = new_transition.get(TransitionKey.DONE)
+ if done is None:
+ raise ValueError("DoneProcessorStep requires a done flag in the transition.")
+
+ processed_done = self.done(done)
+ new_transition[TransitionKey.DONE] = processed_done
+ return new_transition
+
+
+class TruncatedProcessorStep(ProcessorStep, ABC):
+ """An abstract `ProcessorStep` that specifically targets the 'truncated' flag in a transition."""
+
+ @abstractmethod
+ def truncated(self, truncated) -> bool | torch.Tensor:
+ """Processes a 'truncated' flag. Subclasses must implement this method.
+
+ Args:
+ truncated: The input 'truncated' flag from the transition.
+
+ Returns:
+ The processed 'truncated' flag.
+ """
+ ...
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Applies the `truncated` method to the transition's 'truncated' flag."""
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ truncated = new_transition.get(TransitionKey.TRUNCATED)
+ if truncated is None:
+ raise ValueError("TruncatedProcessorStep requires a truncated flag in the transition.")
+
+ processed_truncated = self.truncated(truncated)
+ new_transition[TransitionKey.TRUNCATED] = processed_truncated
+ return new_transition
+
+
+class InfoProcessorStep(ProcessorStep, ABC):
+ """An abstract `ProcessorStep` that specifically targets the 'info' dictionary in a transition."""
+
+ @abstractmethod
+ def info(self, info) -> dict[str, Any]:
+ """Processes an 'info' dictionary. Subclasses must implement this method.
+
+ Args:
+ info: The input 'info' dictionary from the transition.
+
+ Returns:
+ The processed 'info' dictionary.
+ """
+ ...
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Applies the `info` method to the transition's 'info' dictionary."""
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ info = new_transition.get(TransitionKey.INFO)
+ if info is None or not isinstance(info, dict):
+ raise ValueError("InfoProcessorStep requires an info dictionary in the transition.")
+
+ processed_info = self.info(info.copy())
+ new_transition[TransitionKey.INFO] = processed_info
+ return new_transition
+
+
+class ComplementaryDataProcessorStep(ProcessorStep, ABC):
+ """An abstract `ProcessorStep` that targets the 'complementary_data' in a transition."""
+
+ @abstractmethod
+ def complementary_data(self, complementary_data) -> dict[str, Any]:
+ """Processes a 'complementary_data' dictionary. Subclasses must implement this method.
+
+ Args:
+ complementary_data: The input 'complementary_data' from the transition.
+
+ Returns:
+ The processed 'complementary_data' dictionary.
+ """
+ ...
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Applies the `complementary_data` method to the transition's data."""
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ complementary_data = new_transition.get(TransitionKey.COMPLEMENTARY_DATA)
+ if complementary_data is None or not isinstance(complementary_data, dict):
+ raise ValueError("ComplementaryDataProcessorStep requires complementary data in the transition.")
+
+ processed_complementary_data = self.complementary_data(complementary_data.copy())
+ new_transition[TransitionKey.COMPLEMENTARY_DATA] = processed_complementary_data
+ return new_transition
+
+
+class IdentityProcessorStep(ProcessorStep):
+ """A no-op processor step that returns the input transition and features unchanged.
+
+ This can be useful as a placeholder or for debugging purposes.
+ """
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """Returns the transition without modification."""
+ return transition
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """Returns the features without modification."""
+ return features
diff --git a/lerobot/src/lerobot/processor/policy_robot_bridge.py b/lerobot/src/lerobot/processor/policy_robot_bridge.py
new file mode 100644
index 0000000000000000000000000000000000000000..42289ae8828c40bad4c984b35e47e8cc4db1c78b
--- /dev/null
+++ b/lerobot/src/lerobot/processor/policy_robot_bridge.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import asdict, dataclass
+from typing import Any
+
+import torch
+
+from lerobot.configs.types import FeatureType, PipelineFeatureType, PolicyFeature
+from lerobot.processor import ActionProcessorStep, PolicyAction, ProcessorStepRegistry, RobotAction
+from lerobot.utils.constants import ACTION
+
+
+@dataclass
+@ProcessorStepRegistry.register("robot_action_to_policy_action_processor")
+class RobotActionToPolicyActionProcessorStep(ActionProcessorStep):
+ """Processor step to map a dictionary to a tensor action."""
+
+ motor_names: list[str]
+
+ def action(self, action: RobotAction) -> PolicyAction:
+ if len(self.motor_names) != len(action):
+ raise ValueError(f"Action must have {len(self.motor_names)} elements, got {len(action)}")
+ return torch.tensor([action[f"{name}.pos"] for name in self.motor_names])
+
+ def get_config(self) -> dict[str, Any]:
+ return asdict(self)
+
+ def transform_features(self, features):
+ features[PipelineFeatureType.ACTION][ACTION] = PolicyFeature(
+ type=FeatureType.ACTION, shape=(len(self.motor_names),)
+ )
+ return features
+
+
+@dataclass
+@ProcessorStepRegistry.register("policy_action_to_robot_action_processor")
+class PolicyActionToRobotActionProcessorStep(ActionProcessorStep):
+ """Processor step to map a policy action to a robot action."""
+
+ motor_names: list[str]
+
+ def action(self, action: PolicyAction) -> RobotAction:
+ if len(self.motor_names) != len(action):
+ raise ValueError(f"Action must have {len(self.motor_names)} elements, got {len(action)}")
+ return {f"{name}.pos": action[i] for i, name in enumerate(self.motor_names)}
+
+ def get_config(self) -> dict[str, Any]:
+ return asdict(self)
+
+ def transform_features(self, features):
+ for name in self.motor_names:
+ features[PipelineFeatureType.ACTION][f"{name}.pos"] = PolicyFeature(
+ type=FeatureType.ACTION, shape=(1,)
+ )
+ return features
diff --git a/lerobot/src/lerobot/processor/rename_processor.py b/lerobot/src/lerobot/processor/rename_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0aa4070b865319b1ef8363afe68502016dad400
--- /dev/null
+++ b/lerobot/src/lerobot/processor/rename_processor.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from copy import deepcopy
+from dataclasses import dataclass, field
+from typing import Any
+
+from lerobot.configs.types import PipelineFeatureType, PolicyFeature
+
+from .pipeline import ObservationProcessorStep, ProcessorStepRegistry
+
+
+@dataclass
+@ProcessorStepRegistry.register(name="rename_observations_processor")
+class RenameObservationsProcessorStep(ObservationProcessorStep):
+ """
+ A processor step that renames keys in an observation dictionary.
+
+ This step is useful for creating a standardized data interface by mapping keys
+ from an environment's format to the format expected by a LeRobot policy or
+ other downstream components.
+
+ Attributes:
+ rename_map: A dictionary mapping from old key names to new key names.
+ Keys present in an observation that are not in this map will
+ be kept with their original names.
+ """
+
+ rename_map: dict[str, str] = field(default_factory=dict)
+
+ def observation(self, observation):
+ processed_obs = {}
+ for key, value in observation.items():
+ if key in self.rename_map:
+ processed_obs[self.rename_map[key]] = value
+ else:
+ processed_obs[key] = value
+
+ return processed_obs
+
+ def get_config(self) -> dict[str, Any]:
+ return {"rename_map": self.rename_map}
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """Transforms:
+ - Each key in the observation that appears in `rename_map` is renamed to its value.
+ - Keys not in `rename_map` remain unchanged.
+ """
+ new_features: dict[PipelineFeatureType, dict[str, PolicyFeature]] = features.copy()
+ new_features[PipelineFeatureType.OBSERVATION] = {
+ self.rename_map.get(k, k): v for k, v in features[PipelineFeatureType.OBSERVATION].items()
+ }
+ return new_features
+
+
+def rename_stats(stats: dict[str, dict[str, Any]], rename_map: dict[str, str]) -> dict[str, dict[str, Any]]:
+ """
+ Renames the top-level keys in a statistics dictionary using a provided mapping.
+
+ This is a helper function typically used to keep normalization statistics
+ consistent with renamed observation or action features. It performs a defensive
+ deep copy to avoid modifying the original `stats` dictionary.
+
+ Args:
+ stats: A nested dictionary of statistics, where top-level keys are
+ feature names (e.g., `{"observation.state": {"mean": 0.5}}`).
+ rename_map: A dictionary mapping old feature names to new feature names.
+
+ Returns:
+ A new statistics dictionary with its top-level keys renamed. Returns an
+ empty dictionary if the input `stats` is empty.
+ """
+ if not stats:
+ return {}
+ renamed: dict[str, dict[str, Any]] = {}
+ for old_key, sub_stats in stats.items():
+ new_key = rename_map.get(old_key, old_key)
+ renamed[new_key] = deepcopy(sub_stats) if sub_stats is not None else {}
+ return renamed
diff --git a/lerobot/src/lerobot/processor/tokenizer_processor.py b/lerobot/src/lerobot/processor/tokenizer_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..9eb93db1f5f414bbbf6f45517e375de837f62c44
--- /dev/null
+++ b/lerobot/src/lerobot/processor/tokenizer_processor.py
@@ -0,0 +1,530 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+This script defines a processor for tokenizing natural language instructions from an environment transition.
+
+It uses a tokenizer from the Hugging Face `transformers` library to convert task descriptions (text) into
+token IDs and attention masks, which are then added to the observation dictionary.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any
+
+import torch
+
+from lerobot.configs.types import FeatureType, PipelineFeatureType, PolicyFeature
+from lerobot.utils.constants import (
+ ACTION_TOKEN_MASK,
+ ACTION_TOKENS,
+ OBS_LANGUAGE_ATTENTION_MASK,
+ OBS_LANGUAGE_TOKENS,
+)
+from lerobot.utils.import_utils import _transformers_available
+
+from .core import EnvTransition, RobotObservation, TransitionKey
+from .pipeline import ActionProcessorStep, ObservationProcessorStep, ProcessorStepRegistry
+
+# Conditional import for type checking and lazy loading
+if TYPE_CHECKING or _transformers_available:
+ from transformers import AutoProcessor, AutoTokenizer
+else:
+ AutoProcessor = None
+ AutoTokenizer = None
+
+
+@dataclass
+@ProcessorStepRegistry.register(name="tokenizer_processor")
+class TokenizerProcessorStep(ObservationProcessorStep):
+ """
+ Processor step to tokenize a natural language task description.
+
+ This step extracts a task string from the `complementary_data` of an `EnvTransition`,
+ tokenizes it using a Hugging Face `transformers` tokenizer, and adds the resulting
+ token IDs and attention mask to the `observation` dictionary.
+
+ Requires the `transformers` library to be installed.
+
+ Attributes:
+ tokenizer_name: The name of a pretrained tokenizer from the Hugging Face Hub (e.g., "bert-base-uncased").
+ tokenizer: A pre-initialized tokenizer object. If provided, `tokenizer_name` is ignored.
+ max_length: The maximum length to pad or truncate sequences to.
+ task_key: The key in `complementary_data` where the task string is stored.
+ padding_side: The side to pad on ('left' or 'right').
+ padding: The padding strategy ('max_length', 'longest', etc.).
+ truncation: Whether to truncate sequences longer than `max_length`.
+ input_tokenizer: The internal tokenizer instance, loaded during initialization.
+ """
+
+ tokenizer_name: str | None = None
+ tokenizer: Any | None = None # Use `Any` for compatibility without a hard dependency
+ max_length: int = 512
+ task_key: str = "task"
+ padding_side: str = "right"
+ padding: str = "max_length"
+ truncation: bool = True
+
+ # Internal tokenizer instance (not part of the config)
+ input_tokenizer: Any = field(default=None, init=False, repr=False)
+
+ def __post_init__(self):
+ """
+ Initializes the tokenizer after the dataclass is created.
+
+ It checks for the availability of the `transformers` library and loads the tokenizer
+ either from a provided object or by name from the Hugging Face Hub.
+
+ Raises:
+ ImportError: If the `transformers` library is not installed.
+ ValueError: If neither `tokenizer` nor `tokenizer_name` is provided.
+ """
+ if not _transformers_available:
+ raise ImportError(
+ "The 'transformers' library is not installed. "
+ "Please install it with `pip install 'lerobot[transformers-dep]'` to use TokenizerProcessorStep."
+ )
+
+ if self.tokenizer is not None:
+ # Use provided tokenizer object directly
+ self.input_tokenizer = self.tokenizer
+ elif self.tokenizer_name is not None:
+ if AutoTokenizer is None:
+ raise ImportError("AutoTokenizer is not available")
+ self.input_tokenizer = AutoTokenizer.from_pretrained(self.tokenizer_name)
+ else:
+ raise ValueError(
+ "Either 'tokenizer' or 'tokenizer_name' must be provided. "
+ "Pass a tokenizer object directly or a tokenizer name to auto-load."
+ )
+
+ def get_task(self, transition: EnvTransition) -> list[str] | None:
+ """
+ Extracts the task description(s) from the transition's complementary data.
+
+ Args:
+ transition: The environment transition.
+
+ Returns:
+ A list of task strings, or None if the task key is not found or the value is None.
+ """
+ complementary_data = transition.get(TransitionKey.COMPLEMENTARY_DATA)
+ if complementary_data is None:
+ raise ValueError("Complementary data is None so no task can be extracted from it")
+
+ task = complementary_data[self.task_key]
+ if task is None:
+ raise ValueError("Task extracted from Complementary data is None")
+
+ # Standardize to a list of strings for the tokenizer
+ if isinstance(task, str):
+ return [task]
+ elif isinstance(task, list) and all(isinstance(t, str) for t in task):
+ return task
+
+ return None
+
+ def observation(self, observation: RobotObservation) -> RobotObservation:
+ """
+ Tokenizes the task description and adds it to the observation dictionary.
+
+ This method retrieves the task, tokenizes it, moves the resulting tensors to the
+ same device as other data in the transition, and updates the observation.
+
+ Args:
+ observation: The original observation dictionary.
+
+ Returns:
+ The updated observation dictionary including token IDs and an attention mask.
+ """
+ task = self.get_task(self.transition)
+ if task is None:
+ raise ValueError("Task cannot be None")
+
+ # Tokenize the task (this will create CPU tensors)
+ tokenized_prompt = self._tokenize_text(task)
+
+ # Detect the device from existing tensors in the transition to ensure consistency
+ target_device = self._detect_device(self.transition)
+
+ # Move new tokenized tensors to the detected device
+ if target_device is not None:
+ tokenized_prompt = {
+ k: v.to(target_device) if isinstance(v, torch.Tensor) else v
+ for k, v in tokenized_prompt.items()
+ }
+
+ # Create a new observation dict to avoid modifying the original in place
+ new_observation = dict(observation)
+
+ # Add tokenized data to the observation
+ new_observation[OBS_LANGUAGE_TOKENS] = tokenized_prompt["input_ids"]
+ new_observation[OBS_LANGUAGE_ATTENTION_MASK] = tokenized_prompt["attention_mask"].to(dtype=torch.bool)
+
+ return new_observation
+
+ def _detect_device(self, transition: EnvTransition) -> torch.device | None:
+ """
+ Detects the torch.device from existing tensors in the transition.
+
+ It checks tensors in the observation dictionary first, then the action tensor.
+
+ Args:
+ transition: The environment transition.
+
+ Returns:
+ The detected `torch.device`, or None if no tensors are found.
+ """
+ # Check observation tensors first (most likely place to find tensors)
+ observation = transition.get(TransitionKey.OBSERVATION)
+ if observation:
+ for value in observation.values():
+ if isinstance(value, torch.Tensor):
+ return value.device
+
+ # Fallback to checking the action tensor
+ action = transition.get(TransitionKey.ACTION)
+ if isinstance(action, torch.Tensor):
+ return action.device
+
+ return None # No tensors found, default will be CPU
+
+ def _tokenize_text(self, text: str | list[str]) -> dict[str, torch.Tensor]:
+ """
+ A wrapper around the tokenizer call.
+
+ Args:
+ text: A string or list of strings to tokenize.
+
+ Returns:
+ A dictionary containing tokenized 'input_ids' and 'attention_mask' as PyTorch tensors.
+ """
+ return self.input_tokenizer(
+ text,
+ max_length=self.max_length,
+ truncation=self.truncation,
+ padding=self.padding,
+ padding_side=self.padding_side,
+ return_tensors="pt",
+ )
+
+ def get_config(self) -> dict[str, Any]:
+ """
+ Returns the serializable configuration of the processor.
+
+ Note: The tokenizer object itself is not serialized. If the processor was initialized
+ with a tokenizer name, that name will be included in the config.
+
+ Returns:
+ A dictionary with the processor's configuration parameters.
+ """
+ config = {
+ "max_length": self.max_length,
+ "task_key": self.task_key,
+ "padding_side": self.padding_side,
+ "padding": self.padding,
+ "truncation": self.truncation,
+ }
+
+ # Only save tokenizer_name if it was used to create the tokenizer
+ if self.tokenizer_name is not None and self.tokenizer is None:
+ config["tokenizer_name"] = self.tokenizer_name
+
+ return config
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """
+ Adds feature definitions for the language tokens and attention mask.
+
+ This updates the policy features dictionary to include the new data added to the
+ observation, ensuring downstream components are aware of their shape and type.
+
+ Args:
+ features: The dictionary of existing policy features.
+
+ Returns:
+ The updated dictionary of policy features.
+ """
+ # Add a feature for the token IDs if it doesn't already exist
+ if OBS_LANGUAGE_TOKENS not in features[PipelineFeatureType.OBSERVATION]:
+ features[PipelineFeatureType.OBSERVATION][OBS_LANGUAGE_TOKENS] = PolicyFeature(
+ type=FeatureType.LANGUAGE, shape=(self.max_length,)
+ )
+
+ # Add a feature for the attention mask if it doesn't already exist
+ if OBS_LANGUAGE_ATTENTION_MASK not in features[PipelineFeatureType.OBSERVATION]:
+ features[PipelineFeatureType.OBSERVATION][OBS_LANGUAGE_ATTENTION_MASK] = PolicyFeature(
+ type=FeatureType.LANGUAGE, shape=(self.max_length,)
+ )
+
+ return features
+
+
+@dataclass
+@ProcessorStepRegistry.register(name="action_tokenizer_processor")
+class ActionTokenizerProcessorStep(ActionProcessorStep):
+ """
+ Processor step to tokenize action data using a fast action tokenizer.
+
+ This step takes action tensors from an `EnvTransition`, tokenizes them using
+ a Hugging Face `transformers` AutoProcessor (such as the Physical Intelligence "fast" tokenizer),
+ and returns the tokenized action.
+
+ Requires the `transformers` library to be installed.
+
+ Attributes:
+ tokenizer_name: The name of a pretrained processor from the Hugging Face Hub (e.g., "physical-intelligence/fast").
+ tokenizer: A pre-initialized processor/tokenizer object. If provided, `tokenizer_name` is ignored.
+ trust_remote_code: Whether to trust remote code when loading the tokenizer (required for some tokenizers).
+ action_tokenizer: The internal tokenizer/processor instance, loaded during initialization.
+ paligemma_tokenizer_name: The name of a pretrained PaliGemma tokenizer from the Hugging Face Hub (e.g., "google/paligemma-3b-pt-224").
+ """
+
+ action_tokenizer_name: str | None = None
+ action_tokenizer_input_object: Any | None = None
+ trust_remote_code: bool = True
+ max_action_tokens: int = 256
+ fast_skip_tokens: int = 128
+ paligemma_tokenizer_name: str = "google/paligemma-3b-pt-224"
+ # Internal tokenizer instance (not part of the config)
+ action_tokenizer: Any = field(default=None, init=False, repr=False)
+ _paligemma_tokenizer: Any = field(default=None, init=False, repr=False)
+
+ def __post_init__(self):
+ """
+ Initializes the action tokenizer after the dataclass is created.
+
+ It checks for the availability of the `transformers` library and loads the tokenizer
+ either from a provided object or by name from the Hugging Face Hub.
+
+ Raises:
+ ImportError: If the `transformers` library is not installed.
+ ValueError: If neither `tokenizer` nor `tokenizer_name` is provided.
+ """
+ if not _transformers_available:
+ raise ImportError(
+ "The 'transformers' library is not installed. "
+ "Please install it with `pip install 'lerobot[transformers-dep]'` to use ActionTokenizerProcessorStep."
+ )
+
+ if self.action_tokenizer_input_object is not None:
+ self.action_tokenizer = self.action_tokenizer_input_object
+
+ elif self.action_tokenizer_name is not None:
+ if AutoProcessor is None:
+ raise ImportError("AutoProcessor is not available")
+ self.action_tokenizer = AutoProcessor.from_pretrained(
+ self.action_tokenizer_name, trust_remote_code=self.trust_remote_code
+ )
+ else:
+ raise ValueError(
+ "Either 'action_tokenizer' or 'action_tokenizer_name' must be provided. "
+ "Pass a tokenizer object directly or a tokenizer name to auto-load."
+ )
+
+ self._paligemma_tokenizer = AutoTokenizer.from_pretrained(
+ self.paligemma_tokenizer_name,
+ trust_remote_code=self.trust_remote_code,
+ add_eos_token=True,
+ add_bos_token=False,
+ )
+
+ def __call__(self, transition: EnvTransition) -> EnvTransition:
+ """
+ Applies action tokenization to the transition.
+
+ This overrides the base class to handle both tokens and mask.
+
+ Args:
+ transition: The input transition with action data.
+
+ Returns:
+ The processed transition with tokenized actions and mask in complementary data.
+ """
+ self._current_transition = transition.copy()
+ new_transition = self._current_transition
+
+ action = new_transition.get(TransitionKey.ACTION)
+ if action is None:
+ # During inference, no action is available, skip tokenization
+ return new_transition
+
+ # Tokenize and get both tokens and mask
+ tokens, mask = self._tokenize_action(action)
+
+ # Store mask in complementary data
+ complementary_data = new_transition.get(TransitionKey.COMPLEMENTARY_DATA, {})
+ if complementary_data is None:
+ complementary_data = {}
+ complementary_data[ACTION_TOKEN_MASK] = mask
+ complementary_data[ACTION_TOKENS] = tokens
+ new_transition[TransitionKey.COMPLEMENTARY_DATA] = complementary_data
+ return new_transition
+
+ def _act_tokens_to_paligemma_tokens(self, tokens: torch.Tensor) -> torch.Tensor:
+ """
+ Converts action tokens to PaliGemma tokens.
+ """
+ return self._paligemma_tokenizer.vocab_size - 1 - self.fast_skip_tokens - tokens
+
+ def _tokenize_action(self, action: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Tokenizes the action tensor and creates a mask.
+
+ Args:
+ action: The input action tensor to tokenize. Shape: (B, H, action_dim) or (H, action_dim,)
+
+ Returns:
+ A tuple of (tokens, mask) where:
+ - tokens: Tensor of token IDs with shape (B, max_action_tokens)
+ - mask: Boolean mask with shape (B, max_action_tokens), True for real tokens, False for padding
+ """
+ if action is None:
+ raise ValueError("Action cannot be None")
+
+ # Get the device and dtype of the input action
+ device = action.device if isinstance(action, torch.Tensor) else None
+
+ # Handle single sample (add batch dimension)
+ single_sample = action.dim() == 1
+ if single_sample:
+ action = action.unsqueeze(0)
+
+ batch_size = action.shape[0]
+
+ # Tokenize the action batch
+ # The fast tokenizer expects action data and returns token IDs
+ tokens_list = []
+ masks_list = []
+
+ for i in range(batch_size):
+ # Tokenize single action (move to CPU first as tokenizer uses scipy which requires numpy)
+ action_cpu = action[i : i + 1].cpu()
+ tokens = self.action_tokenizer(action_cpu)
+
+ # Convert to numpy array if it's a list
+ if isinstance(tokens, list) or not isinstance(tokens, torch.Tensor):
+ tokens = torch.tensor(tokens, dtype=torch.long, device=action.device)
+ else:
+ # Move tokens back to the same device as input action
+ tokens = tokens.to(device=action.device)
+
+ # Flatten to 1D if needed
+ if tokens.dim() > 1:
+ tokens = tokens.flatten()
+
+ bos_id = self._paligemma_tokenizer.bos_token_id
+ # add bos
+ tokens = torch.cat(
+ [
+ torch.tensor([bos_id], device=action.device),
+ torch.tensor(
+ self._paligemma_tokenizer.encode("Action: ", add_special_tokens=False),
+ device=action.device,
+ ),
+ self._act_tokens_to_paligemma_tokens(tokens),
+ torch.tensor(self._paligemma_tokenizer.encode("|"), device=action.device),
+ ]
+ )
+
+ # Truncate or pad to max_action_tokens
+ if len(tokens) > self.max_action_tokens:
+ logging.warning(
+ f"Token length ({len(tokens)}) exceeds max length ({self.max_action_tokens}), truncating. "
+ "Consider increasing the `max_action_tokens` in your model config if this happens frequently."
+ )
+ tokens = tokens[: self.max_action_tokens]
+ mask = torch.ones(self.max_action_tokens, dtype=torch.bool, device=action.device)
+ else:
+ mask = torch.cat(
+ [
+ torch.ones(len(tokens), dtype=torch.bool, device=action.device),
+ torch.zeros(
+ self.max_action_tokens - len(tokens), dtype=torch.bool, device=action.device
+ ),
+ ]
+ )
+ # Pad tokens with zeros
+ tokens = torch.nn.functional.pad(tokens, (0, self.max_action_tokens - len(tokens)), value=0)
+
+ tokens_list.append(tokens)
+ masks_list.append(mask)
+
+ # Stack into batched tensors
+ tokens_batch = torch.stack(tokens_list, dim=0) # (B, max_action_tokens)
+ masks_batch = torch.stack(masks_list, dim=0) # (B, max_action_tokens)
+
+ # Remove batch dimension if input was single sample
+ if single_sample:
+ tokens_batch = tokens_batch.squeeze(0)
+ masks_batch = masks_batch.squeeze(0)
+
+ # Move to the same device as the input
+ if device is not None:
+ tokens_batch = tokens_batch.to(device)
+ masks_batch = masks_batch.to(device)
+
+ return tokens_batch, masks_batch
+
+ def action(self, action: torch.Tensor) -> torch.Tensor:
+ """
+ This method is not used since we override __call__.
+ Required by ActionProcessorStep ABC.
+ """
+ tokens, _ = self._tokenize_action(action)
+ return tokens
+
+ def get_config(self) -> dict[str, Any]:
+ """
+ Returns the serializable configuration of the processor.
+
+ Note: The tokenizer object itself is not serialized. If the processor was initialized
+ with a tokenizer name, that name will be included in the config.
+
+ Returns:
+ A dictionary with the processor's configuration parameters.
+ """
+ config = {
+ "trust_remote_code": self.trust_remote_code,
+ "max_action_tokens": self.max_action_tokens,
+ }
+
+ # Only save tokenizer_name if it was used to create the tokenizer
+ if self.action_tokenizer_name is not None and self.action_tokenizer_input_object is None:
+ config["action_tokenizer_name"] = self.action_tokenizer_name
+
+ return config
+
+ def transform_features(
+ self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]]
+ ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]:
+ """
+ Updates feature definitions to reflect tokenized actions.
+
+ This updates the policy features dictionary to indicate that the action
+ has been tokenized into a sequence of token IDs with shape (max_action_tokens,).
+
+ Args:
+ features: The dictionary of existing policy features.
+
+ Returns:
+ The updated dictionary of policy features.
+ """
+ return features
diff --git a/lerobot/src/lerobot/robots/hope_jr/__init__.py b/lerobot/src/lerobot/robots/hope_jr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..57aab9e3efa9d2988d22c3112c9ce6f3e6a7de2c
--- /dev/null
+++ b/lerobot/src/lerobot/robots/hope_jr/__init__.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from .config_hope_jr import HopeJrArmConfig, HopeJrHandConfig
+from .hope_jr_arm import HopeJrArm
+from .hope_jr_hand import HopeJrHand
diff --git a/lerobot/src/lerobot/robots/hope_jr/hope_jr_arm.py b/lerobot/src/lerobot/robots/hope_jr/hope_jr_arm.py
new file mode 100644
index 0000000000000000000000000000000000000000..937d0eba831535c4cdc303d79df9111d1214834b
--- /dev/null
+++ b/lerobot/src/lerobot/robots/hope_jr/hope_jr_arm.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import logging
+import time
+from functools import cached_property
+
+from lerobot.cameras.utils import make_cameras_from_configs
+from lerobot.motors import Motor, MotorNormMode
+from lerobot.motors.calibration_gui import RangeFinderGUI
+from lerobot.motors.feetech import (
+ FeetechMotorsBus,
+)
+from lerobot.processor import RobotAction, RobotObservation
+from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected
+
+from ..robot import Robot
+from ..utils import ensure_safe_goal_position
+from .config_hope_jr import HopeJrArmConfig
+
+logger = logging.getLogger(__name__)
+
+
+class HopeJrArm(Robot):
+ config_class = HopeJrArmConfig
+ name = "hope_jr_arm"
+
+ def __init__(self, config: HopeJrArmConfig):
+ super().__init__(config)
+ self.config = config
+ self.bus = FeetechMotorsBus(
+ port=self.config.port,
+ motors={
+ "shoulder_pitch": Motor(1, "sm8512bl", MotorNormMode.RANGE_M100_100),
+ "shoulder_yaw": Motor(2, "sts3250", MotorNormMode.RANGE_M100_100),
+ "shoulder_roll": Motor(3, "sts3250", MotorNormMode.RANGE_M100_100),
+ "elbow_flex": Motor(4, "sts3250", MotorNormMode.RANGE_M100_100),
+ "wrist_roll": Motor(5, "sts3250", MotorNormMode.RANGE_M100_100),
+ "wrist_yaw": Motor(6, "sts3250", MotorNormMode.RANGE_M100_100),
+ "wrist_pitch": Motor(7, "sts3250", MotorNormMode.RANGE_M100_100),
+ },
+ calibration=self.calibration,
+ )
+ self.cameras = make_cameras_from_configs(config.cameras)
+
+ # HACK
+ self.shoulder_pitch = "shoulder_pitch"
+ self.other_motors = [m for m in self.bus.motors if m != "shoulder_pitch"]
+
+ @property
+ def _motors_ft(self) -> dict[str, type]:
+ return {f"{motor}.pos": float for motor in self.bus.motors}
+
+ @property
+ def _cameras_ft(self) -> dict[str, tuple]:
+ return {
+ cam: (self.config.cameras[cam].height, self.config.cameras[cam].width, 3) for cam in self.cameras
+ }
+
+ @cached_property
+ def observation_features(self) -> dict[str, type | tuple]:
+ return {**self._motors_ft, **self._cameras_ft}
+
+ @cached_property
+ def action_features(self) -> dict[str, type]:
+ return self._motors_ft
+
+ @property
+ def is_connected(self) -> bool:
+ return self.bus.is_connected and all(cam.is_connected for cam in self.cameras.values())
+
+ @check_if_already_connected
+ def connect(self, calibrate: bool = True) -> None:
+ """
+ We assume that at connection time, arm is in a rest position,
+ and torque can be safely disabled to run calibration.
+ """
+
+ self.bus.connect(handshake=False)
+ if not self.is_calibrated and calibrate:
+ self.calibrate()
+
+ # Connect the cameras
+ for cam in self.cameras.values():
+ cam.connect()
+
+ self.configure()
+ logger.info(f"{self} connected.")
+
+ @property
+ def is_calibrated(self) -> bool:
+ return self.bus.is_calibrated
+
+ def calibrate(self) -> None:
+ groups = {
+ "all": list(self.bus.motors.keys()),
+ "shoulder": ["shoulder_pitch", "shoulder_yaw", "shoulder_roll"],
+ "elbow": ["elbow_flex"],
+ "wrist": ["wrist_roll", "wrist_yaw", "wrist_pitch"],
+ }
+
+ self.calibration = RangeFinderGUI(self.bus, groups).run()
+ self._save_calibration()
+ print("Calibration saved to", self.calibration_fpath)
+
+ def configure(self) -> None:
+ with self.bus.torque_disabled():
+ self.bus.configure_motors(maximum_acceleration=30, acceleration=30)
+
+ def setup_motors(self) -> None:
+ # TODO: add docstring
+ for motor in reversed(self.bus.motors):
+ input(f"Connect the controller board to the '{motor}' motor only and press enter.")
+ self.bus.setup_motor(motor)
+ print(f"'{motor}' motor id set to {self.bus.motors[motor].id}")
+
+ @check_if_not_connected
+ def get_observation(self) -> RobotObservation:
+ # Read arm position
+ start = time.perf_counter()
+ obs_dict = self.bus.sync_read("Present_Position", self.other_motors)
+ obs_dict[self.shoulder_pitch] = self.bus.read("Present_Position", self.shoulder_pitch)
+ obs_dict = {f"{motor}.pos": val for motor, val in obs_dict.items()}
+ dt_ms = (time.perf_counter() - start) * 1e3
+ logger.debug(f"{self} read state: {dt_ms:.1f}ms")
+
+ # Capture images from cameras
+ for cam_key, cam in self.cameras.items():
+ start = time.perf_counter()
+ obs_dict[cam_key] = cam.async_read()
+ dt_ms = (time.perf_counter() - start) * 1e3
+ logger.debug(f"{self} read {cam_key}: {dt_ms:.1f}ms")
+
+ return obs_dict
+
+ @check_if_not_connected
+ def send_action(self, action: RobotAction) -> RobotAction:
+ goal_pos = {key.removesuffix(".pos"): val for key, val in action.items() if key.endswith(".pos")}
+
+ # Cap goal position when too far away from present position.
+ # /!\ Slower fps expected due to reading from the follower.
+ if self.config.max_relative_target is not None:
+ present_pos = self.bus.sync_read("Present_Position")
+ goal_present_pos = {key: (g_pos, present_pos[key]) for key, g_pos in goal_pos.items()}
+ goal_pos = ensure_safe_goal_position(goal_present_pos, self.config.max_relative_target)
+
+ self.bus.sync_write("Goal_Position", goal_pos)
+ return {f"{motor}.pos": val for motor, val in goal_pos.items()}
+
+ @check_if_not_connected
+ def disconnect(self):
+ self.bus.disconnect(self.config.disable_torque_on_disconnect)
+ for cam in self.cameras.values():
+ cam.disconnect()
+
+ logger.info(f"{self} disconnected.")
diff --git a/lerobot/src/lerobot/robots/hope_jr/hope_jr_hand.py b/lerobot/src/lerobot/robots/hope_jr/hope_jr_hand.py
new file mode 100644
index 0000000000000000000000000000000000000000..82373e5738f49199ff80ab6025d942486fe9d5ca
--- /dev/null
+++ b/lerobot/src/lerobot/robots/hope_jr/hope_jr_hand.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import logging
+import time
+from functools import cached_property
+
+from lerobot.cameras.utils import make_cameras_from_configs
+from lerobot.motors import Motor, MotorNormMode
+from lerobot.motors.calibration_gui import RangeFinderGUI
+from lerobot.motors.feetech import (
+ FeetechMotorsBus,
+)
+from lerobot.processor import RobotAction, RobotObservation
+from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected
+
+from ..robot import Robot
+from .config_hope_jr import HopeJrHandConfig
+
+logger = logging.getLogger(__name__)
+
+RIGHT_HAND_INVERSIONS = [
+ "thumb_mcp",
+ "thumb_dip",
+ "index_ulnar_flexor",
+ "middle_ulnar_flexor",
+ "ring_ulnar_flexor",
+ "ring_pip_dip",
+ "pinky_ulnar_flexor",
+ "pinky_pip_dip",
+]
+
+LEFT_HAND_INVERSIONS = [
+ "thumb_cmc",
+ "thumb_mcp",
+ "thumb_dip",
+ "index_radial_flexor",
+ "index_pip_dip",
+ "middle_radial_flexor",
+ "middle_pip_dip",
+ "ring_radial_flexor",
+ "ring_pip_dip",
+ "pinky_radial_flexor",
+ # "pinky_pip_dip",
+]
+
+
+class HopeJrHand(Robot):
+ config_class = HopeJrHandConfig
+ name = "hope_jr_hand"
+
+ def __init__(self, config: HopeJrHandConfig):
+ super().__init__(config)
+ self.config = config
+ self.bus = FeetechMotorsBus(
+ port=self.config.port,
+ motors={
+ # Thumb
+ "thumb_cmc": Motor(1, "scs0009", MotorNormMode.RANGE_0_100),
+ "thumb_mcp": Motor(2, "scs0009", MotorNormMode.RANGE_0_100),
+ "thumb_pip": Motor(3, "scs0009", MotorNormMode.RANGE_0_100),
+ "thumb_dip": Motor(4, "scs0009", MotorNormMode.RANGE_0_100),
+ # Index
+ "index_radial_flexor": Motor(5, "scs0009", MotorNormMode.RANGE_0_100),
+ "index_ulnar_flexor": Motor(6, "scs0009", MotorNormMode.RANGE_0_100),
+ "index_pip_dip": Motor(7, "scs0009", MotorNormMode.RANGE_0_100),
+ # Middle
+ "middle_radial_flexor": Motor(8, "scs0009", MotorNormMode.RANGE_0_100),
+ "middle_ulnar_flexor": Motor(9, "scs0009", MotorNormMode.RANGE_0_100),
+ "middle_pip_dip": Motor(10, "scs0009", MotorNormMode.RANGE_0_100),
+ # Ring
+ "ring_radial_flexor": Motor(11, "scs0009", MotorNormMode.RANGE_0_100),
+ "ring_ulnar_flexor": Motor(12, "scs0009", MotorNormMode.RANGE_0_100),
+ "ring_pip_dip": Motor(13, "scs0009", MotorNormMode.RANGE_0_100),
+ # Pinky
+ "pinky_radial_flexor": Motor(14, "scs0009", MotorNormMode.RANGE_0_100),
+ "pinky_ulnar_flexor": Motor(15, "scs0009", MotorNormMode.RANGE_0_100),
+ "pinky_pip_dip": Motor(16, "scs0009", MotorNormMode.RANGE_0_100),
+ },
+ calibration=self.calibration,
+ protocol_version=1,
+ )
+ self.cameras = make_cameras_from_configs(config.cameras)
+ self.inverted_motors = RIGHT_HAND_INVERSIONS if config.side == "right" else LEFT_HAND_INVERSIONS
+
+ @property
+ def _motors_ft(self) -> dict[str, type]:
+ return {f"{motor}.pos": float for motor in self.bus.motors}
+
+ @property
+ def _cameras_ft(self) -> dict[str, tuple]:
+ return {
+ cam: (self.config.cameras[cam].height, self.config.cameras[cam].width, 3) for cam in self.cameras
+ }
+
+ @cached_property
+ def observation_features(self) -> dict[str, type | tuple]:
+ return {**self._motors_ft, **self._cameras_ft}
+
+ @cached_property
+ def action_features(self) -> dict[str, type]:
+ return self._motors_ft
+
+ @property
+ def is_connected(self) -> bool:
+ return self.bus.is_connected and all(cam.is_connected for cam in self.cameras.values())
+
+ @check_if_already_connected
+ def connect(self, calibrate: bool = True) -> None:
+ self.bus.connect()
+ if not self.is_calibrated and calibrate:
+ self.calibrate()
+
+ # Connect the cameras
+ for cam in self.cameras.values():
+ cam.connect()
+
+ self.configure()
+ logger.info(f"{self} connected.")
+
+ @property
+ def is_calibrated(self) -> bool:
+ return self.bus.is_calibrated
+
+ def calibrate(self) -> None:
+ fingers = {}
+ for finger in ["thumb", "index", "middle", "ring", "pinky"]:
+ fingers[finger] = [motor for motor in self.bus.motors if motor.startswith(finger)]
+
+ self.calibration = RangeFinderGUI(self.bus, fingers).run()
+ for motor in self.inverted_motors:
+ self.calibration[motor].drive_mode = 1
+ self._save_calibration()
+ print("Calibration saved to", self.calibration_fpath)
+
+ def configure(self) -> None:
+ with self.bus.torque_disabled():
+ self.bus.configure_motors()
+
+ def setup_motors(self) -> None:
+ # TODO: add docstring
+ for motor in self.bus.motors:
+ input(f"Connect the controller board to the '{motor}' motor only and press enter.")
+ self.bus.setup_motor(motor)
+ print(f"'{motor}' motor id set to {self.bus.motors[motor].id}")
+
+ @check_if_not_connected
+ def get_observation(self) -> RobotObservation:
+ obs_dict = {}
+
+ # Read hand position
+ start = time.perf_counter()
+ for motor in self.bus.motors:
+ obs_dict[f"{motor}.pos"] = self.bus.read("Present_Position", motor)
+ dt_ms = (time.perf_counter() - start) * 1e3
+ logger.debug(f"{self} read state: {dt_ms:.1f}ms")
+
+ # Capture images from cameras
+ for cam_key, cam in self.cameras.items():
+ start = time.perf_counter()
+ obs_dict[cam_key] = cam.async_read()
+ dt_ms = (time.perf_counter() - start) * 1e3
+ logger.debug(f"{self} read {cam_key}: {dt_ms:.1f}ms")
+
+ return obs_dict
+
+ @check_if_not_connected
+ def send_action(self, action: RobotAction) -> RobotAction:
+ goal_pos = {key.removesuffix(".pos"): val for key, val in action.items() if key.endswith(".pos")}
+ self.bus.sync_write("Goal_Position", goal_pos)
+ return action
+
+ @check_if_not_connected
+ def disconnect(self):
+ self.bus.disconnect(self.config.disable_torque_on_disconnect)
+ for cam in self.cameras.values():
+ cam.disconnect()
+
+ logger.info(f"{self} disconnected.")
diff --git a/lerobot/src/lerobot/robots/koch_follower/__init__.py b/lerobot/src/lerobot/robots/koch_follower/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6524ab97bf45ae8c7c4eb6b110a049704e5e3e0a
--- /dev/null
+++ b/lerobot/src/lerobot/robots/koch_follower/__init__.py
@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from .config_koch_follower import KochFollowerConfig
+from .koch_follower import KochFollower
diff --git a/lerobot/src/lerobot/robots/koch_follower/config_koch_follower.py b/lerobot/src/lerobot/robots/koch_follower/config_koch_follower.py
new file mode 100644
index 0000000000000000000000000000000000000000..cab1f6e11a65c953acdd5ad05bf316270bc08b79
--- /dev/null
+++ b/lerobot/src/lerobot/robots/koch_follower/config_koch_follower.py
@@ -0,0 +1,39 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass, field
+
+from lerobot.cameras import CameraConfig
+
+from ..config import RobotConfig
+
+
+@RobotConfig.register_subclass("koch_follower")
+@dataclass
+class KochFollowerConfig(RobotConfig):
+ # Port to connect to the arm
+ port: str
+
+ disable_torque_on_disconnect: bool = True
+
+ # `max_relative_target` limits the magnitude of the relative positional target vector for safety purposes.
+ # Set this to a positive scalar to have the same value for all motors, or a dictionary that maps motor
+ # names to the max_relative_target value for that motor.
+ max_relative_target: float | dict[str, float] | None = None
+
+ # cameras
+ cameras: dict[str, CameraConfig] = field(default_factory=dict)
+
+ # Set to `True` for backward compatibility with previous policies/dataset
+ use_degrees: bool = False
diff --git a/lerobot/src/lerobot/robots/koch_follower/koch.mdx b/lerobot/src/lerobot/robots/koch_follower/koch.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..ef43feb06680f79223d511915a46e352d33ac480
--- /dev/null
+++ b/lerobot/src/lerobot/robots/koch_follower/koch.mdx
@@ -0,0 +1 @@
+../../../../docs/source/koch.mdx
\ No newline at end of file
diff --git a/lerobot/src/lerobot/robots/koch_follower/koch_follower.py b/lerobot/src/lerobot/robots/koch_follower/koch_follower.py
new file mode 100644
index 0000000000000000000000000000000000000000..70040b79ce679c6950bb56aeedb4de6594408f40
--- /dev/null
+++ b/lerobot/src/lerobot/robots/koch_follower/koch_follower.py
@@ -0,0 +1,236 @@
+#!/usr/bin/env python
+
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import logging
+import time
+from functools import cached_property
+
+from lerobot.cameras.utils import make_cameras_from_configs
+from lerobot.motors import Motor, MotorCalibration, MotorNormMode
+from lerobot.motors.dynamixel import (
+ DynamixelMotorsBus,
+ OperatingMode,
+)
+from lerobot.processor import RobotAction, RobotObservation
+from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected
+
+from ..robot import Robot
+from ..utils import ensure_safe_goal_position
+from .config_koch_follower import KochFollowerConfig
+
+logger = logging.getLogger(__name__)
+
+
+class KochFollower(Robot):
+ """
+ - [Koch v1.0](https://github.com/AlexanderKoch-Koch/low_cost_robot), with and without the wrist-to-elbow
+ expansion, developed by Alexander Koch from [Tau Robotics](https://tau-robotics.com)
+ - [Koch v1.1](https://github.com/jess-moss/koch-v1-1) developed by Jess Moss
+ """
+
+ config_class = KochFollowerConfig
+ name = "koch_follower"
+
+ def __init__(self, config: KochFollowerConfig):
+ super().__init__(config)
+ self.config = config
+ norm_mode_body = MotorNormMode.DEGREES if config.use_degrees else MotorNormMode.RANGE_M100_100
+ self.bus = DynamixelMotorsBus(
+ port=self.config.port,
+ motors={
+ "shoulder_pan": Motor(1, "xl430-w250", norm_mode_body),
+ "shoulder_lift": Motor(2, "xl430-w250", norm_mode_body),
+ "elbow_flex": Motor(3, "xl330-m288", norm_mode_body),
+ "wrist_flex": Motor(4, "xl330-m288", norm_mode_body),
+ "wrist_roll": Motor(5, "xl330-m288", norm_mode_body),
+ "gripper": Motor(6, "xl330-m288", MotorNormMode.RANGE_0_100),
+ },
+ calibration=self.calibration,
+ )
+ self.cameras = make_cameras_from_configs(config.cameras)
+
+ @property
+ def _motors_ft(self) -> dict[str, type]:
+ return {f"{motor}.pos": float for motor in self.bus.motors}
+
+ @property
+ def _cameras_ft(self) -> dict[str, tuple]:
+ return {
+ cam: (self.config.cameras[cam].height, self.config.cameras[cam].width, 3) for cam in self.cameras
+ }
+
+ @cached_property
+ def observation_features(self) -> dict[str, type | tuple]:
+ return {**self._motors_ft, **self._cameras_ft}
+
+ @cached_property
+ def action_features(self) -> dict[str, type]:
+ return self._motors_ft
+
+ @property
+ def is_connected(self) -> bool:
+ return self.bus.is_connected and all(cam.is_connected for cam in self.cameras.values())
+
+ @check_if_already_connected
+ def connect(self, calibrate: bool = True) -> None:
+ """
+ We assume that at connection time, arm is in a rest position,
+ and torque can be safely disabled to run calibration.
+ """
+
+ self.bus.connect()
+ if not self.is_calibrated and calibrate:
+ logger.info(
+ "Mismatch between calibration values in the motor and the calibration file or no calibration file found"
+ )
+ self.calibrate()
+
+ for cam in self.cameras.values():
+ cam.connect()
+
+ self.configure()
+ logger.info(f"{self} connected.")
+
+ @property
+ def is_calibrated(self) -> bool:
+ return self.bus.is_calibrated
+
+ def calibrate(self) -> None:
+ self.bus.disable_torque()
+ if self.calibration:
+ # Calibration file exists, ask user whether to use it or run new calibration
+ user_input = input(
+ f"Press ENTER to use provided calibration file associated with the id {self.id}, or type 'c' and press ENTER to run calibration: "
+ )
+ if user_input.strip().lower() != "c":
+ logger.info(f"Writing calibration file associated with the id {self.id} to the motors")
+ self.bus.write_calibration(self.calibration)
+ return
+ logger.info(f"\nRunning calibration of {self}")
+ for motor in self.bus.motors:
+ self.bus.write("Operating_Mode", motor, OperatingMode.EXTENDED_POSITION.value)
+
+ input(f"Move {self} to the middle of its range of motion and press ENTER....")
+ homing_offsets = self.bus.set_half_turn_homings()
+
+ full_turn_motors = ["shoulder_pan", "wrist_roll"]
+ unknown_range_motors = [motor for motor in self.bus.motors if motor not in full_turn_motors]
+ print(
+ f"Move all joints except {full_turn_motors} sequentially through their entire "
+ "ranges of motion.\nRecording positions. Press ENTER to stop..."
+ )
+ range_mins, range_maxes = self.bus.record_ranges_of_motion(unknown_range_motors)
+ for motor in full_turn_motors:
+ range_mins[motor] = 0
+ range_maxes[motor] = 4095
+
+ self.calibration = {}
+ for motor, m in self.bus.motors.items():
+ self.calibration[motor] = MotorCalibration(
+ id=m.id,
+ drive_mode=0,
+ homing_offset=homing_offsets[motor],
+ range_min=range_mins[motor],
+ range_max=range_maxes[motor],
+ )
+
+ self.bus.write_calibration(self.calibration)
+ self._save_calibration()
+ logger.info(f"Calibration saved to {self.calibration_fpath}")
+
+ def configure(self) -> None:
+ with self.bus.torque_disabled():
+ self.bus.configure_motors()
+ # Use 'extended position mode' for all motors except gripper, because in joint mode the servos
+ # can't rotate more than 360 degrees (from 0 to 4095) And some mistake can happen while assembling
+ # the arm, you could end up with a servo with a position 0 or 4095 at a crucial point
+ for motor in self.bus.motors:
+ if motor != "gripper":
+ self.bus.write("Operating_Mode", motor, OperatingMode.EXTENDED_POSITION.value)
+
+ # Use 'position control current based' for gripper to be limited by the limit of the current. For
+ # the follower gripper, it means it can grasp an object without forcing too much even tho, its
+ # goal position is a complete grasp (both gripper fingers are ordered to join and reach a touch).
+ # For the leader gripper, it means we can use it as a physical trigger, since we can force with
+ # our finger to make it move, and it will move back to its original target position when we
+ # release the force.
+ self.bus.write("Operating_Mode", "gripper", OperatingMode.CURRENT_POSITION.value)
+
+ # Set better PID values to close the gap between recorded states and actions
+ # TODO(rcadene): Implement an automatic procedure to set optimal PID values for each motor
+ self.bus.write("Position_P_Gain", "elbow_flex", 1500)
+ self.bus.write("Position_I_Gain", "elbow_flex", 0)
+ self.bus.write("Position_D_Gain", "elbow_flex", 600)
+
+ def setup_motors(self) -> None:
+ for motor in reversed(self.bus.motors):
+ input(f"Connect the controller board to the '{motor}' motor only and press enter.")
+ self.bus.setup_motor(motor)
+ print(f"'{motor}' motor id set to {self.bus.motors[motor].id}")
+
+ @check_if_not_connected
+ def get_observation(self) -> RobotObservation:
+ # Read arm position
+ start = time.perf_counter()
+ obs_dict = self.bus.sync_read("Present_Position")
+ obs_dict = {f"{motor}.pos": val for motor, val in obs_dict.items()}
+ dt_ms = (time.perf_counter() - start) * 1e3
+ logger.debug(f"{self} read state: {dt_ms:.1f}ms")
+
+ # Capture images from cameras
+ for cam_key, cam in self.cameras.items():
+ start = time.perf_counter()
+ obs_dict[cam_key] = cam.async_read()
+ dt_ms = (time.perf_counter() - start) * 1e3
+ logger.debug(f"{self} read {cam_key}: {dt_ms:.1f}ms")
+
+ return obs_dict
+
+ @check_if_not_connected
+ def send_action(self, action: RobotAction) -> RobotAction:
+ """Command arm to move to a target joint configuration.
+
+ The relative action magnitude may be clipped depending on the configuration parameter
+ `max_relative_target`. In this case, the action sent differs from original action.
+ Thus, this function always returns the action actually sent.
+
+ Args:
+ action (RobotAction): The goal positions for the motors.
+
+ Returns:
+ RobotAction: The action sent to the motors, potentially clipped.
+ """
+
+ goal_pos = {key.removesuffix(".pos"): val for key, val in action.items() if key.endswith(".pos")}
+
+ # Cap goal position when too far away from present position.
+ # /!\ Slower fps expected due to reading from the follower.
+ if self.config.max_relative_target is not None:
+ present_pos = self.bus.sync_read("Present_Position")
+ goal_present_pos = {key: (g_pos, present_pos[key]) for key, g_pos in goal_pos.items()}
+ goal_pos = ensure_safe_goal_position(goal_present_pos, self.config.max_relative_target)
+
+ # Send goal position to the arm
+ self.bus.sync_write("Goal_Position", goal_pos)
+ return {f"{motor}.pos": val for motor, val in goal_pos.items()}
+
+ @check_if_not_connected
+ def disconnect(self):
+ self.bus.disconnect(self.config.disable_torque_on_disconnect)
+ for cam in self.cameras.values():
+ cam.disconnect()
+
+ logger.info(f"{self} disconnected.")
diff --git a/lerobot/src/lerobot/robots/lekiwi/config_lekiwi.py b/lerobot/src/lerobot/robots/lekiwi/config_lekiwi.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d252072177152f10a5de7e38781ce1d62fa22be
--- /dev/null
+++ b/lerobot/src/lerobot/robots/lekiwi/config_lekiwi.py
@@ -0,0 +1,96 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass, field
+
+from lerobot.cameras.configs import CameraConfig, Cv2Rotation
+from lerobot.cameras.opencv.configuration_opencv import OpenCVCameraConfig
+
+from ..config import RobotConfig
+
+
+def lekiwi_cameras_config() -> dict[str, CameraConfig]:
+ return {
+ "front": OpenCVCameraConfig(
+ index_or_path="/dev/video0", fps=30, width=640, height=480, rotation=Cv2Rotation.ROTATE_180
+ ),
+ "wrist": OpenCVCameraConfig(
+ index_or_path="/dev/video2", fps=30, width=480, height=640, rotation=Cv2Rotation.ROTATE_90
+ ),
+ }
+
+
+@RobotConfig.register_subclass("lekiwi")
+@dataclass
+class LeKiwiConfig(RobotConfig):
+ port: str = "/dev/ttyACM0" # port to connect to the bus
+
+ disable_torque_on_disconnect: bool = True
+
+ # `max_relative_target` limits the magnitude of the relative positional target vector for safety purposes.
+ # Set this to a positive scalar to have the same value for all motors, or a dictionary that maps motor
+ # names to the max_relative_target value for that motor.
+ max_relative_target: float | dict[str, float] | None = None
+
+ cameras: dict[str, CameraConfig] = field(default_factory=lekiwi_cameras_config)
+
+ # Set to `True` for backward compatibility with previous policies/dataset
+ use_degrees: bool = False
+
+
+@dataclass
+class LeKiwiHostConfig:
+ # Network Configuration
+ port_zmq_cmd: int = 5555
+ port_zmq_observations: int = 5556
+
+ # Duration of the application
+ connection_time_s: int = 30
+
+ # Watchdog: stop the robot if no command is received for over 0.5 seconds.
+ watchdog_timeout_ms: int = 500
+
+ # If robot jitters decrease the frequency and monitor cpu load with `top` in cmd
+ max_loop_freq_hz: int = 30
+
+
+@RobotConfig.register_subclass("lekiwi_client")
+@dataclass
+class LeKiwiClientConfig(RobotConfig):
+ # Network Configuration
+ remote_ip: str
+ port_zmq_cmd: int = 5555
+ port_zmq_observations: int = 5556
+
+ teleop_keys: dict[str, str] = field(
+ default_factory=lambda: {
+ # Movement
+ "forward": "w",
+ "backward": "s",
+ "left": "a",
+ "right": "d",
+ "rotate_left": "z",
+ "rotate_right": "x",
+ # Speed control
+ "speed_up": "r",
+ "speed_down": "f",
+ # quit teleop
+ "quit": "q",
+ }
+ )
+
+ cameras: dict[str, CameraConfig] = field(default_factory=lekiwi_cameras_config)
+
+ polling_timeout_ms: int = 15
+ connect_timeout_s: int = 5
diff --git a/lerobot/src/lerobot/robots/lekiwi/lekiwi.mdx b/lerobot/src/lerobot/robots/lekiwi/lekiwi.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..f651589989a9ba21671a17f076a54d00f0256a5e
--- /dev/null
+++ b/lerobot/src/lerobot/robots/lekiwi/lekiwi.mdx
@@ -0,0 +1 @@
+../../../../docs/source/lekiwi.mdx
\ No newline at end of file