Skip to content

Building a Scripted Demonstrator in MuJoCo: Generating Filtered Robot Training Datasets in LeRobot v3 Format

Build a privileged-state scripted demonstrator in MuJoCo using Jacobian IK, filter failed rollouts, and save RGB-joint episodes into LeRobot v3.0.

Contents

Key takeaways

  1. A scripted demonstrator reads privileged ground-truth poses (data.xpos, data.xquat) to compute accurate actions, while the exported dataset logs only realistic observations (mujoco.Renderer RGB frames and data.qpos joint states) plus target commands (data.ctrl).
  2. Combining a five-stage finite-state machine (approach, descend, grasp, lift, place) with damped least-squares Jacobian inverse kinematics (mujoco.mj_jacSite) automates rigid-body manipulation data generation without human teleoperation.
  3. Applying reproducible perturbations to initial object poses, lighting, and smooth waypoint offsets prevents the trained visuomotor policy from memorizing a single deterministic trajectory.
  4. Automated success predicates commit valid episodes with dataset.save_episode(), discard dropped or stalled runs with dataset.clear_episode_buffer(), and flush LeRobot v3.0 Parquet metadata with dataset.finalize().

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 (nbody×3n_{\text{body}} \times 3) and unit orientation quaternions (w,x,y,z)(w, x, y, z) in data.xquat (nbody×4n_{\text{body}} \times 4).

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 CategoryUsed by Scripted TeacherLogged to LeRobot v3.0MuJoCo API Source
Ground-truth object poseYes (waypoint generation)Neverdata.xpos, data.xquat
End-effector site positionYes (IK error vector)Optional (omit for visual policies)data.site_xpos
Joint proprioceptionYes (current configuration)Yes (observation.state)data.qpos
Offscreen RGB camera frameNoYes (observation.images.*)mujoco.Renderer.render()
Actuator control targetOutput commandYes (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.

  1. APPROACH: Open the gripper and drive the end-effector site to a pre-grasp waypoint +0.10 m+0.10\text{ m} above obj_pos.
  2. DESCEND: Once the Euclidean position error drops below 0.01 m0.01\text{ m}, lower the end-effector vertically onto the grasp center.
  3. 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.
  4. LIFT: Keep the gripper closed and raise the object +0.12 m+0.12\text{ m} vertically to clear table obstacles.
  5. 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 Jp∈R3×nvJ_p \in \mathbb{R}^{3 \times n_v} and rotational Jacobian Jr∈R3×nvJ_r \in \mathbb{R}^{3 \times n_v} for a given end-effector site_id. Given Cartesian error e=ptarget−psitee = p_{\text{target}} - p_{\text{site}} and damping factor λ\lambda, the DLS update avoids velocity blow-up near kinematic singularities:

Δq=JpT(JpJpT+λ2I3)−1e\Delta q = J_p^T \left(J_p J_p^T + \lambda^2 I_3\right)^{-1} e

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 6×nv6 \times n_v 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 (x,y)(x, y) offsets and zz-axis yaw rotations inside the object’s freejoint slice of data.qpos, then call mujoco.mj_forward(model, data) so kinematics and contacts update before rendering frame zero.
  • Visual and lighting jitter: Perturb model.light_pos and subtle tabletop model.geom_rgba tones 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 action at 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:

  1. Initialize the dataset schema: Call LeRobotDataset.create(...) with explicit repo_id, fps, robot_type, and features matching your robot’s joint order and camera resolution.
  2. Allocate the offscreen renderer once: Instantiate mujoco.Renderer(model, height=480, width=640) outside the episode loop (setting MUJOCO_GL=egl on headless Linux machines).
  3. Reset, perturb, and forward kinematics: Call mujoco.mj_resetData(model, data), apply your seeded pose and lighting perturbations, and invoke mujoco.mj_forward(model, data).
  4. 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" to dataset.add_frame(...), and advance physics by an integer number of mj_step substeps.
  5. 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. Call dataset.save_episode() on pass, or dataset.clear_episode_buffer() on failure so rejected runs never increment episode indices.
  6. Finalize metadata cleanly: Wrap the loop in a try ... finally block that closes the renderer and invokes dataset.finalize()—a mandatory v3.0 call that flushes buffered meta/episodes metadata 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:

DimensionMuJoCo Scripted DemonstratorPhysical Leader-Follower Teleoperation
Collection throughputParallel workers generate hundreds to thousands of episodes unattendedReal-time single-operator speed; limited by human fatigue
Upfront hardware costStandard workstation only; no physical arm or leader rig neededLeader-follower arms, power supply, calibrated mounts, physical props
Contact and deformable fidelityReliable for rigid-body geometry; limited for cables, cloth, or compliant assembliesCaptures true surface friction, gearbox backlash, lens distortion, and lighting
Initial-state coverageUniform programmatic sampling across the entire reachable workspaceManual object resets often skew toward comfortable center positions
Failure-recovery behaviorLinear nominal trajectories unless explicit recovery branches are codedHuman operators naturally demonstrate micro-corrections and re-grasps
Strongest pipeline roleDebugging training loops, architecture ablations, spatial pretrainingReal-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.

Common mistakes

  • Leaking privileged object coordinates (data.xpos) into observation.state, which breaks deployment because the real robot only observes camera pixels and joint encoders.
  • Skipping clear_episode_buffer() after a failed rollout, causing leftover frames from the failed attempt to merge into the next episode.
  • Forgetting to call dataset.finalize() at the end of a LeRobot v3.0 recording script, leaving Parquet footers and meta/episodes indexes incomplete.
  • Recording every physics integration tick (for example 500 Hz) instead of stepping an integer number of physics substeps per control frame, creating timestamp drift against the declared fps.

Pre-flight checklist

  • MuJoCo 3.16.0 and LeRobot 0.6.1 are installed in a shared Python 3.12 virtual environment.
  • Privileged state access is isolated inside the scripted controller and excluded from dataset.add_frame().
  • The ratio between (1 / fps) and model.opt.timestep is an exact integer number of physics substeps.
  • Initial object poses, lighting parameters, and smooth waypoint offsets vary per episode using deterministic RNG seeds.
  • Only rollouts passing the automated success predicate call save_episode(), and dataset.finalize() runs in a finally block.

Frequently asked questions

Can a policy trained solely on MuJoCo scripted demonstrations deploy directly onto real hardware?
For simple rigid-body pick-and-place tasks, a scripted dataset is effective for validating training code, action normalization, and policy architectures. Direct zero-shot deployment typically still suffers from camera optics, control latency, and contact friction mismatches, so teams pair simulation pretraining with physical calibration and a small set of real teleoperated episodes.
Why use Jacobian inverse kinematics instead of interpolating fixed joint-space waypoints?
Fixed joint-space waypoints break as soon as you randomize the object’s starting position or orientation. Computing end-effector Jacobian updates with mj_jacSite lets the same five-stage state machine adapt cleanly to any reachable pose in the workspace.
Does a high rejection rate during automated filtering hurt dataset quality?
Calling clear_episode_buffer() keeps failed trajectories out of the saved shards, so individual saved episodes stay clean. However, if failures cluster near workspace edges or specific yaw angles, the dataset develops coverage holes—logging failure reasons by workspace coordinate helps you adjust object spawn bounds.

Sources & verification

  1. MuJoCo Documentation — Python Bindings
  2. MuJoCo Documentation — C API Reference (mj_step, mj_jacSite, mjData)
  3. Hugging Face LeRobot Docs — LeRobotDataset v3.0
  4. Mandlekar et al., MimicGen: A Data Generation System for Scalable Robot Learning using Human Demonstrations (arXiv:2310.17596)

Last verified: