opensi·si

This tutorial will explain how to train a neural network to control a real robot autonomously.

Imitation Learning for Robots

This tutorial will explain how to train a neural network to control a real robot autonomously.

You'll learn:

  1. How to record and visualize your dataset.
  2. How to train a policy using your data and prepare it for evaluation.
  3. How to evaluate your policy and visualize the results.

By following these steps, you'll be able to replicate tasks, such as picking up a Lego block and placing it in a bin with a high success rate, as shown in the video below.

Video: pickup lego block task

This tutorial isn’t tied to a specific robot: we walk you through the commands and API snippets you can adapt for any supported platform.

During data collection, you’ll use a “teleoperation” device, such as a leader arm or keyboard to teleoperate the robot and record its motion trajectories.

Once you’ve gathered enough trajectories, you’ll train a neural network to imitate these trajectories and deploy the trained model so your robot can perform the task autonomously.

If you run into any issues at any point, jump into our Discord community for support.

Want to quickly get the right commands for your setup? The quickstart notebook lets you configure your robot once and generates all the commands below ready to paste.

Set up and Calibrate

If you haven't yet set up and calibrated your robot and teleop device, please do so by following the tutorial for your robot, for example SO-101, OpenArm, Koch or LeKiwi. All supported robots are listed under Robots in the sidebar.

Teleoperate

In this example, we’ll demonstrate how to teleoperate the SO101 robot. For each command, we also provide a corresponding API example.

Note that the id associated with a robot is used to store the calibration file. It's important to use the same id when teleoperating, recording, and evaluating when using the same setup.

Command

lerobot-teleoperate \
    --robot.type=so101_follower \
    --robot.port=/dev/tty.usbmodem58760431541 \
    --robot.id=my_awesome_follower_arm \
    --teleop.type=so101_leader \
    --teleop.port=/dev/tty.usbmodem58760431551 \
    --teleop.id=my_awesome_leader_arm

API example

from lerobot.teleoperators.so_leader import SO101Leader, SO101LeaderConfig
from lerobot.robots.so_follower import SO101Follower, SO101FollowerConfig

robot_config = SO101FollowerConfig(
    port="/dev/tty.usbmodem5AB90687491",
    id="my_follower_arm",
)

teleop_config = SO101LeaderConfig(
    port="/dev/tty.usbmodem5AB90689011",
    id="my_leader_arm",
)

robot = SO101Follower(robot_config)
teleop_device = SO101Leader(teleop_config)
robot.connect()
teleop_device.connect()

while True:
    action = teleop_device.get_action()
    robot.send_action(action)

The teleoperate command will automatically:

  1. Identify any missing calibrations and initiate the calibration procedure.
  2. Connect the robot and teleop device and start teleoperation.

Cameras

To add cameras to your setup, follow this Guide.

Teleoperate with cameras

With rerun, you can teleoperate again while simultaneously visualizing the camera feeds and joint positions. This example uses two cameras, wrist and top; we keep the same camera setup for the rest of the tutorial.

Command

lerobot-teleoperate \
    --robot.type=so101_follower \
    --robot.port=/dev/tty.usbmodem5AB90687491 \
    --robot.id=my_follower_arm \
    --robot.cameras="{ wrist: {type: opencv, index_or_path: 0, width: 640, height: 480, fps: 30}, top: {type: opencv, index_or_path: 1, width: 640, height: 480, fps: 30}}" \
    --teleop.type=so101_leader \
    --teleop.port=/dev/tty.usbmodem5AB90689011 \
    --teleop.id=my_leader_arm \
    --display_data=true

API example

شيفرة (42 سطرًا)
import time
from lerobot.teleoperators.so_leader import SO101Leader, SO101LeaderConfig
from lerobot.robots.so_follower import SO101Follower, SO101FollowerConfig
from lerobot.cameras.opencv import OpenCVCameraConfig
from lerobot.utils.visualization_utils import init_visualization, log_visualization_data, shutdown_visualization

robot_config = SO101FollowerConfig(
    port="/dev/tty.usbmodem5AB90687491",
    id="my_follower_arm",
    cameras={
        "wrist": OpenCVCameraConfig(index_or_path=0, width=640, height=480, fps=30),
        "top": OpenCVCameraConfig(index_or_path=1, width=640, height=480, fps=30)
    }
)

