Skip to content

Fine-tuning Tutorial

Fine-tune Dream-1 for a new robot with recordings from it, then run it on your robot.

Important: Fine-tuning is for new robots, not for automating a task. It teaches Dream-1 your robot’s body. It doesn’t promise that a task works reliably. To have a task automated on your robot, email deployments@dreamlabs.co.

Every step uses one or two calls on dream.DreamClient. The code runs as written once you swap in your own robot and dataset.

Step Time
Steps 1 to 4 - Set up and upload About 30 minutes
Step 5 - Processing your dataset A few minutes, longer for big datasets
Step 6 - Training About 7 to 8 hours for 1,000 steps with two or three cameras, longer for more steps, and the job may queue first. Fine-tuning trains at most three cameras.
Step 8 - First start of your model Up to 1 hour

You can stop between any two steps.

You’ll need:

  • A robot that records joint angles. Each recording should store where every joint is, as an absolute angle, and how open each gripper is. Other formats aren’t supported yet. A two-arm robot may also record each gripper’s end-effector pose beside its joints and train on it (steps 3 and 6).
  • Your recordings in LeRobot v2.1 or v3.x format. LeRobot is an open format for robot recordings. Each dataset is a folder with three parts: meta/ describes the recording and the text of each task, data/ holds the state and action tables, and videos/ has the camera videos. Upload v3.x as LeRobot wrote it; processing converts it to v2.1 automatically before training.
  • An API key. Create one here.
  • Credits for training. At the time of writing, training costs $0.20 per step: $100 for 500 steps, $200 for the default 1,000 and $2,000 for 10,000. Running a fine-tuned model then costs $0.0028 per action. Add credits on the Billing page, which shows the current prices (step 6, “What it costs”).
  • Python 3.10, 3.11, or 3.12.

Not sure your recordings qualify? Step 4 checks them on your computer before anything uploads.

This tutorial is also a Jupyter notebook with the same code: download the notebook, then open it in the Python environment you set up in step 1:

Terminal
uv pip install --python ~/dream-env/bin/python notebook
jupyter notebook fine_tuning_tutorial_joint_space.ipynb

The dream library includes the client and the tools that check and upload datasets. Install it with the install step of Setup, on the computer you’ll use for this tutorial: it installs the library from PyPI into a Python 3.12 environment in ~/dream-env and saves your key. Then turn the environment on:

Terminal
source ~/dream-env/bin/activate

You should see: (dream-env) at the start of the prompt.

DreamClient reads your API key from a credentials file, which also names this platform’s own addresses. Create the file once. Replace dl_live_... with your API key, then run:

Terminal
mkdir -p ~/.dreamlabs && cat > ~/.dreamlabs/credentials <<'EOF'
DREAM_GATEWAY_URL={{gateway_url}}
DREAM_API_URL={{platform_url}}
DREAM_DATA_URL={{data_url}}
DREAM_API_KEY=dl_live_...
EOF
chmod 600 ~/.dreamlabs/credentials

Copy the three address lines as they are: they are set by Dream Labs for this platform, and your code never sets them.

Now create the client:

Python
import time

import dream

client = dream.DreamClient()   # Reads the credentials file. Nothing is sent yet.
print(client)

You should see: <dream.DreamClient>. The client never prints your key or the addresses.

An embodiment describes your robot so the service can read your recordings. It says which values in each state and action vector belong to which joint or gripper, and which video belongs to which camera. You register it once, under a name.

The example below is a robot with two arms, each with six joints and a gripper, and three cameras. Replace it with your own robot.

Python
config = {
    # [start, end) spans in the recorded observation.state and action vectors. No gaps, no overlaps.
    "state":  {"right_arm": [0, 6], "right_gripper": [6, 7], "left_arm": [7, 13], "left_gripper": [13, 14]},
    "action": {"right_arm": [0, 6], "right_gripper": [6, 7], "left_arm": [7, 13], "left_gripper": [13, 14]},
    # Each camera role, mapped to the video key your dataset records that camera under.
    "video": {
        "overhead": "observation.images.overhead",
        "wrist_l": "observation.images.wrist_l",
        "wrist_r": "observation.images.wrist_r",
    },
    # Optional: the role of the fixed camera that looks over the workspace.
    "head_camera": "overhead",
}

