mjlab.envs#
Classes
ManagerBasedRlEnv#
- class mjlab.envs.ManagerBasedRlEnv[source]#
Bases:
objectManager-based RL environment.
- __init__(cfg: ManagerBasedRlEnvCfg, device: str, render_mode: str | None = None, **kwargs) None[source]#
- property unwrapped: ManagerBasedRlEnv#
Get the unwrapped environment (base case for wrapper chains).
- load_managers() None[source]#
Load and initialize all managers.
Order is important! Event and command managers must be loaded first, then action and observation managers, then other RL managers.
- step(action: Tensor) tuple[Dict[str, Tensor | Dict[str, Tensor]], Tensor, Tensor, Tensor, dict][source]#
Run one environment step: apply actions, simulate, compute RL signals.
When
auto_reset=True(default), environments that terminate or time out are reset in place and the returned observation is the post-reset state. Whenauto_reset=False, the reset is skipped and the returned observation is the terminal state; the caller must callreset(env_ids=...)for done envs before the nextstep().Forward-call placement. MuJoCo’s
mj_stepruns forward kinematics before integration, so after stepping, derived quantities (xpos,xquat,site_xpos,cvel,sensordata) lagqpos/qvelby one physics substep. Rather than callingsim.forward()twice (once after the decimation loop and once after the reset block), this method calls it once, right before observation computation. This single call refreshes derived quantities for all envs: non-reset envs pick up post-decimation kinematics, reset envs pick up post-reset kinematics.The tradeoff is that termination, reward, and step/interval event managers see derived quantities that are stale by one physics substep (the last
mj_stepranmj_forwardfrom pre-integrationqpos). In practice, the staleness is negligible for reward shaping, termination checks, and event perturbations. Critically, the staleness is consistent: every env, every step, always sees the same lag, so the MDP is well-defined and the value function can learn the correct mapping.Auto-reset parity. Auto-reset reproduces the explicit
reset()flow: events fire on the terminal state before the reset, and freshly reset envs advance commands withdt=0so their timers start full.Note
Events and reset-path resamples all run before
forward(), so state they write (e.g. a velocity push) is refreshed automatically and visible in this step’s observations. Command updates run after the call, so a command that writes sim state must refresh derived quantities itself (seeMotionCommand._update_command). In all cases, do not read derived quantities (root_link_pose_w,body_link_vel_w, etc.) in the same function that writes state (write_root_state_to_sim,write_joint_state_to_sim, etc.). See FAQ & Troubleshooting for details.
- class mjlab.envs.ManagerBasedRlEnvCfg[source]#
Configuration for a manager-based RL environment.
This config defines all aspects of an RL environment: the physical scene, observations, actions, rewards, terminations, and optional features like commands and curriculum learning.
The environment step size is
sim.mujoco.timestep * decimation. For example, with a 2ms physics timestep and decimation=10, the environment runs at 50Hz.- decimation: int#
Number of physics simulation steps per environment step. Higher values mean coarser control frequency. Environment step duration = physics_dt * decimation.
- scene: SceneCfg#
Scene configuration defining terrain, entities, and sensors. The scene specifies
num_envs, the number of parallel environments.
- observations: dict[str, ObservationGroupCfg]#
Observation groups configuration. Each group (e.g., “actor”, “critic”) contains observation terms that are concatenated. Groups can have different settings for noise, history, and delay.
- actions: dict[str, ActionTermCfg]#
Action terms configuration. Each term controls a specific entity/aspect (e.g., joint positions). Action dimensions are concatenated across terms.
- events: dict[str, EventTermCfg]#
Event terms for domain randomization and state resets. Default includes
reset_scene_to_defaultwhich resets entities to their initial state. Can be set to empty to disable all events including default reset.
- seed: int | None = None#
Random seed for reproducibility. If None, a random seed is used. The actual seed used is stored back into this field after initialization.
- sim: SimulationCfg#
Simulation configuration including physics timestep, solver iterations, contact parameters, and NaN guarding.
- viewer: ViewerConfig#
Viewer configuration for rendering (camera position, resolution, etc.).
- episode_length_s: float = 0.0#
Duration of an episode (in seconds).
- Episode length in steps is computed as:
ceil(episode_length_s / (sim.mujoco.timestep * decimation))
- rewards: dict[str, RewardTermCfg]#
Reward terms configuration.
- terminations: dict[str, TerminationTermCfg]#
Termination terms configuration. If empty, episodes never reset. Use
mdp.time_outwithtime_out=Truefor episode time limits.
- commands: dict[str, CommandTermCfg]#
Command generator terms (e.g., velocity targets).
- curriculum: dict[str, CurriculumTermCfg]#
Curriculum terms for adaptive difficulty.
- metrics: dict[str, MetricsTermCfg]#
Custom metric terms for logging per-step values as episode averages.
- recorders: dict[str, RecorderTermCfg]#
Recorder terms for logging observations, actions, or other data during rollouts. If empty, a no-op manager is used with zero overhead.
- is_finite_horizon: bool = False#
Whether the task has a finite or infinite horizon. Defaults to False (infinite).
Finite horizon (True): The time limit defines the task boundary. When reached, no future value exists beyond it, so the agent receives a terminal done signal.
Infinite horizon (False): The time limit is an artificial cutoff. The agent receives a truncated done signal to bootstrap the value of continuing beyond the limit.
- auto_reset: bool = True#
Whether to automatically reset environments that terminate or time out.
When True (default),
step()resets done environments and returns post-reset observations. When False,step()returns the true terminal observation and the caller must explicitly callreset(env_ids=...)for done environments before the nextstep().Note: mjlab’s bundled
train.pygoes through rsl_rl’sOnPolicyRunner, which does not drive manual resets.auto_reset=Falseis intended for users running their own training loop (or a wrapper that handles the reset between steps).
- scale_rewards_by_dt: bool = True#
Whether to multiply rewards by the environment step duration (dt).
When True (default), reward values are scaled by step_dt to normalize cumulative episodic rewards across different simulation frequencies. Set to False for algorithms that expect unscaled reward signals (e.g., HER, static reward scaling).
VecEnvObs#
- mjlab.envs.VecEnvObs(*args, **kwargs)#
The type of parameterized generics.
That is, for example, type(List[int]) is _GenericAlias.
Objects which are instances of this class include: * Parameterized container types, e.g. Tuple[int], List[int].
Note that native container types, e.g. tuple, list, use types.GenericAlias instead.
- Parameterized classes:
class C[T]: pass # C[int] is a _GenericAlias
Callable aliases, generic Callable aliases, and parameterized Callable aliases:
T = TypeVar(‘T’) # _CallableGenericAlias inherits from _GenericAlias. A = Callable[[], None] # _CallableGenericAlias B = Callable[[T], None] # _CallableGenericAlias C = B[int] # _CallableGenericAlias
- Parameterized Final, ClassVar, TypeForm, TypeGuard, and TypeIs:
# All _GenericAlias Final[int] ClassVar[float] TypeForm[bytearray] TypeGuard[bool] TypeIs[range]
Note that instances of this class are not classes (e.g by inspect.isclass), even though they behave like them.
VecEnvStepReturn#
- mjlab.envs.VecEnvStepReturn(*args, **kwargs)#
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.
If the argument is a tuple, the return value is the same object.
alias of
tuple[Dict[str,Tensor|Dict[str,Tensor]],Tensor,Tensor,Tensor,dict]