teleop_config = SO101LeaderConfig(
    port="/dev/tty.usbmodem5AB90689011",
    id="my_leader_arm",
)

init_visualization("rerun", session_name="teleoperation")  # pass "foxglove" to stream to Foxglove instead

robot = SO101Follower(robot_config)
teleop_device = SO101Leader(teleop_config)
robot.connect()
teleop_device.connect()

TARGET_HZ = 30
TIME_PER_FRAME = 1.0 / TARGET_HZ

while True:
    start_time = time.perf_counter()

    observation = robot.get_observation()
    action = teleop_device.get_action()
    robot.send_action(action)
    log_visualization_data("rerun", observation=observation, action=action)

    elapsed_time = time.perf_counter() - start_time
    sleep_time = TIME_PER_FRAME - elapsed_time
    if sleep_time > 0:
        time.sleep(sleep_time)

Record a dataset

Once you're familiar with teleoperation, you can record your first dataset.

We use the Hugging Face hub features for uploading your dataset. If you haven't previously used the Hub, make sure you can login via the cli using a write-access token, this token can be generated from the Hugging Face settings.

Add your token to the CLI by running this command:

hf auth login --token ${HUGGINGFACE_TOKEN} --add-to-git-credential

Then store your Hugging Face repository name in a variable:

HF_USER=$(NO_COLOR=1 hf auth whoami | awk -F': *' 'NR==1 {print $2}')
echo $HF_USER

Now you can record a dataset. To record 5 episodes and upload your dataset to the hub, adapt the code below for your robot and execute the command or API example.

Command

lerobot-record \
    --robot.type=so101_follower \
    --robot.port=/dev/tty.usbmodem585A0076841 \
    --robot.id=my_awesome_follower_arm \
    --robot.cameras="{ front: {type: opencv, index_or_path: 0, width: 1920, height: 1080, fps: 30}}" \
    --robot.cameras="{ wrist: {type: opencv, index_or_path: 0, width: 640, height: 480, fps: 30}, top: {type: opencv, index_or_path: 1, width: 640, height: 480, fps: 30}}" \
    --teleop.type=so101_leader \
    --teleop.port=/dev/tty.usbmodem58760431551 \
    --teleop.id=my_awesome_leader_arm \
    --display_data=true \
    --dataset.repo_id=${HF_USER}/record-test \
    --dataset.num_episodes=5 \
    --dataset.single_task="Grab the black cube" \
    --dataset.streaming_encoding=true \
    --dataset.encoder_threads=2
# Optional: --dataset.rgb_encoder.vcodec=auto

API example

شيفرة (119 سطرًا)
from lerobot.cameras.opencv import OpenCVCameraConfig
from lerobot.datasets.lerobot_dataset import LeRobotDataset
from lerobot.utils.feature_utils import hw_to_dataset_features
from lerobot.robots.so_follower import SO101Follower, SO101FollowerConfig
from lerobot.teleoperators.so_leader.config_so_leader import SO101LeaderConfig
from lerobot.teleoperators.so_leader.so_leader import SO101Leader
from lerobot.common.control_utils import init_keyboard_listener
from lerobot.utils.utils import log_say
from lerobot.utils.visualization_utils import init_visualization
from lerobot.scripts.lerobot_record import record_loop
from lerobot.processor import make_default_processors

NUM_EPISODES = 5
FPS = 30
EPISODE_TIME_SEC = 60
RESET_TIME_SEC = 10
TASK_DESCRIPTION = "My task description"