# Embodiment names are unique within your account. If the name is taken, reuse the existing embodiment,
# but only if its config matches. A registered embodiment can't be changed.
try:
    embodiment = client.add_embodiment("two-arm-robot", config)
except dream.DreamServerError as error:
    if error.code != "conflict":
        raise
    embodiment = next(e for e in client.get_embodiments() if e.name.endswith("/two-arm-robot"))
    if embodiment.embodiment_config != config:
        raise SystemExit(f"{embodiment.name} has a different config. Register this robot under a new name.")
print(embodiment.name)

You should see: <your-username>/two-arm-robot

Key Required Description
state Yes Each part’s name, mapped to its [start, end) span in observation.state. The spans must cover the whole vector, with no gaps or overlaps. Up to 128 of its values train, and a fine-tune reads at most 64, the base model’s state; a part marked not trained in parts stays in the data and counts toward neither.
action Yes The same, for the action vector, up to 128 values. A fine-tune trains at most 34 of them, the base model’s width, and refuses a wider one with invalid_request: mark the parts the model need not drive (a torso, a head) as not trained in parts.
video Yes Each camera role, mapped to the video key in your dataset. The model trains on every role you list, at most three. If your dataset has more than three cameras, list the three to train: the others stay in your dataset, and training leaves them out.
head_camera Unless a role is named overhead The role of the fixed camera that looks over the workspace, the view your dense text labels come from. If you leave it out, a role named overhead is used; a robot with neither is refused.
  • Parts and roles: Lowercase letters, numbers, and underscores, starting with a letter. These become the keys you use when you run the model in step 8.
  • Embodiment name: Lowercase letters, numbers, and hyphens, up to 64 characters.

The client checks your config before sending it. If something is wrong, it raises DreamConfigError with one line that names the part, role, or key to fix.

A two-arm robot that also records each gripper’s end-effector pose (its position and orientation) names six parts for it, by exactly these names and widths, in both state and action: right_eef_xyz (3 values), right_eef_rot6 (6), right_grip (1), left_eef_xyz (3), left_eef_rot6 (6) and left_grip (1). Every other part counts as joints. Each arm’s pose is in that arm’s own base frame, not one frame shared by both arms: <side>_eef_xyz is the tool centre point, the grasp point between the fingers, in metres (on YAM 0.1347 m past the wrist flange along the last link’s z axis); <side>_eef_rot6 is the last link’s orientation as the first two columns of its 3x3 rotation matrix, [R00, R10, R20, R01, R11, R21] (columns, not rows, and not a quaternion); <side>_grip is the gripper aperture, 0 closed to 1 open. The base model learned the pose this way, and nothing can check it for you: a pose recorded another way, at the flange for example, is accepted and trains a model that moves wrong. A fine-tune trains these parts only when you ask for it (step 6), and a body whose action carries right_eef_rot6 or left_eef_rot6 must ask for it: without it the run is refused with invalid_request. Without use_eef, an action that carries right_eef_xyz or left_eef_xyz also needs that side’s _eef_xyz and _eef_rot6 in state, or the run is refused the same way. Single-arm end-effector bodies are not supported.

Important: You can’t change or delete an embodiment after you register it. To change a config, register it under a new name.

A dataset is one LeRobot v2.1 or v3.x folder, or a folder that contains several sessions, one in each subfolder. Versions may not be mixed inside one session. Upload v3.x exactly as LeRobot wrote it: processing converts it to v2.1 automatically before the rest of preparation and training.

Each folder’s meta/info.json needs the fields LeRobot writes for its version: codebase_version ("v2.1" or "v3.x"), fps, total_episodes, total_frames, data_path, video_path and features; v2.1 also has chunks_size. In features, action and observation.state each need a dtype and a one-value shape whose number is the width your config’s spans cover, and each camera needs an entry of dtype "video" named by its video key. Other fields LeRobot writes can stay. This complete v2.1 example shows the features; a standard v3.x export carries the equivalent metadata plus its parquet task and episode indexes:

