Simulator#

Simulator manages the physics engine and exposes a unified PyTorch tensor interface on CPU and GPU.

Physics backends#

reaf-sim supports two backends via Impl:

  • Impl.CPP: MuJoCo (CPU, nworld=1) for evaluation and debugging.

  • Impl.WARP: MuJoCo Warp (CPU and GPU) for batched simulation and RL training.

Usage#

Initialized with an MjSpec, Simulator compiles the model, allocates buffers, and can be stepped standalone without an Environment:

import mujoco
from reaf.simulation.torch import Impl, Simulator

spec = mujoco.MjSpec.from_string(...)
sim = Simulator(mj_spec=spec, nworld=16, xpu_device="cuda:0", impl=Impl.WARP)

sim.reset()      # Reset state (mj_resetData / mjw.reset_data)
sim.step()       # Advance 1 physics substep
sim.step_n(5)    # Advance 5 physics substeps
sim.forward()    # Recompute kinematics and dynamics without advancing time

State and model access#

sim.model and sim.data are wrapped in TorchWrapper, providing zero-copy PyTorch tensor views of MuJoCo buffers (sharing memory with wp.array for Impl.WARP and NumPy arrays for Impl.CPP) with a leading nworld dimension:

qpos = sim.data.qpos  # (nworld, nq)
sim.data.ctrl[:] = torch.randn_like(sim.data.ctrl)
sim.data.qvel[env_mask] = 0.0

Named MjSpec elements (bodies, joints, geoms, actuators, sensors, sites) can be accessed via bind or bind_pattern. Passing a single MjStruct omits the element axis ((nworld, ...)), whereas passing a sequence or calling bind_pattern always preserves it as dim 1 ((nworld, n_elements, ...), including (nworld, 1, ...) for single-element matches):

joint_data = sim.data.bind(sim.model, spec.joint("slider"))
joint_data.qpos  # (nworld,)
joint_data.set("qpos", torch.zeros(sim.nworld, device=sim.xpu_device))

geom_model = sim.model.bind(spec.geom("pole_1"))
geom_model.geom_size  # (nworld, 3)

geoms = sim.model.bind([spec.geom("pole_1")])
geoms.geom_size  # (nworld, 1, 3)

Simulation clock#

sim.clock (Clock) is the source of truth for simulation time. It maintains integer counters for per-world episode_step / episode_substep (exposed in seconds as episode_time without float32 accumulation drift) and monotonic global_step / global_substep (global_time). sim.set_episode_step syncs sim.data.time, and sim.clock.set_global_step restores the global step when resuming from a checkpoint.

Modifying model parameters#

When model fields (e.g., body_mass, geom_size, geom_friction) are modified in-place through sim.model, TorchWrapper automatically:

  • Lazily clones initial field values on first write so sim.model.restore_defaults(env_mask) can restore baseline values on reset without compounding changes across episodes.

  • Tracks the minimal required SetConstLevel (NONE, FIXED, KIN0, INERT0, FULL) flushed by sim.set_const() to recompute derived constants. Per-field levels can be overridden via set_const_level_override on Sim / Simulator (e.g. {"body_mass": SetConstLevel.FIXED}). Downgrading a level skips recomputing derived constants for the omitted stages on Warp (e.g. body_invweight0/dof_invweight0 remain stale); on Impl.CPP, any non-NONE level runs full mj_setConst.

sim.model.geom_size[env_mask] = new_sizes
sim.set_const()  # Called automatically during Environment startup and resets

Write tracking relies on TorchTensor __setitem__:

  • USE Tracked writes: sim.model.<field>[idx] = val or bound.set("<field>", val).

  • AVOID Untracked writes: Augmented assignments (sim.model.geom_size[idx] += delta), in-place Tensor methods (.copy_(), .add_(), out=...), or direct writes to _tensor, warp_model, or mj_model.

Graph capture#

With Impl.WARP, Simulator captures step(), forward(), reset(), and set_const() via wp.ScopedCapture and replays them with wp.capture_launch. Tensor attributes on sim.model and sim.data are read-only so device pointers remain fixed across graph replays.

For full signature details, see reaf.simulation.torch.Simulator in the API reference.