|
|
|
|
|
title: "Robot Learning: A Tutorial" |
|
|
authors: |
|
|
- name: "Francesco Capuano" |
|
|
affiliations: [1, 2] |
|
|
- name: "Caroline Pascal" |
|
|
affiliations: [2] |
|
|
- name: "Adil Zouitine" |
|
|
affiliations: [2] |
|
|
- name: "Thomas Wolf" |
|
|
affiliations: [2] |
|
|
- name: "Michel Aractingi" |
|
|
affiliations: [2] |
|
|
affiliations: |
|
|
- name: "University of Oxford" |
|
|
- name: "Hugging Face" |
|
|
published: "Oct 15, 2025" |
|
|
tableOfContentsAutoCollapse: true |
|
|
|
|
|
|
|
|
import MultiImage from '../components/MultiImage.astro'; |
|
|
import Image from '../components/Image.astro'; |
|
|
import Quote from '../components/Quote.astro'; |
|
|
import ch2_planar_manipulator_free from './assets/image/figures/ch2/ch2-planar-manipulator-free.png'; |
|
|
import ch2_planar_manipulator_floor from './assets/image/figures/ch2/ch2-planar-manipulator-floor.png'; |
|
|
import ch2_planar_manipulator_floor_shelf from './assets/image/figures/ch2/ch2-planar-manipulator-floor-shelf.png'; |
|
|
import ch1_lerobot_figure1 from './assets/image/figures/ch1/ch1-lerobot-figure1.png'; |
|
|
import ch2_approaches from './assets/image/figures/ch2/ch2-approaches.png'; |
|
|
import ch2_platforms from './assets/image/figures/ch2/ch2-platforms.png'; |
|
|
import ch2_cost_accessibility from './assets/image/figures/ch2/ch2-cost-accessibility.png'; |
|
|
import ch2_so100_to_planar_manipulator from './assets/image/figures/ch2/ch2-so100-to-planar-manipulator.png'; |
|
|
import ch2_planar_manipulator_floor_box from './assets/image/figures/ch2/ch2-planar-manipulator-floor-box.png'; |
|
|
import ch2_classical_limitations from './assets/image/figures/ch2/ch2-classical-limitations.png'; |
|
|
import ch3_learning_benefits from './assets/image/figures/ch3/ch3-learning-benefits.png'; |
|
|
import ch3_learning_atlas from './assets/image/figures/ch3/ch3-learning-atlas.png'; |
|
|
import ch3_rl_examples from './assets/image/figures/ch3/ch3-rl-examples.png'; |
|
|
import ch3_agent_env from './assets/image/figures/ch3/ch3-agent-env.png'; |
|
|
import ch3_rl_algorithms_atlas from './assets/image/figures/ch3/ch3-rl-algorithms-atlas.png'; |
|
|
import ch3_duck_sim_vs_real from './assets/image/figures/ch3/ch3-duck-sim-vs-real.png'; |
|
|
import ch3_many_ducks from './assets/image/figures/ch3/ch3-many-ducks.png'; |
|
|
import ch3_hil_serl_examples from './assets/image/figures/ch3/ch3-hil-serl-examples.png'; |
|
|
import ch3_hil_serl_architecture from './assets/image/figures/ch3/ch3-hil-serl-architecture.png'; |
|
|
import ch4_bc_trajectories from './assets/image/figures/ch4/ch4-bc-trajectories.png'; |
|
|
import ch4_observation_action_mapping from './assets/image/figures/ch4/ch4-observation-action-mapping.png'; |
|
|
import ch4_issues_with_bc from './assets/image/figures/ch4/ch4-issues-with-bc.png'; |
|
|
import ch4_task_effect_on_pairs from './assets/image/figures/ch4/ch4-task-effect-on-pairs.png'; |
|
|
import ch4_latent_variable_model from './assets/image/figures/ch4/ch4-latent-variable-model.png'; |
|
|
import ch4_many_latents from './assets/image/figures/ch4/ch4-many-latents.png'; |
|
|
import ch4_diffusion_robot_actions from './assets/image/figures/ch4/ch4-diffusion-robot-actions.png'; |
|
|
import ch4_action_vs_observation_distribution from './assets/image/figures/ch4/ch4-action-vs-observation-distribution.png'; |
|
|
import ch4_normalizing_flows from './assets/image/figures/ch4/ch4-normalizing-flows.png'; |
|
|
import ch4_diffusion_vs_flowmatching from './assets/image/figures/ch4/ch4-diffusion-vs-flowmatching.png'; |
|
|
import ch4_act_encoder from './assets/image/figures/ch4/ch4-act-encoder.png'; |
|
|
import ch4_act_decoder from './assets/image/figures/ch4/ch4-act-decoder.png'; |
|
|
import ch4_act from './assets/image/figures/ch4/ch4-act.png'; |
|
|
import ch4_diffusion_policy from './assets/image/figures/ch4/ch4-diffusion-policy.png'; |
|
|
import ch4_async_inference from './assets/image/figures/ch4/ch4-async-inference.png'; |
|
|
import ch4_queues from './assets/image/figures/ch4/ch4-queues.png'; |
|
|
import ch5_ml_vs_robotics_foundation from './assets/image/figures/ch5/ch5-ml-vs-robotics-foundation.png'; |
|
|
import ch5_generalist_policies_timeline from './assets/image/figures/ch5/ch5-generalist-policies-timeline.png'; |
|
|
import ch5_trends from './assets/image/figures/ch5/ch5-trends.png'; |
|
|
import ch5_pi0 from './assets/image/figures/ch5/ch5-pi0.png'; |
|
|
import ch5_pi0_sampling_timesteps from './assets/image/figures/ch5/ch5-pi0-sampling-timesteps.png'; |
|
|
import ch5_smolvla from './assets/image/figures/ch5/ch5-smolvla.png'; |
|
|
|
|
|
|
|
|
## Foreword |
|
|
|
|
|
Robotics is an inherently multidisciplinary field, which is witnessing unprecedented advancements since its inception in the 1960s. Yet, more than sixty years after the debut of Unimate, robots have still not fully integrated into the rich, unstructured, and dynamic world we humans inhabit. Over the decades, numerous disciplines have shown immense promise in tackling the challenges of creating autonomous robotic systems. This tutorial takes a clear stance in the debate on whether modern Machine Learning can play a pivotal role in the development of autonomous robots: we believe this to be the case. |
|
|
|
|
|
Nonetheless, we also hold that the wealth of research from both academia and industry in classical robotics over the past six decades is, simply put, too valuable to be cast aside in favor of purely learning-based methods. However, the interplay between classical robotics and modern machine learning is still in its nascent stages, and the path to integration yet to be clearly defined. In turn our goal here is to present what we consider to be the most relevant approaches within robot learning today, while warmly extending an invite to collaborate to expand the breadth of this work! Start contributing today [here](https://github.com/fracapuano/robot-learning-tutorial). |
|
|
|
|
|
This tutorial... |
|
|
|
|
|
- Does *not* aim to be a comprehensive guide to general field of robotics, manipulation or underactuated systems: @sicilianoSpringerHandbookRobotics2016 and @tedrakeRoboticManipulationPerception, @tedrakeUnderactuatedRoboticsAlgorithms do this better than we ever could. |
|
|
|
|
|
- Does *not* aim to be an introduction to statistical or deep learning: @shalev-shwartzUnderstandingMachineLearning2014 and @prince2023understanding cover these subjects better than we ever could. |
|
|
|
|
|
- Does *not* aim to be a deep dive into Reinforcement Learning, Diffusion Models, or Flow Matching: invaluable works such as @suttonReinforcementLearningIntroduction2018, @nakkiranStepbyStepDiffusionElementary2024, and @lipmanFlowMatchingGuide2024 do this better than we ever could. |
|
|
|
|
|
Instead, our goal here is to provide an intuitive explanation as per why these disparate ideas have converged to form the exciting field of modern robot learning, driving the unprecedented progress we see today. In this spirit, we follow the adage: "a jack of all trades is a master of none, *but oftentimes better than a master of one*." |
|
|
|
|
|
We sincerely hope this tutorial serves as a valuable starting point for your journey into robot learning. |
|
|
|
|
|
## Introduction |
|
|
|
|
|
<Image |
|
|
src={ch1_lerobot_figure1} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'lerobot is the open-source library for end-to-end robotics developed by Hugging Face. The library is vertically integrated on the entire robotics stack, supporting low-level control of real-world robot devices, advanced data and inference optimizations, as well as SOTA robot learning methods with simple implementations in pure Pytorch.'}/> |
|
|
|
|
|
Autonomous robotics holds the premise of relieving humans from repetitive, tiring or dangerous manual tasks. Consequently, the field of robotics has been widely studied since its first inception in the 1950s. Lately, advancements in Machine Learning (ML) have sparked the development of a relatively new class of methods used to tackle robotics problems, leveraging large amounts of data and computation rather than human expertise and modeling skills to develop autonomous systems. |
|
|
|
|
|
The frontier of robotics research is indeed increasingly moving away from classical model-based control paradigm, embracing the advancements made in ML, aiming to unlock (1) monolithic perception-to-action control pipelines and (2) multi-modal data-driven feature extraction strategies, together with (3) reduced reliance on precise models of the world and (4) a better positioning to benefit from the growing availability of open robotics data. While central problems in manipulation, locomotion and whole-body control demand knowledge of rigid-body dynamics, contact modeling, planning under uncertainty, recent results seem to indicate learning can prove just as effective as explicit modeling, sparking interest in the field of *robot learning*. This interest can be largely justified considering the significant challenges related to deriving accurate models of robot-environment interactions. |
|
|
|
|
|
Moreover, since end-to-end learning on ever-growing collections of text and image data has historically been at the core of the development of *foundation models* capable of semantic reasoning across multiple modalities (images, text, audio, etc.), deriving robotics methods grounded in learning appears particularly consequential, especially as the number of openly available datasets continues to grow. |
|
|
|
|
|
Robotics is, at its core, an inherently multidisciplinary field, requiring a wide range of expertise in both *software* and *hardware*. The integration of learning-based techniques further broadens this spectrum of skills, raising the bar for both research and practical applications. `lerobot` is an open-source library designed to integrate end-to-end with the entire robotics stack. With a strong focus on accessible, real-world robots <mark>(1) `lerobot` supports many, openly available, robotic platforms</mark> for manipulation, locomotion and even whole-body control. `lerobot`also implements a <mark>(2) unified, low-level approach to reading/writing robot configurations</mark> to extend support for other robot platforms with relatively low effort. The library introduces `LeRobotDataset`, <mark>(3) a native robotics dataset’s format</mark> currently being used by the community to efficiently record and share datasets. `lerobot` also supports many state-of-the-art (SOTA) algorithms in robot learning |
|
|
|
|
|
This tutorial serves the double purpose of providing useful references for the Science behind |
|
|
|
|
|
- Section <a href="#classical" data-reference-type="ref" data-reference="classical">[classical]</a> reviews classical robotics foundations, introducing the limitations of dynamics-based approaches to robotics. |
|
|
|
|
|
- Section <a href="#learning-rl" data-reference-type="ref" data-reference="learning-rl">[learning-rl]</a> elaborates on the limitations of dynamics-based methods, and introduce RL as a practical approach to solve robotics problems, considering its upsides and potential limitations. |
|
|
|
|
|
- Section <a href="#learning-imitation" data-reference-type="ref" data-reference="learning-imitation">[learning-imitation]</a> further describes robot learning techniques that aim at solving single-tasks learning, leveraging BC techniques to autonomously reproduce specific expert demonstrations. |
|
|
|
|
|
- Section <a href="#learning-foundation" data-reference-type="ref" data-reference="learning-foundation">[learning-foundation]</a> presents recent contributions on developing generalist models for robotics applications, by learning from large corpora of multi-task multi-robot data (*robotics foundation models*). |
|
|
|
|
|
Our goal with this tutorial is to provide an intuitive explanation of the reasons various disparate ideas from Machine Learning (ML) have converged and are powering the current evolution of Robotics, driving the unprecedented progress we see today. We complement our presentation of the most common and recent approaches in robot learning with practical code implementations using `lerobot`, and start here by presenting the dataset format introduced with `lerobot`. |
|
|
|
|
|
### `LeRobotDataset` |
|
|
|
|
|
`LeRobotDataset` is one of the most impactful features of `lerobot`, developed in keeping with the observation that robotics data is increasingly central in robot learning. Thus, `lerobot` defines a standardized dataset format designed to address the specific needs of robot learning research, providing a unified and convenient access to robotics data across modalities, including sensorimotor readings, multiple camera feeds and teleoperation status. `LeRobotDataset` also accommodates for storing general information regarding the data being collected, including textual descriptions of the task being performed by the teleoperator, the kind of robot used, and relevant measurement specifics like the frames per second at which the recording of both image and robot state’s streams are proceeding. |
|
|
|
|
|
In this, `LeRobotDataset` provides a unified interface for handling multi-modal, time-series data, and it is designed to seamlessly integrate with the PyTorch and Hugging Face ecosystems. `LeRobotDataset` can be easily extended by users and it is highly customizable by users, and it already supports openly available data coming from a variety of embodiments supported in `lerobot`, ranging from manipulator platforms like the SO-100 arm and ALOHA-2 setup, to real-world humanoid arm and hands, as well as entirely simulation-based datasets, and self-driving cars. This dataset format is built to be both efficient for training and flexible enough to accommodate the diverse data types encountered in robotics, while promoting reproducibility and ease of use for users. |
|
|
|
|
|
#### The dataset class design |
|
|
|
|
|
A core design choice behind `LeRobotDataset` is separating the underlying data storage from the user-facing API. This allows for efficient storage while presenting the data in an intuitive, ready-to-use format. |
|
|
|
|
|
Datasets are always organized into three main components: |
|
|
|
|
|
- **Tabular Data**: Low-dimensional, high-frequency data such as joint states, and actions are stored in efficient memory-mapped files, and typically offloaded to the more mature `datasets` library by Hugging Face, providing fast with limited memory consumption. |
|
|
|
|
|
- **Visual Data**: To handle large volumes of camera data, frames are concatenated and encoded into MP4 files. Frames from the same episode are always grouped together into the same video, and multiple videos are grouped together by camera. To reduce stress on the file system, groups of videos for the same camera view are also broke into multiple sub-directories, after a given threshold number. |
|
|
|
|
|
- **Metadata** A collection of JSON files which describes the dataset’s structure in terms of its metadata, serving as the relational counterpart to both the tabular and visual dimensions of data. Metadata include the different feature schema, frame rates, normalization statistics, and episode boundaries. |
|
|
|
|
|
For scalability, and to support datasets with potentially millions of trajectories (resulting in hundreds of millions or billions of individual camera frames), we merge data from different episodes into the same high-level structure. Concretely, this means that any given tabular collection and video will not typically contain information about one episode only, but rather a concatenation of the information available in multiple episodes. This keeps the pressure on the file system limited, both locally and on remote storage providers like Hugging Face, though at the expense of leveraging more heavily relational-like, metadata parts of the dataset, which are used to reconstruct information such as at which position, in a given file, an episode starts or ends. An example struture for a given `LeRobotDataset` would appear as follows: |
|
|
|
|
|
- `meta/info.json`: This metadata is a central metadata file. It contains the complete dataset schema, defining all features (e.g., `observation.state`, `action`), their shapes, and data types. It also stores crucial information like the dataset’s frames-per-second (`fps`), `lerobot`’s version at the time of capture, and the path templates used to locate data and video files. |
|
|
|
|
|
- `meta/stats.json`: This file stores aggregated statistics (mean, std, min, max) for each feature across the entire dataset, used for data normalization for most policy models and accessible externally via `dataset.meta.stats`. |
|
|
|
|
|
- `meta/tasks.jsonl`: This file contains the mapping from natural language task descriptions to integer task indices, which are useful for task-conditioned policy training. |
|
|
|
|
|
- `meta/episodes/*` This directory contains metadata about each individual episode, such as its length, the corresponding task, and pointers to where its data is stored in the dataset’s files. For scalability, this information is stored in files rather than a single large JSON file. |
|
|
|
|
|
- `data/*`: Contains the core frame-by-frame tabular data, using parquet files to allow for fast, memory-mapped access. To improve performance and handle large datasets, data from multiple episodes are concatenated into larger files. These files are organized into chunked subdirectories to keep the size of directories manageable. A single file typically contains data for more than one single episode. |
|
|
|
|
|
- `videos/*`: Contains the MP4 video files for all visual observation streams. Similar to the `data/` directory, the video footage from multiple episodes is concatenated into single MP4 files. This strategy significantly reduces the number of files in the dataset, which is more efficient for modern filesystems. |
|
|
|
|
|
### Code Example: Batching a (Streaming) Dataset |
|
|
|
|
|
This section provides an overview of how to access datasets hosted on Hugging Face using the `LeRobotDataset` class. Every dataset on the Hugging Face Hub containing the three main pillars presented above (Tabular, Visual and relational Metadata), and can be assessed with a single instruction. |
|
|
|
|
|
In practice, most reinforcement learning (RL) and behavioral cloning (BC) algorithms tend to operate on stack of observation and actions. For the sake of brevity, we will refer to joint spaces, and camera frames with the single term of *frame*. For instance, RL algorithms may use a history of previous frames $o_{t-H_o:t}$ to mitigate partial observability, and BC algorithms are in practice trained to regress chunks of multiple actions ($a_{t+t+H_a}$) rather than single controls. To accommodate for these specifics of robot learning training, `LeRobotDataset` provides a native windowing operation, whereby users can define the *seconds* of a given window (before and after) around any given frame, by using the `delta_timestemps` functionality. Unavailable frames are opportunely padded, and a padding mask is also returned to filter out the padded frames. Notably, this all happens within the `LeRobotDataset`, and is entirely transparent to higher level wrappers commonly used in training ML models such as `torch.utils.data.DataLoader`. |
|
|
|
|
|
Conveniently, by using `LeRobotDataset` with a Pytorch `DataLoader` one can automatically collate the individual sample dictionaries from the dataset into a single dictionary of batched tensors for downstream training or inference. `LeRobotDataset` also natively supports streaming mode for datasets. Users can stream data of a large dataset hosted on the Hugging Face Hub, with a one-line change in their implementation. Streaming datasets supports high-performance batch processing (ca. 80-100 it/s, varying on connectivity) and high levels of frames randomization, key features for practical BC algorithms which otherwise may be slow or operating on highly non-i.i.d. data. This feature is designed to improve on accessibility so that large datasets can be processed by users without requiring large amounts of memory and storage. |
|
|
|
|
|
<div class="pbox"> |
|
|
|
|
|
Batching a (Streaming) Dataset |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch1/01_datasets.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch1/01_datasets.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
|
|
|
### Code Example: Collecting Data |
|
|
|
|
|
<span id="paragraph-collecting-data" style="position: absolute;"></span> |
|
|
<div class="pbox"> |
|
|
|
|
|
Record a Dataset |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch1/02_record_data.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch1/02_record_data.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
|
|
|
## Classical Robotics |
|
|
|
|
|
<span id="classical" style="position: absolute;"></span> |
|
|
<Quote source="Sun Tzu"> |
|
|
Know your enemy |
|
|
</Quote> |
|
|
<div class="callout"> |
|
|
|
|
|
TL;DR Learning-based approaches to robotics are motivated by the need to (1) generalize across tasks and embodiments (2) reduce dependency on human expertise (3) leverage historical trends on the production of data |
|
|
|
|
|
</div> |
|
|
|
|
|
### Explicit and Implicit Models |
|
|
|
|
|
<Image |
|
|
src={ch2_approaches} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Overview of methods to generate motion (clearly non-exhausitve, see @bekrisStateRobotMotion2024). The different methods can be grouped based on whether they explicitly (dynamics-based) or implicitly (learning-based) model robot-environment interactions.'}/> |
|
|
|
|
|
Robotics is concerned with producing artificial motion in the physical world in useful, reliable and safe fashion. Thus, robotics is an inherently multi-disciplinar domain: producing autonomous motion in the physical world requires, to the very least, interfacing different software (motion planners) and hardware (motion executioners) components. Further, knowledge of mechanical, electrical, and software engineering, as well as rigid-body mechanics and control theory have therefore proven quintessential in robotics since the field first developed in the 1950s. More recently, Machine Learning (ML) has also proved effective in robotics, complementing these more traditional disciplines @connellRobotLearning1993. As a direct consequence of its multi-disciplinar nature, robotics has developed as a rather wide array of methods, all concerned with the main purpose of <mark>producing artificial motion in the physical world</mark>. |
|
|
|
|
|
Methods to produce robotics motion range from traditional *explicit* models |
|
|
|
|
|
### Different Types of Motion |
|
|
|
|
|
<Image |
|
|
src={ch2_platforms} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Different kinds of motions are achieved with potentially very different robotic platforms. From left to right, top to bottom: ViperX, SO-100, Boston Dynamics’ Spot, Open-Duck, 1X’s NEO, Boston Dynamics’ Atlas. This is an example list of robotic platforms and is (very) far from being exhaustive.'}/> |
|
|
|
|
|
In the vast majority of instances, robotics deals with producing motion via actuating joints connecting nearly entirely-rigid links. A key distinction between focus areas in robotics is based on whether the generated motion modifies (1) the absolute state of the environment (via dexterity), (2) the relative state of the robot with respect to its environment (exercising mobility skills), or (3) a combination of the two (Figure <a href="#robotics-platforms-atlas" data-reference-type="ref" data-reference="robotics-platforms-atlas">[robotics-platforms-atlas]</a>). |
|
|
|
|
|
Effects such as (1) are typically achieved *through* the robot, i.e. generating motion to perform an action inducing a desirable modification, effectively *manipulating* the environment (manipulation). Motions like (2) may result in changes in the robot’s physical location within its environment. Generally, modifications to a robot’s location within its environment may be considered instances of the general *locomotion* problem, further specified as *wheeled* or *legged* locomotion based on whenever a robot makes use of wheels or leg(s) to move in the environment. Lastly, an increased level of dynamism in the robot-environment interactions can be obtained combining (1) and (2), thus designing systems capable to interact with *and* move within their environment. This category is problems is typically termed *mobile manipulation*, and is characterized by a typically much larger set of control variables compared to either locomotion or manipulation alone. |
|
|
|
|
|
The traditional body of work developed since the very inception of robotics is increasingly complemented by learning-based approaches. ML has indeed proven particularly transformative across the entire robotics stack, first empowering planning-based techniques with improved state estimation used for traditional planning @tangPerceptionNavigationAutonomous2023 and then end-to-end replacing controllers, effectively yielding perception-to-action methods @koberReinforcementLearningRobotics. Work in producing robots capable of navigating a diverse set of terrains demonstrated the premise of both dynamics and learning-based approaches for locomotion @griffinWalkingStabilizationUsing2017, @jiDribbleBotDynamicLegged2023, @leeLearningQuadrupedalLocomotion2020, @margolisRapidLocomotionReinforcement2022, and recent works on whole-body control indicated the premise of learning-based approaches to generate rich motion on complex robots, including humanoids @zhangWoCoCoLearningWholeBody2024, @bjorckGR00TN1Open2025. Manipulation has also been widely studied, particularly considering its relevance for many impactful use-cases ranging from high-risk applications for humans @fujitaDevelopmentRobotsNuclear2020, @alizadehComprehensiveSurveySpace2024 to manufacturing @sannemanStateIndustrialRobotics2020. While explicit models have proven fundamental in achieving important milestones towards the development of modern robotics, recent works leveraging implicit models proved particularly promising in surpassing scalability and applicability challenges via learning @koberReinforcementLearningRobotics. |
|
|
|
|
|
### Example: Planar Manipulation |
|
|
|
|
|
Robot manipulators typically consist of a series of links and joints, articulated in a chain finally connected to an *end-effector*. Actuated joints are considered responsible for generating motion of the links, while the end effector is instead used to perform specific actions at the target location (e.g., grasping/releasing objects via closing/opening a gripper end-effector, using a specialized tool like a screwdriver, etc.). |
|
|
|
|
|
Recently, the development of low-cost manipulators like the ALOHA @zhaoLearningFineGrainedBimanual2023 ALOHA-2 @aldacoALOHA2Enhanced and SO-100/SO-101 @knightStandardOpenSO100 platforms significantly lowered the barrier to entry to robotics, considering the increased accessibility of these robots compared to more traditional platforms like the Franka Emika Panda arm (Figure <a href="#robotic-platforms-costs" data-reference-type="ref" data-reference="robotic-platforms-costs">[robotic-platforms-costs]</a>). |
|
|
|
|
|
<Image |
|
|
src={ch2_cost_accessibility} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Cheaper, more accessible robots are starting to rival traditional platforms like the Panda arm platforms in adoption in resource-constrained scenarios. The SO-100, in particular, has a cost in the 100s of Euros, and can be entirely 3D-printed in hours, while the industrially-manufactured Panda arm costs tens of thousands of Euros and is not openly available.'}/> |
|
|
|
|
|
Deriving an intuition as per why learning-based approaches are gaining popularity in the robotics community requires briefly analyzing traditional approaches for manipulation, leveraging tools like forward and inverse kinematics (FK, IK) and control theory. Providing a detailed overview of these methods falls (well) out of the scope of this tutorial, and we refer the reader to works including @sicilianoSpringerHandbookRobotics2016, @lynchModernRoboticsMechanics2017, @tedrakeRoboticManipulationPerception, @tedrakeUnderactuatedRoboticsAlgorithms for a much more comprehensive description of these techniques. Here, we mostly wish to highlight the benefits of ML over these traditional techniques |
|
|
|
|
|
<Image |
|
|
src={ch2_so100_to_planar_manipulator} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'The SO-100 arm is a 6-dof manipulator arm. Preventing some of its joints (shoulder pane, wrist flex and wrist roll) from actuating, it can be represented as a traditional 2-dof planar manipulator (the gripper joint in the end-effector is not considered towards the count of the degrees of freedom used to produce motion).'}/> |
|
|
|
|
|
Consider the (simple) case where a SO-100 is restrained from actuating (1) the shoulder pane and (2) the wrist flex and roll motors. This effectively reduces the degrees of freedom of the SO-100 from the original 5+1 (5 joints + 1 gripper) to 2+1 (shoulder lift, elbow flex + gripper). As the end-effector does not impact motion in this model, the SO-100 is effectively reduced to the planar manipulator robot presented in Figure <a href="#make-so100-planar-manipulator" data-reference-type="ref" data-reference="make-so100-planar-manipulator">[make-so100-planar-manipulator]</a>, where spheres represent actuators, and solid lines indicate length-$l$ links from the base of the SO-100 to the end-effector (*ee*). |
|
|
|
|
|
Further, let us make the simplifying assumption that actuators can produce rotations up to $2 \pi$ radians. In practice, this is seldom the case due to movement obstructions caused by the robot body itself (for instance, the shoulder lift cannot produce counter-clockwise movement due to the presence of the robot’s base used to secure the SO-100 to its support and host the robot bus), but we will introduce movement obstruction at a later stage. |
|
|
|
|
|
All these simplifying assumptions leave us with the planar manipulator of Figure <a href="#planar-manipulation-simple" data-reference-type="ref" data-reference="planar-manipulation-simple">[planar-manipulation-simple]</a>, free of moving its end-effector by controlling the angles $\theta_1$ and $\theta_2$, jointly referred to as the robot’s *configuration*, and indicated with $q = [\theta_1, \theta_2 ] \in [-\pi, +\pi]^2$. The axis attached to the joints indicate the associated reference frame, whereas circular arrows indicate the maximal feasible rotation allowed at each joint. In this tutorial, we do not cover topics related to spatial algebra, and we instead refer the reader to and for excellent explanations of the mechanics and theoretical foundations of producing motion on rigid bodies. |
|
|
|
|
|
<MultiImage |
|
|
images={[ |
|
|
{ |
|
|
src: ch2_planar_manipulator_free, |
|
|
alt: "Free to move", |
|
|
caption: "Free to move", |
|
|
id: "planar-manipulation-simple" |
|
|
}, |
|
|
{ |
|
|
src: ch2_planar_manipulator_floor, |
|
|
alt: "Constrained by the surface", |
|
|
caption: "Constrained by the surface", |
|
|
id: "planar-manipulator-floor" |
|
|
}, |
|
|
{ |
|
|
src: ch2_planar_manipulator_floor_shelf, |
|
|
alt: "Constrained by surface and (fixed) obstacle", |
|
|
caption: "Constrained by surface and (fixed) obstacle", |
|
|
id: "planar-manipulator-floor-shelf" |
|
|
} |
|
|
]} |
|
|
layout="3-column" |
|
|
zoomable |
|
|
downloadable |
|
|
caption="Planar, 2-dof schematic representation of the SO-100 manipulator under diverse deployment settings. From left to right: completely free of moving; constrained by the presence of the surface; constrained by the surface and presence of obstacles. Circular arrows around each joint indicate the maximal rotation feasible at that joint." |
|
|
/> |
|
|
|
|
|
Considering the (toy) example presented in Figure <a href="#planar-manipulation-simple" data-reference-type="ref" data-reference="planar-manipulation-simple">[planar-manipulation-simple]</a>, then we can analytically write the end-effector’s position $p \in \mathbb R^2$ as a function of the robot’s configuration, $p = p(q), p: \mathcal Q \mapsto \mathbb R^2$. In particular, we have: $p(q) = \begin{pmatrix} p_x(\theta_1, \theta_2) \\ p_y(\theta_1, \theta_2) \end{pmatrix} = \begin{pmatrix} l \cos(\theta_1) + l \cos(\theta_1 + \theta_2) \\ l \sin(\theta_1) + l \sin(\theta_1 + \theta_2) \end{pmatrix} \in S^{n=2}_{l_1+l_2} = \{ p(q) \in \mathbb R^2: \Vert p(q) \Vert_2^2 \leq (2l)^2, \ \forall q \in \mathcal Q \}$ |
|
|
|
|
|
Deriving the end-effector’s *pose* |
|
|
|
|
|
In the simplified case here considered (for which $\boldsymbol{p} \equiv p$, as the orientation of the end-effector is disregarded for simplicity), one can solve the problem of controlling the end-effector’s location to reach a goal position $p^*$ by solving analytically for $q: p(q) = f_{\text{FK}}(q) = p^*$. However, in the general case, one might not be able to solve this problem analytically, and can typically resort to iterative optimization methods comparing candidate solutions using a loss function (in the simplest case, $\Vert p(q) - p^* \Vert_2^2$ is a natural candidate), yielding: |
|
|
|
|
|
<span id="ik_problem" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\min_{q \in \mathcal Q} \Vert p(q) - p^* \Vert_2^2 \, . |
|
|
|
|
|
\end{align} |
|
|
``` |
|
|
|
|
|
Exact analytical solutions to IK are even less appealing when one considers the presence of obstacles in the robot’s workspace, resulting in constraints on the possible values of $q \in \mathcal Q \subseteq [-\pi, +\pi]^n \subset \mathbb R^n$ in the general case of $n$-links robots. |
|
|
|
|
|
For instance, the robot in Figure <a href="#planar-manipulator-floor" data-reference-type="ref" data-reference="planar-manipulator-floor">[planar-manipulator-floor]</a> is (very naturally) obstacled by the presence of the surface upon which it rests: $\theta_1$ can now exclusively vary within $[0, \pi]$, while possible variations in $\theta_2$ depend on $\theta_1$ (when $\theta_1 \to 0$ or $\theta_1 \to \pi$, further downwards movements are restricted). Even for a simplified kinematic model, developing techniques to solve eq. <a href="#ik_problem" data-reference-type="ref" data-reference="ik_problem">[ik_problem]</a> is in general non-trivial in the presence of constraints, particularly considering that the feasible set of solutions $\mathcal Q$ may change across problems. Figure <a href="#planar-manipulator-floor-shelf" data-reference-type="ref" data-reference="planar-manipulator-floor-shelf">[planar-manipulator-floor-shelf]</a> provides an example of how the environment influences the feasible set considered, with a new set of constraints deriving from the position of a new obstacle. |
|
|
|
|
|
However, IK |
|
|
|
|
|
Given a desired end-effector trajectory $\dot {p}^*(t)$ (1) indicating anchor regions in space and (2) how much time to spend in each region, diff-IK finds $\dot q(t)$ solving for joints’ *velocities* instead of *configurations*, |
|
|
<span id="reg_ik_velocity" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\dot q(t) = \arg\min_\nu \; \lVert J(q(t)) \nu - \dot {p}^*(t) \rVert_2^2 |
|
|
|
|
|
\end{align} |
|
|
``` |
|
|
|
|
|
Unlike eq. <a href="#ik_problem" data-reference-type="ref" data-reference="ik_problem">[ik_problem]</a>, solving for $\dot q$ is much less dependent on the environment (typically, variations in velocity are constrained by physical limits on the actuators). Conveniently, eq. <a href="#reg_ik_velocity" data-reference-type="ref" data-reference="reg_ik_velocity">[reg_ik_velocity]</a> also often admits the closed-form solution $\dot q = J(q)^+ \dot {p}^*$, where $J^+(q)$ denotes the Moore-Penrose pseudo-inverse of $J(q)$. Finally, discrete-time joint configurations $q$ can be reconstructed from joint velocities $\dot q$ using forward-integration on the continuous-time joint velocity , $q_{t+1} = q_t + \Delta t\,\dot q_t$ for a given $\Delta t$, resulting in tracking via diff-IK. |
|
|
|
|
|
Following trajectories with diff-IK is a valid option in well-controlled and static environments (e.g., industrial manipulators in controlled manufacturing settings), and relies on the ability to define a set of target velocities to track $[\dot {p}^*_0, \dot {p}^*_1, \dots, \dot {p}^*_k ]$ |
|
|
|
|
|
#### Adding Feedback Loops |
|
|
|
|
|
While very effective when a goal trajectory has been well specified, the performance of diff-IK can degrade significantly in the presence of modeling/tracking errors, or in the presence of non-modeled dynamics in the environment. |
|
|
|
|
|
<div class="wrapfigure"> |
|
|
|
|
|
r0.3 <Image |
|
|
src={ch2_planar_manipulator_floor_box} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="image" |
|
|
/> |
|
|
|
|
|
<span id="planar-manipulator-box-velocity" style="position: absolute;"></span> |
|
|
</div> |
|
|
|
|
|
One such case is presented in Figure <a href="#planar-manipulator-box-velocity" data-reference-type="ref" data-reference="planar-manipulator-box-velocity">[planar-manipulator-box-velocity]</a>, where another rigid body other than the manipulator is moving in the environment along the horizontal axis, with velocity $\dot x_B$. Accounting analytically for the presence of this disturbance |
|
|
|
|
|
Less predictable disturbances however (e.g., $\dot x_B \leftarrow \dot x_B + {\varepsilon}, {\varepsilon}\sim N(0,1)$) may prove challenging to model analytically, and one could attain the same result of preventing link-object collision by adding a condition on the distance between the midpoint of $l$ and $x_B$, enforced through a feedback loop on the position of the robot and object at each control cycle. |
|
|
|
|
|
To mitigate the effect of modeling errors, sensing noise and other disturbances, classical pipelines indeed do augment diff-IK with feedback control looping back quantities of interest. In practice, following a trajectory with a closed feedback loop might consist in backwarding the error between the target and measured pose, $\Delta p = p^*- p(q)$, hereby modifying the control applied to $\dot q = J(q)^+ (\dot {p}^*+ k_p \Delta p )$, with $k_p$ defined as the (proportional) gain. |
|
|
|
|
|
More advanced techniques for control consisting in feedback linearization, PID control, Linear Quatratic Regulator (LQR) or Model-Predictive Control (MPC) can be employed to stabilize tracking and reject moderate perturbations, and we refer to for in-detail explanation of these concepts, or for a simple, intuitive example in the case of a point-mass system. Nonetheless, feedback control presents its challenges as well: tuning gains remains laborious and system-specific. Further, manipulation tasks present intermittent contacts inducing hybrid dynamics (mode switches) and discontinuities in the Jacobian, challenging the stability guarantees of the controller and thus often necessitating rather conservative gains and substantial hand-tuning. |
|
|
|
|
|
We point the interested reader to , , and for extended coverage of FK, IK, diff-IK and control for (diff-)IK. |
|
|
|
|
|
### Limitations of Dynamics-based Robotics |
|
|
|
|
|
Despite the last 60+ years of robotics research, autonomous robots are still largely incapable of performing tasks at human-level performance in the physical world generalizing across (1) robot embodiments (different manipulators, different locomotion platforms, etc.) and (2) tasks (tying shoe-laces, manipulating a diverse set of objects). While essential in the early development of robotics, the aforementioned methods require significant human expertise to be used in practice, and are typically specific to a particular applicative problem. |
|
|
|
|
|
<Image |
|
|
src={ch2_classical_limitations} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Dynamics-based approaches to robotics suffer from several limitations: (1) orchestrating multiple components poses integration challenges; (2) the need to develop custom processing pipelines for the sensing modalities and tasks considered hinders scalability; (3) simplified analytical models of physical phenomena (here friction at the gripper; credits to @antonovaReinforcementLearningPivoting2017) limit real-world performance. Lastly, (4) dynamics-based methods overlook trends in the availability and growth of robotics data.'}/> |
|
|
|
|
|
Dynamics-based robotics pipelines have historically been <mark>developed sequentially, engineering the different blocks</mark> now within most architectures for specific purposes. That is, sensing, state estimation, mapping, planning, (diff-)IK, and low-level control have been traditionally developed as distinct modules with fixed interfaces. Pipelining these specific modules proved error-prone, and brittleness emerges |
|
|
|
|
|
Moreover, classical planners operate on compact, assumed-sufficient state representations; extending them to reason directly over raw, heterogeneous and noisy data streams is non-trivial. This results in a <mark>limited scalability to multimodal data and multitask settings</mark>, as incorporating high-dimensional perceptual inputs (RGB, depth, tactile, audio) traditionally required extensive engineering efforts to extract meaningful features for control. Also, the large number of tasks, coupled with the adoption of *per-task* planners, goal parameterizations, and safety constraints, results in an explosion in design and validation options, with little opportunity to reuse solutions across tasks. |
|
|
|
|
|
Setting aside integration and scalability challenges: developing accurate modeling of contact, friction, and compliance for complicated systems remains difficult. Rigid-body approximations are often insufficient in the presence of deformable objects, and <mark>relying on approximated models hinders real-world applicability</mark> of the methods developed. In the case of complex, time-dependent and/or non-linear dynamics, even moderate mismatches in parameters, unmodeled evolutions, or grasp-induced couplings can qualitatively affect the observed dynamics. |
|
|
|
|
|
Lastly, dynamics-based methods (naturally) overlook the rather recent <mark>increase in availability of openly-available robotics datasets</mark>. The curation of academic datasets by large centralized groups of human experts in robotics @oneillOpenXEmbodimentRobotic2025, @khazatskyDROIDLargeScaleInTheWild2025 is now increasingly complemented by a <mark>growing number of robotics datasets contributed in a decentralized fashion</mark> by individuals with varied expertise. If not tangentially, dynamics-based approaches are not posed to maximally benefit from this trend, which holds the premise of allowing generalization in the space of tasks and embodiments, like data was the cornerstone for advancements in vision @alayracFlamingoVisualLanguage2022 and natural-language understanding @brownLanguageModelsAre2020. |
|
|
|
|
|
Taken together, these limitations (Figure <a href="#classical-limitations" data-reference-type="ref" data-reference="classical-limitations">[classical-limitations]</a>) motivate the exploration of learning-based approaches that can (1) integrate perception and control more tightly, (2) adapt across tasks and embodiments with reduced expert modeling interventions and (3) scale gracefully in performance as more robotics data becomes available. |
|
|
|
|
|
## Robot (Reinforcement) Learning |
|
|
|
|
|
<span id="learning-rl" style="position: absolute;"></span> |
|
|
<Quote source="Richard Sutton"> |
|
|
Approximate the solution, not the problem |
|
|
</Quote> |
|
|
<div class="callout"> |
|
|
|
|
|
TL;DR The need for expensive, high-fidelity simulators can be obviated learning from real-world data, using sample-efficient algorithms that can safely train directly on hardware. |
|
|
|
|
|
</div> |
|
|
<Image |
|
|
src={ch3_learning_benefits} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Learning-based robotics streamlines perception-to-action by learning a (1) unified high-level controller capable to take (2) high-dimensional, unstructured sensorimotor information. Learning (3) does not require a dynamics model and instead focuses on interaction data, and (4) empirically correlates with the scale of the data used.'}/> |
|
|
|
|
|
Learning-based techniques for robotics naturally address the limitations presented in Section <a href="#classical" data-reference-type="ref" data-reference="classical">[classical]</a> (Figure <a href="#robot-learning-upsides" data-reference-type="ref" data-reference="robot-learning-upsides">[robot-learning-upsides]</a>). In particular, learning-based techniques typically rely on monolithich prediction-to-action pipelines (*visuomotor policies*) which do directly map sensorimotor inputs to predicted actions, streamlining control policies by removing the need to interface multiple components. Mapping sensory inputs to actions also makes it possible to incorporate diverse input modalities, leveraging the automatic feature extraction capabilities of modern learning systems. Moreover, learning-based approaches can, in principle, bypass explicit modeling altogether and instead rely solely on interaction data |
|
|
|
|
|
Being a field at its relative nascent stages, no prevalent technique(s) proves distinctly better than any other in the domain of robot learning. Still, two major classes of methods gained prominence- <mark>Reinforcement Learning (RL)</mark> and <mark>Behavioral Cloning (BC)</mark> (Figure <a href="#robot-learning-atlas" data-reference-type="ref" data-reference="robot-learning-atlas">[robot-learning-atlas]</a>). In this section, we provide a conceptual overview of applications of RL to robotics, as well as introduce practical examples of how to use RL within `lerobot`. We then introduce the major limitations RL suffers from, to introduce BC techniques in Section <a href="#learning-imitation" data-reference-type="ref" data-reference="learning-imitation">[learning-imitation]</a> and Section sec-learning-foundation. |
|
|
|
|
|
<div class="wrapfigure"> |
|
|
|
|
|
r0.3 <Image |
|
|
src={ch3_learning_atlas} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="image" |
|
|
/> |
|
|
|
|
|
<span id="robot-learning-atlas" style="position: absolute;"></span> |
|
|
</div> |
|
|
|
|
|
In Figure <a href="#robot-learning-atlas" data-reference-type="ref" data-reference="robot-learning-atlas">[robot-learning-atlas]</a> we deliberately include generalist robot models @blackp0VisionLanguageActionFlow2024, @shukorSmolVLAVisionLanguageActionModel2025 alongside task-specific BC methods. While significantly different in spirit |
|
|
|
|
|
<Image |
|
|
src={ch3_rl_examples} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Examples of two different robotics tasks performed using RL. In the manipulation task (A) an agent learns to reach for a yellow plastic block in its environment, and to put it inside of a box. In the locomotion task (B) an agent learns to move its center of mass sideways without falling.'}/> |
|
|
|
|
|
Applications of RL to robotics have been studied long enough that the relationship between these two disciplines has been compared to that of physics and matematics @koberReinforcementLearningRobotics. Indeed, due to their inherently interactive and sequential nature, robotics control problems can be directly cast as RL problems. Figure <a href="#robotics-with-rl-examples" data-reference-type="ref" data-reference="robotics-with-rl-examples">[robotics-with-rl-examples]</a> presents two of such cases. Reaching for an object to then move it somewhere else in the scene is a sequential problem where over time the controller needs to adjust the position of the robot arm based on the current configuration and the (possibly varying) position of the object. Figure <a href="#robotics-with-rl-examples" data-reference-type="ref" data-reference="robotics-with-rl-examples">[robotics-with-rl-examples]</a> also shows an example of a locomotion problem, where sequentiality is inherent in the problem formulation- while sliding to the side, the controller needs to keep adjusting to the robot’s to avoid failure (falling). |
|
|
|
|
|
### A (Concise) Introduction to RL |
|
|
|
|
|
The RL framework @suttonReinforcementLearningIntroduction2018, which we briefly introduce here, has often been used to tackle robotics problems @koberReinforcementLearningRobotics. RL is a subfield within ML fundamentally concerned with the development of autonomous systems (*agents*) capable to *continuously behave* in an evolving environment, developing (ideally, well-performing) control strategies (*policies*). Crucially for robotics, RL agents improve through trial and error, bypassing explicit models of the problem dynamics in favor of interaction data. In RL, this feedback loop between actions and outcomes (Figure <a href="#rl-most-famous-pic" data-reference-type="ref" data-reference="rl-most-famous-pic">[rl-most-famous-pic]</a>) is established through the agent sensing a scalar quantity (*reward*) measuring how desirable a given *transition* is for the accomplishment of its goal. |
|
|
|
|
|
<Image |
|
|
src={ch3_agent_env} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Agent-Environment interaction diagram (image credits to @suttonReinforcementLearningIntroduction2018).'}/> |
|
|
|
|
|
Formally, interactions between an agent and its environment are typically modeled via a Markov Decision Process (MDP) @bellmanMarkovianDecisionProcess1957. Representing robotics problems via MDPs offers several advantages, including (1) incorporating uncertainty through MDP’s inherently stochastic formulation and (2) providing a theoretically-sound framework for learning *without* an explicit model of the environment dynamics. While accommodating a continuous time formulation too, MDPs are typically considered in discrete time in RL, assuming interactions to atomically take place at discrete *timestep* $t=0,1,2,3, \dots, T$. MDPs allowing for an unbounded number of interactions ($T \to + \infty$) are termed *infinite-horizon*, and opposed to *finite-horizon* MDPs in which $T$ is finite. Unless diversely specified, we will only be referring to discrete-time finite-horizon (*episodic*) MDPs. |
|
|
|
|
|
Formally, a lenght-$T$ Markov Decision Process (MDP) is a tuple $\mathcal M = \langle \mathcal S, \mathcal A, \mathcal D, r, \gamma, \rho, T \rangle$, where: |
|
|
|
|
|
- $\mathcal S$ is the *state space*; $s_t\in \mathcal S$ denotes the (possibly non-directly observable) environment state at time $t$. In robotics, states often comprise robot configuration and velocities ($q_t, \dot q_t$), and can also accomodate sensor readings such as camera or audio streams. |
|
|
|
|
|
- $\mathcal A$ is the *action space*; $a_t\in \mathcal A$ may represent joint torques, joint velocities, or even end-effector commands at timestep $t$. In general, actions correspond to commands intervenings on the configuration of the robot. |
|
|
|
|
|
- $\mathcal D$ represents the (possibly non-deterministic) environment dynamics, with $\mathcal D: \mathcal S\times \mathcal A\times \mathcal S\mapsto [0, 1]$, $\mathcal D\, (s_t, a_t, s_{t+1})= \mathbb P (s_{t+1}\vert s_t, a_t)$. For instance, for a planar manipulator dynamics could be considered deterministic when the environment is fully described (Figure <a href="#planar-manipulation-simple" data-reference-type="ref" data-reference="planar-manipulation-simple">[planar-manipulation-simple]</a>), and stochastic when unmodeled disturbances depending on non-observable parameters intervene (Figure <a href="#planar-manipulator-box-velocity" data-reference-type="ref" data-reference="planar-manipulator-box-velocity">[planar-manipulator-box-velocity]</a>). |
|
|
|
|
|
- $r- \mathcal S\times \mathcal A\times \mathcal S\to \mathbb R$ is the *reward function*, weighing the transition $(s_t, a_t, s_{t+1})$ in the context of the achievement of an arbitrary goal. For instance, a simple reward function for quickly moving along the $x$ axis (Figure <a href="#robotics-with-rl-examples" data-reference-type="ref" data-reference="robotics-with-rl-examples">[robotics-with-rl-examples]</a>) could be based on the absolute position of the robot along the $x$ axis ($p_{x_t}$), present negative penalties for falling over (measured from $p_{z_t}$) and a introduce bonuses $\dot p_{x_t}$ for speed, $r (s_t, a_t, s_{t+1})\equiv r(s_t) = p_{x_t} \cdot \dot p_{x_t} - \tfrac{1}{p_{z_t}}$. |
|
|
|
|
|
Lastly, $\gamma \in [0,1)$ represent the discount factor regulating preference for immediate versus long-term reward (with an effective horizon equal to $\tfrac{1}{1-\gamma}$), and $\rho$ is the distribution over $\mathcal S$ for the MDP’s *initial*, $s_0 \sim \rho$. |
|
|
|
|
|
Therefore, a length-$T$ *trajectory* is the (random) sequence |
|
|
``` math |
|
|
\htmlId{trajectory_definition}{\tau = (s_0, a_0, r_0, s_1, a_1, r_1, \dots, s_{T-1}, a_{T-1}, r_{T-1}, s_T),} |
|
|
``` |
|
|
with per-step rewards defined as $r_t = r (s_t, a_t, s_{t+1})$ for ease of notation. Interestingly, assuming both the environment dynamics and conditional distribution over actions given states |
|
|
<span id="dynamics_markovian" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\mathbb P(s_{t+1}\vert s_t, a_t, s_{t-1}, a_{t-1}, \dots s_0, a_0 ) &= \mathbb P (s_{t+1}\vert s_t, a_t) \\ |
|
|
\mathbb P(a_t\vert s_t, a_{t-1}, s_{t-1}, s_0, a_0) &= \mathbb P(a_t\vert s_t), |
|
|
\end{align} |
|
|
``` |
|
|
|
|
|
the probability of observing a given trajectory $\tau$ factorizes into: |
|
|
|
|
|
``` math |
|
|
\htmlId{traj_prob}{\mathbb P(\tau) = \mathbb P (s_0) \prod_{t=0}^{T-1} \mathbb P (s_{t+1}\vert s_t, a_t)\ \mathbb P(a_t\vert s_t).} |
|
|
``` |
|
|
|
|
|
Policies $\mathbb P(a_t\vert s_t)$ are typically indicated as $\pi(a_t\vert s_t)$, often parametrized via $\theta$, yielding $\pi_\theta (a_t\vert s_t)$, and are traine by optimizing the (discounted) *return* associated to a given $\tau$, i.e. the (random) sum of measured rewards over an arbitrary trajectory, |
|
|
``` math |
|
|
G(\tau) = \sum_{t=0}^{T-1} \gamma^{t} r_t. |
|
|
``` |
|
|
In that, agents seek to learn control strategies (*policies*, $\pi_\theta$) maximizing the expected return $\mathbb E_{\tau \sim \pi_\theta} G(\tau)$. For a given dynamics $\mathcal D$ |
|
|
<span id="RL-j-function" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
J(\pi_\theta) &= \mathbb E_{\tau \sim \mathbb P_{\theta; \mathcal D}} [G(\tau)], \\ |
|
|
\mathbb P_{\theta; \mathcal D} (\tau) &= \rho \prod_{t=0}^{T-1} \mathcal D (s_t, a_t, s_{t+1})\ \pi_\theta (a_t\vert s_t). |
|
|
\end{align} |
|
|
``` |
|
|
|
|
|
Crucially, in the RL framework the agent is assumed to only *observe* the environment dynamics and not to intervene on them, and thus eq. <a href="#RL-j-function" data-reference-type="ref" data-reference="RL-j-function">[RL-j-function]</a> varies exclusively with the policy followed. In turn, MDPs naturally provide a framework to optimize over the space of the possible behaviors an agent might enact ($\pi \in \Pi$), searching for the *optimal policy* $\pi^* = \arg \max_{\theta} J(\pi_\theta)$, where $\theta$ is the parametrization adopted by the policy set $\Pi: \pi_\theta \in \Pi, \ \forall \theta$. Besides providing a target for policy search, $G(\tau)$ can also be used to discriminate between states $s_t$ and $s_t, a_t$ pairs. Given any state $s \in \mathcal S$ |
|
|
|
|
|
``` math |
|
|
V_\pi(s) = \mathbb E_{\tau \sim \pi} [G(\tau) \big \vert s_0 = s] |
|
|
``` |
|
|
can be used to discriminate between desirable and undesirable state in terms of long-term (discounted) reward maximization, under a given policy $\pi$. Similarily, the *state-action* value function also conditions the cumulative discounted reward on selecting action $a$ when in $s$, and thereafter act according to $\pi$, |
|
|
``` math |
|
|
Q_\pi(s,a) = \mathbb E_{\tau \sim \pi} [G (\tau) \big \vert s_0 = s, a_0=a]. |
|
|
``` |
|
|
Importantly, value functions are interrelated: |
|
|
<span id="q-as-v" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
Q_\pi(s_t, a_t) &= \mathbb{E}_{s_{t+1}\sim \mathbb P(\bullet \vert s_t, a_t)} [r_t + \gamma V_\pi(s_{t+1})] \\ |
|
|
V_\pi(s_t) &= \mathbb E_{a_t\sim \pi(\bullet \vert s_t)} [Q_\pi (s_t, a_t)], |
|
|
|
|
|
\end{align} |
|
|
``` |
|
|
inducing an ordering over states and state-action pairs under $\pi$, and value functions are thus central to most RL algorithms. A variety of algorithms have been developed in RL attempting to find (approximate) solutions to the problem of maximizing cumulative reward (we report some in Figure <a href="#rl-algos-atlas" data-reference-type="ref" data-reference="rl-algos-atlas">[rl-algos-atlas]</a>). |
|
|
|
|
|
<Image |
|
|
src={ch3_rl_algorithms_atlas} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Popular RL algorithms. See @SpinningUp2018 for a complete list of citations.'}/> |
|
|
|
|
|
Popular approaches to continuous state and action space |
|
|
|
|
|
### Real-world RL for Robotics |
|
|
|
|
|
Streamlined end-to-end control pipelines, data-driven feature extraction and a disregard for explicit modeling in favor of interaction data are all features of RL for robotics. However, RL still suffers from limitations concerning safety and learning efficiency, particularly pressing for real-world robotics applications. |
|
|
|
|
|
First, especially early in training, <mark>actions are typically explorative, and thus may be erractic</mark>. On physical systems, untrained policies may command high velocities, self-collisiding configurations, or torques exceeding joint limits, leading to wear and potential hardware damage. Mitigating these risks requires external safeguards (e.g., watchdogs, safety monitors, emergency stops), often incuring in a high degree of human supervision. Further, in the typical episodic setting considered in most robotics problems, experimentation is substantially slowed down by the need to manually reset the environment over the course of training, a time-consuming and error-prone process. Second, learning efficiently remains problematic in RL, <mark>limiting the applicability of RL in real-world robotics due to consequently prohibitive timescales of training</mark>. Even strong algorithms such as SAC @haarnojaSoftActorCriticOffPolicy2018 typically require a large numbers of transitions $\{ (s_t, a_t, r_t, s_{t+1})\}_{t=1}^N$. On real-world hardware, generating this data is time-consuming. |
|
|
|
|
|
<Image |
|
|
src={ch3_duck_sim_vs_real} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Simulated (left) vs. real-world (right) OpenDuck. Discrepancies in the simulation dynamics (reality gap) pose risks to policy transfer.'}/> |
|
|
|
|
|
Training RL policies in simulation @tobinDomainRandomizationTransferring2017 addresses both issues, eliminating physical risk and dramatically increasing throughput. Yet, simulators require significant modeling effort, and rely on assumptions (simplified physical modeling, instantaneous actuation, static environmental conditions, etc.) limiting the possibilities to transfer the policies learned in simulation, due the discrepancy between real and simulated environments (*reality gap*, Figure <a href="#synthetic-vs-real-duck" data-reference-type="ref" data-reference="synthetic-vs-real-duck">[synthetic-vs-real-duck]</a>). *Domain randomization* @tobinDomainRandomizationTransferring2017 (DR) is a popular technique to overcome the reality gap, and consists in randomizing the parameters of the simulated environment during training, aiming at inducing robustness to specific disturbances. In this, DR is typically employed to increase the diversity of scenarios over the course of training, improving on the performace sim-to-real transferred policies @akkayaSolvingRubiksCube2019, @antonovaReinforcementLearningPivoting2017, @jiDribbleBotDynamicLegged2023. In practice, DR is performed training in simulation on simulated dynamics $\mathcal D$, further parametrized as $\mathcal D \equiv \mathcal D_\xi$, with a *dynamics* (random) vector $\xi$ drawn an arbitrary distribution, $\xi \sim \Xi$. For instance, one could decide to randomize the friction coefficient of the surface in a locomotion task (Figure <a href="#ducks-on-terrains" data-reference-type="ref" data-reference="ducks-on-terrains">[ducks-on-terrains]</a>), or the center of mass of an object for a manipulation task. Over the course of training |
|
|
|
|
|
<Image |
|
|
src={ch3_many_ducks} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'The same locomotion task can be carried out in different (simulated) domains (exemplified by the difference in terrains) at training time, resulting to increased robustness over diverse environment dynamics.'}/> |
|
|
|
|
|
While effective in transfering policies across the reality gap in real-world robotics @tobinDomainRandomizationTransferring2017, @akkayaSolvingRubiksCube2019, @jiDribbleBotDynamicLegged2023, @tiboniDomainRandomizationEntropy2024, DR often requires extensive manual engineering. First, identifying which parameters to randomize |
|
|
|
|
|
Selecting the dynamics distribution $\Xi$ is also non-trivial. On the one hand, distributions with low entropy might risk to cause failure at transfer time, due to the limited robustness induced over the course of training. On the other hand, excessive randomization may cause over-regularization and hinder performance @margolisRapidLocomotionReinforcement2022. Consequently, the research community investigated approaches to automatically select the randomization distribution $\Xi$, using signals from the training process or tuning it to reproduce observed real-world trajectories. @akkayaSolvingRubiksCube2019 use a parametric uniform distribution $\mathcal U(a, b)$ as $\Xi$, widening the bounds $a, b$ as training progresses and the agent’s performance improves (AutoDR). While effective, AutoDR requires significant tuning |
|
|
|
|
|
While DR has shown promise, it does not address the main limitation that, even under the assumption that an ideal distribution $\Xi$ was available, many robotics problems <mark>cannot be simulated with high-enough fidelity under practical computational constraints</mark>. Simulating contact-rich manipulation of possibly deformable or soft materials |
|
|
|
|
|
A perhaps more foundamental limitation of RL for robotics is the general unavailability of complicated tasks’ *dense* reward function, the design of which is essentially based on human expertise, ingenuity and trial-and-error. In practice, *sparse* reward functions can be used to conclude whether one specific goal has been attained |
|
|
|
|
|
To make the most of (1) the growing number of openly available datasets and (2) relatively inexpensive robots like the SO-100, RL could (1) be anchored in already-collected trajectories |
|
|
|
|
|
Off-policy algorithms like Soft Actor-Critic (SAC) @haarnojaSoftActorCriticOffPolicy2018 tend to be more sample efficient then their on-policy counterpart @schulmanProximalPolicyOptimization2017, due to the presence a *replay buffer* used over the course of training. Other than allowing to re-use past transitions $(s_t, a_t, r_t, s_{t+1})$, the replay buffer can also accomodate for the injection of previously-collected data in the training process @ballEfficientOnlineReinforcement2023. Using expert demonstrations to guide learning together with learned rewards, RL can be effectively carried out in the real-world @luoSERLSoftwareSuite2025. Interestingly, when complemented with in-training human interventions, real-world RL agents have been shown to learn policies with near-perfect success rates on challenging manipulation tasks in 1-2 hours @luoPreciseDexterousRobotic2024. |
|
|
|
|
|
##### Sample-efficient RL |
|
|
|
|
|
In an MDP, the optimal policy $\pi^*$ can be derived from its associated $Q$-function, $Q^* \equiv Q_{\pi^*}$, and in particular the optimal action(s) $\mu(s_t)$ can be selected maximizing the optimal $Q$-function over the action space, |
|
|
``` math |
|
|
\mu(s_t) = \max_{a_t\in \mathcal A} Q^*(s_t, a_t). |
|
|
``` |
|
|
Interestingly, the $Q^*$-function satisfies a recursive relationship (*Bellman equation*) based on a very natural intuition [^2]: |
|
|
|
|
|
> \[...\] If the optimal value $Q^*(s_{t+1}, a_{t+1})$ of the \[state\] $s_{t+1}$ was known for all possible actions $a_{t+1}$, then the optimal strategy is to select the action $a_{t+1}$ maximizing the expected value of $r_t + \gamma Q^*(s_{t+1}, a_{t+1})$ |
|
|
> ``` math |
|
|
> Q^*(s_t, a_t) = \mathbb E_{s_{t+1} \sim \mathbb P(\bullet \vert s_t, a_t)} [r_t + \gamma \max_{a_{t+1} \in \mathcal A} Q^*(s_{t+1}, a_{t+1}) \big\vert s_t, a_t] |
|
|
> ``` |
|
|
|
|
|
In turn, the optimal $Q$-function is guaranteed to be self-consistent by definition. *Value-iteration* methods exploit this relationship (and/or its state-value counterpart, $V^*(s_t)$ ) by iteratively updating an initial estimate of $Q^*$, $Q_k$ using the Bellman equation as update rule (*Q-learning*): |
|
|
``` math |
|
|
Q_{i+1}(s_t, a_t) \leftarrow \mathbb E_{s_{t+1} \sim \mathbb P(\bullet \vert s_t, a_t)} [r_t + \gamma \max_{a_{t+1} \in \mathcal A} Q_i (s_{t+1}, a_{t+1}) \big\vert s_t, a_t], \quad i=0,1,2,\dots,K |
|
|
``` |
|
|
Then, one can derive the (ideally, near-optimal) policy by explicitly maximizing over the action space the final (ideally, near-optimal) estimate $Q_K \approx Q^*$ at each timestep. Indeed, one can show that under certain assumptions on the MDP considered, $Q_K \to Q^* \, \text{as } K \to \infty$. |
|
|
|
|
|
Effective in its early applications to small-scale discrete problems, vanilla Q-learning was found complicated to scale to large $\mathcal S\times \mathcal A$ problems, in which storing $Q : \mathcal S\times \mathcal A\mapsto \mathbb R$ alone might result prohibitive. Also, vanilla Q-learning is not directly usable for *continuous*, unstructured state-action space MPDs, such as those considered in robotics. In their seminal work on *Deep Q-Learning* (DQN), @mnihPlayingAtariDeep2013 propose learning Q-values using deep convolutional neural networks, thereby accomodating for large and even unstructured *state* spaces. DQN parametrizes the Q-function using a neural network with parameters $\theta$, updating the parameters by sequentially minimizing the expected squared temporal-difference error (TD-error, $\delta_i$): |
|
|
<span id="dqn-loss" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\mathcal L(\theta_i) &= \mathbb E_{(s_t, a_t) \sim \chi(\bullet)} |
|
|
\big[ |
|
|
(\underbrace{y_i - Q_{\theta_i}(s_t, a_t)}_{\delta_i})^2 |
|
|
\big], \\ |
|
|
y_i &= \mathbb E_{s_{t+1} \sim \mathbb P(\bullet \vert s_t, a_t)} \big[ r_t + \gamma \max_{a_t\in \mathcal A} Q_{\theta_{i-1}} (s_{t+1}, a_{t+1}) \big], |
|
|
\end{align} |
|
|
``` |
|
|
where $\chi$ represents a behavior distribution over state-action pairs. Crucially, $\chi$ can in principle be different from the policy being followed, effectively allowing to reuse prior data stored in a *replay buffer* $D$ in the form of $(s_t, a_t, r_t, s_{t+1})$ transitions, used to form the TD-target $y_i$, TD-error $\delta_i$ and loss function eq. <a href="#dqn-loss" data-reference-type="ref" data-reference="dqn-loss">[dqn-loss]</a> via Monte-Carlo (MC) estimates. |
|
|
|
|
|
While effective in handling large, unstructured state spaces for discrete action-space problems, DQN’s application to continous control problems proved challenging. Indeed, in the case of high-capacity function approximators such as neural networks, solving $\max_{a_t \in \mathcal A} Q_\theta(s_t, a_t)$ at each timestep is simply unfeasible due to the (1) continous nature of the action space ($\mathcal A\subset \mathbb R^n$ for some $n$) and (2) impossibility to express the policy with a cheap (ideally, even closed-form) formulation, so that $\max Q_\theta$ could be solved analytically. @pmlr-v32-silver14 tackle these fundamental challenges by using a *deterministic* function of the state $s_t$ as policy, $\mu_\phi(s_t) = a_t$, parametrized by $\phi$. Thus, policies can be iteratively refined updating $\phi$ along the direction: |
|
|
``` math |
|
|
\htmlId{deterministic-pg}{d_\phi = \mathbb E_{s_t \sim \mathbb P (\bullet)} [\nabla_\phi Q(s_t, a_t)\vert_{a_t = \mu_\phi(s_t)}] = \mathbb E_{s_t \sim \mathbb P(\bullet)} [\nabla_{a_t} Q(s_t, a_t) \vert_{a_t = \mu_\phi(s_t)} \cdot \nabla_\phi \mu(s_t)]} |
|
|
``` |
|
|
|
|
|
Provably, eq. <a href="#deterministic-pg" data-reference-type="ref" data-reference="deterministic-pg">[deterministic-pg]</a> is the *deterministic policy gradient* (DPG) of the policy $\mu_\phi$ @pmlr-v32-silver14, so that updates $\phi_{k+1}\leftarrow \phi_k + \alpha d_\phi$ are guaranteed to increase the (deterministic) cumulative discounted reward, $J(\mu_\phi)$. @lillicrapContinuousControlDeep2019a extended DPG to the case of (1) high-dimensional unstructured observations and (2) continuous action spaces, introducing Deep Deterministic Policy Gradient (DDPG), an important algorithm in RL and its applications to robotics. DDPG adopts a modified TD-target compared to eq. <a href="#TD-target" data-reference-type="ref" data-reference="TD-target">[TD-target]</a>, by maintaining a policy network used to select actions, yielding |
|
|
|
|
|
``` math |
|
|
\htmlId{TD-target-ddpg}{y_i = \mathbb E_{s_{t+1} \sim \mathbb P(\bullet \vert s_t, a_t)} \big[ r_t + \gamma Q_{\theta_{i-1}} (s_{t+1}, \mu_\phi(s_{t+1})) \big] .} |
|
|
``` |
|
|
Similarily to DQN, DDPG also employs the same replay buffer mechanism, reusing past transitions over training for increased sample efficiency and estimate the loss function via MC-estimates. |
|
|
|
|
|
Soft Actor-Critic (SAC) @haarnojaSoftActorCriticOffPolicy2018 is a derivation of DDPG in the max-entropy (MaxEnt) RL framework, in which RL agents are tasked with <mark>maximizing the discounted cumulative reward, while acting as randomly as possible</mark>. MaxEnt RL @haarnojaReinforcementLearningDeep2017b has proven particularly robust thanks to the development of diverse behaviors, incentivized by its entropy-regularization formulation. In that, MaxEnt revisits the RL objective $J (\pi)$ to specifically account for the policy entropy $\mathcal H(\pi (\bullet \vert s_t))$, |
|
|
<span id="J-soft" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
J(\pi) &= \sum_{t=0}^T \mathbb{E}_{(s_t, a_t) \sim \chi} [r_t + \alpha \mathcal H(\pi (\bullet \vert s_t))]. |
|
|
|
|
|
\end{align} |
|
|
``` |
|
|
|
|
|
This modified objective results in the *soft* TD-target: |
|
|
|
|
|
``` math |
|
|
\htmlId{soft-td-target}{y_i = \mathbb E_{s_{t+1} \sim \mathbb P( \bullet \vert s_t, a_t)} [r_t + \gamma \left( Q_{\theta_{i-1}} (s_{t+1}, a_{t+1}) - \alpha \log \pi_\phi(a_{t+1} \vert s_{t+1}) \right)], \quad a_{t+1} \sim \pi_\phi(\bullet \vert s_t)} |
|
|
``` |
|
|
Similarily to DDPG, SAC also maintains an explicit policy, trained under the same MaxEnt framework for the maximization of eq. <a href="#J-soft" data-reference-type="ref" data-reference="J-soft">[J-soft]</a>, updated using- |
|
|
``` math |
|
|
\htmlId{sac-policy-update}{\pi_{k+1} \leftarrow \arg\min_{\pi^\prime \in \Pi} \text{D}_{\text{KL}}\left(\pi^\prime (\bullet \vert s_t) \bigg\Vert \frac{\exp(Q_{\pi_k}(s_t, \bullet))}{Z_{\pi_k}(s_t)} \right)} |
|
|
``` |
|
|
The update rule provided in eq. <a href="#sac-policy-update" data-reference-type="ref" data-reference="sac-policy-update">[sac-policy-update]</a> optimizes the policy while projecting it on a set $\Pi$ of tractable distributions (e.g., Gaussians, @haarnojaReinforcementLearningDeep2017b). |
|
|
|
|
|
##### Sample-efficient, data-driven RL |
|
|
|
|
|
Sampling $(s_t, a_t, r_t, s_{t+1})$ from the replay buffer $D$ conveniently allows to approximate expectations for TD-target and TD-error through Monte-Carlo (MC) estimates. The replay buffer $D$ also proves extremely useful in maintaining a history of previous transitions and using it for training, improving on sample efficiency. Furthermore, it also naturally provides an entry point to inject offline trajectories recorded by a human demonstrator into the training process. |
|
|
|
|
|
Reinforcement Learning with Prior Data (RLPD) @ballEfficientOnlineReinforcement2023 is an Offline-to-Online RL algorithm leveraging prior data to effectively accelerate the training of a SAC agent. Unlike previous works on Offline-to-Online RL, RLPD avoids any pre-training and instead only uses the available offline data $D_\text{offline}$ to improve online-learning from scratch. During each training step, transitions from both the offline and online replay buffers are sampled in equal proportions, and used in the underlying SAC routine. Together with other implementation details (using LayerNorm layers to prevent value overestimation, and the use of ensembles techniques to form the TD-target), RLPD proves a particularly simple yet effective approach to use $D_\text{offline}$ for Offline-to-Online RL. |
|
|
|
|
|
##### Sample-efficient, data-driven, real-world RL |
|
|
|
|
|
Despite the possibility to leverage offline data for learning, the effectiveness of real-world RL training is still limited by the need to define a task-specific, hard-to-define reward function. Further, even assuming to have access to a well-defined reward function, typical robotics pipelines rely on augmenting propioperceptive inputs with camera streams, and thus even well-defined rewards would need to be defined starting from unstructured observation |
|
|
|
|
|
Reward classifiers are particularly useful in treating complex, dynamic tasks |
|
|
|
|
|
Lastly, in order to improve on the robustness of their approach to different goals while maintaing practical scalability, @luoSERLSoftwareSuite2025 introduced a modified state and action space, expressing proprioperceptive configurations $q$ and actions $\dot q$ in the frame of the end-effector pose at $t=0$. Randomizing the initial pose of the end-effector ($s_0$), @luoSERLSoftwareSuite2025 achieved a similar result to that of manually randomizing the environment at every timestep, but with the benefit of maintaining the environment in the same condition across multiple training episodes, achieving higher scalability of their method thanks to the increased practicality of their approach. |
|
|
|
|
|
<Image |
|
|
src={ch3_hil_serl_examples} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'(A) HIL-SERL allows for real-world training of high performance RL agents by building on top advancements presented by of SAC, RLPD and SERL. (B) Example of human intervention during a HIL-SERL training process on a real-world SO-100.'}/> |
|
|
|
|
|
Building on off-policy deep Q-learning with replay buffers, entropy regularization for better exploration, expert demonstrations to guide learning, and a series of tools and recommendations for real-world training using reward classifiers (Figure <a href="#hil-serl-blocks" data-reference-type="ref" data-reference="hil-serl-blocks">[hil-serl-blocks]</a>), @luoPreciseDexterousRobotic2024 introduce human interactions during training, learning near-optimal policies in challenging real-world manipulation tasks in 1-2 hours. |
|
|
|
|
|
Human-in-the-Loop, Sample Efficient Robot reinforcement Learning (HIL-SERL) @luoPreciseDexterousRobotic2024 augments offline-to-online RL with targeted human corrections during training, and employs prior data to (1) train a reward classifier and (2) bootstrap RL training on expert trajectories. While offline demonstrations provide the initial dataset seeding learning and constraining early exploration, interactive, online corrections allow a human supervisor to intervene on failure modes and supply targeted interventions, greatly aiding the learning process @luoPreciseDexterousRobotic2024. Crucially, human intervention data is stored in *both* the offline and online replay buffers, differently from the autonomous transitions generated at training time and stored in the online buffer only. In turn, given an intervention timestep $k \in (0, T)$, length-$K$ human intervention data $\{ s^{\text{human}}_k, a^{\text{human}}_k, r^{\text{human}}_k, s^{\text{human}}_{k+1},\}_{k=1}^K$ is more likely to be sampled than the data generated online during training, providing stronger supervision to the agent while still allowing for autonomous learning. Empirically, HIL-SERL attains near-perfect success rates (99%+) on diverse manipulation tasks within 1-2 hours of training @luoPreciseDexterousRobotic2024, underscoring how offline datasets with online RL can markedly improve stability and data efficiency, and ultimately even allow real-world RL-training. |
|
|
|
|
|
#### Code Example- Real-world RL |
|
|
|
|
|
<Image |
|
|
src={ch3_hil_serl_architecture} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'HIL-SERL is a SOTA RL algorithm for training control policies directly in the real-world. Its implementation in lerobot relies on a decoupled actor-learner architecture, communicating over processes (and possibly networks) with queues used to share (1) transitions (s t , a t , r t , s t + 1) and (2) parameters θ .'}/> |
|
|
|
|
|
This example shows how to use the HIL-SERL implementation supported by `lerobot`. This code example is organized into four parts: we first show how to train a reward classifier from a custom set of demonstrations, then define the `Actor` and `Learner` components, and finally, we bring them together in a complete script showing how to use HIL-SERL in practice. |
|
|
|
|
|
At a higher level, the HIL-SERL architecture (Figure <a href="#ch3-hil-serl-architecture" data-reference-type="ref" data-reference="ch3-hil-serl-architecture">[ch3-hil-serl-architecture]</a>) relies on two main components: |
|
|
|
|
|
- An `Actor`, running a frozen policy network used to interact with the environment and obtain observations. Observations are used to both condition the frozen actor in selecting the action to enact, and to form $(s_t, a_t, r_t, s_{t+1})$ transitions that are shared with the `Learner`. Rewards are inferred using a custom, learned reward classifier trained on a dataset of offline demonstrations. |
|
|
|
|
|
- A `Learner`, used to optimize the policy’s parameters $\theta$ for maximum expected return. The learner samples batches of offline data from online and offline buffers in equal proportion @ballEfficientOnlineReinforcement2023, and shares updated parameters with the `Actor`. |
|
|
|
|
|
The HIL-SERL architecture presented in this example can be exclusively run locally, but the implementation in `lerobot` also allows the `Actor` and `Learner` to run on two separate machines connected by the network. |
|
|
|
|
|
<div class="pbox"> |
|
|
|
|
|
Training a Reward Classifier |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch3/01_reward_classifier.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch3/01_reward_classifier.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
<div class="pbox"> |
|
|
|
|
|
Defining the `Actor` |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch3/02_actor.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch3/02_actor.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
<div class="pbox"> |
|
|
|
|
|
Defining the `Learner` |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch3/03_learner.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch3/03_learner.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
<div class="pbox"> |
|
|
|
|
|
Using HIL-SERL |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch3/04_hil_serl.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch3/04_hil_serl.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
|
|
|
#### Limitations of RL in Real-World Robotics: Simulators and Reward Design |
|
|
|
|
|
Despite the advancements in real-world RL training, training RL agents for real-world tasks still suffers from the following limitations: |
|
|
|
|
|
- In those instances where real-world training experience is prohibitively expensive to gather (e.g., Tokamak control @degraveMagneticControlTokamak2022, Autonomous Stratospehere Navigation @bellemareAutonomousNavigationStratospheric2020)in-simulation training is often the only viable option. However, high-fidelity simulators for real-world problems can be difficult to build and maintain, especially for contact-rich manipulation and tasks involving deformable or soft materials. |
|
|
|
|
|
- Reward design is a fundamental source of brittleness in real-world RL pipelines. While shaping dense rewards is often necessary to guide exploration in long-horizon tasks, the process is error-prone and heavily reliant on human expertise and intuition. Poorly tuned terms can lead to specification gaming or convergence to local optima, making reward shaping a critical challenge for applying RL in practice. Sparse rewards that only signal successful trajectories can avoid these pitfalls but typically result in much slower learning due to reduced supervision. |
|
|
|
|
|
Advances in learning to act from potentially large corpora of human demonstrations via Behavioral Cloning (BC) address both of these concerns. Although suffering from an inherent suboptimality |
|
|
|
|
|
## Robot (Imitation) Learning |
|
|
|
|
|
<span id="learning-imitation" style="position: absolute;"></span> |
|
|
<Quote source="Norbert Wiener"> |
|
|
The best material model for a cat is another, or preferably the same cat |
|
|
</Quote> |
|
|
<div class="callout"> |
|
|
|
|
|
TL;DR Behavioral Cloning provides a natural platform to learn from real-world interactions without the need to design any reward function, and generative models prove more effective than point-wise policies at dealing with multimodal demonstration datasets. |
|
|
|
|
|
</div> |
|
|
<Image |
|
|
src={ch4_bc_trajectories} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'(A) Average (with standard deviation) evolution of the actuation levels over the first 5 recorded episodes in lerobot/svla_so101_pickplace. Proprioperceptive states provide invaluable to determine the robot’s state during an episode. (B) Camera frames are also recorded alongside measurements on the robot’s state, capturing information about the robot’s interaction with its environment.'}/> |
|
|
|
|
|
Learning from human demonstrations provides a pragmatic alternative to the RL pipeline discussed in Section <a href="#learning-rl" data-reference-type="ref" data-reference="learning-rl">[learning-rl]</a>. Indeed, especially in real-world robotics, online exploration is typically <mark>costly and potentially unsafe</mark>, and designing (dense) reward signals is a <mark>brittle and task-specific</mark> process. Further, even success detection itself often requires bespoke instrumentation, while episodic training demands reliable resets |
|
|
|
|
|
Formally, let $\mathcal D = \{ \tau^{(i)} \}_{i=1}^N$ be a set of expert trajectories, with $\tau^{(i)} = \{(o_t^{(i)}, a_t^{(i)})\}_{t=0}^{T_i}$ representing the $i$-th length-$T_i$ trajectory in $\mathcal D$, $o_t \in \mathcal O$ denoting observations (e.g., images and proprioception altogether), and $a_t \in \mathcal A$ the expert actions. Typically, observations $o \in \mathcal O$ consist of both image and proprioperceptive information, while actions $a \in \mathcal A$ represent control specifications for the robot to execute, e.g. a joint configuration. Note that differently from Section <a href="#learning-rl" data-reference-type="ref" data-reference="learning-rl">[learning-rl]</a>, in the imitation learning context $\mathcal D$ denotes an offline dataset collecting $N$ length-$T_i$ reward-free (expert) human trajectories $\tau^{(i)}$, and *not* the environment dynamics. Similarily, in this section $\tau^{(i)}$ represent a length-$T_i$ trajectory of observation-action pairs, which crucially *omits entirely any reward* information. Figure <a href="#ch4-bc-trajectories" data-reference-type="ref" data-reference="ch4-bc-trajectories">[ch4-bc-trajectories]</a> graphically shows trajectories in terms of the average evolution of the actuation on the 6 joints of a teleoperated SO-100 manipulator. Notice how proprioperceptive states are captured jointly with camera frames over the course of the recorded episodes, providing a unified high-frame rate collection of both image and joint teleoperation data. Figure <a href="#ch4-observation-action-mapping" data-reference-type="ref" data-reference="ch4-observation-action-mapping">[ch4-observation-action-mapping]</a> shows $(o_t, a_t)$-pairs for the same dataset, with the actions performed by the human expert illustrated alongside the corresponding observation. In principle, (expert) trajectories $\tau^{(i)}$ can have different lengths since demonstrations might exhibit multi-modal strategies to attain the same goal, resulting in multiple, different behaviors. |
|
|
|
|
|
<Image |
|
|
src={ch4_observation_action_mapping} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Sample observations and action pairs over the course of a given trajectory recorded in lerobot/svla_so101_pickplace. Observations, comprising of both proprioperceptive and visual information, are recorded alongside the configuration of a second, leader robot controlled by a human expert, providing complete information for regressing actions given observations.'}/> |
|
|
|
|
|
Behavioral Cloning (BC) @pomerleauALVINNAutonomousLand1988 aims at producing synthetic behaviors by learning the mapping from observations to actions, and in its most natural formulation can be effectively tackled as a *supevised* learning problem, consisting of learning the (deterministic) mapping $f: \mathcal O\mapsto \mathcal A, \ a_t = f(o_t)$ by solving |
|
|
``` math |
|
|
\htmlId{loss-minimization-SL}{\min_{f} \mathbb{E}_{(o_t, a_t) \sim p(\bullet)} \mathcal L(a_t, f(o_t)),} |
|
|
``` |
|
|
given an arbitrary risk function $\mathcal L: \mathcal A \times \mathcal A \mapsto \mathbb{R}, \ \mathcal L (a, a^\prime)$. |
|
|
|
|
|
Typically, the expert’s joint observation-action distribution $p: \mathcal O\times \mathcal A\mapsto [0,1]$ is assumed to be unknown, in keeping with a classic Supervised Learning (SL) framework[^3]. However, differently from standard SL assumptions, the samples collected in $\mathcal D$ |
|
|
|
|
|
Despite the inherent challenges of learning from non-i.i.d. data, the BC formulation presents several operational advantages in robotics. First, training happens offline and naturally accomodates for expert, demonstration data, hereby severily limiting exploration risks by preventing the robot from performing dangerous actions altogether, by anchoring action in imitation. Second, reward design is entirely unnecessary in BC, as demonstrations already reflect human intent. The absence of rewards also prevents the risk of misalignment and specification gaming (*reward hacking*), otherwise inherent in purely reward-based RL @heessEmergenceLocomotionBehaviours2017. Third, because expert trajectories encode terminal conditions, success detection and resets are implicit in the dataset. Finally, empirical evidence suggests the performance of BC scales naturally with growing corpora of demonstrations collected across tasks, embodiments, and environments. Nonetheless, BC can, in principle, only reproduce behaviors that are at best as good as those of the demonstrator, and therefore offers no remedy for the suboptimal decisions that humans may enact. This limitation is particularly problematic in sequential decision-making tasks where expert demonstrations are scarce |
|
|
|
|
|
<Image |
|
|
src={ch4_issues_with_bc} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Point-wise policies suffer from limitations due to (A) covariate shifts and (B) poor approximation of multimodal demonstrations. (A) Small errors may drive the policy out of distribution, incuring in a vicious circle ultimately resulting in failure. (B) Both modes of reaching for a target object in the scene--either left or right-first--are equally as good and thus equally as likely to be present in a dataset of human demonstrations, ultimately resulting in multimodal demonstrations.'}/> |
|
|
|
|
|
While conceptually elegant, *point-estimate policies* $f : \mathcal O\mapsto \mathcal A$ learned by solving eq. <a href="#loss-minimization-SL" data-reference-type="ref" data-reference="loss-minimization-SL">[loss-minimization-SL]</a> have been observed to suffer from (1) compounding errors @rossReductionImitationLearning2011 and (2) poor fit to multimodal distributions @florenceImplicitBehavioralCloning2022, @keGraspingChopsticksCombating2020. Figure <a href="#ch4-issues-with-bc" data-reference-type="ref" data-reference="ch4-issues-with-bc">[ch4-issues-with-bc]</a> illustrates these two key issues related to learning *explicit policies* @florenceImplicitBehavioralCloning2022. Besides sequentiality in $\mathcal D$, compounding errors due to *covariate shift* may also prove catastrophic, as even small $\epsilon$-prediction errors $0 < \Vert \mu(o_t) - a_t \Vert \leq \epsilon$ can quickly drive the policy into out-of-distribution states, incuring in less confident generations and thus compounding errors (Figure <a href="#ch4-issues-with-bc" data-reference-type="ref" data-reference="ch4-issues-with-bc">[ch4-issues-with-bc]</a>, left). Moreover, point-estimate policies typically fail to learn *multimodal* targets, which are very common in human demonstrations solving real-world robotics problems, as multiple trajectories can be equally as good towards the accomplishment of a goal (e.g., symmetric grasps, Figure <a href="#ch4-issues-with-bc" data-reference-type="ref" data-reference="ch4-issues-with-bc">[ch4-issues-with-bc]</a>, right). In particular, unimodal regressors tend to average across modes, yielding indecisive or even unsafe commands @florenceImplicitBehavioralCloning2022. To address poor multimodal fitting, @florenceImplicitBehavioralCloning2022 propose learning the *generative model* $p(o, a)$ underlying the samples in $\mathcal D$, rather than explicitly learning a prediction function $f- a = f(o)$. |
|
|
|
|
|
### A (Concise) Introduction to Generative Models |
|
|
|
|
|
Generative Models (GMs) aim to learn the stochastic process underlying the very generation of the data collected, and typically do so by fitting a probability distribution that approximates the unknown *data distribution*, $p$. In keeping with the GM literature, $p(x) \leftarrow \mathbb P(x), x \sim p$. In the case of BC, the unknown data distribution $p$ may represent the expert’s joint distribution over $(o, a)$-pairs. Thus, given a finite set of $N$ pairs $\mathcal D = \{ (o,a)_i \}_{i=0}^N$ available as an imitation learning target (and thus assumed to be i.i.d.), GMs seek to learn a *parametric* distribution $p_\theta(o,a)$ such that (1) new samples $(o,a) \sim p_\theta(\bullet)$ resemble those stored in $\mathcal D$, and (2) high likelihood is assigned to the *observed* regions of the *unobservable* $p$. Likelihood-based learning provides a principled training objective to achieve both goals, and it is thus extensively used in GMs @prince2023understanding. |
|
|
|
|
|
#### Variational Auto-Encoders |
|
|
|
|
|
<Image |
|
|
src={ch4_task_effect_on_pairs} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Intuitively, latent variable in a single latent model may contain information regarding the task being performed, which directly results in the likelihood of the same observation-action pair being different for two different tasks. When (A) picking a block the likelihood of a wide gripper’s opening should be higher than narrower one, while it should be the opposite when (B) pushing the block.'}/> |
|
|
|
|
|
A common inductive bias used in GM posits samples $(o,a)$ are influenced from an unobservable latent variable $z \in Z$, resulting in: |
|
|
``` math |
|
|
\htmlId{BC-latent-variable}{p (o,a) = \int_{\operatorname{supp}({Z})} p(o,a \vert z) p(z)} |
|
|
``` |
|
|
Intuitively, in the case of observation-action pairs $(o, a)$ for a robotics application, $z$ could be interpreted as some high level representation of the underlying task being performed by the human demonstrator. In such case, treating $p(o,a)$ as a marginalization over $\operatorname{supp}({Z})$ of the complete joint distribution $p(o,a,z)$ natively captures the effect different tasks have on the likelihood of observation-action pairs. Figure <a href="#ch4-task-effect-on-pairs" data-reference-type="ref" data-reference="ch4-task-effect-on-pairs">[ch4-task-effect-on-pairs]</a> graphically illustrates this concept in the case of a (A) picking and (B) pushing task, for which, nearing the target object, the likelihood of actions resulting in opening the gripper |
|
|
|
|
|
<Image |
|
|
src={ch4_latent_variable_model} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'(A) The latent variable model in a robotics application regulates influence between observed ( o, a) variables and an unobservable latent variable. (B) VAEs approximate exact latent variable models by means of variational inference.'}/> |
|
|
|
|
|
Given a dataset $\mathcal D$ consisting of $N$ i.i.d. observation-action pairs, the log-likelihood of all datapoints under $\theta$ (in Bayesian terms, the *evidence* $p_\theta(\mathcal D)$) can be written as: |
|
|
<span id="evidence-definition-1" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\log p_\theta(\mathcal D) &= \log \sum_{i=0}^N p_\theta ((o,a)_i) \\ |
|
|
&= \log \sum_{i=0}^N \int_{\operatorname{supp}({Z})} p_\theta((o,a)_i \vert z) p(z) \\ |
|
|
&= \log \sum_{i=0}^N \int_{\operatorname{supp}({Z})} \frac{q_\theta(z \vert (o,a)_i)}{q_\theta(z \vert (o,a)_i)} \cdot p_\theta((o,a)_i \vert z) p(z) \\ |
|
|
&= \log \sum_{i=0}^N \mathbb E_{z \sim q_\theta(\bullet \vert (o,a)_i)} [\frac{p(z)}{q_\theta(z \vert (o,a)_i)} \cdot p_\theta((o,a)_i \vert z)], |
|
|
\end{align} |
|
|
``` |
|
|
where we used eq. <a href="#BC-latent-variable" data-reference-type="ref" data-reference="BC-latent-variable">[BC-latent-variable]</a> in eq. <a href="#evidence-definition-1" data-reference-type="ref" data-reference="evidence-definition-1">[evidence-definition-1]</a>, multiplied by $1 = \frac{q_\theta(z \vert (o,a)_i)}{q_\theta(z \vert (o,a)_i)}$ in eq. <a href="#evidence-definition-2" data-reference-type="ref" data-reference="evidence-definition-2">[evidence-definition-2]</a>, and used the definition of expected value in eq. <a href="#evidence-definition" data-reference-type="ref" data-reference="evidence-definition">[evidence-definition]</a>. |
|
|
|
|
|
In the special case where one assumes distributions to be tractable, $p_\theta (\mathcal D)$ is typically tractable too, and $\max_\theta \log p_\theta(\mathcal D)$ provides a natural target for (point-wise) infering the unknown parameters $\theta$ of the generative model. Unfortunately, eq. <a href="#evidence-definition" data-reference-type="ref" data-reference="evidence-definition">[evidence-definition]</a> is rarely tractable when the distribution $p$ is modeled with approximators such as neural networks, especially for high-dimensional, unstructured data. |
|
|
|
|
|
In their seminal work on Variational Auto-Encoders (VAEs), @kingma2013auto present two major contributions to learn complex latent-variable GMs from unstructured data, proposing (1) a tractable, variational lower-bound to eq. <a href="#evidence-definition" data-reference-type="ref" data-reference="evidence-definition">[evidence-definition]</a> as an optimization target to jointly learn likelihood and posterior and (2) using high-capacity function approximators to model the likelihood $p_\theta(o,a\vert z)$ and (approximate) posterior distribution $q_\phi(z \vert o,a) \approx q_\theta(z \vert o,a)$. |
|
|
|
|
|
In particular, the lower bound on eq. <a href="#evidence-definition" data-reference-type="ref" data-reference="evidence-definition">[evidence-definition]</a> (Evidence LOwer Bound, *ELBO*) can be derived from eq. <a href="#evidence-definition" data-reference-type="ref" data-reference="evidence-definition">[evidence-definition]</a> applying Jensen’s inequality |
|
|
<span id="ELBO-intractable" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\log p_\theta(\mathcal D) &\geq \sum_{i=0}^{N} \left( |
|
|
\mathbb{E}_{z \sim q_\theta(\bullet \vert (o,a)_i)} \big[ \log p_\theta((o,a)_i \vert z) \big] |
|
|
+ \mathbb{E}_{z \sim q_\theta(\bullet \vert (o,a)_i)} [\log \left( \frac{p(z)}{q_\theta(z \vert (o,a)_i)} \right)] |
|
|
\right) \\ |
|
|
&= \sum_{i=0}^{N} \left( |
|
|
\mathbb{E}_{z \sim q_\theta(\bullet \vert (o,a)_i)} \big[ \log p_\theta((o,a)_i \vert z) \big] |
|
|
- \text{D}_{\text{KL}}\big[ q_\theta(z \vert (o,a)_i) \Vert p(z) \big] |
|
|
\right) |
|
|
\end{align} |
|
|
``` |
|
|
|
|
|
The true, generally intractable, posterior $q_\theta (z \vert o,a)$ prevents computing both the expectation and KL divergence terms in eq. <a href="#ELBO-intractable" data-reference-type="ref" data-reference="ELBO-intractable">[ELBO-intractable]</a>, and therefore @kingma2013auto propose deriving the ELBO using an *approximate* posterior $q_\phi(z \vert o,a)$, resulting in the final, tractable, ELBO objective, |
|
|
<span id="ELBO" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\text{ELBO}_{\mathcal D}(\theta, \phi) = \sum_{i=0}^{N} \left( |
|
|
\mathbb{E}_{z \sim q_\phi(\bullet \vert (o,a)_i)} \big[ \log p_\theta((o,a)_i \vert z) \big] |
|
|
- \text{D}_{\text{KL}}\big[ q_\phi(z \vert (o,a)_i) \Vert p(z) \big] |
|
|
\right) |
|
|
|
|
|
\end{align} |
|
|
``` |
|
|
From Jensen’s inequality, maximizing ELBO results in maximizing the log-likelihood of the data too, thus providing a natural, tractable optimization target. Indeed, expectations can be estimated using MC estimates from the learned distributions in eq. <a href="#ELBO" data-reference-type="ref" data-reference="ELBO">[ELBO]</a>, while the KL-divergence term can typically be computed in closed-form (1) modeling $q_\phi$ as a Gaussian $q_\phi(z \vert o,a) = \mathcal N\big(\mu_\phi(o,a), \Sigma_\phi(o,a) \big)$ with learned mean vector $\mu_\phi(o,a)$ and learned variance-covariance matrix $\Sigma_\phi(o,a)$ and (2) imposing a standard Gaussian prior on the latent space, $p(z) = \mathcal N(\mathbf{0}, \mathbf{I})$. |
|
|
|
|
|
An intuitive explanation of the learning dynamics of VAEs can be given considering the equivalent case of *minimizing the negative ELBO*, which admits the particularly interpretable factorization (considering, without loss of generality, only one $(o,a) \sim \mathcal D$): |
|
|
<span id="VAE-min-neg-ELBO" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\min_{\theta, \phi} - \text{ELBO}_{\mathcal (o,a) \sim \mathcal D}(\theta, \phi) &= \min_{\theta, \phi}\mathbf{L^{\text{rec}}}(\theta) + \mathbf{L^{\text{reg}}}(\phi), \\ |
|
|
\mathbf{L^{\text{rec}}}(\theta) &= \mathbb{E}_{z \sim q_\phi(\bullet \vert o,a}) \big[ \log p_\theta(o,a \vert z) \big] \\ |
|
|
\mathbf{L^{\text{reg}}}(\phi) &= \text{D}_{\text{KL}}\big[ q_\phi(z \vert o,a) \Vert p(z) \big]. |
|
|
\end{align} |
|
|
``` |
|
|
|
|
|
For any given $(o,a)$ pair, the expected value term in eq. <a href="#VAE-Lrec" data-reference-type="ref" data-reference="VAE-Lrec">[VAE-Lrec]</a> is typically computed via MC estimates, resulting in |
|
|
|
|
|
``` math |
|
|
-\mathbb{E}_{z \sim q_\phi(\bullet \vert o,a)} \big[ \log p_\theta(o,a \vert z) \big] = \mathbf{L^{\text{rec}}} \approx - \frac{1}{n} \sum_{i=0}^n \log p_\theta(o,a \vert z_i). |
|
|
``` |
|
|
Assuming $p_\theta(o,a \vert z)$ to be parametrized with an isotropic Gaussian distribution with mean $\mu_\theta (z) \in \mathbb R^d$ and variance $\sigma^2$, the log-likelihood thus simplifies to- |
|
|
``` math |
|
|
\log p(o,a \vert z_i) = -\frac{1}{2\sigma^{2}} \big \Vert (o,a)-\mu_\theta(z_i) \big\Vert_2^2 -\frac{d}{2}\log(2\pi \sigma^{2}) \implies \mathbf{L^\text{rec}} \approx \frac {1}{n} \sum_{i=0}^n \big\Vert (o,a) - \mu_\theta(z_i) \big \Vert^2_2 |
|
|
``` |
|
|
In practice, it is common to approximate the learned likelihood $p_\theta(o,a \vert z)$ with a parametric distribution (e.g., Gaussian) whose parameters are given by a learned coefficient vector derived from $\mu_\theta(z), \ z \sim p(\bullet)$. Under this formulation, learning a VAE amounts to (1) *reconstructing* the examples in $\mathcal{D}$ by minimizing (1) the reconstruction loss $\mathbf{L^{\text{rec}}}$ |
|
|
|
|
|
#### Diffusion Models |
|
|
|
|
|
VAEs approximate probability distributions via a *single* latent variable model, assuming the underlying unknown distribution can be factored according to eq. <a href="#BC-latent-variable" data-reference-type="ref" data-reference="BC-latent-variable">[BC-latent-variable]</a>, and solve the variational-inference problem of jointly learning the likelihood $p_\theta$ and (approximate) posterior $q_\phi$ for such model. In that, the unknown data distribution $p(o,a)$ is effectively approximated via $\int_Z p(z) p_\theta(o,a \vert z)$, and the underlying generative process reproduced by (1) sampling a latent variable and (2) learning to decode it into a high-likelihood sample under the (unknown) $p(o,a)$. Diffusion Models (DMs) @hoDenoisingDiffusionProbabilistic2020 are another class of GMs which treat the similar problem of approximating an underlying unknown data distribution--*variational inference*--by *partially* extending VAEs to the case where *multiple* latent variables influence each other and the generative process underlying $o,a$ itself. In particular, DMs posit the generative process can be decomposed to a series of piece-wise (Markovian) interactions between (latent) variables (Figure <a href="#ch4-many-latents" data-reference-type="ref" data-reference="ch4-many-latents">[ch4-many-latents]</a>), resulting in |
|
|
<span id="BC-multi-latent-model-1" style="position- absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
p(\underbrace{o,a}_{= z_0}) &= \int_{\operatorname{supp}({Z_0})} \int_{\operatorname{supp}({Z_1})} \ldots \int_{\operatorname{supp}({Z_T})} p(z_0, z_1, \dots z_T) \\ |
|
|
p(z_0, z_1, \dots z_T) &= p(z_T) \prod_{t=1}^{T} p(z_{t-1} \vert z_t), |
|
|
\end{align} |
|
|
``` |
|
|
where we explicitly showed the marginalization over the multiple latents in eq. <a href="#BC-multi-latent-model-1" data-reference-type="ref" data-reference="BC-multi-latent-model-1">[BC-multi-latent-model-1]</a>, and used the law of conditional probability and Markov property in eq. <a href="#BC-multi-latent-model-2" data-reference-type="ref" data-reference="BC-multi-latent-model-2">[BC-multi-latent-model-2]</a>. Also, for ease of notation, we will refer to observation-action pairs $o,a$ as $z_0$. |
|
|
|
|
|
<Image |
|
|
src={ch4_many_latents} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'HMLV models posit the data generation process is influenced by a stack of Markov-dependent latent variables, with samples from the posterior distribution being progressively higher up in the hierarchy.'}/> |
|
|
|
|
|
Similar to VAEs, it is generally not possible to assign an *exact* interpretation to the latent variables. Nevertheless, a reasonable application-driven intuition is that Hierarchical Markov Latent Variable (HMLV) models, by capturing hierarchical and decoupled interactions among latent variables, can reflect the different resolutions at which conditioning factors intervene. For example, in a robotics setting, one might naturally distinguish between high-level trajectory planning (higher up in the hierarchy, $t \to T$) and fine-grained motion adjustments (closer to empirical observations, $t \to 0$). In that, HMLV models thus provide a framework to perform variational inference via multiple, sequential sampling steps from different higher level distributions instead of approximating the generative process with a single-latent variable model. DMs are a particular instantiation of HMLV models for which the posterior is fixed to $q( z_t \vert z_{t-1}) = \mathcal N(z_t \sqrt{1-\beta_t}, \beta_t \mathbf{I})$, for a given $\beta_t \in \mathbb R^+$. In practice, $\beta_t$ is used to iteratively reduce the signal-to-noise ratio along the latents’ hierarchy, similarily to how a diffusion process influences the information of a physical system. |
|
|
|
|
|
Just like VAEs, DMs attemp to learn to reproduce an underlying data distribution $p (o,a)$ given a collection of i.i.d. samples approximating the model posited to have generated the data in the first place (eq. <a href="#BC-multi-latent-model-1" data-reference-type="ref" data-reference="BC-multi-latent-model-1">[BC-multi-latent-model-1]</a>). Similarily to VAEs, DMs approximate the process of sampling from the unknown $p(o,a)$ by (1) sampling from an easy-to-sample distribution (e.g., Gaussian) and (2) learning to reconstruct high-likelihood samples under the unknown distribution. However, in stark contrast with VAEs, the easy-to-sample distribution contains *no mutual information* regarding the data distribution $p(o,a)$. Crucially, as no information from the sample $(o,a)$ (denoted as $z_0 \equiv (o,a)$ for simplicity of notation) is assumed to be propagated throughout the chain of latents, the posterior $q(z_t \vert z_{t-1})$ assumes a relatively amicable structure in DMs, reducing complexity. The *true* likelihood $p(z_{t-1} \vert z_t)$ is instead typically approximated using the parametrization $p_\theta (z_{t-1} \vert z_t)$. In that, the information contained in the unknwon data distribution is *reconstructed* via a process in which samples from a fixed distribution are iteratively turned into (ideally) high-likelihood samples under $p(o,a)$ |
|
|
|
|
|
Under such model, we can express the log-likelihood of an arbitrary sample $z_0$ as: |
|
|
<span id="diffusion-1" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\log p_\theta (z_0) &= \log \int_{\operatorname{supp}({Z_1}) \times \operatorname{supp}({Z_2}) \times \dots \times \operatorname{supp}({Z_T})} p_\theta(\underbrace{z_0, z_1, z_2, \dots z_T}_{z_{0:T}}) \\ |
|
|
&= \log \int_{\operatorname{supp}({Z_{1:T}})} \frac{p_\theta(z_{0:T}) \cdot q(z_{1:T} \vert z_0)}{q(z_{1:T} \vert z_0)} \\ |
|
|
&= \log \mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \bigg[ \frac{p_\theta(z_{0:T})}{q(z_{1:T} \vert z_0)} \bigg] \\ |
|
|
&\geq \mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \bigg[ \log \frac{p_\theta(z_{0:T})}{q(z_{1:T} \vert z_0)} \bigg] \\ |
|
|
&= \mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \bigg[ \log \frac{p(z_T) \prod_{t=1}^{T} p_\theta (z_{t-1} \vert z_t)}{\prod_{t=1}^T q(z_t \vert z_{t-1})} \bigg] \\ |
|
|
&= \mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \bigg[ \log \frac{p(z_T) \cdot p_\theta (z_0 \vert z_1) \prod_{t=2}^{T} p_\theta (z_{t-1} \vert z_t)}{q(z_T \vert z_{T-1}) \prod_{t=1}^{T-1} q(z_t \vert z_{t-1})} \bigg] \\ |
|
|
&= \mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \bigg[ \log \frac{p(z_T) \cdot p_\theta (z_0 \vert z_1) \prod_{t=1}^{T-1} p_\theta (z_{t} \vert z_{t+1})}{q(z_T \vert z_{T-1}) \prod_{t=1}^{T-1} q(z_t \vert z_{t-1})} \bigg] \\ |
|
|
&= |
|
|
\mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \bigg[ \log \frac{p(z_T) \cdot p_\theta (z_0 \vert z_1)}{q(z_t \vert z_{t-1})} \bigg] + |
|
|
\mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \bigg[ \log \prod_{t=1}^{T-1} \frac{p_\theta (z_{t} \vert z_{t+1})}{q(z_t \vert z_{t-1})}\bigg] |
|
|
\\ |
|
|
&= |
|
|
\mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \big[ \log p_\theta (z_0 \vert z_1) \big] + |
|
|
\mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \bigg[ \log \frac{p (z_T)}{q(z_T \vert z_{T-1})} \bigg] + |
|
|
\sum_{t=1}^{T-1} \mathbb{E}_{z_{1:T} \sim q(\bullet \vert z_0)} \bigg[ \log \frac{p_\theta (z_{t} \vert z_{t+1})}{q(z_t \vert z_{t-1})}\bigg] |
|
|
\\ |
|
|
&= |
|
|
\mathbb{E}_{z_1 \sim q(\bullet \vert z_0)} \big[ \log p_\theta (z_0 \vert z_1) \big] + |
|
|
\mathbb{E}_{z_{T-1:T} \sim q(\bullet \vert z_0)} \bigg[ \log \frac{p (z_T)}{q(z_T \vert z_{T-1})} \bigg] + |
|
|
\sum_{t=1}^{T-1} \mathbb{E}_{z_{t-1:t+1} \sim q(\bullet \vert z_0)} \bigg[ \log \frac{p_\theta (z_{t} \vert z_{t+1})}{q(z_t \vert z_{t-1})}\bigg] |
|
|
\\ |
|
|
&= \mathbb{E}_{z_1 \sim q(\bullet \vert z_0)} \log p_\theta (z_0 \vert z_1) - \mathbb{E}_{z_{T-1} \sim q(\bullet \vert z_0)} \big[ \text{D}_{\text{KL}}(q(z_T \vert z_{T-1}) \Vert p(z_T) ) \big] \\ |
|
|
&- \sum_{t=1}^{T-1} \mathbb{E}_{(z_{t-1}, z_{t+1}) \sim q(\bullet \vert z_0)} \big[ \text{D}_{\text{KL}}(q(z_t \vert z_{t-1}) \Vert p_\theta(z_t \vert z_{t+1}) ) \big], \notag |
|
|
\end{align} |
|
|
``` |
|
|
where we: used eq. <a href="#BC-multi-latent-model-1" data-reference-type="ref" data-reference="BC-multi-latent-model-1">[BC-multi-latent-model-1]</a> and multiplied by $1 = \tfrac{q(z_{1-T} \vert z_0)}{q(z_{1:T} \vert z_0)}$ in eq. <a href="#diffusion-1" data-reference-type="ref" data-reference="diffusion-1">[diffusion-1]</a>; used Jensen’s inequality in eq. <a href="#diffusion-jensen" data-reference-type="ref" data-reference="diffusion-jensen">[diffusion-jensen]</a>; used the law of conditional probability for both numerator and denominator in eq. <a href="#diffusion-2" data-reference-type="ref" data-reference="diffusion-2">[diffusion-2]</a>; stepped forward and backward the products in the numerator and denominator products in eq. <a href="#diffusion-3" data-reference-type="ref" data-reference="diffusion-3">[diffusion-3]</a>, respectively; reindexed the product terms in eq. <a href="#diffusion-4" data-reference-type="ref" data-reference="diffusion-4">[diffusion-4]</a>; removed out-of-expectation variables in eq. <a href="#diffusion-expectation-indices" data-reference-type="ref" data-reference="diffusion-expectation-indices">[diffusion-expectation-indices]</a>; used the defintion of KL-divergence in eq. <a href="#diffusion-likelihood" data-reference-type="ref" data-reference="diffusion-likelihood">[diffusion-likelihood]</a>. In turn, eq. <a href="#diffusion-likelihood" data-reference-type="ref" data-reference="diffusion-likelihood">[diffusion-likelihood]</a> provides an optimization target to *learn* $p_\theta$ solving $\max_\theta \log p_\theta (\mathcal D)$. |
|
|
|
|
|
In their seminal work on using DMs for variational inference, @hoDenoisingDiffusionProbabilistic2020 introduce major contributions regarding solving $\min_\theta -\log p_\theta(z_0)$. In particular, @hoDenoisingDiffusionProbabilistic2020 exclusively adopt a *fixed, isotropic Gaussian posterior* in the form of $q(z_t \vert z_{t-1}) = \mathcal{N}(\sqrt{1-\beta_t}z_{t-1}, \beta_t \mathbf I)$. The choice of adopting Gaussians has profound implications on the generative process modeled. Indeed, under the (mild) assumption that the variance is sufficiently small $\beta_t \leq \eta, \eta \in \mathbb R^+$, @sohnLearningStructuredOutput2015 proved that the likelihood $p(z_{t-1} \vert z_t)$ is Gaussian as well, which allows for the particularly convenient parametrization of the approximate likelihood $p_\theta (z_{t-1} \vert z_t) = \mathcal N(\mu_\theta(z_t, t), \Sigma_\theta(z_t,t)), \ t \in [1,T]$, as well as for closed-form tractability of the KL-divergence terms in eq. <a href="#diffusion-likelihood" data-reference-type="ref" data-reference="diffusion-likelihood">[diffusion-likelihood]</a>. Further, the posterior’s structure also enables the analytical description of the distribution of the $t$-th latent variable, $q(z_t \vert z_0) = \mathcal N (\sqrt{\bar{\alpha}_t}z_0, (1-\bar{\alpha}_t) \mathbf{I})$, with $\alpha_t = 1-\beta_t, \ \bar \alpha_t = \prod_{k=1}^t \alpha_k$, conveniently preventing iterative posterior sampling simplifying computing eq. <a href="#diffusion-likelihood" data-reference-type="ref" data-reference="diffusion-likelihood">[diffusion-likelihood]</a>. It follows- |
|
|
<span id="diffusion-likelihood-gradient" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\nabla_\theta \log p_\theta (z_0) = \mathbb E_{z_1 \sim q(\bullet \vert z_0)} \nabla_\theta \log p_\theta (z_0 \vert z_1) - \sum_{t=1}^{T-1} \mathbb E_{z_{t-1}, z_{t+1} \sim q(\bullet \vert z_0)} \nabla_\theta \text{D}_{\text{KL}}(q(z_t \vert z_{t-1}) \Vert p_\theta(z_t \vert z_{t+1}), |
|
|
\end{align} |
|
|
``` |
|
|
where the former term is equivalent to the reconstruction term in eq. <a href="#VAE-min-neg-ELBO" data-reference-type="ref" data-reference="VAE-min-neg-ELBO">[VAE-min-neg-ELBO]</a> and the latter term can be obtained in closed form. |
|
|
|
|
|
<Image |
|
|
src={ch4_diffusion_robot_actions} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'DMs iteratively corrupt samples (left) from an unknown distribution into a quasi-standard Gaussian (center), learning the displacement field (right) that permits to reconstruct samples from the unknown target distribution by iteratively denoising samples of a tractable, easy-to-sample distribution.'}/> |
|
|
|
|
|
Besides mathematical tractability of eq. <a href="#diffusion-likelihood-gradient" data-reference-type="ref" data-reference="diffusion-likelihood-gradient">[diffusion-likelihood-gradient]</a>, adopting Gaussian posteriors allows for a particularly intuitive interpretation of the training dynamics of DMs @permenterInterpretingImprovingDiffusion2024. As the hierarchical latent variables are repeatedly corrupted by applying increasingly more Gaussian noise, they progressively lose information about the original (unknown) sample $z_0$, converging toward a standard Gaussian which eventually contains no information at all (Figure <a href="#diffusion-robot-actions" data-reference-type="ref" data-reference="diffusion-robot-actions">[diffusion-robot-actions]</a>). Figure <a href="#diffusion-robot-actions" data-reference-type="ref" data-reference="diffusion-robot-actions">[diffusion-robot-actions]</a> illustrates this process on a simplified, bidimensional observation-action distribution, where we considered $o=q_2$ and $a=q^h_2$, with $q_2$ denoting the robot’s *elbow flex* actuation and $q^h_2$ the corresponding human teleoperator’s elbow flex. Because the recorded behavior is teleoperated, measurements mostly distribute along the line $a = o + \eta, \eta \sim N(0,1)$, with $\eta$-variability accouting for minor control inconsistencies (Figure <a href="#ch4-action-vs-observation-distribution" data-reference-type="ref" data-reference="ch4-action-vs-observation-distribution">[ch4-action-vs-observation-distribution]</a>). Notice how corrupted samples distribute differently from the most reasonable structure $a \simeq o$, further underscoring how diffusion corrupts both the individual samples and the global distribution (Figure <a href="#diffusion-robot-actions" data-reference-type="ref" data-reference="diffusion-robot-actions">[diffusion-robot-actions]</a>, left and center). In this, using Gaussian posteriors |
|
|
<span id="diffusion-simplified-loss" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
|
|
|
\mathcal L(\theta) = \mathbb{E}_{t, z_0, \epsilon} \big[ |
|
|
\Vert \epsilon - \epsilon_\theta(\sqrt{\bar \alpha_t} z_0 + \epsilon \sqrt{1 - \bar \alpha_t}, t) \Vert^2 \big], \quad t \sim \mathcal{U}(\{1,\dots,T\}), \quad |
|
|
z_0 \sim \mathcal{D}, \quad |
|
|
\epsilon \sim \mathcal{N}(\mathbf{0},\mathbf{I}). |
|
|
\end{align} |
|
|
``` |
|
|
|
|
|
<Image |
|
|
src={ch4_action_vs_observation_distribution} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'A joint action-observation distribution, in the simplified case where the observation is the elbow-flex actuation in a SO-100, and the action is the recorded position for the same joint from the teleoperator arm. The motion recorded being teleoperated, the points distribute along a the diagonal.'}/> |
|
|
|
|
|
In this simplified (minimization) objective, the optimization process differs from eq. <a href="#diffusion-likelihood" data-reference-type="ref" data-reference="diffusion-likelihood">[diffusion-likelihood]</a> in that, rather than maximizing $p_\theta$ directly, the parameters $\theta$ of the pairwise likelihood $p_\theta(z_{t-1} \vert z_t)$ are adjusted to *predict the total displacement* $\epsilon$ for a randomly long ($t \sim \mathcal{U}(\{1,\dots,T\})$) diffusion process starting from a sample of the target distribution. |
|
|
|
|
|
By learning the total displacement from a generally, uninformative corrupted sample obtained diffusing information and a sample from an unknown distribution @hoDenoisingDiffusionProbabilistic2020 show that one can approximate the underlying distribution reversing the displacement, *denoising* samples. Interestingly, under the hypothesis that real-world data belongs to a single, higher-dimensional manifold (Manifold Hypothesis), @permenterInterpretingImprovingDiffusion2024 show that diffusion learns the gradient of a distance function from any off-point manifold (such as perturbed, uniformative samples), and the data manifold itself. Following this gradient |
|
|
<span id="diffusion-denoising-definition" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
z_{t-1} = \frac{1}{\sqrt{\alpha_t}} \left( z_t - \frac{\beta_t}{\sqrt{1 - \bar\alpha_t}} \epsilon_\theta(z_t, t) \right) + \sigma_t \epsilon, \quad \epsilon \sim \mathcal N(\mathbf{0}, \mathbf{I}), |
|
|
\end{align} |
|
|
``` |
|
|
thus showing that the lower-level latent variables in a DM can be obtained by iteratively removing noise from the one-step higher order variable, using the noise regressor $\epsilon_\theta(z_t, t)$ learned minimizing eq. <a href="#diffusion-simplified-loss" data-reference-type="ref" data-reference="diffusion-simplified-loss">[diffusion-simplified-loss]</a>. |
|
|
|
|
|
#### Flow Matching |
|
|
|
|
|
<span id="ch4-flow-matching" style="position: absolute;"></span> |
|
|
|
|
|
The posterior parametrization adopted by DMs proved traditionally effective, yet it raised concerns circa its *efficiency* at inference time, where a possibly large number (hundreds) of compute-expensive denoising steps are needed in order to recover a sample from the target distribution. Flow Matching (FM) @lipmanFlowMatchingGenerative2023 extends DMs to the general case of arbitrary likelihood and posteriors, and in this defines a superseding class of GMs providing a unified framework for learning *continuous transformations* between distributions, encompassing and generalizing DMs. Instead of a *stochastic, discrete, multi-step* denoising process, FM aims to learn a *deterministic, continuous, differentiable flow* $\psi: [0,1] \times Z \mapsto Z$, formalized starting from a (possibly time-dependent) vector field $v: [0,1] \times Z \mapsto Z$ *transporting over time* samples from a simple prior distribution $p_0$--e.g., a standard Gaussian--to a more complex, typically unknown data distribution $p_1$. In this, FM accomodates for arbitrary intermediate distributions, breaking free from the particular case where posterior and likelihood are exclusively Gaussians. Note also how FM models time $t \in [0,1]$ to be varying continuously while moving away *from* an easy-to-sample distribution $p_0$ *towards* the unknown data-distribution, $p_1$. This results in a continuous (and deterministic) trajectory at inference, which is in practice more efficient compared to following stochastic paths like in DMs. Formally, FM can be fully characterized by an ordinary differential equation (ODE) relating instantaneous variations of flows with the underlying vector field, and hence providing complete trajectories over the distributions’ support when integrating over time, |
|
|
``` math |
|
|
\begin{align} |
|
|
\frac{d}{dt} \psi(z, t) &= v(t, \psi(t, z)), \\ |
|
|
\psi(0, z) &= z . |
|
|
\end{align} |
|
|
``` |
|
|
In practice, flow models learn to approximate these dynamics by estimating a vector field $v$ that matches the true, unknown $u$, so that the induced flows $\psi$ can approximate the ideal trajectories $\psi^*$. |
|
|
|
|
|
FM proved very effective in a variety of applications, ranging from image @esserScalingRectifiedFlow2024 and video generation @polyakMovieGenCast2025 to robotics control @blackp0VisionLanguageActionFlow2024. Most notably, in their introductory work on FM for GM, @lipmanFlowMatchingGenerative2023 show how DMs can be seen as a specific instance of FM where the *conditional* target vector field $v$ learned by the noise regressor ${\varepsilon}_\theta$ corresponds to: |
|
|
``` math |
|
|
\htmlId{fm-diffusion-vector-field}{u(t, z\vert z_0) = \frac{\frac{d}{dt}\alpha(1-t)}{1 - (\alpha(1-t))^2}(\alpha(1-t)z - z_0), \quad \alpha(t) = e^{-\frac12 \int_0^t \beta(s) ds}, \quad \forall z_0 \in \mathcal D.} |
|
|
``` |
|
|
Conditional vector fields are defined not only over their argument $z$ and time $t$, but do also vary with respect to an auxiliary variable $z_0$, thereby extending the standard notion of a vector field to incorporate additional conditioning. Note that the traditional discrete-time noise-scheduler $\{\beta_t\}_{t=0}^T$ is now generalized to a continuous map $\beta : [0,1] \mapsto \mathbb R^+$. Crucially, @lipmanFlowMatchingGenerative2023 prove that by exclusively optimizing the vector field for individual data points $z_0 \in \mathcal D$, one also retrieves the optimal flow to morph the entire support of the initial distribution $p_0$ into $p_1 \ \text{s.t.} \mathcal D \sim p_1$. |
|
|
|
|
|
<Image |
|
|
src={ch4_normalizing_flows} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Probability distributions can be modified differently by applying different vector fields, inducing different flows of mass across the same support (top versus bottom, using two different time-invariant 2D-fields u 1(x, y) = (x, 0) and $u_2(x,y) = (x/\sqrt{2}, y/\sqrt{2})$). Notice time flows continuously in [0, 1]. FM models learn to approximate a target vector field, thereby producing arbitrary (goal) transformations of an easy-to-sample initial distribution.'}/> |
|
|
|
|
|
While the noising schedule of DMs results in a stochastic resembling a random (Brownian) walk, FM allows for more general |
|
|
|
|
|
<Image |
|
|
src={ch4_diffusion_vs_flowmatching} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Compared to diffusion, flow matching distorts distribution along a less randomic pattern, resulting in a clearer interpolation between source and target distribution. The visualization shows an example comparison between these two methods on joint distribution of robot observations and actions over T = 50 steps.'}/> |
|
|
|
|
|
In practice, FM can be applied to generative modeling by learning a vector field regressor $v_\theta(z, t)$ to approximate a given target vector field $u(t, z)$. In the particular case of DMs, $u(t, z)$ is defined as in eq. <a href="#fm-diffusion-vector-field" data-reference-type="ref" data-reference="fm-diffusion-vector-field">[fm-diffusion-vector-field]</a>, while in priciple the target vector field can be learned to induce an arbitrary mass displacement, or fixed according to OT. Given a sample from the data distribution $z_1 \sim p_1$ and a sample from an easy-to-sample prior $z_0 \sim p_0$, Conditional FM (CFM) defines a simple path between them using *linear interpolation* between samples $z_t = (1-t)z_0 + t z_1$, which in turn results in the target vector field $u(t, z_t) = z_1 - z_0$. FM models can then be trained with a simple regression objective defined as: |
|
|
<span id="flow-matching-objective" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
|
|
|
\mathcal L(\theta) = \mathbb{E}_{t, z_0, z_1} \big[ |
|
|
\Vert v_\theta((1-t)z_0 + t z_1, t) - (z_1 - z_0) \Vert^2 \big], \quad t \sim \mathcal{U}([0,1]), |
|
|
\end{align} |
|
|
``` |
|
|
where $z_0 \sim p_0(\bullet)$ and $z_1 \sim p_1(\bullet)$. Note how in eq. <a href="#flow-matching-objective" data-reference-type="ref" data-reference="flow-matching-objective">[flow-matching-objective]</a> |
|
|
|
|
|
### Action Chunking with Transformers |
|
|
|
|
|
While GMs prove useful in learning complex, high-dimensional multi-modal distributions, they do not natively address the compouding errors problem characteristic of modeling online, sequential predictions. In Action Chunking with Transformers (ACT), @zhaoLearningFineGrainedBimanual2023 present an application of VAEs to the problem of learning purely from offline trajectories, and introduce a simple, yet effective method to mitigate error compounding, learning high-fidelity autonomous behaviors via BC. Drawing inspiration from how humans plan to enact *sequences* of actions $a_{t-t+k}$ instead of single actions $a_t$, @zhaoLearningFineGrainedBimanual2023 propose learning a GM on a dataset of input demonstrations by modeling *chunks* of multiple actions directly. Besides contributions to learning high-performance autonomous behaviors, @zhaoLearningFineGrainedBimanual2023 also introduce hardware contributions in the form of a low-cost bimanual robot setup (ALOHA) capable of performing fine-grained manipulation tasks, such as opening a lid, slotting a battery in its allotment or even prepare tape for application. Notably, ALOHA bimanual setup costs just as much as a mono-arm Franka arm and can be assembled from easy-to-source parts, underscoring its higher accessibility. |
|
|
|
|
|
@zhaoLearningFineGrainedBimanual2023 do also present significant algorithmic contributions related to synthetizing performant autonomous behaviors for the ALOHA setup, adopting transformers as the architectural backbone to learn a *Conditional* VAE @sohnLearningStructuredOutput2015 from demonstrations. Conditional VAEs are a variation of the standard VAE introducing an arbitrary conditioning on sampling from the latent prior, modeling *one-to-many* relationships between latent and data samples. Further, in stark contrast with previous work @florenceImplicitBehavioralCloning2022, @jannerPlanningDiffusionFlexible2022, @zhaoLearningFineGrainedBimanual2023 do not learn a full joint $p_\theta(o,a)$ on observation and actions, and rather focus on the conditional $p_\theta(a \vert o)$. While the *policy* distribution $p_\theta(a \vert o)$ can in principle be entirely described from the joint $p_\theta(o,a)$, conditional distributions are often intractable when using function approximators, as $p_\theta(a \vert o) = \tfrac{p_\theta(o,a)}{\int_\mathcal Ap_\theta(o,a)}$, and the integral in the denominator is typically intractable. Thus, instead of modeling the full joint using a vanilla VAE, @zhaoLearningFineGrainedBimanual2023 propose learning a *conditional* VAE @sohnLearningStructuredOutput2015 modeling the policy distribution directly, hence approximating $p (a \vert o)$. |
|
|
|
|
|
In practice, when learning from demonstrations adopting CVAEs results in a slight modification to the VAE objective in eq. <a href="#ELBO" data-reference-type="ref" data-reference="ELBO">[ELBO]</a>, which is adapted to: |
|
|
<span id="c-ELBO" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
|
|
|
\text{ELBO}_{\mathcal D}(\theta, \phi, \omega) = \sum_{i=0}^{N} \left( |
|
|
\mathbb{E}_{z \sim q_\phi(\cdot \vert o_i, a_i)} \big[ \log p_\theta(a_i \vert z, o_i) \big] |
|
|
- \text{D}_{\text{KL}}\big[ q_\phi(z \vert o_i, a_i) \Vert p_\omega(z \vert o_i) \big] |
|
|
\right) |
|
|
\end{align} |
|
|
``` |
|
|
Notice how in eq. <a href="#c-ELBO" data-reference-type="ref" data-reference="c-ELBO">[c-ELBO]</a> we are now also learning a new set of parameters $\omega$ for the prior distribution in the latent space. Effectively, this enables conditioning latent-space sampling (and thus reconstruction) during training (and potentially inference too), providing useful when learning inherently conditional distributions like policies. Further, ACT is trained as a $\beta$-CVAE @higgins2017beta, weighing the KL regularization term in eq. <a href="#c-ELBO" data-reference-type="ref" data-reference="c-ELBO">[c-ELBO]</a> with an hyperparameter $\beta \in \mathbb R^+$ regulating the information condensed in the latent space, where *higher* $\beta$ results in a *less* expressive latent space. |
|
|
|
|
|
In their work, @zhaoLearningFineGrainedBimanual2023 ablated using a GM to learn from human demonstrations compared to a simpler, supervised objective, $\mathcal L_1(a,a^\prime) = \Vert a - a^\prime \Vert_1$. Interestingly, they found the performance of these two approaches to be comparable when learning from *scripted* demonstrations. That is, when learning from data collected rolling out a predetermined set of commands $[q^c_0, q^c_1, \dots]$, GM did *not* prove competitive compared to standard supervised learning. However, when learning from human demonstrations |
|
|
|
|
|
In ACT (Figure <a href="#ch4-act" data-reference-type="ref" data-reference="ch4-act">[ch4-act]</a>), inference for a given observation $o \in \mathcal O$ could be performed by (1) defining a prior $p_\omega(z \vert o)$ for the latent variable $z$ and (2) decoding an action chunk from a sampled latent $z \sim p_\omega(\bullet \vert o)$, similarily to how sampling from standard VAEs takes place, with the exception that vanilla VAEs typically pose $p(z\vert o) \equiv p(z) \sim \mathcal N(\mathbf{0}, \mathbf{I})$ and thus skip (1). |
|
|
|
|
|
<Image |
|
|
src={ch4_act_encoder} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'The CVAE encoder used in ACT. Input action chunks are first embedded and aggregated with positional embeddings, before being processed alongside embedded proprioperceptive information, and a learned [CLS] token used to aggregate input level information, and predict the style variable z . The encoder is exclusively used to train the decoder, and it is entirely disregarded at inference time.'}/> |
|
|
|
|
|
However, the authors claim that using a deterministic procedure to sample $z$ benefits policy evaluation, and thus avoid using the conditional prior at all at inference time, effectively using the CVAE framework exclusively to train a more expressive decoder. At test time, @zhaoLearningFineGrainedBimanual2023 propose simply using $z = \mathbf{0}$, as the conditional prior on $z$ used in training is set to be a standard Gaussian. Further, conditioning on the observation $o$ is achieved through explicitly feeding proprioperceptive and visual observations to the decoder, $p_\theta(a \vert z, o)$ at test time. If at inference $z$ is sampled from a standard Gaussian, during training $z$ is sampled from an approximate posterior distribution $q_\phi(z \vert o, a)$, which, however, disregards image observations and exclusively uses proprioperceptive states to form $o$ for efficiency reasons. |
|
|
|
|
|
<Image |
|
|
src={ch4_act_decoder} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'The CVAE decoder used in ACT, comprising of a full encoder-decoder Transformer architecture. Camera observations from all n camera views are first embedded using pre-trained visual encoders, and then aggregated with the corresponding positional embeddings. Then, the proprioperceptive information and style variable z retrieved from the CVAE encoder, are fed to the encoder-decoder Transformer for inference. The encoder shares the matrices K, V with the decoder, and is trained to decode fixed position embeddings into action chunks.'}/> |
|
|
|
|
|
#### Code Example: Training and Using ACT in Practice |
|
|
|
|
|
<Image |
|
|
src={ch4_act} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Action Chunking with Transformer (ACT), as in @zhaoLearningFineGrainedBimanual2023. ACT introduces an action chunking paradigm to cope with high-dimensional multi-modal demonstration data, and a transformer-based CVAE architecture.'}/> |
|
|
<div class="pbox"> |
|
|
|
|
|
Training ACT |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/snippets/ch4/01_training_act.py](https://github.com/fracapuano/robot-learning-tutorial/snippets/ch4/01_training_act.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
<div class="pbox"> |
|
|
|
|
|
Using ACT |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/snippets/ch4/02_using_act.py](https://github.com/fracapuano/robot-learning-tutorial/snippets/ch4/02_using_act.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
|
|
|
### Diffusion Policy |
|
|
|
|
|
DMs have proven very effective in approximating complex highly dimensional distributions, such as distributions over images @hoDenoisingDiffusionProbabilistic2020 or videos @polyakMovieGenCast2025, thanks to their inherent capability to deal with multimodal data, and their training stability. In Diffusion Policy (DP), @chiDiffusionPolicyVisuomotor2024 present an application of DMs the field of robot learning, leveraging diffusion to model expert demonstrations in a variety of simulated and real-world tasks. Similarily to ACT @zhaoLearningFineGrainedBimanual2023, @chiDiffusionPolicyVisuomotor2024 (1) adopt a modified *observation-conditioned target distribution* instead of the full joint $p(o,a)$, and (2) predict multiple actions into the future instead of a single action. Besides the intractability of the observations’ marginal $p_\theta(o)$ given $p_\theta(o,a)$, DP’s choice to model the data distribution through $p_\theta(a \vert o)$ also stems from the computational burden of diffusion at test time: generating actions together with observations would require a large number of denoising steps |
|
|
|
|
|
In practice, conditioning on observation data is achieved conditioning the noise regressor $\epsilon_\theta$ introduced in eq. <a href="#diffusion-simplified-loss" data-reference-type="ref" data-reference="diffusion-simplified-loss">[diffusion-simplified-loss]</a> on a stack of $H_o$ observations, resulting in the *conditional*, simplified diffusion objective: |
|
|
<span id="diffusion-policy-objective" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\mathcal L(\theta) &= \mathbb{E}_{t, a_{t:t+H_a}, \epsilon} \big[ |
|
|
\Vert \epsilon - \epsilon_\theta(\sqrt{\bar \alpha_t} a_{t:t+H_a} + \epsilon \sqrt{1 - \bar \alpha_t}, t, o_{t-H_o:t}) \Vert^2 \big], \\ |
|
|
& t \sim \mathcal{U}(\{1,\dots,T\}), \quad |
|
|
a_{t:t+H_a}, o_{t-H_o:t} \sim \mathcal{D}, \quad |
|
|
\epsilon \sim \mathcal{N}(\mathbf{0},\mathbf{I}). \notag |
|
|
\end{align} |
|
|
``` |
|
|
Note how in eq. <a href="#diffusion-policy-objective" data-reference-type="ref" data-reference="diffusion-policy-objective">[diffusion-policy-objective]</a> the noise regressor is conditioned on both the latent variable rank $t$ *and* on a stack of previous observations $o_{t-H_o-t}$. @chiDiffusionPolicyVisuomotor2024 claim the combination of (1) conditioning on a horizon of previous observations and (2) predicting multiple actions into the future allows DP to *commit to specific modes* in the data at inference time, which proves essential for good performance and avoiding undecisiveness. |
|
|
|
|
|
<Image |
|
|
src={ch4_diffusion_policy} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'The Diffusion Policy archicture, as in @chiDiffusionPolicyVisuomotor2024. A stack of H o previous observations is used as external conditioning to denoise a group of H a actions. Conditioning is performed at every layer of a U-Net block. Diffusion Policy allows to obtain fully-formed action chunks with as little as T = 10 denoising steps.'}/> |
|
|
|
|
|
Figure <a href="#diffusion-policy-architecture" data-reference-type="ref" data-reference="diffusion-policy-architecture">[diffusion-policy-architecture]</a> shows the convolution-based version of the architecture proposed by @chiDiffusionPolicyVisuomotor2024, illustrating inference on a single sample drawn from $\mathcal D$, for simplicity. The starting, arbitrarily noisy chunk of $H_a$ actions $\tilde a_{t:t+H_a}$ is first mapped to a (learned) high-dimensional space. Similarily, both image observations and poses are also embedded before being aggregated to the action embeddings. Then, a U-Net @ronnebergerUNetConvolutionalNetworks2015 is trained to regress the noise added into $\tilde a_{t:t+H_a}$, conditioned on observation information at every layer, thus seeking to optimize eq. <a href="#diffusion-policy-objective" data-reference-type="ref" data-reference="diffusion-policy-objective">[diffusion-policy-objective]</a>. At inference time, the noise predictor is used to predict the quantity of noise at every $t \in [T, \dots, 0 ]$ and iteratively subtract it from $\tilde a_{t-t+H_a}$, reversing the diffusion process simulated in training conditioned on $o_{t-H_o:t}$ to predict $a_{t:t+H_a}$. |
|
|
|
|
|
DP can be trained with as little as 50-150 demos (ca. 15-60 minutes of teleoperation data), and exhibit strong performance on a variety of simulated and real-world tasks, including dexterous and deformable manipulation tasks such as sauce pouring and yoga-mat unrolling. Notably, the authors ablated the relevance of using RGB camera streams as input to their policy, and observed how high frame-rate visual observations can be used to attain performance (measured as success rate) comparable to that of state-based policies, which are typically trained in simulation with priviledged information not directly available in real-world deployments. As high-frame rate RGB inputs naturally accomodate for dynamic, fast changing environments, @chiDiffusionPolicyVisuomotor2024’s conclusion offers significant evidence for learning streamlined control policies directly from pixels. In their work, @chiDiffusionPolicyVisuomotor2024 also ablate the performance of DP against the size of the dataset collected, showing that DP reliably outperforms the considered baseline for all benchmark sizes considered. Further, in order accelerate inference, @chiDiffusionPolicyVisuomotor2024 employ Denoising Diffusion Implicit Models @songDenoisingDiffusionImplicit2022, a variant of Denoising Diffusion Probabilistic Models @hoDenoisingDiffusionProbabilistic2020 (DDPM) adopting a strictly deterministic denoising paradigm (differently from DDPM’s natively stochastic one) inducing the same final distribution’s as DDPM’s, and yet resulting in 10x less denoising steps at inference time @chiDiffusionPolicyVisuomotor2024. Across a range of simulated and real-world tasks, @chiDiffusionPolicyVisuomotor2024 find DPs particularly performant when modeling $\epsilon_\theta$ with a transformer-based network, although the authors note the increased sensitivity of transformer networks to hyperparameters. Thus, @chiDiffusionPolicyVisuomotor2024 explicitly recommend starting out with a simpler, convolution-based architecture for diffusion (Figure <a href="#diffusion-policy-architecture" data-reference-type="ref" data-reference="diffusion-policy-architecture">[diffusion-policy-architecture]</a>), which is however reported to be biased towards learning low-frequency components @tancikFourierFeaturesLet2020, and thus may prove more challenging to train with non-smooth action sequences. |
|
|
|
|
|
#### Code Example: Training and Using Diffusion Policies in Practice |
|
|
|
|
|
<div class="pbox"> |
|
|
|
|
|
Training Diffusion Policy |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch4/03_training_diffusion.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch4/03_training_diffusion.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
<div class="pbox"> |
|
|
|
|
|
Using Diffusion Policy |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch4/04_using_diffusion.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch4/04_using_diffusion.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
|
|
|
### Optimized Inference |
|
|
|
|
|
<span id="ch4-async-inference" style="position: absolute;"></span> |
|
|
|
|
|
Modern visuomotor policies output *action chunks*-sequences $\pi(o_t) = \bigl(a_t,a_{t+1},\dots,a_{t+H_a}\bigr) = \mathbf{A}_t$ with $\mathbf{A}_t$ a sequence of $H_a \gg 1$ low-level commands scheduled for execution in an action queue, all originating from a single environment observation, $o_t$. Predicting series of actions instead of single commands proved essential in learning complex, multi-modal behavior @zhaoLearningFineGrainedBimanual2023, @chiDiffusionPolicyVisuomotor2024, and it also holds the premise to be useful to optimize how inference is carried out in practice. |
|
|
|
|
|
A robot may indeed execute an entire action chunk $\mathbf{A}_t$ *before* a new observation $o_{t+H_a}$ is passed to the policy $\pi$ to predict the next chunk, which would result in open-loop control between observations captured every $H_a$ timesteps. @zhaoLearningFineGrainedBimanual2023 adopt a different strategy, whereby the robot controller interleaves chunk prediction $\mathbf{A}_t \gets \pi(o_t)$ and chunk consumption $a_t \gets \text{PopFront(MATHEXPR)}$, and computes a new chunk of actions at every timestep $t$, to then aggregate the predicted chunks on overlapping sections. While adaptive |
|
|
|
|
|
One can use the fact that policies output multiple actions at the same time to directly (1) the lack of adaptiveness and (2) the presence of lags at runtime by decoupling action chunk *prediction* $\mathbf{A}$ from action *execution* $a_t \gets \text{PopFront}(\mathbf{A}_t)$. This decoupled stack, which we refer to as *asynchronous* (async) inference (<a href="#alg-async-inference" data-reference-type="ref" data-reference="alg-async-inference">[alg-async-inference]</a>), also enables optimized inference by allowing action-chunk inference to run on a separate machine, typically equipped with better computational resources than the ones onboard a robot. In async inference, a $\text{RobotClient}$ sends an observation $o_t$ to a $\text{PolicyServer}$, receiving an action chunk $\mathbf{A}_t$ once inference is complete (Figure <a href="#ch4-async-inference" data-reference-type="ref" data-reference="ch4-async-inference">[ch4-async-inference]</a>). In this, we avoid execution lags by triggering chunk prediction while the control loop is still consuming a previously available chunk, aggregating the previous and incoming chunks whenever the latter is available to the $\text{RobotClient}$. In turn, async-inference tightens the loop between action prediction and action execution efficienty, by increasing the frequency at which observations are processed for chunk prediction while not running inference at every timestep. Crucially, decoupling action prediction from action execution also allows to allocate more computational resources on a remote policy server sending actions to the robot client over the network. |
|
|
|
|
|
<Image |
|
|
src={ch4_async_inference} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Asynchronous inference. Illustration of the asynchronous inference stack. Note that the policy can be run on a remote server, possibly with GPUs.'}/> |
|
|
<div class="algorithm"> |
|
|
|
|
|
<span id="alg-async-inference" style="position: absolute;"></span> |
|
|
<div class="algorithmic"> |
|
|
|
|
|
**Input:** horizon $T$, chunk size $H_a$, threshold $g\in[0,1]$ **Init:** capture $o_0$; send $o_0$ to ; receive $\mathbf{A}_0 \gets \pi(o_0)$ $a_t \gets \text{PopFront}(\mathbf{A}_t)$ ($a_t$) capture new observation, $o_{t+1}$ `async_handle` $\gets \text{AsyncInfer}(o_{t+1})$ $\tilde{\mathbf{A}}_{t+1} \gets \pi(o_{t+1})$ $\mathbf{A}_{t+1} \gets f(\mathbf{A}_t,\tilde{\mathbf{A}}_{t+1})$ |
|
|
|
|
|
$\mathbf{A}_{t+1} \gets \mathbf{A}_t$ |
|
|
|
|
|
</div> |
|
|
</div> |
|
|
|
|
|
In practice, *async* inference (1) tightens the control loop by capturing observations more often, eliminating idle gaps at runtime (2) and directly allows to run inference on more powerful computational resources than the ones typically available onboard autonomous robotic platforms. Algorithmically, one can attain (1) on the -side by consuming actions from a readily available queue until a given condition on the number of remaining actions in the queue ($\vert \mathbf{A}_t \vert / H_a < g$) is met. When this condition is triggered, a new observation of the environment is captured and sent to the (possibly remote) . To avoid redundant server calls and erratic behavior at runtime observations are compared in joint-space, and near-duplicates are dropped. Two observations are considered near-duplicates if their distance in joint-space falls under a predetermined threshold, $d_{\text{lim}} \in \mathbb R_+$. Importantly, should the queue available to the robot client eventually empty out, the most recent observation is processed regardless of similarity. |
|
|
|
|
|
Interestingly, the behavior of async inference can be studied analytically. First, let $\ell$ be a random variable modeling the time needed to receive an action chunk $\mathbf{A}$ after sending an observation $o$, i.e. the sum of (1) the time to send across the observation $o$ between the and , $t_{C \to S}$ (2) the inference latency on the , $\ell_S$ and (3) the time to send $\mathbf{A}$ between the and , $t_{S \to C}$. Under the (reasonable) assumption of independence, $\mathbb E [\ell] = \mathbb E[t_{C \to S}] + \mathbb E[\ell_S] + \mathbb E[t_{S \to C}]$, which can be further simplified to $\mathbb E[\ell] \simeq \mathbb E[\ell_S]$, assuming communication time is (1) equal in both directions and (2) negligible with respect to the inference latency. Second, let $\Delta t$ be the environment’s control cycle. With a real-world frame-rate of 30 frames-per-second (fps), $\Delta t=33\text{ms}$. Consequently, exhausted queues at runtime |
|
|
|
|
|
Figure <a href="#ch4-queues" data-reference-type="ref" data-reference="ch4-queues">[ch4-queues]</a> illustrates how the size of the action chunk $\lvert \mathbf{A}_t \rvert$ evolves over time for three representative values of $g$, detailing the following key scenarios: |
|
|
|
|
|
- **Sequential limit $(g=0)$.** The client drains the entire chunk before forwarding a new observation to the server. During the round-trip latency needed to compute the next chunk, the queue is empty, leaving the robot *incapable of acting*. This reproduces the behavior of a fully sequential deployment and results in an average of $\mathbb E[\ell_S]$ idle seconds. |
|
|
|
|
|
- **Asynchronous inference $(g \in (0,1))$.** Allowing the client to consume a $1-g$ fraction of its available queue $\mathbf{A}_{t-1}$ *before* triggering inference for a new action queue $\mathbf{A}_{t}$, computation is amortized while keeping the queue from emptying. The overlap between successive chunks provides a buffer against modeling errors without the full cost of the $g=1$ regime. The updated queue $\mathbf{A}_t$ is obtained aggregating queues on the overlapping timesteps between $\mathbf{A}_{t-1}$ and the incoming $\tilde{\mathbf{A}}_{t}$. |
|
|
|
|
|
- **Sync-inference limit $(g=1)$.** As an extreme case, and in keeping with @zhaoLearningFineGrainedBimanual2023, an observation is sent at *every* timestep. The queue is therefore almost always filled, with only a minor saw-tooth due to $\Delta t/\mathbb E[\ell_s] < 1$. While maximally reactive, this setting incurs one forward pass per control tick and can prove prohibitively expensive on limited hardware. Importantly, because the client is consuming actions while the server computes the next chunk, the available queue never gets entirely filled. |
|
|
|
|
|
<Image |
|
|
src={ch4_queues} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Action queue size evolution at runtime for various levels of g when (A) not filtering out observation based on joint-space similarity and (B) filtering out near-duplicates observation, measuring their similarity in joint-space.'}/> |
|
|
|
|
|
Figure <a href="#ch4-queues" data-reference-type="ref" data-reference="ch4-queues">[ch4-queues]</a> emphasizes the trade-off governed by $g$: small values of $g$ result in idle periods, whereas $g\approx 1$ assumes a highly accurate model and pays a significant compute price. In practice, choosing $g\in(0,1)$ allows to strike a balance between reactivity against resource budgets. If not for the aforementioned similarity filter, the $\text{RobotClient}$ would send observations for processing every $(1 - g) H_a \cdot \Delta t$ seconds, receiving a new chunk of actions every $(1 - g) H_a \cdot \Delta t + \mathbb E[\ell_S]$, on average. The presence of the filter for observation similarity dilates this processing time, and serves the scope of avoiding the robot stalling due to the queue being constantly integrated with an incoming, nearly identical, action chunk. In particular, Figure <a href="#ch4-queues" data-reference-type="ref" data-reference="ch4-queues">[ch4-queues]</a> results in a queue which is filled with incoming actions *unless* near-duplicate observations are filtered out from the processing pipeline. For clarity, the red arrow in <a href="#ch4-queues" data-reference-type="ref" data-reference="ch4-queues">[ch4-queues]</a> highlights a timestep where the observation similarity mechanism is bypassed, forcing a (nearly identical) observation to be processed as the queue results empty. |
|
|
|
|
|
#### Code Example- Using Async Inference |
|
|
|
|
|
<div class="pbox"> |
|
|
|
|
|
Spinning up a Remote Server |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch4/05_policy_server.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch4/05_policy_server.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
<div class="pbox"> |
|
|
|
|
|
Attaching a Robot Client |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch4/06_robot_client.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch4/06_robot_client.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
|
|
|
## Generalist Robot Policies |
|
|
|
|
|
<span id="learning-foundation" style="position: absolute;"></span> |
|
|
<Quote source="Robert A. Heinlein"> |
|
|
Specialization is for insects |
|
|
</Quote> |
|
|
<div class="callout"> |
|
|
|
|
|
TL;DR Openly available, large-scale datasets and the development of stable-to-train, expressive and efficient architectures fostered research on the development of generalist robot policies that can operate across embodiment and tasks. |
|
|
|
|
|
</div> |
|
|
|
|
|
The advent of large models trained on internet-scale datasets has drastically influenced fields like Computer Vision (CV) and Natural Language Processing (NLP), shifting the previously task-specific paradigm towards combining (1) an initial, task-agnostic large-scale pre-training stage and a (2) task-specific, adjustment phase. This *pre-train-and-adaptat* paradigm has now largely replaced more classic approaches consisting of task-specific data collection, curation and model training in many subdomains within CV and NLP, and it is motivated by the main drawback of limited scalability for *task-specific approaches*, which have been traditionally more labor intensive. Factors including (1) the advancements in generalist models learned with self-supervision for perception @oquabDINOv2LearningRobust2024 or semantic understanding @devlinBERTPretrainingDeep2019 and (2) the popularization of collective efforts to aggregate large-scale openly available datasets @oneillOpenXEmbodimentRobotic2025, @khazatskyDROIDLargeScaleInTheWild2025 are increasingly pushing the field of robot learning towards the pre-train-and-adapt paradigm. This shift taps into the long-standing challenge of developing generalist robot policies, and holds the premise to surpass traditionally siloed approaches to robotics problems and develop a *foundation robotics model*. While Section <a href="#learning-imitation" data-reference-type="ref" data-reference="learning-imitation">[learning-imitation]</a> introduced methods for learning *single-task policies* such as ACT or Diffusion Policy, in this section we present advancements in developing *generalist, multi-task, policies*, capable of performing a wide range of tasks across different environments and embodiments, and guided by unstructured instructions typically given in plain, natural language. |
|
|
|
|
|
<Image |
|
|
src={ch5_ml_vs_robotics_foundation} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Fields within ML such as Computer Vision and NLP converged on the development of foundation models, trained on a variety of large scale models and capable to perform multiple downstream tasks (top). Conversely, robotics suffered from limited standardization in terms of the architectures used, and siloed, task specific datasets, incurring in a high degree of fragmentation which traditionally hindered the development of generalist models for robotics in favour of task-specific models (bottom).'}/> |
|
|
|
|
|
### Preliminaries: Models and Data |
|
|
|
|
|
The remarkable success of foundation models in NLP and CV seems to be increasingly predicated on two core principles: architectural innovation and (joint) data-compute scaling. Indeed, the transformer architecture proved very effective in capturing long-range dependencies in a variety of data formats, and its stability and expressivity made it the *de facto* standard for modern large-scale models trained on internet-scale datasets. However, in stark contrast with large-scale NLP and CV datasets @raffelExploringLimitsTransfer2023, @ImageNet_VSS09, robotics has historically developed around small, task-specific datasets. In turn, this traditionally hindered scalability across problems as well as results, posing concrete challenges to developing general-purpose robot learning algorithms. Indeed, differently from the wealth of relatively readily-available task-agnostic text and images datasets on the internet, robotics data is *intrinsically embodied* and thus task-specific: datasets collected for *manipulation* differ significantly from *locomotion*. In particular, since each expert trajectory is tied to a specific robot platform and the operating conditions of its environment and task, data heterogeneity has long posed a *methodological* challenge for scaling robotics datasets via aggregation. Further, datasets consisting of expert demonstrations are (1) intrinsically more expensive to collect and (2) notoriously heterogeneous |
|
|
|
|
|
<Image |
|
|
src={ch5_generalist_policies_timeline} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Early efforts in the development of generalist models for robotics include BC-Zero @jangBCZZeroShotTask2022, RT-1 @brohanRT1RoboticsTransformer2023, and RT-2 @brohanRT2VisionLanguageActionModels2023: large scale models trained on thousands of demonstrations. The open release of the Open-X @oneillOpenXEmbodimentRobotic2025 and DROID datasets @khazatskyDROIDLargeScaleInTheWild2025 fostered the development of open source models: OpenVLA @kimOpenVLAOpenSourceVisionLanguageAction2024, π 0 @blackp0VisionLanguageActionFlow2024 and SmolVLA @shukorSmolVLAVisionLanguageActionModel2025.'}/> |
|
|
|
|
|
Driven by the goal of developing generalist robot policies, the research community has increasingly explored how insights and techniques from other areas of ML can be integrated into robotics. Figure <a href="#ch5-generalist-policies-timeline" data-reference-type="ref" data-reference="ch5-generalist-policies-timeline">[ch5-generalist-policies-timeline]</a> shows a timeline of some of the most popular contributions attempting at developing generalist policies. Starting from BC-Zero, a latent variable model trained on 25k+ demonstrations, the field has now evolved into $\pi_0$, a transformer-based model trained on 10M+ demonstrations and exhibiting strong few-shot capabilities across tasks and embodiments. In between, Robotics Transformer 1 (RT-1) @brohanRT1RoboticsTransformer2023 represented a significant step in the direction of developing a generalist robot policies over prior work including (1) BC-Zero @jangBCZZeroShotTask2022 and (2) Gato @reedGeneralistAgent2022, in that @brohanRT1RoboticsTransformer2023 use a much larger and diverse set of training tasks compared to both BC-Zero and Gato. In particular, RT-1 uses a transformer architecture, and is trained on as many as 130k human-recorded trajectories collected over 13 robots and over 17 months. RT-1 learns to process a history of camera images and a natural language instruction, and feeds the resulting sequence of high-dimensional tokens to a transformer, trained using a *classification loss on a discretized actions space* consisting of six different 256-bins, one for each joint of a 6-dof robotic arm. |
|
|
|
|
|
In a follow-up work, the same group of authors propose a modified method to learn generalist models, leveraging (1) a more powerful architecture and (2) scaling up the dataset used . In RT-2, @brohanRT2VisionLanguageActionModels2023 propose inheriting internet-scale semantic knowledge from large-scale multi-modal datasets to learn a single, *unified model* for robotics control. Such a model, termed *Vision-Language-Action* (VLA) in the original RT-2 paper, effectively casts robot control as a language-modeling problem, and in particular as a Visual Question-Answering (VQ) task, in which the output token space used to represent *textual tokens* is shared with the *8-bits tokens* used to represent the 256 ($2^8$) actuation levels of a 6-dof robot. In their work, @brohanRT2VisionLanguageActionModels2023 propose co-fine-tuning large-scale VLMs such as PaLIX @chenPaLIXScalingMultilingual2023 or PaLM-E @driessPaLMEEmbodiedMultimodal2023 on a mix of (1) web and (2) robotics data, complementing VQtraining with robotics-specific signal, and learning to directly output robot actions in a shared token space for visual and language inputs. In their work, the authors claim using large models trained on internet-scale data as backbones for VLAs allows models to tap into the rich semantic knowledge embedded in the VLM’s parameters, interpreting instructions and unseen objects by connecting them to concepts acquired while pre-training. For instance, @brohanRT2VisionLanguageActionModels2023 show that while RT-2 has never been explicitly trained to repurpose tools for a *hammering* task, it can still combine its semantic understanding of images, so that when asked which object between (1) a piece of paper, (2) a pair of headphones or (3) a rock may be used instead of a hammer, it correctly answers (3). |
|
|
|
|
|
Traditionally, research efforts revolved around not only training models, but also proposing datasets for the community, a costly and time-consuming process. Due to the aforementioned embodiment gap, the data used in research efforts in robot learning have traditionally proved rather fragmented, tailored to the specific task considered by the specific group of researchers who collected it, which ultimately hindered integration. The Open X-Embodiment project @oneillOpenXEmbodimentRobotic2025 was a landmark collaboration effort to address data fragmentation, by curating the aggregation of 60 *existing* robotics datasets from 22 different robot embodiments and 21 institutions across the world, and resulted in a total 1.4M of cross-embodiments, cross-tasks, openly-available trajectories. Besides the contribution of an aggregate, large scale dataset, @oneillOpenXEmbodimentRobotic2025 also demonstrated significant positive transfer *across tasks and embodiments*, showing that <mark>a single model trained on multi-embodiment data can outperform specialist models</mark> trained on their respective single-embodiment datasets. The Distributed Robot Interaction Dataset (DROID) @khazatskyDROIDLargeScaleInTheWild2025 represents another significant step towards addressing the problem of scarse and disaggregated data in robot learning, providing a unique dataset consisting of 75k+ human demonstrations collected in realistic (*in-the-wild*) manipulation settings, providing another cornerstone for building general-purpose robot policies. Recently, foundational datasets curated through large, centralized efforts, are increasingly complemented by decentralized, community-driven contributions of robotics data. Software libraries like `lerobot` have been instrumental in enabling decentralized collection of large amounts of data, providing the infrastructure for researchers and practitioners to easily contribute trajectories from a wide range of embodiments, democratizing data access via distributed collection. |
|
|
|
|
|
Despite these advancements, the success of large, proprietary models like RT-1 and RT-2, highlighted a growing accessibility gap in robotics research, as training and deploying large-scale robotics foundation models requires computational resources simply unattainable for most research institutions. The OpenVLA project @kimOpenVLAOpenSourceVisionLanguageAction2024 emerged in direct contrast to traditionally closed-source efforts to develop VLAs. In particular, @kimOpenVLAOpenSourceVisionLanguageAction2024 trained OpenVLA by exclusively leveraging openly available data (970k+ trajectories from the Open-X dataset), and openly shared their training recipes alongside the model weights. Architecturally, OpenVLA integrates a pre-trained vision encoder to project visual tokens into the embedding space of the Llama2-7B @touvronLlama2Open2023 language-model backbone. The language model backbone is then used to predict *discrete action tokens* over 256 activation levels. |
|
|
|
|
|
<Image |
|
|
src={ch5_trends} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'Robot learning is undergoing a paradigmatic shift: centralized data collections (A, left) are increasingly larger, often comprising millions of demonstrations, while (A, right) decentralized data collection efforts are becoming an alternative for large scale data collection. (B) Generalist models are also becoming increasingly smaller and easier to run on limited hardware.'}/> |
|
|
|
|
|
Figure <a href="#ch5-trends" data-reference-type="ref" data-reference="ch5-trends">[ch5-trends]</a> shows the current trends in robot learning in terms of size and nature of the robotics datasets contributed, together with the size and accessibility of the available models. As datasets collected via centralized, cross-institutions cooperation of increasing size are made available for the research community, decentralized datasets collected by individual researchers and practitioners also gained traction, closing the gap with academic benchmarks thanks to community-contributed datasets. Further, models used across tasks and embodiments are increasingly becoming much more compute-efficient, and as a result the models’ size has been consistently reducing over time, with consequent gains for autonomous robots in real-world, resource-constrained environments. |
|
|
|
|
|
### VLAs |
|
|
|
|
|
Modern recipes to train large scale VLAs extend early efforts to learn foundation models from large amounts of data via BC, introducing significant advancements concerning both architectural and procedural aspects. From an architectural perspective, modern VLAs such as $\pi_0$ @blackp0VisionLanguageActionFlow2024 leverage a *unified transformer model* for efficiency of computation, while maintaining specialized sub-components within the model for visual perception and action prediction, enabling cross-task performance via language conditioning. Crucially, modern VLAs including$\pi_0$ @blackp0VisionLanguageActionFlow2024 and SmolVLA @shukorSmolVLAVisionLanguageActionModel2025 adopt *unified* transformer models employing disjoint set of weights (*experts*) for both compute-efficient visual-semantic understanding as well as control. Procedurally, VLAs complement advanced Vision-Language Model (VLM) backbones with action-specific modules (1) adopting mid-sized *action experts* to model continuous actions distributions $p (a_{t:t+H_a} \vert o_t)$ |
|
|
|
|
|
These architectural and procedural innovations present three benefits over task-specific methods. First, developing architectures that exploit internet-scale pre-trained backbones allows to fully capitalize on the vast world knowledge and skills state-of-the-art VLMs exhibit, preventig models from needing to learn visual, linguistic and semantic concepts from scratch. Second, using generative models for continuous action distributions allows to learn rich, multimodal data distributions, a much more likely scenario in the big-data regime which is typically tackled while developing generalist policies. Further, introducing separate components for perception and action planning enable using Mixture of Experts (MoE) architectures @fedusReviewSparseExpert2022, which are often more efficient to run |
|
|
|
|
|
#### VLMs for VLAs |
|
|
|
|
|
VLMs are designed to handle both visual and textual modalities, most commonly by taking both images and text as inputs, generating text conditioned on the visual context. Recent advances in VLMs have been driven by the success of LLMs, with many approaches building upon pretrained LLMs and adopting similar training paradigms to the ones used in language modeling. Typically, VLMs @alayracFlamingoVisualLanguage2022, @laurenconWhatMattersWhen2024, @linVILAPretrainingVisual2024 are constructed by integrating a pretrained vision encoder @radfordLearningTransferableVisual2021, @zhaiSigmoidLossLanguage2023, @finiMultimodalAutoregressivePretraining2024 with a pretrained LLM @grattafioriLlama3Herd2024, @jiangMistral7B2023. Training then proceeds in multiple multimodal stages, beginning with a large-scale pretraining on datasets containing image-text pairs @LAION-COCO, @kakaobrain2022coyo700m and interleaved vision-language corpora @OBELICS, @MMC4, all followed by a supervised fine-tuning stage on instruction-tuning datasets @LLaVA-1.5, @tong2024cambrian, @laurenconWhatMattersWhen2024. The inherent multimodal nature of VLMs enables them to jointly reason over vision and language. Pre-training on vast internet-scale datasets allows these models to associate visual patterns with textual descriptions, thereby acquiring a rich semantic understanding of the world |
|
|
|
|
|
Recently, compute efficiency has also become a central focus in multi-modal research. Several works aim to reduce training costs by using smaller, more diverse datasets @LLaVA-1.5, @InstructBLIP, @bai2025qwen25vl, @zhu2024minigpt, @tong2024cambrian, training smaller-scale models @marafiotiSmolVLMRedefiningSmall2025, @moondream, @minicmpv2024, or by adapting pretrained unimodal models by tuning only a small subset of parameters @shukor2023epalm, @vallaeys2024improveddepalm, @MAPL, @FROMAGe, @tsimpoukelli2021multimodalfrozen, @BLIP-2. While the majority of VLM research focuses on image and text modalities, recent work has also demonstrated that similar techniques can be extended to integrate additional modalities, such as video and audio @wang2025internvideo2, @liu2024kangaroo, @zhang2025videollama, @kong2024audioflam |
|
|
|
|
|
### $\pi_0$ |
|
|
|
|
|
$\pi_0$ @blackp0VisionLanguageActionFlow2024 introduce a VLA consisting of a MoE architecture consisting of (1) a pre-trained VLM backbone (Gemma 2.6B @teamGemma2Improving2024) and (2) a dedicated action expert used to generate continuous actions via flow matching. Images and language are embedded with PaliGemma, a VLM merging independently encoded visual and textual features deep in the network (*late-fusion*), while proprioceptive state and actions chunks are routed to a smaller *action expert*, initialized from scratch. The two separate experts communicate via self-attention layers, but maintain disjoint weights to obtain query, key and values matrices at each layer, maintaining specialization while efficiently allocating computation. |
|
|
|
|
|
<Image |
|
|
src={ch5_pi0} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'The π 0 architecture, as in @blackp0VisionLanguageActionFlow2024. Vision and language tokens are routed to a VLM backbone which is prevented from attending robot proprioperceptive states and action tokens, which are instead routed to a smaller subset of weights within the architecture referred to as "action expert". The architecture is trained with Flow Matching on 10M+ trajectories from a mixture of closed and openly available datasets.'}/> |
|
|
|
|
|
Concretely, $\pi_0$ is a single, unified transformer with two disjoint sets of weights $\phi, \theta$. A larger VLM backbone $f_\phi$ initialized from Gemma 2.6B processes multiple image frames obtained from multiple cameras points $[\{ I_t \}_{t=1}^n]$, as well as a language instruction $[\ell_t]$ used to describe the task considered. Concurrently, a 300M-parameter *action expert* based on a similar transformer architecture is used to process both the robot proprioperceptive state $q_t$ and an action chunk $a_{t:t+H_a}$ (Figure <a href="#ch5-pi0" data-reference-type="ref" data-reference="ch5-pi0">[ch5-pi0]</a>). The different expert networks operate separately in processing the respective inputs and turn them into query, key and value matrices, and only share information between each other via self-attention layers. The outputs from the VLM backbone are disregarded, while the vector field regressed by the action expert is used to iteratively refine the action process. In particular, $\pi_0$ uses a *blockwise causal attention mask* over tokens belonging to three separate blocks: (1) image and language tokens $\mathcal T_i$ obtained from $[\{ I_t \}_{t=1}^n, \ell_t]$, (2) proprioperceptive tokens $\mathcal T_q$ obtained from $q_t$, and (3) the action tokens $\mathcal T_a$ for items in the chunk $a^{\tau}_{t:t+H_a}$ at time $\tau$ in the flow-matching process. Notably, *within* each block the attention operations are bidirectional, while *across* blocks, future blocks are masked out. Formally, this corresponds to using an attention mask like: $\mathbf{A} = \bordermatrix{ \mathcal{T}_i \mathcal{T}_q \mathcal{T}_a \cr \mathcal{T}_i \mathbf{1} \mathbf{0} \mathbf{0} \cr \mathcal{T}_q \mathbf{1} \mathbf{1} \mathbf{0} \cr \mathcal{T}_a \mathbf{1} \mathbf{1} \mathbf{1} \cr }, \quad \mathbf{1}: \text{Bidirectional Attention}, \ \mathbf{0}: \text{Masked Attention}$ Note how *intra*-block directional attention allows tokens to communicate freely, while *inter*-block communication is mediated by the attention mask $\mathbf{A}$. *Blockwise causal masking* effectively prevents the pre-trained perception-language tokens from attending to robotics-tokens, likely out of distribution for VLM backbones traditionally trained on large corpora of internet, non-robotics, data. Crucially, because communication is obstructed between image-language tokens, proprioperceptive tokens and action tokens, one can cache keys and values across denoising steps at runtime time, incuring in a reduced computational footprint and faster inference. |
|
|
|
|
|
In $\pi_0$, both the VLM backbone and action expert are update using a *flow matching* loss, and in particular are updated minimizing: |
|
|
<span id="pi0-loss" style="position: absolute;"> |
|
|
</span> |
|
|
|
|
|
``` math |
|
|
\begin{align} |
|
|
\mathcal{L}(\phi, \theta) &= |
|
|
\mathbb{E}_{\tau, \epsilon, o_t, a_{t:t+H_a}}\Big[ |
|
|
\big\Vert |
|
|
v_\theta(\underbrace{\tau a_{t:t+H_a} + (1-\tau) \epsilon}_{\tilde a_{t:t+H_a}},\, o_t,\, \tau) |
|
|
- (\epsilon - a_{t:t+H_a}) |
|
|
\big\Vert^2 |
|
|
\Big], \\ |
|
|
&\tau \sim \mathrm{Beta}_{[0,s]}(1.5,1), \quad |
|
|
\epsilon \sim \mathcal{N}(\mathbf{0}, \mathbf{I}), \quad |
|
|
o_t, a_{t:t+H_a} \sim \mathcal D \notag |
|
|
\end{align} |
|
|
``` |
|
|
where the two experts parametrized by the separate weights $\phi, \theta$ interact with each other via self-attention layers only, so that the action expert $v_\theta$ internal computations also depend on the VLM backbone’s parameters $\phi$. Importantly, @blackp0VisionLanguageActionFlow2024 minimize eq. <a href="#pi0-loss" data-reference-type="ref" data-reference="pi0-loss">[pi0-loss]</a> over both the multimodal backbone and action expert parameters, thus updating both the internal representations of the VLM and action-expert weights using BC-specific gradients. In contrast, @driessKnowledgeInsulatingVisionLanguageAction2025 later show that failing to insulate the VLM knowledge from the flow matching gradients actually harms performance. |
|
|
|
|
|
At runtime, inference is performed iteratively refining action chunks while numerically forward-integrating the vector field predicted by the action expert, |
|
|
``` math |
|
|
\begin{equation} |
|
|
a_{t:t+H_a}^{\tau + \delta} = a_{t:t+H_a}^{\tau } + \delta v_\theta(a_{t:t+H_a}^{\tau }, o_t) |
|
|
\end{equation} |
|
|
``` |
|
|
|
|
|
Flow matching can be seen as a continuous time, deterministic generalization of diffusion processes, and has proven effective in modeling highly complex multi-modal distributions, including those over images and video. In turn, the application of flow matching to large-scale datasets of multiple human behaviors across tasks and embodiments appears rather consequential, particularly considering how it can enable faster inference via a limited number of denoising steps at test time |
|
|
|
|
|
<div class="wrapfigure"> |
|
|
|
|
|
r0.4 <Image |
|
|
src={ch5_pi0_sampling_timesteps} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="image" |
|
|
/> |
|
|
|
|
|
<span id="ch5-pi0-sampling-timesteps" style="position: absolute;"></span> |
|
|
</div> |
|
|
|
|
|
Using such Beta distribution emphasizes higher noise levels during training, a choice @blackp0VisionLanguageActionFlow2024 argue allows $\pi_0$ to focus on learning to reconstruct the mean of the data distribution $\mathbb E[a_{t:t+H_a} \vert o_t]$ over an identity map during training, in keeping with @esserScalingRectifiedFlow2024. To further optimize performance and reduce inference time, @blackp0VisionLanguageActionFlow2024 propose reducing the support of the timestep distribution to $[0,s], \ s < 1$, as for any forward-integration step size $\delta = 1-s$ timesteps above $s$ are never sampled at inference time. |
|
|
|
|
|
Besides adopting a MoE architecture with a VLM backbone initialized from a pre-trained model and trained jointly with an action expert via flow matching, $\pi_0$ also relies on a unique pre-training corpus comprising of a mix of proprietary and open data totaling 10M+ trajectories, which in their work @blackp0VisionLanguageActionFlow2024 claim to be the largest dataset used to develop a foundational robotics model to date. The dataset used to train $\pi_0$ |
|
|
|
|
|
Lastly, @blackp0VisionLanguageActionFlow2024 present cross-embodiment experiments where they demonstrate $\pi_0$’s ability to control both mobile and static manipulator robots with varying arm embodiments. The emergence of cross-embodiment capabilities is largely to be attributed to the presence of large scale cross-embodiment data in $\pi$ data mixture, which is in practice handled by $\pi_0$ outputting actions with maximal configuration size across the whole $\pi$ dataset, and zero-padding robots with fewer dofs. $\pi_0$ does also rely on exactly three camera views at both training and test time, and uses masked image slots for training and deployment scenarios with fewer cameras. |
|
|
|
|
|
#### Code Example: Using $\pi_0$ |
|
|
|
|
|
<div class="pbox"> |
|
|
|
|
|
Using $\pi_0$ |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch5/01_using_pi0.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch5/01_using_pi0.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
|
|
|
### SmolVLA |
|
|
|
|
|
With VLAs in the early stage of development compared to more mature LLMs and VLMs, much of the progress made on VLAs remains proprietary, with many releases exclusively sharing the weights while withholding the data used, full experimental details and essential methodological components of training. In constrast with this closed approach, SmolVLA @shukorSmolVLAVisionLanguageActionModel2025 is an entirely open-source research effort, which aims at democratizing the developments of robotics foundation models by open sourcing the model alongside the data used as well as the training recipes. |
|
|
|
|
|
<Image |
|
|
src={ch5_smolvla} |
|
|
zoomable |
|
|
downloadable |
|
|
alt="Figure" |
|
|
caption={'The SmolVLA architecture, as in @shukorSmolVLAVisionLanguageActionModel2025. SmolVLA is a compact MoE model trained with flow matching to denoise action chunks. Vision and language tokens are fed to a VLM backbone, and share information with the proprioperceptive and action tokens via the attention mechanism. The attention expert interleaves SA and CA layers for further conditioning on the visual features from the VLM backbone. SmolVLA skips computations and reduces the visual tokens, resulting in 7x less memory usage than π 0 (450M parameters vs. π 0 ’s 3.3B).'}/> |
|
|
|
|
|
While encouraging efforts like $\pi_0$ @blackp0VisionLanguageActionFlow2024 demonstrate the feasibility of open VLA systems, they remain (1) large and compute-intensive and (2) dependent on closed datasets collected via centralized efforts on costly robotic platforms, which ultimately hinders the accessibility of the method altogether. SmolVLA mitigates both these issues by (1) prioritizing a compact, compute-efficient VLA design and (2) targeting community-contributed datasets on accessible robotic platforms such as the SO-100 and SO-101 arms. Similarly to $\pi_0$, SmolVLA (Figure <a href="#ch5-smolvla" data-reference-type="ref" data-reference="ch5-smolvla">[ch5-smolvla]</a>) employs a MoE architecture combining a pretrained VLM backbone with a dedicated action expert, and trains with flow matching. To ensure efficiency and accessibility, SmolVLA adopts SmolVLM-2 @marafiotiSmolVLMRedefiningSmall2025 as its VLM backbone, considering SmolVLM-2’s reduced size and capability to process multiple image inputs alongside text items. SmolVLM-2 uses SigLIP @zhaiSigmoidLossLanguage2023 as vision encoder, producing visual features for a SmolLM2 language decoder @allalSmolLM2WhenSmol2025. Further, SmolVLA adopts a smaller action expert consisting of $\sim$100M parameters and an interleaved stack of self and cross-attention layers. To improve efficiency, the action expert adopts a reduced embedding dimension compared to the VLM backbone, resulting in $d_{v_\theta} = 0.75 d_{\text{VLM}}$. @shukorSmolVLAVisionLanguageActionModel2025’s design choices thus result in a much smaller size model compared to $\pi_0$, consisting of ca. 450M parameters versus $\pi_0$’s 3.3B parameters. |
|
|
|
|
|
In practice, SmolVLA consumes multi-view RGB images, a natural-language instruction, and projected sensorimotor state token as inputs, together with the noised *action chunk* $\tilde{a}_{t-t+H_a}$ the action expert $v_\theta$ is trained to denoise. The robot proprioperceptive states are projected to a shared token space with the VLM to match $d_{\text{VLM}}$, and successively projected into the expert’s token space. Similarily to $\pi_0$, SmolVLA adopts separate experts communicating exclusively through self-attention layers, which however do not employ blockwise causal attention masking and rather favour simple causal masking. |
|
|
|
|
|
In contrast with $\pi_0$, the action expert interleaves *cross-attention* (CA) and *self-attention* (SA) layers, a choice shown to yield higher success and smoother action chunks in practice. While in the expert SA layers tokens are used to obtain queries, keys and values, CA layers use action tokens only as queries, and instead project visual, language and proprioperceptive tokens from the VLM backbone to a shared embedding space to then obtain keys and values. Notably, keys and values can be cached here as well, resulting in performance gains at inference time. |
|
|
|
|
|
SmolVLA also trims down both token and layer compute. First, it *reduces visual tokens* via pixel shuffling to a fixed budget of 64 tokens per frame, foregoing the tiling used during VLM pretraining for the sake of runtime efficiency. Second, it *skips upper VLM layers*, as only features from the first $N$ decoder layers, with $N=L/2$, are consumed, which provides a good speed-performance trade-off and effectively halves compute needs for the larger part of SmolVLA. Beyond model compactness, SmolVLA also contributes an inference stack that decouples action prediction from execution for responsiveness on modest hardware (Section <a href="#ch4-async-inference" data-reference-type="ref" data-reference="ch4-async-inference">[ch4-async-inference]</a>). |
|
|
|
|
|
Departing from reliance on proprietary datasets, SmolVLA pretrains exclusively on 450+ *community datasets*, totaling 20k+ trajectories. Because instructions in community contributed dataset can be noisy or missing, the authors re-annotate tasks with a small off-the-shelf VLM using frames sampled from the dataset, and standardize camera viewpoints by mapping sources to a consistent top/wrist/side ordering. At test time, similarily to $\pi_0$, SmolVLA forward-integrates flow over 10 steps, resulting in fast inference. SmolVLA proves effective across a range of both real-world and simulated environments, rivaling $\pi_0$ while being close to 40% faster and consuming 6x less memory @shukorSmolVLAVisionLanguageActionModel2025. |
|
|
|
|
|
#### Code Example: Using SmolVLA |
|
|
|
|
|
<div class="pbox"> |
|
|
|
|
|
Using SmolVLA |
|
|
[https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch5/02_using_smolvla.py](https://github.com/fracapuano/robot-learning-tutorial/blob/main/snippets/ch5/02_using_smolvla.py) |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset |
|
|
from lerobot.datasets.streaming_dataset import StreamingLeRobotDataset |
|
|
|
|
|
delta_timestamps = { |
|
|
"observation.images.wrist_camera": [-0.2, -0.1, 0.0] # 0.2, and 0.1 seconds *before* each frame |
|
|
} |
|
|
|
|
|
# Optionally, use StreamingLeRobotDataset to avoid downloading the dataset |
|
|
dataset = LeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Streams frames from the Hugging Face Hub without loading into memory |
|
|
streaming_dataset = StreamingLeRobotDataset( |
|
|
"lerobot/svla_so101_pickplace", |
|
|
delta_timestamps=delta_timestamps |
|
|
) |
|
|
|
|
|
# Get the 100th frame in the dataset by |
|
|
sample = dataset[100] |
|
|
print(sample) |
|
|
# { |
|
|
# 'observation.state': tensor([...]), |
|
|
# 'action': tensor([...]), |
|
|
# 'observation.images.wrist_camera': tensor([3, C, H, W]), for delta timesteps |
|
|
# ... |
|
|
# } |
|
|
|
|
|
batch_size=16 |
|
|
# wrap the dataset in a DataLoader to use process it batches for training purposes |
|
|
data_loader = torch.utils.data.DataLoader( |
|
|
dataset, |
|
|
batch_size=batch_size |
|
|
) |
|
|
|
|
|
# Iterate over the DataLoader in a training loop |
|
|
num_epochs = 1 |
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
for epoch in range(num_epochs): |
|
|
for batch in data_loader: |
|
|
# Move data to the appropriate device (e.g., GPU) |
|
|
observations = batch["observation.state"].to(device) |
|
|
actions = batch["action"].to(device) |
|
|
images = batch["observation.images.wrist_camera"].to(device) |
|
|
|
|
|
# Next, you can do amazing_model.forward(batch) |
|
|
... |
|
|
``` |
|
|
|
|
|
</div> |
|
|
|
|
|
## Conclusions |
|
|
|
|
|
<span id="conclusions" style="position: absolute;"></span> |
|
|
|
|
|
This tutorial has charted the paradigmatic shift transforming robotics, tracing the <mark>evolution of robotics from structured, model-based methods to the dynamic, data-driven approaches that define modern robot learning</mark>. We began by examining the limitations of traditional dynamics-based control, namely its brittleness and significant engineering overhead, which motivate the adoption of more flexible, learning-based alternatives. Unlike scalable, data-driven techniques, conventional explicit models demand extensive human expertise, hindering wider accessibility and scalability of robotics. |
|
|
|
|
|
Our exploration traced a clear trajectory of progress, beginning with Reinforcement Learning (RL). While RL offers a powerful paradigm for learning through interaction, its application in robotics is complicated by challenges such as sample inefficiency, safety concerns in real-world training, and the complexities of reward design. We saw how modern approaches like HIL-SERL make real-world RL more feasible by incorporating training-time human guidance, datasets of previously collected data as well as learned reward classifiers. |
|
|
|
|
|
Nonetheless, the inherent difficulties of RL increasingly motivate approaches based on imitation learning, capable to safely learns from limited numbers of real-world, reward-free expert demonstrations. In turn, the wider adoption of imitation learning led to the development of single-task policies, where advanced Behavioral Cloning techniques |
|
|
|
|
|
A central theme of this work is the critical role of openness in accelerating this progress. The recent explosion in capability is inseparable from the advent of large-scale, openly available datasets, standardized, stable and accessible model architectures, and accessible, open-source software like `lerobot`. We argue this convergence on open-source robotics is not a mere trend but a fundamental enabler, democratizing access to research and unlocking the potential of large, decentralized efforts to advance the field. |
|
|
|
|
|
The journey detailed in this tutorial, from first principles to the state-of-the-art, aims to equip researchers and practitioners with the context and tools to begin their own explorations in open-source robot learning. |
|
|
|
|
|
[^1]: In here, we refer to both *kinematics* and *dynamics*-based control. |
|
|
|
|
|
[^2]: Quote from @mnihPlayingAtariDeep2013. The notation used has slightly been adapted for consistency with the rest of this tutorial. |
|
|
|
|
|
[^3]: Throughout, we will adopt the terminology and notation for SL used in @shalev-shwartzUnderstandingMachineLearning2014 |
|
|
|
|
|
[^4]: See for a complete derivation |
|
|
|