MuJoCo

MuJoCo stands for Multi-Joint dynamics with Contact. It is a physics engine for facilitating research and development in robotics, biomechanics, graphics and animation, and other areas where fast and accurate simulation is needed. There is physical contact between the robots and their environment - and MuJoCo attempts at getting realistic physics simulations for the possible physical contact dynamics by aiming for physical accuracy and computational efficiency. MuJoCo was introduced by Todorov, Erez and Tassa in “MuJoCo: A physics engine for model-based control” (IROS 2012).

The unique dependencies including the MuJoCo simulator for this set of environments can be installed via:

pip install gymnasium[mujoco]

DeepMind acquired MuJoCo in October 2021 and open-sourced it in 2022, making it free for everyone. Using MuJoCo with Gymnasium requires the framework mujoco be installed (this dependency is installed with the above command). Instructions for installing the MuJoCo engine can be found on their website and GitHub repository.

From version 4.0, mujoco is split into three packages: mujoco-core, mujoco-studio and mujoco, which installs both. Upgrading an existing mujoco 3.x install with pip install -U mujoco can leave a broken install, where import mujoco fails because mujoco-core is missing or corrupted. To avoid this, uninstall the old package first:

pip uninstall -y mujoco && pip install "gymnasium[mujoco]"

To repair an install that is already broken, run pip install --force-reinstall --no-deps mujoco mujoco-core mujoco-studio.

MuJoCo v3 environments and older, which relied on the mujoco-py framework, were migrated to the gymnasium-robotics package starting with gymnasium v1.2. For information on using these older versions, please refer to the gymnasium-robotics documentation. The original mujoco-py framework can be found in its GitHub repository.

The dependencies for the old environment versions can be installed via:

pip install gymnasium_robotics[mujoco-py]

There are eleven MuJoCo environments (in roughly increasing complexity):

Robot

Short Description

CartPoles

InvertedPendulum

MuJoCo version of the CartPole Environment (with Continuous actions)

InvertedDoublePendulum

2 Pole variation of the CartPole Environment

Arms

Reacher

2d arm with the goal of reaching an object

Pusher

3d arm with the goal of pushing an object to a target location

2D Runners

HalfCheetah

2d quadruped with the goal of running

Hopper

2d monoped with the goal of hopping

Walker2d

2d biped with the goal of walking

Swimmers

Swimmer

2d robot with the goal of swimming

Quadruped

Ant

3d quadruped with the goal of running

Humanoid Bipeds

Humanoid

3d humanoid with the goal of running

HumanoidStandup

3d humanoid with the goal of standing up

All of these environments are stochastic in terms of their initial state, with uniform or Gaussian noise (depending on the environment) added to a fixed initial state in order to add stochasticity. The observation spaces of most MuJoCo environments in Gymnasium are built from the positions of the body parts and joints (mujoco.MjData.qpos) and their corresponding velocities (mujoco.MjData.qvel), flattened and concatenated together (more information in the MuJoCo Physics State Documentation). Some positions (such as the x-coordinate of the torso) are excluded by default, and several environments transform these values (e.g. Reacher and InvertedDoublePendulum use the sine and cosine of joint angles) or add other quantities such as body positions, inertias and contact forces; see the “Observation Space” section of each environment.

Among the Gymnasium environments, this set of environments can be considered as more difficult to solve by policy.

Environments can be configured by changing the xml_file argument and/or by tweaking the parameters of their classes.

Versions

Gymnasium includes the following versions of the environments:

Version

Simulator

Notes

v5

mujoco>=2.3.3

Recommended (most features, the least bugs)

v4

mujoco>=2.1.3

Maintained for reproducibility

v3

mujoco-py

Migrated to gymnasium-robotics (from gymnasium v1.2). Deprecated, Kept for reproducibility.

v2

mujoco-py

Migrated to gymnasium-robotics (from gymnasium v1.2). Deprecated, Kept for reproducibility.

For more information, see the section “Version History” for each environment.

v1 and older are no longer included in Gymnasium.

Comparing training performance across versions

The training performance of v2 and v3 is identical assuming the same/default arguments were used.

