Collecting clean demonstration trajectories is often the earliest bottleneck in an imitation learning pipeline. Before assembling a leader-follower teleoperation rig—or while iterating on policy architectures such as ACT and Diffusion Policy—a scripted demonstrator inside a physics engine lets you generate hundreds of labeled episodes deterministically and verify every downstream stage of the training stack.
Building on a Python 3.12 environment configured per the MuJoCo 3.16.0 and LeRobot 0.6.1 installation guide, this tutorial walks through constructing a privileged-state rule-based demonstrator in MuJoCo, filtering out failed rollouts, and writing clean episodes into the LeRobotDataset v3.0 format.
Separating Privileged-State Control from Realistic Observation Logging
A scripted demonstrator works in simulation because of an intentional information asymmetry between the teacher script and the student policy. According to the MuJoCo C API Reference, forward dynamics updates mujoco.MjData at every step, exposing exact global Cartesian body positions in data.xpos () and unit orientation quaternions in data.xquat ().
The scripted controller reads these privileged ground-truth states to compute collision-free waypoints relative to the target object. By contrast, the recorded dataset must contain only signals available to a deployed physical robot: rendered camera images from mujoco.Renderer, joint proprioception from data.qpos, and the commanded actuator target data.ctrl.
| Signal Category | Used by Scripted Teacher | Logged to LeRobot v3.0 | MuJoCo API Source |
|---|---|---|---|
| Ground-truth object pose | Yes (waypoint generation) | Never | data.xpos, data.xquat |
| End-effector site position | Yes (IK error vector) | Optional (omit for visual policies) | data.site_xpos |
| Joint proprioception | Yes (current configuration) | Yes (observation.state) | data.qpos |
| Offscreen RGB camera frame | No | Yes (observation.images.*) | mujoco.Renderer.render() |
| Actuator control target | Output command | Yes (action) | data.ctrl |
Keeping compute_scripted_action(model, data) strictly isolated from extract_policy_observation(model, data, renderer) prevents accidental state leakage. If data.xpos slips into observation.state, validation loss inside simulation looks artificially low, yet the trained checkpoint cannot run on hardware that only provides RGB frames and joint encoder readings.
Implementing the Finite-State Machine and Jacobian IK Waypoint Controller
For rigid-body pick-and-place tasks, pairing a five-stage finite-state machine (FSM) with a damped least-squares (DLS) Jacobian inverse kinematics (IK) controller keeps the demonstrator concise and adaptable across randomized object poses.
- APPROACH: Open the gripper and drive the end-effector site to a pre-grasp waypoint above
obj_pos. - DESCEND: Once the Euclidean position error drops below , lower the end-effector vertically onto the grasp center.
- GRASP: Switch the gripper actuator command to its closed setpoint and hold position for a fixed settling window (for example, 12 control steps) so contact forces stabilize.
- LIFT: Keep the gripper closed and raise the object vertically to clear table obstacles.
- PLACE: Translate above the target zone, descend to release height, open the gripper, and retract upward.
In the MuJoCo Python Bindings and API Reference, mujoco.mj_jacSite(model, data, jacp, jacr, site_id) fills the translational Jacobian and rotational Jacobian for a given end-effector site_id. Given Cartesian error and damping factor , the DLS update avoids velocity blow-up near kinematic singularities:
The following function computes one bounded joint-position step for a 6-DOF arm controlling data.qpos[:6]:
import numpy as np
import mujoco
def dls_ik_step(
model: mujoco.MjModel,
data: mujoco.MjData,
site_id: int,
target_pos: np.ndarray,
arm_dof: int = 6,
damping: float = 0.05,
max_step: float = 0.04,
) -> np.ndarray:
"""Compute a damped least-squares joint position target toward target_pos."""
jacp = np.zeros((3, model.nv), dtype=np.float64)
jacr = np.zeros((3, model.nv), dtype=np.float64)
mujoco.mj_jacSite(model, data, jacp, jacr, site_id)
J = jacp[:, :arm_dof]
err = target_pos - data.site_xpos[site_id]
lam_sq = damping ** 2
dq = J.T @ np.linalg.solve(J @ J.T + lam_sq * np.eye(3), err)
dq = np.clip(dq, -max_step, max_step)
return data.qpos[:arm_dof] + dq
When full 6-DOF pose orientation must also be constrained, stack jacr beneath jacp with an axis-angle orientation error vector to form a system. Always decouple the simulation physics rate from the policy recording rate: a typical model.opt.timestep of 0.002 s (500 Hz) requires running multiple mujoco.mj_step(model, data) substeps per logged control frame.
Preventing Policy Overfitting with Initial Pose, Lighting, and Trajectory Perturbations
A deterministic scripted demonstrator running from identical initial conditions creates an overly narrow state distribution. Visuomotor policies trained on narrow trajectories suffer from covariate shift as soon as test-time pose or lighting shifts slightly. As demonstrated in MimicGen (arXiv:2310.17596), transforming reference demonstrations across randomized initial object poses and filtering successful executions dramatically broadens spatial generalization.
Introduce controlled variation using a seeded np.random.default_rng(seed) across three layers:
- Initial object pose randomization: Sample uniform offsets and -axis yaw rotations inside the object’s
freejointslice ofdata.qpos, then callmujoco.mj_forward(model, data)so kinematics and contacts update before rendering frame zero. - Visual and lighting jitter: Perturb
model.light_posand subtle tabletopmodel.geom_rgbatones at episode reset so the vision encoder relies on object geometry rather than fixed shadow silhouettes. - Smooth low-frequency trajectory offsets: Avoid adding independent white Gaussian noise to
actionat every timestep, which injects high-frequency tremor that corrupts action-chunking predictors. Instead, sample a single episode-level offset for the approach height or lateral arc curvature and interpolate it smoothly along the waypoint spline.
Automated Success Predicates and Filtered LeRobot v3.0 Dataset Recording
Even in rigid-body simulation, randomized object spawns occasionally trigger fingertip collisions or dropped grasps. Wiring a deterministic success predicate into the LeRobotDataset v3.0 write lifecycle (create → add_frame → save_episode or clear_episode_buffer → finalize) guarantees that only clean trajectories enter the final Parquet and MP4 shards.
Follow this six-step recording workflow:
- Initialize the dataset schema: Call
LeRobotDataset.create(...)with explicitrepo_id,fps,robot_type, andfeaturesmatching your robot’s joint order and camera resolution. - Allocate the offscreen renderer once: Instantiate
mujoco.Renderer(model, height=480, width=640)outside the episode loop (settingMUJOCO_GL=eglon headless Linux machines). - Reset, perturb, and forward kinematics: Call
mujoco.mj_resetData(model, data), apply your seeded pose and lighting perturbations, and invokemujoco.mj_forward(model, data). - Step control frames and buffer data: At each control tick, render RGB via
renderer.update_scene(data, camera="cam_front"), pass"observation.state","action","observation.images.front", and"task"todataset.add_frame(...), and advance physics by an integer number ofmj_stepsubsteps. - Filter with a success predicate: At episode termination, verify that the object rests within the target zone radius (
data.xpos[obj_id]) with near-zero residual velocity. Calldataset.save_episode()on pass, ordataset.clear_episode_buffer()on failure so rejected runs never increment episode indices. - Finalize metadata cleanly: Wrap the loop in a
try ... finallyblock that closes the renderer and invokesdataset.finalize()—a mandatory v3.0 call that flushes bufferedmeta/episodesmetadata and closes incremental Parquet footers.
import numpy as np
import mujoco
from lerobot.datasets.lerobot_dataset import LeRobotDataset
def is_episode_success(
data: mujoco.MjData, obj_body_id: int, goal_xy: np.ndarray, tol: float = 0.035
) -> bool:
pos = data.xpos[obj_body_id]
dist_xy = np.linalg.norm(pos[:2] - goal_xy)
return bool(dist_xy < tol and 0.01 < pos[2] < 0.08)
def collect_filtered_dataset(xml_path: str, repo_id: str, target_episodes: int = 50):
model = mujoco.MjModel.from_xml_path(xml_path)
data = mujoco.MjData(model)
renderer = mujoco.Renderer(model, height=480, width=640)
fps = 25
substeps = int(round((1.0 / fps) / model.opt.timestep)) # e.g., 0.002s -> 20 substeps
features = {
"observation.state": {"dtype": "float32", "shape": (7,), "names": [f"j{i}" for i in range(7)]},
"action": {"dtype": "float32", "shape": (7,), "names": [f"j{i}" for i in range(7)]},
"observation.images.front": {"dtype": "video", "shape": (480, 640, 3), "names": ["height", "width", "channels"]},
}
dataset = LeRobotDataset.create(
repo_id=repo_id, fps=fps, robot_type="sim_6dof_arm", features=features
)
saved, attempts = 0, 0
try:
while saved < target_episodes:
attempts += 1
mujoco.mj_resetData(model, data)
# Apply seeded object qpos, lighting, and FSM reset here
mujoco.mj_forward(model, data)
for _ in range(180): # up to 7.2 seconds at 25 fps
state = data.qpos[:7].astype(np.float32).copy()
# Compute 7-D target action from FSM + dls_ik_step
action = data.ctrl[:7].astype(np.float32).copy()
renderer.update_scene(data, camera="cam_front")
rgb = renderer.render() # uint8 (480, 640, 3)
dataset.add_frame({
"observation.state": state,
"action": action,
"observation.images.front": rgb,
"task": "pick the cube and place it in the target zone",
})
data.ctrl[:7] = action
for _ in range(substeps):
mujoco.mj_step(model, data)
obj_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, "cube")
if is_episode_success(data, obj_id, goal_xy=np.array([0.25, 0.15])):
dataset.save_episode()
saved += 1
else:
dataset.clear_episode_buffer()
finally:
renderer.close()
dataset.finalize()
Pay close attention to the ratio between fps and model.opt.timestep. With a default 0.002 s physics step (500 Hz), fps=25 divides cleanly into exactly 20 substeps (0.04 s per frame), whereas fps=30 yields 16.67 substeps and introduces rounding drift. If downstream policies require 30 Hz videos, adjust model.opt.timestep to 1.0 / 300.0 or 1.0 / 600.0 so each recorded frame spans an exact integer count of physics ticks.
Comparing MuJoCo Scripted Demonstrators Against Physical Leader-Follower Teleoperation
Scripted simulation datasets and physical teleoperation serve complementary roles inside a broader synthetic and real robotics data strategy. Comparing them across operational dimensions clarifies where each fits:
| Dimension | MuJoCo Scripted Demonstrator | Physical Leader-Follower Teleoperation |
|---|---|---|
| Collection throughput | Parallel workers generate hundreds to thousands of episodes unattended | Real-time single-operator speed; limited by human fatigue |
| Upfront hardware cost | Standard workstation only; no physical arm or leader rig needed | Leader-follower arms, power supply, calibrated mounts, physical props |
| Contact and deformable fidelity | Reliable for rigid-body geometry; limited for cables, cloth, or compliant assemblies | Captures true surface friction, gearbox backlash, lens distortion, and lighting |
| Initial-state coverage | Uniform programmatic sampling across the entire reachable workspace | Manual object resets often skew toward comfortable center positions |
| Failure-recovery behavior | Linear nominal trajectories unless explicit recovery branches are coded | Human operators naturally demonstrate micro-corrections and re-grasps |
| Strongest pipeline role | Debugging training loops, architecture ablations, spatial pretraining | Real-world fine-tuning, compliant contact skills, hardware deployment |
Using a MuJoCo scripted demonstrator first validates camera keys, joint ordering, normalization statistics, and policy convergence before hardware assembly is finished. Once the training pipeline is verified end-to-end, supplementing those synthetic episodes with targeted physical teleoperation captures the real-world contact nuances and recovery behaviors that rule-based scripts omit.