Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/source/en/user_guide/getting_started/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ When reinstalling, include any other options you still need in the same invocati
| `--rslrl` | Add the RSL-RL provider |
| `--skrl-jax` | Add the SKRL JAX runtime, Linux-only |
| `--skrl-torch` | Compatibility option; SKRL Torch is already a required repository dependency |
| `--sim-gpu` | Install the NVIDIA CUDA physics SDK (`motrixsim-gpu`). Use `sh install.sh --gpu cuda --sim-gpu` on a supported NVIDIA host. |
| `--docs` | Add documentation tools |
| `--all` | Full development environment, Python 3.10 only |
| `--help` | Show the full installer option reference |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ mxlab train task=cartpole/skrl.ppo task.train_backend=torch
mxlab train task=g1-wbt-dance/motrix.fastsac sim=motrixsim
```

Use `mxlab train task=cartpole/skrl.ppo sim_device=cuda:0` for GPU simulation. The default simulation device is CPU. The learner keeps its provider device setting. Playback uses the simulation device recorded at training time. Use `mxlab play env=cartpole sim_device=cpu` to override it, or `mxlab view env=cartpole sim_device=cuda:0` to inspect the GPU environment.

### Training Scale and Random Seed

```bash
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ sh install.sh --docs
| `--rslrl` | 添加 RSL-RL provider |
| `--skrl-jax` | 添加 SKRL JAX runtime,仅 Linux |
| `--skrl-torch` | 兼容性参数;SKRL Torch 已是仓库必需依赖 |
| `--sim-gpu` | 安装 NVIDIA CUDA 仿真 SDK(`motrixsim-gpu`)。在支持的 NVIDIA 主机上运行 `sh install.sh --gpu cuda --sim-gpu`。 |
| `--docs` | 添加文档工具链 |
| `--all` | 完整开发环境,仅 Python 3.10 |
| `--help` | 查看脚本的完整参数说明 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ mxlab train task=cartpole/skrl.ppo task.train_backend=torch
mxlab train task=g1-wbt-dance/motrix.fastsac sim=motrixsim
```

用 `mxlab train task=cartpole/skrl.ppo sim_device=cuda:0` 在 GPU 上仿真。仿真默认使用 CPU,learner 设备由 provider 配置决定。回放默认使用训练记录中的仿真设备,可用 `mxlab play env=cartpole sim_device=cpu` 覆盖。用 `mxlab view env=cartpole sim_device=cuda:0` 查看 GPU 环境。

### 训练规模与随机种子

```bash
Expand Down
11 changes: 11 additions & 0 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ usage() {
echo "Options:"
echo " --all Install the full development environment (all packages, groups and extras;"
echo " ROCm hosts skip CUDA-only extras such as skrl-jax)"
echo " --sim-gpu Install the NVIDIA MotrixSim GPU physics runtime"
echo " --docs Include the docs toolchain (sphinx) for building the documentation"
echo " --gpu cuda|rocm|hygon GPU profile (default: auto-detected from the kernel driver)"
echo " Hygon skips accelerator packages; install DTK-compatible Torch yourself."
Expand All @@ -37,6 +38,7 @@ PYTHON=""
SKRL_JAX=""
RSLRL=""
DOCS=""
SIM_GPU=""

while [ $# -gt 0 ]; do
case "$1" in
Expand All @@ -59,6 +61,9 @@ while [ $# -gt 0 ]; do
esac
shift
;;
--sim-gpu)
SIM_GPU=1
;;
--skrl-torch)
# SKRL Torch is already included in the required root dependencies.
;;
Expand Down Expand Up @@ -111,6 +116,11 @@ if [ -z "$GPU" ]; then
fi
fi

if [ -n "$SIM_GPU" ] && [ "$GPU" != cuda ]; then
echo "error: --sim-gpu requires the NVIDIA CUDA profile" >&2
exit 1
fi

if [ "$GPU" = hygon ] && [ -n "$SKRL_JAX" ]; then
echo "error: --skrl-jax installs a CUDA JAX runtime and is not supported with --gpu hygon" >&2
exit 1
Expand Down Expand Up @@ -247,6 +257,7 @@ elif [ -n "$ALL" ]; then
fi
else
EXTRAS=""
[ -n "$SIM_GPU" ] && EXTRAS="$EXTRAS --extra sim-gpu"
[ -n "$SKRL_JAX" ] && EXTRAS="$EXTRAS --extra skrl-jax"
[ -n "$RSLRL" ] && EXTRAS="$EXTRAS --extra rslrl"
[ -n "$DOCS" ] && EXTRAS="$EXTRAS --extra docs"
Expand Down
41 changes: 26 additions & 15 deletions motrix_env_core/src/motrix_env_core/array/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import abc
import dataclasses
from contextlib import nullcontext
from dataclasses import dataclass
from typing import Generic, TypeVar

Expand Down Expand Up @@ -152,11 +153,15 @@ class ArrayEnv(ABEnv, Generic[EnvCfgType]):
def __init__(self, cfg: EnvCfgType, num_envs: int = 1):
self._cfg = cfg
self._num_envs = num_envs
self.device = torch.device(cfg.sim.device)
if self.device.type == "cuda" and self.device.index is None:
self.device = torch.device("cuda", torch.cuda.current_device())
self._step_context = nullcontext
self.perf = Perf()
self.engine_error_codes = torch.zeros(num_envs, dtype=torch.int32)
self.engine_error_mask = torch.zeros(num_envs, dtype=torch.bool)
self._truncated = torch.zeros(num_envs, dtype=torch.bool)
self._episode_steps = torch.zeros(num_envs, dtype=torch.long)
self.engine_error_codes = torch.zeros(num_envs, dtype=torch.int32, device=self.device)
self.engine_error_mask = torch.zeros(num_envs, dtype=torch.bool, device=self.device)
self._truncated = torch.zeros(num_envs, dtype=torch.bool, device=self.device)
self._episode_steps = torch.zeros(num_envs, dtype=torch.long, device=self.device)
self._initialized = False
self._final_obs: FinalObs | None = None
self._metrics: dict[str, float | torch.Tensor] = {}
Expand Down Expand Up @@ -202,7 +207,7 @@ def initialize(self) -> "ArrayEnvState":
self._truncated.zero_()
self._episode_steps.zero_()
self._init_owned_state()
self.reset(torch.arange(self._num_envs))
self.reset(torch.arange(self._num_envs, device=self.device))
state = self.state
with self.perf.scope("observation"):
self.compute_observation(state)
Expand All @@ -220,7 +225,7 @@ def _init_owned_state(self) -> None:

def _zeros_box(self, space: gym.spaces.Box) -> torch.Tensor:
dtype = torch.from_numpy(np.empty((), dtype=space.dtype)).dtype
return torch.zeros((self._num_envs, *space.shape), dtype=dtype)
return torch.zeros((self._num_envs, *space.shape), dtype=dtype, device=self.device)

def _zeros_obs(self, spec: ObservationSpec) -> EnvObs:
return EnvObs({name: self._zeros_box(group.space) for name, group in spec.groups.items()})
Expand All @@ -247,8 +252,7 @@ def _reset_done_envs(self) -> None:

def _clear_engine_error_rewards(self) -> None:
"""Publish a finite failure reward, only from the done/reset slow path."""
if bool(self.engine_error_mask.any()):
self.state.reward.masked_fill_(self.engine_error_mask, 0.0)
self.state.reward.masked_fill_(self.engine_error_mask, 0.0)

@abc.abstractmethod
def reset(self, env_ids: torch.Tensor) -> None:
Expand All @@ -275,7 +279,7 @@ def _update_truncate(self) -> None:
"""Mark rows that reached the configured episode limit."""
max_episode_steps = self._max_episode_steps()
if max_episode_steps:
self._truncated[:] = self._episode_steps >= max_episode_steps
torch.ge(self._episode_steps, max_episode_steps, out=self._truncated)

@abc.abstractmethod
def create_renderer(self, config: RenderConfig) -> SimRenderer:
Expand Down Expand Up @@ -374,6 +378,10 @@ def step(self, actions: torch.Tensor) -> ArrayEnvState:
tensors (and copy dictionary contents) that must outlive the
borrowed-buffer lifetime; finish asynchronous copies before reuse.
"""
with self._step_context():
return self._step(actions)

def _step(self, actions: torch.Tensor) -> ArrayEnvState:
if not self.is_initialized:
with self.perf.scope("initialize"):
self.initialize()
Expand All @@ -394,12 +402,7 @@ def step(self, actions: torch.Tensor) -> ArrayEnvState:
state.terminated.logical_or_(self.engine_error_mask)
self._episode_steps += 1
self._update_truncate()
trunc_ids = torch.nonzero(self._truncated, as_tuple=False).flatten()
if trunc_ids.numel():
with self.perf.scope("final_obs"):
self._final_obs = self._capture_final_obs(trunc_ids)
with self.perf.scope("reset"):
self._reset_done_envs()
self._process_episode_boundaries()
with self.perf.scope("observation"):
self._pre_compute_observation()
# The hook may have selected another observation buffer; do not
Expand All @@ -410,5 +413,13 @@ def step(self, actions: torch.Tensor) -> ArrayEnvState:
# that the cached view still holds stale.
return self.state

def _process_episode_boundaries(self) -> None:
trunc_ids = torch.nonzero(self._truncated, as_tuple=False).flatten()
if trunc_ids.numel():
with self.perf.scope("final_obs"):
self._final_obs = self._capture_final_obs(trunc_ids)
with self.perf.scope("reset"):
self._reset_done_envs()


__all__ = ["ArrayEnv", "ArrayEnvState", "EnvCfgType", "EnvObs", "FinalObs"]
1 change: 1 addition & 0 deletions motrix_env_core/src/motrix_env_core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class EnvCfg:

scene: SceneCfg | None = None
sim: SimCfg = SimCfg()
backend: str | None = None
max_episode_seconds: float = None
ctrl_dt: float = 0.01
render_spacing: float = 1.0
Expand Down
17 changes: 17 additions & 0 deletions motrix_env_core/src/motrix_env_core/config/sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

from math import isfinite

import torch

from motrix_env_core.config.decorate import configclass


Expand All @@ -15,7 +17,18 @@ class SimCfg:
solver_tolerance: float | None = None
gravity: tuple[float, float, float] | None = None

device: str = "cpu"
# Per-world capacities for backends with fixed-size contact storage.
max_contacts: int | None = None
max_contact_constraints: int | None = None

def validate(self) -> None:
try:
device = torch.device(self.device)
except (TypeError, RuntimeError) as exc:
raise ValueError(f"Invalid sim.device {self.device!r}") from exc
if device.type not in ("cpu", "cuda"):
raise ValueError(f"sim.device must be CPU or CUDA, got {device}")
if isinstance(self.dt, bool) or not isfinite(self.dt) or self.dt <= 0.0:
raise ValueError(f"sim.dt must be positive and finite, got {self.dt}")
if self.solver_iterations is not None and (
Expand All @@ -26,5 +39,9 @@ def validate(self) -> None:
raise ValueError(f"sim.solver_iterations must be a positive integer, got {self.solver_iterations}")
if self.solver_tolerance is not None and (not isfinite(self.solver_tolerance) or self.solver_tolerance <= 0.0):
raise ValueError(f"sim.solver_tolerance must be positive and finite, got {self.solver_tolerance}")
for name in ("max_contacts", "max_contact_constraints"):
limit = getattr(self, name)
if limit is not None and (type(limit) is not int or limit <= 0):
raise ValueError(f"sim.{name} must be a positive integer, got {limit}")
if self.gravity is not None and len(self.gravity) != 3:
raise ValueError(f"sim.gravity must contain 3 values, got {self.gravity!r}")
40 changes: 34 additions & 6 deletions motrix_env_core/src/motrix_env_core/direct/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

import torch

from motrix_env_core.array.env import ArrayEnv, EnvObs
from motrix_env_core.array.env import ArrayEnv, EnvObs, FinalObs
from motrix_env_core.array.env import ArrayEnvState as ArrayEnvState
from motrix_env_core.base import EnvCfg
from motrix_env_core.config import configclass
Expand Down Expand Up @@ -51,21 +51,22 @@ def __init__(
headless: bool = False,
record: RecordConfig | None = None,
):
super().__init__(cfg, num_envs)
from motrix_env_core.sim.registry import create_sim_backend, default_sim_backend_name
from motrix_env_core.sim.registry import create_sim_backend

factory = create_sim_backend(backend or default_sim_backend_name())
factory = create_sim_backend(backend or cfg.backend, cfg.sim.device)
if not factory.capabilities.env_creation:
raise ValueError(
f"Backend {factory.name!r} cannot create a DirectEnv or ManagerEnv. "
f"{factory.capabilities.env_creation_unavailable_reason}"
)
super().__init__(cfg, num_envs)
# Construction compiles the scene inside the backend: no compiled
# artifact crosses the boundary.
render = RenderConfig(headless=headless, record=record)
self.sim: SimBackend = factory(cfg.scene, cfg.sim, num_envs, render=render)
self._reward = torch.zeros(num_envs)
self._terminated = torch.zeros(num_envs, dtype=torch.bool)
self._step_context = self.sim.step_context
self._reward = torch.zeros(num_envs, device=self.device)
self._terminated = torch.zeros(num_envs, dtype=torch.bool, device=self.device)
self._obs: EnvObs | None = None
self._reward_terms: dict[str, torch.Tensor] = {}

Expand Down Expand Up @@ -129,6 +130,33 @@ def create_renderer(self, config: RenderConfig) -> SimRenderer:
render_spacing=self.render_spacing,
)

def _process_episode_boundaries(self) -> None:
if self.device.type == "cuda" and not (self._terminated | self._truncated).any():
return
super()._process_episode_boundaries()

def _capture_final_obs(self, env_ids: torch.Tensor) -> FinalObs:
# Use the inactive buffer so the published starting observation stays intact.
obs = self._obs_buffers[1 - self._obs_index]
self._preview_observation(self.state.replace(obs=obs))
failed = self.engine_error_mask.index_select(0, env_ids)
return FinalObs(
env_ids,
EnvObs(
{
name: group.index_select(0, env_ids).masked_fill_(failed.view(-1, *([1] * (group.ndim - 1))), 0.0)
for name, group in obs.groups.items()
}
),
)

def _preview_observation(self, state: ArrayEnvState) -> None:
"""Write pre-reset observations without advancing any task-owned observation history.

Tasks with stateful observation updates override this hook.
"""
self.compute_observation(state)

def physics_step(self) -> None:
self.sim.step(self._cfg.sim_substeps, result=self.engine_error_codes)

Expand Down
34 changes: 28 additions & 6 deletions motrix_env_core/src/motrix_env_core/manager/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ def __init__(self, action_space: gym.spaces.Box, state: ActionState) -> None:
def process(self, actions: torch.Tensor) -> torch.Tensor | None:
"""Record raw tensor actions and process one batched action slice."""
state = self.state
ptr = (int(state.action_ptr[0]) + 1) % state.action_queue.shape[1]
state.action_ptr[0] = ptr
state.action_queue[:, ptr] = actions
ptr = state.action_ptr
ptr.add_(1).remainder_(state.action_queue.shape[1])
state.action_queue.index_copy_(1, ptr, actions.unsqueeze(1))
return self._process(actions)

@abc.abstractmethod
Expand All @@ -87,9 +87,18 @@ def _process(self, actions: torch.Tensor) -> torch.Tensor | None:

def reset(self, env_ids: torch.Tensor) -> None:
"""Clear raw history and reset action-specific state for selected rows."""
self.state.action_queue[env_ids] = 0.0
self.state.action_queue.index_fill_(0, env_ids.long(), 0)
self._reset(env_ids)

def reset_masked(self, world_mask: torch.Tensor) -> None:
"""Clear selected action histories and reset action-specific state."""
self.state.action_queue.masked_fill_(world_mask[:, None, None], 0)
self._reset_masked(world_mask)

def _reset_masked(self, world_mask: torch.Tensor) -> None:
"""Optional device-side counterpart of the action-specific reset."""
raise NotImplementedError

@abc.abstractmethod
def _reset(self, env_ids: torch.Tensor) -> None:
"""Reset action-specific state for selected environment rows."""
Expand Down Expand Up @@ -136,7 +145,7 @@ def __init__(
) -> None:
self.cfgs = cfgs
self.actuators = self._resolve_actuators(cfgs, actuators)
self.writes = sim.compile_writes(
self.writes = sim.compile_action_writes(
{name: CtrlTargetsWrite(cfg.actuator_names) for name, cfg in cfgs.items() if cfg.actuator_names != ()}
)
self.terms: dict[str, ActionTerm] = {}
Expand Down Expand Up @@ -219,10 +228,23 @@ def reset(self, env_ids: torch.Tensor) -> None:
for term in self.terms.values():
term.reset(env_ids)

@property
def supports_masked_reset(self) -> bool:
return all(type(term)._reset_masked is not ActionTerm._reset_masked for term in self.terms.values())

def reset_masked(self, world_mask: torch.Tensor) -> None:
for term in self.terms.values():
term.reset_masked(world_mask)

def clear_targets_masked(self, world_mask: torch.Tensor) -> None:
for name, actuators in self.actuators.items():
if actuators is not None:
self.writes.buffer(name).masked_fill_(world_mask[:, None], 0)

def clear_targets(self, env_ids: torch.Tensor) -> None:
for name, actuators in self.actuators.items():
if actuators is not None:
self.writes.buffer(name)[env_ids] = 0.0
self.writes.buffer(name).index_fill_(0, env_ids, 0.0)


__all__ = ["ActionManager"]
Loading