def main():
    # Create robot configuration
    robot_config = SO101FollowerConfig(
        port="/dev/tty.usbmodem5AB90687491",
        id="my_follower_arm",
        cameras={
            "wrist": OpenCVCameraConfig(index_or_path=0, width=640, height=480, fps=30),
            "top": OpenCVCameraConfig(index_or_path=1, width=640, height=480, fps=30)
        }
    )

    teleop_config = SO101LeaderConfig(
        port="/dev/tty.usbmodem5AB90689011",
        id="my_leader_arm",
    )

    # Initialize the robot and teleoperator
    robot = SO101Follower(robot_config)
    teleop = SO101Leader(teleop_config)

    # Configure the dataset features
    action_features = hw_to_dataset_features(robot.action_features, "action")
    obs_features = hw_to_dataset_features(robot.observation_features, "observation")
    dataset_features = {**action_features, **obs_features}

    # Create the dataset
    dataset = LeRobotDataset.create(
        repo_id="<hf_username>/<dataset_repo_id>",
        fps=FPS,
        features=dataset_features,
        robot_type=robot.name,
        use_videos=True,
        image_writer_threads=4,
    )

    # Initialize the keyboard listener and rerun visualization
    _, events = init_keyboard_listener()
    init_visualization("rerun", session_name="recording")

    # Connect the robot and teleoperator
    robot.connect()
    teleop.connect()

    # Create the required processors
    teleop_action_processor, robot_action_processor, robot_observation_processor = make_default_processors()

    episode_idx = 0
    while episode_idx < NUM_EPISODES and not events["stop_recording"]:
        log_say(f"Recording episode {episode_idx + 1} of {NUM_EPISODES}")

        record_loop(
            robot=robot,
            events=events,
            fps=FPS,
            teleop_action_processor=teleop_action_processor,
            robot_action_processor=robot_action_processor,
            robot_observation_processor=robot_observation_processor,
            teleop=teleop,
            dataset=dataset,
            control_time_s=EPISODE_TIME_SEC,
            single_task=TASK_DESCRIPTION,
            display_data=True,
        )

        # Reset the environment if not stopping or re-recording
        if not events["stop_recording"] and (episode_idx < NUM_EPISODES - 1 or events["rerecord_episode"]):
            log_say("Reset the environment")
            record_loop(
                robot=robot,
                events=events,
                fps=FPS,
                teleop_action_processor=teleop_action_processor,
                robot_action_processor=robot_action_processor,
                robot_observation_processor=robot_observation_processor,
                teleop=teleop,
                control_time_s=RESET_TIME_SEC,
                single_task=TASK_DESCRIPTION,
                display_data=True,
            )

        if events["rerecord_episode"]:
            log_say("Re-recording episode")
            events["rerecord_episode"] = False
            events["exit_early"] = False
            dataset.clear_episode_buffer()
            continue

        dataset.save_episode()
        episode_idx += 1

    # finalize dataset
    log_say("Finalizing dataset...")
    dataset.finalize()
    # Clean up
    log_say("Stop recording")
    robot.disconnect()
    teleop.disconnect()
    dataset.push_to_hub()

if __name__ == "__main__":
    main()

The camera names you choose (here wrist and top) become the dataset keys observation.images.wrist and observation.images.top. A policy trained on this dataset expects the same camera names and resolution when you deploy it, so reuse the same --robot.cameras value in every step of this tutorial. If the names have to differ, see Rename Map.

lerobot-record adds the date and time of the session to the end of --dataset.repo_id, so every recording gets a unique name: ${HF_USER}/record-test is saved as ${HF_USER}/record-test_YYYYMMDD_HHMMSS (for example record-test_20260929_143012). Find the full name on your Hugging Face profile or with ls ~/.cache/huggingface/lerobot/${HF_USER}, and use it wherever the commands below say record-test_YYYYMMDD_HHMMSS. To keep the exact name you passed, add --dataset.no_stamp=true.

Dataset upload

Locally, your dataset is stored in this folder: ~/.cache/huggingface/lerobot/{repo-id}. At the end of data recording, your dataset will be uploaded on your Hugging Face page (e.g. ``) that you can obtain by running:

echo https://huggingface.co/datasets/${HF_USER}/record-test_YYYYMMDD_HHMMSS

Your dataset will be automatically tagged with LeRobot for the community to find it easily, and you can also add custom tags, for example --dataset.tags='["tutorial"]'.

You can look for other LeRobot datasets on the hub by searching for LeRobot tags.

You can also push your local dataset to the Hub manually, running:

hf upload ${HF_USER}/record-test_YYYYMMDD_HHMMSS ~/.cache/huggingface/lerobot/${HF_USER}/record-test_YYYYMMDD_HHMMSS --repo-type dataset