The training performance of v2/v3 and v4 are not directly comparable because of the change to the newer simulator, but the results for not Ant and not Humanoids are comparable (for more information see GitHub Comment #1 and GitHub Comment #2).

The Training performance of v4 and v5 is different because of the many changes in the environments, but the Half Cheetah and Swimmer exhibit identical behaviour, Pusher and Reacher are close (for more information see GitHub Issue).

Exact reproducibility

Note: The exact behavior of the MuJoCo simulator changes slightly between mujoco versions due to floating point operation ordering (more information of their Documentation), if exact reproducibility is needed besides using the seed for experiments the same simulator version should be used.

Changes in mujoco 4.0

mujoco 4.0 changes the simulation results of some environments, even though the environment versions are unchanged. With the same seed and actions, mujoco 3.3.7 and 4.0.1 give these results:

  • Ant, Humanoid and HumanoidStandup: observations differ from the first step. These environments combine the RK4 integrator with a free root joint, and mujoco 4.0 made RK4 more accurate for free and ball joint orientations. Humanoid and HumanoidStandup also use the PGS solver, which changed in mujoco 3.11 and 3.17. Training results for these environments are not directly comparable across mujoco versions, so report the mujoco version you used.

  • HalfCheetah and Hopper: rounding-level differences that grow over long episodes, as described in Numerical sensitivity of long-horizon trajectory comparisons.

  • The other environments: identical within about 1e-12.

For more information, see the MuJoCo changelog.

Numerical sensitivity of long-horizon trajectory comparisons

Some MuJoCo environments, notably InvertedDoublePendulum and other unstable-balance tasks, are chaotic: they exponentially amplify arbitrarily small numerical differences. Differences at the rounding level naturally arising from a different compute backend (CPU vs. MPS/CUDA), thread count, or mujoco version can therefore grow until two step-by-step trajectories look completely different, even though the simulator dynamics are identical. As an illustration, with the same seed and an identical deterministic action sequence, nudging the tip pole angle of InvertedDoublePendulum-v5 by 1e-9 after reset grows to a maximum absolute observation difference of ~7e-08 (roughly a 70-fold amplification) by the end of the 11-step episode — a rounding-level difference from a different backend will be amplified the same way.

import gymnasium as gym
import numpy as np

env = gym.make("InvertedDoublePendulum-v5")

def rollout(nudge):
    obs, _ = env.reset(seed=1000)
    env.action_space.seed(1000)  # both rollouts see the identical action sequence
    mujoco_env = env.unwrapped
    if nudge:  # perturb the simulator state, not just the returned observation
        qpos = mujoco_env.data.qpos.copy()
        qpos[2] += nudge  # the tip pole angle, an unstable direction
        mujoco_env.set_state(qpos, mujoco_env.data.qvel.copy())
    trajectory = []
    for _ in range(200):  # bounded horizon to keep the experiment cheap
        obs, _, terminated, truncated, _ = env.step(np.zeros(1, dtype=np.float32))
        trajectory.append(np.array(obs, dtype=float))
        if terminated or truncated:
            break
    return trajectory

a = rollout(0.0)
b = rollout(1e-9)
print(len(a), len(b), max(abs(x - y).max() for x, y in zip(a, b)))
# 11 11 6.8e-08

Practical advice:

  • Do not hand-pick a tolerance. Instead, measure how much the environment amplifies rounding noise on its own: run the same environment twice on the same machine from the same seed, nudge the initial state by the smallest float step, and record the step-by-step difference between the two trajectories. That divergence curve tells you the window and tolerance within which a cross-backend (CPU vs. MPS/CUDA) difference is indistinguishable from noise the system already has against itself.

  • Short horizons compare directly; long horizons do not. For regression or cross-version comparisons, first-step or short-horizon trajectory comparisons capture implementation differences before chaotic amplification dominates.

  • For long horizons, compare aggregate statistics such as seed-matched success rates or episode returns over many episodes. These are insensitive to the exact floating-point path taken within an episode.

Rendering Arguments

All of the MuJoCo Environments besides the general Gymnasium arguments, and environment specific arguments they also take the following arguments for configuring the renderer:

import gymnasium

env = gymnasium.make("Ant-v5", render_mode="rgb_array", width=1280, height=720)

Parameter

Type

Default

Description

render_mode

str

None

The modality of the render result. Must be one of human, rgb_array, depth_array, or rgbd_tuple. Note that human does not return a rendered image, but renders directly to the window

width

int

480

The width of the render window

height

int

480

The height of the render window

camera_id

int | None

None

The camera ID used for the render window

camera_name

str | None

None

The name of the camera used for the render window (mutually exclusive option with camera_id)

default_camera_config

dict[str, float | int] | None

None

The mjvCamera properties

max_geom

int

1000

Max number of geometrical objects to render (useful for 3rd-party environments)

visual_options

dict[int, bool] | None

None

A dictionary with mjVisual flags and value pairs, example {mujoco.mjtVisFlag.mjVIS_CONTACTPOINT: True, mujoco.mjtVisFlag.mjVIS_CONTACTFORCE: True} (show contact points and forces).

Rendering Backend

The MuJoCo simulator renders images with OpenGL and can use 3 different back ends “glfw” (default), “egl”, “osmesa”, which can be selected by setting an environment variable.

Backend

Environment Variable

Description

GLFW

MUJOCO_GL=glfw (default)

Renders with Window System on GPU

EGL

MUJOCO_GL=egl

Renders headless on GPU

OSMESA

MUJOCO_GL=osmesa

Renders headless on CPU

More information of the MuJoCo/OpenGL documentation.