Simulator¶
The simulator modules ndm_gym.sim.rigid.isaaclab_mjwarp and hdmi_sim need Isaac Lab 3, Newton and MuJoCo-Warp,
muscle_sim Newton and MuJoCo-Warp, hand_sim, quadrotor_sim and quadruped_sim MuJoCo-Warp alone (Installation).
Without them, they and the commands that run them raise
SimulatorNotInstalled.
ndm_gym.sim
¶
Simulators: articulated rigid bodies (rigid).
The simulator stack (Isaac Lab 3 with Newton and MuJoCo-Warp, at the versions of Isaac Lab's lock) is installed by
scripts/setup.sh, not by a pip install of this repository. The modules that need it check for it on import
(require_simulator), as Isaac Lab's launcher does in the commands that run the simulator (launcher).
SimulatorNotInstalled
¶
Bases: ModuleNotFoundError
A simulator feature was used where the simulator is not installed.
require_simulator
¶
require_simulator(
feature: str, modules: tuple[str, ...] = SIMULATOR
) -> None
Raise :class:SimulatorNotInstalled for feature (a module or a command) unless all of modules are
installed. Looks the modules up without importing them.
ndm_gym.sim.launcher
¶
Isaac Lab's launcher (isaaclab.app) for the commands that run the simulator: training, evaluation, collection.
With Isaac Lab installed, add_launcher_args and launch_simulation are Isaac Lab's own. Without it the commands
still import, with their argument definitions (ndm_gym.wmbench.fit reads ndm_gym.train's), and both raise
:class:ndm_gym.sim.SimulatorNotInstalled, which says how to install the simulator.
RoboKit's simulator subclasses need RoboKit and MuJoCo Warp, imported when they are built (task).
ndm_gym.sim.robokit_ndm
¶
RoboKit's MuJoCo Warp simulator (robokit.sim.MjWarpSim) with a world model of the MuJoCo model (worldmodels.mjcf) in place
of its physics step, for RoboKit's SimMPC. ndm_sim() returns a subclass whose step() first runs the MuJoCo Warp stages
the task's costs read (derived: kinematics, sensors, collision, ...) on the current state, so that derived fields lag the
state by one step as MuJoCo's do, then advances qpos, qvel and time by the world model of the step's length. Everything else is
the parent's: entities, sensors, resets, scenes, torch views, resized (which keeps the subclass and its world models).
On a GPU the world model's step is one torch CUDA graph over the simulator's own arrays (zero-copy views). Inside an enclosing
capture (SimMPC's per-step graphs) the graph is added to it as a child graph node, so a planning step stays one CUDA graph;
outside one it is replayed on Warp's stream. A staged planner steps several lengths (SimMPC writes opt.timestep before each
step): there is one world model per length, and planning() tells each simulator the length SimMPC sets by intercepting that
write at run time. On the device, a guard flags any step whose timestep differs from the length the world model was chosen for.
A length with no world model is an error: raised at once when the step runs eagerly, flagged on the device when it runs inside
a captured graph; check() raises on either flag. SimMPC warms up every step length it may use (1, 2 and 4 timesteps) while
it builds its graphs, so during that build a step of a length with no world model only captures the flag. RoboKit's files stay
unmodified.
add_child_graph
¶
add_child_graph(stream: int, graph: int)
Add graph (a CUgraph, copied) to the graph being captured on stream (a CUstream handle) after the capture's current
dependencies, and let the capture continue after it: cuGraphAddChildGraphNode, as replaying a graph inside a capture is not
permitted.
ndm_sim
¶
ndm_sim()
The world-model subclass of robokit.sim.MjWarpSim: NdmSim(model, nworld, ..., ndm={step length in s: world model},
derived=("kinematics",)). The world models are MjcfWorldModels or their inference_copys on the simulator's device;
derived names MuJoCo Warp stages (mujoco_warp.kinematics, transmission, sensor_pos, collision, ...) run in
that order, or actuator_velocity: the actuators' velocities from qvel and the moments transmission set (MuJoCo Warp's
own kernel, the first part of fwd_velocity, without its passive forces and inverse dynamics), which actuator-velocity
sensors read.
planning
¶
planning()
While active, SimMPC's write of a step's timestep (its _set_value_kernel launch into a simulator's opt.timestep)
also sets that NdmSim's host-side step length, so that the step it captures or runs next uses the world model of that
length. warp.launch is wrapped for the duration (the module objects stay as they are).
load_models
¶
load_models(paths: dict, model, device, dtype=None) -> dict
{step length: inference copy} from fit_mjcf --save files ({step length: path}), each checked against its length.
ndm_gym.sim.robokit_rec
¶
Transitions recorded from RoboKit's MuJoCo Warp simulator (robokit.sim.MjWarpSim) as RoboKit runs it, for the world model
of MJCF models (worldmodels.mjcf). recording_sim() returns a subclass of RoboKit's simulator whose step() writes, for the
first record worlds, the state and the controls before the step, the step's length (substeps times the timestep the
caller set) and the state after it into a ring buffer on the device. Its kernels are plain launches, so inside an enclosing
CUDA graph capture (SimMPC's rollout graphs) they are recorded with the step's own kernels and run at every replay; the ring's
cursor lives on the device. resized() keeps the subclass, as SimMPC builds its rollout worlds with it. RoboKit's files stay
unmodified: a run swaps the simulator class at run time.
drain() takes the rows written since the last drain (an error if the ring went round, so no row is lost silently) and
recording() turns them into the recordings wmbench/fit_mjcf.py reads: one step length at a time, a reset wherever a
world's next row does not start from the state its previous row ended in (a new rollout).
recording_sim
¶
recording_sim()
The recording subclass of robokit.sim.MjWarpSim (RecordingSim(model, nworld, ..., record=8, capacity=4096)).
recording
¶
recording(
rows: dict, dt: float, tol: float = 1e-06
) -> dict
The rows of one step length dt (RecordingSim.drain's, concatenated) as a recording of wmbench/fit_mjcf.py:
qpos and qvel (T + 1, K, .), ctrl (T, K, nu), reset (T, K) where the next row does not start from this row's end state
(or the step length changes), and dt. Rows of other step lengths are left out; none of this length is an error.
mbrl-lib's environments for its controller on batched simulators need mbrl-lib (at 3f93ccc) with gymnasium 0.26,
imported when they are built (task).
ndm_gym.sim.mbrl_envs
¶
mbrl-lib's MuJoCo environments (facebookresearch/mbrl-lib at 3f93ccc, its code unmodified) as its true-dynamics controller
(mbrl/diagnostics/control_env.py) builds them, for planning on batched simulators: the models of benchmarks/mbrl_lib,
each environment's reward and termination as functions of batched states and actions (torch), and the run-time patches
that build the environments as the benchmark runs them, in this process and in control_env.py's pool workers:
- gymnasium 0.26.3's hopper.xml and walker2d.xml are in global coordinates, which MuJoCo >= 2.3.4 refuses; their
local-coordinate copies (
local_models, a directory withhopper_local.xmlandwalker2d_local.xml) load instead. tools/convert_mbrl_models.py makes them, into data/mbrl_models; a missing copy is an error that names that command; - a dm_control task steps PlaNet's action repeat (mbrl-lib's
planet_*.yamlframe_skip) per environment step, through the vendored dmc2gym'sframe_skip; - with
own_margins, the contact margins of the MuJoCo mbrl-lib's own environment runs (2.x: a contact's margin is the larger of its two geoms' margins; MuJoCo 4.0.1 adds them, so gymnasium's Hopper touches the ground 1 mm earlier): each geom's margin halved (set_own_margins). Off by default, which keeps the models as the installed MuJoCo reads them; - with
own_mujoco, the model as that MuJoCo (2.3.3) steps it (set_own_mujoco): these contact margins, its inverse weights of the bodies that move on slides only, whose joints' armature MuJoCo >= 3 leaves out (set_own_invweight), and its convex collision, libccd's with one contact per pair (set_own_ccd). The PETS pusher needs the three: its object is such a body, pushed by capsules against a cylinder. Off by default. Both options refuse a copy whose joint ranges are rounded (the copies of before that tool held six digits): its limits would not be that MuJoCo's.
A reward reads pre and post, what the environment's MuJoCo data holds before and after the step: qpos and qvel, and
the derived arrays (xpos, xmat, site_xpos, subtree_linvel, cfrc_ext) where a reward reads them. gymnasium's MuJoCo
environments do not recompute kinematics after mj_step, so their derived arrays are those of the step's last physics step, not
of qpos (the PETS pusher's reward reads them before its step). dm_control recomputes them after each of its control steps
(mj_step1), and one dmc2gym step sums the rewards of its repeat control steps. The world model gives the derived arrays of
its own states (Kinematics), steps dm_control's control step repeat times per environment step, and gives the pusher the
kinematics of the state before the step (a named difference, PUSHER); it gives no contact forces. What
each simulator refuses, with the reason: MbrlEnv.not_run (every simulator), ndm_refused, warp_refused.
patch_envs(counter_fix=True) also fixes, at run time, mbrl-lib's dm_control step counter: its handler's
set_env_state and FreezeDmcontrol restore _elapsed_steps on the outer gymnasium wrapper, not on gym's TimeLimit
inside dmc2gym, which therefore counts every rollout step of a pool worker and cuts all its rollouts to one step after
ceil(1000 / repeat) of them; the fix restores that TimeLimit's counter too.
MbrlEnv
dataclass
¶
MbrlEnv(
name: str,
env: str,
model: str,
episode: int,
reads: frozenset,
repeat: int = 1,
pets: tuple[int, int, int] | None = None,
override: str | None = None,
planar: bool = False,
not_run: str | None = None,
ndm_refused: str | None = None,
warp_refused: str | None = None,
named: str | None = None,
)
One environment: env is mbrl-lib's name for it (control_env.py's --env), episode its length in environment
steps (the PETS override's trial_length, gymnasium's time limit, dm_control's divided by the repeat), pets the PETS
override's (population, horizon, iterations), reads the fields its reward and termination read; not_run,
ndm_refused and warp_refused why it is not run at all, on the world model or on MuJoCo Warp; named the world
model's named difference in its reward.
settings
¶
settings() -> dict
The optimizer settings to plan with: control_env.py's defaults, the PETS override's, PlaNet's.
Fields
¶
Fields(**arrays)
Batched views (B, ...) of MuJoCo data arrays as torch tensors: qpos, qvel, and on request xpos, xmat (B, nbody, 3, 3),
xipos, site_xpos, subtree_linvel, cfrc_ext. get raises for an array its source does not give.
of_mjdata
staticmethod
¶
of_mjdata(
m,
d,
names=(
"qpos",
"qvel",
"xpos",
"xmat",
"xipos",
"site_xpos",
"subtree_linvel",
"cfrc_ext",
),
) -> Fields
A copy of one CPU MjData's arrays, as a batch of one (float64).
Kinematics
¶
Kinematics(m, device='cpu', dtype=torch.float32)
MuJoCo's forward kinematics of a tree of hinge and slide joints in torch, batched over qpos (..., nq): the bodies' positions and rotations (xpos, xmat (..., nbody, 3, 3)), their centres of mass (xipos) and the sites' positions (site_xpos) as mj_kinematics computes them, and with qvel each subtree's centre-of-mass velocity (subtree_linvel, as mj_subtreeVel): the derived arrays a reward reads, of the world model's states. Free and ball joints are refused.
Scorer
¶
Scorer(spec: MbrlEnv, m, substeps: int, device='cpu')
An environment's reward and termination of a batch of steps: reward(pre, post, ctrl, goal) and terminated(post)
for one environment step (gymnasium environments) or one control step (dm_control, whose environment step sums
repeat of them), ctrl (B, nu) the action as the environment received it. Model constants are read once from m
onto device; substeps: the physics steps of one control step (a gymnasium environment's frame skip, whose dt it is).
refusal
¶
refusal(spec: MbrlEnv, sim: str) -> str | None
Why spec is not run on sim (cpu, warp or ndm), or None.
contact_margin_rule
¶
contact_margin_rule() -> str
How the installed MuJoCo sets a contact's margin from its two geoms' margins: "max" (the larger, MuJoCo 2.x) or
"sum", read off a sphere on a plane whose margins are both 0.01.
set_own_margins
¶
set_own_margins(m)
The contact margins of mbrl-lib's own MuJoCo on the model m, in place: where the installed MuJoCo adds the two
geoms' margins, every geom's margin is halved, which gives each contact the larger of the two when all the model's geoms
share one margin (gymnasium's Hopper, Walker2d, Ant and Humanoid; a model without margins stays as it is). A model whose
geoms' margins differ is refused. Where the installed MuJoCo already takes the larger margin, nothing changes.
set_own_invweight
¶
set_own_invweight(m)
MuJoCo 2.3.3's body_invweight0 and dof_invweight0 on the model m, in place, for the bodies the installed
MuJoCo marks as moving on slides only (body_simple 2, MuJoCo >= 3). It gives them the inverse of the body's mass,
without the joints' armature; MuJoCo 2.3.3 computes the general values, the mean diagonal of J M^-1 J^T at qpos0 with the
armature in M, and so does this. The solver scales a constraint's regularization by these weights: the PETS pusher's
object (1.3e-8 kg on two slides with an armature of 0.04) got contacts 4.4e6 times softer. The other bodies' values are
the same in both versions and stay; a model without such a body stays as it is.
set_own_ccd
¶
set_own_ccd(m)
MuJoCo 2.3.3's convex collision on the model m, in place: libccd's penetration with one contact per pair and 50
iterations. MuJoCo 4.0.1 runs its native pipeline and returns several contacts for a pair unless both are disabled
(mjDSBL_NATIVECCD, mjDSBL_MULTICCD). It matters for the pairs without an analytic collision function (the PETS pusher's
capsules against its cylinder). MuJoCo Warp has its own pipeline and reads the second flag only. A MuJoCo without the
native pipeline (2.x) keeps its model; one with it and without the second flag is refused.
set_own_mujoco
¶
set_own_mujoco(m)
The model m as mbrl-lib's own MuJoCo (2.3.3) steps it, in place: its contact margins, its inverse weights of
slider bodies and its convex collision.
reads_global_coordinates
¶
reads_global_coordinates() -> bool
Whether the installed MuJoCo compiles a model in global coordinates (up to 2.3.3) or refuses it.
check_exact_ranges
¶
check_exact_ranges(m, original: str, copy: str)
Refuse the model m of a local-coordinate copy whose joint ranges are not the original file's: every joint
the original gives a range (in degrees for a hinge, as gymnasium's files do) must hold it within 1e-12. The copies made
before tools/convert_mbrl_models.py hold ranges rounded to six digits (1.6e-7 rad off at 45 degrees).
patch_envs
¶
patch_envs(
local_models: str | None,
counter_fix: bool = False,
own_margins: bool = False,
own_mujoco: bool = False,
)
Build the benchmark's environments from here on in this process: gymnasium's hopper.xml and walker2d.xml from the
local-coordinate copies in local_models (None: gymnasium's own, which MuJoCo >= 2.3.4 refuses), dm_control tasks at
PlaNet's action repeat; a copy that is missing is an error that names the command that makes it; with counter_fix,
mbrl-lib's dm_control step counter restored on gym's TimeLimit too; with
own_margins, the gymnasium MuJoCo environments' contact margins as mbrl-lib's own MuJoCo sets them, and with
own_mujoco their models as it steps them (the module's docstring; both refused for dm_control tasks). Idempotent;
unpatch_envs undoes it.
worker_init
¶
worker_init(
local_models,
counter_fix,
own_margins,
own_mujoco,
init,
initargs,
)
A pool worker's initializer: the patches, then control_env.py's own init.
make_env
¶
make_env(spec: MbrlEnv, seed: int)
(handler, env) as control_env.py builds its evaluation environment: mbrl-lib's handler for the name, global numpy seeded (the PETS environments reset from it), then reset with the seed. Call patch_envs first.
physics
¶
physics(spec: MbrlEnv, env)
(MjModel, MjData, physics steps per control step, control steps per environment step) of the environment's simulation.
control_step_seconds
¶
control_step_seconds(spec: MbrlEnv, env) -> float
The control step: the world model's step and the recordings' (dm_control: its own control step, inside the repeat).
state
¶
state(spec: MbrlEnv, handler, env) -> dict
What a batched rollout needs of the environment's current state: qpos, qvel, the environment steps left before its time limit truncates a rollout (gymnasium's TimeLimit counts as control_env.py's rollouts do), for dm_control the control steps left before its own time limit, and the reacher's goal (a hidden attribute the reward reads).
tolerance
¶
tolerance(
x,
lower=0.0,
upper=0.0,
margin=0.0,
sigmoid="gaussian",
value_at_margin=0.1,
)
dm_control's rewards.tolerance (dm_control/utils/rewards.py; Copyright 2017 The dm_control Authors, Apache License 2.0) for the sigmoids the benchmark's tasks use.
recording_dm_control
¶
recording_dm_control(
spec: MbrlEnv, env, out: list, names=None
)
While active, each dm_control control step inside the environment's steps appends (MjData fields after it, names
or all of Fields.of_mjdata's, ctrl, dm_control's reward) to out: the states one dmc2gym step passes through.
ndm_gym.sim.mbrl_ndm
¶
Batched rollouts of mbrl-lib's environments (sim.mbrl_envs) for its true-dynamics controller's optimizer, on MuJoCo Warp
or on the NDM (worldmodels.mjcf). values(state, actions) scores action sequences (B, H, A) from one start state as
control_env.py's pool scores them on CPU MuJoCo (mbrl.util.env.EnvHandler.rollout_env): each sequence's undiscounted sum of
the environment's rewards, up to and including the step at which it terminates or its time limit truncates the rollout.
MuJoCo Warp: B worlds of the environment's own MjModel. An environment step sets ctrl and runs its physics steps (the frame
skip; dm_control: n_sub_steps per control step and repeat control steps, each followed by the kinematics and the subtrees'
centres of mass and velocities, as dm_control's step leaves them), then rne_postconstraint where a reward reads the contact
forces, as gymnasium's step does. What a reward reads before a step is the data then: the derived arrays of the last physics
step, as gymnasium's environments hold them, and of the start state itself at the start, as mbrl-lib's set_state (mj_forward)
leaves them. The constraint solver's warm start is zeroed at each start. On a GPU each control step's physics is one captured
Warp graph and the rewards run on its stream; on Warp's CPU device everything runs eagerly.
The NDM: one world-model step per control step (dm_control: repeat of them per environment step, with the same action, the
rewards summed as dm_control sums them), on qpos and qvel; the derived arrays a reward reads are
the forward kinematics of the world model's states (mbrl_envs.Kinematics; the pusher's named difference). Environments
whose rewards read contact forces are refused (mbrl_envs.refusal). On a GPU each control step (world model, kinematics,
reward, termination, the running sums) is one torch CUDA graph on static buffers, with the world model, kinematics, reward and
termination compiled as one function (compile); on the CPU it runs eagerly (compile needs a GPU).
WarpRollouts
¶
WarpRollouts(
spec: MbrlEnv,
mjm,
substeps: int,
nworld: int,
device: str = "cuda:0",
)
values(state, actions) on nworld MuJoCo Warp worlds of mjm on Warp's device ("cpu" or "cuda:N").
values
¶
values(state: dict, actions: Tensor) -> torch.Tensor
(B,) float32 on the CPU: the returns of actions (B, H, A) from state (sim.mbrl_envs.state).
NdmRollouts
¶
NdmRollouts(
spec: MbrlEnv,
mjm,
substeps: int,
wm,
nworld: int,
compile: bool = False,
)
values(state, actions) with a world model (an MjcfWorldModel or its inference copy, on its device) in place of the
physics: one world-model step per control step, which must be the model's step.
load_ndm_copy
¶
load_ndm_copy(path: str, mjm, device, dtype=torch.bfloat16)
A fit_mjcf --save file's world model of mjm (its planar root, step and network), as an inference copy in dtype
(None: fp32) on device.