Record function

lerobot-record provides a suite of tools for capturing and managing data during robot operation:

1. Data Storage
  • Data is stored using the LeRobotDataset format and is stored on disk during recording.
  • By default, the dataset is pushed to your Hugging Face page after recording.
    • To disable uploading, use --dataset.push_to_hub=False.
2. Checkpointing and Resuming
  • Checkpoints are automatically created during recording.
  • If an issue occurs or you want to record additional episodes in the same dataset, you can resume by re-running the same command with --resume=true. Pass the full dataset name, including its timestamp (--dataset.repo_id=${HF_USER}/record-test_YYYYMMDD_HHMMSS). When resuming a recording, --dataset.num_episodes must be set to the number of additional episodes to be recorded, and not to the targeted total number of episodes in the dataset! Make sure that you also set --dataset.root="local_path", it's a local path to save the new part of the dataset and is required to resume.
  • Re-running the command without --resume=true starts a new dataset with a new timestamp. If you use --dataset.no_stamp=true, delete the existing dataset directory first.
3. Recording Parameters

Set the flow of data recording using command-line arguments:

  • --dataset.episode_time_s=60 Duration of each data recording episode (default: 60 seconds).
  • --dataset.reset_time_s=60 Duration for resetting the environment after each episode (default: 60 seconds).
  • --dataset.num_episodes=50 Total number of episodes to record (default: 50).
4. Keyboard Controls During Recording

Control the data recording flow using keyboard shortcuts:

  • Press Right Arrow (→) or n: Early stop the current episode or reset time and move to the next.
  • Press Left Arrow (←) or r: Cancel the current episode and re-record it.
  • Press Escape (ESC) or q: Immediately stop the session, encode videos, and upload the dataset.

These control-flow shortcuts work on X11, Wayland, and headless/SSH sessions. When a global keyboard backend isn't available (Wayland, a headless machine, or macOS without Accessibility permission), lerobot-record automatically reads the same keys from the terminal — launch it from an interactive terminal and keep it focused. You can also use the letter equivalents n (next, same as →), r (re-record, same as ←) and q (quit, same as ESC). No $DISPLAY setup is required.

This applies to the recording control flow only. Keyboard teleoperation (driving the robot with the keyboard) still needs a global key backend, so it works only on an X11 session, a Windows desktop, or macOS with Accessibility/Input Monitoring granted — not on Wayland or headless sessions.

Tips for gathering data

Once you're comfortable with data recording, you can create a larger dataset for training. A good starting task is grasping an object at different locations and placing it in a bin. We suggest recording at least 50 episodes, with 10 episodes per location. Keep the cameras fixed and maintain consistent grasping behavior throughout the recordings. Also make sure the object you are manipulating is visible on the cameras. A good rule of thumb is you should be able to do the task yourself by only looking at the camera images.

In the following sections, you’ll train your neural network. After achieving reliable grasping performance, you can start introducing more variations during data collection, such as additional grasp locations, different grasping techniques, and altering camera positions.

Avoid adding too much variation too quickly, as it may hinder your results.

If you want to dive deeper into this important topic, you can check out the blog post we wrote on what makes a good dataset.

Cadence reporting

lerobot-record paces the loop at --dataset.fps and reports what it actually achieved: a one-line digest for every episode you keep, and a block for the whole session when recording ends — including on Ctrl-C.

Cadence (episode 0): 29.88 Hz vs 30 Hz target · 600 ticks, 20.0 s measured · 8/599 ticks over the 33.3 ms budget (work mean 18.4 ms, worst 45.1 ms)
Cadence (episode 1): 29.88 Hz vs 30 Hz target · 600 ticks, 20.0 s measured · 8/599 ticks over the 33.3 ms budget (work mean 18.4 ms, worst 45.1 ms)
Cadence summary — whole run, 2 episodes · target 30 Hz (33.3 ms budget per tick): 1200 ticks, 1198 judged
  effective cadence: 29.88 Hz over 40.1 s measured
  ticks over the 33.3 ms work budget: 16/1198 (1.3%) — work mean 18.4 ms, worst 45.1 ms
  loop-body steps (share of measured work):
    observe      mean  13.65 ms · worst  40.20 ms ·  74.4% of work · 1200 calls
    process_obs  mean   0.30 ms · worst   0.30 ms ·   1.6% of work · 1200 calls
    teleop       mean   1.80 ms · worst   1.80 ms ·   9.8% of work · 1200 calls
    send         mean   0.90 ms · worst   0.90 ms ·   4.9% of work · 1200 calls
    record       mean   1.70 ms · worst   1.90 ms ·   9.3% of work · 1200 calls
  pacing headroom: 15.1 ms slept per tick on average (max 16.7 ms) — near zero means the loop is saturated