{
  "codebase_version": "v2.1",
  "robot_type": "yam",
  "total_episodes": 2,
  "total_frames": 300,
  "total_tasks": 2,
  "total_videos": 6,
  "total_chunks": 1,
  "chunks_size": 1000,
  "fps": 30,
  "splits": { "train": "0:2" },
  "data_path": "data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet",
  "video_path": "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4",
  "features": {
    "action": { "dtype": "float32", "shape": [14], "names": null },
    "observation.state": { "dtype": "float32", "shape": [14], "names": null },
    "observation.images.overhead": { "dtype": "video", "shape": [720, 1280, 3], "names": ["height", "width", "channels"], "info": { "video.fps": 30, "video.codec": "h264" } },
    "observation.images.wrist_l": { "dtype": "video", "shape": [720, 1280, 3], "names": ["height", "width", "channels"], "info": { "video.fps": 30, "video.codec": "h264" } },
    "observation.images.wrist_r": { "dtype": "video", "shape": [720, 1280, 3], "names": ["height", "width", "channels"], "info": { "video.fps": 30, "video.codec": "h264" } },
    "timestamp": { "dtype": "float32", "shape": [1], "names": null },
    "frame_index": { "dtype": "int64", "shape": [1], "names": null },
    "episode_index": { "dtype": "int64", "shape": [1], "names": null },
    "index": { "dtype": "int64", "shape": [1], "names": null },
    "task_index": { "dtype": "int64", "shape": [1], "names": null }
  }
}

validate_dataset runs the same checks as the service, on your computer, without sending anything. It confirms that:

  • Each table is as wide as the spans in your config.
  • The camera videos match the roles in your config: every camera has a role, or, in a dataset with more than three cameras, exactly three do.
  • Every camera covers every episode. v2.1 uses videos/chunk-<NNN>/<video key>/<episode>.mp4; v3.x uses videos/<video key>/chunk-<NNN>/file-<NNN>.mp4 and may put several episodes in one file. video_path must name the version’s standard layout.
  • Each video holds one frame per frame of its episode, evenly spaced at the frame rate in meta/info.json (30 fps, or 15, 10 or 5, which training brings up to 30).
  • Each camera’s entry in meta/info.json names the axes of its shape ("names": ["height", "width", "channels"]), which training reads them by.
  • Every recording has the same frame rate and features.
  • Every data row names its episode_index; v2.1 keeps one episode per table, while v3.x may consolidate several episodes in one table. An index column, if present, counts up by one from frame to frame.
  • There’s at least one episode, and each spans at least 1.6 s from its first frame to its last (49 frames at 30 fps, 25 at 15, 17 at 10, 9 at 5), the length of one training sample.
  • Every task has text in meta/tasks.jsonl (v2.1) or meta/tasks.parquet (v3.x).

If your timestamps drift from your videos, the check still passes, with a line in report.notes: processing sets each timestamp to frame_index / fps, so each frame is paired with its own video frame.

The model learns to follow the task text, so write each task the way you’ll prompt the robot.

Python
import pathlib

DATASET_DIR = pathlib.Path("~/data/headphones").expanduser()   # Your LeRobot v2.1 or v3.x dataset

report = client.validate_dataset(DATASET_DIR, config)
if not report.ok:
    raise SystemExit(report.error)   # One line that names what to fix
print(f"{report.sessions} sessions, {report.episodes} episodes, {report.frames} frames")
print("state", report.state_dim, "action", report.action_dim, "fps", report.fps, "cameras", report.video_keys)
for line in report.warnings:
    print("WARNING", line)   # Not a failure: something that is usually a recording mistake
FPS = report.fps   # Your recording's frame rate. Step 8 plays actions back at this rate.

You should see: The episode and frame counts, and the cameras your config names.

A dataset that passes can still hold bad recordings: the checks confirm that training can run on your data, not that the data is good. So validate_dataset also reads the episodes for what is usually a recording mistake and lists each in report.warnings, one line that names the session and the episodes. A warning never fails the check, and upload_dataset shows the same lines and uploads anyway. Read them before you start a fine-tune, because a model trained on such episodes learns them. It warns about:

  • An action or state that never changes in an episode; one value of it (a joint, a gripper) that never changes in the whole session; and a joint that never changes in an episode while the rest of its arm moves. An episode that uses one arm, or leaves a gripper alone, is not warned about.
  • Values above 10, a value that jumps by more than 1 between two frames at 30 fps (more at a lower frame rate), and a first action more than 0.5 from the first state. These limits suit an arm recorded in radians and metres.
  • Two episodes with exactly the same actions.
  • A <side>_grip part outside 0 to 1, and a <side>_eef_rot6 part that is not the first two columns of a rotation matrix.
  • A video that is not the size meta/info.json gives its camera, is not 16:9, is black, or shows one unchanging picture; and one video file on two cameras of an episode.
  • Fewer than 10 episodes.

The warnings are guesses, so one can be wrong for your robot: a gripper you never use does not change. They do not judge whether a demonstration succeeded or whether the task text describes it; watch your episodes for that. The Upload page lists the same warnings under each session, except a black or unchanging video, which only validate_dataset reads.

upload_dataset checks the dataset again, packs it into one file, uploads it, and registers it under the name you give it.

Important: For a v3.x upload, the dataset stays in its original format while it is sent. During Processing, Dream Labs splits its consolidated tables and videos into v2.1 episodes, then runs the same preparation and training path as a v2.1 upload. You do not need to rename files or run a conversion script.

Important: upload_dataset first writes the dataset as one uncompressed file in your computer’s temporary folder, so that folder needs free space about the size of the dataset. If it has less, the call stops before writing anything and says how much it needs and how much is free. To use a disk with more room, set TMPDIR when you start Python (TMPDIR=/path/with/space python upload.py), or in a notebook run import tempfile; tempfile.tempdir = "/path/with/space" before you upload.

Python
dataset = client.upload_dataset(DATASET_DIR, "headphones-1", embodiment.name)
print(dataset.id, dataset.status, dataset.episodes, dataset.size_bytes)

You should see: An ID that starts with ds_, and the status ready_to_process.

Important: Save the dataset ID. You need it to check the dataset’s status. If you lose it, client.get_datasets() lists your datasets, newest first, each with its name and ID.

  • Name: Lowercase letters, numbers, and hyphens, up to 64 characters. A name is available unless another of your datasets uses it. The name of a failed dataset can be used again.
  • If the upload stops: Run the same call again. The upload starts over under the same name.

The service now prepares your dataset for training. Its status moves from ready_to_process to processing to processed. If processing fails, the status is failed, and dataset.error says why. You can start a fine-tuning job only on a processed dataset.

This loop checks the status every 30 seconds until processing ends:

Python
while dataset.status not in ("processed", "failed"):
    time.sleep(30)
    dataset = client.get_dataset_status(dataset.id)
    print(dataset.status)
assert dataset.status == "processed", dataset.error

You should see: processing, repeated, then processed. A short dataset takes several minutes.

To pick up later: Get the dataset by its ID: dataset = client.get_dataset_status("ds_...").

finetune queues a training job on your processed dataset. The suffix you choose becomes the end of your model’s ID: dream-1-ft:<account>-<suffix>, where <account> is an 8-character ID for your account. For example, dream-1-ft:a1b2c3d4-headphones.

Python
# use_eef=True also trains the end-effector pose (the body must name the six end-effector parts, step 3)
job = client.finetune(dataset.name, "headphones")
print(job["id"], job["status"], "queue position", job["queue_position"])

while job["fine_tuned_model"] is None and job["status"] in ("queued", "running", "succeeded"):
    time.sleep(60)
    job = client.get_finetuning_status(job["id"])
    print(job["status"], job.get("queue_position"))

checkpoint = job["fine_tuned_model"]
assert checkpoint, f"No model: {job['status']} {job.get('error')}"
print("model:", checkpoint)

You should see: queued, then running, then your model’s ID.

Parameter Description
suffix Required. 1 to 40 lowercase letters, numbers, and hyphens. Each job needs a new suffix. A suffix that’s already used by one of your models, or by a job that’s queued or running, raises conflict.
steps Optional. Any multiple of 100 from 500 to 10000. Default: 1000. The price grows with the steps (“What it costs” below), and so does the time.
resume_from Optional. One of your models’ IDs, to keep training it (“Keep training a model” below). Default: a new model from Dream-1.
learning_rate Optional. 1e-6 to 1e-4. Default: 1e-5.
use_eef Optional. Default: False. Also trains the end-effector pose, the six parts in step 3, beside the joints.
lr_schedule Optional. "constant" or "cosine". Default: "constant". Both warm up first; "cosine" then lowers the learning rate to 0 by the last step.
base_share Optional. 0.5 or 0.0. Default: 0.5. The share of each training batch drawn from Dream-1’s own general training data: 0.5 keeps more of what the model already does in general, and 0.0 trains on your sessions alone, which fits them more closely but can lose general skill. The site’s Fine-tune form calls it Training data: “Mix in Dream Labs data” is 0.5, “Train on my data only” is 0.0.