This is worth reading before you train on the dataset. A frame's timestamp is derived from its index, so a session that ran at 25 Hz still produces a dataset that claims 30 — the recorded motion is simply faster than reality. Above, observe is 74% of the loop's work and its worst is 40 ms on a 33.3 ms budget: the cameras are what pushed those 16 ticks over. Pacing headroom near zero means there is nothing left to absorb a slow tick.

The reset phases between episodes are paced the same way but are deliberately not part of these numbers, since they record nothing. lerobot-teleoperate and lerobot-replay report the same way, and lerobot-rollout adds the interpolation-specific lines described in Cadence Reporting.

Troubleshooting:

  • On Linux, the recording control-flow keys (arrow keys, Escape) work on X11, Wayland, and headless/SSH sessions as long as lerobot-record runs in an interactive terminal — no $DISPLAY setup is needed. If the keys have no effect, make sure you are in an interactive (TTY) terminal, not a piped/non-TTY session, and that it is focused; the letter equivalents n / r / q also work. Keyboard teleoperation (as opposed to the recording control flow) still requires a global key backend — an X11 session, a Windows desktop, or macOS with Accessibility/Input Monitoring granted — and is unavailable on Wayland or headless machines. See pynput limitations.

Visualize a dataset

Your dataset is uploaded to the Hub by default (unless you passed --dataset.push_to_hub=False), so you can open it in the LeRobot Dataset Visualizer right away: enter your repo id on its home page, or go straight to the first episode with the link this prints:

echo "https://huggingface.co/spaces/lerobot/visualize_dataset?path=/${HF_USER}/record-test_YYYYMMDD_HHMMSS/episode_0"

Sign in on the visualizer to open a private dataset. See Explore a Dataset in the Browser for a walkthrough.

Replay an episode

A useful feature is the replay function, which allows you to replay any episode that you've recorded or episodes from any dataset out there. This function helps you test the repeatability of your robot's actions and assess transferability across robots of the same model.

You can replay the first episode on your robot with either the command below or with the API example:

Command

lerobot-replay \
    --robot.type=so101_follower \
    --robot.port=/dev/tty.usbmodem58760431541 \
    --robot.id=my_awesome_follower_arm \
    --dataset.repo_id=${HF_USER}/record-test_YYYYMMDD_HHMMSS \
    --dataset.episode=0 # choose the episode you want to replay

API example

import time

from lerobot.datasets import LeRobotDataset
from lerobot.robots.so_follower import SO101Follower, SO101FollowerConfig
from lerobot.utils.robot_utils import precise_sleep
from lerobot.utils.utils import log_say

episode_idx = 0

robot_config = SO101FollowerConfig(port="/dev/tty.usbmodem5AB90687491", id="my_follower_arm")

robot = SO101Follower(robot_config)
robot.connect()

dataset = LeRobotDataset("<hf_username>/<dataset_repo_id>", episodes=[episode_idx])
actions = dataset.select_columns("action")

log_say(f"Replaying episode {episode_idx}")
for idx in range(dataset.num_frames):
    t0 = time.perf_counter()

    action = {
        name: float(actions[idx]["action"][i]) for i, name in enumerate(dataset.features["action"]["names"])
    }
    robot.send_action(action)

    precise_sleep(max(1.0 / dataset.fps - (time.perf_counter() - t0), 0.0))

robot.disconnect()

Your robot should replicate movements similar to those you recorded. For example, check out this video where we use replay on an ALOHA robot from Trossen Robotics.