Important: Cosine decay works best for specialization (a fine-tune on a single task). You may not get high reliability on specialist tasks yet.

A value outside these ranges raises invalid_request, and the error names the parameter. Your model is the result of the last training step.

With use_eef=True, the dataset’s robot must carry all six end-effector parts at their widths; one that doesn’t raises DreamConfigError naming the part before anything is sent, and the service refuses it with invalid_request. A body whose action carries right_eef_rot6 or left_eef_rot6 trains only with use_eef=True: a job on it without use_eef is refused with invalid_request. With use_eef or without, a job trains at most 34 action values, the base model’s width; a wider action is refused with invalid_request.

You choose how many steps a job trains: any multiple of 100 from 500 to 10,000. At the time of writing each step costs $0.20, so a job costs $100 for 500 steps, $200 for the default 1,000, $400 for 2,000 and $2,000 for 10,000. The Fine-tune form on the Datasets page and the payment_required message name the current price. Your balance and the current prices are on the Billing page; an API key can’t read them.

Running your fine-tuned model is charged per action, as any model is, at the fine-tune’s own price: $0.0028 per action at the time of writing, twice the base Dream-1’s. The Models page shows each of your models’ price.

When you queue a job, its price is held from your prepaid credits, which the Billing page shows; if your available credits don’t cover it, finetune raises payment_required, and the message names the price and what you have. The hold is charged when your model is published. A run that ends early is charged only for the last checkpoint it saved, in proportion to the steps it reached, and a run that saved none costs nothing.

While the hold is open, your robot keys can spend only what’s left above it. If the price equals your balance, your keys pause until the job ends, so add credits first if a robot should keep running during training. Once queued, a job runs to the end; cancel is refused with conflict.

A job shows queued until a training slot is free, and queue_position is its place in line. It then waits for a GPU, with progress["phase"] set to waiting_for_gpu. Then it shows running while it prepares and trains, with progress["loss"] where the service reports it. The loop checks once a minute.

A 1,000-step job on a robot with two or three cameras takes about 7 to 8 hours, and more steps take longer: a 10,000-step job takes two to three days. Fine-tuning trains at most three cameras.

  • Failed: The status is failed, there’s no model, and error says why.
  • Stopped short: The status is succeeded with notice set: the run ended before its last step (its loss stopped being a number, or it failed), the model is the newest checkpoint it had saved, and you were charged for that checkpoint’s share of the steps. A run that saved no checkpoint is failed and costs nothing.

To train one of your models further, pass its ID as resume_from, with steps set to the new steps. The job picks up where that model’s training ended, optimizer and learning-rate schedule included, and you pay only for the new steps. It makes a new model under its own suffix; the one it continues stays as it is.

Python
job = client.finetune(dataset.name, "headphones-more", steps=1000, resume_from="dream-1-ft:a1b2c3d4-headphones")
  • Which models: Your own, trained after this option was added and finished to their last step, within 29 days of when that job finished. Models trained before it can’t be continued, because they didn’t keep what training needs to pick up, and after 29 days what it kept is deleted. The model itself stays yours to run either way.
  • What must match: The dataset’s robot, learning_rate, batch_size and use_eef stay the model’s own, and the schedule is constant. A model trained with lr_schedule="cosine" can’t be continued, since its learning rate ended at 0.
  • Otherwise: finetune raises invalid_request saying which rule the job breaks, before anything is held.

To pick up later: List your jobs, newest first, to find the job ID. A job runs to its end once queued; there is no cancel.

Python
from dream import fine_tuning

for job in fine_tuning.list():
    print(job["id"], job["status"], job.get("fine_tuned_model"))

get_models lists every model your account can run: public Dream models and your fine-tuned models. Your models have owner set to mine.

Python
for model in client.get_models():
    if model.owner == "mine":
        print(model.id, "ready" if model.servable else "not ready")

# If you start a new session, set checkpoint to your model's ID:
# checkpoint = "dream-1-ft:<account>-headphones"

You should see: Your model’s ID, marked ready.

servable means the model can run. It doesn’t mean the model is running now. The first call to a model that isn’t running waits while it starts (step 8).

client.policy({"checkpoint": checkpoint}) selects the model to run. It doesn’t send anything. The first get_action call opens a session, and later calls continue it, so the model keeps context across the episode.

Start each episode with a new session. Call client.reset_episode() at the start of every episode. This ends the previous session and empties the frames the client kept, and the next get_action opens a new one. When you finish, call client.close().

Hand the client every camera tick with client.set_observation(frames, observation). It returns at once and never waits for the network. client.get_action() takes no argument: it sends your newest state with the frames the client kept for each camera.

Both dicts are keyed by the embodiment your model was trained on. frames has one frame for each camera, and observation has every other key:

Key One for each Value
state.<part> Part of state In observation: a list of floats as wide as the part’s span, in your dataset’s units
video.<role> Role in video In frames: the camera’s newest frame, one base64 JPEG. See Camera frames.
prompt Observation In observation: the task, in words

For the example robot, the keys are state.right_arm (6 values), state.right_gripper (1 value), state.left_arm (6 values), state.left_gripper (1 value), video.overhead, video.wrist_l, video.wrist_r, and prompt.

A missing part or camera, or a part with the wrong width, raises an error that names the key.

Important: Don’t use the YAM keys from the API documentation, such as state.arm_r.* and image_window.*. A fine-tuned model refuses an observation that mixes the two.

  • Ticks: Hand the client a tick every time your cameras have a new frame, or at least once for each step, as the loop below does. Every tick of an episode has the same cameras, and each tick replaces the state, so get_action always sends the state of your last tick.
  • Spacing: The client keeps one frame every 6 recorded frames, which is 0.2 seconds at 30 fps (obs_fps in the loop below), and sends each camera’s last 9, oldest first. This matches the window the model trained on.
  • Episode start: Until 9 frames are kept, the client sends the ones it has, spread over the 9 positions. A single frame looks like a still image to the model.
  • Size: Every frame is stretched to 320 x 176 pixels, never padded, the same way your recordings were resized for training, and the model then trims 2.5% from each edge, as it did in training. Frame each camera as in your recordings. Frames that are already 320 x 176 upload fastest.
  • Shape: Record and run in a 16:9 camera mode, such as 1280x720: most of the robot video Dream-1 was trained on, before it learned from your recordings, is 16:9. If your camera has no 16:9 mode, center-crop each frame to 16:9 before you encode it, rather than sending 4:3 or square frames, which the model squashes into 320 x 176: a 4:3 frame (640x480) reaches it 1.36x wider than it is, and a square one 1.82x. Crop the same way when you record your fine-tuning data and when you run the model. For an OpenCV image frame taller than 16:9: h, w = frame.shape[:2]; top = (h - w * 9 // 16) // 2; frame = frame[top : top + w * 9 // 16]. If you already recorded without cropping, run without cropping too. The client never crops your frames.
  • Format: One JPEG for each camera, never a list, quality about 85, encoded as base64 with no data: prefix. OpenCV’s cv2.imencode creates one from an OpenCV image.

The reply’s per_key has one action.<part> for each part of action. Each has 48 rows, one for each step ahead at your dataset’s frame rate, in your dataset’s units.

For the example robot, the reply includes:

Key Shape
action.right_arm [48, 6]
action.right_gripper [48]
action.left_arm [48, 6]
action.left_gripper [48]

Read actions from per_key. A robot laid out exactly like the YAM arms, as the example is, also gets q_r_chunk and q_l_chunk. You can ignore them.

The client doesn’t smooth the change from one chunk to the next. Blend from your last command into each new chunk over a few rows.

The first call: A model that isn’t running raises a retryable DreamServerError with the reason pool_warming while it starts. This happens on a new model’s first call, and on any model’s first call after it’s been idle. Starting can take up to an hour and shows no progress; in our tests it took 25 to 50 minutes. Try again after retry_after_s seconds.

Once it’s running: A call takes about 250 to 450 ms.

Rate limit: Each session can make 3 calls in a row, then 1 call every 0.7 seconds. A faster call raises a retryable error with the reason rate_limited.

Both pool_warming and rate_limited use the code DA-2000. Check reason to tell them apart.

When the loop stops: It tries again after every retryable error, and after a call that got no reply in time or lost its connection (DreamTimeout, DreamProtocolError). It stops on any other error, and after four error replies in a row, when the model keeps failing. An observation the model can’t read is refused at once with malformed (DreamBadRequest), which is never retryable, and its message names the problem.

Replace these three calls with your robot’s own:

Call Returns or takes
robot.state() Returns the state vector, laid out like observation.state in your dataset
robot.camera(role) Returns the newest frame from one camera, as a BGR image array
robot.command(row) Takes one action vector, laid out like the actions in your dataset

The loop also uses config from step 3, FPS from step 4, and checkpoint from step 6 or 7. If you start a new session, set them again.

This loop is the simplest version: request 48 steps, play them while handing the client a tick after each, and request again. To keep the robot moving without a pause, request the next chunk while the current one plays.

Python
import base64

import cv2
import numpy as np

PROMPT = "pick up the headphones"
FRAME_SIZE = (320, 176)    # Width x height. Sending this size uploads fastest.


def camera_frames():
    """Returns the newest frame from each camera as a base64 JPEG, under its video.<role>."""
    frames = {}
    for role in config["video"]:
        small = cv2.resize(robot.camera(role), FRAME_SIZE, interpolation=cv2.INTER_AREA)
        ok, jpeg = cv2.imencode(".jpg", small, [cv2.IMWRITE_JPEG_QUALITY, 85])
        if not ok:
            raise RuntimeError(f"camera {role}: JPEG encoding failed")
        frames[f"video.{role}"] = base64.b64encode(jpeg.tobytes()).decode("ascii")
    return frames


def build_observation(state):
    """Builds one state.<part> for each state part, and the prompt."""
    observation = {f"state.{part}": [float(v) for v in state[start:end]] for part, (start, end) in config["state"].items()}
    observation["prompt"] = PROMPT
    return observation


def tick():
    """Hands the client one camera tick: the newest frame from each camera, and the robot's state now."""
    client.set_observation(camera_frames(), build_observation(robot.state()))


def action_rows(action):
    """Converts per_key into rows of your action vector, one row for each step ahead."""
    per_key = {key: np.asarray(value, dtype=np.float32) for key, value in action["per_key"].items()}
    steps = len(next(iter(per_key.values())))
    rows = np.zeros((steps, max(end for _, end in config["action"].values())), dtype=np.float32)
    for part, (start, end) in config["action"].items():
        rows[:, start:end] = per_key[f"action.{part}"].reshape(steps, end - start)
    return rows


def get_action():
    """client.get_action, asked again while the model starts, on any other retryable error and on a network error.

    A model that fails four times in a row (reason "error") is not asked again. An observation the model can't read
    is refused at once with reason "malformed", never retried, and its message names the problem. Every wait ends
    with a new tick, so the next try sends the robot as it is then.
    """
    errors_in_a_row = 0
    while True:
        try:
            return client.get_action()   # The newest state, with the frames the client kept for each camera
        except dream.DreamSessionExpired:
            errors_in_a_row = 0
            continue  # the session restarted; the client already holds the new one
        except dream.DreamServerError as error:
            if not error.retryable:
                raise  # a refused observation names the key that is missing or wrong
            errors_in_a_row = errors_in_a_row + 1 if error.reason == "error" else 0
            if errors_in_a_row > 3:
                raise  # the model fails this observation every time; its message says why
            wait = error.retry_after_s or 10
            print(f"{error.reason}: trying again in {wait:.1f} seconds")
            time.sleep(wait)
        except (dream.DreamTimeout, dream.DreamProtocolError) as error:
            errors_in_a_row = 0
            print(f"{error}: asking again in 1 s")  # no reply in time, or the connection was lost
            time.sleep(1)
        tick()


# The client keeps one frame every 6 recorded frames (0.2 seconds at 30 fps), the spacing the model trained on.
client.policy({"checkpoint": checkpoint, "obs_fps": FPS / 6})
try:
    client.reset_episode()   # For each new episode: a new session, and no frames kept from the last one.
    tick()
    while True:
        action = get_action()
        for row in action_rows(action):   # 48 steps ahead, in your dataset's units
            robot.command(row)
            time.sleep(1 / FPS)
            tick()   # After every step: the newest frames and state
finally:
    client.close()   # Ends the session

You should see: pool_warming: trying again in ... seconds while the model starts. Once it’s running, the robot starts moving.

Warning: The model’s actions aren’t checked against your robot’s limits. Apply your own joint, velocity, and workspace limits in robot.command, and keep the emergency stop button within reach whenever the robot runs.