diff --git a/docs/source/en/user_guide/getting_started/installation.md b/docs/source/en/user_guide/getting_started/installation.md index c75c45283..4a6280d0d 100644 --- a/docs/source/en/user_guide/getting_started/installation.md +++ b/docs/source/en/user_guide/getting_started/installation.md @@ -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 | diff --git a/docs/source/en/user_guide/tutorial/training/training_and_result.md b/docs/source/en/user_guide/tutorial/training/training_and_result.md index 1ca60b294..b1f419d75 100644 --- a/docs/source/en/user_guide/tutorial/training/training_and_result.md +++ b/docs/source/en/user_guide/tutorial/training/training_and_result.md @@ -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 diff --git a/docs/source/zh_CN/user_guide/getting_started/installation.md b/docs/source/zh_CN/user_guide/getting_started/installation.md index 2fced9c93..2c3df4679 100644 --- a/docs/source/zh_CN/user_guide/getting_started/installation.md +++ b/docs/source/zh_CN/user_guide/getting_started/installation.md @@ -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` | 查看脚本的完整参数说明 | diff --git a/docs/source/zh_CN/user_guide/tutorial/training/training_and_result.md b/docs/source/zh_CN/user_guide/tutorial/training/training_and_result.md index 26f55df72..1fec1ea1c 100644 --- a/docs/source/zh_CN/user_guide/tutorial/training/training_and_result.md +++ b/docs/source/zh_CN/user_guide/tutorial/training/training_and_result.md @@ -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 diff --git a/install.sh b/install.sh index eec82f770..966d08f09 100755 --- a/install.sh +++ b/install.sh @@ -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." @@ -37,6 +38,7 @@ PYTHON="" SKRL_JAX="" RSLRL="" DOCS="" +SIM_GPU="" while [ $# -gt 0 ]; do case "$1" in @@ -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. ;; @@ -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 @@ -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" diff --git a/motrix_env_core/src/motrix_env_core/array/env.py b/motrix_env_core/src/motrix_env_core/array/env.py index 87a90db88..412636545 100644 --- a/motrix_env_core/src/motrix_env_core/array/env.py +++ b/motrix_env_core/src/motrix_env_core/array/env.py @@ -3,6 +3,7 @@ import abc import dataclasses +from contextlib import nullcontext from dataclasses import dataclass from typing import Generic, TypeVar @@ -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] = {} @@ -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) @@ -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()}) @@ -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: @@ -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: @@ -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() @@ -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 @@ -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"] diff --git a/motrix_env_core/src/motrix_env_core/base.py b/motrix_env_core/src/motrix_env_core/base.py index 45205c272..39dc2b26b 100644 --- a/motrix_env_core/src/motrix_env_core/base.py +++ b/motrix_env_core/src/motrix_env_core/base.py @@ -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 diff --git a/motrix_env_core/src/motrix_env_core/config/sim.py b/motrix_env_core/src/motrix_env_core/config/sim.py index c1632cd5b..44194cb21 100644 --- a/motrix_env_core/src/motrix_env_core/config/sim.py +++ b/motrix_env_core/src/motrix_env_core/config/sim.py @@ -3,6 +3,8 @@ from math import isfinite +import torch + from motrix_env_core.config.decorate import configclass @@ -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 ( @@ -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}") diff --git a/motrix_env_core/src/motrix_env_core/direct/env.py b/motrix_env_core/src/motrix_env_core/direct/env.py index f6f5b2f5d..38da9c9a7 100644 --- a/motrix_env_core/src/motrix_env_core/direct/env.py +++ b/motrix_env_core/src/motrix_env_core/direct/env.py @@ -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 @@ -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] = {} @@ -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) diff --git a/motrix_env_core/src/motrix_env_core/manager/actions.py b/motrix_env_core/src/motrix_env_core/manager/actions.py index ca541daed..697ee6518 100644 --- a/motrix_env_core/src/motrix_env_core/manager/actions.py +++ b/motrix_env_core/src/motrix_env_core/manager/actions.py @@ -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 @@ -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.""" @@ -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] = {} @@ -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"] diff --git a/motrix_env_core/src/motrix_env_core/manager/commands.py b/motrix_env_core/src/motrix_env_core/manager/commands.py index 518ed2f0d..2835b8459 100644 --- a/motrix_env_core/src/motrix_env_core/manager/commands.py +++ b/motrix_env_core/src/motrix_env_core/manager/commands.py @@ -71,6 +71,14 @@ def reset(self, ctx: context.ManagerContext, env_ids: torch.Tensor, episode_rese episode_reset; simulator reset terms subsequently process all env_ids. """ + def reset_masked(self, ctx: context.ManagerContext, world_mask: torch.Tensor, episode_reset: torch.Tensor) -> None: + """Optional static reset. Both masks are aligned to the N environment rows. + + Implementations must leave every row outside world_mask unchanged. + Episode statistics may include only rows selected by episode_reset. + """ + raise NotImplementedError + @configclass(kw_only=True) class CommandCfg(abc.ABC): @@ -105,6 +113,8 @@ def __init__( cfgs: dict[str, CommandCfg], build_context: context.BuildContext, num_envs: int, + *, + device: torch.device, ) -> None: # Command factories must be independent: the context they receive # carries an empty commands mapping (and no actions) by contract. @@ -119,7 +129,11 @@ def __init__( ) self.terms[name] = term for metric_name, value in collect_metrics( - term, num_envs, context=f"Manager command {name!r}", context_path=("commands", name) + term, + num_envs, + context=f"Manager command {name!r}", + context_path=("commands", name), + device=device, ): if metric_name in self.metrics: raise ValueError(f"Duplicate per-environment metric name: {metric_name!r}") diff --git a/motrix_env_core/src/motrix_env_core/manager/env.py b/motrix_env_core/src/motrix_env_core/manager/env.py index 0e2f94ff2..577daa687 100644 --- a/motrix_env_core/src/motrix_env_core/manager/env.py +++ b/motrix_env_core/src/motrix_env_core/manager/env.py @@ -67,7 +67,7 @@ def _validate_reset_ids(env_ids: torch.Tensor, label: str) -> torch.Tensor: f"ManagerEnv.reset {label} must have an integer dtype, got {env_ids.dtype}; " "use torch.tensor([...], dtype=torch.long)." ) - return env_ids + return env_ids.long() def _merge_query_declarations( @@ -127,7 +127,6 @@ def _manager_group_to_dict( class ManagerBasedEnvCfg(EnvCfg): """Complete environment config with manager groups at the top level.""" - backend: str | None = None sim_reset: ManagerResetCfg = ManagerResetCfg() commands: dict[str, CommandCfg] = field(default_factory=dict) actions: dict[str, ActionCfg] = field(default_factory=dict) @@ -204,25 +203,31 @@ def __init__( """ if not isinstance(cfg, ManagerBasedEnvCfg): raise TypeError(f"{type(cfg).__name__} must inherit ManagerBasedEnvCfg.") - super().__init__(cfg, num_envs) self._build_seed = 1 if seed is None else seed from motrix_env_core.manager.random import RandomSource # Root Torch seeding belongs to the training entry point, not env construction. self._random = RandomSource() - 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 cfg.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._step_context = self.sim.step_context self.model = self.sim.compile_model(cfg.model_query_cfgs()) + # Term factories allocate their durable tensors during this scoped build. + with self.device: + self._build_terms(cfg) + + def _build_terms(self, cfg: ManagerBasedEnvCfg) -> None: # Full-width ctrl buffer in canonical actuator order, owned by the # compiled ctrl write program; routing happens here, the backend only # receives the merged targets. @@ -233,6 +238,14 @@ def __init__( self._initialize_manager_state() self._build_managers(cfg) self._compile_simulator_reads(cfg) + self._uses_episode_step_limit = type(self)._update_truncate is ArrayEnv._update_truncate + self._native_masked_reset = ( + self.sim.supports_native_masked_reset + and self._action_manager.supports_masked_reset + and all( + type(term).reset_masked is not CommandTerm.reset_masked for term in self._command_manager.terms.values() + ) + ) def _initialize_manager_state(self) -> None: self.metrics: dict[str, torch.Tensor] = {} @@ -257,6 +270,7 @@ def _build_managers(self, cfg: ManagerBasedEnvCfg) -> None: cfg.command_cfgs(), build_context=self.build_context(actions={}, commands={}), num_envs=self.num_envs, + device=self.device, ) self._register_metrics(self._command_manager.metrics) self._sim_reset_runtime = SimResetRuntime.create( @@ -348,6 +362,8 @@ def state(self) -> ArrayEnvState: ) def _init_owned_state(self) -> None: + self._truncation_limit = self._max_episode_steps() + self._steps_until_truncation = self._truncation_limit or 0 startup_started = perf_counter() env_name = type(self).__name__ if self._task_program is None: @@ -378,7 +394,11 @@ def _execute_evaluate_kernel(self) -> None: ) def _capture_final_obs(self, env_ids: torch.Tensor) -> FinalObs: - return self.observation_manager.preview(env_ids) + final = self.observation_manager.preview(env_ids) + failed = self.engine_error_mask.index_select(0, env_ids) + for group in final.obs.groups.values(): + group.masked_fill_(failed.view(-1, *([1] * (group.ndim - 1))), 0.0) + return final @property def action_cfgs(self) -> dict[str, ActionCfg]: @@ -466,6 +486,74 @@ def _reset_sim_rows(self, env_ids: torch.Tensor, episode_reset: torch.Tensor) -> with self.perf.scope("reset_read_inputs"): self.sim_data.execute(env_ids) + def _process_episode_boundaries(self) -> None: + native_reset = self._native_masked_reset and self._task_program.reset_masked_kernel is not None + if self.device.type != "cuda" and not native_reset: + super()._process_episode_boundaries() + return + + episode_reset = self.termination_manager.terminated | self._truncated + sim_reset = episode_reset | self._sim_reset_requested[:, 0] + if not native_reset: + if sim_reset.any(): + super()._process_episode_boundaries() + return + + stateless = self._sim_reset_runtime.supports_stateless_masked_reset + can_skip_gate = self.device.type == "cuda" and stateless and self._uses_episode_step_limit + reset_ids = None + truncation_due = False + if can_skip_gate: + # Episode resets can only decrease the maximum episode length. + # That makes the countdown a safe lower bound on the next truncation. + limit = self._max_episode_steps() + if limit != self._truncation_limit: + self._truncation_limit = limit + self._steps_until_truncation = 0 + if limit: + self._steps_until_truncation -= 1 + truncation_due = self._steps_until_truncation <= 0 + + if not can_skip_gate or truncation_due: + counts = torch.stack((sim_reset, self._truncated)).sum(dim=1) + if truncation_due: + longest_remaining = self._episode_steps.masked_fill(episode_reset, 0).amax() + reset_count, trunc_count, longest = torch.cat((counts, longest_remaining.view(1))).tolist() + self._steps_until_truncation = limit - longest + else: + reset_count, trunc_count = counts.tolist() + if not reset_count: + return + if trunc_count: + trunc_ids = torch.nonzero_static(self._truncated, size=trunc_count).flatten() + with self.perf.scope("final_obs"): + self._final_obs = self._capture_final_obs(trunc_ids) + if not stateless: + reset_ids = torch.nonzero_static(sim_reset, size=reset_count).flatten() + + with self.perf.scope("reset"): + self._reset_with_masks(sim_reset, episode_reset, reset_ids) + + def _clear_engine_error_rewards(self) -> None: + super()._clear_engine_error_rewards() + mask = self.engine_error_mask[:, None] + self._reward_manager.term_rewards.masked_fill_(mask, 0.0) + self._reward_manager.weighted_term_rewards.masked_fill_(mask, 0.0) + + def _reset_with_masks( + self, sim_reset: torch.Tensor, episode_reset: torch.Tensor, reset_ids: torch.Tensor | None + ) -> None: + self._clear_engine_error_rewards() + self._episode_steps.masked_fill_(episode_reset, 0) + self.observation_manager.reset_masked(episode_reset) + with self.perf.scope("action_reset"): + self._action_manager.reset_masked(episode_reset) + self._action_manager.clear_targets_masked(sim_reset) + with self.perf.scope("apply_sim_reset"): + self._sim_reset_runtime.apply_masked(self._task_program, sim_reset, episode_reset, reset_ids) + with self.perf.scope("reset_read_inputs"): + self.sim_data.execute_masked(sim_reset) + def _reset_done_envs(self) -> None: """Reset done lanes and requested sim-reset lanes in one pass. @@ -485,7 +573,7 @@ def _reset_done_envs(self) -> None: if env_ids.numel(): self._clear_engine_error_rewards() with self.perf.scope("select_done"): - self._episode_steps[env_ids] = 0 + self._episode_steps.index_fill_(0, env_ids, 0) with self.perf.scope("reset_envs"): self._reset_rows( env_ids, @@ -510,12 +598,16 @@ def reset(self, env_ids: torch.Tensor, sim_reset_ids: torch.Tensor | None = None appends its endpoint. Episode-reset lanes instead publish a first frame on the next compute call. """ - env_ids = _validate_reset_ids(env_ids, "env_ids") + device = self._episode_steps.device + env_ids = _validate_reset_ids(env_ids, "env_ids").to(device) if sim_reset_ids is not None: - sim_reset_ids = _validate_reset_ids(sim_reset_ids, "sim_reset_ids") + sim_reset_ids = _validate_reset_ids(sim_reset_ids, "sim_reset_ids").to(device) self._final_obs = None + if sim_reset_ids is not None and env_ids.numel(): + # Explicit callers can supply overlapping sets. Episode reset takes precedence. + sim_reset_ids = sim_reset_ids[~torch.isin(sim_reset_ids, env_ids)] self._reset_rows(env_ids, sim_reset_ids) - self._episode_steps[env_ids] = 0 + self._episode_steps.index_fill_(0, env_ids, 0) def _reset_rows(self, env_ids: torch.Tensor, sim_reset_ids: torch.Tensor | None = None) -> None: """Torch-control-plane reset shared by the public wrapper and the @@ -530,9 +622,6 @@ def _reset_rows(self, env_ids: torch.Tensor, sim_reset_ids: torch.Tensor | None # Context remains whole-batch and never carries reset-pass scratch. episode_reset = torch.ones_like(env_ids, dtype=torch.bool) if sim_reset_ids is not None and sim_reset_ids.numel(): - if env_ids.numel(): - # Episode reset wins when the public caller supplies overlapping sets. - sim_reset_ids = sim_reset_ids[~torch.isin(sim_reset_ids, env_ids)] episode_reset = torch.cat([episode_reset, torch.zeros_like(sim_reset_ids, dtype=torch.bool)]) env_ids = torch.cat([env_ids, sim_reset_ids]) if env_ids.numel(): @@ -542,7 +631,7 @@ def _make_metrics_view(self) -> dict[str, Any]: """Assemble the persistent live metrics view for the current state. Values are views into the kernel reward/termination buffers and the - term-owned CPU tensor arrays, so kernels write them in place every + term-owned tensors, so kernels write them in place every step and nothing needs rebuilding per transition. Host-side writers may add batch-level scalar entries (e.g. sampler statistics at reset time). Consumers retain values across steps through diff --git a/motrix_env_core/src/motrix_env_core/manager/metrics.py b/motrix_env_core/src/motrix_env_core/manager/metrics.py index 6b1e86348..091167e04 100644 --- a/motrix_env_core/src/motrix_env_core/manager/metrics.py +++ b/motrix_env_core/src/motrix_env_core/manager/metrics.py @@ -103,6 +103,7 @@ def collect_metrics( *, context: str, context_path: tuple[str, ...], + device: torch.device = torch.device("cpu"), ) -> tuple[tuple[str, torch.Tensor], ...]: """Collect metric fields from one canonical manager term, recursing into nested kernel-data members. @@ -124,14 +125,15 @@ def collect_metrics( num_envs, context=f"{context} field {data_field.name!r}", context_path=(*context_path, data_field.name), + device=device, ) ) continue tensor = child if not isinstance(tensor, torch.Tensor): raise TypeError(f"{context} metric field {data_field.name!r} must hold a torch.Tensor.") - if tensor.device.type != "cpu": - raise TypeError(f"{context} metric field {data_field.name!r} must be CPU-backed.") + if tensor.device != device: + raise TypeError(f"{context} metric field {data_field.name!r} must be on {device}.") if spec.scalar: if tensor.ndim != 0: raise ValueError( diff --git a/motrix_env_core/src/motrix_env_core/manager/observations.py b/motrix_env_core/src/motrix_env_core/manager/observations.py index 24fe92cc8..acc0f1181 100644 --- a/motrix_env_core/src/motrix_env_core/manager/observations.py +++ b/motrix_env_core/src/motrix_env_core/manager/observations.py @@ -242,7 +242,11 @@ def begin_step(self) -> EnvObs: def reset(self, env_ids: torch.Tensor) -> None: """Invalidate only episode-reset histories, not simulator-only resets.""" - self._history_reset[env_ids] = True + self._history_reset.index_fill_(0, env_ids.long(), True) + + def reset_masked(self, world_mask: torch.Tensor) -> None: + """Invalidate selected histories for the next observation publication.""" + self._history_reset.logical_or_(world_mask) def publish_reset(self, env_ids: torch.Tensor) -> None: """Repeat-fill explicit episode-reset lanes, leaving other rows untouched.""" @@ -259,7 +263,7 @@ def publish_reset(self, env_ids: torch.Tensor) -> None: initialized = repeat_observation(values, group.history_length) self._history[name][reset] = initialized destination[reset] = initialized.flatten(1) - self._history_reset[env_ids] = False + self._history_reset.index_fill_(0, env_ids.long(), False) def commit(self) -> None: """Publish exactly one control-step endpoint, repeat-filling new episodes.""" diff --git a/motrix_env_core/src/motrix_env_core/manager/resolver.py b/motrix_env_core/src/motrix_env_core/manager/resolver.py index 40b2d0dd8..61696083f 100644 --- a/motrix_env_core/src/motrix_env_core/manager/resolver.py +++ b/motrix_env_core/src/motrix_env_core/manager/resolver.py @@ -533,7 +533,7 @@ def _resolve_manager_context(self) -> ManagerContext: metrics = dict(self._env.metrics) commands = dict(self._env.command_terms) value = ManagerContext( - env_id=torch.arange(self._env.num_envs, dtype=torch.int64), + env_id=torch.arange(self._env.num_envs, dtype=torch.int64, device=self._env.device), actions=actions, commands=commands, metrics=metrics, diff --git a/motrix_env_core/src/motrix_env_core/manager/sim_reset.py b/motrix_env_core/src/motrix_env_core/manager/sim_reset.py index adf59eaa6..a7d066fa5 100644 --- a/motrix_env_core/src/motrix_env_core/manager/sim_reset.py +++ b/motrix_env_core/src/motrix_env_core/manager/sim_reset.py @@ -7,6 +7,7 @@ from collections.abc import Callable from dataclasses import dataclass +from functools import cached_property from typing import TYPE_CHECKING, Any import torch @@ -24,12 +25,22 @@ @dataclass(frozen=True, slots=True, init=False) class ResetTerm(BaseTerm): - """Immutable reset dispatch descriptor and its static positional arguments.""" + """Describe a simulator reset dispatch and its write outputs. + + With ``stateless=True``, dispatch may receive all world IDs and full-size + buffers even if few worlds reset. It may read the context and draw from + its RNG, and must write only to ``sim_writes``. Only selected rows are + committed. Other terms always receive compact IDs and outputs. + """ writes: dict[str, SimWrite] + stateless: bool - def __init__(self, dispatch: Callable[..., None], *args: Any, writes: dict[str, SimWrite]) -> None: + def __init__( + self, dispatch: Callable[..., None], *args: Any, writes: dict[str, SimWrite], stateless: bool = False + ) -> None: object.__setattr__(self, "writes", dict(writes)) + object.__setattr__(self, "stateless", stateless) BaseTerm.__init__(self, dispatch, *args) def __post_init__(self) -> None: @@ -47,6 +58,10 @@ class SimResetRuntime: writes: dict[str, dict[str, SimWrite]] buffers: tuple[torch.Tensor, ...] + @cached_property + def supports_stateless_masked_reset(self) -> bool: + return all(term.stateless for term in self.terms.values()) + @classmethod def create( cls, @@ -67,6 +82,7 @@ def create( created.dispatch, *canonicalize_term_args(created.args, context=f"Manager simulator reset term {name!r}"), writes=created.writes, + stateless=created.stateless, ) writes = {name: term.writes for name, term in terms.items()} for term_name, term_writes in writes.items(): @@ -98,14 +114,26 @@ def apply( env_ids: torch.Tensor, episode_reset: torch.Tensor, ) -> None: - """Materialize compact term outputs, scatter them, and execute reset.""" + """Apply compact term outputs to the selected simulator rows.""" with active_perf_scope("reset_kernel"): task_program.reset_kernel(env_ids, episode_reset, self.buffers) - for buffer in self.buffers: - compact = buffer[: env_ids.numel()].clone() - buffer[env_ids] = compact with active_perf_scope("backend_apply"): - self.program.execute(env_ids) + self.program.execute_compact(env_ids, self.buffers) + + def apply_masked( + self, + task_program: TorchTaskProgram, + world_mask: torch.Tensor, + episode_reset: torch.Tensor, + env_ids: torch.Tensor | None, + ) -> None: + with active_perf_scope("reset_kernel"): + task_program.reset_masked_kernel(world_mask, episode_reset, env_ids, self.buffers) + with active_perf_scope("backend_apply"): + if env_ids is None: + self.program.execute_masked(world_mask) + else: + self.program.execute_compact(env_ids, self.buffers) __all__ = ["ResetTerm", "SimResetRuntime"] diff --git a/motrix_env_core/src/motrix_env_core/mdp/action.py b/motrix_env_core/src/motrix_env_core/mdp/action.py index 913f95808..7e0696c9c 100644 --- a/motrix_env_core/src/motrix_env_core/mdp/action.py +++ b/motrix_env_core/src/motrix_env_core/mdp/action.py @@ -63,7 +63,7 @@ def __init__(self, space: gym.spaces.Box, state: JointPositionActionState) -> No super().__init__(space, state) # Seeded generator driving reset-time delay resampling; lives on the # term (not the kernel-data state) because it is host-only. - self.generator = torch.Generator() + self.generator = torch.Generator(device=state.action_queue.device) def _process(self, actions: torch.Tensor) -> torch.Tensor: """Map raw policy actions to targets using manager-owned action history. @@ -74,12 +74,11 @@ def _process(self, actions: torch.Tensor) -> torch.Tensor: ``motrix_env_core.torch_manager.actions.process_joint_position_actions``. """ state = self.state - ptr = int(state.action_ptr[0]) target_raw = actions if state.delay_hi > 0: queue = state.action_queue width = queue.shape[1] - delay_indices = (ptr - state.delay_steps) % width + delay_indices = (state.action_ptr - state.delay_steps) % width target_raw = torch.take_along_dim(queue, delay_indices[:, None, None], dim=1)[:, 0, :] return target_raw * state.action_scales + state.default_angles @@ -92,8 +91,21 @@ def _reset(self, env_ids: torch.Tensor) -> None: state.delay_hi + 1, (env_ids.numel(),), generator=self.generator, + device=state.delay_steps.device, ) + def _reset_masked(self, world_mask: torch.Tensor) -> None: + state = self.state + if state.delay_hi > 0: + delays = torch.randint( + state.delay_lo, + state.delay_hi + 1, + state.delay_steps.shape, + generator=self.generator, + device=state.delay_steps.device, + ) + state.delay_steps.copy_(torch.where(world_mask, delays, state.delay_steps)) + @configclass(kw_only=True) class JointPositionActionCfg(ActionCfg): @@ -166,7 +178,7 @@ def __call__(self, ctx: BuildContext, actuators: tuple[ActuatorSpec, ...] | None raise ValueError(f"position actuator {spec.name!r} must define or inherit ctrl_range") ctrl_ranges.append(spec.ctrl_range) space = joint_position_action_space_from_ctrl_ranges( - torch.tensor(ctrl_ranges, dtype=torch.float32), state.default_angles.cpu(), state.action_scales.cpu() + torch.tensor(ctrl_ranges, dtype=torch.float32), state.default_angles, state.action_scales ) term = JointPositionActionTerm(space, state) # Reset-time delay resampling is reproducible per environment seed. @@ -198,7 +210,7 @@ def _resolve_default_pose( @staticmethod def _read_position_actuator_kps(model: SimModel) -> torch.Tensor: - return torch.as_tensor(model.others["actuator_kp"]).detach().cpu() + return torch.as_tensor(model.others["actuator_kp"]).detach() @staticmethod def _read_position_actuator_effort_limits(model: SimModel) -> torch.Tensor: diff --git a/motrix_env_core/src/motrix_env_core/mdp/action_space.py b/motrix_env_core/src/motrix_env_core/mdp/action_space.py index 57d5e8c97..13cb60a7c 100644 --- a/motrix_env_core/src/motrix_env_core/mdp/action_space.py +++ b/motrix_env_core/src/motrix_env_core/mdp/action_space.py @@ -37,7 +37,7 @@ def symmetric_residual_action_space( scales = torch.as_tensor(action_scales, dtype=torch.float32) boundaries = torch.maximum(torch.abs(lower - default_values), torch.abs(upper - default_values)) / scales boundaries = torch.where(scales == 0.0, torch.zeros_like(boundaries), boundaries) - return gym.spaces.Box(-boundaries.numpy(), boundaries.numpy(), dtype=np.float32) + return gym.spaces.Box(-boundaries.cpu().numpy(), boundaries.cpu().numpy(), dtype=np.float32) def asymmetric_residual_action_space( @@ -66,8 +66,8 @@ def asymmetric_residual_action_space( high = (upper - default_values) / scales zero = torch.zeros_like(low) return gym.spaces.Box( - torch.where(scales == 0.0, zero, low).numpy(), - torch.where(scales == 0.0, zero, high).numpy(), + torch.where(scales == 0.0, zero, low).cpu().numpy(), + torch.where(scales == 0.0, zero, high).cpu().numpy(), dtype=np.float32, ) diff --git a/motrix_env_core/src/motrix_env_core/mdp/terrain.py b/motrix_env_core/src/motrix_env_core/mdp/terrain.py index fe8fbb048..593744980 100644 --- a/motrix_env_core/src/motrix_env_core/mdp/terrain.py +++ b/motrix_env_core/src/motrix_env_core/mdp/terrain.py @@ -50,7 +50,7 @@ def heightfield_lookup(grid: HeightFieldGrid, x: torch.Tensor, y: torch.Tensor) arrive as zero-copy tensor views of the shared grid arrays. """ if not grid.enabled: - return torch.full((x.shape[0],), float(grid.constant), dtype=torch.float64) + return torch.full_like(x, float(grid.constant), dtype=torch.float64) heights = grid.heights origin = grid.origin spacing = grid.spacing @@ -59,8 +59,10 @@ def heightfield_lookup(grid: HeightFieldGrid, x: torch.Tensor, y: torch.Tensor) # world coordinates, so the whole mapping stays in float64. fx = ((x - origin[0]) / spacing[0]).clamp(0.0, heights.shape[1] - 1.0 - 1e-6) fy = ((y - origin[1]) / spacing[1]).clamp(0.0, heights.shape[0] - 1.0 - 1e-6) - col = fx.to(torch.long) - row = fy.to(torch.long) + # Failed physics rows still pass through transition evaluation before reset. + # Keep their NaN interpolation weights, but never index the grid with NaN. + col = fx.to(torch.long).clamp(0, heights.shape[1] - 2) + row = fy.to(torch.long).clamp(0, heights.shape[0] - 2) tx = fx - col ty = fy - row h00 = heights[row, col] diff --git a/motrix_env_core/src/motrix_env_core/perf.py b/motrix_env_core/src/motrix_env_core/perf.py index 4f581ada4..6e94181b1 100644 --- a/motrix_env_core/src/motrix_env_core/perf.py +++ b/motrix_env_core/src/motrix_env_core/perf.py @@ -84,11 +84,12 @@ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: class Perf: """Opt-in hierarchical wall-clock profiler owned by one environment.""" - __slots__ = ("_clock", "_depth", "_enabled", "_frames", "_roots", "_scope_cache") + __slots__ = ("_clock", "_depth", "_enabled", "_frames", "_roots", "_scope_cache", "_synchronize") def __init__(self, *, enabled: bool = False, clock: _Clock = perf_counter_ns) -> None: self._enabled = enabled self._clock = clock + self._synchronize: Callable[[], object] | None = None self._roots: dict[str, _MutablePerfNode] = {} self._frames: list[_PerfFrame] = [] self._depth = 0 @@ -98,11 +99,14 @@ def __init__(self, *, enabled: bool = False, clock: _Clock = perf_counter_ns) -> def enabled(self) -> bool: return self._enabled - def enable(self) -> None: + def enable(self, *, synchronize: Callable[[], object] | None = None) -> None: + """Enable timing and optionally wait for device work at every scope boundary.""" self._set_enabled(True) + self._synchronize = synchronize def disable(self) -> None: self._set_enabled(False) + self._synchronize = None def _set_enabled(self, enabled: bool) -> None: if self._depth: @@ -127,6 +131,8 @@ def begin(self, name: str) -> None: if node is None: node = _MutablePerfNode(name) nodes[name] = node + if self._synchronize is not None: + self._synchronize() started_ns = self._clock() if depth == len(self._frames): self._frames.append(_PerfFrame(node=node, started_ns=started_ns)) @@ -147,6 +153,8 @@ def end(self, name: str | None = None) -> int: frame = self._frames[depth - 1] if name is not None and frame.node.name != name: raise RuntimeError(f"Perf scope mismatch: expected {frame.node.name!r}, got {name!r}.") + if self._synchronize is not None: + self._synchronize() elapsed_ns = self._clock() - frame.started_ns if elapsed_ns < 0: raise RuntimeError("Perf clock moved backwards.") diff --git a/motrix_env_core/src/motrix_env_core/registry.py b/motrix_env_core/src/motrix_env_core/registry.py index e5265f73e..45a3462b5 100644 --- a/motrix_env_core/src/motrix_env_core/registry.py +++ b/motrix_env_core/src/motrix_env_core/registry.py @@ -38,6 +38,7 @@ def make( num_envs: int = 1, mode: str = "train", seed: int | None = None, + sim_device: str | None = None, headless: bool = False, record: RecordConfig | None = None, ) -> ABEnv: @@ -45,6 +46,8 @@ def make( env_cfg = copy.deepcopy(self.env_cfg) if mode == "play": env_cfg = env_cfg.for_play() + if sim_device is not None: + env_cfg.sim.device = sim_device env_cfg.validate() return _construct_env(self.env_cls, env_cfg, num_envs, self.sim, seed, headless=headless, record=record) @@ -384,6 +387,8 @@ def resolve( name: str, env_cfg: EnvCfg | None = None, sim: str | None = None, + *, + sim_device: str | None = None, ) -> EnvBuildSpec: """Resolve a registered environment into spawn-safe construction metadata.""" @@ -395,6 +400,8 @@ def resolve( env_cfg = copy.deepcopy(env_cfg) env_cfg.validate() + if sim_device is not None: + env_cfg.sim.device = sim_device return EnvBuildSpec( env_cls=env_cls, env_cfg=env_cfg, @@ -410,6 +417,7 @@ def make( sim: str | None = None, seed: int | None = None, *, + sim_device: str | None = None, headless: bool = False, record: RecordConfig | None = None, ) -> ABEnv: @@ -425,6 +433,7 @@ def make( sim: Simulator name resolved through the SimBackend registry (:func:`motrix_env_core.sim.registry.create_sim_backend`) and injected into manager-based environments. + sim_device: Simulation device override, such as cpu or cuda:0. seed: Runtime seed applied to manager-based environment configs. headless: Disable window output independently of the rollout config. record: Optional image dimensions and recording settings. @@ -437,6 +446,9 @@ def make( env_cfg_override=env_cfg_override, mode=mode, ) + if sim_device is not None: + env_cfg.sim.device = sim_device + env_cfg.sim.validate() env_cls = _env_cls_or_raise(name, meta) return _construct_env(env_cls, env_cfg, num_envs, sim, seed, headless=headless, record=record) diff --git a/motrix_env_core/src/motrix_env_core/sim/backend.py b/motrix_env_core/src/motrix_env_core/sim/backend.py index 0bedd29e9..5b956e005 100644 --- a/motrix_env_core/src/motrix_env_core/sim/backend.py +++ b/motrix_env_core/src/motrix_env_core/sim/backend.py @@ -13,6 +13,7 @@ import abc from collections.abc import Mapping +from contextlib import nullcontext from dataclasses import dataclass from pathlib import Path from typing import ClassVar @@ -23,7 +24,7 @@ from motrix_env_core.config.scene import SceneCfg from motrix_env_core.sim.model import ModelQuery, SimModel, SimModelCompiler from motrix_env_core.sim.read import PhysicsReadProgram -from motrix_env_core.sim.write import SimWrite, SimWriteCompiler, WriteProgram +from motrix_env_core.sim.write import CtrlTargetsWrite, SimWrite, SimWriteCompiler, WriteProgram @dataclass(frozen=True) @@ -114,6 +115,10 @@ class SimBackend(abc.ABC): name: str capabilities: ClassVar[SimBackendCapabilities] = SimBackendCapabilities() + supports_native_masked_reset = False + + # Backends may order the complete control step on a device stream. + step_context = staticmethod(nullcontext) def __init__(self, scene: SceneCfg, sim: SimCfg, num_envs: int, *, render: RenderConfig | None = None) -> None: """Compile ``scene`` and allocate ``num_envs`` batched data rows. @@ -199,6 +204,10 @@ def compile_model(self, queries: Mapping[str, ModelQuery]) -> SimModel: """Lower the scene surface and model-query declarations into one model.""" return self.model_compiler.compile(self._scene, queries) + def reset_masked(self, world_mask: torch.Tensor) -> None: + """Restore selected worlds to defaults and refresh derived state.""" + self.compile_writes({}, reset=True).execute_masked(world_mask) + def compile_writes( self, writes: Mapping[str, SimWrite], @@ -215,6 +224,13 @@ def compile_writes( """ return self.write_compiler.compile(writes, reset=reset, forward_kinematics=forward_kinematics) + def compile_action_writes(self, writes: Mapping[str, CtrlTargetsWrite]) -> WriteProgram: + """Compile full-batch action writes. Buffers may alias live controls. + + Fill each buffer for all worlds and call ``execute()`` without row selection. + """ + return self.compile_writes(writes) + @property def write_compiler(self) -> SimWriteCompiler: """Return the compiler bound to this backend's model and live data. diff --git a/motrix_env_core/src/motrix_env_core/sim/body.py b/motrix_env_core/src/motrix_env_core/sim/body.py index 04c41126f..f5ff24cd2 100644 --- a/motrix_env_core/src/motrix_env_core/sim/body.py +++ b/motrix_env_core/src/motrix_env_core/sim/body.py @@ -91,6 +91,7 @@ def assemble_body_model( init_link_positions: np.ndarray, init_link_quats: np.ndarray, robot_cfg: RobotCfg | None = None, + device: torch.device = torch.device("cpu"), ) -> BodyModel: """Assemble a :class:`BodyModel` from backend-extracted engine facts. @@ -167,11 +168,13 @@ def assemble_body_model( base_link_name=base_link_name, link_names=tuple(link_names), joint_names=joint_names, - joint_pos_limits=None if limits is None else (torch.from_numpy(limits[0]), torch.from_numpy(limits[1])), + joint_pos_limits=None + if limits is None + else (torch.as_tensor(limits[0], device=device), torch.as_tensor(limits[1], device=device)), actuators=body_actuators, - init_base_position=torch.from_numpy(init_base_position), - init_base_quat=torch.from_numpy(init_base_quat), - init_joint_pos=torch.from_numpy(init_joint_pos), - init_link_positions=torch.from_numpy(positions), - init_link_quats=torch.from_numpy(quats), + init_base_position=torch.as_tensor(init_base_position, device=device), + init_base_quat=torch.as_tensor(init_base_quat, device=device), + init_joint_pos=torch.as_tensor(init_joint_pos, device=device), + init_link_positions=torch.as_tensor(positions, device=device), + init_link_quats=torch.as_tensor(quats, device=device), ) diff --git a/motrix_env_core/src/motrix_env_core/sim/model.py b/motrix_env_core/src/motrix_env_core/sim/model.py index b57026423..ae47cd346 100644 --- a/motrix_env_core/src/motrix_env_core/sim/model.py +++ b/motrix_env_core/src/motrix_env_core/sim/model.py @@ -182,7 +182,7 @@ class KinematicTreeQuery(ModelQuery): """ body: str - device: str = "cpu" + device: str | None = None def compile_with(self, compiler: SimModelCompiler, *, key: str) -> None: compiler.compile_kinematic_tree(key, self.body, self.device) @@ -294,17 +294,21 @@ class SimModelCompiler(abc.ABC): the compiler to their engine model at construction. """ - def compile(self, scene: SceneCfg, queries: Mapping[str, ModelQuery]) -> SimModel: + def compile( + self, scene: SceneCfg, queries: Mapping[str, ModelQuery], *, device: torch.device = torch.device("cpu") + ) -> SimModel: """Compile the scene surface and every named metadata query. Args: scene: The scene configuration the bound engine model was compiled from; it drives the unconditional model surface. queries: Model queries keyed by their logical result names. + device: Default device for model tensors. Returns: The backend-neutral simulator model and compiled metadata values. """ + self._device = device self._begin_compile() for key, query in queries.items(): query.compile_with(self, key=key) @@ -349,7 +353,7 @@ def compile_body_joint_position_limits(self, key: str, body: str) -> None: """ @abc.abstractmethod - def compile_kinematic_tree(self, key: str, body: str, device: str) -> None: + def compile_kinematic_tree(self, key: str, body: str, device: str | None) -> None: """Compile the differentiable kinematic tree of one body tree. Args: diff --git a/motrix_env_core/src/motrix_env_core/sim/read.py b/motrix_env_core/src/motrix_env_core/sim/read.py index da94397f3..19beea541 100644 --- a/motrix_env_core/src/motrix_env_core/sim/read.py +++ b/motrix_env_core/src/motrix_env_core/sim/read.py @@ -488,15 +488,15 @@ class PhysicsReadProgram(abc.ABC): Built once by :meth:`SimBackend.compile_reads` from the complete declared query set and executed many times. The program owns its physical memory planning: equal declared queries are collapsed onto shared storage - while every declared key stays servable, the authoritative arena is - private, ``execute`` is the only writer, and consumers read only through - the stable read-only logical views the program serves. + while every declared key stays servable through a stable read-only view. + Views may alias live simulator storage. Read them after ``execute`` for + current values and clone any values needed across simulator mutations. """ @property @abc.abstractmethod def arena_bytes(self) -> int: - """Size of the program's authoritative destination storage in bytes.""" + """Size of program-owned read storage in bytes.""" @property @abc.abstractmethod @@ -511,7 +511,7 @@ def query(self, key: str) -> SimDataQuery: def view(self, key: str) -> torch.Tensor: """Return the stable read-only logical view for one declared query key. - The view aliases the arena with the query's declared trailing shape and + The view has the query's declared trailing shape and leading batch dimension, is a float32 torch tensor, and stays valid for the program's lifetime. """ @@ -524,8 +524,14 @@ def __getitem__(self, key: str) -> torch.Tensor: @abc.abstractmethod def execute(self, env_ids: torch.Tensor | None = None) -> None: - """Refresh the authoritative arena — the full batch, or selected rows. + """Make current physics data available for the full batch or selected rows. ``env_ids`` is either ``None`` (full batch) or a one-dimensional integer row-index tensor. """ + + def execute_masked(self, world_mask: torch.Tensor) -> None: + """Refresh selected rows of a whole-batch boolean mask.""" + ids = world_mask.nonzero(as_tuple=True)[0] + if ids.numel(): + self.execute(ids) diff --git a/motrix_env_core/src/motrix_env_core/sim/registry.py b/motrix_env_core/src/motrix_env_core/sim/registry.py index fe7e58b34..98fee276b 100644 --- a/motrix_env_core/src/motrix_env_core/sim/registry.py +++ b/motrix_env_core/src/motrix_env_core/sim/registry.py @@ -14,9 +14,11 @@ from collections.abc import Callable from importlib.metadata import entry_points +import torch + from motrix_env_core.sim.backend import SimBackend -SimBackendFactory = Callable[[], SimBackend] +SimBackendFactory = Callable[[torch.device], type[SimBackend]] SIM_BACKEND_ENTRY_POINT_GROUP = "motrix_env.sim_backends" @@ -36,7 +38,7 @@ def register_sim_backend( Args: name: Simulator name, such as ``"motrixsim"``. - factory: Builds the backend carrying the simulator's capabilities. + factory: Resolves the concrete backend class for the requested device. default: Designates this simulator as the one used when none is configured explicitly. """ @@ -64,15 +66,10 @@ def default_sim_backend_name() -> str: return _default_sim_backend -def create_sim_backend(name: str) -> type[SimBackend]: - """Return the :class:`SimBackend` subclass registered for ``name``. - - Backends are constructed with ``(scene, sim, num_envs)`` — scene - compilation is the backend's internal affair — so the registry hands - out the class (or any ``(scene, sim, num_envs)`` factory), never an - instance. - """ - factory = _lookup(name)() +def create_sim_backend(name: str | None = None, device: torch.device | str = "cpu") -> type[SimBackend]: + """Resolve the backend class before compiling a scene or allocating frontend buffers.""" + name = name if name is not None else default_sim_backend_name() + factory = _lookup(name)(torch.device(device)) if not (isinstance(factory, type) and issubclass(factory, SimBackend)): raise TypeError(f"Sim backend factory for {name!r} returned {type(factory).__name__}") return factory diff --git a/motrix_env_core/src/motrix_env_core/sim/write.py b/motrix_env_core/src/motrix_env_core/sim/write.py index 6c43962f0..f9b8b928d 100644 --- a/motrix_env_core/src/motrix_env_core/sim/write.py +++ b/motrix_env_core/src/motrix_env_core/sim/write.py @@ -336,14 +336,15 @@ def compile_geom_friction(self, name: str, write: GeomFrictionWrite) -> None: class WriteProgram(abc.ABC): """Compiled set of writes executed together at one point in the loop. - Owns one value buffer per declared write; environments fill buffers + Ordinary programs expose staging buffers isolated from live simulator state. + Environments fill buffers (row-scoped ops read only the ``execute(env_ids)`` rows) and call :meth:`execute` to push everything to the backend in one crossing. """ @abc.abstractmethod def buffer(self, name: str) -> torch.Tensor: - """Return the program-owned buffer of one declaration.""" + """Return the writable buffer for one declaration.""" @abc.abstractmethod def execute(self, env_ids: torch.Tensor | None = None) -> None: @@ -352,3 +353,15 @@ def execute(self, env_ids: torch.Tensor | None = None) -> None: ``env_ids`` selects rows; ``None`` means every row. Reset-before-write and derived-state refresh behavior are fixed when the program is compiled. """ + + def execute_masked(self, world_mask: torch.Tensor) -> None: + """Apply full-batch buffers to the selected rows of a boolean mask.""" + ids = world_mask.nonzero(as_tuple=True)[0] + if ids.numel(): + self.execute(ids) + + def execute_compact(self, env_ids: torch.Tensor, buffers: tuple[torch.Tensor, ...]) -> None: + """Apply the first K buffer rows to the corresponding K world IDs.""" + for buffer in buffers: + buffer[env_ids] = buffer[: env_ids.numel()].clone() + self.execute(env_ids) diff --git a/motrix_env_core/src/motrix_env_core/torch_manager/runtime.py b/motrix_env_core/src/motrix_env_core/torch_manager/runtime.py index 433f56e33..b937139ce 100644 --- a/motrix_env_core/src/motrix_env_core/torch_manager/runtime.py +++ b/motrix_env_core/src/motrix_env_core/torch_manager/runtime.py @@ -32,6 +32,7 @@ from motrix_env_core.array.env import EnvObs from motrix_env_core.manager.kernel import EvaluationOutputs +from motrix_env_core.manager.kernel_data.data import iter_leaves from motrix_env_core.manager.resolver import ( CommandAdvanceHook, CommandResetHook, @@ -97,6 +98,9 @@ class TorchTaskProgram: observe_kernel: Callable[[EnvObs], None] reset_kernel: Callable[[torch.Tensor, torch.Tensor, tuple[torch.Tensor, ...]], None] reward_weights: torch.Tensor + reset_masked_kernel: ( + Callable[[torch.Tensor, torch.Tensor, torch.Tensor | None, tuple[torch.Tensor, ...]], None] | None + ) = None _K = TypeVar("_K") @@ -139,7 +143,17 @@ def __init__(self, env: ManagerEnv, program: ResolvedManagerProgram, compile: bo self.layout = program.layout self.compile_enabled = compile self.ctx = program.context - _apply_default_thread_cap(env.num_envs) + if self.ctx.env_id.is_cuda: + self._static_options = {"triton.cudagraphs": True} + if compile: + # Terms mutate the persistent command, action and metric buffers in + # place. Dynamo guards their addresses when recording a CUDA graph. + for _, _, tensor in iter_leaves(self.ctx): + if isinstance(tensor, torch.Tensor) and tensor.is_cuda: + torch._dynamo.mark_static_address(tensor) + else: + _apply_default_thread_cap(env.num_envs) + self._static_options = _compile_options() # Typed call sequences encode the execution contract structurally: # evaluate follows the fixed phase order command update hooks -> @@ -157,7 +171,9 @@ def __init__(self, env: ManagerEnv, program: ResolvedManagerProgram, compile: bo self.observations: dict[str, tuple[ObservationTermCall, ...]] = program.observations reward_cfgs = env.cfg.reward_cfgs() self.reward_weights = torch.tensor( - [float(reward_cfgs[term.name].weight) for term in self.layout.rewards], dtype=torch.float32 + [float(reward_cfgs[term.name].weight) for term in self.layout.rewards], + dtype=torch.float32, + device=self.ctx.env_id.device, ) # Reset-term compact-write layout mirrors SimResetRuntime.buffers: # one entry per declared write, ordered by term then output name. @@ -178,6 +194,7 @@ def task_program(self) -> TorchTaskProgram: observe_kernel=self.observe, reset_kernel=self.reset, reward_weights=self.reward_weights, + reset_masked_kernel=self.reset_masked, ) def evaluate( @@ -197,19 +214,64 @@ def observe(self, outputs: EnvObs) -> None: kernel(outputs) def reset( - self, env_ids: torch.Tensor, episode_reset: torch.Tensor, reset_buffers: tuple[torch.Tensor, ...] + self, + env_ids: torch.Tensor, + episode_reset: torch.Tensor, + reset_buffers: tuple[torch.Tensor, ...], + *, + reset_commands: bool = True, ) -> None: - if not self.command_reset_hooks and not self._reset_terms: + if not self._reset_terms and not (reset_commands and self.command_reset_hooks): return - # Normalize ids onto the kernel tensors' device (via the context - # anchor) so the cached static graph sees one form regardless of the - # caller's device, dtype, layout, or autograd history. + # Use a consistent ID tensor for the cached compact reset graph. ids = env_ids.detach().to(device=self.ctx.env_id.device, dtype=torch.int64).contiguous() kernel = self._compiled_kernels.get_or_build( - ("reset", id(reset_buffers)), lambda: self._build_compiled_reset(reset_buffers) + ("reset", id(reset_buffers), reset_commands), + lambda: self._build_compiled_reset(reset_buffers, reset_commands=reset_commands), ) kernel(ids, episode_reset) + def reset_masked( + self, + world_mask: torch.Tensor, + episode_reset: torch.Tensor, + env_ids: torch.Tensor | None, + reset_buffers: tuple[torch.Tensor, ...], + ) -> None: + # Compact terms keep their row contract when a program contains any + # stateful term. Mask-aware commands still run before those terms. + buffers = reset_buffers if env_ids is None else () + if self.command_reset_hooks or buffers: + kernel = self._compiled_kernels.get_or_build( + ("reset_masked", id(buffers)), lambda: self._build_masked_reset(buffers) + ) + kernel(world_mask, episode_reset) + if env_ids is not None and self._reset_terms: + self.reset(env_ids, episode_reset[env_ids], reset_buffers, reset_commands=False) + + def _build_masked_reset(self, reset_buffers: tuple[torch.Tensor, ...]) -> Callable: + ctx = self.ctx + receivers = tuple(ctx.commands[hook.receiver_key] for hook in self.command_reset_hooks) + writes = ( + tuple( + (call, {name: reset_buffers[offset + index] for index, name in enumerate(names)}) + for call, offset, names in self._reset_terms + ) + if reset_buffers + else () + ) + if self.compile_enabled and ctx.env_id.is_cuda: + for buffer in reset_buffers: + torch._dynamo.mark_static_address(buffer) + + def kernel(world_mask: torch.Tensor, episode_reset: torch.Tensor) -> None: + for receiver in receivers: + receiver.reset_masked(ctx, world_mask, episode_reset) + for call, sim_writes in writes: + call.invoke(ctx, ctx.env_id, sim_writes) + + return torch.compile(kernel, dynamic=False, options=self._static_options) if self.compile_enabled else kernel + def _build_compiled_evaluate( self, reward_weights: torch.Tensor, @@ -226,6 +288,10 @@ def _build_compiled_evaluate( reward_plan = self.rewards termination_plan = self.terminations + if self.compile_enabled and ctx.env_id.is_cuda: + for buffer in buffers: + torch._dynamo.mark_static_address(buffer) + def kernel(reward_view: torch.Tensor, terminated_view: torch.Tensor) -> None: for hook in update_hooks: receiver = ctx.commands[hook.receiver_key] @@ -251,7 +317,7 @@ def kernel(reward_view: torch.Tensor, terminated_view: torch.Tensor) -> None: hook.function(receiver, ctx) if self.compile_enabled: - return torch.compile(kernel, dynamic=False, options=_compile_options()) + return torch.compile(kernel, dynamic=False, options=self._static_options) return kernel def _build_compiled_observe(self) -> Callable[[EnvObs], None]: @@ -264,11 +330,21 @@ def _build_compiled_observe(self) -> Callable[[EnvObs], None]: num_envs = ctx.env_id.shape[0] term_bufs = { group_name: tuple( - torch.empty(num_envs, term.output_slice.stop - term.output_slice.start, dtype=torch.float32) + torch.empty( + num_envs, + term.output_slice.stop - term.output_slice.start, + dtype=torch.float32, + device=ctx.env_id.device, + ) for term in group.terms ) for group_name, group in self.layout.observations.items() } + if self.compile_enabled and ctx.env_id.is_cuda: + for group_buffers in term_bufs.values(): + for buffer in group_buffers: + torch._dynamo.mark_static_address(buffer) + per_term_plan = tuple( ( group_name, @@ -290,19 +366,22 @@ def group_kernel(target: torch.Tensor) -> None: target.copy_(torch.cat([buf for _call, buf in entries], dim=1)) if self.compile_enabled: - return torch.compile(group_kernel, dynamic=False, options=_compile_options()) + return torch.compile(group_kernel, dynamic=False, options=self._static_options) return group_kernel group_kernels = {group_name: make_group_kernel(entries) for group_name, entries in per_term_plan} def kernel(outputs: EnvObs) -> None: for name, group_kernel in group_kernels.items(): - group_kernel(outputs[name]) + target = outputs[name] + if self.compile_enabled and target.is_cuda: + torch._dynamo.mark_static_address(target) + group_kernel(target) return kernel def _build_compiled_reset( - self, reset_buffers: tuple[torch.Tensor, ...] + self, reset_buffers: tuple[torch.Tensor, ...], *, reset_commands: bool = True ) -> Callable[[torch.Tensor, torch.Tensor], None]: """Compile the reset schedule as a dynamic gather-compact graph. @@ -318,7 +397,7 @@ def _build_compiled_reset( Terms use default Torch random draws through ``ctx.rand`` inside the numerical graph. """ ctx = self.ctx - command_reset_hooks = self.command_reset_hooks + command_reset_hooks = self.command_reset_hooks if reset_commands else () write_plan = tuple( ( call, @@ -340,7 +419,7 @@ def kernel( call.invoke(ctx, env_ids, sim_writes) if self.compile_enabled: - kernel = torch.compile(kernel, dynamic=True, options=_compile_options()) + kernel = torch.compile(kernel, dynamic=True, options={} if ctx.env_id.is_cuda else _compile_options()) last_count: int | None = None writes_by_term: tuple[dict[str, torch.Tensor], ...] = () diff --git a/motrix_env_core/tests/test_direct_env_sim_backend.py b/motrix_env_core/tests/test_direct_env_sim_backend.py index 53da9fe7d..755f6bbbe 100644 --- a/motrix_env_core/tests/test_direct_env_sim_backend.py +++ b/motrix_env_core/tests/test_direct_env_sim_backend.py @@ -170,7 +170,7 @@ def write_compiler(self): return self._write_compiler -register_sim_backend("fake-direct", lambda: _FakeBackend) +register_sim_backend("fake-direct", lambda device: _FakeBackend) @configclass @@ -281,6 +281,27 @@ def test_direct_observations_survive_the_next_step() -> None: previous = current +def test_direct_truncation_captures_owned_pre_reset_observations() -> None: + env = _FakeDirectEnv(_FakeDirectCfg(max_episode_seconds=0.02), num_envs=2, backend="fake-direct") + start = env.initialize().obs.policy + start_snapshot = start.clone() + env.state.episode_steps[1] = env.cfg.max_episode_steps - 1 + + state = env.step(torch.full((2, 2), 0.5)) + + assert state.truncated.tolist() == [False, True] + final = state.final_obs + assert final is not None + assert final.env_ids.tolist() == [1] + torch.testing.assert_close(final.obs.policy, state.obs.policy[:1]) + torch.testing.assert_close(state.obs.policy[1], start_snapshot[1]) + torch.testing.assert_close(start, start_snapshot) + snapshot = final.obs.policy.clone() + env.step(torch.zeros((2, 2))) + env.step(torch.zeros((2, 2))) + torch.testing.assert_close(final.obs.policy, snapshot) + + def test_direct_env_compiles_empty_read_program() -> None: class EmptyReadEnv(_FakeDirectEnv): def __init__(self, cfg, num_envs, backend: str | None = None): @@ -381,3 +402,9 @@ def compute_transition(self, state: ArrayEnvState) -> None: assert restarted.metrics == {} assert restarted.reward_terms == {} torch.testing.assert_close(restarted.reward, torch.zeros(2)) + + +def test_direct_env_uses_configured_backend_with_explicit_override() -> None: + assert isinstance(_FakeDirectEnv(_FakeDirectCfg(backend="fake-direct"), 2).sim, _FakeBackend) + cfg = _FakeDirectCfg(backend="not-registered") + assert isinstance(_FakeDirectEnv(cfg, 2, backend="fake-direct").sim, _FakeBackend) diff --git a/motrix_env_core/tests/test_manager_sim_backend.py b/motrix_env_core/tests/test_manager_sim_backend.py index 52f586f0e..52e8cee7f 100644 --- a/motrix_env_core/tests/test_manager_sim_backend.py +++ b/motrix_env_core/tests/test_manager_sim_backend.py @@ -220,6 +220,9 @@ def _process(self, actions: torch.Tensor) -> torch.Tensor: def _reset(self, env_ids: np.ndarray) -> None: self.state.source[env_ids] = 0.0 + def _reset_masked(self, world_mask: torch.Tensor) -> None: + self.state.source.masked_fill_(world_mask[:, None], 0) + def _ctrl_action_space(ctx, actuator_indices) -> gym.spaces.Box: del ctx, actuator_indices @@ -298,7 +301,7 @@ class _FakeActionsCfg(ManagerActionsCfg): ctrl: _CtrlActionCfg = _CtrlActionCfg() -register_sim_backend("fake-manager", lambda: _FakeBackend) +register_sim_backend("fake-manager", lambda device: _FakeBackend) @configclass @@ -342,7 +345,11 @@ def test_manager_env_steps_on_fake_backend() -> None: @pytest.mark.parametrize("failed_reward", [1.0, float("nan"), float("inf")]) -def test_engine_error_terminates_and_resets_only_failed_rows(failed_reward: float, monkeypatch) -> None: +@pytest.mark.parametrize("native_masked_reset", [False, True]) +def test_engine_error_terminates_and_resets_only_failed_rows( + failed_reward: float, native_masked_reset: bool, monkeypatch +) -> None: + monkeypatch.setattr(_FakeBackend, "supports_native_masked_reset", native_masked_reset) env = _make_env() runtime = _FakeBackend.last env.initialize() @@ -384,6 +391,103 @@ def transition_with_failed_reward(state): assert not runtime.reset_calls +@pytest.mark.parametrize("mixed_terms", [False, True]) +def test_native_reset_term_row_contract(mixed_terms: bool, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(_FakeBackend, "supports_native_masked_reset", True) + monkeypatch.setattr(torch, "compile", lambda fn, **kwargs: fn) + + def reset_velocity(ctx: ManagerContext, env_ids: torch.Tensor, outputs: Mapping[str, torch.Tensor]) -> None: + outputs["joint_velocity"].fill_(env_ids.numel()) + + def reset_position(ctx: ManagerContext, env_ids: torch.Tensor, outputs: Mapping[str, torch.Tensor]) -> None: + ctx.actions["ctrl"].source[env_ids] += 10.0 + outputs["joint_position"].copy_(ctx.sim["dof_pos"][env_ids] + 1.0) + + @configclass + class VelocityResetCfg(ResetTermCfg): + def __call__(self, ctx: BuildContext) -> ResetTerm: + return ResetTerm(reset_velocity, writes={"joint_velocity": CtrlTargetsWrite()}, stateless=True) + + @configclass + class PositionResetCfg(ResetTermCfg): + def __call__(self, ctx: BuildContext) -> ResetTerm: + return ResetTerm(reset_position, writes={"joint_position": CtrlTargetsWrite()}) + + @configclass + class ResetsCfg(ManagerResetCfg): + velocity: VelocityResetCfg = VelocityResetCfg() + + @configclass + class MixedResetsCfg(ResetsCfg): + position: PositionResetCfg = PositionResetCfg() + + resets = MixedResetsCfg() if mixed_terms else ResetsCfg() + env = ManagerEnv(_FakeManagerCfg(sim_reset=resets), num_envs=3, backend="fake-manager") + env.initialize() + env.sim.reset_calls.clear() + env.step(torch.full((3, 1), 0.5)) + assert not env.sim.reset_calls + + env.sim.status_codes[1] = 1 + expected = env.sim.dof_pos + 0.25 * env.cfg.sim_substeps + untouched_velocities = env.sim.dof_vel[[0, 2]] + env.step(torch.full((3, 1), 0.5)) + + torch.testing.assert_close(env.sim.dof_vel[[0, 2]], untouched_velocities) + torch.testing.assert_close(env.sim.dof_vel[1], torch.full((2,), 1.0 if mixed_terms else 3.0)) + source = env.action_terms["ctrl"].state.source[:, 0] + torch.testing.assert_close(source, torch.tensor([0.5, 10.0 if mixed_terms else 0.0, 0.5])) + if mixed_terms: + expected[1] += 1.0 + else: + expected[1] = torch.tensor([0.5, -0.5]) + torch.testing.assert_close(env.sim.dof_pos, expected) + + +def test_stateless_cuda_reset_captures_staggered_timeouts(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(_FakeBackend, "supports_native_masked_reset", True) + monkeypatch.setattr(torch, "compile", lambda fn, **kwargs: fn) + env = _make_env() + env.cfg.max_episode_seconds = 3.1 * env.cfg.ctrl_dt + env.initialize() + # Exercise the host gate policy with otherwise ordinary CPU tensors. + monkeypatch.setattr(env, "device", torch.device("cuda:0")) + actions = torch.zeros((3, 1)) + + assert env.step(actions).final_obs is None + env.reset(torch.tensor([0])) + assert env.step(actions).final_obs is None + state = env.step(actions) + assert state.episode_steps.tolist() == [2, 0, 0] + final = state.final_obs + assert final is not None + assert final.env_ids.tolist() == [1, 2] + assert not torch.equal(final.obs.policy, state.obs.policy[final.env_ids]) + + state = env.step(actions) + assert state.episode_steps.tolist() == [0, 1, 1] + assert state.final_obs is not None + assert state.final_obs.env_ids.tolist() == [0] + + env.cfg.max_episode_seconds = 1.1 * env.cfg.ctrl_dt + state = env.step(actions) + assert state.final_obs is not None + assert state.final_obs.env_ids.tolist() == [0, 1, 2] + + +def test_cuda_fallback_skips_sparse_reset_when_no_rows_are_done(monkeypatch: pytest.MonkeyPatch) -> None: + env = _make_env() + env.initialize() + # Exercise only the CUDA branch selection using CPU tensors. + monkeypatch.setattr(env, "device", torch.device("cuda:0")) + + def unexpected_sparse_reset(): + pytest.fail("The idle CUDA fallback entered the sparse reset path") + + monkeypatch.setattr(env, "_reset_done_envs", unexpected_sparse_reset) + env._process_episode_boundaries() + + def test_public_reset_restarts_only_episode_lane_counters() -> None: env = _make_env() env.initialize() diff --git a/motrix_env_core/tests/test_registry.py b/motrix_env_core/tests/test_registry.py index 304734a11..8dd1ddca9 100644 --- a/motrix_env_core/tests/test_registry.py +++ b/motrix_env_core/tests/test_registry.py @@ -87,7 +87,7 @@ def compile_reads(self, queries) -> PhysicsReadProgram: return _EmptyReadProgram() -register_sim_backend("fake-registry", lambda: _FakeRegistryBackend) +register_sim_backend("fake-registry", lambda device: _FakeRegistryBackend) @pytest.fixture(autouse=True) @@ -260,7 +260,7 @@ def __init__(self, scene, sim, num_envs, *, render: RenderConfig): factory = RenderBackend - monkeypatch.setattr(sim_registry, "create_sim_backend", lambda name: factory) + monkeypatch.setattr(sim_registry, "create_sim_backend", lambda name, device: factory) env_type = DirectRenderEnv if workflow == "direct" else ManagerEnv with pytest.raises(BackendConstructionReached): env_type(cfg, backend="render-test", headless=headless, record=record) @@ -283,7 +283,7 @@ class CompileOnlyBackend(_FakeRegistryBackend): def __init__(self, scene: SceneCfg, sim, num_envs: int) -> None: pytest.fail("Compile-only backend must not be constructed by an environment") - monkeypatch.setitem(sim_registry._sim_backends, "compile-only", lambda: CompileOnlyBackend) + monkeypatch.setitem(sim_registry._sim_backends, "compile-only", lambda _device: CompileOnlyBackend) env_name = "core-test-compile-only-env" cfg_type = DirectEnvCfg if workflow == "direct" else ManagerBasedEnvCfg env_base = DirectEnv if workflow == "direct" else ManagerEnv diff --git a/motrix_env_core/tests/test_sim_cfg.py b/motrix_env_core/tests/test_sim_cfg.py index cce35ab91..e4d57e62e 100644 --- a/motrix_env_core/tests/test_sim_cfg.py +++ b/motrix_env_core/tests/test_sim_cfg.py @@ -61,3 +61,14 @@ def test_sim_cfg_supports_backend_defaults_and_explicit_physics(): def test_sim_cfg_retains_gravity_length_validation(): with pytest.raises(ValueError, match=r"sim\.gravity must contain 3 values"): SimCfg(gravity=(0.0, -9.81)).validate() + + +@pytest.mark.parametrize("device", ["cpu", "cuda", "cuda:2"]) +def test_sim_cfg_accepts_cpu_and_cuda_devices_without_allocating(device): + SimCfg(device=device).validate() + + +@pytest.mark.parametrize("device", ["", "invalid-device", "mps"]) +def test_sim_cfg_rejects_unsupported_devices(device): + with pytest.raises(ValueError, match="sim.device"): + SimCfg(device=device).validate() diff --git a/motrix_env_motrixsim/pyproject.toml b/motrix_env_motrixsim/pyproject.toml index ba6388737..df246b033 100644 --- a/motrix_env_motrixsim/pyproject.toml +++ b/motrix_env_motrixsim/pyproject.toml @@ -16,5 +16,8 @@ dependencies = [ "numpy>=1.26", ] +[project.optional-dependencies] +gpu = ["motrixsim-gpu===1.0.0; sys_platform == 'linux' or (sys_platform == 'win32' and platform_machine == 'AMD64')"] + [project.entry-points."motrix_env.sim_backends"] motrixsim = "motrix_env_motrixsim.register:register" diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/_gpu_primitives.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/_gpu_primitives.py new file mode 100644 index 000000000..1a5f01e4d --- /dev/null +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/_gpu_primitives.py @@ -0,0 +1,703 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Version-specific MotrixSim GPU 1.0.0 runtime primitives.""" + +from typing import Any + +import numpy as np +import torch +import warp as wp + + +@wp.struct +class ResetBuffer: + values: wp.array2d(dtype=wp.uint8) + fill: wp.uint8 + + +@wp.kernel +def reset_solver_rows( + mask: wp.array(dtype=wp.bool), + position: wp.array2d(dtype=wp.float32), + initial_position: wp.array(dtype=wp.float32), + velocity: wp.array2d(dtype=wp.float32), + control: wp.array2d(dtype=wp.float32), + buffers: wp.array(dtype=ResetBuffer), +): + world, lane = wp.tid() + if not mask[world]: + return + for column in range(lane, position.shape[1], 32): + position[world, column] = initial_position[column] + for column in range(lane, velocity.shape[1], 32): + velocity[world, column] = 0.0 + for column in range(lane, control.shape[1], 32): + control[world, column] = 0.0 + for i in range(buffers.shape[0]): + entry = buffers[i] + buf = entry.values + for column in range(lane, buf.shape[1], 32): + buf[world, column] = entry.fill + + +class GpuSolverResetter: + """Reset step inputs and both warm-start banks for the selected worlds.""" + + def __init__(self, model, data, device): + self._device = device + self._shape = (data.num_worlds, 32) + domains = data.low.domains + # The scene model supplies the defaults independently of live world 0. + self._initial_position = wp.array(model.compute_init_dof_pos(), dtype=wp.float32, device=device) + solver = domains["solver"] + normal = solver.persistent_normal_lambdas + collision = domains["rigid_collision"] + warm = solver.persistent_lambdas + zero_arrays = [ + normal.equality_mask, + normal.unilateral_mask, + collision.contact_count, + collision.overflow, + solver.constraint_lambdas.equality, + solver.constraint_lambdas.unilateral, + ] + if warm is not None: + zero_arrays.extend((warm.counts, warm.segment_counts, warm.row_counter)) + descriptors = [] + for array in zero_arrays: + if array.size: + descriptors.append(self._descriptor(array, data.num_worlds, 0)) + if warm is not None and warm.tags.size: + # SDK 1.0.0 initializes both int32 tag banks to -1 (invalid pair). + descriptors.append(self._descriptor(warm.tags, data.num_worlds, 0xFF)) + self._buffers = wp.array(descriptors, dtype=ResetBuffer, device=device) + self._position = data.dof_pos + self._velocity = data.dof_vel + self._control = data.actuator_ctrls + + def _descriptor(self, array, num_worlds: int, fill: int): + row_bytes = array.strides[0] + descriptor = ResetBuffer() + descriptor.values = wp.array(ptr=array.ptr, shape=(num_worlds, row_bytes), dtype=wp.uint8, device=self._device) + descriptor.fill = fill + return descriptor + + def execute(self, warp_mask) -> None: + wp.launch( + reset_solver_rows, + self._shape, + inputs=[ + warp_mask, + self._position, + self._initial_position, + self._velocity, + self._control, + self._buffers, + ], + device=self._device, + ) + + +class GpuStepStatus: + """Advance physics and publish per-world engine status codes.""" + + def __init__(self, backend): + self._backend = backend + self._overflow = wp.to_torch(backend.data.low.domains["rigid_collision"].overflow) + + def step(self, substeps: int, result: torch.Tensor | None) -> None: + backend = self._backend + for _ in range(substeps): + backend.model.step(backend.data, stream=backend._stream) + # Bound magnitudes well below float32 square-overflow as well as NaN/Inf. + good = (backend.position.abs() < 1e4).all(dim=1) & (backend.velocity.abs() < 1e4).all(dim=1) + failed = ~good | self._overflow.ne(0) + if result is not None: + result.copy_(failed) + elif failed.any(): + raise RuntimeError("MotrixSim CUDA encountered a non-finite state or contact overflow") + + +def joint_actuator_slots(model): + return model.low.actuator_model.joint_slot_by_ctrl_index + + +@wp.kernel +def recompute_link_rbi( + world_mask: wp.array(dtype=wp.bool), + model_rbi: wp.array2d(dtype=wp.float32), + high_offsets: wp.array(dtype=wp.int32), + high_indices: wp.array(dtype=wp.int32), + transforms_r: wp.array(dtype=wp.mat33f), + transforms_t: wp.array(dtype=wp.vec3f), + default_mass: wp.array(dtype=wp.float32), + default_h: wp.array(dtype=wp.vec3f), + default_shift: wp.array(dtype=wp.mat33f), + apparent_mass: wp.array2d(dtype=wp.float32), + apparent_com: wp.array3d(dtype=wp.float32), + link_rbi: wp.array3d(dtype=wp.float32), +): + world, low_link = wp.tid() + if not world_mask[world]: + return + start = high_offsets[low_link] + end = high_offsets[low_link + 1] + if start == end: + return + mass = model_rbi[low_link, 0] + h = wp.vec3(model_rbi[low_link, 1], model_rbi[low_link, 2], model_rbi[low_link, 3]) + inertia = wp.mat33( + model_rbi[low_link, 4], + model_rbi[low_link, 5], + model_rbi[low_link, 6], + model_rbi[low_link, 7], + model_rbi[low_link, 8], + model_rbi[low_link, 9], + model_rbi[low_link, 10], + model_rbi[low_link, 11], + model_rbi[low_link, 12], + ) + for k in range(start, end): + hi = high_indices[k] + m = apparent_mass[world, hi] + c_app = wp.vec3(apparent_com[world, hi, 0], apparent_com[world, hi, 1], apparent_com[world, hi, 2]) + c = transforms_r[k] * c_app + transforms_t[k] + mass = mass + (m - default_mass[k]) + h = h + (m * c - default_h[k]) + c_sq = wp.dot(c, c) + shift = m * (wp.mat33(c_sq, 0.0, 0.0, 0.0, c_sq, 0.0, 0.0, 0.0, c_sq) - wp.outer(c, c)) + inertia = inertia + (shift - default_shift[k]) + link_rbi[world, low_link, 0] = mass + link_rbi[world, low_link, 1] = h[0] + link_rbi[world, low_link, 2] = h[1] + link_rbi[world, low_link, 3] = h[2] + for row in range(3): + for col in range(3): + link_rbi[world, low_link, 4 + row * 3 + col] = inertia[row, col] + + +class GpuParameterOverrides: + """Device-resident link inertia and collider sliding-friction overrides.""" + + def __init__(self, backend): + self._backend = backend + self._device = backend._warp_device + self._overrides = backend.data.low.domains["overrides"] + self._num_worlds = backend.data.num_worlds + self._link_bound = False + self._friction_bound = False + + def bind_link_inertia(self) -> tuple[torch.Tensor, torch.Tensor]: + if not self._link_bound: + backend = self._backend + ov = self._overrides + model = backend.model + self._mass_table = wp.to_torch(ov.apparent_link_mass) + self._com_table = wp.to_torch(ov.apparent_link_com) + self._default_mass = torch.as_tensor(ov._default_apparent_link_mass, device=backend.device) + self._default_com = torch.as_tensor(ov._default_apparent_link_com, device=backend.device) + self._num_low_links = int(ov._model_link_rbi.shape[0]) + if self._num_low_links: + # RigidBodyInertia packs (mass: f32, h: vec3f, inertia: mat33f) = 13 float32s. + # Concrete float32 views avoid late dtype=Any template reloads after CUDAGraph capture. + self._model_rbi = wp.array( + ptr=ov._model_link_rbi.ptr, + shape=(self._num_low_links, 13), + dtype=wp.float32, + device=self._device, + ) + self._link_rbi = wp.array( + ptr=ov.link_rbi.ptr, + shape=(self._num_worlds, self._num_low_links, 13), + dtype=wp.float32, + device=self._device, + ) + groups: list[list[int]] = [[] for _ in range(self._num_low_links)] + for hi in range(len(model.links)): + low_idx = model._low_link_index_for_high_link(hi) + if low_idx is not None: + groups[low_idx].append(hi) + offsets = [0] + indices: list[int] = [] + rs, ts, dm, dh, ds = [], [], [], [], [] + for low_idx in range(self._num_low_links): + for hi in groups[low_idx]: + rot, pos = model._apparent_to_low_transform(hi) + rot64 = np.asarray(rot, dtype=np.float64) + t64 = -rot64 @ np.asarray(pos, dtype=np.float64) + m0 = float(ov._default_apparent_link_mass[hi]) + c0 = rot64 @ np.asarray(ov._default_apparent_link_com[hi], dtype=np.float64) + t64 + s0 = m0 * (np.dot(c0, c0) * np.eye(3) - np.outer(c0, c0)) + indices.append(hi) + rs.append(rot64.astype(np.float32)) + ts.append(t64.astype(np.float32)) + dm.append(np.float32(m0)) + dh.append((m0 * c0).astype(np.float32)) + ds.append(s0.astype(np.float32)) + offsets.append(len(indices)) + self._num_mapped_high = len(indices) + if self._num_mapped_high: + self._high_offsets = wp.array(offsets, dtype=wp.int32, device=self._device) + self._high_indices = wp.array(indices, dtype=wp.int32, device=self._device) + self._transforms_r = wp.array(rs, dtype=wp.mat33f, device=self._device) + self._transforms_t = wp.array(ts, dtype=wp.vec3f, device=self._device) + self._default_rbi_mass = wp.array(dm, dtype=wp.float32, device=self._device) + self._default_rbi_h = wp.array(dh, dtype=wp.vec3f, device=self._device) + self._default_rbi_shift = wp.array(ds, dtype=wp.mat33f, device=self._device) + self._link_bound = True + return self._mass_table, self._com_table + + def bind_geom_friction(self, geom_indices: list[int]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + backend = self._backend + if not self._friction_bound: + ov = self._overrides + self._collider_friction = wp.to_torch(ov.collider_friction) + self._default_sliding_friction = torch.as_tensor( + ov._default_collider_friction_values[:, 0], device=backend.device + ) + self._friction_bound = True + source_cols: list[int] = [] + collider_cols: list[int] = [] + low_model = backend.host_model.low + for column, geom_index in enumerate(geom_indices): + for collider in low_model.get_collider_indices(geom_index) or (): + source_cols.append(column) + collider_cols.append(int(collider)) + return ( + self._collider_friction, + torch.tensor(source_cols, dtype=torch.long, device=backend.device), + torch.tensor(collider_cols, dtype=torch.long, device=backend.device), + ) + + def restore_defaults(self, mask: torch.Tensor, warp_mask, *, recompute_inertia: bool) -> None: + if self._friction_bound: + sliding = self._collider_friction[..., 0] + sliding.copy_(torch.where(mask[:, None], self._default_sliding_friction, sliding)) + if self._link_bound: + self._mass_table.copy_(torch.where(mask[:, None], self._default_mass, self._mass_table)) + self._com_table.copy_(torch.where(mask[:, None, None], self._default_com, self._com_table)) + if recompute_inertia: + self.commit_link_inertia(warp_mask) + + def commit_link_inertia(self, warp_mask) -> None: + if not self._link_bound or self._num_low_links == 0 or self._num_mapped_high == 0: + return + wp.launch( + recompute_link_rbi, + (self._num_worlds, self._num_low_links), + inputs=[ + warp_mask, + self._model_rbi, + self._high_offsets, + self._high_indices, + self._transforms_r, + self._transforms_t, + self._default_rbi_mass, + self._default_rbi_h, + self._default_rbi_shift, + self._overrides.apparent_link_mass, + self._overrides.apparent_link_com, + self._link_rbi, + ], + device=self._device, + ) + if self._overrides.needs_link_spatial_inertia: + self._backend.model._materialize_link_spatial_inertia(self._backend.data) + + +@wp.kernel +def read_geom_contacts( + world_mask: wp.array(dtype=wp.bool), + contacts: wp.array2d(dtype=Any), + counts: wp.array(dtype=wp.int32), + limit: int, + collider_pairs: wp.array2d(dtype=wp.int32), + normal_report: bool, + result: wp.array2d(dtype=wp.float32), +): + world = wp.tid() + if not world_mask[world]: + return + found = wp.int32(0) + normal = wp.vec3() + for i in range(wp.min(counts[world], limit)): + pair = contacts[world, i].pair_index + for j in range(collider_pairs.shape[0]): + a = collider_pairs[j, 0] + b = collider_pairs[j, 1] + if (pair[0] == a and pair[1] == b) or (pair[0] == b and pair[1] == a): + if normal_report and found == 0: + normal = contacts[world, i].normal + if pair[0] != a: + normal = -normal + found += 1 + break + if normal_report: + for axis in range(3): + result[world, axis] = normal[axis] + else: + result[world, 0] = float(found) + + +@wp.kernel +def dense_contact_rows( + world_mask: wp.array(dtype=wp.bool), + contacts: wp.array2d(dtype=Any), + counts: wp.array(dtype=wp.int32), + slots: wp.array2d(dtype=wp.int32), + records: wp.array2d(dtype=Any), + record_counts: wp.array(dtype=wp.int32), + rows: wp.array3d(dtype=wp.int32), +): + world, i = wp.tid() + if not world_mask[world]: + return + if i >= counts[world]: + return + contact = contacts[world, i] + for axis in range(6): + rows[world, i, axis] = -1 + slot = slots[world, i] + for j in range(wp.min(record_counts[world], records.shape[1])): + r = records[world, j] + if int(r.pos) == slot + 1 and r.feature_id == contact.feature_id and int(r.midx) == contact.index_in_manifold: + rows[world, i, int(r.axis)] = int(r.lineno) + + +@wp.kernel +def link_contact_wrenches( + world_mask: wp.array(dtype=wp.bool), + contacts: wp.array2d(dtype=Any), + counts: wp.array(dtype=wp.int32), + rows: wp.array3d(dtype=wp.int32), + impulses: wp.array2d(dtype=wp.float32), + poses: wp.array3d(dtype=wp.float32), + local_com: wp.array3d(dtype=wp.float32), + high_links: wp.array(dtype=wp.int32), + low_links: wp.array(dtype=wp.int32), + inv_dt: float, + output: wp.array3d(dtype=wp.float32), +): + world, column = wp.tid() + if not world_mask[world]: + return + link = high_links[column] + low = low_links[column] + origin = wp.vec3(poses[world, link, 0], poses[world, link, 1], poses[world, link, 2]) + rotation = wp.quat(poses[world, link, 3], poses[world, link, 4], poses[world, link, 5], poses[world, link, 6]) + com = origin + wp.quat_rotate( + rotation, wp.vec3(local_com[world, link, 0], local_com[world, link, 1], local_com[world, link, 2]) + ) + force = wp.vec3() + moment = wp.vec3() + for i in range(wp.min(counts[world], rows.shape[1])): + c = contacts[world, i] + if c.link_index[0] != low and c.link_index[1] != low: + continue + n = c.normal + # motrixsim-gpu 1.0.0 resolves tangent impulses in this world-frame basis. + reference = wp.vec3(1.0, 0.0, 0.0) + if wp.abs(n[0]) >= 0.9: + reference = wp.vec3(0.0, 1.0, 0.0) + t0 = wp.normalize(wp.cross(n, reference)) + t1 = wp.cross(n, t0) + linear = wp.vec3() + angular = wp.vec3() + for axis in range(6): + row = rows[world, i, axis] + if row >= 0 and row < impulses.shape[1]: + direction = n + if axis == 1 or axis == 4: + direction = t0 + elif axis == 2 or axis == 5: + direction = t1 + value = direction * impulses[world, row] + if axis < 3: + linear += value + else: + angular += value + if c.link_index[0] == low: + force -= linear + moment -= angular + wp.cross(c.point - com, linear) + if c.link_index[1] == low: + force += linear + moment += angular + wp.cross(c.point + n * c.penetration_depth - com, linear) + for j in range(3): + output[world, column, j] = force[j] * inv_dt + output[world, column, 3 + j] = moment[j] * inv_dt + + +@wp.kernel +def touch_force( + world_mask: wp.array(dtype=wp.bool), + contacts: wp.array2d(dtype=Any), + counts: wp.array(dtype=wp.int32), + rows: wp.array3d(dtype=wp.int32), + impulses: wp.array2d(dtype=wp.float32), + frames: wp.array(dtype=Any), + frame_count: int, + frame_id: int, + colliders: wp.array(dtype=wp.int32), + size: wp.vec3, + box: bool, + inv_dt: float, + output: wp.array2d(dtype=wp.float32), +): + world = wp.tid() + if not world_mask[world]: + return + frame = frames[world * frame_count + frame_id] + total = wp.float32(0.0) + for i in range(wp.min(counts[world], rows.shape[1])): + c = contacts[world, i] + row = rows[world, i, 0] + if row < 0 or row >= impulses.shape[1]: + continue + for j in range(colliders.shape[0]): + collider = colliders[j] + if collider != c.pair_index[0] and collider != c.pair_index[1]: + continue + point = c.point + if collider == c.pair_index[1]: + point = point + c.normal * c.penetration_depth + local = wp.transpose(frame.rotation) * (point - frame.translation) + inside = wp.length_sq(local) <= size[0] * size[0] + if box: + inside = wp.abs(local[0]) <= size[0] and wp.abs(local[1]) <= size[1] and wp.abs(local[2]) <= size[2] + if inside: + total += wp.abs(impulses[world, row]) + break + output[world, 0] = total * inv_dt + + +@wp.kernel +def geom_pair_hits( + world_mask: wp.array(dtype=wp.bool), + contacts: wp.array2d(dtype=Any), + counts: wp.array(dtype=wp.int32), + limit: int, + pairs: wp.array2d(dtype=wp.int32), + offsets: wp.array(dtype=wp.int32), + output: wp.array2d(dtype=wp.float32), +): + world, group = wp.tid() + if not world_mask[world]: + return + for i in range(wp.min(counts[world], limit)): + pair = contacts[world, i].pair_index + for j in range(offsets[group], offsets[group + 1]): + a, b = pairs[j, 0], pairs[j, 1] + if (pair[0] == a and pair[1] == b) or (pair[0] == b and pair[1] == a): + output[world, group] = 1.0 + return + output[world, group] = 0.0 + + +class GpuContactProjector: + """Bind solver storage and share one dense row lookup per snapshot refresh.""" + + def __init__(self, backend): + self.backend = backend + self._domains = backend.data.low.domains + low_model = backend.host_model.low + self._contact_sensors = {sensor.name: sensor for sensor in low_model.low_contact_sensors} + self._touch_sensors = {sensor.name: sensor for sensor in low_model.low_touch_sensors} + self._rows = None + self.prepare_rows = None + + def geom_colliders(self, index): + return self.backend.host_model.low.get_collider_indices(index) or () + + def pair_reader(self, groups): + offsets = [0] + flat = [] + for group in groups: + flat.extend(group) + offsets.append(len(flat)) + backend = self.backend + if not flat: + result = backend.position.new_zeros((backend.data.num_worlds, len(groups))) + return lambda mask: result + device = backend._warp_device + pairs = wp.array(flat, dtype=wp.int32, device=device).reshape((-1, 2)) + bounds = wp.array(offsets, dtype=wp.int32, device=device) + shape = (backend.data.num_worlds, len(groups)) + output = wp.empty(shape, dtype=wp.float32, device=device) + result = wp.to_torch(output) + collision = self._domains["rigid_collision"] + limit = min(int(collision.max_contact_count), int(collision.contacts.shape[1])) + + def fetch(mask): + wp.launch( + geom_pair_hits, + shape, + inputs=[mask, collision.contacts, collision.contact_count, limit, pairs, bounds, output], + device=device, + ) + return result + + return fetch + + def sensor_reader(self, name): + if name in self._touch_sensors: + return self.touch_reader(self._touch_sensors[name]) + sensor = self._contact_sensors.get(name) + if sensor is None: + return None + report = sensor.report + if ( + report.normal + and not any((report.found, report.force, report.torque, report.pos, report.tangent, report.dist)) + and sensor.max_num == 1 + and sensor.reduce == "none" + ): + return self.geom_contact_reader(sensor.collider_pairs, normal=True) + if ( + not report.found + or any((report.force, report.torque, report.pos, report.normal, report.tangent, report.dist)) + or sensor.max_num != 1 + ): + raise NotImplementedError( + f"MotrixSim CUDA cannot provide contact sensor {name!r} with its requested report" + ) + return self.geom_contact_reader(sensor.collider_pairs) + + def link_contact_reader(self, indices): + if not indices: + empty = self.backend.position.new_empty((self.backend.data.num_worlds, 0, 6)) + return lambda mask: empty + + collision = self._domains["rigid_collision"] + solver = self._domains["solver"] + maps = self.backend.host_model.low.link_low_maps + # A high-level link can span virtual joints. Its colliders belong to the final rigid link. + low = [maps[i].index + maps[i].num - 1 for i in indices] + high_ids = wp.array(indices, dtype=wp.int32, device=self.backend._warp_device) + low_ids = wp.array(low, dtype=wp.int32, device=self.backend._warp_device) + output = wp.zeros( + (self.backend.data.num_worlds, len(indices), 6), dtype=wp.float32, device=self.backend._warp_device + ) + result = wp.to_torch(output) + + rows = self._contact_rows() + poses = self.backend.model.get_link_poses(self.backend.data) + + def fetch(mask): + wp.launch( + link_contact_wrenches, + (self.backend.data.num_worlds, len(indices)), + inputs=[ + mask, + collision.contacts, + collision.contact_count, + rows, + solver.constraint_lambdas.unilateral, + poses, + self._domains["overrides"].apparent_link_com, + high_ids, + low_ids, + 1.0 / self.backend.model.timestep, + output, + ], + device=self.backend._warp_device, + ) + return result + + return fetch + + def _contact_rows(self): + if self._rows is not None: + return self._rows + collision = self._domains["rigid_collision"] + solver = self._domains["solver"] + sparse = solver.sparse_jacobian + if sparse is not None: + self._rows = sparse.contact_rows.rows + else: + limit = min(int(collision.max_contact_count), int(collision.contacts.shape[1])) + row_shape = (collision.contacts.shape[0], limit) + rows = wp.empty((*row_shape, 6), dtype=wp.int32, device=self.backend._warp_device) + warm = solver.persistent_lambdas + + def prepare(mask): + wp.launch( + dense_contact_rows, + row_shape, + inputs=[ + mask, + collision.contacts, + collision.contact_count, + warm.slots, + warm.rows, + warm.row_counter, + rows, + ], + device=self.backend._warp_device, + ) + + self._rows = rows + self.prepare_rows = prepare + return self._rows + + def touch_reader(self, sensor): + shape = sensor.shape.shape_type + if shape not in ("sphere", "box") or sensor.loc.location_type != "Frame": + raise NotImplementedError(f"Unsupported touch sensor geometry for {sensor.name!r}: {shape}") + collision = self._domains["rigid_collision"] + impulses = self._domains["solver"].constraint_lambdas.unilateral + sensors = self._domains["sensors"] + colliders = wp.array(sensor.colliders, dtype=wp.int32, device=self.backend._warp_device) + output = wp.zeros((self.backend.data.num_worlds, 1), dtype=wp.float32, device=self.backend._warp_device) + result = wp.to_torch(output) + rows = self._contact_rows() + size = wp.vec3(*sensor.size) + + def fetch(mask): + wp.launch( + touch_force, + self.backend.data.num_worlds, + inputs=[ + mask, + collision.contacts, + collision.contact_count, + rows, + impulses, + sensors.base_to_frames, + sensors.frame_len, + sensor.loc.location_id, + colliders, + size, + shape == "box", + 1.0 / self.backend.model.timestep, + output, + ], + device=self.backend._warp_device, + ) + return result + + return fetch + + def geom_contact_reader(self, collider_pairs, *, normal=False): + collision = self._domains["rigid_collision"] + if not collider_pairs: + empty = self.backend.position.new_zeros((self.backend.data.num_worlds, 3 if normal else 1)) + return lambda mask: empty + pairs = wp.array(collider_pairs, dtype=wp.int32, device=self.backend._warp_device).reshape((-1, 2)) + output = wp.zeros( + (self.backend.data.num_worlds, 3 if normal else 1), dtype=wp.float32, device=self.backend._warp_device + ) + + result = wp.to_torch(output) + limit = min(int(collision.max_contact_count), int(collision.contacts.shape[1])) + + def fetch(mask): + wp.launch( + read_geom_contacts, + self.backend.data.num_worlds, + inputs=[mask, collision.contacts, collision.contact_count, limit, pairs, normal, output], + device=self.backend._warp_device, + ) + return result + + return fetch diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/gpu_reads.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/gpu_reads.py new file mode 100644 index 000000000..b7335f78d --- /dev/null +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/gpu_reads.py @@ -0,0 +1,330 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Compile CUDA reads into live views and captured derived projections.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from typing import TYPE_CHECKING + +import torch +import warp as wp + +from motrix_env_core.sim.read import PhysicsReadProgram, SimDataQuery +from motrix_env_motrixsim._gpu_primitives import GpuContactProjector +from motrix_env_motrixsim.read_compiler import MotrixReadCompiler, canonical_reads + +if TYPE_CHECKING: + from motrix_env_motrixsim.gpu_runtime import MotrixCudaBackend + +Projection = Callable[[tuple[torch.Tensor, ...]], torch.Tensor] + + +def _column_slice(indices) -> slice | None: + columns = tuple(int(index) for index in indices) + if not columns: + return slice(0, 0) + first = columns[0] + if columns == tuple(range(first, first + len(columns))): + return slice(first, first + len(columns)) + return None + + +class CudaReadCompiler(MotrixReadCompiler): + """Resolve names and bind device storage once for one SceneData instance.""" + + def __init__(self, backend: MotrixCudaBackend, queries: Mapping[str, SimDataQuery]): + self.backend = backend + self._model = backend.host_model + self.queries = dict(queries) + self.fields: dict[str, Projection] = {} + self.views: dict[str, torch.Tensor] = {} + self.sources: list[Callable] = [] + self.sensors: dict[str, Projection] = {} + self.native_sensors: dict[str, torch.Tensor] = {} + self.poses: dict[tuple[str, str], torch.Tensor] = {} + self.contacts = GpuContactProjector(backend) + self.link_poses = None + self.velocity_sources = [] + + def build(self) -> PhysicsReadProgram: + queries, self.aliases = canonical_reads(self.queries) + with self.backend.physics_stream(): + return self.compile(queries) + + def _build_program(self) -> PhysicsReadProgram: + return CudaReads(self) + + def _source(self, fetch: Callable) -> Projection: + index = len(self.sources) + self.sources.append(fetch) + return lambda values: values[index] + + def _joint_columns(self, key, indices, target): + span = _column_slice(indices) + if span is not None: + self.views[key] = target[:, span] + else: + columns = torch.as_tensor(indices, dtype=torch.long, device=target.device) + self.fields[key] = lambda values: target[:, columns] + + def compile_body_joint_position(self, key: str, body: str) -> None: + obj = self._get_body(self._validate_name(body, key), key) + self._joint_columns(key, obj.get_dof_pos_indices(False), self.backend.position) + + def compile_body_joint_velocity(self, key: str, body: str) -> None: + obj = self._get_body(self._validate_name(body, key), key) + self._joint_columns(key, obj.get_dof_vel_indices(False), self.backend.velocity) + + def compile_joints_position(self, key: str, joints: tuple[str, ...]) -> None: + resolved = self._one_dof_joints(key, joints, position=True) + self._joint_columns(key, [joint.dof_pos_index for joint in resolved], self.backend.position) + + def compile_joints_velocity(self, key: str, joints: tuple[str, ...]) -> None: + resolved = self._one_dof_joints(key, joints, position=False) + self._joint_columns(key, [joint.dof_vel_index for joint in resolved], self.backend.velocity) + + def _link_pose(self, key, links, components): + if self.link_poses is None: + self.link_poses = wp.to_torch(self.backend.model.get_link_poses(self.backend.data)) + poses = self.link_poses + if isinstance(links, str): + index = self._get_link_index(self._validate_name(links, key), key) + self.views[key] = poses[:, index, components] + else: + indices = self._link_indices(key, links) + span = _column_slice(indices) + if span is not None: + self.views[key] = poses[:, span, components] + else: + index = torch.tensor(indices, device=self.backend.device) + self.fields[key] = lambda values: poses[:, index, components] + + def compile_links_position(self, key: str, links: str | tuple[str, ...]) -> None: + self._link_pose(key, links, slice(3)) + + def compile_links_quaternion(self, key: str, links: str | tuple[str, ...]) -> None: + self._link_pose(key, links, slice(3, 7)) + + def _link_velocity(self, key, links, method): + single = isinstance(links, str) + names = (links,) if single else links + self._link_indices(key, names) + arrays = tuple(method(self.backend.model.get_link(name))(self.backend.data) for name in names) + self.velocity_sources.extend(arrays) + velocities = tuple(wp.to_torch(array) for array in arrays) + if single: + self.views[key] = velocities[0] + elif len(velocities) == 1: + self.views[key] = velocities[0][:, None, :] + else: + # SDK views can be slices of one packed per-world allocation. Use + # the SDK's actual pointers/strides to distinguish those from + # independently materialized per-link results. + first, second = arrays[:2] + link_stride = second.ptr - first.ptr + row_stride, component_stride = first.strides + span = (len(arrays) - 1) * link_stride + velocities[0].shape[-1] * component_stride + if ( + link_stride > 0 + and span <= row_stride + and all( + array.strides == first.strides and array.ptr == first.ptr + i * link_stride + for i, array in enumerate(arrays) + ) + ): + packed = wp.array( + ptr=first.ptr, + shape=(first.shape[0], len(arrays), first.shape[1]), + strides=(row_stride, link_stride, component_stride), + dtype=first.dtype, + device=first.device, + ) + self.views[key] = wp.to_torch(packed) + else: + self.fields[key] = lambda values: torch.stack(velocities, dim=1) + + def compile_links_linear_velocity(self, key: str, links: str | tuple[str, ...]) -> None: + self._link_velocity(key, links, lambda link: link.get_linear_velocity) + + def compile_links_angular_velocity(self, key: str, links: str | tuple[str, ...]) -> None: + self._link_velocity(key, links, lambda link: link.get_angular_velocity) + + def compile_links_net_contact_force(self, key: str, links: str | tuple[str, ...]) -> None: + single = isinstance(links, str) + indices = self._link_indices(key, (links,) if single else links) + source = self._source(self.contacts.link_contact_reader(indices)) + self.fields[key] = (lambda values: source(values)[:, 0]) if single else source + + def compile_body_link_net_contact_force(self, key: str, body: str, exclude_links: tuple[str, ...]) -> None: + body = self._get_body(self._validate_name(body, key), key) + excluded = set(self._validate_names(exclude_links, key, "excluded links", allow_empty=True)) + links = body.links + unknown = excluded.difference(link.name for link in links) + if unknown: + raise KeyError(f"Simulator query {key!r} excludes unknown body links: {sorted(unknown)}.") + self.fields[key] = self._source( + self.contacts.link_contact_reader([link.index for link in links if link.name not in excluded]) + ) + + def compile_sensor_values(self, key: str, sensors: tuple[str, ...]) -> None: + for name in self._validate_names(sensors, key, "sensors"): + if name not in self.sensors: + fetch = self.contacts.sensor_reader(name) + if fetch is None: + if name not in self._model.sensors.names: + raise KeyError(f"Simulator query {key!r} references unknown sensor {name!r}.") + view = wp.to_torch(self.backend.model.get_sensor_value(name, self.backend.data)) + self.native_sensors[name] = view + self.sensors[name] = lambda values, view=view: view + else: + self.sensors[name] = self._source(fetch) + if len(sensors) == 1 and sensors[0] in self.native_sensors: + self.views[key] = self.native_sensors[sensors[0]] + return + sources = tuple(self.sensors[name] for name in sensors) + self.fields[key] = ( + sources[0] if len(sources) == 1 else lambda values: torch.cat([s(values) for s in sources], dim=1) + ) + + def _pose(self, key, kind, name, components): + token = (kind, name) + if token not in self.poses: + if kind == "geom": + self._get_geom(self._validate_name(name, key), key) + obj = self.backend.model.get_geom(name) + else: + self._get_site(self._validate_name(name, key), key) + obj = self.backend.model.get_site(name) + self.poses[token] = wp.to_torch(obj.get_pose(self.backend.data)) + pose = self.poses[token] + self.views[key] = pose[:, components] + + def compile_site_position(self, key: str, site: str) -> None: + self._pose(key, "site", site, slice(3)) + + def compile_site_quaternion(self, key: str, site: str) -> None: + self._pose(key, "site", site, slice(3, 7)) + + def compile_geom_position(self, key: str, geom: str) -> None: + self._pose(key, "geom", geom, slice(3)) + + def compile_geom_quaternion(self, key: str, geom: str) -> None: + self._pose(key, "geom", geom, slice(3, 7)) + + def compile_geom_linear_velocity(self, key: str, geom: str) -> None: + self._get_geom(self._validate_name(geom, key), key) + obj = self.backend.model.get_geom(geom) + velocity = wp.to_torch(obj.get_linear_velocity(self.backend.data)) + self.views[key] = velocity + + def compile_geom_pair_colliding(self, key: str, pairs: tuple[tuple[str, str], ...]) -> None: + def colliders(name): + return self.contacts.geom_colliders(self._get_geom(name, key).index) + + groups = [ + [(a, b) for a in colliders(left) for b in colliders(right)] + for left, right in self._validate_name_pairs(pairs, key) + ] + self.fields[key] = self._source(self.contacts.pair_reader(groups)) + + def compile_dof_position(self, key: str) -> None: + self.views[key] = self.backend.position + + def compile_dof_velocity(self, key: str) -> None: + self.views[key] = self.backend.velocity + + def compile_actuator_ctrl(self, key: str) -> None: + self.views[key] = self.backend.control + + +class CudaReads(PhysicsReadProgram): + def __init__(self, compiler: CudaReadCompiler): + backend = compiler.backend + self._backend = backend + self._queries = compiler.queries + self._velocity_sources = tuple(compiler.velocity_sources) + self._world_mask = torch.ones_like(backend._all_worlds) + full_mask = wp.from_torch(backend._all_worlds) + masked = wp.from_torch(self._world_mask) + sources = tuple(compiler.sources) + prepare_contacts = compiler.contacts.prepare_rows + + def fetch(mask): + if prepare_contacts is not None: + prepare_contacts(mask) + return tuple(source(mask) for source in sources) + + values = fetch(full_mask) + outputs = {key: project(values).to(torch.float32).clone() for key, project in compiler.fields.items()} + self._arena_bytes = sum(out.numel() * out.element_size() for out in outputs.values()) + views = compiler.views | outputs + self._outputs = {key: views[canonical] for key, canonical in compiler.aliases.items()} + fields = tuple((outputs[key], project) for key, project in compiler.fields.items()) + # CUDA graphs retain raw addresses. Keep the indexed projections and + # the Warp launch closures alive along with their input tensors. + self._graph_inputs = (fields, fetch, values, full_mask, masked) + + def publish(values): + for output, project in fields: + output.copy_(project(values)) + + def publish_masked(values, mask): + for output, project in fields: + rows = mask.reshape((-1,) + (1,) * (output.ndim - 1)) + output.copy_(torch.where(rows, project(values), output)) + + self._graph = None + self._masked_graph = None + if fields: + options = {"triton.cudagraphs": False} + publish = torch.compile(publish, dynamic=False, options=options) + publish_masked = torch.compile(publish_masked, dynamic=False, options=options) + publish(values) + publish_masked(values, self._world_mask) + self._graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self._graph, stream=backend._torch_stream): + fetch(full_mask) + publish(values) + self._masked_graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(self._masked_graph, stream=backend._torch_stream): + fetch(masked) + publish_masked(values, self._world_mask) + + @property + def arena_bytes(self) -> int: + return self._arena_bytes + + @property + def keys(self) -> tuple[str, ...]: + return tuple(self._queries) + + def query(self, key: str) -> SimDataQuery: + return self._queries[key] + + def view(self, key: str) -> torch.Tensor: + return self._outputs[key] + + def execute(self, env_ids: torch.Tensor | None = None) -> None: + if env_ids is not None: + if ( + not isinstance(env_ids, torch.Tensor) + or env_ids.ndim != 1 + or env_ids.dtype not in (torch.int32, torch.int64) + ): + raise TypeError("Partial simulator read env_ids must be a one-dimensional integer tensor.") + if env_ids.numel() == 0: + return + env_ids = env_ids.to(self._backend.device, dtype=torch.long) + with self._backend.physics_stream(): + self.execute_masked(self._backend.world_mask(env_ids)) + elif self._graph is not None: + with self._backend.physics_stream(): + self._graph.replay() + + def execute_masked(self, world_mask: torch.Tensor) -> None: + if self._masked_graph is not None: + with self._backend.physics_stream(): + self._world_mask.copy_(world_mask) + self._masked_graph.replay() diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/gpu_runtime.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/gpu_runtime.py new file mode 100644 index 000000000..e6266d35d --- /dev/null +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/gpu_runtime.py @@ -0,0 +1,178 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Batched CUDA physics on a Warp stream ordered with the calling Torch stream.""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from contextlib import contextmanager + +import torch +import warp as wp +from motrixsim import gpu + +from motrix_env_core.config.scene import SceneCfg +from motrix_env_core.config.sim import SimCfg +from motrix_env_core.mdp.terrain import HeightFieldGrid, heightfield_lookup +from motrix_env_core.sim.backend import RenderConfig, SimBackend, SimRenderer +from motrix_env_core.sim.model import ModelQuery, SimModel +from motrix_env_core.sim.read import PhysicsReadProgram, SimDataQuery +from motrix_env_core.sim.write import CtrlTargetsWrite, WriteProgram +from motrix_env_motrixsim._gpu_primitives import GpuParameterOverrides, GpuSolverResetter, GpuStepStatus +from motrix_env_motrixsim.compiler import MotrixSimSceneCompiler +from motrix_env_motrixsim.gpu_reads import CudaReadCompiler +from motrix_env_motrixsim.gpu_writes import CudaWriteCompiler +from motrix_env_motrixsim.runtime import MotrixSimModelCompiler, _heightfield_grid, _named_geom + + +class MotrixCudaBackend(SimBackend): + name = "motrixsim" + supports_native_masked_reset = True + + def __init__(self, scene: SceneCfg, sim: SimCfg, num_envs: int, *, render: RenderConfig | None = None) -> None: + super().__init__(scene, sim, num_envs, render=render) + device = torch.device(sim.device) + self.device = torch.device("cuda", torch.cuda.current_device() if device.index is None else device.index) + self._warp_device = wp.get_device(str(self.device)) + self._stream = wp.Stream(self._warp_device) + self._stream.wait_stream(wp.get_stream(self._warp_device)) + self._caller_ready = wp.Event(self._warp_device) + self._torch_stream = torch.cuda.ExternalStream(self._stream.cuda_stream, device=self.device) + host_model = MotrixSimSceneCompiler().compile(scene, sim, render=render) + self.host_model = host_model + self._model_compiler = MotrixSimModelCompiler(host_model) + with self.physics_stream(): + self.model = gpu.SceneModel.from_cmodel( + host_model, max_contacts=sim.max_contacts, max_contact_constraints=sim.max_contact_constraints + ) + self.data = gpu.SceneData(self.model, batch=num_envs) + self.position = wp.to_torch(self.data.dof_pos) + self.velocity = wp.to_torch(self.data.dof_vel) + self.control = wp.to_torch(self.data.actuator_ctrls) + self._resetter = GpuSolverResetter(host_model, self.data, self._warp_device) + self._step_status = GpuStepStatus(self) + self._all_worlds = self.position.new_ones(num_envs, dtype=torch.bool) + self._terrain: dict[str, float | HeightFieldGrid] = {} + self._gain_tables: dict[str, torch.Tensor] = {} + self._gain_defaults: dict[str, torch.Tensor] = {} + self._overrides: GpuParameterOverrides | None = None + self._mocap_defaults = [] + with self.physics_stream(): + for body in self.model.bodies: + if body.is_mocap: + mocap = body.mocap + self._mocap_defaults.append((mocap, wp.to_torch(mocap.get_pose(self.data))[0].clone())) + self._write_compiler = CudaWriteCompiler(self) + self._default_reset = self._write_compiler.compile({}, reset=True) + + @contextmanager + def physics_stream(self) -> Iterator[None]: + current = torch.cuda.current_stream(self.device) + with wp.ScopedStream(self._stream, sync_enter=False, sync_exit=False): + if current.cuda_stream == self._stream.cuda_stream: + yield + return + caller = wp.stream_from_torch(current) + self._stream.wait_stream(caller, event=self._caller_ready) + try: + with torch.cuda.stream(self._torch_stream): + yield + finally: + caller.wait_stream(self._stream) + + step_context = physics_stream + + @property + def model_compiler(self) -> MotrixSimModelCompiler: + return self._model_compiler + + @property + def write_compiler(self) -> CudaWriteCompiler: + return self._write_compiler + + def compile_action_writes(self, writes: Mapping[str, CtrlTargetsWrite]) -> WriteProgram: + return CudaWriteCompiler(self, direct_ctrl=True).compile(writes, forward_kinematics=False) + + @property + def num_dof_pos(self) -> int: + return self.model.num_dof_pos + + @property + def num_dof_vel(self) -> int: + return self.model.num_dof_vel + + @property + def num_actuators(self) -> int: + return self.model.num_actuators + + def create_renderer(self, config: RenderConfig, *, num_envs: int, render_spacing: float) -> SimRenderer: + from motrix_env_motrixsim.renderer import MotrixSimRenderer + + return MotrixSimRenderer( + self.model, + lambda: self.data, + config, + num_envs=num_envs, + render_spacing=render_spacing, + system_camera=self._scene.system_camera, + render_app=gpu.render.RenderApp(headless=config.headless), + ) + + def world_mask(self, ids: torch.Tensor | None) -> torch.Tensor: + if ids is None: + return self._all_worlds + return torch.zeros_like(self._all_worlds).index_fill_(0, ids, True) + + def gain_table(self, attribute: str) -> torch.Tensor: + if attribute not in self._gain_tables: + table = wp.to_torch(getattr(self.data, attribute)) + self._gain_tables[attribute] = table + self._gain_defaults[attribute] = table.clone() + return self._gain_tables[attribute] + + @property + def overrides(self) -> GpuParameterOverrides: + if self._overrides is None: + self._overrides = GpuParameterOverrides(self) + return self._overrides + + def reset_masked(self, world_mask: torch.Tensor) -> None: + self._default_reset.execute_masked(world_mask) + + def reset_inputs(self, mask: torch.Tensor, warp_mask, *, recompute_inertia: bool = True) -> None: + self._resetter.execute(warp_mask) + for attribute, table in self._gain_tables.items(): + table.copy_(torch.where(mask[:, None], self._gain_defaults[attribute], table)) + if self._overrides is not None: + self._overrides.restore_defaults(mask, warp_mask, recompute_inertia=recompute_inertia) + for mocap, default in self._mocap_defaults: + poses = wp.to_torch(mocap.get_pose(self.data)) + poses.copy_(torch.where(mask[:, None], default, poses)) + mocap.set_pose(self.data, wp.from_torch(poses), world_mask=warp_mask) + + def sample_terrain_height(self, geom_name: str, env_ids: torch.Tensor, xy: torch.Tensor) -> torch.Tensor: + from motrixsim import GeomHField + + if geom_name not in self._terrain: + geom = _named_geom(self.host_model, geom_name) + self._terrain[geom_name] = ( + _heightfield_grid(geom, geom_name, self.device) + if isinstance(geom, GeomHField) + else float(geom.local_pose[2]) + ) + xy = xy.to(self.device) + terrain = self._terrain[geom_name] + if isinstance(terrain, float): + return xy.new_full(xy.shape[:-1], terrain, dtype=torch.float32) + return heightfield_lookup(terrain, xy[..., 0].double(), xy[..., 1].double()).float() + + def compile_model(self, queries: Mapping[str, ModelQuery]) -> SimModel: + return self.model_compiler.compile(self._scene, queries, device=self.device) + + def compile_reads(self, queries: Mapping[str, SimDataQuery]) -> PhysicsReadProgram: + return CudaReadCompiler(self, queries).build() + + def step(self, substeps: int, result: torch.Tensor | None = None) -> None: + with self.physics_stream(): + self._step_status.step(substeps, result) diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/gpu_writes.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/gpu_writes.py new file mode 100644 index 000000000..b456e8c4e --- /dev/null +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/gpu_writes.py @@ -0,0 +1,288 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Bind resolved MotrixSim write fields to persistent CUDA storage.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import numpy as np +import torch +import warp as wp +from motrixsim import write + +from motrix_env_core.sim.write import WriteProgram +from motrix_env_motrixsim._gpu_primitives import joint_actuator_slots +from motrix_env_motrixsim.write_compiler import MotrixWriteCompiler, ResolvedWrite + +if TYPE_CHECKING: + from motrix_env_motrixsim.gpu_runtime import MotrixCudaBackend + + +@dataclass +class _Channel: + slot: int + target: torch.Tensor + columns: torch.Tensor | None + quaternion: bool + + +@dataclass +class _LinkOverride: + slot: int + table: torch.Tensor + columns: torch.Tensor + positive: bool + + +@dataclass +class _FrictionOverride: + slot: int + spin_roll: torch.Tensor + collider_friction: torch.Tensor + source_cols: torch.Tensor + collider_cols: torch.Tensor + + +class CudaWriteCompiler(MotrixWriteCompiler): + def __init__(self, backend: MotrixCudaBackend, *, direct_ctrl: bool = False): + super().__init__(backend.host_model) + self.backend = backend + self.direct_ctrl = direct_ctrl + + def allocate(self, *, reset: bool, refresh: bool) -> WriteProgram: + with self.backend.physics_stream(): + return CudaWrites(self.backend, self._pending, reset, refresh, direct_ctrl=self.direct_ctrl) + + +class CudaWrites(WriteProgram): + def __init__( + self, + backend: MotrixCudaBackend, + fields: list[tuple[str, ResolvedWrite]], + reset: bool, + refresh: bool, + *, + direct_ctrl: bool = False, + ): + self._full_batch_only = direct_ctrl + self._backend = backend + self._reset = reset + self._refresh = refresh + self._buffers: dict[str, torch.Tensor] = {} + self._channels: list[_Channel] = [] + mocaps: dict[str, list] = {} + self._gains: list[tuple[int, torch.Tensor, torch.Tensor]] = [] + self._link_overrides: list[_LinkOverride] = [] + self._friction_overrides: list[_FrictionOverride] = [] + for slot, (name, field) in enumerate(fields): + direct = None + for indices, target in ( + (field.ctrl_indices, backend.control), + (field.pos_indices, backend.position), + (field.vel_indices, backend.velocity), + ): + if indices is None: + continue + shape = indices.shape + flat = indices.ravel() + quaternion = isinstance(field.native, write.JointQuaternion) + if flat.size and np.array_equal(flat, np.arange(flat[0], flat[0] + flat.size)): + selected = target[:, int(flat[0]) : int(flat[-1]) + 1] + if direct_ctrl and field.ctrl_indices is not None: + direct = selected + else: + self._channels.append(_Channel(slot, selected, None, quaternion)) + else: + self._channels.append( + _Channel(slot, target, torch.as_tensor(flat, device=backend.device), quaternion) + ) + break + else: + source = field.native + if isinstance(source, (write.BodyPosition, write.BodyRotation)): + rotation = isinstance(source, write.BodyRotation) + shape = (len(source.selection), 4 if rotation else 3) + components = slice(3, 7) if rotation else slice(3) + for column, body in enumerate(source.selection): + mocaps.setdefault(body, []).append((slot, column, components)) + else: + shape = self._bind_parameter(slot, source) + self._buffers[name] = ( + direct if direct is not None else backend.position.new_zeros((backend.data.num_worlds, *shape)) + ) + self._mocap_fields = tuple((backend.model.get_body(body).mocap, fields) for body, fields in mocaps.items()) + self._recompute_inertia = bool(self._link_overrides) + self._values = tuple(self._buffers.values()) + self._quaternion_identity = ( + backend.position.new_tensor((0, 0, 0, 1)) if any(channel.quaternion for channel in self._channels) else None + ) + + def _bind_parameter(self, slot: int, source: write.WriteSource) -> tuple[int, ...]: + backend = self._backend + model = backend.model + names = source.selection + if isinstance(source, (write.ActuatorKpOverride, write.ActuatorDampingOverride)): + actuators = [model.get_actuator(name) for name in names] + slots = joint_actuator_slots(model) + for a in actuators: + if a.typ != "position" or a.target_type not in ("joint", "floating_base") or a.index not in slots: + raise ValueError( + "MotrixSim CUDA 1.0.0 supports gain overrides only for joint or floating-base " + f"position actuators, got {a.name!r} ({a.typ}/{a.target_type})" + ) + columns = torch.tensor([slots[a.index] for a in actuators], device=backend.device, dtype=torch.long) + attr = ( + "actuator_kp_overrides" + if isinstance(source, write.ActuatorKpOverride) + else "actuator_damping_overrides" + ) + self._gains.append((slot, backend.gain_table(attr), columns)) + return (len(names),) + + if isinstance(source, (write.LinkMassOverride, write.LinkCenterOfMassOverride)): + mass_table, com_table = backend.overrides.bind_link_inertia() + columns = torch.tensor( + [model.get_link(name).index for name in names], device=backend.device, dtype=torch.long + ) + if isinstance(source, write.LinkMassOverride): + self._link_overrides.append(_LinkOverride(slot, mass_table, columns, positive=True)) + return (len(names),) + self._link_overrides.append(_LinkOverride(slot, com_table, columns, positive=False)) + return (len(names), 3) + + if isinstance(source, write.GeomFrictionOverride): + geoms = [backend.host_model.get_geom(name) for name in names] + geom_indices = [g.index for g in geoms] + spin_roll = backend.position.new_tensor(np.stack([g.friction[1:] for g in geoms])) + collider_friction, source_cols, collider_cols = backend.overrides.bind_geom_friction(geom_indices) + self._friction_overrides.append( + _FrictionOverride(slot, spin_roll, collider_friction, source_cols, collider_cols) + ) + return (len(names), 3) + + raise NotImplementedError(f"Unsupported CUDA parameter {type(source).__name__}") + + def buffer(self, name: str) -> torch.Tensor: + return self._buffers[name] + + def execute(self, env_ids: torch.Tensor | None = None) -> None: + self._execute(env_ids, self._values, compact=False) + + def execute_compact(self, env_ids: torch.Tensor, buffers: tuple[torch.Tensor, ...]) -> None: + self._execute(env_ids, buffers, compact=True) + + def execute_masked(self, world_mask: torch.Tensor) -> None: + self._execute(None, self._values, compact=False, world_mask=world_mask) + + def _execute( + self, + ids: torch.Tensor | None, + buffers: tuple[torch.Tensor, ...], + *, + compact: bool, + world_mask: torch.Tensor | None = None, + ) -> None: + backend = self._backend + if self._full_batch_only and (ids is not None or world_mask is not None or compact): + raise RuntimeError("This action write program supports full-batch execute() only.") + channels = self._channels + if ids is not None: + if not isinstance(ids, torch.Tensor) or ids.ndim != 1 or ids.dtype not in (torch.int32, torch.int64): + raise TypeError("Simulator write env_ids must be a one-dimensional integer tensor.") + if ids.numel() == 0: + return + ids = ids.to(backend.device, dtype=torch.long) + if not ( + self._reset + or self._refresh + or channels + or self._gains + or self._link_overrides + or self._friction_overrides + or self._mocap_fields + ): + return + rows = slice(None) if ids is None else ids + source_rows = slice(0, ids.numel()) if compact else rows + + with backend.physics_stream(): + mask = world_mask if world_mask is not None else backend.world_mask(ids) + warp_mask = wp.from_torch(mask) if self._reset or self._recompute_inertia or self._mocap_fields else None + for friction in self._friction_overrides: + raw = buffers[friction.slot][source_rows] + supported = ((raw[..., 1:] == friction.spin_roll) | ~raw[..., 0:1].isfinite()).all(dim=(1, 2)) + if world_mask is not None: + supported = supported | ~mask + torch._assert_async(supported.all(), "MotrixSim CUDA 1.0.0 supports only sliding-friction overrides") + if self._reset: + backend.reset_inputs(mask, warp_mask, recompute_inertia=not self._recompute_inertia) + for channel in channels: + values = buffers[channel.slot][source_rows] + if channel.quaternion: + norm = torch.linalg.vector_norm(values, dim=-1, keepdim=True) + values = torch.where(norm == 0, self._quaternion_identity, values / norm) + values = values.flatten(1) + self._update_columns(channel.target, channel.columns, ids, world_mask, values) + for slot, table, columns in self._gains: + row_index = rows if ids is None else ids[:, None] + previous = table[row_index, columns] + values = buffers[slot][source_rows] + values = torch.where(values.isfinite() & (values >= 0), values, previous) + self._update_columns(table, columns, ids, world_mask, values) + for override in self._link_overrides: + row_index = rows if ids is None else ids[:, None] + previous = override.table[row_index, override.columns] + values = buffers[override.slot][source_rows] + if values.ndim == 3: + valid = values.isfinite().all(dim=-1, keepdim=True) + else: + valid = values.isfinite() & ((values > 0) if override.positive else (values >= 0)) + values = torch.where(valid, values, previous) + self._update_columns(override.table, override.columns, ids, world_mask, values) + if self._recompute_inertia: + backend.overrides.commit_link_inertia(warp_mask) + for friction in self._friction_overrides: + if friction.collider_cols.numel() == 0: + continue + row_index = rows if ids is None else ids[:, None] + previous = friction.collider_friction[row_index, friction.collider_cols, 0] + picked = buffers[friction.slot][source_rows][:, friction.source_cols] + sliding = picked[..., 0] + valid = picked.isfinite().all(dim=-1) & (sliding >= 0) + values = torch.where(valid, sliding, previous) + if ids is not None: + friction.collider_friction[ids[:, None], friction.collider_cols, 0] = values + else: + if world_mask is not None: + values = torch.where(world_mask[:, None], values, previous) + friction.collider_friction[:, friction.collider_cols, 0] = values + for mocap, fields in self._mocap_fields: + poses = wp.to_torch(mocap.get_pose(backend.data)) + for slot, column, components in fields: + self._update_columns( + poses[:, components], None, ids, world_mask, buffers[slot][source_rows, column] + ) + mocap.set_pose(backend.data, wp.from_torch(poses), world_mask=warp_mask) + if self._refresh: + # SDK 1.0.0 only exposes a whole-batch kinematics refresh. + backend.model.forward_kinematic(backend.data) + + @staticmethod + def _update_columns(target, columns, ids, mask, values) -> None: + mask_view = None if mask is None else mask.reshape((-1,) + (1,) * (values.ndim - 1)) + if columns is None: + if ids is not None: + target[ids] = values + elif mask_view is not None: + target.copy_(torch.where(mask_view, values, target)) + else: + target.copy_(values) + elif ids is not None: + target[ids[:, None], columns] = values + else: + if mask_view is not None: + values = torch.where(mask_view, values, target[:, columns]) + target.index_copy_(1, columns, values) diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/kinematics.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/kinematics.py index a2cbc6498..98f79eef9 100644 --- a/motrix_env_motrixsim/src/motrix_env_motrixsim/kinematics.py +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/kinematics.py @@ -13,13 +13,14 @@ import motrixsim as mtx import numpy as np +import torch from motrix_env_core.math.kinematics import KinematicTree from motrix_env_core.math.quaternion import mul as quat_mul from motrix_env_core.math.quaternion import rotate_vector -def kinematic_tree(model: mtx.SceneModel, base_link: str, *, device: str = "cpu") -> KinematicTree: +def kinematic_tree(model: mtx.SceneModel, base_link: str, *, device: str | torch.device = "cpu") -> KinematicTree: """Extract the moving-link tree rooted at ``base_link`` from a compiled model. Fixed links are folded into the offsets of their nearest moving diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/read_compiler.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/read_compiler.py new file mode 100644 index 000000000..263648f6a --- /dev/null +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/read_compiler.py @@ -0,0 +1,109 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Compile-time model lookups shared by both MotrixSim read programs.""" + +from collections.abc import Mapping + +import motrixsim as mtx + +from motrix_env_core.sim.read import SimDataQuery, SimDataQueryCompiler + + +def canonical_reads(queries: Mapping[str, SimDataQuery]) -> tuple[dict[str, SimDataQuery], dict[str, str]]: + canonical_queries: dict[str, SimDataQuery] = {} + canonical_keys: dict[str, str] = {} + for key, query in queries.items(): + duplicate = next((c for c, q in canonical_queries.items() if q == query), None) + canonical_keys[key] = key if duplicate is None else duplicate + if duplicate is None: + canonical_queries[key] = query + return canonical_queries, canonical_keys + + +class MotrixReadCompiler(SimDataQueryCompiler): + _model: mtx.SceneModel + + def _link_indices(self, key: str, names: tuple[str, ...]) -> tuple[int, ...]: + link_names = self._validate_names(names, key, "links") + return tuple(self._get_link_index(name, key) for name in link_names) + + @staticmethod + def _validate_name(name: str, key: str) -> str: + if not isinstance(name, str) or not name: + raise ValueError(f"Simulator query {key!r} names must be non-empty strings.") + return name + + @classmethod + def _validate_names( + cls, + names: tuple[str, ...], + key: str, + kind: str, + *, + allow_empty: bool = False, + ) -> tuple[str, ...]: + if not isinstance(names, tuple): + raise TypeError(f"Simulator query {key!r} {kind} must be tuple[str, ...].") + if not names and not allow_empty: + raise ValueError(f"Simulator query {key!r} must contain at least one {kind} entry.") + for name in names: + cls._validate_name(name, key) + if len(set(names)) != len(names): + raise ValueError(f"Simulator query {key!r} contains duplicate {kind}: {names}.") + return names + + @staticmethod + def _validate_name_pairs(pairs: tuple[tuple[str, str], ...], key: str) -> tuple[tuple[str, str], ...]: + if not isinstance(pairs, tuple): + raise TypeError(f"Simulator query {key!r} geom pairs must be tuple[tuple[str, str], ...].") + if not pairs: + raise ValueError(f"Simulator query {key!r} must contain at least one geom pair entry.") + for pair in pairs: + if not isinstance(pair, tuple) or len(pair) != 2: + raise TypeError(f"Simulator query {key!r} geom pairs must contain two-name tuples.") + if any(not isinstance(name, str) or not name for name in pair): + raise TypeError(f"Simulator query {key!r} geom pairs must contain non-empty string names.") + if len(set(pairs)) != len(pairs): + raise ValueError(f"Simulator query {key!r} contains duplicate geom pairs: {pairs}.") + return pairs + + def _one_dof_joints(self, key: str, names: tuple[str, ...], *, position: bool) -> tuple[mtx.Joint, ...]: + joint_names = self._validate_names(names, key, "joints") + joints = [] + for name in joint_names: + joint = self._model.get_joint(name) + if joint is None: + raise KeyError(f"Simulator query {key!r} references unknown joint {name!r}.") + width = joint.num_dof_pos if position else joint.num_dof_vel + if width != 1: + quantity = "position" if position else "velocity" + raise ValueError( + f"Simulator query {key!r} joint {name!r} has {width} {quantity} DOFs; exactly one is required." + ) + joints.append(joint) + return tuple(joints) + + def _get_body(self, name: str, key: str) -> mtx.Body: + body = self._model.get_body(name) + if body is None: + raise KeyError(f"Simulator query {key!r} references unknown body {name!r}.") + return body + + def _get_site(self, name: str, key: str) -> mtx.Site: + site = self._model.get_site(name) + if site is None: + raise KeyError(f"Simulator query {key!r} references unknown site {name!r}.") + return site + + def _get_geom(self, name: str, key: str) -> mtx.Geom: + geom = self._model.get_geom(name) + if geom is None: + raise KeyError(f"Simulator query {key!r} references unknown geom {name!r}.") + return geom + + def _get_link_index(self, name: str, key: str) -> int: + link = self._model.get_link(name) + if link is None: + raise KeyError(f"Simulator query {key!r} references unknown link {name!r}.") + return link.index diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/register.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/register.py index f7c0f4a64..cff087e93 100644 --- a/motrix_env_motrixsim/src/motrix_env_motrixsim/register.py +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/register.py @@ -7,13 +7,28 @@ discovery never imports the native simulator. """ +from importlib.util import find_spec + +import torch + +from motrix_env_core.sim.backend import SimBackend from motrix_env_core.sim.registry import register_sim_backend -def _sim_backend(): - from motrix_env_motrixsim.runtime import MotrixSimBackend +def _sim_backend(device: torch.device) -> type[SimBackend]: + if device.type == "cpu": + from motrix_env_motrixsim.runtime import MotrixSimBackend + + return MotrixSimBackend + if device.type != "cuda": + raise ValueError(f"MotrixSim does not support simulation on {device}") + if find_spec("motrixsim.gpu") is None: + raise ImportError("MotrixSim CUDA requires motrix-env-motrixsim[gpu]") + if not torch.cuda.is_available() or (device.index is not None and device.index >= torch.cuda.device_count()): + raise ValueError(f"Requested MotrixSim CUDA device {device} is unavailable") + from motrix_env_motrixsim.gpu_runtime import MotrixCudaBackend - return MotrixSimBackend + return MotrixCudaBackend def register() -> None: diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/renderer.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/renderer.py index dcbb76a37..b3d625fb4 100644 --- a/motrix_env_motrixsim/src/motrix_env_motrixsim/renderer.py +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/renderer.py @@ -35,12 +35,13 @@ def __init__( num_envs: int, render_spacing: float, system_camera: SystemCameraCfg, + render_app: RenderApp | None = None, ): self._data_source = data_source self._headless = config.headless self._closed = False offsets = _render_layout(num_envs, render_spacing) - self._render = RenderApp(headless=config.headless) + self._render = RenderApp(headless=config.headless) if render_app is None else render_app self._render.launch( model, batch=num_envs, diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/runtime.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/runtime.py index f5964192d..2b344c0a5 100644 --- a/motrix_env_motrixsim/src/motrix_env_motrixsim/runtime.py +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/runtime.py @@ -51,10 +51,10 @@ def _begin_compile(self) -> None: def _build_model(self, scene: SceneCfg) -> SimModel: actuators = _actuator_specs(self._model.actuators) init_dof_pos = np.asarray(self._model.compute_init_dof_pos(), dtype=np.float32) - bodies = _build_body_models(self._model, scene, actuators, init_dof_pos) + bodies = _build_body_models(self._model, scene, actuators, init_dof_pos, self._device) return SimModel( actuators=actuators, - init_dof_pos=torch.from_numpy(init_dof_pos), + init_dof_pos=torch.as_tensor(init_dof_pos, device=self._device), others=self._others, bodies=bodies, ) @@ -64,57 +64,29 @@ def compile_geom_specs(self, key: str, geom_names: tuple[str, ...]) -> None: def compile_height_field_data(self, key: str, geom_name: str) -> None: geom = _named_geom(self._model, geom_name) - if not isinstance(geom, mtx.GeomHField) or geom.hfield is None: - raise ValueError( - f"HeightFieldDataQuery requires geom {geom_name!r} to carry a height field, got {type(geom).__name__}." - ) - hfield = geom.hfield - pose = np.asarray(geom.local_pose, dtype=np.float32).reshape(-1) - quat_ijkw = pose[3:7] - if abs(float(quat_ijkw[3])) < 1.0 - 1e-5: - raise ValueError( - f"HeightFieldDataQuery requires geom {geom_name!r} to be world-aligned " - f"(identity rotation), got quaternion {tuple(quat_ijkw)}." - ) - heights = np.ascontiguousarray(np.asarray(hfield.height_matrix, dtype=np.float32)) - nrow, ncol = heights.shape - bound = np.asarray(hfield.bound, dtype=np.float32) - extent_x, extent_y = float(bound[3]), float(bound[4]) - spacing = np.asarray( - [2.0 * extent_x / max(ncol - 1, 1), 2.0 * extent_y / max(nrow - 1, 1)], - dtype=np.float32, - ) - origin = np.asarray([float(pose[0]) - extent_x, float(pose[1]) - extent_y], dtype=np.float32) - # Export one shared, immutable grid: the float64 conversion happens - # once here instead of in every consuming term. - self._others[key] = HeightFieldGrid( - heights=torch.from_numpy(heights).to(torch.float64).contiguous(), - origin=torch.from_numpy(origin).to(torch.float64).contiguous(), - spacing=torch.from_numpy(spacing).to(torch.float64).contiguous(), - z0=torch.as_tensor([pose[2]], dtype=torch.float64), - constant=0.0, - enabled=True, - ) + self._others[key] = _heightfield_grid(geom, geom_name, self._device) def compile_body_joint_position_limits(self, key: str, body: str) -> None: lower, upper = _body_joint_position_limits(self._model, body) - self._others[key] = (torch.from_numpy(lower), torch.from_numpy(upper)) + self._others[key] = (torch.as_tensor(lower, device=self._device), torch.as_tensor(upper, device=self._device)) - def compile_kinematic_tree(self, key: str, body: str, device: str) -> None: + def compile_kinematic_tree(self, key: str, body: str, device: str | None) -> None: scene_body = self._model.get_body(body) if scene_body is None: raise KeyError(f"Unknown body {body!r}.") - self._others[key] = kinematic_tree(self._model, scene_body.base_link.name, device=device) + self._others[key] = kinematic_tree( + self._model, scene_body.base_link.name, device=self._device if device is None else device + ) def compile_dof_position_limits(self, key: str) -> None: lower, upper = _dof_position_limits(self._model) - self._others[key] = (torch.from_numpy(lower), torch.from_numpy(upper)) + self._others[key] = (torch.as_tensor(lower, device=self._device), torch.as_tensor(upper, device=self._device)) def compile_actuator_kp(self, key: str, actuator_names: tuple[str, ...] | None) -> None: - self._others[key] = torch.from_numpy(_nominal_actuator_kp(self._model, actuator_names)) + self._others[key] = torch.as_tensor(_nominal_actuator_kp(self._model, actuator_names), device=self._device) def compile_actuator_kd(self, key: str, actuator_names: tuple[str, ...] | None) -> None: - self._others[key] = torch.from_numpy(_nominal_actuator_kd(self._model, actuator_names)) + self._others[key] = torch.as_tensor(_nominal_actuator_kd(self._model, actuator_names), device=self._device) def compile_link_mass(self, key: str, body: str) -> None: self._others[key] = float(_named_link(self._model, body).mass) @@ -134,14 +106,50 @@ def compile_body_masses(self, key: str, body: str, links: tuple[str, ...] | None masses = [body_links[name].mass for name in links] except KeyError as exc: raise KeyError(f"Link {exc.args[0]!r} is not part of body {body!r}.") from None - self._others[key] = torch.as_tensor(masses, dtype=torch.float32) + self._others[key] = torch.as_tensor(masses, dtype=torch.float32, device=self._device) def compile_link_center_of_mass(self, key: str, body: str) -> None: com = np.asarray(_named_link(self._model, body).center_of_mass, dtype=np.float32).reshape(3) - self._others[key] = torch.from_numpy(com) + self._others[key] = torch.as_tensor(com, device=self._device) def compile_geom_friction(self, key: str, geom: str) -> None: - self._others[key] = torch.as_tensor(_named_geom(self._model, geom).friction, dtype=torch.float32) + self._others[key] = torch.as_tensor( + _named_geom(self._model, geom).friction, dtype=torch.float32, device=self._device + ) + + +def _heightfield_grid(geom: mtx.Geom, geom_name: str, device: torch.device) -> HeightFieldGrid: + if not isinstance(geom, mtx.GeomHField) or geom.hfield is None: + raise ValueError( + f"HeightFieldDataQuery requires geom {geom_name!r} to carry a height field, got {type(geom).__name__}." + ) + hfield = geom.hfield + pose = np.asarray(geom.local_pose, dtype=np.float32).reshape(-1) + quat_ijkw = pose[3:7] + if abs(float(quat_ijkw[3])) < 1.0 - 1e-5: + raise ValueError( + f"HeightFieldDataQuery requires geom {geom_name!r} to be world-aligned " + f"(identity rotation), got quaternion {tuple(quat_ijkw)}." + ) + heights = np.ascontiguousarray(np.asarray(hfield.height_matrix, dtype=np.float32)) + nrow, ncol = heights.shape + bound = np.asarray(hfield.bound, dtype=np.float32) + extent_x, extent_y = float(bound[3]), float(bound[4]) + spacing = np.asarray( + [2.0 * extent_x / max(ncol - 1, 1), 2.0 * extent_y / max(nrow - 1, 1)], + dtype=np.float32, + ) + origin = np.asarray([float(pose[0]) - extent_x, float(pose[1]) - extent_y], dtype=np.float32) + # Export one shared, immutable grid: the float64 conversion happens + # once here instead of in every consuming term. + return HeightFieldGrid( + heights=torch.as_tensor(heights, dtype=torch.float64, device=device).contiguous(), + origin=torch.as_tensor(origin, dtype=torch.float64, device=device).contiguous(), + spacing=torch.as_tensor(spacing, dtype=torch.float64, device=device).contiguous(), + z0=torch.as_tensor([pose[2]], dtype=torch.float64, device=device), + constant=0.0, + enabled=True, + ) def _nominal_actuator_kp(model: mtx.SceneModel, actuator_names: tuple[str, ...] | None) -> FloatArray: @@ -259,6 +267,7 @@ def _build_body_models( scene: SceneCfg, scene_actuators: tuple[ActuatorSpec, ...], default_dof: FloatArray, + device: torch.device, ) -> dict[str, BodyModel]: """Assemble one ``BodyModel`` per ``BodyCfg`` declared in the scene.""" facts = [_body_facts(model, name, cfg) for name, cfg in scene.iter_objs() if isinstance(cfg, BodyCfg)] @@ -298,6 +307,7 @@ def _build_body_models( init_link_positions=poses[:, :3], init_link_quats=poses[:, 3:7], robot_cfg=robot_cfg, + device=device, ) return bodies diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/sim_data.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/sim_data.py index 9f218cc94..ec01b3488 100644 --- a/motrix_env_motrixsim/src/motrix_env_motrixsim/sim_data.py +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/sim_data.py @@ -13,7 +13,8 @@ import torch from motrix_env_core.perf import active_perf_scope -from motrix_env_core.sim import PhysicsReadProgram, SimDataQuery, SimDataQueryCompiler +from motrix_env_core.sim import PhysicsReadProgram, SimDataQuery +from motrix_env_motrixsim.read_compiler import MotrixReadCompiler, canonical_reads FloatArray: TypeAlias = np.ndarray @@ -58,7 +59,7 @@ class _ResolvedQuery: trailing_shape: tuple[int, ...] | None = None -class _MotrixSimDataQueryCompiler(SimDataQueryCompiler): +class _MotrixSimDataQueryCompiler(MotrixReadCompiler): """Compile semantic queries into one MotrixSim physical read program.""" def __init__( @@ -251,90 +252,6 @@ def _batch_links( indices = self._link_indices(key, names) self._record(key, source_type(indices), (len(indices), width)) - def _link_indices(self, key: str, names: tuple[str, ...]) -> tuple[int, ...]: - link_names = self._validate_names(names, key, "links") - return tuple(self._get_link_index(name, key) for name in link_names) - - @staticmethod - def _validate_name(name: str, key: str) -> str: - if not isinstance(name, str) or not name: - raise ValueError(f"Simulator query {key!r} names must be non-empty strings.") - return name - - @classmethod - def _validate_names( - cls, - names: tuple[str, ...], - key: str, - kind: str, - *, - allow_empty: bool = False, - ) -> tuple[str, ...]: - if not isinstance(names, tuple): - raise TypeError(f"Simulator query {key!r} {kind} must be tuple[str, ...].") - if not names and not allow_empty: - raise ValueError(f"Simulator query {key!r} must contain at least one {kind} entry.") - for name in names: - cls._validate_name(name, key) - if len(set(names)) != len(names): - raise ValueError(f"Simulator query {key!r} contains duplicate {kind}: {names}.") - return names - - @staticmethod - def _validate_name_pairs(pairs: tuple[tuple[str, str], ...], key: str) -> tuple[tuple[str, str], ...]: - if not isinstance(pairs, tuple): - raise TypeError(f"Simulator query {key!r} geom pairs must be tuple[tuple[str, str], ...].") - if not pairs: - raise ValueError(f"Simulator query {key!r} must contain at least one geom pair entry.") - for pair in pairs: - if not isinstance(pair, tuple) or len(pair) != 2: - raise TypeError(f"Simulator query {key!r} geom pairs must contain two-name tuples.") - if any(not isinstance(name, str) or not name for name in pair): - raise TypeError(f"Simulator query {key!r} geom pairs must contain non-empty string names.") - if len(set(pairs)) != len(pairs): - raise ValueError(f"Simulator query {key!r} contains duplicate geom pairs: {pairs}.") - return pairs - - def _one_dof_joints(self, key: str, names: tuple[str, ...], *, position: bool) -> tuple[mtx.Joint, ...]: - joint_names = self._validate_names(names, key, "joints") - joints = [] - for name in joint_names: - joint = self._model.get_joint(name) - if joint is None: - raise KeyError(f"Simulator query {key!r} references unknown joint {name!r}.") - width = joint.num_dof_pos if position else joint.num_dof_vel - if width != 1: - quantity = "position" if position else "velocity" - raise ValueError( - f"Simulator query {key!r} joint {name!r} has {width} {quantity} DOFs; exactly one is required." - ) - joints.append(joint) - return tuple(joints) - - def _get_body(self, name: str, key: str) -> mtx.Body: - body = self._model.get_body(name) - if body is None: - raise KeyError(f"Simulator query {key!r} references unknown body {name!r}.") - return body - - def _get_site(self, name: str, key: str) -> mtx.Site: - site = self._model.get_site(name) - if site is None: - raise KeyError(f"Simulator query {key!r} references unknown site {name!r}.") - return site - - def _get_geom(self, name: str, key: str) -> mtx.Geom: - geom = self._model.get_geom(name) - if geom is None: - raise KeyError(f"Simulator query {key!r} references unknown geom {name!r}.") - return geom - - def _get_link_index(self, name: str, key: str) -> int: - link = self._model.get_link(name) - if link is None: - raise KeyError(f"Simulator query {key!r} references unknown link {name!r}.") - return link.index - @dataclass(frozen=True) class _BatchQueryRead: @@ -450,12 +367,6 @@ def compile_read_program( """Compile fixed semantic queries into one MotrixSim batch-query program.""" # Memory planning is backend-owned: collapse equal declarations onto # one region, then serve every declared key as an alias of it. - canonical_queries: dict[str, SimDataQuery] = {} - canonical_keys: dict[str, str] = {} - for key, query in queries.items(): - duplicate = next((c for c, q in canonical_queries.items() if q == query), None) - canonical_keys[key] = key if duplicate is None else duplicate - if duplicate is None: - canonical_queries[key] = query + canonical_queries, canonical_keys = canonical_reads(queries) compiler = _MotrixSimDataQueryCompiler(model, source, queries, canonical_keys) return compiler.compile(canonical_queries) diff --git a/motrix_env_motrixsim/src/motrix_env_motrixsim/write_compiler.py b/motrix_env_motrixsim/src/motrix_env_motrixsim/write_compiler.py index c3e8ba6b6..8c3ebdd68 100644 --- a/motrix_env_motrixsim/src/motrix_env_motrixsim/write_compiler.py +++ b/motrix_env_motrixsim/src/motrix_env_motrixsim/write_compiler.py @@ -3,6 +3,7 @@ """MotrixSim compiler and executable program for declarative sim writes.""" +from abc import abstractmethod from dataclasses import dataclass import motrixsim as mtx @@ -35,31 +36,25 @@ @dataclass(frozen=True) -class _CompiledWrite: +class ResolvedWrite: + native: mtx_write.WriteSource pos_indices: np.ndarray | None = None vel_indices: np.ndarray | None = None refresh_kinematics: bool = False - native: mtx_write.WriteSource | None = None ctrl_indices: np.ndarray | None = None -class MotrixSimWriteCompiler(SimWriteCompiler): - """Compile neutral write declarations against one MotrixSim model and data batch. +class MotrixWriteCompiler(SimWriteCompiler): + """Resolve ordered write declarations and ownership against the host scene model.""" - Every write compiles into one native write plan; reset and - forward-kinematics behavior are baked into the plan at compile time. - """ - - def __init__(self, model: mtx.SceneModel, data: mtx.SceneData) -> None: + def __init__(self, model: mtx.SceneModel) -> None: self._model = model - self._data = data - self._pending: list[tuple[str, _CompiledWrite]] = [] + self._pending: list[tuple[str, ResolvedWrite]] = [] def _begin_compile(self) -> None: self._pending = [] def _build_program(self, *, reset: bool, forward_kinematics: bool) -> WriteProgram: - native_fields: dict[str, mtx_write.WriteSource] = {} ctrl_owners: dict[int, str] = {} claimed_pos: dict[int, str] = {} claimed_vel: dict[int, str] = {} @@ -71,20 +66,12 @@ def _build_program(self, *, reset: bool, forward_kinematics: bool) -> WriteProgr self._claim(name, compiled.pos_indices, claimed_pos, "position") if compiled.vel_indices is not None: self._claim(name, compiled.vel_indices, claimed_vel, "velocity") - native_fields[name] = compiled.native refresh_kinematics |= compiled.refresh_kinematics - buffers: dict[str, torch.Tensor] = {} - native_program = None - if native_fields: - # Reset (restore defaults, then apply the writes) and the FK pass - # are baked into the native plan at compile time. - refresh = forward_kinematics and (reset or refresh_kinematics) - native_program = self._model.compile_write(native_fields, reset=reset, forward_kinematic=refresh).allocate( - self._data - ) - for name in native_fields: - buffers[name] = torch.from_numpy(native_program[name]) - return _MotrixSimWriteProgram(self._data, buffers, native_program) + return self.allocate(reset=reset, refresh=forward_kinematics and (reset or refresh_kinematics)) + + @abstractmethod + def allocate(self, *, reset: bool, refresh: bool) -> WriteProgram: + """Bind the resolved fields to this device's simulator storage.""" def compile_body_joint_position(self, name: str, write: BodyJointPositionWrite) -> None: body = _named_body(self._model, write.body) @@ -94,7 +81,7 @@ def compile_body_joint_position(self, name: str, write: BodyJointPositionWrite) self._pending.append( ( name, - _CompiledWrite( + ResolvedWrite( native=mtx_write.BodyJointPosition([joint.name for joint in joints]), pos_indices=indices, refresh_kinematics=True, @@ -110,7 +97,7 @@ def compile_body_joint_velocity(self, name: str, write: BodyJointVelocityWrite) self._pending.append( ( name, - _CompiledWrite( + ResolvedWrite( native=mtx_write.BodyJointVelocity([joint.name for joint in joints]), vel_indices=indices, ), @@ -123,7 +110,7 @@ def compile_joint_position(self, name: str, write: JointPositionWrite) -> None: self._pending.append( ( name, - _CompiledWrite( + ResolvedWrite( native=mtx_write.BodyJointPosition([joint.name for joint in joints]), pos_indices=indices, refresh_kinematics=True, @@ -137,7 +124,7 @@ def compile_joint_velocity(self, name: str, write: JointVelocityWrite) -> None: self._pending.append( ( name, - _CompiledWrite( + ResolvedWrite( native=mtx_write.BodyJointVelocity([joint.name for joint in joints]), vel_indices=indices, ), @@ -145,14 +132,23 @@ def compile_joint_velocity(self, name: str, write: JointVelocityWrite) -> None: ) def compile_joint_quaternion(self, name: str, write: JointQuaternionWrite) -> None: - self._ball_joints(name, write.joints) + joints = self._ball_joints(name, write.joints) + indices = np.asarray([range(j.dof_pos_index, j.dof_pos_index + 4) for j in joints], dtype=np.int64) self._pending.append( - (name, _CompiledWrite(native=mtx_write.JointQuaternion(list(write.joints)), refresh_kinematics=True)) + ( + name, + ResolvedWrite( + pos_indices=indices, native=mtx_write.JointQuaternion(list(write.joints)), refresh_kinematics=True + ), + ) ) def compile_joint_angular_velocity(self, name: str, write: JointAngularVelocityWrite) -> None: - self._ball_joints(name, write.joints) - self._pending.append((name, _CompiledWrite(native=mtx_write.JointAngularVelocity(list(write.joints))))) + joints = self._ball_joints(name, write.joints) + indices = np.asarray([range(j.dof_vel_index, j.dof_vel_index + 3) for j in joints], dtype=np.int64) + self._pending.append( + (name, ResolvedWrite(vel_indices=indices, native=mtx_write.JointAngularVelocity(list(write.joints)))) + ) def compile_ctrl_targets(self, name: str, write: CtrlTargetsWrite) -> None: if write.actuators is None: @@ -167,7 +163,7 @@ def compile_ctrl_targets(self, name: str, write: CtrlTargetsWrite) -> None: [_named_actuator(self._model, actuator).index for actuator in write.actuators], dtype=np.int64 ) selection = list(write.actuators) - self._pending.append((name, _CompiledWrite(native=mtx_write.ActuatorCtrls(selection), ctrl_indices=indices))) + self._pending.append((name, ResolvedWrite(native=mtx_write.ActuatorCtrls(selection), ctrl_indices=indices))) def compile_body_position(self, name: str, write: BodyPositionWrite) -> None: bases = self._floating_bases(name, write.bodies, type(write).__name__) @@ -175,8 +171,8 @@ def compile_body_position(self, name: str, write: BodyPositionWrite) -> None: self._pending.append( ( name, - _CompiledWrite( - pos_indices=indices.ravel(), + ResolvedWrite( + pos_indices=indices, refresh_kinematics=True, native=mtx_write.BodyPosition(list(write.bodies)), ), @@ -189,8 +185,8 @@ def compile_body_rotation(self, name: str, write: BodyRotationWrite) -> None: self._pending.append( ( name, - _CompiledWrite( - pos_indices=indices.ravel(), + ResolvedWrite( + pos_indices=indices, refresh_kinematics=True, native=mtx_write.BodyRotation(list(write.bodies)), ), @@ -203,8 +199,8 @@ def compile_body_linear_velocity(self, name: str, write: BodyLinearVelocityWrite self._pending.append( ( name, - _CompiledWrite( - vel_indices=indices.ravel(), + ResolvedWrite( + vel_indices=indices, native=mtx_write.BodyLinearVelocity(list(write.bodies)), ), ) @@ -216,8 +212,8 @@ def compile_body_angular_velocity(self, name: str, write: BodyAngularVelocityWri self._pending.append( ( name, - _CompiledWrite( - vel_indices=indices.ravel(), + ResolvedWrite( + vel_indices=indices, native=mtx_write.BodyAngularVelocity(list(write.bodies)), ), ) @@ -226,34 +222,34 @@ def compile_body_angular_velocity(self, name: str, write: BodyAngularVelocityWri def compile_kinematic_body_position(self, name: str, write: KinematicBodyPositionWrite) -> None: self._mocaps(name, write.bodies) self._pending.append( - (name, _CompiledWrite(native=mtx_write.BodyPosition(list(write.bodies)), refresh_kinematics=True)) + (name, ResolvedWrite(native=mtx_write.BodyPosition(list(write.bodies)), refresh_kinematics=True)) ) def compile_kinematic_body_rotation(self, name: str, write: KinematicBodyRotationWrite) -> None: self._mocaps(name, write.bodies) self._pending.append( - (name, _CompiledWrite(native=mtx_write.BodyRotation(list(write.bodies)), refresh_kinematics=True)) + (name, ResolvedWrite(native=mtx_write.BodyRotation(list(write.bodies)), refresh_kinematics=True)) ) def compile_actuator_kp(self, name: str, write: ActuatorKpWrite) -> None: self._targets(name, write.actuators, "actuator", _named_actuator) - self._pending.append((name, _CompiledWrite(native=mtx_write.ActuatorKpOverride(list(write.actuators))))) + self._pending.append((name, ResolvedWrite(native=mtx_write.ActuatorKpOverride(list(write.actuators))))) def compile_actuator_damping(self, name: str, write: ActuatorDampingWrite) -> None: self._targets(name, write.actuators, "actuator", _named_actuator) - self._pending.append((name, _CompiledWrite(native=mtx_write.ActuatorDampingOverride(list(write.actuators))))) + self._pending.append((name, ResolvedWrite(native=mtx_write.ActuatorDampingOverride(list(write.actuators))))) def compile_link_mass(self, name: str, write: LinkMassWrite) -> None: self._targets(name, write.links, "link", _named_link) - self._pending.append((name, _CompiledWrite(native=mtx_write.LinkMassOverride(list(write.links))))) + self._pending.append((name, ResolvedWrite(native=mtx_write.LinkMassOverride(list(write.links))))) def compile_link_com(self, name: str, write: LinkComWrite) -> None: self._targets(name, write.links, "link", _named_link) - self._pending.append((name, _CompiledWrite(native=mtx_write.LinkCenterOfMassOverride(list(write.links))))) + self._pending.append((name, ResolvedWrite(native=mtx_write.LinkCenterOfMassOverride(list(write.links))))) def compile_geom_friction(self, name: str, write: GeomFrictionWrite) -> None: self._targets(name, write.geoms, "geom", _named_geom) - self._pending.append((name, _CompiledWrite(native=mtx_write.GeomFrictionOverride(list(write.geoms))))) + self._pending.append((name, ResolvedWrite(native=mtx_write.GeomFrictionOverride(list(write.geoms))))) def _joints(self, name: str, joint_names: tuple[str, ...]): if not joint_names: @@ -270,17 +266,20 @@ def _joints(self, name: str, joint_names: tuple[str, ...]): joints.append(joint) return joints - def _ball_joints(self, name: str, joint_names: tuple[str, ...]) -> None: + def _ball_joints(self, name: str, joint_names: tuple[str, ...]) -> list[mtx.Joint]: if not joint_names: raise ValueError(f"Simulator write {name!r} must declare at least one joint.") if len(set(joint_names)) != len(joint_names): raise ValueError(f"Simulator write {name!r} contains duplicate joint names.") + joints = [] for joint_name in joint_names: joint = self._model.get_joint(joint_name) if joint is None: raise KeyError(f"Unknown joint {joint_name!r} in write {name!r}.") if joint.num_dof_pos != 4 or joint.num_dof_vel != 3: raise ValueError(f"Simulator write joint {joint_name!r} in {name!r} must be a ball joint.") + joints.append(joint) + return joints def _require_single_dof_body(self, name: str, body_name: str, joints, channel: str) -> None: if joints and all(joint.num_dof_pos == 1 and joint.num_dof_vel == 1 for joint in joints): @@ -316,7 +315,7 @@ def _targets(self, name: str, names: tuple[str, ...], target_type: str, resolver @staticmethod def _claim(name: str, indices: np.ndarray, claimed: dict[int, str], channel: str) -> None: - for index in indices: + for index in indices.flat: previous = claimed.get(int(index)) if previous is not None: raise ValueError( @@ -325,7 +324,7 @@ def _claim(name: str, indices: np.ndarray, claimed: dict[int, str], channel: str claimed[int(index)] = name def _claim_ctrl_targets(self, name: str, indices: np.ndarray, owners: dict[int, str]) -> None: - for index in indices: + for index in indices.flat: existing = owners.get(int(index)) if existing is not None: target = self._model.actuators[int(index)].name @@ -333,6 +332,26 @@ def _claim_ctrl_targets(self, name: str, indices: np.ndarray, owners: dict[int, owners[int(index)] = name +class MotrixSimWriteCompiler(MotrixWriteCompiler): + def __init__(self, model: mtx.SceneModel, data: mtx.SceneData) -> None: + super().__init__(model) + self._data = data + + def allocate(self, *, reset: bool, refresh: bool) -> WriteProgram: + native_fields = {name: field.native for name, field in self._pending} + buffers: dict[str, torch.Tensor] = {} + native_program = None + if native_fields: + # Reset (restore defaults, then apply the writes) and the FK pass + # are baked into the native plan at compile time. + native_program = self._model.compile_write(native_fields, reset=reset, forward_kinematic=refresh).allocate( + self._data + ) + for name in native_fields: + buffers[name] = torch.from_numpy(native_program[name]) + return _MotrixSimWriteProgram(self._data, buffers, native_program) + + class _MotrixSimWriteProgram(WriteProgram): """Compiled MotrixSim writes with program-owned value buffers.""" diff --git a/motrix_env_motrixsim/tests/test_motrixsim_backend.py b/motrix_env_motrixsim/tests/test_motrixsim_backend.py index dd7656ee5..b7c53aa69 100644 --- a/motrix_env_motrixsim/tests/test_motrixsim_backend.py +++ b/motrix_env_motrixsim/tests/test_motrixsim_backend.py @@ -14,12 +14,14 @@ ActuatorCtrlQuery, ActuatorKdQuery, ActuatorKpQuery, + BatchLinkNetContactForceQuery, BodyAngularVelocityWrite, BodyJointPositionLimitsQuery, BodyJointPositionQuery, BodyJointPositionWrite, BodyJointVelocityQuery, BodyLinearVelocityWrite, + BodyLinkNetContactForceQuery, BodyPositionWrite, BodyRotationWrite, DofPositionLimitsQuery, @@ -31,12 +33,14 @@ JointVelocityQuery, LinkAngularVelocityQuery, LinkLinearVelocityQuery, + LinkNetContactForceQuery, LinkPositionQuery, LinkQuaternionQuery, + SensorValuesQuery, ) -from motrix_env_core.sim.model import SimModel +from motrix_env_core.sim.model import KinematicTreeQuery, SimModel from motrix_env_core.sim.registry import create_sim_backend, list_sim_backends -from motrix_env_core.sim.write import BodyJointVelocityWrite, CtrlTargetsWrite, JointVelocityWrite +from motrix_env_core.sim.write import BodyJointVelocityWrite, CtrlTargetsWrite, JointQuaternionWrite, JointVelocityWrite from motrix_env_motrixsim.compiler import MotrixSimSceneCompiler from motrix_env_motrixsim.runtime import MotrixSimBackend @@ -66,6 +70,12 @@ def test_motrixsim_backend_is_registered(): create_sim_backend("unknown") +def test_motrixsim_factory_defaults_to_cpu_and_rejects_other_device_types(): + assert create_sim_backend() is MotrixSimBackend + with pytest.raises(ValueError, match="does not support simulation on meta"): + create_sim_backend("motrixsim", "meta") + + def test_sim_cfg_configures_msd_world_before_build(): cfg = SimCfg( dt=0.005, @@ -517,3 +527,404 @@ def test_read_views_alias_arena_and_stay_conventionally_read_only(): # The backing numpy views stay non-writeable; torch cannot carry that # flag, so the read-only contract is documented on ``view``. assert not program._views["all_pos"].flags.writeable + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +def test_cuda_live_control_views_on_alternating_caller_streams(): + pytest.importorskip("motrixsim.gpu") + from motrix_env_core import registry + + cfg = registry.make_env_config("cartpole") + cfg.sim.device = "cuda:0" + device = torch.device(cfg.sim.device) + backend = create_sim_backend("motrixsim", device)(cfg.scene, cfg.sim, 3) + reads = backend.compile_reads({"ctrl": ActuatorCtrlQuery(), "alias": ActuatorCtrlQuery()}) + writes = backend.compile_action_writes({"ctrl": CtrlTargetsWrite()}) + controls = reads["ctrl"] + assert controls is reads["alias"] + assert controls.data_ptr() == writes.buffer("ctrl").data_ptr() + assert reads.arena_bytes == 0 + with pytest.raises(RuntimeError, match="full-batch"): + writes.execute(torch.tensor([1], device=device)) + with pytest.raises(RuntimeError, match="full-batch"): + writes.execute_masked(torch.tensor([False, True, False], device=device)) + streams = [torch.cuda.Stream(device=device), torch.cuda.Stream(device=device)] + caller = torch.cuda.current_stream(device) + for index, stream in enumerate(streams, 1): + stream.wait_stream(caller) + with torch.cuda.stream(stream): + writes.buffer("ctrl").fill_(index) + writes.execute() + reads.execute(torch.tensor([1], device=device)) + torch.testing.assert_close(controls, torch.full_like(controls, index)) + caller.wait_stream(stream) + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +@pytest.mark.parametrize("masked", [False, True]) +def test_cuda_control_staging_preserves_unselected_worlds(masked): + pytest.importorskip("motrixsim.gpu") + from motrix_env_core import registry + + cfg = registry.make_env_config("cartpole") + cfg.sim.device = "cuda:0" + backend = create_sim_backend("motrixsim", cfg.sim.device)(cfg.scene, cfg.sim, 3) + controls = backend.compile_reads({"ctrl": ActuatorCtrlQuery()})["ctrl"] + writes = backend.compile_writes({"ctrl": CtrlTargetsWrite()}) + initial = controls.clone() + writes.buffer("ctrl").copy_(initial + 1) + torch.testing.assert_close(controls, initial) + + if masked: + writes.execute_masked(torch.tensor([False, True, False], device=backend.device)) + else: + writes.execute(torch.tensor([1], device=backend.device)) + + initial[1] += 1 + torch.testing.assert_close(controls, initial) + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +def test_cuda_contact_reports_for_offset_load(tmp_path): + pytest.importorskip("motrixsim.gpu") + scene = tmp_path / "offset_contact.xml" + scene.write_text( + """ + + + + + + + + + + + + + """ + ) + device = torch.device("cuda:0") + backend = create_sim_backend("motrixsim", device)( + SceneCfg(file=scene), SimCfg(dt=0.005, gravity=(0, 0, -9.81), device=str(device)), 2 + ) + reads = backend.compile_reads( + { + "wrench": BodyLinkNetContactForceQuery(body="load"), + "link_wrench": LinkNetContactForceQuery(link="load"), + "batch_wrench": BatchLinkNetContactForceQuery(links=("load",)), + "reports": SensorValuesQuery(sensors=("pressure", "miss", "up", "down")), + } + ) + backend.step(180) + reads.execute() + + # The normal balances the 1 kg load, 0.1 m from its center of mass. + expected = torch.tensor([0, 0, 9.81, 0, -0.981, 0], device=device) + torch.testing.assert_close(reads["wrench"][:, 0], expected.expand(2, -1), atol=0.01, rtol=0.001) + reports = torch.tensor([9.81, 0, 0, 0, 1, 0, 0, -1], device=device) + torch.testing.assert_close(reads["reports"], reports.expand(2, -1), atol=0.01, rtol=0.001) + torch.testing.assert_close(reads["link_wrench"], reads["wrench"][:, 0]) + torch.testing.assert_close(reads["batch_wrench"], reads["wrench"]) + + untouched = reads["link_wrench"][1].clone() + mask = torch.tensor([True, False], device=device) + backend.reset_masked(mask) + reads.execute_masked(mask) + torch.testing.assert_close(reads["link_wrench"][0], torch.zeros_like(untouched)) + torch.testing.assert_close(reads["link_wrench"][1], untouched) + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +def test_cuda_compact_writes_route_rows_in_caller_order(): + pytest.importorskip("motrixsim.gpu") + from motrix_env_core import registry + + cfg = registry.make_env_config("dm-finger-spin", mode="play") + cfg.sim.device = "cuda:0" + device = torch.device(cfg.sim.device) + backend = create_sim_backend("motrixsim", device)(cfg.scene, cfg.sim, 4) + joints = ("distal", "hinge") + program = backend.compile_writes({"position": JointPositionWrite(joints)}, reset=True) + read = backend.compile_reads({"position": JointPositionQuery(joints=joints)}) + read.execute() + expected = read["position"].clone() + ids = torch.tensor([3, 0], device=device) + compact = torch.tensor([[0.2, -0.1], [-0.4, 0.3]], device=device) + staging = program.buffer("position") + staging[:2].copy_(compact) + program.execute_compact(ids, (staging,)) + read.execute() + expected[ids] = compact + torch.testing.assert_close(read["position"], expected) + with pytest.raises(ValueError, match="conflict"): + backend.compile_writes({"a": JointPositionWrite(joints), "b": JointPositionWrite(("hinge",))}) + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +def test_cuda_actuator_gains_skip_invalid_values_and_restore_selected_worlds(): + pytest.importorskip("motrixsim.gpu") + from motrix_env_core import registry + from motrix_env_core.sim.write import ActuatorDampingWrite, ActuatorKpWrite + + cfg = registry.make_env_config("go2-walk-flat") + cfg.sim.device = "cuda:0" + device = torch.device(cfg.sim.device) + backend = create_sim_backend("motrixsim", device)(cfg.scene, cfg.sim, 3) + actuators = backend.model.actuators[:2][::-1] + names = tuple(a.name for a in actuators) + gains = backend.compile_writes({"kp": ActuatorKpWrite(names), "kd": ActuatorDampingWrite(names)}) + reset = backend.compile_writes({}, reset=True) + rows = torch.tensor([2, 0], device=device) + for key in ("kp", "kd"): + gains.buffer(key)[:2] = gains.buffer(key).new_tensor([[3.5, float("nan")], [float("inf"), 0]]) + with backend.physics_stream(): + defaults = [(a.get_kp_override(backend.data), a.get_damping_override(backend.data)) for a in actuators] + gains.execute_compact(rows, (gains.buffer("kp"), gains.buffer("kd"))) + for restored in (False, True): + if restored: + reset.execute(rows[:1]) + with backend.physics_stream(): + for column, actuator in enumerate(actuators): + for initial, getter in zip(defaults[column], (actuator.get_kp_override, actuator.get_damping_override)): + expected = initial.copy() + if column == 0 and not restored: + expected[2] = 3.5 + elif column == 1: + expected[0] = 0 + np.testing.assert_array_equal(getter(backend.data), expected) + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +def test_cuda_reset_commits_final_parameter_values_once(monkeypatch): + pytest.importorskip("motrixsim.gpu") + from motrix_env_core import registry + from motrix_env_core.sim.write import LinkMassWrite + + cfg = registry.make_env_config("cartpole") + cfg.sim.device = "cuda:0" + backend = create_sim_backend("motrixsim", cfg.sim.device)(cfg.scene, cfg.sim, 3) + updates = backend.compile_writes({"mass": LinkMassWrite(("cart", "pole"))}) + reset = backend.compile_writes({"pole": LinkMassWrite(("pole",))}, reset=True) + get_cart_mass = backend.model.get_link("cart").get_mass_override + get_pole_mass = backend.model.get_link("pole").get_mass_override + with backend.physics_stream(): + cart_default = get_cart_mass(backend.data).copy() + pole_default = get_pole_mass(backend.data).copy() + updates.buffer("mass").copy_(updates.buffer("mass").new_tensor([[2, 5], [3, 6], [4, 7]])) + updates.execute() + reset.buffer("pole")[:, 0] = reset.buffer("pole").new_tensor([float("nan"), 8, 9]) + + commits = 0 + original_commit = backend.overrides.commit_link_inertia + + def record(warp_mask): + nonlocal commits + commits += 1 + original_commit(warp_mask) + + monkeypatch.setattr(backend.overrides, "commit_link_inertia", record) + reset.execute_masked(torch.tensor([True, False, True], device=backend.device)) + + assert commits == 1 + cart_default[1] = 3 + pole_default[1:] = [6, 9] + with backend.physics_stream(): + np.testing.assert_allclose(get_cart_mass(backend.data), cart_default) + np.testing.assert_allclose(get_pole_mass(backend.data), pole_default) + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +def test_cuda_parameter_overrides_match_sdk_setters_for_welded_links_and_colliders(tmp_path): + pytest.importorskip("motrixsim.gpu") + from motrix_env_core.sim.write import ( + ActuatorDampingWrite, + ActuatorKpWrite, + GeomFrictionWrite, + LinkComWrite, + LinkMassWrite, + ) + + scene = tmp_path / "welded_overrides.xml" + scene.write_text( + """ + + + + + + + + + + + + + + + + + + + + + """ + ) + sim_cfg = SimCfg(dt=0.005, device="cuda:0") + scene_cfg = SceneCfg(file=scene) + backend = create_sim_backend("motrixsim", sim_cfg.device)(scene_cfg, sim_cfg, 4) + reference = create_sim_backend("motrixsim", sim_cfg.device)(scene_cfg, sim_cfg, 4) + + writes = backend.compile_writes( + { + "mass": LinkMassWrite(("base", "welded_child", "arm")), + "com": LinkComWrite(("base", "welded_child")), + "friction": GeomFrictionWrite(("g1", "g2")), + "kp": ActuatorKpWrite(("act_root", "act_j1")), + "kd": ActuatorDampingWrite(("act_root", "act_j1")), + } + ) + device = backend.device + masses = torch.tensor([[3.1, 1.7, 0.9], [2.2, float("nan"), 1.1], [4.0, 0.8, 0.6], [2.5, 2.1, 1.3]], device=device) + coms = torch.tensor( + [ + [[0.05, -0.01, 0.02], [0.03, -0.02, 0.08]], + [[0.02, -0.03, 0.04], [-0.04, 0.09, -0.03]], + [[float("nan"), 0.0, 0.0], [0.08, 0.01, -0.05]], + [[-0.03, 0.04, 0.01], [0.02, -0.06, 0.07]], + ], + device=device, + ) + frictions = torch.tensor( + [ + [[1.1, 0.01, 0.001], [0.4, 0.02, 0.002]], + [[0.3, 0.01, 0.001], [float("nan"), 0.02, 0.002]], + [[0.9, 0.01, 0.001], [1.3, 0.02, 0.002]], + [[0.5, 0.01, 0.001], [0.9, 0.02, 0.002]], + ], + device=device, + ) + kps = torch.tensor([[15.0, 25.0], [10.0, float("nan")], [18.0, 30.0], [12.0, 22.0]], device=device) + kds = torch.tensor([[1.5, 2.5], [float("nan"), 1.0], [2.0, 3.0], [0.5, 1.2]], device=device) + + writes.buffer("mass").copy_(masses) + writes.buffer("com").copy_(coms) + writes.buffer("friction").copy_(frictions) + writes.buffer("kp").copy_(kps) + writes.buffer("kd").copy_(kds) + writes.execute_masked(torch.tensor([True, True, True, False], device=device)) + + with reference.physics_stream(): + for col, name in enumerate(("base", "welded_child", "arm")): + vals = masses[:, col].cpu().numpy() + vals[3] = np.nan + reference.model.get_link(name).set_mass_override(reference.data, vals) + for col, name in enumerate(("base", "welded_child")): + vals = coms[:, col].cpu().numpy() + vals[3] = np.nan + reference.model.get_link(name).set_center_of_mass_override(reference.data, vals) + for col, name in enumerate(("g1", "g2")): + vals = frictions[:, col, 0].cpu().numpy() + vals[3] = np.nan + reference.model.get_geom(name).set_friction_override(reference.data, vals) + for col, name in enumerate(("act_root", "act_j1")): + kp_vals = kps[:, col].cpu().numpy() + kd_vals = kds[:, col].cpu().numpy() + kp_vals[3] = np.nan + kd_vals[3] = np.nan + reference.model.get_actuator(name).set_kp_override(reference.data, kp_vals) + reference.model.get_actuator(name).set_damping_override(reference.data, kd_vals) + + backend.control.fill_(0.35) + reference.control.fill_(0.35) + backend.step(20) + reference.step(20) + torch.testing.assert_close(backend.position, reference.position, atol=1e-5, rtol=1e-5) + torch.testing.assert_close(backend.velocity, reference.velocity, atol=1e-5, rtol=1e-5) + + # Masked reset of world 0 restores every overridden domain to nominal defaults. + backend.reset_masked(torch.tensor([True, False, False, False], device=device)) + with backend.physics_stream(), reference.physics_stream(): + for name in ("base", "welded_child", "arm"): + assert np.isclose( + backend.model.get_link(name).get_mass_override(backend.data)[0], + reference.model.get_link(name).get_mass_override(reference.data)[3], + ) + for name in ("g1", "g2"): + assert np.isclose( + backend.model.get_geom(name).get_friction_override(backend.data)[0], + reference.model.get_geom(name).get_friction_override(reference.data)[3], + ) + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +def test_cuda_ball_joint_write_normalizes_each_quaternion(tmp_path): + pytest.importorskip("motrixsim.gpu") + scene = tmp_path / "ball.xml" + scene.write_text( + '' + '' + ) + device = torch.device("cuda:0") + backend = create_sim_backend("motrixsim", device)(SceneCfg(file=scene), SimCfg(device=str(device)), 2) + writes = backend.compile_writes({"ball": JointQuaternionWrite(("ball",))}) + reads = backend.compile_reads({"position": DofPositionQuery()}) + writes.buffer("ball")[:, 0] = torch.tensor([[0, 3, 0, 4], [0, 0, 0, 2]], device=device) + writes.execute() + reads.execute() + torch.testing.assert_close(reads["position"], torch.tensor([[0, 0.6, 0, 0.8], [0, 0, 0, 1]], device=device)) + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +@pytest.mark.parametrize("name", ["go2-walk-flat", "go2-walk-rough"]) +def test_cuda_metadata_and_terrain_follow_simulation_device(name): + pytest.importorskip("motrixsim.gpu") + from motrix_env_core import registry + + cfg = registry.make_env_config(name) + cpu = create_sim_backend("motrixsim")(cfg.scene, cfg.sim, 1) + cfg.sim.device = "cuda:0" + device = torch.device(cfg.sim.device) + backend = create_sim_backend("motrixsim", device)(cfg.scene, cfg.sim, 1) + body = cfg.scene.objs.robot.resolved_base_link_name + model = backend.compile_model({"tree": KinematicTreeQuery(body), "host": KinematicTreeQuery(body, "cpu")}) + assert ( + model.init_dof_pos.device + == model.bodies["robot"].init_joint_pos.device + == model.others["tree"].axes.device + == device + ) + assert model.others["host"].axes.device.type == "cpu" + ids = torch.tensor([0]) + xy = torch.tensor([[[0.0, 0.0], [0.25, 0.25]]]) + expected = cpu.sample_terrain_height(cfg.ground_geom_name, ids, xy) + actual = backend.sample_terrain_height(cfg.ground_geom_name, ids, xy) + assert actual.device == device + torch.testing.assert_close(actual.cpu(), expected, atol=5e-3, rtol=1e-3) + with pytest.raises(KeyError, match="absent"): + backend.sample_terrain_height("absent", ids, xy) + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires NVIDIA CUDA") +def test_cuda_manager_keeps_captured_read_inputs_alive(): + pytest.importorskip("motrixsim.gpu") + from motrix_env_core import registry + + env = registry.make("g1-wbt-dance", num_envs=16, seed=7, sim_device="cuda:0") + actions = torch.zeros((env.num_envs, *env.action_space.shape), device=env.device) + env.initialize() + for _ in range(4): + state = env.step(actions) + torch.testing.assert_close(state.reward, torch.nan_to_num(state.reward)) + torch.testing.assert_close(state.obs.policy, torch.nan_to_num(state.obs.policy)) + assert (env.engine_error_codes == 0).all() diff --git a/motrix_env_mujoco/src/motrix_env_mujoco/backend.py b/motrix_env_mujoco/src/motrix_env_mujoco/backend.py index 833477256..72e106924 100644 --- a/motrix_env_mujoco/src/motrix_env_mujoco/backend.py +++ b/motrix_env_mujoco/src/motrix_env_mujoco/backend.py @@ -8,7 +8,7 @@ import torch from motrix_env_core.config.sim import SimCfg -from motrix_env_core.sim.backend import SimBackend, SimBackendCapabilities +from motrix_env_core.sim.backend import RenderConfig, SimBackend, SimBackendCapabilities from motrix_env_core.sim.model import SimModelCompiler from motrix_env_core.sim.read import PhysicsReadProgram from motrix_env_mujoco.compiler import MuJoCoSceneCompiler @@ -33,8 +33,8 @@ class MuJoCoSimBackend(SimBackend): _GAP = "MuJoCo only compiles scene models; it provides no live simulation." - def __init__(self, scene, sim: SimCfg, num_envs: int) -> None: - super().__init__(scene, sim, num_envs) + def __init__(self, scene, sim: SimCfg, num_envs: int, *, render: RenderConfig | None = None) -> None: + super().__init__(scene, sim, num_envs, render=render) self._mujoco_model = MuJoCoSceneCompiler().compile(scene, sim) @property diff --git a/motrix_env_mujoco/src/motrix_env_mujoco/register.py b/motrix_env_mujoco/src/motrix_env_mujoco/register.py index 103287f3f..353d92a29 100644 --- a/motrix_env_mujoco/src/motrix_env_mujoco/register.py +++ b/motrix_env_mujoco/src/motrix_env_mujoco/register.py @@ -8,6 +8,9 @@ simulation, so it never claims the default slot. """ +import torch + +from motrix_env_core.sim.backend import SimBackend from motrix_env_core.sim.registry import register_sim_backend @@ -19,7 +22,9 @@ def _install_hint(exc: ModuleNotFoundError) -> ModuleNotFoundError: return exc -def _sim_backend(): +def _sim_backend(device: torch.device) -> type[SimBackend]: + if device.type != "cpu": + raise ValueError(f"MuJoCo does not support simulation on {device}") try: from motrix_env_mujoco.backend import MuJoCoSimBackend except ModuleNotFoundError as exc: diff --git a/motrix_env_mujoco/tests/test_mujoco_scene_compiler.py b/motrix_env_mujoco/tests/test_mujoco_scene_compiler.py index ddba30d78..7ff3f64e6 100644 --- a/motrix_env_mujoco/tests/test_mujoco_scene_compiler.py +++ b/motrix_env_mujoco/tests/test_mujoco_scene_compiler.py @@ -45,8 +45,10 @@ def test_mujoco_backend_is_registered_and_loaded_lazily(): assert isinstance(MuJoCoSceneCompiler().compile(SceneCfg(), SimCfg()), mj.MjModel) # Compile-only backend: construction compiles the scene, behavior gaps loudly. + from motrix_env_core.renderer import RenderConfig + assert not MuJoCoSimBackend.capabilities.env_creation - backend = MuJoCoSimBackend(SceneCfg(), SimCfg(), 1) + backend = MuJoCoSimBackend(SceneCfg(), SimCfg(), 1, render=RenderConfig(headless=True)) with pytest.raises(NotImplementedError, match="no live simulation"): backend.compile_reads({}) with pytest.raises(NotImplementedError): @@ -367,3 +369,10 @@ class RobotObjsCfg(SceneObjsCfg): assert model.actuator_forcerange[actuator_id] == pytest.approx([-5.0, 5.0]) assert model.actuator_gainprm[actuator_id, 0] == pytest.approx(20.0) assert model.actuator_biasprm[actuator_id, :3] == pytest.approx([0.0, -20.0, -2.0]) + + +def test_mujoco_factory_rejects_cuda(): + from motrix_env_core.sim.registry import create_sim_backend + + with pytest.raises(ValueError, match="MuJoCo does not support simulation on cuda:0"): + create_sim_backend("mujoco", "cuda:0") diff --git a/motrix_envs/src/motrix_envs/basic/acrobot/acrobot_np.py b/motrix_envs/src/motrix_envs/basic/acrobot/acrobot_np.py index c794cbe04..b039c6dd6 100644 --- a/motrix_envs/src/motrix_envs/basic/acrobot/acrobot_np.py +++ b/motrix_envs/src/motrix_envs/basic/acrobot/acrobot_np.py @@ -59,7 +59,7 @@ def __init__( ) self._target_radius = 0.2 - self._step_count = torch.zeros(self._num_envs, dtype=torch.int64) + self._step_count = torch.zeros(self._num_envs, dtype=torch.int64, device=self.device) self._max_steps = int(cfg.max_episode_seconds / cfg.ctrl_dt) @property @@ -119,6 +119,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: sigmoid="linear", ), dtype=torch.float32, + device=self.device, ) in_target = dist_to_target < self._target_radius @@ -148,11 +149,11 @@ def reset(self, env_ids: torch.Tensor) -> None: num_reset = env_ids.numel() self._step_count[env_ids] = 0 - shoulder_angle = (torch.rand(num_reset, dtype=torch.float32) * 2.0 - 1.0) * np.pi - elbow_angle = (torch.rand(num_reset, dtype=torch.float32) * 2.0 - 1.0) * np.pi + shoulder_angle = (torch.rand(num_reset, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * np.pi + elbow_angle = (torch.rand(num_reset, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * np.pi dof_pos = torch.stack([shoulder_angle, elbow_angle], dim=-1) - dof_vel = torch.zeros((num_reset, 2), dtype=torch.float32) + dof_vel = torch.zeros((num_reset, 2), dtype=torch.float32, device=self.device) self._reset_position[env_ids] = dof_pos self._reset_velocity[env_ids] = dof_vel diff --git a/motrix_envs/src/motrix_envs/basic/bounce_ball/bounce_ball_np.py b/motrix_envs/src/motrix_envs/basic/bounce_ball/bounce_ball_np.py index ea4596ef4..a706c8424 100644 --- a/motrix_envs/src/motrix_envs/basic/bounce_ball/bounce_ball_np.py +++ b/motrix_envs/src/motrix_envs/basic/bounce_ball/bounce_ball_np.py @@ -84,11 +84,11 @@ def __init__( # Episode-scoped task state: full-batch buffers, reset writes the # done rows in place. num_envs = self._num_envs - self._ball_was_upward = torch.zeros(num_envs, dtype=torch.bool) - self._consecutive_bounces = torch.zeros(num_envs, dtype=torch.int32) - self._target_heights = torch.zeros(num_envs, dtype=torch.float32) - self._current_actions = torch.zeros((num_envs, 6), dtype=torch.float32) - self._last_actions = torch.zeros((num_envs, 6), dtype=torch.float32) + self._ball_was_upward = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._consecutive_bounces = torch.zeros(num_envs, dtype=torch.int32, device=self.device) + self._target_heights = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._current_actions = torch.zeros((num_envs, 6), dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros((num_envs, 6), dtype=torch.float32, device=self.device) # Observation space: joint states + paddle position + target height (29D) self._observation_spec = ObservationSpec( @@ -96,15 +96,17 @@ def __init__( ) # Initial arm joint positions - self._init_arm_qpos = torch.tensor(self._cfg.arm_init_qpos, dtype=torch.float32) * torch.pi / 180.0 + self._init_arm_qpos = ( + torch.tensor(self._cfg.arm_init_qpos, dtype=torch.float32, device=self.device) * torch.pi / 180.0 + ) # Action scaling - self._action_scale = torch.tensor(self._cfg.action_scale, dtype=torch.float32) - self._action_bias = torch.tensor(self._cfg.action_bias, dtype=torch.float32) + self._action_scale = torch.tensor(self._cfg.action_scale, dtype=torch.float32, device=self.device) + self._action_bias = torch.tensor(self._cfg.action_bias, dtype=torch.float32, device=self.device) # Ball initial conditions - self._ball_init_pos = torch.tensor(self._cfg.ball_init_pos, dtype=torch.float32) - self._ball_init_vel = torch.tensor(self._cfg.ball_init_vel, dtype=torch.float32) + self._ball_init_pos = torch.tensor(self._cfg.ball_init_pos, dtype=torch.float32, device=self.device) + self._ball_init_vel = torch.tensor(self._cfg.ball_init_vel, dtype=torch.float32, device=self.device) # Constants for marker poses self._ball_radius = 0.019 # Ball radius in meters @@ -120,6 +122,7 @@ def __init__( 1.0, # identity quaternion ], dtype=torch.float32, + device=self.device, ) # Paddle home marker pose: [x, y, z, qx, qy, qz, qw] self._paddle_home_marker_pose = torch.tensor( @@ -133,6 +136,7 @@ def __init__( 1.0, # identity quaternion ], dtype=torch.float32, + device=self.device, ) @property @@ -568,23 +572,31 @@ def reset(self, env_ids: torch.Tensor) -> None: # Randomize target heights for the environments being reset if cfg.randomize_target_height: min_height, max_height = cfg.target_height_range - new_target_heights = torch.rand(num_reset, dtype=torch.float32) * (max_height - min_height) + min_height + new_target_heights = ( + torch.rand(num_reset, dtype=torch.float32, device=self.device) * (max_height - min_height) + min_height + ) else: # Use mean of target_height_range when not randomizing default_height = sum(cfg.target_height_range) / 2.0 - new_target_heights = torch.full((num_reset,), default_height, dtype=torch.float32) + new_target_heights = torch.full((num_reset,), default_height, dtype=torch.float32, device=self.device) # Add noise to initial arm joint positions only (not ball) - arm_noise_pos = (torch.rand(num_reset, 6, dtype=torch.float32) * 2.0 - 1.0) * cfg.reset_noise_scale - arm_vel = (torch.rand(num_reset, 6, dtype=torch.float32) * 2.0 - 1.0) * cfg.reset_noise_scale + arm_noise_pos = ( + torch.rand(num_reset, 6, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * cfg.reset_noise_scale + arm_vel = ( + torch.rand(num_reset, 6, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * cfg.reset_noise_scale arm_pos = self._init_arm_qpos.tile((num_reset, 1)) + arm_noise_pos - ball_pos = self._ball_init_pos + (torch.rand(num_reset, 3, dtype=torch.float32) * 2.0 - 1.0) * 0.01 + ball_pos = ( + self._ball_init_pos + (torch.rand(num_reset, 3, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * 0.01 + ) self._arm_reset_position[env_ids] = arm_pos self._arm_reset_velocity[env_ids] = arm_vel self._ball_reset_position[env_ids] = ball_pos - self._ball_reset_rotation[env_ids] = torch.tensor([0.0, 0.0, 0.0, 1.0], dtype=torch.float32) + self._ball_reset_rotation[env_ids] = torch.tensor([0.0, 0.0, 0.0, 1.0], dtype=torch.float32, device=self.device) self._ball_reset_linear_velocity[env_ids] = 0.0 self._ball_reset_angular_velocity[env_ids] = 0.0 self._reset_program.execute(env_ids) diff --git a/motrix_envs/src/motrix_envs/basic/cartpole/cartpole_np.py b/motrix_envs/src/motrix_envs/basic/cartpole/cartpole_np.py index fd43516ab..0eb810100 100644 --- a/motrix_envs/src/motrix_envs/basic/cartpole/cartpole_np.py +++ b/motrix_envs/src/motrix_envs/basic/cartpole/cartpole_np.py @@ -39,7 +39,7 @@ def __init__( super().__init__(cfg, num_envs, backend=backend, **kwargs) self.model = self.sim.compile_model(_SIM_MODEL_QUERIES) self.sim_data = self.sim.compile_reads(_SIM_DATA_QUERIES) - self._ctrl_writes = self.sim.write_compiler.compile({"ctrl": CtrlTargetsWrite()}) + self._ctrl_writes = self.sim.compile_action_writes({"ctrl": CtrlTargetsWrite()}) self._reset_program = self.sim.write_compiler.compile( { "cartpole_position": JointPositionWrite(("slider", "hinge")), @@ -91,8 +91,8 @@ def reset(self, env_ids: torch.Tensor) -> None: cfg: CartPoleEnvCfg = self._cfg rows = env_ids.numel() scale = cfg.reset_noise_scale - dof_pos = (torch.rand(rows, 2, dtype=torch.float32) * 2.0 - 1.0) * scale - dof_vel = (torch.rand(rows, 2, dtype=torch.float32) * 2.0 - 1.0) * scale + dof_pos = (torch.rand(rows, 2, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * scale + dof_vel = (torch.rand(rows, 2, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * scale self._reset_position[env_ids] = dof_pos self._reset_velocity[env_ids] = dof_vel diff --git a/motrix_envs/src/motrix_envs/basic/cheetah/cheetah_np.py b/motrix_envs/src/motrix_envs/basic/cheetah/cheetah_np.py index a874b9728..a15de063d 100644 --- a/motrix_envs/src/motrix_envs/basic/cheetah/cheetah_np.py +++ b/motrix_envs/src/motrix_envs/basic/cheetah/cheetah_np.py @@ -107,6 +107,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: sigmoid="linear", ), dtype=torch.float32, + device=self.device, ) torso_height = inputs["torso_pos"][:, 2] @@ -122,8 +123,8 @@ def compute_transition(self, state: ArrayEnvState) -> None: def reset(self, env_ids: torch.Tensor) -> None: num = env_ids.numel() - qpos = torch.zeros((num, self._reset_position.shape[1]), dtype=torch.float32) - dof_vel = torch.zeros((num, self._reset_velocity.shape[1]), dtype=torch.float32) + qpos = torch.zeros((num, self._reset_position.shape[1]), dtype=torch.float32, device=self.device) + dof_vel = torch.zeros((num, self._reset_velocity.shape[1]), dtype=torch.float32, device=self.device) self._reset_position[env_ids] = qpos self._reset_velocity[env_ids] = dof_vel self._reset_program.execute(env_ids) diff --git a/motrix_envs/src/motrix_envs/basic/finger/finger_np.py b/motrix_envs/src/motrix_envs/basic/finger/finger_np.py index 624841e86..e34620ef1 100644 --- a/motrix_envs/src/motrix_envs/basic/finger/finger_np.py +++ b/motrix_envs/src/motrix_envs/basic/finger/finger_np.py @@ -111,7 +111,7 @@ def __init__( else None ) - self._target_xyz = torch.zeros((num_envs, 3), dtype=torch.float32) + self._target_xyz = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) self._target_radius = float(cfg.target_radius) self._spin_vel_threshold = float(cfg.spin_velocity_threshold) @@ -129,8 +129,8 @@ def _init_action_space(self): # Episode-scoped action history: full-batch buffers, reset writes the # done rows in place. - self._actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32) - self._last_actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32) + self._actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32, device=self.device) @property def observation_spec(self) -> ObservationSpec: @@ -161,7 +161,9 @@ def _reset_target(self, env_ids: torch.Tensor, positions: torch.Tensor) -> None: if self._target_reset is None: return self._target_reset.buffer("target_position")[env_ids, 0] = positions - self._target_reset.buffer("target_rotation")[env_ids, 0] = torch.tensor([0.0, 0.0, 0.0, 1.0]) + self._target_reset.buffer("target_rotation")[env_ids, 0] = torch.tensor( + [0.0, 0.0, 0.0, 1.0], device=self.device + ) self._target_reset.buffer("target_linear_velocity")[env_ids, 0] = 0.0 self._target_reset.buffer("target_angular_velocity")[env_ids, 0] = 0.0 self._target_reset.execute(env_ids) @@ -174,7 +176,7 @@ def _reset_collision_free_joint_angles(self, env_ids: torch.Tensor): positions = self._joint_resets.buffer("joints_position") velocities = self._joint_resets.buffer("joints_velocity") velocities[env_ids] = 0.0 - pending = torch.ones((num,), dtype=torch.bool) + pending = torch.ones((num,), dtype=torch.bool, device=self.device) for _ in range(max_attempts): if not bool(pending.any()): break @@ -183,15 +185,17 @@ def _reset_collision_free_joint_angles(self, env_ids: torch.Tensor): for column in range(2): low = float(self._joint_limit_low[column]) high = float(self._joint_limit_high[column]) - positions[env_ids[pending], column] = (torch.rand(num_pending, dtype=torch.float32) * 2.0 - 1.0) * ( - (high - low) / 2.0 - ) + (high + low) / 2.0 + positions[env_ids[pending], column] = ( + torch.rand(num_pending, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * ((high - low) / 2.0) + (high + low) / 2.0 - positions[env_ids[pending], 2] = (torch.rand(num_pending, dtype=torch.float32) * 2.0 - 1.0) * np.pi + positions[env_ids[pending], 2] = ( + torch.rand(num_pending, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * np.pi self._joint_resets.execute(env_ids) if self._target_reset is not None: - self._reset_target(env_ids, torch.tile(torch.tensor([0.0, 0.0, 0.4]), (num, 1))) + self._reset_target(env_ids, torch.tile(torch.tensor([0.0, 0.0, 0.4], device=self.device), (num, 1))) self.sim_data.execute(env_ids) # Contact iff any declared collidable geom pair is colliding; this # reproduces the legacy global ``num_contacts > 0`` check exactly. @@ -237,10 +241,10 @@ def compute_transition(self, state: ArrayEnvState) -> None: else: spin = spin_sparse - touch_raw = torch.zeros((self._num_envs,), dtype=torch.float32) - touch_bonus = torch.zeros((self._num_envs,), dtype=torch.float32) - approach_dist = torch.zeros((self._num_envs,), dtype=torch.float32) - approach_reward = torch.zeros((self._num_envs,), dtype=torch.float32) + touch_raw = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) + touch_bonus = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) + approach_dist = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) + approach_reward = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) if self._cfg.reward_mode == "shaped": if float(getattr(self._cfg, "spin_touch_bonus_scale", 0.0)) > 0.0: @@ -318,12 +322,12 @@ def compute_transition(self, state: ArrayEnvState) -> None: dist_to_target = self._dist_to_target(slice(None)) turn_sparse = (dist_to_target <= 0.0).float() - touch_raw = torch.zeros((self._num_envs,), dtype=torch.float32) - touch_bonus = torch.zeros((self._num_envs,), dtype=torch.float32) - approach_dist = torch.zeros((self._num_envs,), dtype=torch.float32) - approach_reward = torch.zeros((self._num_envs,), dtype=torch.float32) - action_l2 = torch.zeros((self._num_envs,), dtype=torch.float32) - action_delta_l2 = torch.zeros((self._num_envs,), dtype=torch.float32) + touch_raw = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) + touch_bonus = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) + approach_dist = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) + approach_reward = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) + action_l2 = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) + action_delta_l2 = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) if self._cfg.reward_mode == "shaped": # Encourage approaching the spinner so the agent actually makes contact and can rotate it. @@ -406,7 +410,7 @@ def reset(self, env_ids: torch.Tensor) -> None: # Match dm_control: radius = cap1.geom_size.sum() for capsule (radius + half-length). cap1_size = self.model.others["geoms"]["cap1"].size radius = float(sum(cap1_size[:2])) - target_angle = (torch.rand(num, dtype=torch.float32) * 2.0 - 1.0) * np.pi + target_angle = (torch.rand(num, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * np.pi target_x = hinge_xyz[:, 0] + radius * torch.sin(target_angle) target_z = hinge_xyz[:, 2] + radius * torch.cos(target_angle) self._target_xyz[env_ids] = torch.stack([target_x, hinge_xyz[:, 1], target_z], dim=-1) diff --git a/motrix_envs/src/motrix_envs/basic/hopper/hopper_np.py b/motrix_envs/src/motrix_envs/basic/hopper/hopper_np.py index ef57c7a30..11e91e80e 100644 --- a/motrix_envs/src/motrix_envs/basic/hopper/hopper_np.py +++ b/motrix_envs/src/motrix_envs/basic/hopper/hopper_np.py @@ -144,6 +144,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: margin=self._stand_height * 0.5, ), dtype=torch.float32, + device=self.device, ) if self._hop_speed > 0.0: @@ -156,6 +157,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: sigmoid="linear", ), dtype=torch.float32, + device=self.device, ) leg_vel = torch.linalg.norm(dof_vel[:, 4:7], dim=-1) @@ -197,6 +199,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: sigmoid="quadratic", ), dtype=torch.float32, + device=self.device, ) small_control = (small_control + 4) / 5 @@ -212,7 +215,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: def reset(self, env_ids: torch.Tensor) -> None: num_reset = env_ids.numel() - dof_pos = torch.zeros((num_reset, self._reset_position.shape[1]), dtype=torch.float32) + dof_pos = torch.zeros((num_reset, self._reset_position.shape[1]), dtype=torch.float32, device=self.device) dof_pos[:, 2] = 0 @@ -220,11 +223,12 @@ def reset(self, env_ids: torch.Tensor) -> None: lower = self._joint_pos_lower[3:] upper = self._joint_pos_upper[3:] dof_pos[:, 3:] = ( - torch.rand((num_reset, self._reset_position.shape[1] - 3), dtype=torch.float32) * (upper - lower) + torch.rand((num_reset, self._reset_position.shape[1] - 3), dtype=torch.float32, device=self.device) + * (upper - lower) + lower ) - dof_vel = torch.zeros((num_reset, self._reset_velocity.shape[1]), dtype=torch.float32) + dof_vel = torch.zeros((num_reset, self._reset_velocity.shape[1]), dtype=torch.float32, device=self.device) self._reset_position[env_ids] = dof_pos self._reset_velocity[env_ids] = dof_vel diff --git a/motrix_envs/src/motrix_envs/basic/humanoid/humanoid_np.py b/motrix_envs/src/motrix_envs/basic/humanoid/humanoid_np.py index c195205e4..28142f2cc 100644 --- a/motrix_envs/src/motrix_envs/basic/humanoid/humanoid_np.py +++ b/motrix_envs/src/motrix_envs/basic/humanoid/humanoid_np.py @@ -101,7 +101,7 @@ def __init__( self._move_speed = float(cfg.move_speed) self._stand_height = float(cfg.stand_height) - self._target_direction = torch.tensor([1.0, 0.0, 0.0], dtype=torch.float32) + self._target_direction = torch.tensor([1.0, 0.0, 0.0], dtype=torch.float32, device=self.device) self._target_direction_xy = self._target_direction[:2].clone() self._qpos_low, self._qpos_high = self._build_qpos_limits() @@ -441,21 +441,25 @@ def _randomize_joints(self, env_ids: torch.Tensor) -> None: num_actuators = int(self.num_actuators) low, high = self._qpos_low, self._qpos_high - qpos = torch.zeros((n, num_dof_pos), dtype=torch.float32) + qpos = torch.zeros((n, num_dof_pos), dtype=torch.float32, device=self.device) qpos[:, 2] = self._reset_height qpos[:, 3] = 1.0 # qpos 7=abdomen_z (yaw), 8=abdomen_y (pitch), 9=abdomen_x (roll) per humanoid.xml - qpos[:, 7] = torch.empty(n, dtype=torch.float32).uniform_(*self._hip_yaw_range) - qpos[:, 8] = torch.empty(n, dtype=torch.float32).uniform_(*self._hip_pitch_range) - qpos[:, 9] = torch.empty(n, dtype=torch.float32).uniform_(*self._hip_roll_range) + qpos[:, 7] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_(*self._hip_yaw_range) + qpos[:, 8] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_(*self._hip_pitch_range) + qpos[:, 9] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_(*self._hip_roll_range) self._randomize_symmetric_legs(qpos, n, num_dof_pos, low, high) self._randomize_symmetric_arms(qpos, n, num_dof_pos, low, high) self._randomize_remaining_joints(qpos, n, num_dof_pos, low, high) - qvel = (torch.rand(n, num_dof_vel, dtype=torch.float32) * 2.0 - 1.0) * self._reset_qvel_range - actuator_ctrls = (torch.rand(n, num_actuators, dtype=torch.float32) * 2.0 - 1.0) * self._reset_actuator_range + qvel = ( + torch.rand(n, num_dof_vel, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * self._reset_qvel_range + actuator_ctrls = ( + torch.rand(n, num_actuators, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * self._reset_actuator_range torso_pose = qpos[:, :7].clone() torso_pose[:, 3:7] = torch.cat([qpos[:, 4:7], qpos[:, 3:4]], dim=1) @@ -479,15 +483,19 @@ def _randomize_symmetric_legs( ) -> None: for left_idx, right_idx, (min_rad, max_rad) in self._symmetric_leg_pairs_rad: if left_idx < num_dof_pos: - lo = float(torch.clamp(torch.tensor(min_rad), low[left_idx], high[left_idx])) - hi = float(torch.clamp(torch.tensor(max_rad), low[left_idx], high[left_idx])) - qpos[:, left_idx] = torch.empty(n, dtype=torch.float32).uniform_(lo, hi) + lo = float(torch.clamp(torch.tensor(min_rad, device=self.device), low[left_idx], high[left_idx])) + hi = float(torch.clamp(torch.tensor(max_rad, device=self.device), low[left_idx], high[left_idx])) + qpos[:, left_idx] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_(lo, hi) if right_idx < num_dof_pos: right_min_rad = -max_rad right_max_rad = -min_rad - lo = float(torch.clamp(torch.tensor(right_min_rad), low[right_idx], high[right_idx])) - hi = float(torch.clamp(torch.tensor(right_max_rad), low[right_idx], high[right_idx])) - qpos[:, right_idx] = torch.empty(n, dtype=torch.float32).uniform_(lo, hi) + lo = float( + torch.clamp(torch.tensor(right_min_rad, device=self.device), low[right_idx], high[right_idx]) + ) + hi = float( + torch.clamp(torch.tensor(right_max_rad, device=self.device), low[right_idx], high[right_idx]) + ) + qpos[:, right_idx] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_(lo, hi) def _randomize_symmetric_arms( self, qpos: torch.Tensor, n: int, num_dof_pos: int, low: torch.Tensor, high: torch.Tensor @@ -515,16 +523,18 @@ def _randomize_symmetric_arms( right_max_clipped = min(right_max, hi_r) if left_min < left_max: - qpos[:, left_idx] = torch.empty(n, dtype=torch.float32).uniform_(left_min, left_max) + qpos[:, left_idx] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_( + left_min, left_max + ) else: - qpos[:, left_idx] = torch.empty(n, dtype=torch.float32).uniform_(lo_l, hi_l) + qpos[:, left_idx] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_(lo_l, hi_l) if right_min_clipped < right_max_clipped: - qpos[:, right_idx] = torch.empty(n, dtype=torch.float32).uniform_( + qpos[:, right_idx] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_( right_min_clipped, right_max_clipped ) else: - qpos[:, right_idx] = torch.empty(n, dtype=torch.float32).uniform_(lo_r, hi_r) + qpos[:, right_idx] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_(lo_r, hi_r) def _randomize_remaining_joints( self, qpos: torch.Tensor, n: int, num_dof_pos: int, low: torch.Tensor, high: torch.Tensor @@ -538,4 +548,4 @@ def _randomize_remaining_joints( if i not in used_indices: lo = float(low[i]) if torch.isfinite(low[i]) else default_lo hi = float(high[i]) if torch.isfinite(high[i]) else default_hi - qpos[:, i] = torch.empty(n, dtype=torch.float32).uniform_(lo, hi) + qpos[:, i] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_(lo, hi) diff --git a/motrix_envs/src/motrix_envs/basic/lqr/lqr_np.py b/motrix_envs/src/motrix_envs/basic/lqr/lqr_np.py index ea4b4e287..92424c41a 100644 --- a/motrix_envs/src/motrix_envs/basic/lqr/lqr_np.py +++ b/motrix_envs/src/motrix_envs/basic/lqr/lqr_np.py @@ -71,8 +71,8 @@ def __init__( obs_dim = self._nq + self._nv ctrl_ranges = np.asarray([spec.ctrl_range for spec in self.model.actuators], dtype=np.float32) - self._action_low = torch.from_numpy(ctrl_ranges[:, 0].copy()) - self._action_high = torch.from_numpy(ctrl_ranges[:, 1].copy()) + self._action_low = torch.from_numpy(ctrl_ranges[:, 0].copy()).to(self.device) + self._action_high = torch.from_numpy(ctrl_ranges[:, 1].copy()).to(self.device) self._observation_spec = ObservationSpec( {"policy": ObservationGroupSpec(gym.spaces.Box(-np.inf, np.inf, (obs_dim,), dtype=np.float32))} ) @@ -148,7 +148,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: def reset(self, env_ids: torch.Tensor) -> None: num_envs = env_ids.numel() - qpos = torch.randn(num_envs, self._nq, dtype=torch.float32) + qpos = torch.randn(num_envs, self._nq, dtype=torch.float32, device=self.device) norms = torch.linalg.norm(qpos, dim=-1, keepdim=True) zero_norm = norms[:, 0] < 1e-8 if zero_norm.any(): @@ -156,7 +156,7 @@ def reset(self, env_ids: torch.Tensor) -> None: norms = torch.linalg.norm(qpos, dim=-1, keepdim=True) qpos *= self._cfg.reset_position_norm / norms.clamp_min(1e-8) - qvel = torch.zeros((num_envs, self._nv), dtype=torch.float32) + qvel = torch.zeros((num_envs, self._nv), dtype=torch.float32, device=self.device) self._reset_position[env_ids] = qpos self._reset_velocity[env_ids] = qvel self._reset_program.execute(env_ids) diff --git a/motrix_envs/src/motrix_envs/basic/manipulator/manipulator_np.py b/motrix_envs/src/motrix_envs/basic/manipulator/manipulator_np.py index e7ef91e45..cb969f707 100644 --- a/motrix_envs/src/motrix_envs/basic/manipulator/manipulator_np.py +++ b/motrix_envs/src/motrix_envs/basic/manipulator/manipulator_np.py @@ -85,11 +85,8 @@ def _quat_from_y_angle(angle: torch.Tensor) -> torch.Tensor: def _quat_to_z_axis(quat: torch.Tensor) -> torch.Tensor: - axis = torch.tensor([0.0, 0.0, 1.0], dtype=quat.dtype) - w = quat[..., 3:4] - im = quat[..., :3] - t = 2.0 * torch.cross(im, axis.expand_as(im), dim=-1) - return axis + w * t + torch.cross(im, t, dim=-1) + x, y, z, w = quat.unbind(dim=-1) + return torch.stack((2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x.square() + y.square())), dim=-1) def _tolerance( @@ -154,17 +151,17 @@ def __init__( # Episode-scoped action history: full-batch buffers, reset writes the # done rows in place. - self._actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32) - self._last_actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32) - self._prev_move_dist = torch.zeros(self._num_envs, dtype=torch.float32) + self._actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32, device=self.device) + self._prev_move_dist = torch.zeros(self._num_envs, dtype=torch.float32, device=self.device) def _init_action_space(self): ctrl_ranges = np.asarray([spec.ctrl_range for spec in self.model.actuators], dtype=np.float32) self._action_space = gym.spaces.Box( ctrl_ranges[:, 0], ctrl_ranges[:, 1], (self.num_actuators,), dtype=np.float32 ) - self._act_low = torch.from_numpy(ctrl_ranges[:, 0]) - self._act_high = torch.from_numpy(ctrl_ranges[:, 1]) + self._act_low = torch.from_numpy(ctrl_ranges[:, 0]).to(self.device) + self._act_high = torch.from_numpy(ctrl_ranges[:, 1]).to(self.device) def _init_observation_spec(self) -> None: # arm_pos(sin,cos)=16 + arm_vel=8 + touch=5 + hand=3 + object=3 + target=3 + rel=3 @@ -229,17 +226,17 @@ def compute_observation(self, state: ArrayEnvState) -> None: def _sample_arm_joint_angles(self, num: int) -> torch.Tensor: low = self._joint_limit_low[: len(_ARM_JOINTS)] high = self._joint_limit_high[: len(_ARM_JOINTS)] - return torch.rand(num, len(_ARM_JOINTS), dtype=torch.float32) * (high - low) + low + return torch.rand(num, len(_ARM_JOINTS), dtype=torch.float32, device=self.device) * (high - low) + low def _sample_target_pose(self, num: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: cfg = self._cfg - target_x = torch.empty(num, dtype=torch.float32).uniform_( + target_x = torch.empty(num, dtype=torch.float32, device=self.device).uniform_( float(cfg.target_x_range[0]), float(cfg.target_x_range[1]) ) - target_z = torch.empty(num, dtype=torch.float32).uniform_( + target_z = torch.empty(num, dtype=torch.float32, device=self.device).uniform_( float(cfg.target_z_range[0]), float(cfg.target_z_range[1]) ) - target_angle = torch.empty(num, dtype=torch.float32).uniform_( + target_angle = torch.empty(num, dtype=torch.float32, device=self.device).uniform_( float(cfg.target_angle_range[0]), float(cfg.target_angle_range[1]) ) return target_x, target_z, target_angle @@ -248,7 +245,7 @@ def _set_target_mocap( self, env_ids: torch.Tensor, target_x: torch.Tensor, target_z: torch.Tensor, target_angle: torch.Tensor ): num = env_ids.numel() - pose = torch.zeros((num, 7), dtype=torch.float32) + pose = torch.zeros((num, 7), dtype=torch.float32, device=self.device) pose[:, 0] = target_x pose[:, 1] = float(self._cfg.target_y) pose[:, 2] = target_z @@ -270,18 +267,18 @@ def _set_object_state( num = dof_pos.shape[0] # Default: uniform in workspace. - object_x = torch.empty(num, dtype=torch.float32).uniform_( + object_x = torch.empty(num, dtype=torch.float32, device=self.device).uniform_( float(cfg.object_x_range[0]), float(cfg.object_x_range[1]) ) - object_z = torch.empty(num, dtype=torch.float32).uniform_( + object_z = torch.empty(num, dtype=torch.float32, device=self.device).uniform_( float(cfg.object_z_range[0]), float(cfg.object_z_range[1]) ) - object_angle = torch.empty(num, dtype=torch.float32).uniform_( + object_angle = torch.empty(num, dtype=torch.float32, device=self.device).uniform_( float(cfg.object_angle_range[0]), float(cfg.object_angle_range[1]) ) # dm_control-style object init distribution. - r = torch.rand(num, dtype=torch.float32) + r = torch.rand(num, dtype=torch.float32, device=self.device) in_hand = r < float(cfg.p_in_hand) in_target = (r >= float(cfg.p_in_hand)) & (r < float(cfg.p_in_hand + cfg.p_in_target)) uniform = ~(in_hand | in_target) @@ -302,10 +299,10 @@ def _set_object_state( if not pending.any(): break n = int(pending.sum()) - object_x[pending] = torch.empty(n, dtype=torch.float32).uniform_( + object_x[pending] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_( float(cfg.object_x_range[0]), float(cfg.object_x_range[1]) ) - object_z[pending] = torch.empty(n, dtype=torch.float32).uniform_( + object_z[pending] = torch.empty(n, dtype=torch.float32, device=self.device).uniform_( float(cfg.object_z_range[0]), float(cfg.object_z_range[1]) ) @@ -321,17 +318,17 @@ def _set_object_state( dof_vel[:] = 0.0 if uniform.any(): - dof_vel[uniform, 0] = torch.empty(int(uniform.sum()), dtype=torch.float32).uniform_( + dof_vel[uniform, 0] = torch.empty(int(uniform.sum()), dtype=torch.float32, device=self.device).uniform_( float(cfg.object_x_vel_range[0]), float(cfg.object_x_vel_range[1]) ) def initialize_episode(self, env_ids: torch.Tensor) -> None: """Episode initialization: direct state construction, no physics stepping.""" num = env_ids.numel() - arm_pos = torch.zeros((num, len(_ARM_JOINTS)), dtype=torch.float32) + arm_pos = torch.zeros((num, len(_ARM_JOINTS)), dtype=torch.float32, device=self.device) arm_vel = torch.zeros_like(arm_pos) - object_pos = torch.zeros((num, 3), dtype=torch.float32) - object_vel = torch.zeros((num, 3), dtype=torch.float32) + object_pos = torch.zeros((num, 3), dtype=torch.float32, device=self.device) + object_vel = torch.zeros((num, 3), dtype=torch.float32, device=self.device) # Optionally randomize arm joint angles and symmetrize the hand. if getattr(self._cfg, "randomize_arm", True): diff --git a/motrix_envs/src/motrix_envs/basic/pendulum/pendulum_np.py b/motrix_envs/src/motrix_envs/basic/pendulum/pendulum_np.py index ae34c9a88..8c643cf12 100644 --- a/motrix_envs/src/motrix_envs/basic/pendulum/pendulum_np.py +++ b/motrix_envs/src/motrix_envs/basic/pendulum/pendulum_np.py @@ -57,7 +57,7 @@ def __init__( {"policy": ObservationGroupSpec(gym.spaces.Box(-np.inf, np.inf, (3,), dtype=np.float32))} ) # Episode-scoped control history for the control-delta penalty. - self._prev_ctrl = torch.zeros(self._num_envs, dtype=torch.float32) + self._prev_ctrl = torch.zeros(self._num_envs, dtype=torch.float32, device=self.device) @property def observation_spec(self) -> ObservationSpec: @@ -109,6 +109,7 @@ def compute_transition(self, state: ArrayEnvState): sigmoid="gaussian", ), dtype=torch.float32, + device=self.device, ) reward = 3.0 * upright + energy_reward - vel_penalty - 0.001 * ctrl**2 - 0.001 * ctrl_delta**2 @@ -124,10 +125,12 @@ def reset(self, env_ids: torch.Tensor) -> None: cfg: PendulumEnvCfg = self._cfg reset_noise_scale = getattr(cfg, "reset_noise_scale", 0.0) num_reset = env_ids.numel() - dof_pos = (torch.rand(num_reset, 1, dtype=torch.float32) * 2.0 - 1.0) * np.pi - dof_vel = torch.zeros(num_reset, 1, dtype=torch.float32) + dof_pos = (torch.rand(num_reset, 1, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * np.pi + dof_vel = torch.zeros(num_reset, 1, dtype=torch.float32, device=self.device) if reset_noise_scale > 0.0: - dof_vel = (torch.rand(num_reset, 1, dtype=torch.float32) * 2.0 - 1.0) * reset_noise_scale + dof_vel = ( + torch.rand(num_reset, 1, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * reset_noise_scale self._reset_position[env_ids] = dof_pos self._reset_velocity[env_ids] = dof_vel diff --git a/motrix_envs/src/motrix_envs/basic/point_mass/point_mass_np.py b/motrix_envs/src/motrix_envs/basic/point_mass/point_mass_np.py index b3ca69e75..a9020142b 100644 --- a/motrix_envs/src/motrix_envs/basic/point_mass/point_mass_np.py +++ b/motrix_envs/src/motrix_envs/basic/point_mass/point_mass_np.py @@ -63,7 +63,7 @@ def __init__( self._target_radius = cfg.target_radius # Target stay counter, used to control reset after 0.5 seconds of overlap - self._in_target_steps = torch.zeros(self._num_envs, dtype=torch.int64) + self._in_target_steps = torch.zeros(self._num_envs, dtype=torch.int64, device=self.device) self._required_in_target_steps = int(0.5 / cfg.ctrl_dt) @property @@ -163,18 +163,18 @@ def reset(self, env_ids: torch.Tensor) -> None: num_reset = env_ids.numel() # Random initial position within a range for the point mass (only x, y) - x_pos = (torch.rand(num_reset, dtype=torch.float32) * 2.0 - 1.0) * 1.0 - y_pos = (torch.rand(num_reset, dtype=torch.float32) * 2.0 - 1.0) * 1.0 + x_pos = (torch.rand(num_reset, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * 1.0 + y_pos = (torch.rand(num_reset, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * 1.0 point_position = torch.stack([x_pos, y_pos], dim=-1) - point_velocity = torch.zeros((num_reset, 2), dtype=torch.float32) + point_velocity = torch.zeros((num_reset, 2), dtype=torch.float32, device=self.device) # Randomize target position using its slide joints - target_x = (torch.rand(num_reset, dtype=torch.float32) * 2.0 - 1.0) * 1.5 - target_y = (torch.rand(num_reset, dtype=torch.float32) * 2.0 - 1.0) * 1.5 + target_x = (torch.rand(num_reset, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * 1.5 + target_y = (torch.rand(num_reset, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * 1.5 target_position = torch.stack([target_x, target_y], dim=-1) - target_velocity = torch.zeros((num_reset, 2), dtype=torch.float32) + target_velocity = torch.zeros((num_reset, 2), dtype=torch.float32, device=self.device) self._point_position[env_ids] = point_position self._point_velocity[env_ids] = point_velocity diff --git a/motrix_envs/src/motrix_envs/basic/quadruped/quadruped_np.py b/motrix_envs/src/motrix_envs/basic/quadruped/quadruped_np.py index a795d276c..0e07f7cae 100644 --- a/motrix_envs/src/motrix_envs/basic/quadruped/quadruped_np.py +++ b/motrix_envs/src/motrix_envs/basic/quadruped/quadruped_np.py @@ -214,7 +214,9 @@ def __init__( # size) in every quadruped asset, so the capsule branch of the # legacy shape check reduces to the size tuple length. self._leg_geom_sizes = { - name: torch.as_tensor(self.model.others["geoms"][name].size, dtype=torch.float32).flatten() + name: torch.as_tensor( + self.model.others["geoms"][name].size, dtype=torch.float32, device=self.device + ).flatten() for name in self._leg_geom_names } @@ -253,13 +255,13 @@ def _init_action_space(self): self._action_space = gym.spaces.Box( ctrl_ranges[:, 0], ctrl_ranges[:, 1], (self.num_actuators,), dtype=np.float32 ) - self._act_low = torch.from_numpy(ctrl_ranges[:, 0]) - self._act_high = torch.from_numpy(ctrl_ranges[:, 1]) + self._act_low = torch.from_numpy(ctrl_ranges[:, 0]).to(self.device) + self._act_high = torch.from_numpy(ctrl_ranges[:, 1]).to(self.device) # Episode-scoped action history: full-batch buffers, reset writes the # done rows in place. - self._actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32) - self._last_actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32) + self._actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros((self._num_envs, self.num_actuators), dtype=torch.float32, device=self.device) @property def observation_spec(self) -> ObservationSpec: @@ -388,7 +390,7 @@ def _geom_ball_surface_clearance( def _leg_body_ball_penalty(self, rows) -> torch.Tensor: if not self._leg_geom_names: - return torch.zeros((self._num_envs,), dtype=torch.float32) + return torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) inputs = self.sim_data ball_pos = inputs["ball_geom_pos"][rows] @@ -468,7 +470,7 @@ def _escape_reward(self, rows) -> torch.Tensor: ) def _radial_speed_reward(self) -> torch.Tensor: - radial_speed_reward = torch.zeros((self._num_envs,), dtype=torch.float32) + radial_speed_reward = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) if not self._cfg.include_origin: return radial_speed_reward @@ -487,7 +489,7 @@ def _radial_speed_reward(self) -> torch.Tensor: ) def _heading_reward(self) -> torch.Tensor: - heading_reward = torch.zeros((self._num_envs,), dtype=torch.float32) + heading_reward = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) if self._cfg.heading_reward_weight <= 0.0: return heading_reward @@ -652,7 +654,7 @@ def _locomotion_reward(self, upright_reward: torch.Tensor, components: dict[str, return self._sum_scaled_rewards(reward_terms, self._locomotion_reward_scales()) def _random_quaternion(self, num: int) -> torch.Tensor: - q = torch.randn(num, 4, dtype=torch.float32) + q = torch.randn(num, 4, dtype=torch.float32, device=self.device) return q / torch.norm(q, dim=-1, keepdim=True) def _yaw_quaternion(self, yaw: torch.Tensor) -> torch.Tensor: @@ -678,7 +680,7 @@ def _execute_reset(self, env_ids: torch.Tensor, dof_pos: torch.Tensor, dof_vel: def _lift_non_contacting(self, env_ids: torch.Tensor, dof_pos: torch.Tensor, dof_vel: torch.Tensor) -> torch.Tensor: z = dof_pos[:, 2].clone() - pending = torch.ones((env_ids.numel(),), dtype=torch.bool) + pending = torch.ones((env_ids.numel(),), dtype=torch.bool, device=self.device) for _ in range(1000): if not pending.any(): break @@ -726,10 +728,10 @@ def compute_transition(self, state: ArrayEnvState) -> None: def reset(self, env_ids: torch.Tensor) -> None: num = env_ids.numel() dof_pos = self._init_dof_pos.unsqueeze(0).repeat(num, 1).contiguous() - dof_vel = torch.zeros((num, self.num_dof_vel), dtype=torch.float32) + dof_vel = torch.zeros((num, self.num_dof_vel), dtype=torch.float32, device=self.device) if self._cfg.fix_heading: - dof_pos[:, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], dtype=torch.float32) + dof_pos[:, 3:7] = torch.tensor([0.0, 0.0, 0.0, 1.0], dtype=torch.float32, device=self.device) else: dof_pos[:, 3:7] = self._random_quaternion(num) @@ -953,22 +955,24 @@ def compute_transition(self, state: ArrayEnvState) -> None: def reset(self, env_ids: torch.Tensor) -> None: num = env_ids.numel() dof_pos = self._init_dof_pos.unsqueeze(0).repeat(num, 1).contiguous() - dof_vel = torch.zeros((num, self.num_dof_vel), dtype=torch.float32) + dof_vel = torch.zeros((num, self.num_dof_vel), dtype=torch.float32, device=self.device) floor_radius = self._floor_geom_size0 if floor_radius <= 0.0: floor_radius = self._terrain_size spawn_radius = 0.12 * floor_radius - yaw = torch.rand(num, dtype=torch.float32) * 2.0 * torch.pi - dof_pos[:, 0] = (torch.rand(num, dtype=torch.float32) * 2.0 - 1.0) * spawn_radius - dof_pos[:, 1] = (torch.rand(num, dtype=torch.float32) * 2.0 - 1.0) * spawn_radius + yaw = torch.rand(num, dtype=torch.float32, device=self.device) * 2.0 * torch.pi + dof_pos[:, 0] = (torch.rand(num, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * spawn_radius + dof_pos[:, 1] = (torch.rand(num, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * spawn_radius dof_pos[:, 3:7] = self._yaw_quaternion(yaw) - ball_xy = (torch.rand(num, 2, dtype=torch.float32) * 2.0 - 1.0) * spawn_radius + ball_xy = (torch.rand(num, 2, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * spawn_radius ball_qpos = self._ball_pos_slice dof_pos[:, ball_qpos.start : ball_qpos.start + 2] = ball_xy dof_pos[:, ball_qpos.start + 2] = self._ball_geom_size0 - dof_pos[:, ball_qpos.start + 3 : ball_qpos.stop] = torch.tensor([0.0, 0.0, 0.0, 1.0], dtype=torch.float32) + dof_pos[:, ball_qpos.start + 3 : ball_qpos.stop] = torch.tensor( + [0.0, 0.0, 0.0, 1.0], dtype=torch.float32, device=self.device + ) ball_qvel = self._ball_vel_slice dof_vel[:, ball_qvel.start : ball_qvel.stop] = 0.0 diff --git a/motrix_envs/src/motrix_envs/basic/reacher/reacher_np.py b/motrix_envs/src/motrix_envs/basic/reacher/reacher_np.py index 8fb5d344f..88471ba69 100644 --- a/motrix_envs/src/motrix_envs/basic/reacher/reacher_np.py +++ b/motrix_envs/src/motrix_envs/basic/reacher/reacher_np.py @@ -58,7 +58,7 @@ def __init__( self._target_velocity = self._reset_program.buffer("target_velocity") self._target_size = cfg.target_size - self._target_xyz = torch.zeros((num_envs, 3), dtype=torch.float32) + self._target_xyz = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) self._init_observation_spec() self._init_action_space() @@ -104,6 +104,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: dist, bounds=(0.0, self._target_size), margin=self._target_size, value_at_margin=0.0, sigmoid="linear" ), dtype=torch.float32, + device=self.device, ) terminated = ( self.sim_data["dof_pos"].isnan().any(dim=-1) @@ -123,14 +124,14 @@ def reset(self, env_ids: torch.Tensor) -> None: """Reset environment with randomized target position in xy plane (z=0).""" num_reset = env_ids.numel() - arm_position = (torch.rand(num_reset, 2, dtype=torch.float32) * 2.0 - 1.0) * np.pi + arm_position = (torch.rand(num_reset, 2, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * np.pi - target_x = (torch.rand(num_reset, dtype=torch.float32) * 2.0 - 1.0) * 0.15 - target_y = torch.full((num_reset,), 0.15, dtype=torch.float32) + target_x = (torch.rand(num_reset, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * 0.15 + target_y = torch.full((num_reset,), 0.15, dtype=torch.float32, device=self.device) target_position = torch.stack([target_x, target_y], dim=-1) - arm_velocity = torch.zeros((num_reset, 2), dtype=torch.float32) - target_velocity = torch.zeros((num_reset, 2), dtype=torch.float32) + arm_velocity = torch.zeros((num_reset, 2), dtype=torch.float32, device=self.device) + target_velocity = torch.zeros((num_reset, 2), dtype=torch.float32, device=self.device) self._arm_position[env_ids] = arm_position self._arm_velocity[env_ids] = arm_velocity diff --git a/motrix_envs/src/motrix_envs/basic/stewart/stewart_np.py b/motrix_envs/src/motrix_envs/basic/stewart/stewart_np.py index ed62870a6..e5370fe9c 100644 --- a/motrix_envs/src/motrix_envs/basic/stewart/stewart_np.py +++ b/motrix_envs/src/motrix_envs/basic/stewart/stewart_np.py @@ -49,8 +49,8 @@ def _normalize_actions(actions: torch.Tensor, num_envs: int, action_dim: int) -> return actions.clamp(-1.0, 1.0) -def _identity_quat(shape: tuple[int, ...]) -> torch.Tensor: - quat = torch.zeros((*shape, 4), dtype=torch.float32) +def _identity_quat(shape: tuple[int, ...], device: torch.device) -> torch.Tensor: + quat = torch.zeros((*shape, 4), dtype=torch.float32, device=device) quat[..., 3] = 1.0 return quat @@ -58,7 +58,7 @@ def _identity_quat(shape: tuple[int, ...]) -> torch.Tensor: def _normalize_quat(quat: torch.Tensor) -> torch.Tensor: quat = quat.to(torch.float32) norm = torch.norm(quat, dim=-1, keepdim=True) - identity = _identity_quat(tuple(quat.shape[:-1])) + identity = _identity_quat(tuple(quat.shape[:-1]), quat.device) safe = norm > 1e-8 return torch.where(safe, quat / torch.clamp(norm, min=1e-8), identity) @@ -207,13 +207,17 @@ def __init__( if self._model_action_dim != 6: raise ValueError(f"Stewart model mismatch: expected 6 actuators, got {self._model_action_dim}") - self._actuator_low = torch.tensor([spec.ctrl_range[0] for spec in self.model.actuators], dtype=torch.float32) - self._actuator_high = torch.tensor([spec.ctrl_range[1] for spec in self.model.actuators], dtype=torch.float32) + self._actuator_low = torch.tensor( + [spec.ctrl_range[0] for spec in self.model.actuators], dtype=torch.float32, device=self.device + ) + self._actuator_high = torch.tensor( + [spec.ctrl_range[1] for spec in self.model.actuators], dtype=torch.float32, device=self.device + ) # Snapshot the default-pose geometry the same way the legacy env read # it from a fresh SceneData: write default rows (reset runs FK) and # read the compiled queries once before any episode reset. - default_ids = torch.arange(self._num_envs, dtype=torch.int64) + default_ids = torch.arange(self._num_envs, dtype=torch.int64, device=self.device) self.sim_data.execute(default_ids) inputs = self.sim_data self._top_pos_init = inputs["top_pos"][0].clone() @@ -234,35 +238,36 @@ def __init__( # Episode-scoped task state: full-batch buffers, reset writes the done # rows in place. num_envs = self._num_envs - self._target_pos = torch.zeros((num_envs, 3), dtype=torch.float32) - self._target_quat = _identity_quat((num_envs,)) - self._target_tilt_cmd = torch.zeros((num_envs, 2), dtype=torch.float32) - self._prev_rel = torch.zeros((num_envs, 3), dtype=torch.float32) - self._filtered_rel_vel = torch.zeros((num_envs, 3), dtype=torch.float32) - self._last_rel_vel = torch.zeros((num_envs, 3), dtype=torch.float32) - self._prev_top_quat = _identity_quat((num_envs,)) - self._filtered_top_ang_vel = torch.zeros((num_envs, 3), dtype=torch.float32) - self._last_top_ang_vel = torch.zeros((num_envs, 3), dtype=torch.float32) - self._initial_rel_xy = torch.zeros(num_envs, dtype=torch.float32) - self._prev_zero_vel_rel_xy = torch.zeros(num_envs, dtype=torch.float32) - self._still_steps = torch.zeros(num_envs, dtype=torch.int32) - self._still_window_active = torch.zeros(num_envs, dtype=torch.bool) - self._policy_action = torch.zeros((num_envs, self._action_dim), dtype=torch.float32) - self._prev_action_exec = torch.zeros((num_envs, self._action_dim), dtype=torch.float32) - self._action_exec = torch.zeros((num_envs, self._action_dim), dtype=torch.float32) - self._disturb_time = torch.zeros(num_envs, dtype=torch.float32) - self._disturb_pos = torch.zeros((num_envs, 3), dtype=torch.float32) - self._disturb_lin_vel = torch.zeros((num_envs, 3), dtype=torch.float32) - self._disturb_rot_deg = torch.zeros((num_envs, 2), dtype=torch.float32) - self._disturb_ang_vel_deg = torch.zeros((num_envs, 2), dtype=torch.float32) - self._disturb_pos_alpha = torch.ones((num_envs, 3), dtype=torch.float32) - self._disturb_pos_limit_scale = torch.ones((num_envs, 3), dtype=torch.float32) - self._disturb_pos_noise_scale = torch.zeros((num_envs, 3), dtype=torch.float32) - self._disturb_pos_jitter_scale = torch.zeros((num_envs, 3), dtype=torch.float32) - self._disturb_rot_alpha = torch.ones((num_envs, 2), dtype=torch.float32) - self._disturb_rot_limit_scale = torch.ones((num_envs, 2), dtype=torch.float32) - self._disturb_rot_noise_scale = torch.zeros((num_envs, 2), dtype=torch.float32) - self._disturb_rot_jitter_scale = torch.zeros((num_envs, 2), dtype=torch.float32) + self._target_pos = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._target_quat = _identity_quat((num_envs,), self.device) + self._target_tilt_cmd = torch.zeros((num_envs, 2), dtype=torch.float32, device=self.device) + self._prev_rel = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._filtered_rel_vel = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._last_rel_vel = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._prev_top_quat = _identity_quat((num_envs,), self.device) + self._filtered_top_ang_vel = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._last_top_ang_vel = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._initial_rel_xy = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._prev_zero_vel_rel_xy = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._still_steps = torch.zeros(num_envs, dtype=torch.int32, device=self.device) + self._still_window_active = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._policy_action = torch.zeros((num_envs, self._action_dim), dtype=torch.float32, device=self.device) + self._prev_action_exec = torch.zeros((num_envs, self._action_dim), dtype=torch.float32, device=self.device) + self._action_exec = torch.zeros((num_envs, self._action_dim), dtype=torch.float32, device=self.device) + self._disturb_time = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._disturb_pos = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._disturb_lin_vel = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._disturb_rot_deg = torch.zeros((num_envs, 2), dtype=torch.float32, device=self.device) + self._disturb_ang_vel_deg = torch.zeros((num_envs, 2), dtype=torch.float32, device=self.device) + self._disturb_pos_alpha = torch.ones((num_envs, 3), dtype=torch.float32, device=self.device) + self._disturb_pos_limit_scale = torch.ones((num_envs, 3), dtype=torch.float32, device=self.device) + self._disturb_pos_noise_scale = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._disturb_pos_jitter_scale = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._disturb_rot_alpha = torch.ones((num_envs, 2), dtype=torch.float32, device=self.device) + self._disturb_rot_limit_scale = torch.ones((num_envs, 2), dtype=torch.float32, device=self.device) + self._disturb_rot_noise_scale = torch.zeros((num_envs, 2), dtype=torch.float32, device=self.device) + self._disturb_rot_jitter_scale = torch.zeros((num_envs, 2), dtype=torch.float32, device=self.device) + self._substep_error_codes = torch.zeros(num_envs, dtype=torch.int32, device=self.device) @property def observation_spec(self) -> ObservationSpec: @@ -330,14 +335,16 @@ def _apply_pose_delta(self, actions: torch.Tensor) -> None: ratio = (rel_xy_now / max(self._cfg.center_control_radius, 1e-6)).clamp(0.0, 1.0) gain = self._cfg.center_control_min_gain + (1.0 - self._cfg.center_control_min_gain) * ratio else: - gain = torch.ones((actions.shape[0],), dtype=torch.float32) + gain = torch.ones((actions.shape[0],), dtype=torch.float32, device=self.device) effective_actions = actions * gain[:, None] target_pos = self._top_pos_init.unsqueeze(0).expand(actions.shape[0], -1).contiguous() target_roll_deg = effective_actions[:, 0] * self._cfg.target_rotation_limit_deg target_pitch_deg = effective_actions[:, 1] * self._cfg.target_rotation_limit_deg target_tilt_cmd = torch.stack([target_roll_deg, target_pitch_deg], dim=-1) - target_euler_deg = torch.cat([target_tilt_cmd, torch.zeros((actions.shape[0], 1), dtype=torch.float32)], dim=-1) + target_euler_deg = torch.cat( + [target_tilt_cmd, torch.zeros((actions.shape[0], 1), dtype=torch.float32, device=self.device)], dim=-1 + ) target_euler_rad = target_euler_deg * torch.pi / 180.0 target_quat = _from_euler(target_euler_rad[..., 0], target_euler_rad[..., 1], target_euler_rad[..., 2]) @@ -369,22 +376,34 @@ def _reset_episode_disturbance(self, env_ids: torch.Tensor) -> None: freq_min = max(1e-4, float(self._cfg.disturb_freq_min_hz)) freq_max = max(freq_min, float(self._cfg.disturb_freq_max_hz)) - pos_freq = torch.empty(num, 3, dtype=torch.float32).uniform_(freq_min, freq_max) - rot_freq = torch.empty(num, 2, dtype=torch.float32).uniform_(freq_min, freq_max) + pos_freq = torch.empty(num, 3, dtype=torch.float32, device=self.device).uniform_(freq_min, freq_max) + rot_freq = torch.empty(num, 2, dtype=torch.float32, device=self.device).uniform_(freq_min, freq_max) self._disturb_pos_alpha[env_ids] = torch.exp(-2.0 * torch.pi * pos_freq * self._cfg.ctrl_dt) self._disturb_rot_alpha[env_ids] = torch.exp(-2.0 * torch.pi * rot_freq * self._cfg.ctrl_dt) - pos_limit_scale = torch.ones((num, 3), dtype=torch.float32) + pos_limit_scale = torch.ones((num, 3), dtype=torch.float32, device=self.device) if self._cfg.disturb_pos_xy_max > 0.0: xy_min_ratio = min(max(self._cfg.disturb_pos_xy_min / max(self._cfg.disturb_pos_xy_max, 1e-8), 0.0), 1.0) - pos_limit_scale[:, :2] = torch.empty(num, 2, dtype=torch.float32).uniform_(float(xy_min_ratio), 1.0) + pos_limit_scale[:, :2] = torch.empty(num, 2, dtype=torch.float32, device=self.device).uniform_( + float(xy_min_ratio), 1.0 + ) if self._cfg.disturb_pos_z_max > 0.0: - pos_limit_scale[:, 2] = torch.empty(num, dtype=torch.float32).uniform_(0.75, 1.0) + pos_limit_scale[:, 2] = torch.empty(num, dtype=torch.float32, device=self.device).uniform_(0.75, 1.0) self._disturb_pos_limit_scale[env_ids] = pos_limit_scale - self._disturb_rot_limit_scale[env_ids] = torch.empty(num, 2, dtype=torch.float32).uniform_(0.75, 1.0) - self._disturb_pos_noise_scale[env_ids] = torch.empty(num, 3, dtype=torch.float32).uniform_(0.35, 0.60) - self._disturb_rot_noise_scale[env_ids] = torch.empty(num, 2, dtype=torch.float32).uniform_(0.35, 0.60) - self._disturb_pos_jitter_scale[env_ids] = torch.empty(num, 3, dtype=torch.float32).uniform_(0.02, 0.06) - self._disturb_rot_jitter_scale[env_ids] = torch.empty(num, 2, dtype=torch.float32).uniform_(0.03, 0.08) + self._disturb_rot_limit_scale[env_ids] = torch.empty(num, 2, dtype=torch.float32, device=self.device).uniform_( + 0.75, 1.0 + ) + self._disturb_pos_noise_scale[env_ids] = torch.empty(num, 3, dtype=torch.float32, device=self.device).uniform_( + 0.35, 0.60 + ) + self._disturb_rot_noise_scale[env_ids] = torch.empty(num, 2, dtype=torch.float32, device=self.device).uniform_( + 0.35, 0.60 + ) + self._disturb_pos_jitter_scale[env_ids] = torch.empty(num, 3, dtype=torch.float32, device=self.device).uniform_( + 0.02, 0.06 + ) + self._disturb_rot_jitter_scale[env_ids] = torch.empty(num, 2, dtype=torch.float32, device=self.device).uniform_( + 0.03, 0.08 + ) def _update_disturbance_state(self, advance: bool) -> None: num = self._num_envs @@ -397,17 +416,19 @@ def _update_disturbance_state(self, advance: bool) -> None: self._disturb_ang_vel_deg[:] = 0.0 return - ramp = torch.ones((num,), dtype=torch.float32) + ramp = torch.ones((num,), dtype=torch.float32, device=self.device) if self._cfg.disturb_ramp_seconds > 1e-8: ramp = (self._disturb_time / self._cfg.disturb_ramp_seconds).clamp(0.0, 1.0) base_pos_limit = self._cfg.disturbance_scale * torch.tensor( [self._cfg.disturb_pos_xy_max, self._cfg.disturb_pos_xy_max, self._cfg.disturb_pos_z_max], dtype=torch.float32, + device=self.device, ) base_rot_limit = self._cfg.disturbance_scale * torch.tensor( [self._cfg.disturb_rot_max_deg, self._cfg.disturb_rot_max_deg], dtype=torch.float32, + device=self.device, ) pos_limit = ramp[:, None] * base_pos_limit[None, :] * self._disturb_pos_limit_scale rot_limit = ramp[:, None] * base_rot_limit[None, :] * self._disturb_rot_limit_scale @@ -418,10 +439,10 @@ def _update_disturbance_state(self, advance: bool) -> None: prev_pos = self._disturb_pos.clone() prev_rot = self._disturb_rot_deg.clone() - pos_noise = torch.randn(num, 3, dtype=torch.float32) - rot_noise = torch.randn(num, 2, dtype=torch.float32) - pos_jitter = torch.randn(num, 3, dtype=torch.float32) - rot_jitter = torch.randn(num, 2, dtype=torch.float32) + pos_noise = torch.randn(num, 3, dtype=torch.float32, device=self.device) + rot_noise = torch.randn(num, 2, dtype=torch.float32, device=self.device) + pos_jitter = torch.randn(num, 3, dtype=torch.float32, device=self.device) + rot_jitter = torch.randn(num, 2, dtype=torch.float32, device=self.device) pos_blend = torch.sqrt((1.0 - self._disturb_pos_alpha**2).clamp(min=0.0)) rot_blend = torch.sqrt((1.0 - self._disturb_rot_alpha**2).clamp(min=0.0)) @@ -442,7 +463,7 @@ def _update_disturbance_state(self, advance: bool) -> None: def _apply_disturbance_to_stage(self, env_ids: torch.Tensor) -> None: num = env_ids.numel() disturb_rot_deg = torch.cat( - [self._disturb_rot_deg[env_ids], torch.zeros((num, 1), dtype=torch.float32)], + [self._disturb_rot_deg[env_ids], torch.zeros((num, 1), dtype=torch.float32, device=self.device)], dim=-1, ) disturb_rot_rad = disturb_rot_deg * torch.pi / 180.0 @@ -460,7 +481,7 @@ def _apply_disturbance_to_stage(self, env_ids: torch.Tensor) -> None: stage_pos = self._stage_pos_init[None, :] + self._disturb_pos[env_ids] stage_ang_vel = ( torch.cat( - [self._disturb_ang_vel_deg[env_ids], torch.zeros((num, 1), dtype=torch.float32)], + [self._disturb_ang_vel_deg[env_ids], torch.zeros((num, 1), dtype=torch.float32, device=self.device)], dim=-1, ) * torch.pi @@ -529,24 +550,67 @@ def _update_ball_kinematics(self) -> dict[str, torch.Tensor]: "tilt_deg": torch.maximum(torch.abs(roll_deg), torch.abs(pitch_deg)), } + def _stage_full_batch_disturbance(self) -> None: + num = self._num_envs + program = self._body_state_writes["disturb_stage"] + if (not self._cfg.disturbance_enabled) or self._cfg.disturbance_scale <= 0.0: + program.buffer("disturb_stage_position")[:, 0] = self._stage_pos_init + program.buffer("disturb_stage_rotation")[:, 0] = self._stage_quat_init + program.buffer("disturb_stage_linear_velocity")[:, 0] = 0.0 + program.buffer("disturb_stage_angular_velocity")[:, 0] = 0.0 + program.execute() + return + disturb_rot_deg = torch.cat( + [self._disturb_rot_deg, torch.zeros((num, 1), dtype=torch.float32, device=self.device)], + dim=-1, + ) + disturb_rot_rad = disturb_rot_deg * torch.pi / 180.0 + disturb_rot_quat = _from_euler(disturb_rot_rad[..., 0], disturb_rot_rad[..., 1], disturb_rot_rad[..., 2]) + stage_quat = _quat_mul(disturb_rot_quat, self._stage_quat_init.expand(disturb_rot_quat.shape)) + roll_rad, pitch_rad, yaw_rad = _euler_xyz(_normalize_quat(stage_quat)) + roll_deg = (roll_rad * 180.0 / torch.pi).clamp( + -self._cfg.disturb_rot_limit_deg, self._cfg.disturb_rot_limit_deg + ) + pitch_deg = (pitch_rad * 180.0 / torch.pi).clamp( + -self._cfg.disturb_rot_limit_deg, self._cfg.disturb_rot_limit_deg + ) + yaw_deg = yaw_rad * 180.0 / torch.pi + stage_euler_rad = torch.stack([roll_deg, pitch_deg, yaw_deg], dim=-1) * torch.pi / 180.0 + stage_quat = _from_euler(stage_euler_rad[..., 0], stage_euler_rad[..., 1], stage_euler_rad[..., 2]) + stage_pos = self._stage_pos_init[None, :] + self._disturb_pos + stage_ang_vel = ( + torch.cat( + [self._disturb_ang_vel_deg, torch.zeros((num, 1), dtype=torch.float32, device=self.device)], + dim=-1, + ) + * torch.pi + / 180.0 + ) + program.buffer("disturb_stage_position")[:, 0] = stage_pos + program.buffer("disturb_stage_rotation")[:, 0] = _normalize_quat(stage_quat) + program.buffer("disturb_stage_linear_velocity")[:, 0] = self._disturb_lin_vel + program.buffer("disturb_stage_angular_velocity")[:, 0] = stage_ang_vel + program.execute() + def _prepare_control_step(self) -> None: self._smooth_actions(self._policy_action) self._apply_pose_delta(self._action_exec) self._update_disturbance_state(advance=True) - all_ids = torch.arange(self._num_envs, dtype=torch.int64) - self._apply_disturbance_to_stage(all_ids) - self.sim_data.execute(all_ids) + self._stage_full_batch_disturbance() + self.sim_data.execute() ctrl = self._ctrl_writes.buffer("ctrl") ctrl.copy_(self._compute_leg_ctrls(slice(None), self._target_pos, self._target_quat)) self._ctrl_writes.execute() def _simulate_control_step(self) -> None: - all_ids = torch.arange(self._num_envs, dtype=torch.int64) + stage_program = self._body_state_writes["disturb_stage"] + self.engine_error_codes.zero_() for _ in range(self._cfg.sim_substeps): - self._apply_disturbance_to_stage(all_ids) - self.sim.step(1) + stage_program.execute() + self.sim.step(1, result=self._substep_error_codes) + self.engine_error_codes.bitwise_or_(self._substep_error_codes) - self._apply_disturbance_to_stage(all_ids) + stage_program.execute() def physics_step(self) -> None: # Stewart interleaves floating-base disturbance writes with per-substep @@ -645,13 +709,13 @@ def compute_transition(self, state: ArrayEnvState) -> None: reward = term_center + term_zero_vel_closer + term_still_bonus - term_terminal = torch.zeros((self._num_envs,), dtype=torch.float32) + term_terminal = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) reward = torch.where(fallen, torch.full_like(reward, float(self._cfg.fall_penalty)), reward) term_terminal[fallen] = float(self._cfg.fall_penalty) # Timeout flag for logging only; the framework owns truncation via its # terminated/truncated bookkeeping. - timeout = torch.zeros((self._num_envs,), dtype=torch.bool) + timeout = torch.zeros((self._num_envs,), dtype=torch.bool, device=self.device) if self._cfg.max_episode_steps is not None and self._cfg.max_episode_steps > 0: timeout = (state.episode_steps + 1) >= self._cfg.max_episode_steps timeout &= ~(fallen | success) @@ -689,19 +753,21 @@ def compute_transition(self, state: ArrayEnvState) -> None: def reset(self, env_ids: torch.Tensor) -> None: num = env_ids.numel() - zeros3 = torch.zeros((num, 3), dtype=torch.float32) + zeros3 = torch.zeros((num, 3), dtype=torch.float32, device=self.device) - roll_deg = torch.empty(num, dtype=torch.float32).uniform_( + roll_deg = torch.empty(num, dtype=torch.float32, device=self.device).uniform_( float(self._cfg.min_init_tilt_deg), float(self._cfg.init_tilt_deg) ) - roll_deg *= torch.where(torch.rand(num) < 0.5, -1.0, 1.0) - pitch_deg = torch.empty(num, dtype=torch.float32).uniform_( + roll_deg *= torch.where(torch.rand(num, device=self.device) < 0.5, -1.0, 1.0) + pitch_deg = torch.empty(num, dtype=torch.float32, device=self.device).uniform_( float(self._cfg.min_init_tilt_deg), float(self._cfg.init_tilt_deg) ) - pitch_deg *= torch.where(torch.rand(num) < 0.5, -1.0, 1.0) + pitch_deg *= torch.where(torch.rand(num, device=self.device) < 0.5, -1.0, 1.0) target_pos = self._top_pos_init.unsqueeze(0).expand(num, -1).contiguous() - target_euler_deg = torch.stack([roll_deg, pitch_deg, torch.zeros((num,), dtype=torch.float32)], dim=-1) + target_euler_deg = torch.stack( + [roll_deg, pitch_deg, torch.zeros((num,), dtype=torch.float32, device=self.device)], dim=-1 + ) target_euler_rad = target_euler_deg * torch.pi / 180.0 target_quat = _from_euler(target_euler_rad[..., 0], target_euler_rad[..., 1], target_euler_rad[..., 2]) @@ -728,8 +794,10 @@ def reset(self, env_ids: torch.Tensor) -> None: dim=-1, ) top_pose = torch.cat([target_pos, _normalize_quat(target_quat)], dim=-1) - hidden_ball_pos = torch.tensor([0.0, 0.0, -10.0], dtype=torch.float32).unsqueeze(0).expand(num, -1) - ball_pose = torch.cat([hidden_ball_pos, _identity_quat((num,))], dim=-1) + hidden_ball_pos = ( + torch.tensor([0.0, 0.0, -10.0], dtype=torch.float32, device=self.device).unsqueeze(0).expand(num, -1) + ) + ball_pose = torch.cat([hidden_ball_pos, _identity_quat((num,), self.device)], dim=-1) for name, pose in (("stage", stage_pose), ("top", top_pose), ("ball", ball_pose)): self._reset_program.buffer(f"{name}_position")[env_ids, 0] = pose[:, :3] self._reset_program.buffer(f"{name}_rotation")[env_ids, 0] = pose[:, 3:7] @@ -752,20 +820,27 @@ def reset(self, env_ids: torch.Tensor) -> None: radius = ( self._cfg.platform_radius * self._cfg.init_ball_radius_ratio - * torch.sqrt(torch.rand(num, dtype=torch.float32)) + * torch.sqrt(torch.rand(num, dtype=torch.float32, device=self.device)) ) - theta = torch.rand(num, dtype=torch.float32) * 2.0 * torch.pi + theta = torch.rand(num, dtype=torch.float32, device=self.device) * 2.0 * torch.pi local_xy = torch.stack([radius * torch.cos(theta), radius * torch.sin(theta)], dim=-1) local_pos = torch.cat( [ local_xy, - torch.full((num, 1), self._cfg.top_surface_offset + self._cfg.ball_radius, dtype=torch.float32), + torch.full( + (num, 1), + self._cfg.top_surface_offset + self._cfg.ball_radius, + dtype=torch.float32, + device=self.device, + ), ], dim=-1, ) world_pos = target_pos + _rotate_vector(target_quat, local_pos) - self._write_body_state("ball", env_ids, world_pos, _identity_quat((num,)), zeros3, zeros3) - self._write_ctrl_rows(env_ids, torch.zeros((num, self._model_action_dim), dtype=torch.float32)) + self._write_body_state("ball", env_ids, world_pos, _identity_quat((num,), self.device), zeros3, zeros3) + self._write_ctrl_rows( + env_ids, torch.zeros((num, self._model_action_dim), dtype=torch.float32, device=self.device) + ) self.sim_data.execute(env_ids) ball_pos = self.sim_data["ball_pos"][env_ids] diff --git a/motrix_envs/src/motrix_envs/basic/walker/walker_np.py b/motrix_envs/src/motrix_envs/basic/walker/walker_np.py index 86975e872..e4fead1ed 100644 --- a/motrix_envs/src/motrix_envs/basic/walker/walker_np.py +++ b/motrix_envs/src/motrix_envs/basic/walker/walker_np.py @@ -146,6 +146,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: margin=self._stand_height * 4 / 5, ), dtype=torch.float32, + device=self.device, ) rwd_upright = (1 + torso_upright) / 2 rwd_stand = (3 * rwd_height + 1 * rwd_upright) / 4 @@ -168,6 +169,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: sigmoid="linear", ), dtype=torch.float32, + device=self.device, ) reward_terms["move"] = rwd_move rwd = rwd_stand * (5 * rwd_move + 1) / 6 @@ -182,14 +184,18 @@ def compute_transition(self, state: ArrayEnvState) -> None: def reset(self, env_ids: torch.Tensor) -> None: num_reset = env_ids.numel() - dof_pos = torch.zeros((num_reset, self._reset_position.shape[1]), dtype=torch.float32) - dof_pos[:, 2] = (torch.rand(num_reset, dtype=torch.float32) * 2.0 - 1.0) * np.pi # randomize root yaw + dof_pos = torch.zeros((num_reset, self._reset_position.shape[1]), dtype=torch.float32, device=self.device) + dof_pos[:, 2] = ( + torch.rand(num_reset, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * np.pi # randomize root yaw lower = self._joint_pos_lower[3:] upper = self._joint_pos_upper[3:] dof_pos[:, 3:] = ( - torch.rand((num_reset, self._reset_position.shape[1] - 3), dtype=torch.float32) * (upper - lower) + lower + torch.rand((num_reset, self._reset_position.shape[1] - 3), dtype=torch.float32, device=self.device) + * (upper - lower) + + lower ) # randomize other joint angles - dof_vel = torch.zeros((num_reset, self._reset_velocity.shape[1]), dtype=torch.float32) + dof_vel = torch.zeros((num_reset, self._reset_velocity.shape[1]), dtype=torch.float32, device=self.device) self._reset_position[env_ids] = dof_pos self._reset_velocity[env_ids] = dof_vel diff --git a/motrix_envs/src/motrix_envs/locomotion/anymal_c/anymal_c_np.py b/motrix_envs/src/motrix_envs/locomotion/anymal_c/anymal_c_np.py index 916d84a9d..320f32e97 100644 --- a/motrix_envs/src/motrix_envs/locomotion/anymal_c/anymal_c_np.py +++ b/motrix_envs/src/motrix_envs/locomotion/anymal_c/anymal_c_np.py @@ -93,6 +93,7 @@ def __init__( **kwargs, ): super().__init__(cfg, num_envs, backend=backend, **kwargs) + self._gravity = _GRAVITY.to(self.device) self.model = self.sim.compile_model(_sim_model_queries(cfg)) self.sim_data = self.sim.compile_reads(_sim_data_queries(cfg)) self._heading_writes = self.sim.write_compiler.compile( @@ -144,12 +145,14 @@ def __init__( def _init_buffer(self): cfg = self._cfg - self.default_angles = torch.zeros(self._num_action, dtype=torch.float32) + self.default_angles = torch.zeros(self._num_action, dtype=torch.float32, device=self.device) # PD parameters controlled by kp and kv in XML # Normalization coefficients self.commands_scale = torch.tensor( - [cfg.normalization.lin_vel, cfg.normalization.lin_vel, cfg.normalization.ang_vel], dtype=torch.float32 + [cfg.normalization.lin_vel, cfg.normalization.lin_vel, cfg.normalization.ang_vel], + dtype=torch.float32, + device=self.device, ) # Set default joint angles @@ -164,11 +167,11 @@ def _init_buffer(self): # Episode-scoped navigation state: full-batch buffers, reset writes the # done rows in place. num_envs = self._num_envs - self._pose_commands = torch.zeros((num_envs, 3), dtype=torch.float32) - self._last_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32) - self._current_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32) - self._ever_reached = torch.zeros(num_envs, dtype=torch.bool) - self._min_distance = torch.zeros(num_envs, dtype=torch.float32) + self._pose_commands = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32, device=self.device) + self._current_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32, device=self.device) + self._ever_reached = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._min_distance = torch.zeros(num_envs, dtype=torch.float32, device=self.device) def _init_contact_geometry(self): """Initialize geometry name pairs required for contact detection""" @@ -235,7 +238,7 @@ def action_space(self): return self._action_space def apply_action(self, actions: torch.Tensor, state: ArrayEnvState): - actions = torch.as_tensor(actions, dtype=torch.float32) + actions = torch.as_tensor(actions, dtype=torch.float32, device=self.device) # Save current action for incremental control self._last_actions.copy_(self._current_actions) self._current_actions.copy_(actions) @@ -347,11 +350,11 @@ def compute_transition(self, state: ArrayEnvState): # Update target position marker num_envs = self._num_envs - self._update_target_marker(torch.arange(num_envs, dtype=torch.int64), self._pose_commands) + self._update_target_marker(torch.arange(num_envs, dtype=torch.int64, device=self.device), self._pose_commands) # Update arrow visualization (no physical effect) base_lin_vel_xy = base_lin_vel[:, :2] self._update_heading_arrows( - torch.arange(num_envs, dtype=torch.int64), root_pos, desired_vel_xy, base_lin_vel_xy + torch.arange(num_envs, dtype=torch.int64, device=self.device), root_pos, desired_vel_xy, base_lin_vel_xy ) # Calculate reward @@ -380,7 +383,7 @@ def _update_heading_arrows( cur_yaw = torch.where( torch.linalg.vector_norm(base_lin_vel_xy, dim=1) > 1e-3, torch.atan2(base_lin_vel_xy[:, 1], base_lin_vel_xy[:, 0]), - torch.zeros((), dtype=torch.float32), + torch.zeros((), dtype=torch.float32, device=self.device), ) robot_arrow_pos = robot_pos.clone() robot_arrow_pos[:, 2] = arrow_height @@ -390,7 +393,7 @@ def _update_heading_arrows( des_yaw = torch.where( torch.linalg.vector_norm(desired_vel_xy, dim=1) > 1e-6, torch.atan2(desired_vel_xy[:, 1], desired_vel_xy[:, 0]), - torch.zeros((), dtype=torch.float32), + torch.zeros((), dtype=torch.float32, device=self.device), ) self._heading_writes.buffer("desired_pos")[env_ids, 0] = robot_arrow_pos self._heading_writes.buffer("desired_rot")[env_ids, 0] = _yaw_quaternion(des_yaw) @@ -404,7 +407,7 @@ def _compute_reward(self, velocity_commands: torch.Tensor) -> torch.Tensor: """ num_envs = self._num_envs # Calculate termination condition penalties - termination_penalty = torch.zeros(num_envs, dtype=torch.float32) + termination_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) # Check if DOF velocity exceeds limit dof_vel = self.get_dof_vel() @@ -444,7 +447,7 @@ def _compute_reward(self, velocity_commands: torch.Tensor) -> torch.Tensor: # One-time reward for first time reaching position first_time_reach = reached_all & ~self._ever_reached self._ever_reached |= reached_all - arrival_bonus = torch.where(first_time_reach, 10.0, torch.zeros((), dtype=torch.float32)) + arrival_bonus = torch.where(first_time_reach, 10.0, torch.zeros((), dtype=torch.float32, device=self.device)) # Distance approach reward: incentivize getting closer to target # Use historical minimum distance to calculate progress @@ -464,9 +467,13 @@ def _compute_reward(self, velocity_commands: torch.Tensor) -> torch.Tensor: # Arrival and stop determination (reward bonus) speed_xy = torch.linalg.vector_norm(base_lin_vel[:, :2], dim=1) zero_ang_mask = gyro[:, 2].abs() < 0.05 # Relax to 0.05 rad/s ≈ 2.86°/s - zero_ang_bonus = torch.where(reached_all & zero_ang_mask, 6.0, torch.zeros((), dtype=torch.float32)) + zero_ang_bonus = torch.where( + reached_all & zero_ang_mask, 6.0, torch.zeros((), dtype=torch.float32, device=self.device) + ) stop_base = 2 * (0.8 * torch.exp(-((speed_xy / 0.2) ** 2)) + 1.2 * torch.exp(-((gyro[:, 2].abs() / 0.1) ** 4))) - stop_bonus = torch.where(reached_all, stop_base + zero_ang_bonus, torch.zeros((), dtype=torch.float32)) + stop_bonus = torch.where( + reached_all, stop_base + zero_ang_bonus, torch.zeros((), dtype=torch.float32, device=self.device) + ) # 4. Z-axis linear velocity penalty lin_vel_z_penalty = torch.square(base_lin_vel[:, 2]) @@ -525,14 +532,16 @@ def _update_target_marker(self, env_ids: torch.Tensor, pose_commands: torch.Tens num_envs = pose_commands.shape[0] arrow_pos = pose_commands.clone() arrow_pos[:, 2] = 0.05 - arrow_pos = torch.stack([pose_commands[:, 0], pose_commands[:, 1], torch.full((num_envs,), 0.5)], dim=1) + arrow_pos = torch.stack( + [pose_commands[:, 0], pose_commands[:, 1], torch.full((num_envs,), 0.5, device=self.device)], dim=1 + ) arrow_quat = _yaw_quaternion(pose_commands[:, 2]) self._target_writes.buffer("target_pos")[env_ids, 0] = arrow_pos self._target_writes.buffer("target_rot")[env_ids, 0] = arrow_quat self._target_writes.execute(env_ids) def _compute_terminated(self, state: ArrayEnvState) -> ArrayEnvState: - terminated = torch.zeros(self._num_envs, dtype=torch.bool) + terminated = torch.zeros(self._num_envs, dtype=torch.bool, device=self.device) # Check if DOF velocity exceeds limit (prevent inf/numerical divergence) dof_vel = self.get_dof_vel() @@ -565,21 +574,27 @@ def reset(self, env_ids: torch.Tensor) -> None: # First generate robot initial position (in world coordinates) pos_range = cfg.init_state.pos_randomization_range - robot_init_x = pos_range[0] + (pos_range[2] - pos_range[0]) * torch.rand(num_envs, dtype=torch.float32) - robot_init_y = pos_range[1] + (pos_range[3] - pos_range[1]) * torch.rand(num_envs, dtype=torch.float32) + robot_init_x = pos_range[0] + (pos_range[2] - pos_range[0]) * torch.rand( + num_envs, dtype=torch.float32, device=self.device + ) + robot_init_y = pos_range[1] + (pos_range[3] - pos_range[1]) * torch.rand( + num_envs, dtype=torch.float32, device=self.device + ) robot_init_pos = torch.stack([robot_init_x, robot_init_y], dim=1) # [num_envs, 2] # Generate target position: offset relative to robot initial position # pose_command_range now represents offset range relative to robot pose_command_range = cfg.commands.pose_command_range - offset_low = torch.tensor(pose_command_range[:2], dtype=torch.float32) - offset_high = torch.tensor(pose_command_range[3:5], dtype=torch.float32) - target_offset = offset_low + (offset_high - offset_low) * torch.rand((num_envs, 2), dtype=torch.float32) + offset_low = torch.tensor(pose_command_range[:2], dtype=torch.float32, device=self.device) + offset_high = torch.tensor(pose_command_range[3:5], dtype=torch.float32, device=self.device) + target_offset = offset_low + (offset_high - offset_low) * torch.rand( + (num_envs, 2), dtype=torch.float32, device=self.device + ) target_positions = robot_init_pos + target_offset # Target position in world coordinates # Generate target heading (absolute heading, random in horizontal direction) target_headings = pose_command_range[2] + (pose_command_range[5] - pose_command_range[2]) * torch.rand( - (num_envs, 1), dtype=torch.float32 + (num_envs, 1), dtype=torch.float32, device=self.device ) pose_commands = torch.cat([target_positions, target_headings], dim=1) @@ -660,4 +675,4 @@ def reset(self, env_ids: torch.Tensor) -> None: self._min_distance[rows] = distance_to_target def _compute_projected_gravity(self, quat: torch.Tensor) -> torch.Tensor: - return _rotate_vector(quat, _GRAVITY) + return _rotate_vector(quat, self._gravity) diff --git a/motrix_envs/src/motrix_envs/locomotion/anymal_c/cfg.py b/motrix_envs/src/motrix_envs/locomotion/anymal_c/cfg.py index d743c0b6b..6c422f878 100644 --- a/motrix_envs/src/motrix_envs/locomotion/anymal_c/cfg.py +++ b/motrix_envs/src/motrix_envs/locomotion/anymal_c/cfg.py @@ -108,7 +108,7 @@ class AnymalCEnvCfg(DirectEnvCfg): scene: SceneCfg = SceneCfg(file=model_file, objs=SceneObjsCfg(robot=AnymalC())) reset_noise_scale: float = 0.01 max_episode_seconds: float = 7.0 - sim: SimCfg = SimCfg(dt=0.01) + sim: SimCfg = SimCfg(dt=0.01, max_contacts=128, max_contact_constraints=384) ctrl_dt: float = 0.01 reset_yaw_scale: float = 0.1 max_dof_vel: float = 100.0 # maximum joint velocity threshold, greater tolerance during early training diff --git a/motrix_envs/src/motrix_envs/locomotion/ball_balance/mdp/reset.py b/motrix_envs/src/motrix_envs/locomotion/ball_balance/mdp/reset.py index 3c831dc76..4178f07fe 100644 --- a/motrix_envs/src/motrix_envs/locomotion/ball_balance/mdp/reset.py +++ b/motrix_envs/src/motrix_envs/locomotion/ball_balance/mdp/reset.py @@ -54,6 +54,7 @@ def __call__(self, ctx) -> ResetTerm: torch.tensor(self.spawn, dtype=torch.float32), torch.tensor(self.noise, dtype=torch.float32) * self.noise_scale, writes={"position": BodyPositionWrite((body,))}, + stateless=True, ) @@ -80,6 +81,7 @@ def __call__(self, ctx) -> ResetTerm: _reset_body_rot, amplitude, writes={"rotation": BodyRotationWrite((body,))}, + stateless=True, ) @@ -104,6 +106,7 @@ def __call__(self, ctx) -> ResetTerm: _reset_body_lin_vel, amplitude, writes={"linear_velocity": BodyLinearVelocityWrite((body,))}, + stateless=True, ) @@ -128,6 +131,7 @@ def __call__(self, ctx) -> ResetTerm: _reset_body_rot_vel, amplitude, writes={"angular_velocity": BodyAngularVelocityWrite((body,))}, + stateless=True, ) @@ -182,6 +186,7 @@ def __call__(self, ctx) -> ResetTerm: noise_scale=float(self.noise * self.noise_scale), ), writes={"position": JointPositionWrite(joints), "velocity": JointVelocityWrite(joints)}, + stateless=True, ) @@ -222,4 +227,5 @@ def __call__(self, ctx) -> ResetTerm: "linear_velocity": BodyLinearVelocityWrite((self.ball_link_name,)), "angular_velocity": BodyAngularVelocityWrite((self.ball_link_name,)), }, + stateless=True, ) diff --git a/motrix_envs/src/motrix_envs/locomotion/ball_balance/mdp/rewards.py b/motrix_envs/src/motrix_envs/locomotion/ball_balance/mdp/rewards.py index c45853f5f..7aa7dd2a8 100644 --- a/motrix_envs/src/motrix_envs/locomotion/ball_balance/mdp/rewards.py +++ b/motrix_envs/src/motrix_envs/locomotion/ball_balance/mdp/rewards.py @@ -5,7 +5,6 @@ from dataclasses import dataclass -import numpy as np import torch from motrix_env_core.config import configclass @@ -102,6 +101,6 @@ def __call__(self, ctx) -> RewardTerm: missing = sorted(set(joint_names).difference(default)) if missing: raise KeyError(f"key pose 'default' is missing joints: {missing}") - reference = np.asarray([default[name] for name in joint_names], dtype=np.float32) - params = DofDefaultParams(torch.from_numpy(reference), float(self.sigma)) + reference = torch.tensor([default[name] for name in joint_names], dtype=torch.float32) + params = DofDefaultParams(reference, float(self.sigma)) return RewardTerm(dof_default_reward, params) diff --git a/motrix_envs/src/motrix_envs/locomotion/ball_balance/microduck.py b/motrix_envs/src/motrix_envs/locomotion/ball_balance/microduck.py index 7bc69b494..9cb0c03f3 100644 --- a/motrix_envs/src/motrix_envs/locomotion/ball_balance/microduck.py +++ b/motrix_envs/src/motrix_envs/locomotion/ball_balance/microduck.py @@ -187,7 +187,9 @@ class MicroduckBallBalanceEnvCfg(ManagerBasedEnvCfg): max_episode_seconds: float = 20.0 sim_reset: ManagerResetCfg = ResetCfg() - sim: SimCfg = SimCfg(dt=0.005, solver_iterations=6, solver_tolerance=1e-4) + sim: SimCfg = SimCfg( + dt=0.005, solver_iterations=6, solver_tolerance=1e-4, max_contacts=128, max_contact_constraints=384 + ) ctrl_dt: float = 0.02 actions: ActionsCfg = ActionsCfg() observations: ObservationsCfg = ObservationsCfg() diff --git a/motrix_envs/src/motrix_envs/locomotion/go1/cfg.py b/motrix_envs/src/motrix_envs/locomotion/go1/cfg.py index 780491132..2fb4e93f0 100644 --- a/motrix_envs/src/motrix_envs/locomotion/go1/cfg.py +++ b/motrix_envs/src/motrix_envs/locomotion/go1/cfg.py @@ -124,7 +124,7 @@ class Go1TerrainWalkDirectEnvCfg(DirectEnvCfg): normalization: Normalization = Normalization() asset: Asset = Asset() sensor: Sensor = Sensor() - sim: SimCfg = SimCfg(dt=0.01) + sim: SimCfg = SimCfg(dt=0.01, max_contacts=256, max_contact_constraints=768) ctrl_dt: float = 0.01 diff --git a/motrix_envs/src/motrix_envs/locomotion/go1/walk_stairs_terrain.py b/motrix_envs/src/motrix_envs/locomotion/go1/walk_stairs_terrain.py index 38679a4e3..8f68b9472 100644 --- a/motrix_envs/src/motrix_envs/locomotion/go1/walk_stairs_terrain.py +++ b/motrix_envs/src/motrix_envs/locomotion/go1/walk_stairs_terrain.py @@ -60,6 +60,7 @@ def __init__( **kwargs, ): super().__init__(cfg, num_envs, backend=backend, **kwargs) + self._gravity = _GRAVITY.to(self.device) self.model = self.sim.compile_model({}) self.sim_data = self.sim.compile_reads(_sim_data_queries(cfg)) self._ctrl_writes = self.sim.write_compiler.compile({"ctrl": CtrlTargetsWrite()}) @@ -91,7 +92,7 @@ def __init__( for j in range(5): h_index = offset_h[j][i] offset.append([(i - 2) * 8.0, (j - 2) * 8.0, height_list[h_index]]) - self.offset_list = torch.tensor(offset, dtype=torch.float32) + self.offset_list = torch.tensor(offset, dtype=torch.float32, device=self.device) self._init_base_pose = self.model.init_dof_pos[:7].clone() self._init_buffer() self.period_counter = 0 @@ -140,9 +141,11 @@ def _init_buffer(self): assert isinstance(cfg, Go1WalkDirectStairsEnvCfg) # init buffers - self.reset_buf = torch.ones(self._num_envs, dtype=torch.bool) - self.kps = torch.full((self._num_action,), cfg.control_config.stiffness, dtype=torch.float32) - self.kds = torch.full((self._num_action,), cfg.control_config.damping, dtype=torch.float32) + self.reset_buf = torch.ones(self._num_envs, dtype=torch.bool, device=self.device) + self.kps = torch.full( + (self._num_action,), cfg.control_config.stiffness, dtype=torch.float32, device=self.device + ) + self.kds = torch.full((self._num_action,), cfg.control_config.damping, dtype=torch.float32, device=self.device) self.commands_scale = torch.tensor( ( [ @@ -152,9 +155,10 @@ def _init_buffer(self): ] ), dtype=torch.float32, + device=self.device, ) - self.default_angles = torch.zeros(self._num_action, dtype=torch.float32) + self.default_angles = torch.zeros(self._num_action, dtype=torch.float32, device=self.device) self.hip_indices = [] self.calf_indices = [] actuator_names = [spec.name for spec in self.model.actuators] @@ -178,13 +182,13 @@ def _init_buffer(self): # Episode-scoped task state: full-batch buffers, reset writes the done # rows in place. num_envs = self._num_envs - self._commands = torch.zeros((num_envs, 3), dtype=torch.float32) - self._contacts = torch.zeros((num_envs, self.foot_check_num), dtype=torch.bool) - self._contact_force = torch.zeros((num_envs, 12), dtype=torch.float32) - self._feet_air_time = torch.zeros((num_envs, self.foot_check_num), dtype=torch.float32) - self._last_dof_vel = torch.zeros((num_envs, self._num_action), dtype=torch.float32) - self._current_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32) - self._last_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32) + self._commands = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._contacts = torch.zeros((num_envs, self.foot_check_num), dtype=torch.bool, device=self.device) + self._contact_force = torch.zeros((num_envs, 12), dtype=torch.float32, device=self.device) + self._feet_air_time = torch.zeros((num_envs, self.foot_check_num), dtype=torch.float32, device=self.device) + self._last_dof_vel = torch.zeros((num_envs, self._num_action), dtype=torch.float32, device=self.device) + self._current_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32, device=self.device) spacing = 2.0 cols = int(np.ceil(np.sqrt(self._num_envs))) @@ -196,10 +200,10 @@ def _init_buffer(self): y = row * spacing z = 0.0 offsets.append([x, y, z]) - self.offsets = torch.tensor(offsets, dtype=torch.float32) + self.offsets = torch.tensor(offsets, dtype=torch.float32, device=self.device) def apply_action(self, actions: torch.Tensor, state: ArrayEnvState): - actions = torch.as_tensor(actions, dtype=torch.float32) + actions = torch.as_tensor(actions, dtype=torch.float32, device=self.device) # Copy values: the read buffer is a view that the upcoming physics-step # read overwrites in place. self._last_dof_vel.copy_(self.get_dof_vel()) @@ -229,7 +233,7 @@ def compute_observation(self, state: ArrayEnvState): linear_vel = inputs["local_linvel"] gyro = inputs["gyro"] base_quat = inputs["root_quat"] - local_gravity = rotate_inverse(base_quat, _GRAVITY) + local_gravity = rotate_inverse(base_quat, self._gravity) diff = inputs["robot_joint_pos"] - self.default_angles noisy_linvel = linear_vel * self.cfg.normalization.lin_vel noisy_gyro = gyro * self.cfg.normalization.ang_vel @@ -287,9 +291,9 @@ def update_contact_force(self): self._contact_force.copy_(torch.cat(force, dim=1)) def resample_commands(self, num_envs: int): - low = torch.tensor(self.cfg.commands.vel_limit[0], dtype=torch.float32) - high = torch.tensor(self.cfg.commands.vel_limit[1], dtype=torch.float32) - return low + (high - low) * torch.rand((num_envs, 3), dtype=torch.float32) + low = torch.tensor(self.cfg.commands.vel_limit[0], dtype=torch.float32, device=self.device) + high = torch.tensor(self.cfg.commands.vel_limit[1], dtype=torch.float32, device=self.device) + return low + (high - low) * torch.rand((num_envs, 3), dtype=torch.float32, device=self.device) def update_reward(self, state: ArrayEnvState) -> ArrayEnvState: terminated = state.terminated @@ -303,7 +307,7 @@ def update_reward(self, state: ArrayEnvState) -> ArrayEnvState: termination = self._reward_termination(terminated) * self.cfg.reward_config.scales["termination"] rwd = rwd + termination - rwd = torch.where(terminated, torch.zeros((), dtype=torch.float32), rwd) + rwd = torch.where(terminated, torch.zeros((), dtype=torch.float32, device=self.device), rwd) state.reward.copy_(rwd) @@ -315,7 +319,7 @@ def reset(self, env_ids: torch.Tensor) -> None: num_period = 25 idx = generate_repeating_array(num_period, num_reset, self.period_counter) self.period_counter = (self.period_counter + num_reset) % num_period - base_pose[:, :3] = self.offset_list[torch.as_tensor(idx, dtype=torch.int64)] + base_pose[:, :3] = self.offset_list[torch.as_tensor(idx, dtype=torch.int64, device=self.device)] _reset_pose = base_pose self._reset_position[env_ids] = _reset_pose[:, :3] @@ -366,7 +370,7 @@ def _reward_ang_vel_xy(self): def _reward_orientation(self): # Penalize non flat base orientation base_quat = self.sim_data["root_quat"] - gravity = rotate_inverse(base_quat, _GRAVITY) + gravity = rotate_inverse(base_quat, self._gravity) return torch.sum(torch.square(gravity[:, :2]), dim=1) def _reward_torques(self): @@ -434,7 +438,7 @@ def _reward_calf_pos(self, commands: torch.Tensor): def _reward_feet_stumble(self): # Penalize feet hitting vertical surfaces foot_forces = self.sim_data["foot_contact_forces"] - is_stumble = torch.zeros((self._num_envs,), dtype=torch.float32) + is_stumble = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) for k in range(len(self.cfg.sensor.feet)): contact_force = foot_forces[:, 3 * k : 3 * k + 3] is_stumble += (torch.linalg.vector_norm(contact_force, dim=1) > 5 * torch.abs(contact_force[:, 2])).to( diff --git a/motrix_envs/src/motrix_envs/locomotion/humanoid/cfg.py b/motrix_envs/src/motrix_envs/locomotion/humanoid/cfg.py index 45ab216fc..5a2fe7f65 100644 --- a/motrix_envs/src/motrix_envs/locomotion/humanoid/cfg.py +++ b/motrix_envs/src/motrix_envs/locomotion/humanoid/cfg.py @@ -12,6 +12,8 @@ data those terms consume. No environment subclass is needed. """ +from dataclasses import replace + from motrix_robots.humanoid import HumanoidRobotCfg from motrix_env_core.base import SimCfg @@ -225,9 +227,22 @@ def __post_init__(self) -> None: # static grid so the fused kernel can look up ground heights itself. # The exported query's presence in model.others selects the rough path. floor_obj = getattr(self.scene.objs, "floor", None) - if isinstance(floor_obj, HFieldTerrainCfg): + is_rough = isinstance(floor_obj, HFieldTerrainCfg) + if is_rough: self.queries.model["ground_heightfield"] = HeightFieldDataQuery(geom=ground_geom) + default_contacts, default_constraints = (512, 1536) if is_rough else (256, 768) + if self.sim.max_contacts is None or self.sim.max_contact_constraints is None: + self.sim = replace( + self.sim, + max_contacts=default_contacts if self.sim.max_contacts is None else self.sim.max_contacts, + max_contact_constraints=( + default_constraints + if self.sim.max_contact_constraints is None + else self.sim.max_contact_constraints + ), + ) + # Scene-level facts shared by several terms. self.rewards.feet_phase.ground_geom = ground_geom self.sim_reset.humanoid_state.ground_geom = ground_geom diff --git a/motrix_envs/src/motrix_envs/locomotion/humanoid/dex_evt.py b/motrix_envs/src/motrix_envs/locomotion/humanoid/dex_evt.py index fad7bd4bf..ed2dfd1a4 100644 --- a/motrix_envs/src/motrix_envs/locomotion/humanoid/dex_evt.py +++ b/motrix_envs/src/motrix_envs/locomotion/humanoid/dex_evt.py @@ -117,7 +117,9 @@ def make_dex_evt_walk_flat_cfg() -> HumanoidVelocityTrackingManagerEnvCfg: ground_geom="floor", ) ), - sim=SimCfg(dt=0.005, solver_iterations=6, solver_tolerance=0.0001), + sim=SimCfg( + dt=0.005, solver_iterations=6, solver_tolerance=0.0001, max_contacts=1024, max_contact_constraints=4096 + ), ) @@ -139,6 +141,9 @@ def make_dex_evt_walk_rough_cfg() -> HumanoidVelocityTrackingManagerEnvCfg: robot=_make_dex_evt_robot(), ), ), + sim=SimCfg( + dt=0.005, solver_iterations=6, solver_tolerance=0.0001, max_contacts=1536, max_contact_constraints=6144 + ), sim_reset=WalkResetCfg(humanoid_state=WalkStateResetCfg(spawn_xy_range=4.0)), render_spacing=0.0, ) diff --git a/motrix_envs/src/motrix_envs/locomotion/humanoid/g1.py b/motrix_envs/src/motrix_envs/locomotion/humanoid/g1.py index 7b656d528..c4b0823d7 100644 --- a/motrix_envs/src/motrix_envs/locomotion/humanoid/g1.py +++ b/motrix_envs/src/motrix_envs/locomotion/humanoid/g1.py @@ -149,7 +149,7 @@ def make_g129dof_walk_flat_cfg() -> HumanoidVelocityTrackingManagerEnvCfg: ) ) ), - sim=SimCfg(dt=0.01, solver_iterations=3, solver_tolerance=1e-4), + sim=SimCfg(dt=0.01, solver_iterations=3, solver_tolerance=1e-4, max_contacts=512, max_contact_constraints=1536), ) @@ -169,6 +169,7 @@ def make_g129dof_walk_rough_cfg() -> HumanoidVelocityTrackingManagerEnvCfg: robot=UnitreeG129Dof(), ), ), + sim=SimCfg(dt=0.01, solver_iterations=3, solver_tolerance=1e-4), sim_reset=WalkResetCfg(humanoid_state=WalkStateResetCfg(spawn_xy_range=4.0)), render_spacing=0.0, ) diff --git a/motrix_envs/src/motrix_envs/locomotion/humanoid/k1.py b/motrix_envs/src/motrix_envs/locomotion/humanoid/k1.py index f32d11417..082596840 100644 --- a/motrix_envs/src/motrix_envs/locomotion/humanoid/k1.py +++ b/motrix_envs/src/motrix_envs/locomotion/humanoid/k1.py @@ -115,7 +115,9 @@ def make_k1_walk_flat_cfg() -> HumanoidVelocityTrackingManagerEnvCfg: ), rewards=_make_k1_rewards(), terminations=_make_k1_terminations(), - sim=SimCfg(dt=0.005, solver_iterations=6, solver_tolerance=1e-4), + sim=SimCfg( + dt=0.005, solver_iterations=6, solver_tolerance=1e-4, max_contacts=1024, max_contact_constraints=4096 + ), ) @@ -137,6 +139,9 @@ def make_k1_walk_rough_cfg() -> HumanoidVelocityTrackingManagerEnvCfg: robot=_make_k1_robot(), ), ), + sim=SimCfg( + dt=0.005, solver_iterations=6, solver_tolerance=1e-4, max_contacts=1536, max_contact_constraints=6144 + ), sim_reset=WalkResetCfg(humanoid_state=WalkStateResetCfg(spawn_xy_range=4.0)), render_spacing=0.0, ) diff --git a/motrix_envs/src/motrix_envs/locomotion/humanoid/microduck.py b/motrix_envs/src/motrix_envs/locomotion/humanoid/microduck.py index b6ee8d88d..56b533879 100644 --- a/motrix_envs/src/motrix_envs/locomotion/humanoid/microduck.py +++ b/motrix_envs/src/motrix_envs/locomotion/humanoid/microduck.py @@ -129,6 +129,7 @@ def make_microduck_walk_rough_cfg() -> HumanoidVelocityTrackingManagerEnvCfg: robot=_make_microduck_robot(), ), ), + sim=SimCfg(dt=0.005, solver_iterations=6, solver_tolerance=1e-4), sim_reset=WalkResetCfg(humanoid_state=WalkStateResetCfg(spawn_xy_range=4.0)), render_spacing=0.0, ) diff --git a/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/command.py b/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/command.py index b4da6ec2b..d2c5d0c49 100644 --- a/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/command.py +++ b/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/command.py @@ -6,7 +6,6 @@ import math from dataclasses import dataclass -import numpy as np import torch from motrix_env_core.config import configclass @@ -63,12 +62,10 @@ def _resample_command( resample: torch.Tensor, ) -> None: """Resample velocity commands only on the selected lanes.""" - ids = resample.nonzero().flatten() - sampled = _uniform_range( - ctx.rand.uniform((ids.numel(), 3), dtype=commands.dtype, device=commands.device), low, high - ) - stand = ctx.rand.uniform((ids.numel(),), dtype=commands.dtype, device=commands.device) < float(stand_prob) - commands[ids] = torch.where(stand[:, None], torch.zeros_like(sampled), sampled) + sampled = _uniform_range(ctx.rand.uniform(commands.shape, dtype=commands.dtype, device=commands.device), low, high) + stand = ctx.rand.uniform(resample.shape, dtype=commands.dtype, device=commands.device) < float(stand_prob) + sampled = torch.where(stand[:, None], 0.0, sampled) + commands.copy_(torch.where(resample[:, None], sampled, commands)) @dataclass(frozen=True, slots=True) @@ -172,7 +169,18 @@ def reset(self: "WalkCommand", ctx: ManagerContext, env_ids: torch.Tensor, episo not just terminated/truncated lanes), guarded so a pass with no episode rows leaves both EMA and scale untouched. """ - idx = env_ids + self._reset_rows(ctx, env_ids, episode_reset) + + def reset_masked(self, ctx: ManagerContext, world_mask: torch.Tensor, episode_reset: torch.Tensor) -> None: + self._reset_rows(ctx, ctx.env_id, episode_reset, world_mask) + + def _reset_rows( + self, + ctx: ManagerContext, + idx: torch.Tensor, + episode_reset: torch.Tensor, + world_mask: torch.Tensor | None = None, + ) -> None: episode = episode_reset do_update = episode.any() avg_ep_len = self.avg_ep_len @@ -220,12 +228,18 @@ def reset(self: "WalkCommand", ctx: ManagerContext, env_ids: torch.Tensor, episo stand = ctx.rand.uniform((idx.numel(),), dtype=command.dtype, device=command.device) < float(self.stand_prob) command.copy_(torch.where(stand[:, None], torch.zeros_like(sampled), sampled)) _phase(command, phase, sin_cos, phase_offset, steps[:, 0], phase_step[:, 0]) - self.command[idx] = command - self.phase[idx] = phase - self.sin_cos[idx] = sin_cos - self.phase_offset[idx] = phase_offset - self.phase_step[idx] = phase_step - self.steps[idx] = steps + for target, value in ( + (self.command, command), + (self.phase, phase), + (self.sin_cos, sin_cos), + (self.phase_offset, phase_offset), + (self.phase_step, phase_step), + (self.steps, steps), + ): + if world_mask is None: + target[idx] = value + else: + target.copy_(torch.where(world_mask[:, None], value, target)) @configclass(kw_only=True) @@ -257,13 +271,7 @@ def __call__(self, ctx: BuildContext) -> CommandTerm: vel_limit_high=torch.tensor(self.vel_limit[1], dtype=torch.float32), stand_prob=float(self.stand_prob), resample_steps=float(max(int(round(self.resampling_time / self.ctrl_dt)), 1)), - phase_step=torch.from_numpy( - np.full( - (num_envs, 1), - 2.0 * math.pi * self.ctrl_dt / self.gait_period, - dtype=np.float32, - ) - ), + phase_step=torch.full((num_envs, 1), 2.0 * math.pi * self.ctrl_dt / self.gait_period, dtype=torch.float32), gait_period_base=float(self.gait_period), gait_period_width=float(self.gait_period_randomization_width), curriculum_enabled=self.curriculum_enabled, diff --git a/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/reset.py b/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/reset.py index e2fca956f..3908ceaef 100644 --- a/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/reset.py +++ b/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/reset.py @@ -138,7 +138,8 @@ def _sample_randomized_dynamics( params.friction_range[0], params.friction_range[1], ) - sim_writes["friction"][:, 0, :] = params.friction_default * ratio + sim_writes["friction"][:, 0, :] = params.friction_default + sim_writes["friction"][:, 0, :1] *= ratio mass_randomized = params.mass_scale_range[1] > params.mass_scale_range[0] base_mass_randomized = params.base_mass_off_range[1] > params.base_mass_off_range[0] if mass_randomized or base_mass_randomized: @@ -316,4 +317,5 @@ def __call__(self, ctx: BuildContext) -> ResetTerm: kernel, WalkResetParams(**params), writes=writes, + stateless=True, ) diff --git a/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/rewards.py b/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/rewards.py index f503b1853..1c7e64ef2 100644 --- a/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/rewards.py +++ b/motrix_envs/src/motrix_envs/locomotion/humanoid/walk_manager_mdp/rewards.py @@ -164,7 +164,7 @@ def __call__(self, ctx) -> RewardTerm: return RewardTerm( pose_reward, body.init_joint_pos, - torch.from_numpy(weights), + torch.as_tensor(weights), JointPositionQuery(joints=body.joint_names), ) diff --git a/motrix_envs/src/motrix_envs/locomotion/quadruped/cfg.py b/motrix_envs/src/motrix_envs/locomotion/quadruped/cfg.py index 7c888032d..c4ba218a4 100644 --- a/motrix_envs/src/motrix_envs/locomotion/quadruped/cfg.py +++ b/motrix_envs/src/motrix_envs/locomotion/quadruped/cfg.py @@ -305,7 +305,7 @@ class QuadrupedWalkEnvCfg(DirectEnvCfg): gait_schedule_lateral_weight: float = 1.00 # Shared by training and the compiled deployment task, not backend recipes. termination_min_up_z: float = 0.5 - sim: SimCfg = SimCfg(dt=0.01, solver_iterations=1) + sim: SimCfg = SimCfg(dt=0.01, solver_iterations=1, max_contacts=128, max_contact_constraints=384) ctrl_dt: float = 0.02 def validate(self) -> None: diff --git a/motrix_envs/src/motrix_envs/locomotion/quadruped/velocity_command.py b/motrix_envs/src/motrix_envs/locomotion/quadruped/velocity_command.py index d66602139..338214085 100644 --- a/motrix_envs/src/motrix_envs/locomotion/quadruped/velocity_command.py +++ b/motrix_envs/src/motrix_envs/locomotion/quadruped/velocity_command.py @@ -26,7 +26,7 @@ def __init__( self._upper = upper self._standing_probability = standing_probability self._hard_case_probability = hard_case_probability - self._hard_cases = torch.as_tensor(hard_cases, dtype=torch.float32) + self._hard_cases = torch.as_tensor(hard_cases, dtype=torch.float32, device=rng.device) self._rng = rng if hard_case_probability > 0.0 and not hard_cases: @@ -35,14 +35,18 @@ def __init__( raise ValueError("hard-case commands must lie inside the configured velocity bounds") def read_command(self, *, batch_size: int = 1) -> PlanarVelocityCommand: - u = torch.rand((batch_size, 3), generator=self._rng) + u = torch.rand((batch_size, 3), generator=self._rng, device=self._rng.device) values = self._lower + (self._upper - self._lower) * u if self._hard_case_probability > 0.0: - hard = torch.rand((batch_size,), generator=self._rng) < self._hard_case_probability - choices = torch.randint(self._hard_cases.shape[0], (batch_size,), generator=self._rng) + hard = torch.rand((batch_size,), generator=self._rng, device=self._rng.device) < self._hard_case_probability + choices = torch.randint( + self._hard_cases.shape[0], (batch_size,), generator=self._rng, device=self._rng.device + ) values[hard] = self._hard_cases[choices[hard]] if self._standing_probability > 0.0: - standing = torch.rand((batch_size,), generator=self._rng) < self._standing_probability + standing = ( + torch.rand((batch_size,), generator=self._rng, device=self._rng.device) < self._standing_probability + ) values[standing] = 0.0 return PlanarVelocityCommand(values) diff --git a/motrix_envs/src/motrix_envs/locomotion/quadruped/walk_np.py b/motrix_envs/src/motrix_envs/locomotion/quadruped/walk_np.py index ce97f9d38..fb2890efd 100644 --- a/motrix_envs/src/motrix_envs/locomotion/quadruped/walk_np.py +++ b/motrix_envs/src/motrix_envs/locomotion/quadruped/walk_np.py @@ -49,9 +49,7 @@ def _torch_uniform(rng: torch.Generator, low, high, size) -> torch.Tensor: """Sample float32 uniform values in ``[low, high)`` from one torch stream.""" - low = torch.as_tensor(low, dtype=torch.float32) - high = torch.as_tensor(high, dtype=torch.float32) - return low + (high - low) * torch.rand(size, generator=rng) + return low + (high - low) * torch.rand(size, generator=rng, device=rng.device) def _sim_data_queries(cfg: QuadrupedWalkEnvCfg): @@ -186,6 +184,7 @@ def __init__( raise ValueError("Quadruped walk foot position sensor names must be unique") super().__init__(cfg, num_envs, backend=backend, **kwargs) + self._footprint = _FOOTPRINT.to(self.device) self.model = self.sim.compile_model(_sim_model_queries(cfg)) self.sim_data = self.sim.compile_reads(_sim_data_queries(cfg)) self._ctrl_writes = self.sim.write_compiler.compile({"ctrl": CtrlTargetsWrite()}) @@ -220,14 +219,14 @@ def __init__( # Two independent torch streams derived from one root seed drawn from # the global torch RNG (training frameworks seed torch, so runs stay # reproducible under their seeding). - root_seed = int(torch.randint(0, 2**32 - 1, (1,)).item()) - self._command_rng = torch.Generator() + root_seed = int(torch.randint(0, 2**32 - 1, (1,), device=self.device).item()) + self._command_rng = torch.Generator(device=self.device) self._command_rng.manual_seed(root_seed) - self._randomization_rng = torch.Generator() + self._randomization_rng = torch.Generator(device=self.device) self._randomization_rng.manual_seed(root_seed + 1) self._velocity_command_binding = RandomPlanarVelocityBinding( - torch.as_tensor(velocity_cfg.lower, dtype=torch.float32), - torch.as_tensor(velocity_cfg.upper, dtype=torch.float32), + torch.as_tensor(velocity_cfg.lower, dtype=torch.float32, device=self.device), + torch.as_tensor(velocity_cfg.upper, dtype=torch.float32, device=self.device), rng=self._command_rng, standing_probability=velocity_cfg.standing_probability, hard_case_probability=velocity_cfg.hard_case_probability, @@ -238,24 +237,27 @@ def __init__( f"standing_threshold must be finite and non-negative, got {velocity_cfg.standing_threshold}" ) - self.default_angles = _resolve_key_pose(robot, self.model.actuators, cfg.key_pose_name) + self.default_angles = _resolve_key_pose(robot, self.model.actuators, cfg.key_pose_name).to(self.device) if self.default_angles.shape != (self._num_action,): raise ValueError( "Quadruped default joint positions must match actuator count: " f"got {tuple(self.default_angles.shape)}, expected {(self._num_action,)}" ) - ctrl_ranges = torch.tensor([spec.ctrl_range for spec in self.model.actuators], dtype=torch.float32) + ctrl_ranges = torch.tensor( + [spec.ctrl_range for spec in self.model.actuators], dtype=torch.float32, device=self.device + ) self._joint_position_lower = ctrl_ranges[:, 0] self._joint_position_upper = ctrl_ranges[:, 1] self._init_action_space() self._init_observation_spec() self._init_base_pose = self.model.init_dof_pos[:7].clone() - self._init_base_pose[:3] = torch.tensor(cfg.initial_base_position, dtype=torch.float32) + self._init_base_pose[:3] = torch.tensor(cfg.initial_base_position, dtype=torch.float32, device=self.device) self._init_joint_position = self.default_angles.clone() self._hip_indices = torch.tensor( [index for index, actuator in enumerate(self.model.actuators) if "hip" in actuator.target_name], dtype=torch.int64, + device=self.device, ) has_non_position_actuator = any( @@ -263,6 +265,15 @@ def __init__( ) if cfg.randomization.enabled and has_non_position_actuator: raise TypeError("Quadruped PD randomization requires position actuators") + self._base_lin_vel_noise = torch.as_tensor( + cfg.randomization.base_lin_vel_noise, dtype=torch.float32, device=self.device + ) + self._base_ang_vel_noise = torch.as_tensor( + cfg.randomization.base_ang_vel_noise, dtype=torch.float32, device=self.device + ) + self._base_com_offset_noise = torch.as_tensor( + cfg.randomization.base_com_offset_noise, dtype=torch.float32, device=self.device + ) self._randomize_action_delay = cfg.randomization.enabled and any(cfg.randomization.action_delay_steps) # Declare the enabled override writes once and batch every reset's # randomization into a single program execution. @@ -285,31 +296,35 @@ def __init__( randomize_writes["com"] = LinkComWrite((self._base_link_name,)) self._randomize_writes = self.sim.write_compiler.compile(randomize_writes) if randomize_writes else None - self.feet_contact = torch.zeros((num_envs, self._num_feet), dtype=torch.bool) - self._last_feet_contact = torch.zeros((num_envs, self._num_feet), dtype=torch.bool) - self.feet_pos = torch.zeros((num_envs, self._num_feet, 3), dtype=torch.float32) + self.feet_contact = torch.zeros((num_envs, self._num_feet), dtype=torch.bool, device=self.device) + self._last_feet_contact = torch.zeros((num_envs, self._num_feet), dtype=torch.bool, device=self.device) + self.feet_pos = torch.zeros((num_envs, self._num_feet, 3), dtype=torch.float32, device=self.device) self._last_feet_pos = torch.zeros_like(self.feet_pos) self.feet_world_pos = torch.zeros_like(self.feet_pos) self._last_feet_world_pos = torch.zeros_like(self.feet_world_pos) - self._static_anchor_pos = torch.zeros((num_envs, self._num_feet, 2), dtype=torch.float32) - self._static_anchor_valid = torch.zeros((num_envs, self._num_feet), dtype=torch.bool) - self._last_joint_vel = torch.zeros((num_envs, self._num_action), dtype=torch.float32) + self._static_anchor_pos = torch.zeros((num_envs, self._num_feet, 2), dtype=torch.float32, device=self.device) + self._static_anchor_valid = torch.zeros((num_envs, self._num_feet), dtype=torch.bool, device=self.device) + self._last_joint_vel = torch.zeros((num_envs, self._num_action), dtype=torch.float32, device=self.device) self._default_feet_width: torch.Tensor | None = None self._default_base_com_forward_offset: torch.Tensor | None = None # Episode-scoped task state: full-batch buffers, reset writes the done # rows in place. - self._commands = torch.zeros((num_envs, 3), dtype=torch.float32) - self._command_resampling_time = torch.full((num_envs,), torch.inf, dtype=torch.float32) + self._commands = torch.zeros((num_envs, 3), dtype=torch.float32, device=self.device) + self._command_resampling_time = torch.full((num_envs,), torch.inf, dtype=torch.float32, device=self.device) self._command_control_steps = 0 - self._phase = torch.zeros(num_envs, dtype=torch.float32) - self._feet_phase = torch.zeros((num_envs, self._num_feet), dtype=torch.float32) - self._gait_schedule_alpha = torch.zeros(num_envs, dtype=torch.float32) - self._gait_frequency = torch.full((num_envs,), float(cfg.gait_frequency), dtype=torch.float32) - self._swing_fraction = torch.full((num_envs,), float(cfg.reward_config.swing_fraction), dtype=torch.float32) - self._current_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32) - self._last_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32) - self._action_delay_steps = torch.zeros(num_envs, dtype=torch.int64) + self._phase = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._feet_phase = torch.zeros((num_envs, self._num_feet), dtype=torch.float32, device=self.device) + self._gait_schedule_alpha = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._gait_frequency = torch.full( + (num_envs,), float(cfg.gait_frequency), dtype=torch.float32, device=self.device + ) + self._swing_fraction = torch.full( + (num_envs,), float(cfg.reward_config.swing_fraction), dtype=torch.float32, device=self.device + ) + self._current_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32, device=self.device) + self._action_delay_steps = torch.zeros(num_envs, dtype=torch.int64, device=self.device) self._set_hard_case_probability(0) # ---- obs/action space plumbing ---------------------------------------- @@ -372,13 +387,13 @@ def _obs_noise(self, data: torch.Tensor, scale: float) -> torch.Tensor: level = float(self.cfg.noise_config.level) if level <= 0.0: return data - noise = torch.rand(data.shape, dtype=torch.float32) * 2.0 - 1.0 + noise = torch.rand(data.shape, dtype=torch.float32, device=self.device) * 2.0 - 1.0 return data + level * scale * noise def _read_feet_contact(self, env_ids: torch.Tensor | None = None) -> torch.Tensor: rows = slice(None) if env_ids is None else env_ids inputs = self.sim_data - contacts = torch.zeros((self._num_envs, self._num_feet), dtype=torch.bool) + contacts = torch.zeros((self._num_envs, self._num_feet), dtype=torch.bool, device=self.device) for i, name in enumerate(self._feet_contact_sensors): contacts[rows, i] = inputs[name][rows, 0] > 0.0 return contacts @@ -444,7 +459,7 @@ def _advance_phase(self): # ---- env loop --------------------------------------------------------- def apply_action(self, actions: torch.Tensor, state: ArrayEnvState) -> None: - actions = torch.as_tensor(actions, dtype=torch.float32) + actions = torch.as_tensor(actions, dtype=torch.float32, device=self.device) self._last_actions.copy_(self._current_actions) self._current_actions.copy_(actions) if self._randomize_action_delay: @@ -514,7 +529,7 @@ def compute_transition(self, state: ArrayEnvState) -> None: def _compute_reward( self, state: ArrayEnvState, linvel: torch.Tensor, gyro: torch.Tensor, dof_pos: torch.Tensor ) -> torch.Tensor: - reward = torch.zeros((self._num_envs,), dtype=torch.float32) + reward = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) reward_cfg = self.cfg.reward_config reward_fns = { "tracking_lin_vel": self._reward_tracking_lin_vel, @@ -555,17 +570,19 @@ def reset(self, env_ids: torch.Tensor) -> None: self._capture_default_feet_width(env_ids) base_pose = self._init_base_pose.repeat(num_reset, 1) - base_linear_velocity = torch.zeros((num_reset, 3), dtype=torch.float32) - base_angular_velocity = torch.zeros((num_reset, 3), dtype=torch.float32) + base_linear_velocity = torch.zeros((num_reset, 3), dtype=torch.float32, device=self.device) + base_angular_velocity = torch.zeros((num_reset, 3), dtype=torch.float32, device=self.device) joint_position = self._init_joint_position.repeat(num_reset, 1) - joint_velocity = torch.zeros((num_reset, self._reset_joint_velocity.shape[1]), dtype=torch.float32) + joint_velocity = torch.zeros( + (num_reset, self._reset_joint_velocity.shape[1]), dtype=torch.float32, device=self.device + ) self._randomize_dof_noise(env_ids, base_linear_velocity, base_angular_velocity, joint_position, joint_velocity) spawn_range = self.cfg.spawn_xy_range if spawn_range > 0.0: - xy = (torch.rand(num_reset, 2, dtype=torch.float32) * 2.0 - 1.0) * spawn_range + xy = (torch.rand(num_reset, 2, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * spawn_range ground_height = ( - self.sim.sample_terrain_height(self.cfg.ground_geom_name, env_ids, xy[:, None, :] + _FOOTPRINT) + self.sim.sample_terrain_height(self.cfg.ground_geom_name, env_ids, xy[:, None, :] + self._footprint) .max(dim=1) .values ) @@ -591,7 +608,9 @@ def reset(self, env_ids: torch.Tensor) -> None: self._last_feet_world_pos[env_ids] = self.feet_world_pos[env_ids] self._last_joint_vel[env_ids] = self.get_dof_vel()[env_ids] - self._commands[env_ids] = torch.as_tensor(self.resample_commands(num_reset), dtype=torch.float32) + self._commands[env_ids] = torch.as_tensor( + self.resample_commands(num_reset), dtype=torch.float32, device=self.device + ) self._command_resampling_time[env_ids] = self._sample_command_resampling_time(num_reset) self._phase[env_ids] = 0.0 self._feet_phase[env_ids] = 0.0 @@ -631,7 +650,7 @@ def _capture_default_feet_width(self, env_ids: torch.Tensor) -> None: num_reset = env_ids.numel() base_pose = self._init_base_pose.repeat(num_reset, 1) joint_position = self._init_joint_position.repeat(num_reset, 1) - joint_velocity = torch.zeros((num_reset, self._reset_joint_velocity.shape[1]), dtype=torch.float32) + joint_velocity = torch.zeros_like(self._reset_joint_velocity[env_ids]) self._reset_position[env_ids] = base_pose[:, :3] self._reset_rotation[env_ids] = base_pose[:, 3:7] @@ -661,7 +680,7 @@ def resample_commands(self, num_envs: int) -> torch.Tensor: def _sample_command_resampling_time(self, num_envs: int) -> torch.Tensor: interval = self.cfg.commands.velocity.resampling_seconds_range if interval is None: - return torch.full((num_envs,), torch.inf, dtype=torch.float32) + return torch.full((num_envs,), torch.inf, dtype=torch.float32, device=self.device) low, high = interval return _torch_uniform(self._command_rng, low, high, (num_envs,)) @@ -673,7 +692,9 @@ def _update_commands(self) -> None: due = remaining <= 0.0 num_due = int(due.sum()) if num_due: - self._commands[due] = torch.as_tensor(self.resample_commands(num_due), dtype=torch.float32) + self._commands[due] = torch.as_tensor( + self.resample_commands(num_due), dtype=torch.float32, device=self.device + ) remaining[due] = self._sample_command_resampling_time(num_due) def _randomize_dof_noise( @@ -706,10 +727,10 @@ def _randomize_dof_noise( ) if any(randomization.base_lin_vel_noise): - noise = torch.as_tensor(randomization.base_lin_vel_noise, dtype=torch.float32) + noise = self._base_lin_vel_noise base_linear_velocity += _torch_uniform(rng, -noise, noise, (num_reset, 3)) if any(randomization.base_ang_vel_noise): - noise = torch.as_tensor(randomization.base_ang_vel_noise, dtype=torch.float32) + noise = self._base_ang_vel_noise base_angular_velocity += _torch_uniform(rng, -noise, noise, (num_reset, 3)) def _randomize_params(self, env_ids: torch.Tensor) -> None: @@ -723,10 +744,10 @@ def _randomize_params(self, env_ids: torch.Tensor) -> None: if self._randomize_action_delay: delay_low, delay_high = randomization.action_delay_steps if delay_low == delay_high: - self._action_delay_steps[env_ids] = delay_low + self._action_delay_steps.index_fill_(0, env_ids.long(), delay_low) else: self._action_delay_steps[env_ids] = torch.randint( - delay_low, delay_high + 1, (num_reset,), generator=rng + delay_low, delay_high + 1, (num_reset,), generator=rng, device=self.device ) # All override writes for this reset batch into one program execution. @@ -757,7 +778,7 @@ def _randomize_params(self, env_ids: torch.Tensor) -> None: base_mass_scale = _torch_uniform(rng, *self.cfg.randomization.base_mass_scale_range, (num_reset,)) program.buffer("mass")[env_ids, 0] = self.model.others["base_mass"] * base_mass_scale if self._randomize_base_com: - noise = torch.as_tensor(self.cfg.randomization.base_com_offset_noise, dtype=torch.float32) + noise = self._base_com_offset_noise base_com_offset = _torch_uniform(rng, -noise, noise, (num_reset, 3)) program.buffer("com")[env_ids, 0] = self.model.others["base_com"] + base_com_offset program.execute(env_ids) @@ -773,6 +794,7 @@ def _reward_tracking_lin_vel(self, linvel, gyro, dof_pos) -> torch.Tensor: (self._num_envs, 2), float(reward_cfg.tracking_lin_vel_sigma), dtype=torch.float32, + device=self.device, ) forward_sigma = reward_cfg.tracking_lin_vel_forward_sigma if forward_sigma is not None: @@ -803,7 +825,7 @@ def _reward_ang_vel_xy(self, linvel, gyro, dof_pos) -> torch.Tensor: def _reward_base_height(self, linvel, gyro, dof_pos) -> torch.Tensor: del linvel, gyro, dof_pos base_pos = self.sim_data["base_pos"] - env_ids = torch.arange(self._num_envs, dtype=torch.int64) + env_ids = torch.arange(self._num_envs, dtype=torch.int64, device=self.device) ground_height = self.sim.sample_terrain_height(self.cfg.ground_geom_name, env_ids, base_pos[:, None, :2])[:, 0] base_height = base_pos[:, 2].to(torch.float32) - ground_height return torch.square(base_height - self.cfg.reward_config.base_height_target) @@ -842,7 +864,7 @@ def _posture_constraint_scale(self) -> torch.Tensor: def _reward_feet_spacing(self, linvel, gyro, dof_pos) -> torch.Tensor: del linvel, gyro, dof_pos if self._default_feet_width is None: - return torch.zeros((self._num_envs,), dtype=torch.float32) + return torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) front_width = self.feet_pos[:, 0, 1] - self.feet_pos[:, 1, 1] rear_width = self.feet_pos[:, 2, 1] - self.feet_pos[:, 3, 1] @@ -913,7 +935,7 @@ def _reward_touchdown_velocity(self, linvel, gyro, dof_pos) -> torch.Tensor: def _reward_contact(self, linvel, gyro, dof_pos) -> torch.Tensor: del linvel, gyro, dof_pos - res = torch.zeros((self._num_envs,), dtype=torch.float32) + res = torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) feet_phase = self._feet_phase contacts = self.feet_contact swing_start = 1.0 - self._swing_fraction @@ -1004,8 +1026,8 @@ def _reward_dof_acc(self, linvel, gyro, dof_pos) -> torch.Tensor: def _reward_hip_position(self, linvel, gyro, dof_pos) -> torch.Tensor: del linvel, gyro - if self._hip_indices.size == 0: - return torch.zeros((self._num_envs,), dtype=torch.float32) + if self._hip_indices.numel() == 0: + return torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) reward_cfg = self.cfg.reward_config hip_error = torch.abs(dof_pos[:, self._hip_indices] - self.default_angles[self._hip_indices]) @@ -1023,7 +1045,7 @@ def _reward_base_com_position(self, linvel, gyro, dof_pos) -> torch.Tensor: del linvel, gyro, dof_pos reward_cfg = self.cfg.reward_config if self._default_base_com_forward_offset is None: - return torch.zeros((self._num_envs,), dtype=torch.float32) + return torch.zeros((self._num_envs,), dtype=torch.float32, device=self.device) base_com_x = float(self.model.others["base_com"][0]) # Keep the training reference identical to the audit metric: diff --git a/motrix_envs/src/motrix_envs/locomotion/wbt/cfg.py b/motrix_envs/src/motrix_envs/locomotion/wbt/cfg.py index 4e31f5a00..40984bbfc 100644 --- a/motrix_envs/src/motrix_envs/locomotion/wbt/cfg.py +++ b/motrix_envs/src/motrix_envs/locomotion/wbt/cfg.py @@ -207,7 +207,7 @@ class WbtEnvCfg(ManagerBasedEnvCfg): max_episode_seconds: float = 10.0 sim_reset: ManagerResetCfg = ResetCfg() - sim: SimCfg = SimCfg(dt=0.005) + sim: SimCfg = SimCfg(dt=0.005, max_contacts=256, max_contact_constraints=768) ctrl_dt: float = 0.02 commands: CommandsCfg = CommandsCfg() actions: ActionsCfg = ActionsCfg() diff --git a/motrix_envs/src/motrix_envs/locomotion/wbt/dex_evt.py b/motrix_envs/src/motrix_envs/locomotion/wbt/dex_evt.py index 1102f9ca8..74ecfb51d 100644 --- a/motrix_envs/src/motrix_envs/locomotion/wbt/dex_evt.py +++ b/motrix_envs/src/motrix_envs/locomotion/wbt/dex_evt.py @@ -61,7 +61,9 @@ class DexEvtWbtEnvCfg(WbtEnvCfg): action_scales_by_effort_limit_over_p_gain=False, ), ) - sim: SimCfg = SimCfg(dt=0.005, solver_iterations=6, solver_tolerance=0.0001) + sim: SimCfg = SimCfg( + dt=0.005, solver_iterations=6, solver_tolerance=0.0001, max_contacts=1024, max_contact_constraints=4096 + ) scene: StandardSceneCfg = StandardSceneCfg( system_camera=SystemCameraCfg(distance=7.0, elevation=-20.0, azimuth=180.0), objs=StandardSceneObjsCfg( diff --git a/motrix_envs/src/motrix_envs/locomotion/wbt/g1/backflip.py b/motrix_envs/src/motrix_envs/locomotion/wbt/g1/backflip.py index 44813744d..b869ab71c 100644 --- a/motrix_envs/src/motrix_envs/locomotion/wbt/g1/backflip.py +++ b/motrix_envs/src/motrix_envs/locomotion/wbt/g1/backflip.py @@ -6,7 +6,7 @@ from motrix_robots.unitree import UnitreeG129Dof from motrix_env_core import registry -from motrix_env_core.base import EnvCfg, SimCfg +from motrix_env_core.base import EnvCfg from motrix_env_core.config import configclass from motrix_env_core.config.scene import SystemCameraCfg from motrix_env_core.manager import ManagerEnv @@ -92,7 +92,8 @@ class G1BackflipWbtEnvCfg(G1WbtEnvCfg): the sole anchor-position check, backed by the tilt-only orientation check and body-z/NaN guards. Rewards and reset are the holosoma fastsac recipe unchanged (centered-noise reference-state teleport with - velocities, mixed frame sampling). + velocities, mixed frame sampling). The inherited 5 ms physics step resolves + the roughly 0.1 s ground-contact impulse at launch. """ scene: StandardSceneCfg = StandardSceneCfg( @@ -100,11 +101,6 @@ class G1BackflipWbtEnvCfg(G1WbtEnvCfg): objs=StandardSceneObjsCfg(robot=UnitreeG129Dof()), ) - # The launch impulse that creates angular momentum spans ~0.1 s of - # ground contact; a coarser timestep loses it to the contact solve and - # the flip stops being learnable, despite the higher collector - # throughput. - sim: SimCfg = SimCfg(dt=0.005, solver_iterations=3) render_spacing: float = 1.5 commands: CommandsCfg = CommandsCfg( diff --git a/motrix_envs/src/motrix_envs/locomotion/wbt/g1/common.py b/motrix_envs/src/motrix_envs/locomotion/wbt/g1/common.py index 662df59ca..ae982d0cd 100644 --- a/motrix_envs/src/motrix_envs/locomotion/wbt/g1/common.py +++ b/motrix_envs/src/motrix_envs/locomotion/wbt/g1/common.py @@ -43,7 +43,7 @@ class G1WbtEnvCfg(WbtEnvCfg): motion_files: InitVar[tuple[str, ...] | None] = None commands: CommandsCfg = CommandsCfg(motion=WbtMotionCommandCfg()) - sim: SimCfg = SimCfg(dt=0.005, solver_iterations=3) + sim: SimCfg = SimCfg(dt=0.005, solver_iterations=3, max_contacts=128, max_contact_constraints=384) scene: StandardSceneCfg = StandardSceneCfg( system_camera=SystemCameraCfg(distance=6.0, elevation=-20.0, azimuth=180.0), objs=StandardSceneObjsCfg(robot=UnitreeG129Dof()), diff --git a/motrix_envs/src/motrix_envs/locomotion/wbt/k1.py b/motrix_envs/src/motrix_envs/locomotion/wbt/k1.py index fe6cfbcad..96a185e2c 100644 --- a/motrix_envs/src/motrix_envs/locomotion/wbt/k1.py +++ b/motrix_envs/src/motrix_envs/locomotion/wbt/k1.py @@ -60,7 +60,9 @@ class K1WbtEnvCfg(WbtEnvCfg): action_scales_by_effort_limit_over_p_gain=False, ), ) - sim: SimCfg = SimCfg(dt=0.005, solver_iterations=6, solver_tolerance=1e-4) + sim: SimCfg = SimCfg( + dt=0.005, solver_iterations=6, solver_tolerance=1e-4, max_contacts=1024, max_contact_constraints=4096 + ) scene: StandardSceneCfg = StandardSceneCfg( system_camera=SystemCameraCfg(distance=6.0, elevation=-20.0, azimuth=180.0), objs=StandardSceneObjsCfg(robot=BoosterK1()), diff --git a/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/command.py b/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/command.py index aa91be48a..bb6255965 100644 --- a/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/command.py +++ b/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/command.py @@ -151,19 +151,32 @@ def reset(self, ctx: ManagerContext, env_ids: torch.Tensor, episode_reset: torch frame indices back; finally the sampler opens new episodes on the episode rows. """ - idx = env_ids - self.sampler.fold_episode_stats(idx, episode_reset, ctx.terminated, self.steps[idx, 0]) - self.sampler.rebuild() - if bool(self.sequential_clips): - # Sequential playback rematerializes onto the current frame. - self.sampler.mark_episode_starts(idx, episode_reset, self.steps[idx, 0]) - return - draws = 2 * ctx.rand.uniform((idx.numel(), self.sampler.draw_count), device=self.steps.device) - 1 - steps = self.sampler.sample(draws, self.start_at_timestep_zero_prob) - # ``clip_ended`` is intentionally left untouched; advance recomputes it - # on the following transition. - self.steps[idx, 0] = steps - self.sampler.mark_episode_starts(idx, episode_reset, self.steps[idx, 0]) + self._reset_rows(ctx, env_ids, episode_reset) + + def reset_masked(self, ctx: ManagerContext, world_mask: torch.Tensor, episode_reset: torch.Tensor) -> None: + self._reset_rows(ctx, ctx.env_id, episode_reset, world_mask) + + def _reset_rows( + self, + ctx: ManagerContext, + idx: torch.Tensor, + episode_reset: torch.Tensor, + world_mask: torch.Tensor | None = None, + ) -> None: + steps = self.steps[idx, 0] + self.sampler.fold_episode_stats(idx, episode_reset, ctx.terminated, steps) + self.sampler.rebuild(active=None if world_mask is None else world_mask.any()) + if not bool(self.sequential_clips): + draws = 2 * ctx.rand.uniform((idx.numel(), self.sampler.draw_count), device=self.steps.device) - 1 + sampled = self.sampler.sample(draws, self.start_at_timestep_zero_prob) + if world_mask is None: + self.steps[idx, 0] = sampled + steps = sampled + else: + steps = torch.where(world_mask, sampled, steps) + self.steps[:, 0].copy_(steps) + # Advance recomputes clip_ended on the next transition. + self.sampler.mark_episode_starts(idx, episode_reset, steps) @configclass(kw_only=True) diff --git a/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/observations.py b/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/observations.py index 5bc46a888..3d04d3552 100644 --- a/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/observations.py +++ b/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/observations.py @@ -157,7 +157,7 @@ def __call__(self, ctx) -> ObsTerm: if missing: raise ValueError(f"RobotCfg {robot_name!r} key pose is missing queried joints: {missing}.") reference = np.asarray([positions[name] for name in queried_joints], dtype=np.float32) - params = RelativePositionParams(torch.from_numpy(reference), float(self.noise.amplitude)) + params = RelativePositionParams(torch.as_tensor(reference), float(self.noise.amplitude)) return ObsTerm(reference.shape[0], dof_pos_rel_obs, params) diff --git a/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/reset.py b/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/reset.py index 23a09f814..81e26b38f 100644 --- a/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/reset.py +++ b/motrix_envs/src/motrix_envs/locomotion/wbt/mdp/reset.py @@ -53,8 +53,9 @@ def __call__(self, ctx) -> ResetTerm: amplitude = np.asarray(self.noise, dtype=np.float32) * np.float32(self.noise_scale) return ResetTerm( _reset_body_pos, - torch.from_numpy(amplitude), + torch.as_tensor(amplitude), writes={"position": BodyPositionWrite((body,))}, + stateless=True, ) @@ -107,8 +108,9 @@ def __call__(self, ctx) -> ResetTerm: amplitude = np.asarray(self.noise, dtype=np.float32) * np.float32(self.noise_scale) return ResetTerm( _reset_body_rot, - torch.from_numpy(amplitude), + torch.as_tensor(amplitude), writes={"rotation": BodyRotationWrite((body,))}, + stateless=True, ) @@ -138,8 +140,9 @@ def __call__(self, ctx) -> ResetTerm: amplitude = np.asarray(self.noise, dtype=np.float32) * np.float32(self.noise_scale) return ResetTerm( _reset_body_lin_vel, - torch.from_numpy(amplitude), + torch.as_tensor(amplitude), writes={"linear_velocity": BodyLinearVelocityWrite((body,))}, + stateless=True, ) @@ -169,8 +172,9 @@ def __call__(self, ctx) -> ResetTerm: amplitude = np.asarray(self.noise, dtype=np.float32) * np.float32(self.noise_scale) return ResetTerm( _reset_body_rot_vel, - torch.from_numpy(amplitude), + torch.as_tensor(amplitude), writes={"angular_velocity": BodyAngularVelocityWrite((body,))}, + stateless=True, ) @@ -203,4 +207,5 @@ def __call__(self, ctx) -> ResetTerm: _reset_body_dof_pos, float(self.noise * self.noise_scale), writes={"position": JointPositionWrite(joints), "velocity": JointVelocityWrite(joints)}, + stateless=True, ) diff --git a/motrix_envs/src/motrix_envs/manipulation/franka_lift_cube/cfg.py b/motrix_envs/src/motrix_envs/manipulation/franka_lift_cube/cfg.py index 414abd5c4..a9f17e9ce 100755 --- a/motrix_envs/src/motrix_envs/manipulation/franka_lift_cube/cfg.py +++ b/motrix_envs/src/motrix_envs/manipulation/franka_lift_cube/cfg.py @@ -67,7 +67,7 @@ class FrankaLiftCubeEnvCfg(DirectEnvCfg): render_spacing: float = 2.0 scene: SceneCfg = SceneCfg(file=model_file) max_episode_seconds: float = 2.5 - sim: SimCfg = SimCfg(dt=0.01) + sim: SimCfg = SimCfg(dt=0.01, max_contacts=128, max_contact_constraints=384) move_speed: float = 1.0 ctrl_dt: float = 0.01 reset_noise_scale = 0.05 diff --git a/motrix_envs/src/motrix_envs/manipulation/franka_lift_cube/franka_lift_cube_np.py b/motrix_envs/src/motrix_envs/manipulation/franka_lift_cube/franka_lift_cube_np.py index 4ae8bf4cd..7190aab19 100755 --- a/motrix_envs/src/motrix_envs/manipulation/franka_lift_cube/franka_lift_cube_np.py +++ b/motrix_envs/src/motrix_envs/manipulation/franka_lift_cube/franka_lift_cube_np.py @@ -71,7 +71,9 @@ def __init__( }, reset=True, ) - self.default_joint_pos = torch.as_tensor(self._cfg.init_state.default_joint_pos, dtype=torch.float32) + self.default_joint_pos = torch.as_tensor( + self._cfg.init_state.default_joint_pos, dtype=torch.float32, device=self.device + ) self._action_dim = 8 self._obs_dim = 36 # 9 + 9 + 3 + 7 + 8 @@ -83,10 +85,14 @@ def __init__( self._num_dof_pos = 9 # self._model.num_dof_pos # 9 self._num_dof_vel = 9 # self._model.num_dof_vel # 9 self._init_dof_pos = self.default_joint_pos - self._init_dof_vel = torch.zeros(self._num_dof_vel, dtype=torch.float32) + self._init_dof_vel = torch.zeros(self._num_dof_vel, dtype=torch.float32, device=self.device) - self.joint_pos_min_limit = torch.tensor(self._cfg.control_config.min_pos, dtype=torch.float32) - self.joint_pos_max_limit = torch.tensor(self._cfg.control_config.max_pos, dtype=torch.float32) + self.joint_pos_min_limit = torch.tensor( + self._cfg.control_config.min_pos, dtype=torch.float32, device=self.device + ) + self.joint_pos_max_limit = torch.tensor( + self._cfg.control_config.max_pos, dtype=torch.float32, device=self.device + ) self.epsilon = START_EPSILON @@ -95,9 +101,9 @@ def __init__( # Episode-scoped task state: full-batch buffers, reset writes the done # rows in place. num_envs = self._num_envs - self._commands = torch.zeros(num_envs, 3, dtype=torch.float32) - self._current_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32) - self._last_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32) + self._commands = torch.zeros(num_envs, 3, dtype=torch.float32, device=self.device) + self._current_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32, device=self.device) @property def observation_spec(self) -> ObservationSpec: @@ -190,7 +196,7 @@ def reset(self, env_ids: torch.Tensor) -> None: # Robot arm initial joint angle noise noise_scale = self._cfg.init_state.joint_pos_reset_noise_scale - noise_pos = (torch.rand(self._num_dof_pos, dtype=torch.float32) * 2.0 - 1.0) * noise_scale + noise_pos = (torch.rand(self._num_dof_pos, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * noise_scale robot_dof_pos = self._init_dof_pos + noise_pos # Domain randomization for cube position @@ -198,16 +204,16 @@ def reset(self, env_ids: torch.Tensor) -> None: # y -0.25, 0.25 x_low, x_high = -0.1, 0.1 y_low, y_high = -0.25, 0.25 - pos_x = torch.rand((), dtype=torch.float32) * (x_high - x_low) + x_low - pos_y = torch.rand((), dtype=torch.float32) * (y_high - y_low) + y_low + pos_x = torch.rand((), dtype=torch.float32, device=self.device) * (x_high - x_low) + x_low + pos_y = torch.rand((), dtype=torch.float32, device=self.device) * (y_high - y_low) + y_low self._reset_program.buffer("robot_position")[env_ids] = robot_dof_pos self._reset_program.buffer("robot_velocity")[env_ids] = self._init_dof_vel self._reset_program.buffer("cube_position")[env_ids, 0] = torch.tensor( - [pos_x, pos_y, 0.05], dtype=torch.float32 + [pos_x, pos_y, 0.05], dtype=torch.float32, device=self.device ) self._reset_program.buffer("cube_rotation")[env_ids, 0] = torch.tensor( - [1.0, 0.0, 0.0, 0.0], dtype=torch.float32 + [1.0, 0.0, 0.0, 0.0], dtype=torch.float32, device=self.device ) self._reset_program.buffer("cube_linear_velocity")[:, 0][env_ids] = 0.0 self._reset_program.buffer("cube_angular_velocity")[:, 0][env_ids] = 0.0 @@ -324,9 +330,9 @@ def _generated_commands(self, num_envs: int): y_low, y_high = self._cfg.command_config.target_pos_y z_low, z_high = self._cfg.command_config.target_pos_z - pos_x = torch.rand(num_envs, dtype=torch.float32) * (x_high - x_low) + x_low - pos_y = torch.rand(num_envs, dtype=torch.float32) * (y_high - y_low) + y_low - pos_z = torch.rand(num_envs, dtype=torch.float32) * (z_high - z_low) + z_low + pos_x = torch.rand(num_envs, dtype=torch.float32, device=self.device) * (x_high - x_low) + x_low + pos_y = torch.rand(num_envs, dtype=torch.float32, device=self.device) * (y_high - y_low) + y_low + pos_z = torch.rand(num_envs, dtype=torch.float32, device=self.device) * (z_high - z_low) + z_low command_cube_target_pos = torch.stack([pos_x, pos_y, pos_z], dim=-1) assert not command_cube_target_pos.isnan().any(), "command_cube_target_pos contain nan" diff --git a/motrix_envs/src/motrix_envs/manipulation/franka_open_cabinet/cfg.py b/motrix_envs/src/motrix_envs/manipulation/franka_open_cabinet/cfg.py index 9bc06832c..f76644b8e 100755 --- a/motrix_envs/src/motrix_envs/manipulation/franka_open_cabinet/cfg.py +++ b/motrix_envs/src/motrix_envs/manipulation/franka_open_cabinet/cfg.py @@ -22,6 +22,6 @@ class FrankaOpenCabinetEnvCfg(DirectEnvCfg): scene: SceneCfg = SceneCfg(file=model_file) max_episode_seconds: float = 7.0 - sim: SimCfg = SimCfg(dt=0.01) + sim: SimCfg = SimCfg(dt=0.01, max_contacts=256, max_contact_constraints=768) ctrl_dt: float = 0.01 render_spacing: float = 2.0 diff --git a/motrix_envs/src/motrix_envs/manipulation/franka_open_cabinet/franka_open_cabinet_np.py b/motrix_envs/src/motrix_envs/manipulation/franka_open_cabinet/franka_open_cabinet_np.py index 35414bce5..401792efd 100755 --- a/motrix_envs/src/motrix_envs/manipulation/franka_open_cabinet/franka_open_cabinet_np.py +++ b/motrix_envs/src/motrix_envs/manipulation/franka_open_cabinet/franka_open_cabinet_np.py @@ -102,6 +102,7 @@ def __init__( 0.04, ], dtype=torch.float32, + device=self.device, ) self._action_dim = 8 @@ -114,13 +115,13 @@ def __init__( self._num_dof_pos = 9 # self._model.num_dof_pos # 9 self._num_dof_vel = 9 # self._model.num_dof_vel # 9 self._init_dof_pos = self.robot_default_joint_pos - self._init_dof_vel = torch.zeros(self._num_dof_vel, dtype=torch.float32) + self._init_dof_vel = torch.zeros(self._num_dof_vel, dtype=torch.float32, device=self.device) # Initialize properties self.robot_joint_pos_min_limit = torch.tensor( - [spec.ctrl_range[0] for spec in self.model.actuators], dtype=torch.float32 + [spec.ctrl_range[0] for spec in self.model.actuators], dtype=torch.float32, device=self.device ) self.robot_joint_pos_max_limit = torch.tensor( - [spec.ctrl_range[1] for spec in self.model.actuators], dtype=torch.float32 + [spec.ctrl_range[1] for spec in self.model.actuators], dtype=torch.float32, device=self.device ) self.count = 0 @@ -128,9 +129,9 @@ def __init__( # Episode-scoped task state: full-batch buffers, reset writes the done # rows in place. num_envs = self._num_envs - self._current_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32) - self._last_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32) - self._current_gripper_action = torch.zeros(num_envs, dtype=torch.float32) + self._current_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32, device=self.device) + self._current_gripper_action = torch.zeros(num_envs, dtype=torch.float32, device=self.device) @property def observation_spec(self) -> ObservationSpec: @@ -239,7 +240,9 @@ def compute_transition(self, state: ArrayEnvState): def reset(self, env_ids: torch.Tensor) -> None: num_reset = env_ids.numel() - noise_pos = (torch.rand(num_reset, self._num_dof_pos, dtype=torch.float32) * 2.0 - 1.0) * 0.125 + noise_pos = ( + torch.rand(num_reset, self._num_dof_pos, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * 0.125 dof_pos = self._init_dof_pos.unsqueeze(0).expand(num_reset, -1) + noise_pos # noise in [-0.125, 0.125] self._reset_program.buffer("robot_position")[env_ids] = dof_pos diff --git a/motrix_envs/src/motrix_envs/manipulation/rm65_insert_peg/cfg.py b/motrix_envs/src/motrix_envs/manipulation/rm65_insert_peg/cfg.py index c53278b42..7fdbe33fd 100644 --- a/motrix_envs/src/motrix_envs/manipulation/rm65_insert_peg/cfg.py +++ b/motrix_envs/src/motrix_envs/manipulation/rm65_insert_peg/cfg.py @@ -102,7 +102,7 @@ class PegInsertEnvCfg(DirectEnvCfg): render_spacing: float = 2.0 scene: SceneCfg = SceneCfg(file=model_file) max_episode_seconds: float = 3.0 - sim: SimCfg = SimCfg(dt=0.002) + sim: SimCfg = SimCfg(dt=0.002, max_contacts=128, max_contact_constraints=384) move_speed: float = 0.5 ctrl_dt: float = 0.01 reset_noise_scale: float = 0.005 diff --git a/motrix_envs/src/motrix_envs/manipulation/rm65_insert_peg/insert_peg_np.py b/motrix_envs/src/motrix_envs/manipulation/rm65_insert_peg/insert_peg_np.py index e03ecea13..ac70ab9d2 100644 --- a/motrix_envs/src/motrix_envs/manipulation/rm65_insert_peg/insert_peg_np.py +++ b/motrix_envs/src/motrix_envs/manipulation/rm65_insert_peg/insert_peg_np.py @@ -45,8 +45,6 @@ _SIM_MODEL_QUERIES = {} -_Z_AXIS = torch.tensor([0.0, 0.0, 1.0], dtype=torch.float32) - def _rotate_vector(quats: torch.Tensor, vector: torch.Tensor) -> torch.Tensor: """Rotate vectors by unit (x, y, z, w) quaternions: v + 2*im×(im×v − w·v).""" @@ -86,7 +84,10 @@ def __init__( ) self._peg_reset_translation = self._reset_program.buffer("peg_translation") self._peg_reset_orientation = self._reset_program.buffer("peg_orientation")[:, 0] - self.default_joint_pos = torch.as_tensor(self._cfg.init_state.default_joint_pos, dtype=torch.float32) + self._z_axis = torch.tensor([0.0, 0.0, 1.0], device=self.device) + self.default_joint_pos = torch.as_tensor( + self._cfg.init_state.default_joint_pos, dtype=torch.float32, device=self.device + ) self._action_dim = 7 self._num_dof_pos = 8 @@ -98,11 +99,17 @@ def __init__( {"policy": ObservationGroupSpec(gym.spaces.Box(-np.inf, np.inf, (self._obs_dim,), dtype=np.float32))} ) - self._init_dof_pos = torch.cat([self.default_joint_pos, torch.zeros(1, dtype=torch.float32)]) - self._init_dof_vel = torch.zeros(self._num_dof_vel, dtype=torch.float32) + self._init_dof_pos = torch.cat( + [self.default_joint_pos, torch.zeros(1, dtype=torch.float32, device=self.device)] + ) + self._init_dof_vel = torch.zeros(self._num_dof_vel, dtype=torch.float32, device=self.device) - self.joint_pos_min_limit = torch.tensor(self._cfg.control_config.min_pos, dtype=torch.float32) - self.joint_pos_max_limit = torch.tensor(self._cfg.control_config.max_pos, dtype=torch.float32) + self.joint_pos_min_limit = torch.tensor( + self._cfg.control_config.min_pos, dtype=torch.float32, device=self.device + ) + self.joint_pos_max_limit = torch.tensor( + self._cfg.control_config.max_pos, dtype=torch.float32, device=self.device + ) self.action_scale = self._cfg.action_config.action_scale self.gripper_closed = self._cfg.action_config.gripper_closed @@ -110,35 +117,35 @@ def __init__( # Episode-scoped task state: full-batch buffers, reset writes the done # rows in place. - self._current_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32) + self._current_actions = torch.zeros(num_envs, self._action_dim, dtype=torch.float32, device=self.device) self._last_actions = torch.zeros_like(self._current_actions) - self._socket_pos = torch.zeros(num_envs, 3, dtype=torch.float32) - self._initial_peg_pos = torch.zeros(num_envs, 3, dtype=torch.float32) - self._current_gripper_action = torch.zeros(num_envs, dtype=torch.float32) - self._gripper_is_closed = torch.zeros(num_envs, dtype=torch.bool) - self._grasp_success = torch.zeros(num_envs, dtype=torch.bool) - self._phase = torch.zeros(num_envs, dtype=torch.int32) - self._prev_hand_to_peg_dist = torch.zeros(num_envs, dtype=torch.float32) - self._prev_peg_to_socket_dist = torch.zeros(num_envs, dtype=torch.float32) - self._prev_gripper_closure = torch.zeros(num_envs, dtype=torch.float32) - self._prev_midpoint_xy_dist = torch.zeros(num_envs, dtype=torch.float32) - self._prev_pregrasp_height_error = torch.zeros(num_envs, dtype=torch.float32) - self._prev_peg_height = torch.zeros(num_envs, dtype=torch.float32) - self._prev_socket_xy_dist = torch.zeros(num_envs, dtype=torch.float32) - self._prev_insert_depth = torch.zeros(num_envs, dtype=torch.float32) - self._prev_socket_entry_gap = torch.full((num_envs,), 0.2, dtype=torch.float32) - self._consecutive_capture_steps = torch.zeros(num_envs, dtype=torch.int32) - self._consecutive_grasp_steps = torch.zeros(num_envs, dtype=torch.int32) - self._consecutive_pregrasp_open_steps = torch.zeros(num_envs, dtype=torch.int32) + self._socket_pos = torch.zeros(num_envs, 3, dtype=torch.float32, device=self.device) + self._initial_peg_pos = torch.zeros(num_envs, 3, dtype=torch.float32, device=self.device) + self._current_gripper_action = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._gripper_is_closed = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._grasp_success = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._phase = torch.zeros(num_envs, dtype=torch.int32, device=self.device) + self._prev_hand_to_peg_dist = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._prev_peg_to_socket_dist = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._prev_gripper_closure = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._prev_midpoint_xy_dist = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._prev_pregrasp_height_error = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._prev_peg_height = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._prev_socket_xy_dist = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._prev_insert_depth = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._prev_socket_entry_gap = torch.full((num_envs,), 0.2, dtype=torch.float32, device=self.device) + self._consecutive_capture_steps = torch.zeros(num_envs, dtype=torch.int32, device=self.device) + self._consecutive_grasp_steps = torch.zeros(num_envs, dtype=torch.int32, device=self.device) + self._consecutive_pregrasp_open_steps = torch.zeros(num_envs, dtype=torch.int32, device=self.device) def _sample_peg_xy(self, socket_xy: torch.Tensor) -> torch.Tensor: peg_init = self._cfg.peg_init_config num_reset = socket_xy.shape[0] def _uniform(low: float, high: float, size) -> torch.Tensor: - return torch.rand(size, dtype=torch.float32) * (high - low) + low + return torch.rand(size, dtype=torch.float32, device=self.device) * (high - low) + low - peg_xy = torch.empty(num_reset, 2, dtype=torch.float32) + peg_xy = torch.empty(num_reset, 2, dtype=torch.float32, device=self.device) peg_xy[:, 0] = _uniform(peg_init.x_range[0], peg_init.x_range[1], (num_reset,)) peg_xy[:, 1] = _uniform(peg_init.y_range[0], peg_init.y_range[1], (num_reset,)) @@ -210,7 +217,7 @@ def apply_action(self, actions: torch.Tensor, state: ArrayEnvState): midpoint_z_offset = finger_midpoint[:, 2] - peg_pos[:, 2] - peg_axis = _rotate_vector(peg_quat, _Z_AXIS) + peg_axis = _rotate_vector(peg_quat, self._z_axis) peg_uprightness = peg_axis[:, 2].clamp(-1.0, 1.0) @@ -274,7 +281,7 @@ def compute_observation(self, state: ArrayEnvState): inputs = self.sim_data peg_pos = inputs["peg_pos"][rows] - peg_axis = _rotate_vector(inputs["peg_quat"][rows], _Z_AXIS) + peg_axis = _rotate_vector(inputs["peg_quat"][rows], self._z_axis) socket_pos = self._socket_pos @@ -362,7 +369,7 @@ def reset(self, env_ids: torch.Tensor) -> None: num_reset = env_ids.numel() noise_scale = self._cfg.init_state.joint_pos_reset_noise_scale - noise_pos = (torch.rand(self._num_dof_pos, dtype=torch.float32) * 2.0 - 1.0) * noise_scale + noise_pos = (torch.rand(self._num_dof_pos, dtype=torch.float32, device=self.device) * 2.0 - 1.0) * noise_scale robot_dof_pos = self._init_dof_pos + noise_pos # Restore the semantic reset targets first and read the socket position @@ -382,7 +389,7 @@ def reset(self, env_ids: torch.Tensor) -> None: peg_xy = self._sample_peg_xy(socket_pos[:, :2]) peg_x = peg_xy[:, 0] peg_y = peg_xy[:, 1] - peg_z = torch.rand(num_reset, dtype=torch.float32) * (2 * peg_init.z_noise_scale) + ( + peg_z = torch.rand(num_reset, dtype=torch.float32, device=self.device) * (2 * peg_init.z_noise_scale) + ( peg_init.z_pos - peg_init.z_noise_scale ) @@ -522,7 +529,7 @@ def _collect_reward_features(self) -> dict: lift_height = torch.clamp(peg_pos[:, 2] - initial_peg_pos[:, 2], min=0.0) peg_xy_shift = torch.linalg.norm(peg_pos[:, :2] - initial_peg_pos[:, :2], dim=-1) peg_drop_height = torch.clamp(initial_peg_pos[:, 2] - peg_pos[:, 2], min=0.0) - peg_axis = _rotate_vector(peg_quat, _Z_AXIS) + peg_axis = _rotate_vector(peg_quat, self._z_axis) peg_uprightness = peg_axis[:, 2].clamp(-1.0, 1.0) peg_linear_vel = inputs["peg_lin_vel"] peg_speed = torch.linalg.norm(peg_linear_vel, dim=-1) @@ -712,10 +719,10 @@ def _compute_pregrasp_rewards(self, reward_cfg, features: dict, progress: dict, find_peg_reward = torch.where( features["is_gripper_command_open"] & (~tracking["ever_grasped"]), xy_align_reward + height_align_reward + xy_progress_reward + height_progress_reward, - torch.zeros(num_envs, dtype=torch.float32), + torch.zeros(num_envs, dtype=torch.float32, device=self.device), ) - hover_above_peg_penalty = torch.zeros(num_envs, dtype=torch.float32) + hover_above_peg_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) # hover_above_peg_mask = ( # features["is_gripper_command_open"] @@ -729,7 +736,7 @@ def _compute_pregrasp_rewards(self, reward_cfg, features: dict, progress: dict, # * torch.tanh((features["midpoint_z_offset"][hover_above_peg_mask] - 0.045) / 0.02) # ) - pregrasp_open_reward = torch.zeros(num_envs, dtype=torch.float32) + pregrasp_open_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) pregrasp_open_mask = ( tracking["pregrasp_ready"] & (~tracking["grasp_channel_ready"]) @@ -738,7 +745,7 @@ def _compute_pregrasp_rewards(self, reward_cfg, features: dict, progress: dict, ) pregrasp_open_reward[pregrasp_open_mask] = 0.0 - pregrasp_stall_penalty = torch.zeros(num_envs, dtype=torch.float32) + pregrasp_stall_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) pregrasp_stall_mask = pregrasp_open_mask & (tracking["consecutive_pregrasp_open"] > 4) pregrasp_stall_penalty[pregrasp_stall_mask] = ( -4.0 @@ -746,7 +753,7 @@ def _compute_pregrasp_rewards(self, reward_cfg, features: dict, progress: dict, - reward_cfg.hand_approach_bonus * 0.8 * features["close_quality"][pregrasp_stall_mask] ) - ready_but_open_penalty = torch.zeros(num_envs, dtype=torch.float32) + ready_but_open_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) ready_but_open_mask = ( tracking["grasp_channel_ready"] & features["is_gripper_command_open"] & (~tracking["ever_grasped"]) ) @@ -754,7 +761,7 @@ def _compute_pregrasp_rewards(self, reward_cfg, features: dict, progress: dict, -24.0 - reward_cfg.gripper_close_bonus * 6.0 * features["close_quality"][ready_but_open_mask] ) - close_in_grasp_zone_reward = torch.zeros(num_envs, dtype=torch.float32) + close_in_grasp_zone_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) close_zone_mask = ( tracking["pregrasp_ready"] & features["is_gripper_command_closed"] & (~tracking["ever_grasped"]) ) @@ -762,7 +769,7 @@ def _compute_pregrasp_rewards(self, reward_cfg, features: dict, progress: dict, "close_quality" ][close_zone_mask] * (0.3 + 0.7 * features["close_commitment"][close_zone_mask]) - premature_close_penalty = torch.zeros(num_envs, dtype=torch.float32) + premature_close_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) premature_close_mask = ( features["is_gripper_command_closed"] & (~tracking["pregrasp_ready"]) & (~tracking["ever_grasped"]) ) @@ -772,7 +779,7 @@ def _compute_pregrasp_rewards(self, reward_cfg, features: dict, progress: dict, - 8.0 * torch.tanh(torch.clamp(features["midpoint_z_offset"][premature_close_mask] - 0.045, min=0.0) / 0.02) ) - gripper_close_progress_reward = torch.zeros(num_envs, dtype=torch.float32) + gripper_close_progress_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) close_progress_mask = ( features["is_gripper_command_closed"] & tracking["pregrasp_ready"] & (~tracking["ever_grasped"]) ) @@ -781,13 +788,13 @@ def _compute_pregrasp_rewards(self, reward_cfg, features: dict, progress: dict, + 9.0 * torch.tanh(progress["gripper_closure_progress"][close_progress_mask].clamp(0.0, 0.12) / 0.03) ) - grasp_channel_reward = torch.zeros(num_envs, dtype=torch.float32) + grasp_channel_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) grasp_channel_mask = features["is_gripper_command_closed"] & tracking["grasp_channel_ready"] grasp_channel_reward[grasp_channel_mask] = 40.0 + reward_cfg.gripper_close_bonus * 12.0 * features[ "close_quality" ][grasp_channel_mask] * (0.2 + 0.8 * features["close_commitment"][grasp_channel_mask]) - stable_close_reward = torch.zeros(num_envs, dtype=torch.float32) + stable_close_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) stable_close_mask = grasp_channel_mask & (~tracking["ever_grasped"]) stable_close_reward[stable_close_mask] = ( reward_cfg.grasp_weight @@ -815,21 +822,21 @@ def _compute_grasp_transport_rewards(self, reward_cfg, features: dict, progress: """Reward successful capture, lifting, and transporting the peg toward the socket.""" num_envs = features["xy_dist"].shape[0] - capture_reward = torch.zeros(num_envs, dtype=torch.float32) + capture_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) capture_mask = tracking["grasp_candidate"] & (~tracking["ever_grasped"]) capture_reward[capture_mask] = reward_cfg.grasp_weight * ( 1.2 * features["close_quality"][capture_mask] * (0.35 + 0.65 * features["close_commitment"][capture_mask]) + 0.8 * torch.tanh(tracking["consecutive_capture"][capture_mask].to(torch.float32) / 2.0) ) - lift_intent_reward = torch.zeros(num_envs, dtype=torch.float32) + lift_intent_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) lift_intent_reward[capture_mask] = ( reward_cfg.lift_weight * 2.2 * torch.tanh(progress["peg_height_progress"][capture_mask].clamp(0.0, 0.008) / 0.003) ) - grasp_reward = torch.zeros(num_envs, dtype=torch.float32) + grasp_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) grasp_reward[tracking["ever_grasped"]] = reward_cfg.grasp_weight * 0.4 * features["close_commitment"][ tracking["ever_grasped"] ] + reward_cfg.lift_weight * 0.7 * torch.tanh( @@ -840,13 +847,13 @@ def _compute_grasp_transport_rewards(self, reward_cfg, features: dict, progress: stable_grasp_mask = tracking["ever_grasped"] & (tracking["consecutive_grasp"] > 5) grasp_reward[stable_grasp_mask] += 10.0 - grip_hold_reward = torch.zeros(num_envs, dtype=torch.float32) + grip_hold_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) hold_mask = tracking["ever_grasped"] & features["is_gripper_command_closed"] grip_hold_reward[hold_mask] = reward_cfg.gripper_close_bonus * 1.2 * features["close_commitment"][ hold_mask ] + reward_cfg.grasp_weight * 0.2 * (1 - torch.tanh(features["midpoint_to_peg_dist"][hold_mask] / 0.025)) - release_after_grasp_penalty = torch.zeros(num_envs, dtype=torch.float32) + release_after_grasp_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) release_mask = tracking["ever_grasped"] & ( (~features["is_gripper_command_closed"]) | (features["close_commitment"] < 0.35) ) @@ -854,14 +861,14 @@ def _compute_grasp_transport_rewards(self, reward_cfg, features: dict, progress: torch.clamp(0.35 - features["close_commitment"][release_mask], min=0.0) / 0.15 ) - carry_upright_reward = torch.zeros(num_envs, dtype=torch.float32) + carry_upright_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) carry_upright_reward[tracking["ever_grasped"]] = ( reward_cfg.orientation_weight * 2.5 * ((features["peg_uprightness"][tracking["ever_grasped"]] - 0.9) / 0.1).clamp(0.0, 1.0) ) - carry_tilt_penalty = torch.zeros(num_envs, dtype=torch.float32) + carry_tilt_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) carry_tilt_penalty[tracking["ever_grasped"]] = ( -reward_cfg.orientation_weight * 3.0 @@ -870,14 +877,14 @@ def _compute_grasp_transport_rewards(self, reward_cfg, features: dict, progress: carry_target_z = features["socket_top_z"] + self._cfg.peg_config.peg_length * 0.5 + 0.01 carry_height_error = torch.abs(features["peg_pos"][:, 2] - carry_target_z) - carry_height_reward = torch.zeros(num_envs, dtype=torch.float32) + carry_height_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) carry_height_mask = tracking["ever_grasped"] & (features["xy_dist"] > 0.045) carry_height_reward[carry_height_mask] = ( reward_cfg.lift_weight * 1.4 * (1 - torch.tanh(carry_height_error[carry_height_mask] / 0.03)) ) - move_to_socket_reward = torch.zeros(num_envs, dtype=torch.float32) + move_to_socket_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) move_to_socket_reward[tracking["ever_grasped"]] = ( reward_cfg.peg_to_socket_approach_weight * 2.2 @@ -889,7 +896,7 @@ def _compute_grasp_transport_rewards(self, reward_cfg, features: dict, progress: * torch.tanh(progress["xy_socket_progress"][tracking["ever_grasped"]].clamp(-0.02, 0.02) / 0.006) ) - transport_stall_penalty = torch.zeros(num_envs, dtype=torch.float32) + transport_stall_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) transport_stall_mask = ( tracking["ever_grasped"] & (features["xy_dist"] > 0.04) & (progress["xy_socket_progress"] < 0.0015) ) @@ -899,7 +906,7 @@ def _compute_grasp_transport_rewards(self, reward_cfg, features: dict, progress: * torch.tanh((features["xy_dist"][transport_stall_mask] - 0.04) / 0.03) ) - lift_reward = torch.zeros(num_envs, dtype=torch.float32) + lift_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) lift_stage_mask = ( features["is_gripper_command_closed"] & (tracking["pregrasp_ready"] | tracking["grasp_channel_ready"]) @@ -909,7 +916,7 @@ def _compute_grasp_transport_rewards(self, reward_cfg, features: dict, progress: reward_cfg.lift_weight * 4.5 * torch.tanh(features["lift_height"][lift_stage_mask] / 0.03) ) - carry_lift_reward = torch.zeros(num_envs, dtype=torch.float32) + carry_lift_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) carry_lift_mask = tracking["ever_grasped"] & (features["lift_height"] < 0.035) carry_lift_reward[carry_lift_mask] = ( reward_cfg.lift_weight @@ -917,7 +924,7 @@ def _compute_grasp_transport_rewards(self, reward_cfg, features: dict, progress: * (1 - torch.tanh(torch.clamp(0.035 - features["lift_height"][carry_lift_mask], min=0.0) / 0.02)) ) - lift_progress_reward = torch.zeros(num_envs, dtype=torch.float32) + lift_progress_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) lift_progress_reward[lift_stage_mask] = ( reward_cfg.lift_weight * 5.0 @@ -928,7 +935,7 @@ def _compute_grasp_transport_rewards(self, reward_cfg, features: dict, progress: (progress["xy_socket_progress"] < 0) & tracking["ever_grasped"], -reward_cfg.peg_to_socket_approach_weight * torch.tanh(torch.clamp(-progress["xy_socket_progress"], min=0.0, max=0.02) / 0.01), - torch.zeros(num_envs, dtype=torch.float32), + torch.zeros(num_envs, dtype=torch.float32, device=self.device), ) return { @@ -955,26 +962,26 @@ def _compute_insert_rewards(self, reward_cfg, features: dict, tracking: dict) -> tracking["ever_grasped"] & (features["xy_dist"] < 0.01) & (features["peg_uprightness"] > 0.96) ) - insert_progress_reward = torch.zeros(num_envs, dtype=torch.float32) + insert_progress_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) insert_progress_reward[aligned_for_insert] = ( reward_cfg.insert_weight * 2.2 * torch.tanh(tracking["insert_depth_progress"][aligned_for_insert].clamp(-0.01, 0.01) / 0.003) ) - preinsert_descend_reward = torch.zeros(num_envs, dtype=torch.float32) + preinsert_descend_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) preinsert_descend_reward[aligned_for_insert] = ( reward_cfg.insert_weight * 0.15 * (1 - torch.tanh(tracking["socket_entry_gap"][aligned_for_insert] / 0.015)) ) - descend_progress_reward = torch.zeros(num_envs, dtype=torch.float32) + descend_progress_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) descend_progress_reward[aligned_for_insert] = ( reward_cfg.insert_weight * 2.4 * torch.tanh(tracking["socket_entry_gap_progress"][aligned_for_insert].clamp(-0.02, 0.02) / 0.004) ) - hover_near_socket_penalty = torch.zeros(num_envs, dtype=torch.float32) + hover_near_socket_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) hover_near_socket_mask = ( tracking["ever_grasped"] & (features["xy_dist"] < 0.05) & (tracking["socket_entry_gap"] > 0.03) ) @@ -984,7 +991,7 @@ def _compute_insert_rewards(self, reward_cfg, features: dict, tracking: dict) -> * torch.tanh((tracking["socket_entry_gap"][hover_near_socket_mask] - 0.03) / 0.03) ) - high_hold_near_socket_penalty = torch.zeros(num_envs, dtype=torch.float32) + high_hold_near_socket_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) high_hold_mask = ( tracking["ever_grasped"] & (features["xy_dist"] < 0.06) @@ -998,7 +1005,7 @@ def _compute_insert_rewards(self, reward_cfg, features: dict, tracking: dict) -> ) ) - premature_descend_penalty = torch.zeros(num_envs, dtype=torch.float32) + premature_descend_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) premature_descend_mask = ( tracking["ever_grasped"] & (features["xy_dist"] > 0.028) @@ -1017,7 +1024,7 @@ def _compute_insert_rewards(self, reward_cfg, features: dict, tracking: dict) -> ) ) - touch_reward = torch.zeros(num_envs, dtype=torch.float32) + touch_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) touch_reward[tracking["touch_socket"]] = 120.0 insert_reward = tracking["insert_depth"] * reward_cfg.insert_weight * 6.0 @@ -1028,7 +1035,7 @@ def _compute_insert_rewards(self, reward_cfg, features: dict, tracking: dict) -> torch.float32 ) - precision_reward = torch.zeros(num_envs, dtype=torch.float32) + precision_reward = torch.zeros(num_envs, dtype=torch.float32, device=self.device) precision_reward[tracking["touch_socket"]] = reward_cfg.precision_weight * ( 1 - torch.tanh(features["xy_dist"][tracking["touch_socket"]] / 0.008) ) @@ -1057,7 +1064,7 @@ def _compute_safety_penalties(self, reward_cfg, features: dict, tracking: dict) peg_drop_excess = torch.clamp(features["peg_drop_height"] - 0.002, min=0.0) peg_speed_excess = torch.clamp(features["peg_speed"] - 0.18, min=0.0) - pregrasp_knock_penalty = torch.zeros(num_envs, dtype=torch.float32) + pregrasp_knock_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) pregrasp_knock_mask = (~tracking["ever_grasped"]) & ( (features["midpoint_xy_dist"] < 0.05) | tracking["pregrasp_ready"] | tracking["grasp_channel_ready"] ) @@ -1068,11 +1075,11 @@ def _compute_safety_penalties(self, reward_cfg, features: dict, tracking: dict) - reward_cfg.anti_shake_weight * 1800.0 * torch.tanh(peg_speed_excess[pregrasp_knock_mask] / 0.25) ) - drop_penalty = torch.zeros(num_envs, dtype=torch.float32) + drop_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) peg_dropped = tracking["ever_grasped"] & (~tracking["is_grasping"]) drop_penalty[peg_dropped] = -100.0 - carry_shake_penalty = torch.zeros(num_envs, dtype=torch.float32) + carry_shake_penalty = torch.zeros(num_envs, dtype=torch.float32, device=self.device) carry_mask = tracking["ever_grasped"] & (~tracking["success"]) @@ -1169,7 +1176,7 @@ def _compute_reward(self, state: ArrayEnvState, terminated: torch.Tensor): ("pregrasp_knock_penalty", "drop_penalty", "carry_shake_penalty"), ), ) - reward = torch.zeros(self._num_envs, dtype=torch.float32) + reward = torch.zeros(self._num_envs, dtype=torch.float32, device=self.device) reward_details = {} for reward_dict, reward_keys in reward_component_groups: for reward_key in reward_keys: diff --git a/motrix_envs/src/motrix_envs/manipulation/rm65_open_cabinet/cfg.py b/motrix_envs/src/motrix_envs/manipulation/rm65_open_cabinet/cfg.py index 8afe23219..f6438d319 100644 --- a/motrix_envs/src/motrix_envs/manipulation/rm65_open_cabinet/cfg.py +++ b/motrix_envs/src/motrix_envs/manipulation/rm65_open_cabinet/cfg.py @@ -135,7 +135,7 @@ class RM65OpenCabinetEnvCfg(DirectEnvCfg): scene: SceneCfg = SceneCfg(file=model_file) max_episode_seconds: float = 30.0 - sim: SimCfg = SimCfg(dt=0.005) + sim: SimCfg = SimCfg(dt=0.005, max_contacts=256, max_contact_constraints=768) ctrl_dt: float = 0.025 render_spacing: float = 2.0 action_scale = (0.05, 0.05, 0.05, 0.05, 0.05, 0.05) diff --git a/motrix_envs/src/motrix_envs/manipulation/rm65_open_cabinet/rm65_open_cabinet_np.py b/motrix_envs/src/motrix_envs/manipulation/rm65_open_cabinet/rm65_open_cabinet_np.py index 3d36e9355..056a67950 100755 --- a/motrix_envs/src/motrix_envs/manipulation/rm65_open_cabinet/rm65_open_cabinet_np.py +++ b/motrix_envs/src/motrix_envs/manipulation/rm65_open_cabinet/rm65_open_cabinet_np.py @@ -97,8 +97,11 @@ def __init__( gripper_mirror, ], dtype=torch.float32, + device=self.device, + ) + self._gripper_mimic_multipliers = torch.tensor( + [-1.0, 1.0, -1.0, -1.0, -1.0], dtype=torch.float32, device=self.device ) - self._gripper_mimic_multipliers = torch.tensor([-1.0, 1.0, -1.0, -1.0, -1.0], dtype=torch.float32) self._init_action_spaces() self._parse_arm_control_config() @@ -108,7 +111,7 @@ def __init__( self._num_dof_pos = 12 # 6 arm + 6 gripper joints self._num_dof_vel = 12 self._init_dof_pos = self.robot_default_joint_pos - self._init_dof_vel = torch.zeros(self._num_dof_vel, dtype=torch.float32) + self._init_dof_vel = torch.zeros(self._num_dof_vel, dtype=torch.float32, device=self.device) self._init_model_handles() self._init_obs_buffers() @@ -126,56 +129,64 @@ def _init_obs_buffers(self) -> None: # None until the first observation: the first finite-difference # velocity is zero, matching a missing previous sample. self._obs_prev_dof_pos_abs_raw: torch.Tensor | None = None - self._obs_handle_bias_pos = torch.zeros(num_envs, 3, dtype=torch.float32) - self._obs_handle_bias_quat = torch.tensor([0.0, 0.0, 0.0, 1.0], dtype=torch.float32).repeat(num_envs, 1) + self._obs_handle_bias_pos = torch.zeros(num_envs, 3, dtype=torch.float32, device=self.device) + self._obs_handle_bias_quat = torch.tensor([0.0, 0.0, 0.0, 1.0], dtype=torch.float32, device=self.device).repeat( + num_envs, 1 + ) handle_dim = 7 # pos(3) + quat(4) - self._obs_handle_pose_last = torch.zeros(num_envs, handle_dim, dtype=torch.float32) + self._obs_handle_pose_last = torch.zeros(num_envs, handle_dim, dtype=torch.float32, device=self.device) latency_steps = max(int(self._obs_noise_cfg.latency_steps), 0) self._obs_handle_pose_buffer = ( - torch.zeros(num_envs, latency_steps + 1, handle_dim, dtype=torch.float32) if latency_steps > 0 else None + torch.zeros(num_envs, latency_steps + 1, handle_dim, dtype=torch.float32, device=self.device) + if latency_steps > 0 + else None ) # Action pipeline state action_dim = self._action_dim - self._current_actions = torch.zeros(num_envs, action_dim, dtype=torch.float32) - self._last_actions = torch.zeros(num_envs, action_dim, dtype=torch.float32) + self._current_actions = torch.zeros(num_envs, action_dim, dtype=torch.float32, device=self.device) + self._last_actions = torch.zeros(num_envs, action_dim, dtype=torch.float32, device=self.device) buffer_len = max(int(self._arm_action_delay_buffer_len), 1) - self._action_delay_buffer = torch.zeros(num_envs, buffer_len, action_dim, dtype=torch.float32) + self._action_delay_buffer = torch.zeros( + num_envs, buffer_len, action_dim, dtype=torch.float32, device=self.device + ) if self._action_history_len > 0: - self._action_history = torch.zeros(num_envs, self._action_history_len, action_dim, dtype=torch.float32) + self._action_history = torch.zeros( + num_envs, self._action_history_len, action_dim, dtype=torch.float32, device=self.device + ) # Per-episode arm randomization - self._arm_action_delay_steps_per_env = torch.zeros(num_envs, dtype=torch.int32) - self._arm_actuator_lag_alpha_per_env = torch.zeros(num_envs, dtype=torch.float32) - self._arm_max_step_per_env = torch.zeros(num_envs, dtype=torch.float32) - self._arm_max_acc_step_per_env = torch.zeros(num_envs, dtype=torch.float32) + self._arm_action_delay_steps_per_env = torch.zeros(num_envs, dtype=torch.int32, device=self.device) + self._arm_actuator_lag_alpha_per_env = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._arm_max_step_per_env = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._arm_max_acc_step_per_env = torch.zeros(num_envs, dtype=torch.float32, device=self.device) # Arm action filtering state arm_dim = self._arm_action_dim - self._arm_target_smooth = torch.zeros(num_envs, arm_dim, dtype=torch.float32) - self._arm_prev_delta = torch.zeros(num_envs, arm_dim, dtype=torch.float32) - self._arm_actuator_target = torch.zeros(num_envs, arm_dim, dtype=torch.float32) + self._arm_target_smooth = torch.zeros(num_envs, arm_dim, dtype=torch.float32, device=self.device) + self._arm_prev_delta = torch.zeros(num_envs, arm_dim, dtype=torch.float32, device=self.device) + self._arm_actuator_target = torch.zeros(num_envs, arm_dim, dtype=torch.float32, device=self.device) # Gripper logic state - self._gripper_target_smooth = torch.zeros(num_envs, dtype=torch.float32) - self._gripper_binary_closed = torch.zeros(num_envs, dtype=torch.bool) - self._gripper_closed_cmd = torch.zeros(num_envs, dtype=torch.bool) - self._prev_gripper_closed_cmd = torch.zeros(num_envs, dtype=torch.bool) - self._gripper_steps_since_switch = torch.zeros(num_envs, dtype=torch.int32) - self._gripper_close_ratio = torch.zeros(num_envs, dtype=torch.float32) - self._current_gripper_action = torch.zeros(num_envs, dtype=torch.float32) + self._gripper_target_smooth = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._gripper_binary_closed = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._gripper_closed_cmd = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._prev_gripper_closed_cmd = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._gripper_steps_since_switch = torch.zeros(num_envs, dtype=torch.int32, device=self.device) + self._gripper_close_ratio = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._current_gripper_action = torch.zeros(num_envs, dtype=torch.float32, device=self.device) # Grasp / opening task state - self._grasp_hold_steps = torch.zeros(num_envs, dtype=torch.int32) - self._grasped = torch.zeros(num_envs, dtype=torch.bool) - self._phase2_mask = torch.zeros(num_envs, dtype=torch.bool) - self._prev_open_dist = torch.zeros(num_envs, dtype=torch.float32) - self._open_bonus_progress = torch.zeros(num_envs, dtype=torch.int32) + self._grasp_hold_steps = torch.zeros(num_envs, dtype=torch.int32, device=self.device) + self._grasped = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._phase2_mask = torch.zeros(num_envs, dtype=torch.bool, device=self.device) + self._prev_open_dist = torch.zeros(num_envs, dtype=torch.float32, device=self.device) + self._open_bonus_progress = torch.zeros(num_envs, dtype=torch.int32, device=self.device) def _init_action_spaces(self) -> None: self._action_dim = len(self._cfg.action_scale) + 1 self._arm_action_dim = self._action_dim - 1 - self.action_scale = torch.tensor(self._cfg.action_scale, dtype=torch.float32) + self.action_scale = torch.tensor(self._cfg.action_scale, dtype=torch.float32, device=self.device) self._action_history_len = max(int(getattr(self._cfg, "action_history_len", 0)), 0) base_obs_dim = self._action_dim * 2 + 7 # action_dim*2 + 7 self._obs_dim = base_obs_dim + self._action_dim * self._action_history_len @@ -257,10 +268,10 @@ def _parse_gripper_control_config(self) -> None: def _init_model_handles(self) -> None: self.robot_joint_pos_min_limit = torch.tensor( - [spec.ctrl_range[0] for spec in self.model.actuators], dtype=torch.float32 + [spec.ctrl_range[0] for spec in self.model.actuators], dtype=torch.float32, device=self.device ) self.robot_joint_pos_max_limit = torch.tensor( - [spec.ctrl_range[1] for spec in self.model.actuators], dtype=torch.float32 + [spec.ctrl_range[1] for spec in self.model.actuators], dtype=torch.float32, device=self.device ) self._obs_joint_pos_min_limit = self.robot_joint_pos_min_limit[: self._action_dim].clone() self._obs_joint_pos_max_limit = self.robot_joint_pos_max_limit[: self._action_dim].clone() @@ -273,7 +284,7 @@ def _compute_hold_action(self, dof_pos: torch.Tensor) -> torch.Tensor: num_envs = dof_pos.shape[0] arm_pos = dof_pos[:, : self._arm_action_dim] if self._arm_action_mode == "delta": - arm_action = torch.zeros(num_envs, self._arm_action_dim, dtype=torch.float32) + arm_action = torch.zeros(num_envs, self._arm_action_dim, dtype=torch.float32, device=self.device) elif self._arm_action_mode == "joint_target": if self._arm_action_in_degrees: arm_action = torch.rad2deg(arm_pos).to(torch.float32) @@ -326,27 +337,36 @@ def _sample_arm_delay_lag(self, num_envs: int) -> tuple[torch.Tensor, torch.Tens self._arm_action_delay_steps_max + 1, (num_envs,), dtype=torch.int32, + device=self.device, ) lag_alpha = ( - torch.rand(num_envs, dtype=torch.float32) + torch.rand(num_envs, dtype=torch.float32, device=self.device) * (self._arm_actuator_lag_alpha_max - self._arm_actuator_lag_alpha_min) + self._arm_actuator_lag_alpha_min ) else: - delay_steps = torch.full((num_envs,), int(self._arm_action_delay_steps), dtype=torch.int32) - lag_alpha = torch.full((num_envs,), float(self._arm_actuator_lag_alpha), dtype=torch.float32) + delay_steps = torch.full( + (num_envs,), int(self._arm_action_delay_steps), dtype=torch.int32, device=self.device + ) + lag_alpha = torch.full( + (num_envs,), float(self._arm_actuator_lag_alpha), dtype=torch.float32, device=self.device + ) if self._arm_speed_acc_randomization_enabled: max_step = ( - torch.rand(num_envs, dtype=torch.float32) * (self._arm_max_step_max - self._arm_max_step_min) + torch.rand(num_envs, dtype=torch.float32, device=self.device) + * (self._arm_max_step_max - self._arm_max_step_min) + self._arm_max_step_min ) max_acc_step = ( - torch.rand(num_envs, dtype=torch.float32) * (self._arm_max_acc_step_max - self._arm_max_acc_step_min) + torch.rand(num_envs, dtype=torch.float32, device=self.device) + * (self._arm_max_acc_step_max - self._arm_max_acc_step_min) + self._arm_max_acc_step_min ) else: - max_step = torch.full((num_envs,), float(self._arm_max_step), dtype=torch.float32) - max_acc_step = torch.full((num_envs,), float(self._arm_max_acc_step), dtype=torch.float32) + max_step = torch.full((num_envs,), float(self._arm_max_step), dtype=torch.float32, device=self.device) + max_acc_step = torch.full( + (num_envs,), float(self._arm_max_acc_step), dtype=torch.float32, device=self.device + ) return delay_steps, lag_alpha, max_step, max_acc_step def _apply_action_delay(self, actions: torch.Tensor) -> torch.Tensor: @@ -357,7 +377,7 @@ def _apply_action_delay(self, actions: torch.Tensor) -> torch.Tensor: buffer = torch.roll(self._action_delay_buffer, 1, dims=1) buffer[:, 0, :] = actions self._action_delay_buffer = buffer - return buffer[torch.arange(num_envs), delay_steps, :] + return buffer[torch.arange(num_envs, device=self.device), delay_steps, :] def _update_action_history(self, raw_actions: torch.Tensor) -> None: if self._action_history_len <= 0: @@ -487,7 +507,13 @@ def apply_action(self, actions: torch.Tensor, state: ArrayEnvState): return None - def compute_observation(self, state: ArrayEnvState): + def compute_observation(self, state: ArrayEnvState) -> None: + self._compute_observation(state, preview=False) + + def _preview_observation(self, state: ArrayEnvState) -> None: + self._compute_observation(state, preview=True) + + def _compute_observation(self, state: ArrayEnvState, *, preview: bool) -> None: """Build the full observation batch from cached simulator data. Reads only the cache left by the last read-program execution in the @@ -521,7 +547,8 @@ def compute_observation(self, state: ArrayEnvState): reset_mask = episode_steps == 0 if bool(reset_mask.any()): dof_vel_rel[reset_mask] = 0.0 - self._obs_prev_dof_pos_abs_raw = dof_pos_abs_raw.clone() + if not preview: + self._obs_prev_dof_pos_abs_raw = dof_pos_abs_raw.clone() if obs_noise_cfg.enabled and obs_noise_cfg.joint_noise_enabled and obs_noise_cfg.joint_vel_std > 0.0: dof_vel_rel = dof_vel_rel + torch.randn_like(dof_vel_rel) * obs_noise_cfg.joint_vel_std @@ -531,7 +558,7 @@ def compute_observation(self, state: ArrayEnvState): robot_grasp_pose = self._grasp_pose(slice(None)) drawer_grasp_pose = self._handle_pose(slice(None)) if obs_noise_cfg.enabled and obs_noise_cfg.handle_pose_noise_enabled: - drawer_grasp_pose = self._get_noisy_handle_pose(drawer_grasp_pose) + drawer_grasp_pose = self._get_noisy_handle_pose(drawer_grasp_pose, preview=preview) pos_delta = drawer_grasp_pose[:, :3] - robot_grasp_pose[:, :3] quat_target = drawer_grasp_pose[:, 3:] quat_current = robot_grasp_pose[:, 3:] @@ -600,7 +627,9 @@ def reset(self, env_ids: torch.Tensor) -> None: num_reset = env_ids.numel() noise_scale = self._cfg.reset.joint_pos_noise_scale - noise_pos = (torch.rand(num_reset, self._action_dim, dtype=torch.float32) * 2.0 - 1.0) * noise_scale + noise_pos = ( + torch.rand(num_reset, self._action_dim, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * noise_scale dof_pos = self._init_dof_pos.unsqueeze(0).repeat(num_reset, 1) dof_pos[:, : self._action_dim] += noise_pos # Add noise in range [-0.125, 0.125] @@ -620,9 +649,11 @@ def reset(self, env_ids: torch.Tensor) -> None: init_binary_closed = init_close_ratio > self._gripper_close_on_threshold arm_delay_steps, arm_lag_alpha, arm_max_step, arm_max_acc_step = self._sample_arm_delay_lag(num_reset) obs_noise_cfg = self._obs_noise_cfg - bias_pos = torch.zeros(num_reset, 3, dtype=torch.float32) + bias_pos = torch.zeros(num_reset, 3, dtype=torch.float32, device=self.device) if obs_noise_cfg.target_pos_bias_std > 0.0: - bias_pos = torch.randn(num_reset, 3, dtype=torch.float32) * obs_noise_cfg.target_pos_bias_std + bias_pos = ( + torch.randn(num_reset, 3, dtype=torch.float32, device=self.device) * obs_noise_cfg.target_pos_bias_std + ) bias_quat = self._sample_quat_bias(num_reset, obs_noise_cfg.target_rot_bias_std) handle_pose = self._handle_pose(env_ids) # Seed the env-owned observation caches for the rows being reset; the @@ -660,7 +691,7 @@ def reset(self, env_ids: torch.Tensor) -> None: self._open_bonus_progress[env_ids] = 0 def _sample_quat_bias(self, num_envs: int, rot_std: float): - identity = torch.tensor([0.0, 0.0, 0.0, 1.0], dtype=torch.float32) + identity = torch.tensor([0.0, 0.0, 0.0, 1.0], dtype=torch.float32, device=self.device) base = identity.unsqueeze(0).repeat(num_envs, 1) if rot_std <= 0.0: return base @@ -668,12 +699,12 @@ def _sample_quat_bias(self, num_envs: int, rot_std: float): def _apply_quat_noise(self, quat: torch.Tensor, rot_std: float): num_envs = quat.shape[0] - axes = torch.randn(num_envs, 3, dtype=torch.float32) + axes = torch.randn(num_envs, 3, dtype=torch.float32, device=self.device) axis_norm = torch.linalg.norm(axes, dim=-1, keepdim=True) - safe_axis = torch.tensor([1.0, 0.0, 0.0], dtype=torch.float32) + safe_axis = torch.tensor([1.0, 0.0, 0.0], dtype=torch.float32, device=self.device) axes = torch.where(axis_norm < 1e-6, safe_axis, axes) axes = axes / torch.clamp(axis_norm, min=1e-6) - angles = torch.randn(num_envs, dtype=torch.float32) * rot_std + angles = torch.randn(num_envs, dtype=torch.float32, device=self.device) * rot_std half_angles = angles * 0.5 sin_half = torch.sin(half_angles) cos_half = torch.cos(half_angles) @@ -682,7 +713,7 @@ def _apply_quat_noise(self, quat: torch.Tensor, rot_std: float): quat_norm = torch.linalg.norm(noisy_quat, dim=-1, keepdim=True) return noisy_quat / torch.clamp(quat_norm, min=1e-6) - def _get_noisy_handle_pose(self, handle_pose: torch.Tensor): + def _get_noisy_handle_pose(self, handle_pose: torch.Tensor, *, preview: bool = False): cfg = self._obs_noise_cfg if not cfg.enabled or not cfg.handle_pose_noise_enabled: return handle_pose @@ -694,14 +725,18 @@ def _get_noisy_handle_pose(self, handle_pose: torch.Tensor): if cfg.target_pos_bias_std > 0.0: bias_pos = self._obs_handle_bias_pos if not isinstance(bias_pos, torch.Tensor) or bias_pos.shape != (num_envs, 3): - bias_pos = torch.randn(num_envs, 3, dtype=torch.float32) * cfg.target_pos_bias_std + bias_pos = torch.randn(num_envs, 3, dtype=torch.float32, device=self.device) * cfg.target_pos_bias_std if bias_resample_prob > 0.0: - resample_mask = torch.rand(num_envs) < bias_resample_prob + resample_mask = torch.rand(num_envs, device=self.device) < bias_resample_prob if bool(resample_mask.any()): + if preview: + bias_pos = bias_pos.clone() bias_pos[resample_mask] = ( - torch.randn(int(resample_mask.sum()), 3, dtype=torch.float32) * cfg.target_pos_bias_std + torch.randn(int(resample_mask.sum()), 3, dtype=torch.float32, device=self.device) + * cfg.target_pos_bias_std ) - self._obs_handle_bias_pos = bias_pos + if not preview: + self._obs_handle_bias_pos = bias_pos noisy_pose[:, :3] = noisy_pose[:, :3] + bias_pos if cfg.target_rot_bias_std > 0.0: @@ -709,20 +744,25 @@ def _get_noisy_handle_pose(self, handle_pose: torch.Tensor): if not isinstance(bias_quat, torch.Tensor) or bias_quat.shape != (num_envs, 4): bias_quat = self._sample_quat_bias(num_envs, cfg.target_rot_bias_std) if bias_resample_prob > 0.0: - resample_mask = torch.rand(num_envs) < bias_resample_prob + resample_mask = torch.rand(num_envs, device=self.device) < bias_resample_prob if bool(resample_mask.any()): + if preview: + bias_quat = bias_quat.clone() bias_quat[resample_mask] = self._sample_quat_bias(int(resample_mask.sum()), cfg.target_rot_bias_std) - self._obs_handle_bias_quat = bias_quat + if not preview: + self._obs_handle_bias_quat = bias_quat noisy_pose[:, 3:] = quaternion.mul(bias_quat, noisy_pose[:, 3:]) if cfg.target_pos_std > 0.0: - noisy_pose[:, :3] = noisy_pose[:, :3] + (torch.randn(num_envs, 3, dtype=torch.float32) * cfg.target_pos_std) + noisy_pose[:, :3] = noisy_pose[:, :3] + ( + torch.randn(num_envs, 3, dtype=torch.float32, device=self.device) * cfg.target_pos_std + ) if cfg.target_rot_std > 0.0: noisy_pose[:, 3:] = self._apply_quat_noise(noisy_pose[:, 3:], cfg.target_rot_std) dropout_prob = float(min(max(cfg.dropout_prob, 0.0), 1.0)) if dropout_prob > 0.0: - dropout_mask = torch.rand(num_envs) < dropout_prob + dropout_mask = torch.rand(num_envs, device=self.device) < dropout_prob if bool(dropout_mask.any()): last_pose = self._obs_handle_pose_last if cfg.hold_last_on_dropout and isinstance(last_pose, torch.Tensor): @@ -730,7 +770,8 @@ def _get_noisy_handle_pose(self, handle_pose: torch.Tensor): else: noisy_pose[dropout_mask] = handle_pose[dropout_mask] - self._obs_handle_pose_last = noisy_pose.clone() + if not preview: + self._obs_handle_pose_last = noisy_pose.clone() latency_steps = max(int(cfg.latency_steps), 0) if latency_steps > 0: @@ -741,7 +782,8 @@ def _get_noisy_handle_pose(self, handle_pose: torch.Tensor): else: buffer = torch.roll(buffer, 1, dims=1) buffer[:, 0, :] = noisy_pose - self._obs_handle_pose_buffer = buffer + if not preview: + self._obs_handle_pose_buffer = buffer return buffer[:, -1, :] return noisy_pose diff --git a/motrix_envs/src/motrix_envs/manipulation/shadow_hand/cfg.py b/motrix_envs/src/motrix_envs/manipulation/shadow_hand/cfg.py index 0b71286fd..45ed709d7 100644 --- a/motrix_envs/src/motrix_envs/manipulation/shadow_hand/cfg.py +++ b/motrix_envs/src/motrix_envs/manipulation/shadow_hand/cfg.py @@ -39,7 +39,7 @@ class ShadowHandReposeEnvCfg(DirectEnvCfg): # ==================== # Simulation Parameters # ==================== - sim: SimCfg = SimCfg(dt=0.01) + sim: SimCfg = SimCfg(dt=0.01, max_contacts=256, max_contact_constraints=768) sim_substeps: int = 1 # Number of simulation steps per control step ctrl_dt: float = 0.01 * sim_substeps diff --git a/motrix_envs/src/motrix_envs/manipulation/shadow_hand/shadow_hand_np.py b/motrix_envs/src/motrix_envs/manipulation/shadow_hand/shadow_hand_np.py index 3fa56c3c0..9eb9c409b 100644 --- a/motrix_envs/src/motrix_envs/manipulation/shadow_hand/shadow_hand_np.py +++ b/motrix_envs/src/motrix_envs/manipulation/shadow_hand/shadow_hand_np.py @@ -57,9 +57,9 @@ _SIM_MODEL_QUERIES = {"hand_joint_position_limits": BodyJointPositionLimitsQuery(body="rh_forearm")} -def _generate_random_shoemake(size: int) -> torch.Tensor: +def _generate_random_shoemake(size: int, device: torch.device) -> torch.Tensor: """Uniformly distributed random quaternions (Shoemake's method), (x, y, z, w).""" - u1, u2, u3 = torch.rand(3, size, dtype=torch.float32) + u1, u2, u3 = torch.rand(3, size, dtype=torch.float32, device=device) sqrt1_u1 = torch.sqrt(1 - u1) sqrtu1 = torch.sqrt(u1) w = sqrt1_u1 * torch.sin(2 * torch.pi * u2) @@ -140,10 +140,10 @@ def __init__( # Get actuator control ranges from model self._actuator_ctrl_lower = torch.tensor( - [spec.ctrl_range[0] for spec in self.model.actuators], dtype=torch.float32 + [spec.ctrl_range[0] for spec in self.model.actuators], dtype=torch.float32, device=self.device ) self._actuator_ctrl_upper = torch.tensor( - [spec.ctrl_range[1] for spec in self.model.actuators], dtype=torch.float32 + [spec.ctrl_range[1] for spec in self.model.actuators], dtype=torch.float32, device=self.device ) # Hand limits use the same articulated-DOF order as the hand position slice. @@ -164,15 +164,15 @@ def __init__( self._cube_base_vel = slice(-6, None) # Initial cube position (in hand) - self._in_hand_pos = torch.tensor(cfg.cube_initial_pos, dtype=torch.float32) + self._in_hand_pos = torch.tensor(cfg.cube_initial_pos, dtype=torch.float32, device=self.device) # Episode-scoped task state: full-batch buffers, reset writes the done # rows in place. num_envs = self._num_envs self._goal_pos = self._in_hand_pos.unsqueeze(0).repeat(num_envs, 1) - self._goal_rot = torch.zeros(num_envs, 4, dtype=torch.float32) - self._prev_actions = torch.zeros(num_envs, self._num_actuators, dtype=torch.float32) - self._successes = torch.zeros(num_envs, dtype=torch.int64) + self._goal_rot = torch.zeros(num_envs, 4, dtype=torch.float32, device=self.device) + self._prev_actions = torch.zeros(num_envs, self._num_actuators, dtype=torch.float32, device=self.device) + self._successes = torch.zeros(num_envs, dtype=torch.int64, device=self.device) @property def observation_spec(self) -> ObservationSpec: @@ -364,13 +364,13 @@ def _compute_reward(self): reward = torch.where(fallen, reward + cfg.fall_penalty, reward) # Termination conditions - terminated = torch.zeros(num_envs, dtype=torch.bool) + terminated = torch.zeros(num_envs, dtype=torch.bool, device=self.device) # 1. Fall termination terminated = terminated | fallen # 2. Success termination with hold mechanism - new_pos = torch.zeros(num_envs, dtype=torch.bool) + new_pos = torch.zeros(num_envs, dtype=torch.bool, device=self.device) if cfg.max_consecutive_successes > 0: # Reset progress on goal reached when max consecutive successes reached new_pos = self._successes >= cfg.max_consecutive_successes @@ -387,10 +387,10 @@ def _update_target_visualization(self): cfg = self._cfg # Compute visualization position (offset from goal position) - viz_pos = self._goal_pos + torch.tensor(cfg.viz_target_offset, dtype=torch.float32) + viz_pos = self._goal_pos + torch.tensor(cfg.viz_target_offset, dtype=torch.float32, device=self.device) # Update mocap body pose - all_ids = torch.arange(self._num_envs, dtype=torch.int64) + all_ids = torch.arange(self._num_envs, dtype=torch.int64, device=self.device) self._target_writes.buffer("target_pos")[all_ids, 0] = viz_pos self._target_writes.buffer("target_rot")[all_ids, 0] = self._goal_rot self._target_writes.execute(all_ids) @@ -407,12 +407,12 @@ def reset(self, env_ids: torch.Tensor) -> None: # Add noise to DOF positions dof_pos_noise = ( - torch.rand(num_resets, self._num_hand_dofs, dtype=torch.float32) * 2.0 - 1.0 + torch.rand(num_resets, self._num_hand_dofs, dtype=torch.float32, device=self.device) * 2.0 - 1.0 ) * cfg.reset_dof_pos_noise # Add noise to DOF velocities dof_vel_noise = ( - torch.rand(num_resets, self._num_hand_dofs, dtype=torch.float32) * 2.0 - 1.0 + torch.rand(num_resets, self._num_hand_dofs, dtype=torch.float32, device=self.device) * 2.0 - 1.0 ) * cfg.reset_dof_vel_noise # Set hand DOF states for all envs being reset. @@ -420,12 +420,14 @@ def reset(self, env_ids: torch.Tensor) -> None: hand_vel[env_ids] = dof_vel_noise # Reset cube position with small noise - cube_pos_noise = (torch.rand(num_resets, 3, dtype=torch.float32) * 2.0 - 1.0) * cfg.reset_position_noise + cube_pos_noise = ( + torch.rand(num_resets, 3, dtype=torch.float32, device=self.device) * 2.0 - 1.0 + ) * cfg.reset_position_noise cube_pos = self._in_hand_pos.unsqueeze(0).repeat(num_resets, 1) cube_pos = cube_pos + cube_pos_noise # Randomize cube orientation - cube_quat = _generate_random_shoemake(num_resets) + cube_quat = _generate_random_shoemake(num_resets, self.device) # BodyPositionWrite / BodyRotationWrite buffers are (N, B, 3) / (N, B, 4). self._reset_program.buffer("cube_position")[env_ids, 0] = cube_pos @@ -438,7 +440,7 @@ def reset(self, env_ids: torch.Tensor) -> None: # Reset episode-scoped task state for the reset rows. The goal position # is fixed; the goal orientation is sampled uniformly on SO(3). self._goal_pos[env_ids] = self._in_hand_pos - self._goal_rot[env_ids] = _generate_random_shoemake(num_resets) + self._goal_rot[env_ids] = _generate_random_shoemake(num_resets, self.device) self._prev_actions[env_ids] = 0.0 self._successes[env_ids] = 0 @@ -449,4 +451,4 @@ def _reset_goal_pose(self, env_ids): # Goal position is fixed # Randomize goal orientation using Shoemake method for uniform SO(3) sampling - self._goal_rot[env_ids] = _generate_random_shoemake(num_resets) + self._goal_rot[env_ids] = _generate_random_shoemake(num_resets, self.device) diff --git a/motrix_envs/src/motrix_envs/motion/sampler.py b/motrix_envs/src/motrix_envs/motion/sampler.py index fe238febc..8c88a4bb7 100644 --- a/motrix_envs/src/motrix_envs/motion/sampler.py +++ b/motrix_envs/src/motrix_envs/motion/sampler.py @@ -29,6 +29,10 @@ from motrix_envs.motion.tracked import WbtMotionClip +def _publish_rebuild(target: torch.Tensor, value: torch.Tensor, active: torch.Tensor | None) -> None: + target.copy_(value if active is None else torch.where(active, value, target)) + + @dataclass(frozen=True, slots=True) class MotionStartSampler: """Pluggable start-frame curriculum consumed by a motion command term. @@ -75,7 +79,7 @@ def fold_episode_stats( ) -> None: """Fold finished reset rows into the curriculum statistics (reset hook).""" - def rebuild(self) -> None: + def rebuild(self, *, active: torch.Tensor | None = None) -> None: """Recompute the sampling distribution from the statistics (reset hook).""" def mark_episode_starts( @@ -117,7 +121,7 @@ def sample(self, draws: torch.Tensor, start_at_timestep_zero_prob: float) -> tor def _clip_geometry(clip: WbtMotionClip) -> tuple[np.ndarray, np.ndarray]: """Per-clip ``(start, end)`` global frame bounds from the per-frame boundaries.""" - ends = np.unique(clip.frame_clip_end.numpy()) + ends = np.unique(clip.frame_clip_end.cpu().numpy()) starts = np.concatenate(([0], ends[:-1] + 1)).astype(np.int64) return starts, ends.astype(np.int64) @@ -181,10 +185,10 @@ def from_clip( offsets = np.concatenate(([0], np.cumsum(bins)[:-1])) num_bins = int(bins.sum()) return AdaptiveTimestepsSampler( - clip_frame_start=torch.from_numpy(starts), - clip_frame_end=torch.from_numpy(ends), - clip_bins=torch.from_numpy(bins), - bin_clip_offset=torch.from_numpy(offsets), + clip_frame_start=torch.as_tensor(starts), + clip_frame_end=torch.as_tensor(ends), + clip_bins=torch.as_tensor(bins), + bin_clip_offset=torch.as_tensor(offsets), failed_count=torch.zeros((num_bins,), dtype=torch.float32), current_failed=torch.zeros((num_bins,), dtype=torch.float32), sampling_cdf=torch.cumsum(torch.full((num_bins,), 1.0 / num_bins), dim=0), @@ -243,36 +247,38 @@ def fold_episode_stats( histogram.scatter_add_(0, failed_bins, episode_failed.to(torch.float32)) self.current_failed.add_(histogram) - def rebuild(self) -> None: + def rebuild(self, *, active: torch.Tensor | None = None) -> None: """Rebuild the sampling CDF from the smoothed failure statistics.""" num_bins = self.failed_count.numel() probabilities = self.failed_count + self.uniform_ratio / num_bins kernel_size = max(self.kernel_size, 1) if kernel_size > 1: - kernel = torch.tensor([self.kernel_lambda**i for i in range(kernel_size)], dtype=torch.float32) + kernel = probabilities.new_tensor([self.kernel_lambda**i for i in range(kernel_size)]) kernel /= kernel.sum() - padded = torch.nn.functional.pad(probabilities[None, None, :], (0, kernel_size - 1), mode="rep") + padded = torch.nn.functional.pad(probabilities[None, None, :], (0, kernel_size - 1), mode="replicate") probability = (padded.unfold(2, kernel_size, 1) @ kernel)[0, 0] else: probability = probabilities total = probability.sum() - uniform = torch.full((num_bins,), 1.0 / num_bins, dtype=torch.float32) + uniform = torch.full_like(probability, 1.0 / num_bins) positive = total > 0.0 probabilities = torch.where( positive, probability / torch.where(positive, total, torch.ones_like(total)), uniform ) - self.entropy.copy_(-(probabilities * torch.log(probabilities + 1e-12)).sum() / math.log(max(num_bins, 2))) + _publish_rebuild( + self.entropy, -(probabilities * torch.log(probabilities + 1e-12)).sum() / math.log(max(num_bins, 2)), active + ) top_bin = torch.argmax(probabilities) # Gather (not ``probabilities[top_bin]``): tensor indexing would sync # the index to a Python int and break the graph. - self.top1_prob.copy_(torch.gather(probabilities, 0, top_bin.reshape(1)).reshape(())) - self.top1_bin.copy_(top_bin.to(torch.float32) / float(num_bins)) - self.failure_mass.copy_(self.failed_count.sum()) + _publish_rebuild(self.top1_prob, torch.gather(probabilities, 0, top_bin.reshape(1)).reshape(()), active) + _publish_rebuild(self.top1_bin, top_bin.to(torch.float32) / float(num_bins), active) + _publish_rebuild(self.failure_mass, self.failed_count.sum(), active) # Per-clip phase addressing keeps every bin reachable inside its clip # (starts clamp to a non-terminal frame), so no tail masking applies. cdf = torch.cumsum(probabilities, dim=0).to(torch.float32) cdf[-1] = 1.0 - self.sampling_cdf.copy_(cdf) + _publish_rebuild(self.sampling_cdf, cdf, active) def per_clip_bins(clip: WbtMotionClip, bin_frames: int) -> tuple[np.ndarray, np.ndarray]: @@ -283,7 +289,7 @@ def per_clip_bins(clip: WbtMotionClip, bin_frames: int) -> tuple[np.ndarray, np. frame minimum), so a drawn start never begins on a terminal frame while a nonterminal one exists in that clip. """ - ends_per_frame = clip.frame_clip_end.numpy() + ends_per_frame = clip.frame_clip_end.cpu().numpy() starts = np.concatenate(([0], np.flatnonzero(np.diff(ends_per_frame) != 0) + 1)).astype(np.int64) ends = ends_per_frame[starts] bin_start = [] @@ -370,8 +376,8 @@ def from_clip( num_bins = int(bin_start.size) num_frames = clip.joint_pos.shape[0] return ReturnTimestepsSampler( - bin_start=torch.from_numpy(bin_start), - bin_span=torch.from_numpy(bin_span), + bin_start=torch.as_tensor(bin_start), + bin_span=torch.as_tensor(bin_span), sampling_cdf=torch.cumsum(torch.full((num_bins,), 1.0 / num_bins), dim=0), bin_return=torch.zeros((num_bins,), dtype=torch.float32), bin_history=torch.full((num_bins,), 1.0 / max(num_bins, 1), dtype=torch.float32), @@ -443,16 +449,17 @@ def fold_episode_stats( self.lane_gamma[idx] * (undiscounted / lengths.clamp(min=1.0)) / (1.0 - self.sampling_gamma), torch.zeros_like(returns), ) - values = (returns + bootstrap) * episode + values = torch.where(reset_episode, returns + bootstrap, 0.0) by_bin = torch.zeros_like(self.bin_return) counts = torch.zeros_like(self.bin_return) by_bin.index_add_(0, self.lane_start_bin[idx], values) counts.index_add_(0, self.lane_start_bin[idx], episode) touched = counts > 0 - means = torch.where(touched, by_bin / counts.clamp(min=1.0), self.bin_return) - self.bin_return.copy_((1.0 - self.return_ema) * self.bin_return + self.return_ema * means) + means = by_bin / counts.clamp(min=1.0) + updated = (1.0 - self.return_ema) * self.bin_return + self.return_ema * means + self.bin_return.copy_(torch.where(touched, updated, self.bin_return)) - def rebuild(self) -> None: + def rebuild(self, *, active: torch.Tensor | None = None) -> None: """Advance the history once per rebuild, then construct the sampling CDF. The 0.001 history rate follows SuperMimic's start-bin curriculum. @@ -463,18 +470,20 @@ def rebuild(self) -> None: scaled = -25.0 * self.bin_return / max(self.g_max, 1e-9) soft = torch.exp(scaled - scaled.max()) soft = soft / soft.sum() - self.bin_history.mul_(0.999).add_(0.001 * soft) + _publish_rebuild(self.bin_history, 0.999 * self.bin_history + 0.001 * soft, active) history = self.bin_history / self.bin_history.sum() probability = self.uniform_mix / num_bins + self.return_mix * soft + self.history_mix * history probability = probability / probability.sum() - self.mean_bin_return.copy_(self.bin_return.mean()) - self.entropy.copy_(-(probability * torch.log(probability + 1e-12)).sum() / math.log(max(num_bins, 2))) + _publish_rebuild(self.mean_bin_return, self.bin_return.mean(), active) + _publish_rebuild( + self.entropy, -(probability * torch.log(probability + 1e-12)).sum() / math.log(max(num_bins, 2)), active + ) top_bin = torch.argmax(probability) - self.top1_prob.copy_(torch.gather(probability, 0, top_bin.reshape(1)).reshape(())) - self.top1_bin.copy_(top_bin.to(torch.float32) / float(num_bins)) + _publish_rebuild(self.top1_prob, torch.gather(probability, 0, top_bin.reshape(1)).reshape(()), active) + _publish_rebuild(self.top1_bin, top_bin.to(torch.float32) / float(num_bins), active) cdf = torch.cumsum(probability, dim=0).to(torch.float32) cdf[-1] = 1.0 - self.sampling_cdf.copy_(cdf) + _publish_rebuild(self.sampling_cdf, cdf, active) def mark_episode_starts( self, diff --git a/motrix_envs/src/motrix_envs/motion/tracked.py b/motrix_envs/src/motrix_envs/motion/tracked.py index 4416fe448..92a162bf2 100644 --- a/motrix_envs/src/motrix_envs/motion/tracked.py +++ b/motrix_envs/src/motrix_envs/motion/tracked.py @@ -131,21 +131,21 @@ def create( reference_index = motion.body_index(reference_body_name) return WbtMotionClip( - joint_pos=torch.from_numpy(np.ascontiguousarray(motion.joint_pos[:, joint_motion_idx])), - joint_vel=torch.from_numpy(np.ascontiguousarray(motion.joint_vel[:, joint_motion_idx])), - tracked_bodies_pos_w=torch.from_numpy(np.ascontiguousarray(motion.body_pos_w[:, tracked_idx])), - tracked_bodies_quat_w=torch.from_numpy(np.ascontiguousarray(motion.body_quat_w[:, tracked_idx])), - tracked_bodies_lin_vel_w=torch.from_numpy(np.ascontiguousarray(motion.body_lin_vel_w[:, tracked_idx])), - tracked_bodies_ang_vel_w=torch.from_numpy(np.ascontiguousarray(motion.body_ang_vel_w[:, tracked_idx])), - root_body_pos_w=torch.from_numpy(np.ascontiguousarray(motion.body_pos_w[:, root_index])), - root_body_quat_w=torch.from_numpy(np.ascontiguousarray(motion.body_quat_w[:, root_index])), - root_body_lin_vel_w=torch.from_numpy(np.ascontiguousarray(motion.body_lin_vel_w[:, root_index])), - root_body_ang_vel_w=torch.from_numpy(np.ascontiguousarray(motion.body_ang_vel_w[:, root_index])), - reference_body_pos_w=torch.from_numpy(np.ascontiguousarray(motion.body_pos_w[:, reference_index])), - reference_body_quat_w=torch.from_numpy(np.ascontiguousarray(motion.body_quat_w[:, reference_index])), + joint_pos=torch.as_tensor(np.ascontiguousarray(motion.joint_pos[:, joint_motion_idx])), + joint_vel=torch.as_tensor(np.ascontiguousarray(motion.joint_vel[:, joint_motion_idx])), + tracked_bodies_pos_w=torch.as_tensor(np.ascontiguousarray(motion.body_pos_w[:, tracked_idx])), + tracked_bodies_quat_w=torch.as_tensor(np.ascontiguousarray(motion.body_quat_w[:, tracked_idx])), + tracked_bodies_lin_vel_w=torch.as_tensor(np.ascontiguousarray(motion.body_lin_vel_w[:, tracked_idx])), + tracked_bodies_ang_vel_w=torch.as_tensor(np.ascontiguousarray(motion.body_ang_vel_w[:, tracked_idx])), + root_body_pos_w=torch.as_tensor(np.ascontiguousarray(motion.body_pos_w[:, root_index])), + root_body_quat_w=torch.as_tensor(np.ascontiguousarray(motion.body_quat_w[:, root_index])), + root_body_lin_vel_w=torch.as_tensor(np.ascontiguousarray(motion.body_lin_vel_w[:, root_index])), + root_body_ang_vel_w=torch.as_tensor(np.ascontiguousarray(motion.body_ang_vel_w[:, root_index])), + reference_body_pos_w=torch.as_tensor(np.ascontiguousarray(motion.body_pos_w[:, reference_index])), + reference_body_quat_w=torch.as_tensor(np.ascontiguousarray(motion.body_quat_w[:, reference_index])), frame_clip_end=torch.full((motion.num_frames,), motion.num_frames - 1, dtype=torch.int64), extensions={ - name: MotionChannel(torch.from_numpy(load_extension_channel(motion, name))) + name: MotionChannel(torch.as_tensor(load_extension_channel(motion, name))) for name in extension_channels }, ) diff --git a/motrix_envs/tests/test_humanoid_walk.py b/motrix_envs/tests/test_humanoid_walk.py index 5f054fffc..648e7fba3 100644 --- a/motrix_envs/tests/test_humanoid_walk.py +++ b/motrix_envs/tests/test_humanoid_walk.py @@ -3,6 +3,7 @@ """Behavioral contract tests for the manager-based humanoid walk presets.""" +from dataclasses import replace from types import SimpleNamespace import pytest @@ -95,7 +96,11 @@ def test_walk_rough_only_overrides_scene_spawn_range_and_render_spacing(make_fla assert rough_cfg.commands == flat_cfg.commands assert rough_cfg.actions == flat_cfg.actions assert rough_cfg.terminations == flat_cfg.terminations - assert rough_cfg.sim == flat_cfg.sim + assert replace(rough_cfg.sim, max_contacts=None, max_contact_constraints=None) == replace( + flat_cfg.sim, max_contacts=None, max_contact_constraints=None + ) + assert rough_cfg.sim.max_contacts >= flat_cfg.sim.max_contacts + assert rough_cfg.sim.max_contact_constraints >= flat_cfg.sim.max_contact_constraints assert flat_cfg.sim_reset.humanoid_state.spawn_xy_range == 0.0 assert rough_cfg.sim_reset.humanoid_state.spawn_xy_range > flat_cfg.sim_reset.humanoid_state.spawn_xy_range assert flat_cfg.render_spacing > 0.0 diff --git a/motrix_envs/tests/test_wbt_motion_command.py b/motrix_envs/tests/test_wbt_motion_command.py index 3a3a4df57..5808e5b16 100644 --- a/motrix_envs/tests/test_wbt_motion_command.py +++ b/motrix_envs/tests/test_wbt_motion_command.py @@ -291,6 +291,16 @@ def _multi_clip(clip_lengths: tuple[int, ...]) -> WbtMotionClip: return dataclasses.replace(clip, frame_clip_end=frame_clip_end) +def test_adaptive_smoothing_repeats_last_bin_at_clip_end(): + sampler = dataclasses.replace(_adaptive_sampler(2), kernel_size=2, kernel_lambda=1.0, uniform_ratio=0.0) + sampler.failed_count[-1] = 1.0 + + sampler.rebuild() + + # The middle bin averages zero and one; the last bin averages one and one. + torch.testing.assert_close(sampler.sampling_cdf, torch.tensor([0.0, 1.0 / 3.0, 1.0])) + + def test_per_clip_bins_never_straddle_clip_boundaries(): # Two clips of 40 and 13 frames at env_fps=10: 5 + 2 bins, each bin's # frames inside exactly one clip. diff --git a/motrix_rl/src/motrix_rl/backend_runtime.py b/motrix_rl/src/motrix_rl/backend_runtime.py index dfc6eacf8..f2bd5f40c 100644 --- a/motrix_rl/src/motrix_rl/backend_runtime.py +++ b/motrix_rl/src/motrix_rl/backend_runtime.py @@ -1,6 +1,8 @@ # Copyright Motphys Technology Co., Ltd. 2025, 2026 # SPDX-License-Identifier: Apache-2.0 +import torch + from motrix_rl import frameworks, utils from motrix_rl.method import RlMethod @@ -12,6 +14,7 @@ def resolve_train_backend( method: RlMethod, requested_backend: str | None, device_supports: utils.DeviceSupports, + sim_device: str | None = None, ) -> str: """Resolve the training backend for an RL method. @@ -20,16 +23,19 @@ def resolve_train_backend( method: Requested RL method. requested_backend: Backend requested by the user, or None for auto selection. device_supports: Runtime support information for built-in backends. + sim_device: Requested simulation device. """ if requested_backend is not None: _validate_backend(method, requested_backend, device_supports) return requested_backend framework = frameworks.get_framework(method.rllib) + cuda_sim = sim_device is not None and torch.device(sim_device).type == "cuda" candidates = [ backend for backend in framework.supported_train_backends(method.algo) if _backend_available(backend, device_supports) + and (backend != "jax" or not cuda_sim or device_supports.jax_gpu) ] if not candidates: raise ValueError( diff --git a/motrix_rl/src/motrix_rl/commands/play.py b/motrix_rl/src/motrix_rl/commands/play.py index 4aa028288..07284830d 100644 --- a/motrix_rl/src/motrix_rl/commands/play.py +++ b/motrix_rl/src/motrix_rl/commands/play.py @@ -47,6 +47,7 @@ def _policy_play_target( policy_path: str | Path, requested_env_name: str | None, sim: str | None = None, + sim_device: str | None = None, ) -> PlayTarget: policy_path = Path(policy_path) logger.info(f"Using specified policy: {policy_path}") @@ -61,13 +62,15 @@ def _policy_play_target( raise ValueError(f"env={requested_env_name!r} does not match policy metadata env {metadata.env_name!r}") if sim is not None: metadata = replace(metadata, sim=sim) + if sim_device is not None: + metadata = replace(metadata, sim_device=sim_device) logger.info(f"Using policy metadata: {metadata.rllib}.{metadata.algo} ({metadata.train_backend})") return PlayTarget(run=runs.open_run_context(run_dir, metadata), policy_path=policy_path) def _resolve_play_target(cfg: PlayConfig) -> PlayTarget: if cfg.policy is not None: - return _policy_play_target(cfg.policy, cfg.env, sim=cfg.sim) + return _policy_play_target(cfg.policy, cfg.env, sim=cfg.sim, sim_device=cfg.sim_device) rllib = cfg.rllib if rllib is not None: @@ -76,8 +79,12 @@ def _resolve_play_target(cfg: PlayConfig) -> PlayTarget: target = _latest_play_target(cfg.env or DEFAULT_ENV_NAME, rllib=rllib) logger.info(f"Auto-discovered best policy: {target.policy_path}") - if cfg.sim is not None: - metadata = replace(target.run.metadata, sim=cfg.sim) + if cfg.sim is not None or cfg.sim_device is not None: + metadata = replace( + target.run.metadata, + sim=cfg.sim or target.run.metadata.sim, + sim_device=cfg.sim_device or target.run.metadata.sim_device, + ) target = replace(target, run=runs.open_run_context(target.run.run_dir, metadata)) return target diff --git a/motrix_rl/src/motrix_rl/config.py b/motrix_rl/src/motrix_rl/config.py index e52a85b7c..e70b51e6a 100644 --- a/motrix_rl/src/motrix_rl/config.py +++ b/motrix_rl/src/motrix_rl/config.py @@ -95,6 +95,7 @@ class TrainConfig(TaskConfig): render: bool = False play: bool = False sim: str | None = None + sim_device: str | None = None resume: str | None = None @@ -104,6 +105,7 @@ class PlayConfig: env: str | None = None sim: str | None = None + sim_device: str | None = None policy: str | None = None num_envs: int | None = None seed: int | None = None diff --git a/motrix_rl/src/motrix_rl/configs/algo_base/motrix.fastsac.yaml b/motrix_rl/src/motrix_rl/configs/algo_base/motrix.fastsac.yaml index 5e3291d8e..8bad4c53c 100644 --- a/motrix_rl/src/motrix_rl/configs/algo_base/motrix.fastsac.yaml +++ b/motrix_rl/src/motrix_rl/configs/algo_base/motrix.fastsac.yaml @@ -87,7 +87,7 @@ trainer: max_ingest_per_iter: 8 # Backoff sleep in seconds when a worker temporarily has no work or the ring is full. idle_sleep_s: 0.0005 - # Actor-only collector inference device; the environment and transition path always remain on CPU. + # Collector policy device. Unindexed CUDA follows the learner. sim_device controls physics. collector_inference_device: cuda # Compile the fixed-shape CUDA collector policy with reduce-overhead mode. collector_compile: true @@ -101,13 +101,10 @@ trainer: # machine's CPU/GPU balance (see issue #62's sweep table). learner_cpu_cores: null collector_cpu_cores: null - # Transition-ring transport: "auto" (default) puts the ring slots in - # CUDA-IPC device memory when learner and collector inference share one - # GPU (fused single H2D on the collector, D2D-only learner ingest) and - # falls back to host shared memory otherwise; "on"/"off" force the - # device/host path ("on" warns and falls back to the host ring when the - # two sides are not on one GPU). Keep the values quoted: unquoted on/off - # parse as booleans in YAML. + # Transition-ring transport: "auto" uses CUDA IPC when learner and + # collector inference share a GPU and CUDA simulation, if used, is on it + # too. "off" uses host memory. "on" warns if the placement requires the + # host ring. Quote these values in YAML so they stay strings. transition_ipc: "auto" # Weight-snapshot transport: "auto" (default) enables CUDA-IPC device slots # only when learner and collector share one GPU and the actor params reach diff --git a/motrix_rl/src/motrix_rl/configs/play.yaml b/motrix_rl/src/motrix_rl/configs/play.yaml index ad45fdc57..276917017 100644 --- a/motrix_rl/src/motrix_rl/configs/play.yaml +++ b/motrix_rl/src/motrix_rl/configs/play.yaml @@ -6,6 +6,7 @@ defaults: # Overrides the simulator name recorded in the run metadata for manager envs. sim: null +sim_device: null hydra: output_subdir: null diff --git a/motrix_rl/src/motrix_rl/configs/train.yaml b/motrix_rl/src/motrix_rl/configs/train.yaml index 28b43fe79..ac779a4d6 100644 --- a/motrix_rl/src/motrix_rl/configs/train.yaml +++ b/motrix_rl/src/motrix_rl/configs/train.yaml @@ -25,6 +25,7 @@ hydra: # registered default (motrixsim). Torch-fronted environments reject an # explicitly provided simulator here because they construct their own backend. sim: null +sim_device: null logging: backend: tensorboard interval: 100 diff --git a/motrix_rl/src/motrix_rl/contracts.py b/motrix_rl/src/motrix_rl/contracts.py index 444a945e0..53c907527 100644 --- a/motrix_rl/src/motrix_rl/contracts.py +++ b/motrix_rl/src/motrix_rl/contracts.py @@ -49,6 +49,7 @@ class TrainerContext(Generic[CfgT]): rl_cfg: CfgT logging: Any checkpoint: Any + sim_device: str | None = None render: RenderConfig | None = None resume_from: str | None = None # Live metrics for this run; disabled unless the control plane enabled it for training. diff --git a/motrix_rl/src/motrix_rl/frameworks.py b/motrix_rl/src/motrix_rl/frameworks.py index 6d9ad144a..c0e5daf19 100644 --- a/motrix_rl/src/motrix_rl/frameworks.py +++ b/motrix_rl/src/motrix_rl/frameworks.py @@ -185,6 +185,7 @@ def create_trainer_context( run_dir=run.run_dir, checkpoint_dir=run.checkpoint_dir, sim=run.sim, + sim_device=run.metadata.sim_device, checkpoint_format=metadata.checkpoint_format, num_envs=num_envs, play_num_envs=play_num_envs, diff --git a/motrix_rl/src/motrix_rl/numa.py b/motrix_rl/src/motrix_rl/numa.py index 759ff63a0..018ed229e 100644 --- a/motrix_rl/src/motrix_rl/numa.py +++ b/motrix_rl/src/motrix_rl/numa.py @@ -394,14 +394,30 @@ def _hip_pci_bus_ids( return tuple(_normalize_pci_bus_id(bus_id) for bus_id in bus_ids) +def _physical_cuda_ordinal(device_index: int) -> int | None: + """Map a visible CUDA ordinal through integer CUDA_VISIBLE_DEVICES entries.""" + visible = os.environ.get("CUDA_VISIBLE_DEVICES") + if visible is None: + return device_index + entries: list[int] = [] + for token in visible.split(","): + item = token.strip() + if not item or item in ("-1", "NoDevFiles"): + break + if not item.isdigit(): + return None + entries.append(int(item)) + return entries[device_index] if 0 <= device_index < len(entries) else None + + def gpu_numa_node(device_index: int, runtime: Literal["cuda", "hip"]) -> int | None: """NUMA node hosting a GPU for the explicitly selected runtime, or ``None``. HIP queries visible runtime ordinals in an isolated subprocess, never initializing HIP in the parent. CUDA retains NVML and the NVIDIA topology - fallback. Both read sysfs ``numa_node``; -1 means unknown. The caller owns - runtime selection, so importing this module never imports Torch. CUDA uses - physical NVML indices; CUDA_VISIBLE_DEVICES ordinal remapping is not handled. + fallback, mapping visible integer ordinals through ``CUDA_VISIBLE_DEVICES``. + Both read sysfs ``numa_node``; -1 means unknown. The caller owns runtime + selection, so importing this module never imports Torch. """ if runtime not in ("cuda", "hip"): raise ValueError(f"Unknown GPU runtime: {runtime!r}") @@ -414,6 +430,10 @@ def gpu_numa_node(device_index: int, runtime: Literal["cuda", "hip"]) -> int | N os.environ.get("CUDA_VISIBLE_DEVICES"), ) else: + mapped = _physical_cuda_ordinal(device_index) + if mapped is None: + return None + device_index = mapped session = _nvml() bus_ids = session[1] if session is not None else None if bus_ids is None or device_index >= len(bus_ids): diff --git a/motrix_rl/src/motrix_rl/runner.py b/motrix_rl/src/motrix_rl/runner.py index 65254072a..335bdf8e7 100644 --- a/motrix_rl/src/motrix_rl/runner.py +++ b/motrix_rl/src/motrix_rl/runner.py @@ -39,16 +39,35 @@ def create_training_handle(request: TrainRequest) -> frameworks.TrainerHandle: """Create a trainer handle for a new training run.""" startup_started = time.perf_counter() config = request.config + resume_from = None + if config.resume is not None: + resume_from = str(checkpoints.resolve_resume_checkpoint_path(config.resume)) + if config.sim is None or config.sim_device is None: + previous_run = runs.find_metadata_for_policy(resume_from) + if previous_run is not None: + _, metadata = previous_run + config = replace( + config, + sim=metadata.sim if config.sim is None else config.sim, + sim_device=metadata.sim_device if config.sim_device is None else config.sim_device, + ) task = config.task method = RlMethod(rllib=task.rllib, algo=task.algo) logger.info("Training startup: resolving train backend for %s/%s", method.rllib, method.algo) step_started = time.perf_counter() - device_supports = utils.get_device_supports() + candidates = ( + (task.train_backend,) + if task.train_backend is not None + else frameworks.get_framework(method.rllib).supported_train_backends(method.algo) + ) + # Torch providers do not need to initialize a CUDA context to check backend availability. + device_supports = utils.get_device_supports() if "jax" in candidates else utils.DeviceSupports(torch=True) train_backend = backend_runtime.resolve_train_backend( task.env, method, task.train_backend, device_supports, + sim_device=config.sim_device, ) logger.info( "Training startup: resolved train backend '%s' in %.3fs (env=%s, num_envs=%d)", @@ -72,6 +91,7 @@ def create_training_handle(request: TrainRequest) -> frameworks.TrainerHandle: train_backend=provider.train_backend, algo=method.algo, sim=config.sim, + sim_device=config.sim_device, seed=config.seed, checkpoint_format=provider.checkpoint_format, runs_root=request.runs_root, @@ -82,9 +102,6 @@ def create_training_handle(request: TrainRequest) -> frameworks.TrainerHandle: time.perf_counter() - step_started, run.run_dir, ) - resume_from = None - if config.resume is not None: - resume_from = str(checkpoints.resolve_resume_checkpoint_path(config.resume)) metrics = MetricsLogger.from_env(run.run_dir) try: handle = _create_handle( @@ -195,6 +212,7 @@ def _running_fields(run: runs.RunContext, provider: frameworks.AgentProvider, co "algo": metadata.algo, "seed": metadata.seed, "sim": metadata.sim, + "sim_device": metadata.sim_device, "checkpoint_format": metadata.checkpoint_format, "family": _METRICS_FAMILIES.get(metadata.algo), "job_type": "train", diff --git a/motrix_rl/src/motrix_rl/runs.py b/motrix_rl/src/motrix_rl/runs.py index 003dc72cb..3d5eb654c 100644 --- a/motrix_rl/src/motrix_rl/runs.py +++ b/motrix_rl/src/motrix_rl/runs.py @@ -27,6 +27,7 @@ class RunMetadata: created_at: str checkpoint_format: str sim: str | None = None + sim_device: str | None = None motrixlab_version: str | None = None system: dict | None = None performance: dict | None = None @@ -58,6 +59,7 @@ def make_metadata( seed: int | None, checkpoint_format: str, sim: str | None = None, + sim_device: str | None = None, ) -> RunMetadata: return RunMetadata( env_name=env_name, @@ -68,6 +70,7 @@ def make_metadata( created_at=datetime.now(timezone.utc).isoformat(), checkpoint_format=checkpoint_format, sim=sim, + sim_device=sim_device, ) @@ -80,6 +83,7 @@ def create_run_context( checkpoint_format: str | None, runs_root: Path | str = LOG_DIR_PREFIX, sim: str | None = None, + sim_device: str | None = None, ) -> RunContext: """Create a framework-owned run directory and write its metadata. @@ -102,6 +106,7 @@ def create_run_context( seed=seed, checkpoint_format=_normalize_checkpoint_format(checkpoint_format) or "", sim=sim, + sim_device=sim_device, ) write_metadata(run_dir, metadata) context = RunContext(run_dir=run_dir, metadata=metadata) diff --git a/motrix_rl/src/motrix_rl/system_metrics.py b/motrix_rl/src/motrix_rl/system_metrics.py index a122ef27d..0d57ec939 100644 --- a/motrix_rl/src/motrix_rl/system_metrics.py +++ b/motrix_rl/src/motrix_rl/system_metrics.py @@ -460,6 +460,7 @@ def capture_system_info(topology: Any = None, fallback_device: Any = None) -> di _add_device_role(roles, learner.device, "learner") for collector in topology.collectors: _add_device_role(roles, collector.infer_device, "collector-inference") + _add_device_role(roles, collector.sim_device, "simulation") elif fallback_device is not None: _add_device_role(roles, fallback_device, "trainer") @@ -504,10 +505,21 @@ def _cuda_device_name(index: int) -> str: try: import torch - if torch.cuda.is_available(): + if torch.cuda.is_initialized(): return torch.cuda.get_device_name(index) except Exception: pass + # Device inventory is also collected by the async parent before spawn. + # Use the monitor's device names without initializing Torch CUDA there. + visible = os.environ.get("CUDA_VISIBLE_DEVICES") + names = _gpu_device_names() + if names: + try: + physical = int(visible.split(",")[index]) if visible else index + if physical >= 0 and names[physical]: + return names[physical] + except (ValueError, IndexError): + pass return f"cuda:{index}" diff --git a/motrix_rl/src/motrix_rl/topology.py b/motrix_rl/src/motrix_rl/topology.py index 3f7dae6d6..692e98908 100644 --- a/motrix_rl/src/motrix_rl/topology.py +++ b/motrix_rl/src/motrix_rl/topology.py @@ -67,6 +67,7 @@ class CollectorInfo: collector_id: Zero-based collector ID. num_envs: Number of environments assigned to the collector. infer_device: Device used for collector policy inference. + sim_device: Device used by the collector simulation and frontend. numa_node: NUMA node assigned to the collector, or ``None``. cpus: CPU IDs assigned to the collector. """ @@ -76,6 +77,7 @@ class CollectorInfo: infer_device: torch.device numa_node: int | None cpus: tuple[int, ...] + sim_device: torch.device = torch.device("cpu") @dataclass(frozen=True) @@ -348,6 +350,7 @@ def resolve_async_trainer_topology( default_device: torch.device, *, cpus_per_collector: int | None = None, + sim_device: str = "cpu", ) -> AsyncTrainerTopology: """Resolve the generic worker layout for an asynchronous trainer. @@ -359,6 +362,7 @@ def resolve_async_trainer_topology( collector_inference_device: Collector inference device specification. default_device: Device used by a single learner. cpus_per_collector: Optional number of CPUs per collector slice. + sim_device: Simulation placement. Unindexed CUDA follows the owning learner. Returns: A complete generic trainer topology. @@ -371,6 +375,15 @@ def resolve_async_trainer_topology( raise ValueError(f"invalid worker counts: {num_collectors=} {num_learners=}") if num_collectors % num_learners != 0: raise ValueError(f"num_collectors={num_collectors} must divide evenly across num_learners={num_learners}") + if default_device.type == "cuda" and default_device.index is None: + default_device = torch.device("cuda", 0) + requested_sim = torch.device(sim_device) + if requested_sim.type not in ("cpu", "cuda"): + raise ValueError(f"sim_device must be CPU or CUDA, got {requested_sim}") + if requested_sim.type == "cuda": + available = torch.cuda.device_count() + if not available or (requested_sim.index is not None and requested_sim.index >= available): + raise ValueError(f"Requested simulation device {requested_sim} is unavailable") learner_devices = resolve_learner_devices(learner_device_specs, num_learners, default_device) collector_devices = resolve_collector_inference_devices( collector_inference_device, learner_devices, num_collectors, num_learners, default_device @@ -395,7 +408,14 @@ def learner_node(device: torch.device) -> int | None: if not multi_node or device.type != "cuda": return None index = device.index if device.index is not None else 0 - return system_numa.gpu_numa_node(index, runtime="hip" if torch.version.hip else "cuda") + node = system_numa.gpu_numa_node(index, runtime="hip" if torch.version.hip else "cuda") + if node is None or inherited_cpus is None: + return node + try: + allowed = bool(set(system_numa.numa_node_cpus(node)) & inherited_cpus) + except ValueError: + return node + return node if allowed else None reserved_cpus: set[int] = set() @@ -433,12 +453,19 @@ def rank_device(rank: int) -> torch.device: ) assigned_counts[learner_rank] += 1 collector_learner_ranks.append(learner_rank) - owner_node = learners[learner_rank].numa_node + owner = learners[learner_rank] + collector_sim = requested_sim + if requested_sim.type == "cuda" and requested_sim.index is None: + if owner.device.type != "cuda": + raise ValueError("Unindexed CUDA simulation requires a CUDA learner for each collector") + collector_sim = owner.device + owner_node = owner.numa_node collectors.append( CollectorInfo( collector_id=collector_id, num_envs=num_envs_i, infer_device=collector_device, + sim_device=collector_sim, numa_node=owner_node, cpus=allocate_collector_cpus(owner_node), ) diff --git a/motrix_rl/src/motrix_rl/transport/gpu_ipc_ring.py b/motrix_rl/src/motrix_rl/transport/gpu_ipc_ring.py index 47b2b8b04..a6d5eeb6b 100644 --- a/motrix_rl/src/motrix_rl/transport/gpu_ipc_ring.py +++ b/motrix_rl/src/motrix_rl/transport/gpu_ipc_ring.py @@ -9,9 +9,8 @@ ride as floats (0/1 exactly representable; larger integers are converted back losslessly by the consumer's ``copy_`` only while they stay float32-exact — a schema carrying wide counters should use the host ring). -Fusion lets the collector publish one env-step batch with a **single** H2D -copy from one pinned staging buffer, and lets the learner ingest with pure -D2D strided copies — no host transfer stays on the learner's critical path. +Same-device batches are packed directly into a slot. Host batches are fused +in pinned memory for a single H2D copy. The learner ingests device views. Ownership and handoff ~~~~~~~~~~~~~~~~~~~~~ @@ -30,7 +29,7 @@ advanced once the corresponding device writes have completed, proven by CUDA events: -* producer: after the slot's H2D is enqueued, record a per-slot event; +* producer: after the slot's device writes are enqueued, record a per-slot event; ``_write`` advances only up to the boundary of completed events (lazily flushed by :meth:`GpuIpcTransitionRing.push` / :meth:`GpuIpcTransitionRing.is_full`). The single pinned staging buffer is likewise not reused until the previous @@ -169,10 +168,8 @@ def is_full(self) -> bool: def push(self, batch: Mapping[str, torch.Tensor], payload=None) -> bool: """Publish one env-step batch into the next slot. Returns False if full. - ``batch`` maps every schema field name to one of the collector's CPU - tensors (integer / boolean fields may be any numeric dtype; they are - stored as floats). One fused H2D lands the whole slot; the cursor - publishes lazily once it completes. + Pack same-device tensors in place or upload a fused host batch. + The cursor publishes once all slot writes have completed. """ if set(batch) != set(self._offsets): raise ValueError(f"transition batch fields {sorted(batch)} do not match the schema {list(self._offsets)}") @@ -183,26 +180,33 @@ def push(self, batch: Mapping[str, torch.Tensor], payload=None) -> bool: raise ValueError("slot payload requires a payload store") if store is not None and not store.can_write(payload, self.cursors.read_completed_count): return False - if self._staging_used and not self._staging_event.query(): - # The previous H2D still reads the staging buffer; it completes in - # well under one env step, so this is normally a no-op wait. - self._staging_event.synchronize() - s = self._staging - for name, value in batch.items(): - begin, end = self._offsets[name] - s[:, begin:end].copy_(value.reshape(self.num_envs, -1)) issued = self._write_issued_count - slot = issued % self.capacity - if store is not None: - store.write(issued, payload) + slot = self.slots[issued % self.capacity] stream = torch.cuda.current_stream(self.slots.device) - self.slots[slot].copy_(s, non_blocking=True) - event = torch.cuda.Event() - event.record(stream) + fields = [batch[name].reshape(self.num_envs, -1) for name in self._offsets] + source_device = fields[0].device + with torch.cuda.device(slot.device): + if all(value.device == slot.device for value in fields): + torch.cat(fields, dim=1, out=slot) + elif source_device.type == "cuda" and all(value.device == source_device for value in fields): + packed = torch.cat(fields, dim=1) + stream.wait_stream(torch.cuda.current_stream(source_device)) + slot.copy_(packed, non_blocking=True) + else: + if self._staging_used and not self._staging_event.query(): + self._staging_event.synchronize() + for name, value in batch.items(): + begin, end = self._offsets[name] + self._staging[:, begin:end].copy_(value.reshape(self.num_envs, -1)) + slot.copy_(self._staging, non_blocking=True) + self._staging_event.record(stream) + self._staging_used = True + if store is not None: + store.write(issued, payload) + event = torch.cuda.Event() + event.record(stream) self._write_events.append(_PendingEvent(issued + 1, event)) self._write_issued_count = issued + 1 - self._staging_event.record(stream) - self._staging_used = True return True # -------------------------------------------------------------- consumer diff --git a/motrix_rl/src/motrix_rl/transport/ring.py b/motrix_rl/src/motrix_rl/transport/ring.py index e00d800cc..53be0554d 100644 --- a/motrix_rl/src/motrix_rl/transport/ring.py +++ b/motrix_rl/src/motrix_rl/transport/ring.py @@ -187,8 +187,12 @@ def push(self, batch: Mapping[str, torch.Tensor], payload=None) -> bool: return False index = self.write_completed_count slot = index % self.capacity - for name, value in batch.items(): - self.data[name][slot].copy_(value) + first = next(iter(batch.values())) + if first.is_cuda and all(value.device == first.device for value in batch.values()): + self._copy_cuda_batch(slot, batch) + else: + for name, value in batch.items(): + self.data[name][slot].copy_(value) if store is not None: store.write(index, payload) # Publish the slot. On x86/TSO the field copies above are guaranteed @@ -198,6 +202,22 @@ def push(self, batch: Mapping[str, torch.Tensor], payload=None) -> bool: self.cursors._write[0] += 1 return True + def _copy_cuda_batch(self, slot: int, batch: Mapping[str, torch.Tensor]) -> None: + destinations = tuple((name, storage[slot]) for name, storage in self.data.items()) + # Pack native bytes so mixed schema dtypes keep their full precision. + # A single ordered D2H copy completes before the slot is published. + packed = torch.cat( + [ + batch[name].to(dtype=dst.dtype).expand_as(dst).reshape(-1).contiguous().view(torch.uint8) + for name, dst in destinations + ] + ).cpu() + offset = 0 + for _, dst in destinations: + bytes_ = dst.view(-1).view(torch.uint8) + bytes_.copy_(packed.narrow(0, offset, bytes_.numel())) + offset += bytes_.numel() + def has_next(self) -> bool: """Whether at least one unread slot is committed (i.e. readable).""" return self.size() > 0 diff --git a/motrix_rl/src/motrix_rl/utils.py b/motrix_rl/src/motrix_rl/utils.py index b7bd5d6d9..736f20d8b 100644 --- a/motrix_rl/src/motrix_rl/utils.py +++ b/motrix_rl/src/motrix_rl/utils.py @@ -83,11 +83,5 @@ def class_to_dict(obj) -> dict | list | Any: def env_infos(state) -> dict: - """Compose Gym-style step infos for the RL-library boundary. - - The env state keeps the per-term reward breakdown (``reward_terms``) and - metrics as first-class fields; RL libraries receive the breakdown under - ``infos["Reward"]`` and reduced batch-level scalar metrics under - ``infos["metrics"]``. - """ - return {"Reward": state.reward_terms, "metrics": state.process_metrics()} + """Expose step diagnostics on their original device until the trainer logs them.""" + return {"Reward": state.reward_terms, "metrics": state.metrics} diff --git a/motrix_rl/tests/test_backend_runtime.py b/motrix_rl/tests/test_backend_runtime.py index 65807bde3..87c5cb4d6 100644 --- a/motrix_rl/tests/test_backend_runtime.py +++ b/motrix_rl/tests/test_backend_runtime.py @@ -166,3 +166,18 @@ def create_trainer( context: frameworks.TrainerContext[_RuntimeCfg], ) -> frameworks.TrainerBase: raise NotImplementedError + + +@pytest.mark.parametrize("jax_gpu, expected", [(False, "torch"), (True, "jax")]) +def test_auto_backend_prefers_the_cuda_capable_backend_for_cuda_sim(monkeypatch, jax_gpu, expected): + _register_method(monkeypatch, rllib="runtime", algo="ppo", backends=("jax", "torch")) + assert ( + backend_runtime.resolve_train_backend( + "demo-env", + RlMethod(rllib="runtime", algo="ppo"), + None, + DeviceSupports(torch=True, jax=True, jax_gpu=jax_gpu), + sim_device="cuda:1", + ) + == expected + ) diff --git a/motrix_rl/tests/test_numa.py b/motrix_rl/tests/test_numa.py index 7f5ea4f0a..703e26d53 100644 --- a/motrix_rl/tests/test_numa.py +++ b/motrix_rl/tests/test_numa.py @@ -104,3 +104,20 @@ def denied(cpus): assert threads == [] numa.pin_worker_cpus({2, 4}) assert threads == [2] + + +def test_gpu_numa_node_maps_cuda_visible_devices_ordinals(monkeypatch, tmp_path): + from pathlib import Path as RealPath + + pci_root = tmp_path / "pci" + for bus, node in (("0000:01:00.0", "0"), ("0000:81:00.0", "1")): + dev = pci_root / bus + dev.mkdir(parents=True) + (dev / "numa_node").write_text(node) + monkeypatch.setattr(numa, "_nvml", lambda: (object(), ["0000:01:00.0", "0000:81:00.0"])) + monkeypatch.setattr(numa, "Path", lambda p: pci_root if str(p) == "/sys/bus/pci/devices" else RealPath(p)) + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1") + assert numa.gpu_numa_node(0, "cuda") == 1 + assert numa.gpu_numa_node(1, "cuda") is None + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "GPU-deadbeef") + assert numa.gpu_numa_node(0, "cuda") is None diff --git a/motrix_rl/tests/test_runner.py b/motrix_rl/tests/test_runner.py index 770a70532..e39ba12a6 100644 --- a/motrix_rl/tests/test_runner.py +++ b/motrix_rl/tests/test_runner.py @@ -4,7 +4,7 @@ import gzip import json import threading -from dataclasses import dataclass +from dataclasses import dataclass, replace from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path @@ -126,7 +126,7 @@ def log_message(self, *args): assert [record["data"]["state"] for record in records] == ["running", "finished"] running = records[0]["data"] expected = json.loads(RUNNING_FIXTURE.read_text())["body"]["records"][0]["data"] - assert set(running) == set(expected) + assert set(running) == set(expected) | {"sim_device"} assert running["config"] == runs.task_config_snapshot(_train_request(tmp_path).config) assert running["run_dir"] == str(result.run.run_dir) assert train_metrics.run_id == "demo-run" @@ -183,3 +183,28 @@ def create_trainer( ) -> frameworks.TrainerBase: self.trainer = _RunnerTrainer(context) return self.trainer + + +@pytest.mark.parametrize("sim, sim_device", [(None, None), ("explicit-sim", "cpu")]) +def test_resume_inherits_sim_placement_and_honors_overrides(demo_framework, tmp_path, sim, sim_device): + request = _train_request(tmp_path) + previous_dir = tmp_path / "old-run" + checkpoint = previous_dir / "checkpoints" / "checkpoint.pt" + checkpoint.parent.mkdir(parents=True) + checkpoint.touch() + metadata = runs.make_metadata( + env_name="demo-env", + rllib="external", + train_backend="custom", + algo="demo", + seed=7, + checkpoint_format="pt", + sim="motrixsim", + sim_device="cuda:1", + ) + runs.write_metadata(previous_dir, metadata) + cfg = replace(request.config, resume=str(checkpoint), sim=sim, sim_device=sim_device) + handle = runner.create_training_handle(replace(request, config=cfg)) + context = handle.trainer.context + assert (context.sim, context.sim_device) == (sim or "motrixsim", sim_device or "cuda:1") + assert context.resume_from == str(checkpoint) diff --git a/motrix_rl/tests/test_topology.py b/motrix_rl/tests/test_topology.py index e2edd8193..b12d6b433 100644 --- a/motrix_rl/tests/test_topology.py +++ b/motrix_rl/tests/test_topology.py @@ -278,3 +278,42 @@ def test_resolve_learner_devices_rejects_bad_configs(monkeypatch) -> None: resolve_learner_devices(["cuda:0", "cuda:5"], 2, torch.device("cuda")) with pytest.raises(ValueError, match="requires CUDA"): resolve_learner_devices(None, 2, torch.device("cpu")) + + +@pytest.mark.parametrize( + "requested, expected", + [ + ("cpu", ["cpu", "cpu"]), + ("cuda", ["cuda:0", "cuda:1"]), + ("cuda:1", ["cuda:1", "cuda:1"]), + ], +) +def test_collector_sim_placement_is_independent_of_policy_device(monkeypatch, requested, expected): + monkeypatch.setattr(system_numa, "available_numa_nodes", lambda: [0]) + monkeypatch.setattr(torch.cuda, "device_count", lambda: 2) + topology = resolve_async_trainer_topology( + 8, + 2, + 2, + ["cuda:0", "cuda:1"], + "cpu", + torch.device("cuda:0"), + sim_device=requested, + ) + assert [str(collector.infer_device) for collector in topology.collectors] == ["cpu", "cpu"] + assert [str(collector.sim_device) for collector in topology.collectors] == expected + + +def test_topology_falls_back_to_inherited_cpus_when_gpu_numa_node_disallowed(monkeypatch) -> None: + node_cpus = {0: [0, 1, 2, 3], 1: [4, 5, 6, 7]} + monkeypatch.setattr(system_numa, "available_numa_nodes", lambda: [0, 1]) + monkeypatch.setattr(system_numa, "gpu_numa_node", lambda index, runtime: 0) + monkeypatch.setattr(system_numa, "numa_node_cpus", lambda node: node_cpus[node]) + monkeypatch.setattr("os.sched_getaffinity", lambda pid: {4, 5, 6, 7}) + monkeypatch.setattr("torch.cuda.device_count", lambda: 1) + + topo = resolve_async_trainer_topology(4, 1, 1, None, "cuda", torch.device("cuda:0")) + assert topo.learners[0].numa_node is None + assert list(topo.learners[0].cpus) == [4, 5, 6, 7] + assert topo.collectors[0].numa_node is None + assert topo.collectors[0].cpus == (4, 5, 6, 7) diff --git a/motrix_rl/tests/test_transport_ring.py b/motrix_rl/tests/test_transport_ring.py index 8aa02db4d..acbd8a6c3 100644 --- a/motrix_rl/tests/test_transport_ring.py +++ b/motrix_rl/tests/test_transport_ring.py @@ -160,3 +160,16 @@ def test_cursors_are_the_channel_protocol_object(): assert cursors.read_completed_count == 0 ring.commit_reads(1) assert cursors.read_completed_count == 1 + + +@pytest.mark.integration +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA tensors") +def test_host_ring_preserves_mixed_schema_values_from_cuda(): + ring = _ring() + batch = _batch(7) + batch["frame"].add_(2**52) + assert ring.push({key: value.cuda() for key, value in batch.items()}) + count, views = ring.read_span() + assert count == 1 + for name, expected in batch.items(): + torch.testing.assert_close(views[name][0], expected) diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/collector.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/collector.py index ebe613e99..e3a39c8fd 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/collector.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/collector.py @@ -54,6 +54,33 @@ def deterministic(self, obs: torch.Tensor) -> torch.Tensor: return self.actor.explore(self._normalize(obs), deterministic=True) +class _DeviceEpisodeHistory: + """Keep the same last 100 completions as the host collector, newest first.""" + + def __init__(self, num_envs: int, device: torch.device): + self.ids = torch.arange(num_envs, device=device) + self.positions = torch.arange(100, device=device) + self.count = torch.zeros((), device=device, dtype=torch.int64) + self.history = torch.zeros((2, 100), device=device) + self.width = min(num_envs, 100) + + def append(self, returns: torch.Tensor, lengths: torch.Tensor, done: torch.Tensor) -> None: + # Larger environment IDs finish later in the host loop for a tied step. + ids = torch.where(done, self.ids, -1).topk(self.width).values.clamp_min_(0) + completed = done.sum() + new_ids = ids[self.positions.clamp_max(self.width - 1)] + old_positions = (self.positions - completed).clamp_min_(0) + newest = torch.stack((returns[new_ids], lengths[new_ids])) + self.history = torch.where(self.positions < completed, newest, self.history[:, old_positions]) + self.count.add_(completed) + + def summary(self) -> tuple[float, float, int]: + # Empty history naturally reports NaN. Only these three scalars cross devices. + means = self.history.sum(dim=1) / self.count.clamp_max(100) + ret, length, count = torch.cat((means.double(), self.count.reshape(1))).tolist() + return ret, length, int(count) + + class Collector: def __init__( self, @@ -77,7 +104,7 @@ def __init__( self.device = collector_device if self.device.type == "cuda": torch.cuda.set_device(self.device) - self.env_device = torch.device("cpu") + self.env_device = env.env.device self.num_envs = env.num_envs self.act_dim = act_dim self.ring = ring @@ -127,32 +154,35 @@ def __init__( self._obs_host = None self._obs_device = None self._actions_host = None - if self.device.type in ("cuda", "mps"): + if self.device.type in ("cuda", "mps") and self.env_device.type == "cpu": pin = self._is_cuda self._obs_host = torch.empty((self.num_envs, obs_dim), dtype=torch.float32, pin_memory=pin) self._obs_device = torch.empty_like(self._obs_host, device=self.device) self._actions_host = torch.empty((self.num_envs, act_dim), dtype=torch.float32, pin_memory=pin) - if self._is_cuda and bool(self.async_options.collector_compile): - import torch._inductor.config as inductor_config + if self._is_cuda and bool(self.async_options.collector_compile): + import torch._inductor.config as inductor_config - inductor_config.compile_threads = 1 - self._policy_runtime = torch.compile(self._policy, mode="reduce-overhead") + inductor_config.compile_threads = 1 + self._policy_runtime = torch.compile(self._policy, mode="reduce-overhead") - self._action_scale_cpu = self.actor.action_scale.detach().cpu() - self._action_bias_cpu = self.actor.action_bias.detach().cpu() + self._action_scale = self.actor.action_scale.detach().to(self.env_device) + self._action_bias = self.actor.action_bias.detach().to(self.env_device) # rollout state self.obs = None self.critic_obs = None # episode bookkeeping (owned here since the collector sees reward/done) self.ep_return = torch.zeros(self.num_envs, device=self.env_device) - self.ep_len = torch.zeros(self.num_envs, device=self.env_device) + self.ep_len = torch.zeros_like(self.ep_return) + self._gpu_episodes = None + if self.env_device.type == "cuda": + self._gpu_episodes = _DeviceEpisodeHistory(self.num_envs, self.env_device) self.recent_returns: list[float] = [] self.recent_lengths: list[float] = [] self.n_episodes = 0 - self.term_accum: dict[str, float] = {} + self.term_accum: dict[str, torch.Tensor] = {} self.term_count = 0 - self.last_env_metrics: dict[str, float] = {} + self.last_env_metrics: dict[str, float | torch.Tensor] = {} # windowed collector timing (wall-clock spent producing one env-step batch) self._collect_t = 0.0 self._sample_actions_t = 0.0 @@ -179,8 +209,13 @@ def _autocast(self): @torch.no_grad() def _infer(self, obs: torch.Tensor) -> torch.Tensor: - if self.device.type == "cpu": - return self._policy_runtime(obs) + if self._obs_host is None: + with self._autocast(): + actions = self._policy_runtime(obs.to(self.device)) + # Graph-backed inference can reuse its output on the next replay. + return ( + actions.clone() if actions.device == self.env_device and self._is_cuda else actions.to(self.env_device) + ) self._obs_host.copy_(obs) self._obs_device.copy_(self._obs_host, non_blocking=True) @@ -203,7 +238,7 @@ def warmup_inference(self) -> None: def _sample_actions(self, warming: bool) -> torch.Tensor: if warming and not self.is_resume: actions = torch.empty(self.num_envs, self.act_dim, device=self.env_device).uniform_(-1.0, 1.0) - return actions * self._action_scale_cpu + self._action_bias_cpu + return actions * self._action_scale + self._action_bias return self._infer(self.obs) def sync_weights(self, *, record_timing: bool = False) -> None: @@ -252,9 +287,9 @@ def step_once(self) -> bool: final = self.env.final_frames(result) if final is not None: final_payload = FinalObsPayload( - torch.as_tensor(final.env_ids, dtype=torch.long), - torch.as_tensor(final.obs.policy), - torch.as_tensor(final.obs.value_or_policy), + final.env_ids, + final.obs.policy, + final.obs.value_or_policy, ) rewards = result.reward.detach() terminated = result.terminated.detach().long() @@ -275,28 +310,23 @@ def step_once(self) -> bool: t_bookkeep = time.perf_counter() # episode bookkeeping (mirrors sync agent.py collect phase) - self.ep_return += rewards - self.ep_len += 1 - done_idx = torch.nonzero(terminated | truncated, as_tuple=False).flatten() - if done_idx.numel(): - # Vectorized: one batched gather + clear instead of per-episode - # Python-level scalar indexing — early in training hundreds of - # dones per step make the scalar loop dominate bookkeeping. - self.recent_returns.extend(self.ep_return[done_idx].tolist()) - self.recent_lengths.extend(self.ep_len[done_idx].tolist()) - self.ep_return[done_idx] = 0.0 - self.ep_len[done_idx] = 0.0 - self.n_episodes += int(done_idx.numel()) - self.recent_returns = self.recent_returns[-100:] - self.recent_lengths = self.recent_lengths[-100:] + done = result.terminated | result.truncated + if self._gpu_episodes is None: + self._record_episodes(rewards, done) + else: + self.ep_return.add_(rewards) + self.ep_len.add_(1) + self._gpu_episodes.append(self.ep_return, self.ep_len, done) + self.ep_return.masked_fill_(done, 0) + self.ep_len.masked_fill_(done, 0) info = result.info reward_terms = info.get("Reward") if reward_terms: for k, v in reward_terms.items(): - self.term_accum[k] = self.term_accum.get(k, 0.0) + float(v.mean()) + self.term_accum[k] = self.term_accum.get(k, 0.0) + torch.as_tensor(v).detach().mean() self.term_count += 1 - self.last_env_metrics = {k: float(np.mean(v)) for k, v in info.get("metrics", {}).items()} + self.last_env_metrics = info.get("metrics", {}) self.obs = result.obs self.critic_obs = result.critic_obs @@ -316,6 +346,22 @@ def step_once(self) -> bool: self._collect_n += 1 return True + def _record_episodes(self, rewards, done): + self.ep_return += rewards + self.ep_len += 1 + done_idx = torch.nonzero(done, as_tuple=False).flatten() + if done_idx.numel(): + # Vectorized: one batched gather + clear instead of per-episode + # Python-level scalar indexing — early in training hundreds of + # dones per step make the scalar loop dominate bookkeeping. + self.recent_returns.extend(self.ep_return[done_idx].tolist()) + self.recent_lengths.extend(self.ep_len[done_idx].tolist()) + self.ep_return[done_idx] = 0.0 + self.ep_len[done_idx] = 0.0 + self.n_episodes += int(done_idx.numel()) + self.recent_returns = self.recent_returns[-100:] + self.recent_lengths = self.recent_lengths[-100:] + # ------------------------------------------------------------------ stats def snapshot_stats(self) -> dict: """Compact rollout-stats snapshot for the learner's log panel. @@ -324,15 +370,24 @@ def snapshot_stats(self) -> dict: interval since the last call. Used by the M1 collector process to ship episode/reward info to the learner process (which owns logging). """ - rr, rl = self.recent_returns, self.recent_lengths - term_means = {k: v / max(self.term_count, 1) for k, v in self.term_accum.items()} + if self._gpu_episodes is None: + rr, rl = self.recent_returns, self.recent_lengths + mean_return = sum(rr) / len(rr) if rr else float("nan") + mean_length = sum(rl) / len(rl) if rl else float("nan") + episodes = self.n_episodes + else: + mean_return, mean_length, episodes = self._gpu_episodes.summary() + term_means = {k: float(v) / max(self.term_count, 1) for k, v in self.term_accum.items()} stats = { "collector_id": self.collector_id, - "return": (sum(rr) / len(rr)) if rr else float("nan"), - "ep_len": (sum(rl) / len(rl)) if rl else float("nan"), - "episodes": self.n_episodes, + "return": mean_return, + "ep_len": mean_length, + "episodes": episodes, "reward_terms": term_means, - "env_metrics": dict(self.last_env_metrics), + "env_metrics": { + k: float(v.float().mean()) if isinstance(v, torch.Tensor) else float(np.mean(v)) + for k, v in self.last_env_metrics.items() + }, "policy_lag": self.policy_lag, # Average wall-clock milliseconds per successful env-step batch. # Nested stages use dotted paths (``sync.wait_writer``, diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner.py index cd42f5489..2a07f7ea3 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner.py @@ -341,7 +341,13 @@ def _flush_complete_generations(self) -> int: env_offset = 0 for ring, payload in zip(self.rings, generation): if payload is not None: - parts.append(FinalObsPayload(payload.env_ids + env_offset, payload.obs, payload.critic_obs)) + parts.append( + FinalObsPayload( + payload.env_ids.to(self.agent.device) + env_offset, + payload.obs.to(self.agent.device), + payload.critic_obs.to(self.agent.device), + ) + ) env_offset += ring.num_envs final_payloads.append( FinalObsPayload( diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/topology.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/topology.py index 49229d977..01a9463a6 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/topology.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/topology.py @@ -45,7 +45,10 @@ def use_ipc_transition_ring( - opts: FastSacAsyncOptionsCfg, learner_device: torch.device, collector_device: torch.device + opts: FastSacAsyncOptionsCfg, + learner_device: torch.device, + collector_device: torch.device, + sim_device: torch.device = torch.device("cpu"), ) -> bool: """Return whether a collector's transition ring should use CUDA IPC. @@ -53,31 +56,30 @@ def use_ipc_transition_ring( opts: FastSAC asynchronous transport options. learner_device: Device used by the owning learner. collector_device: Collector inference device. + sim_device: Collector simulation device. Returns: - ``True`` when both workers use the same CUDA GPU and the configured - mode permits CUDA IPC. + ``True`` when the mode permits CUDA IPC and inference and learning + share one GPU with CUDA simulation, if used. """ mode = getattr(opts, "transition_ipc", "auto") if isinstance(mode, bool): mode = "on" if mode else "off" if mode not in ("auto", "on", "off"): raise ValueError(f"async_options.transition_ipc must be auto, on or off, got {mode!r}") - same_gpu = same_cuda_device(learner_device, collector_device) if mode == "off": return False + same_gpu = same_cuda_device(learner_device, collector_device) and ( + sim_device.type == "cpu" or same_cuda_device(learner_device, sim_device) + ) if mode == "on" and not same_gpu: - reason = ( - "collector inference device is not CUDA" - if collector_device.type != "cuda" - else f"learner device {learner_device} and collector device {collector_device} are different GPUs" - if learner_device.type == "cuda" - else "learner device is not CUDA" - ) logger.warning( - "async_options.transition_ipc=on requires learner and collector inference on the same GPU, " - "but %s; falling back to the host shared-memory transition ring", - reason, + "async_options.transition_ipc=on requires a shared GPU for learner, collector inference and " + "CUDA simulation " + "(got %s, %s, %s). Falling back to the host transition ring.", + learner_device, + collector_device, + sim_device, ) return same_gpu @@ -120,6 +122,8 @@ def resolve_fastsac_topology( async_options: FastSacAsyncOptionsCfg, actor_param_numel: int, cpus_per_collector: int | None = None, + *, + sim_device: str = "cpu", ) -> AsyncTrainerTopology: """Resolve the complete FastSAC worker topology in one pass. @@ -133,6 +137,7 @@ def resolve_fastsac_topology( async_options: FastSAC asynchronous transport options. actor_param_numel: Number of actor parameters. cpus_per_collector: Optional CPUs per collector slice. + sim_device: Simulation placement for the collectors. Returns: A generic topology populated with FastSAC transport decisions. @@ -149,6 +154,7 @@ def resolve_fastsac_topology( collector_inference_device, default_device, cpus_per_collector=cpus_per_collector, + sim_device=sim_device, ) channels = tuple( replace( @@ -157,6 +163,7 @@ def resolve_fastsac_topology( async_options, topology.learners[channel.consumer_id].device, topology.collectors[index].infer_device, + topology.collectors[index].sim_device, ), ) for index, channel in enumerate(topology.transition_channels) diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/train.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/train.py index b08b9830b..9e5d24de4 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/train.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/train.py @@ -72,7 +72,7 @@ def __init__(self, *, context: TrainerContext[FastSacCfg]) -> None: env_name = context.env_name self._rlcfg = context.rl_cfg self._env_name = env_name - self._env_spec = env_registry.resolve(env_name, sim=context.sim) + self._env_spec = env_registry.resolve(env_name, sim=context.sim, sim_device=context.sim_device) self._render = context.render self._resume_from = context.resume_from self._context = context @@ -90,6 +90,8 @@ def _make_env( render: RenderConfig | None, device: torch.device | None = None, mode: str = "train", + *, + sim_device: str | None = None, ) -> FastSacEnvWrap: return build_env( self._env_spec, @@ -98,6 +100,7 @@ def _make_env( render=render, mode=mode, seed=self._context.seed, + sim_device=sim_device, ) def _dims(self, env: FastSacEnvWrap): @@ -151,7 +154,7 @@ def train(self) -> None: # Read dims once in the parent (cheap 1-env build), then discard. Each # child rebuilds its own env because env objects are not picklable across spawn. - probe = self._make_env(1, render=None, device=torch.device("cpu")) + probe = self._make_env(1, render=None, device=torch.device("cpu"), sim_device="cpu") obs_dim, critic_obs_dim, act_dim, action_scale, action_bias = self._dims(probe) max_episode_steps = probe.max_episode_steps observation_spec = probe.observation_spec @@ -160,10 +163,14 @@ def train(self) -> None: probe.close() dims = (obs_dim, critic_obs_dim, act_dim) - learner_device = self._device() - num_collectors = async_options.num_collectors num_learners = async_options.num_learners + requested_sim = self._env_spec.env_cfg.sim.device + indexed_sim = torch.device(requested_sim) + if num_learners == 1 and cfg.device is None and indexed_sim.type == "cuda" and indexed_sim.index is not None: + default_device = indexed_sim + else: + default_device = self._device() if num_learners < 1: raise ValueError(f"num_learners must be >= 1, got {num_learners}") if num_learners > 1 and num_collectors % num_learners != 0: @@ -210,10 +217,11 @@ def train(self) -> None: num_learners, async_options.learner_devices, async_options.collector_inference_device, - self._device(), + default_device, async_options, param_numel, cpus_per_collector=cpus_per_collector, + sim_device=requested_sim, ) learner_devices = [learner.device for learner in topology.learners] collector_devices = [collector.infer_device for collector in topology.collectors] @@ -227,14 +235,15 @@ def train(self) -> None: # Provenance for performance snapshots: record the devices this run # actually uses (topology is the single source of truth), not the # host inventory. - annotate_run(self._context.run_dir, system=capture_system_info(topology=topology)) + sim_devices = [str(collector.sim_device) for collector in topology.collectors] + annotate_run( + self._context.run_dir, + system=capture_system_info(topology=topology), + sim_device=sim_devices[0], + collector_sim_devices=sim_devices, + ) final_obs_enabled = max_episode_steps is not None transition_schema = fastsac_transition_schema(frame_dim, value_frame_dim, act_dim) - final_stores: list[FinalObsStorage] | None = ( - [FinalObsStorage(async_options.ring_capacity, shard, frame_dim, value_frame_dim) for shard in env_shards] - if final_obs_enabled - else None - ) rings: list[HostTransitionRing | RingCursors] = [ RingCursors() if ipc @@ -242,9 +251,13 @@ def train(self) -> None: transition_schema, async_options.ring_capacity, shard, - payload_store=final_stores[i] if final_stores is not None else None, + payload_store=( + FinalObsStorage(async_options.ring_capacity, shard, frame_dim, value_frame_dim) + if final_obs_enabled + else None + ), ) - for i, (ipc, shard) in enumerate(zip(ring_ipc, env_shards)) + for ipc, shard in zip(ring_ipc, env_shards) ] weights = [ WeightChannelShared(fastsac_inference_bundle_spec(obs_dim, param_numel)) for _ in range(num_collectors) @@ -309,10 +322,11 @@ def _drain_child_errors() -> list[tuple[str, str]]: unique_collector_devices[0] if len(unique_collector_devices) == 1 else unique_collector_devices ) print( - f"[motrix.fastsac async] collector/learner training '{self._env_name}' learner={learner_device} " + f"[motrix.fastsac async] collector/learner training '{self._env_name}' learner={learner_devices[0]} " f"learner_replicas={num_learners} " + (f"learner_devices={[str(d) for d in learner_devices]} " if num_learners > 1 else "") - + f"collector_env=cpu collector_inference={collector_banner} num_collectors={num_collectors} " + + f"collector_env={list(dict.fromkeys(sim_devices))} collector_inference={collector_banner} " + f"num_collectors={num_collectors} " f"numa_nodes={numa_nodes} learner_numa_nodes={learner_numa_nodes} " f"num_envs={num_envs} iters={num_iterations} " f"from={resume_step} utd_mode={async_options.utd_mode}" @@ -377,15 +391,7 @@ def _drain_child_errors() -> list[tuple[str, str]]: ], "learner_cpus": topology.learners[rank].cpus if learner_numa_nodes else None, "learner_numa_node": learner_numa_nodes[rank] if learner_numa_nodes else None, - "final_stores": ( - [ - final_stores[index] - for index in range(num_collectors) - if topology.transition_channels[index].consumer_id == rank - ] - if final_stores is not None - else None - ), + "final_obs_enabled": final_obs_enabled, }, name="fastsac-async-learner" if num_learners == 1 else f"fastsac-async-learner-{rank}", ) @@ -396,6 +402,7 @@ def _drain_child_errors() -> list[tuple[str, str]]: target=run_collector_process, kwargs={ "env_spec": self._env_spec, + "sim_device": sim_devices[i], "cfg": cfg, "num_envs": env_shards[i], "dims": dims, @@ -416,7 +423,6 @@ def _drain_child_errors() -> list[tuple[str, str]]: "collector_device": topology.collectors[i].infer_device, "run_dir": str(self._context.run_dir), "handshake": handshake, - "final_store": final_stores[i] if final_stores is not None else None, }, name=f"fastsac-async-collector-{i}", ) diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/transport/final_obs.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/transport/final_obs.py index e0c0128f0..65bdd00e0 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/transport/final_obs.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/transport/final_obs.py @@ -6,7 +6,7 @@ With auto-reset envs the observation returned by the terminating step is NOT the reset observation that the following slot stores, yet the replay buffer needs it to bootstrap the n-step return. This store keeps those sparse rows -in host shared memory; the generic ring treats it as an opaque +on the transition device; the generic ring treats it as an opaque ``SlotPayloadStore`` and governs row reclamation with the transition cursors. """ @@ -21,7 +21,7 @@ @dataclass class FinalObsPayload: - """Owned compact CPU observation rows belonging to one transition slot.""" + """Owned compact observation rows belonging to one transition slot.""" env_ids: torch.Tensor obs: torch.Tensor @@ -36,12 +36,25 @@ class FinalObsStorage: releases its rows; no independently published or consumed cursor exists. """ - def __init__(self, capacity: int, num_envs: int, obs_dim: int, critic_obs_dim: int): + def __init__( + self, + capacity: int, + num_envs: int, + obs_dim: int, + critic_obs_dim: int, + device: torch.device = torch.device("cpu"), + ): self.slot_capacity = capacity self.capacity = 3 * num_envs - self.env_ids = _shared((self.capacity,), torch.int64) - self.obs = _shared((self.capacity, obs_dim), torch.float32) - self.critic_obs = _shared((self.capacity, critic_obs_dim), torch.float32) + + def rows(shape, dtype): + if device.type == "cpu": + return _shared(shape, dtype) + return torch.empty(shape, dtype=dtype, device=device) + + self.env_ids = rows((self.capacity,), torch.int64) + self.obs = rows((self.capacity, obs_dim), torch.float32) + self.critic_obs = rows((self.capacity, critic_obs_dim), torch.float32) self.starts = _shared((capacity,), torch.int64) self.counts = _shared((capacity,), torch.int64) self.ends = _shared((capacity,), torch.int64) @@ -72,10 +85,16 @@ def write(self, index: int, payload: FinalObsPayload | None) -> None: n = 0 if payload is None else len(payload.env_ids) start = self._row_write if n: - rows = (start + torch.arange(n, dtype=torch.int64)) % self.capacity - self.env_ids[rows] = torch.as_tensor(payload.env_ids, dtype=torch.int64) - self.obs[rows] = torch.as_tensor(payload.obs, dtype=torch.float32) - self.critic_obs[rows] = torch.as_tensor(payload.critic_obs, dtype=torch.float32) + device = self.env_ids.device + rows = (start + torch.arange(n, device=device)) % self.capacity + fields = ((self.env_ids, payload.env_ids), (self.obs, payload.obs), (self.critic_obs, payload.critic_obs)) + if device.type == "cuda": + stream = torch.cuda.current_stream(device) + for source in {source.device for _, source in fields}: + if source.type == "cuda" and source != device: + stream.wait_stream(torch.cuda.current_stream(source)) + for target, source in fields: + target[rows] = source.to(device=device, dtype=target.dtype, non_blocking=device.type == "cuda") self.starts[slot] = start self.counts[slot] = n self.ends[slot] = start + n @@ -90,7 +109,7 @@ def read(self, index: int, count: int) -> list[FinalObsPayload | None]: if not n: result.append(None) continue - rows = (int(self.starts[slot]) + torch.arange(n, dtype=torch.int64)) % self.capacity + rows = (int(self.starts[slot]) + torch.arange(n, device=self.env_ids.device)) % self.capacity # Advanced indexing produces owned snapshots, including on wrap. result.append(FinalObsPayload(self.env_ids[rows], self.obs[rows], self.critic_obs[rows])) return result diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/transport/handshake.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/transport/handshake.py index a883d2c51..a9d934513 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/transport/handshake.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/transport/handshake.py @@ -46,7 +46,7 @@ def ship_weight_slots(self, collector_id: int, params) -> None: self.slot_queues[collector_id].put(params) def ship_ring_slots(self, collector_id: int, ring_slots) -> None: - """Ship the CUDA-IPC transition-ring slots (``None`` for host rings).""" + """Ship CUDA-IPC transition slots and final rows (``None`` for host rings).""" self.ring_slot_queues[collector_id].put(ring_slots) # ------------------------------------------------------ collector side diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py index c7fe4cf82..a6c25d070 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py @@ -76,19 +76,21 @@ def set_seed(seed: int | None) -> None: def build_env( env_spec: EnvBuildSpec, num_envs: int, - device: torch.device, + device: torch.device | None, render: RenderConfig | None = None, mode: str = "train", seed: int | None = None, + sim_device: str | None = None, ) -> FastSacEnvWrap: env = env_spec.make( + **({"sim_device": sim_device} if sim_device is not None else {}), num_envs=num_envs, mode=mode, seed=seed, headless=render.headless if render else False, record=render.record if render else None, ) - return FastSacEnvWrap(env, device, render=render) + return FastSacEnvWrap(env, env.device if device is None else device, render=render) def actor_param_numel(cfg: FastSacCfg, dims, action_scale, action_bias) -> int: @@ -244,10 +246,10 @@ def run_collector_process( run_dir: str, handshake: StartupHandshake, collector_device: torch.device, + sim_device: str | None = None, collector_id: int = 0, numa_node: int | None = None, cpus: list[int] | None = None, - final_store: FinalObsStorage | None = None, ) -> None: role = f"collector[{collector_id}]" _install_graceful_sigint(control) @@ -263,9 +265,8 @@ def run_collector_process( opts = cfg.trainer.async_options pin_worker_cpus(resolve_worker_cpus(opts.collector_cpu_cores, "collector_cpu_cores")) obs_dim, critic_obs_dim, act_dim = dims - device = torch.device("cpu") env_started = time.perf_counter() - env = build_env(env_spec, num_envs, device, seed=seed) + env = build_env(env_spec, num_envs, None, seed=seed, sim_device=sim_device) logger.info( "collector startup: env build (scene + manager kernels) finished in %.3fs", time.perf_counter() - env_started, @@ -281,6 +282,7 @@ def run_collector_process( if isinstance(ring, RingCursors): if ring_slots is None: raise RuntimeError("the learner shipped no transition-ring slots for the IPC ring handshake") + ring_slots, final_store = ring_slots ring = GpuIpcTransitionRing( ring, ring_slots, @@ -349,14 +351,16 @@ def run_collector_process( except Empty: pass collector_data_queue.put(collector.snapshot_stats()) + if isinstance(ring, GpuIpcTransitionRing): + while not control.stop and ring.write_completed_count < ring.write_issued_count: + time.sleep(opts.idle_sleep_s) except BaseException: + control.set_stop() if not isinstance(sys.exc_info()[1], (KeyboardInterrupt, SystemExit)): # Ctrl+C is an operator action, not a defect: the stop flag is # already set by the SIGINT handler; don't spam async_errors. error_queue.put((role, traceback.format_exc())) raise - finally: - control.set_stop() # signal the learner if the collector exits for any reason # ------------------------------------------------------------------ learner process @@ -389,15 +393,15 @@ def run_learner_process( num_learners: int = 1, rendezvous_file: str | None = None, learner_device: str | None = None, - final_stores: list[FinalObsStorage] | None = None, + final_obs_enabled: bool = False, notify_checkpoints: bool = False, observation_spec: ObservationSpec | None = None, ) -> None: """One learner process; ``rank 0`` additionally owns stats aggregation, logging and checkpointing. - ``final_stores`` is either absent for all owned collectors or contains one - store per owned ring; final-observation support is uniform across collectors. + ``final_obs_enabled`` requests truncation bootstrapping and learner-owned + CUDA final-observation buffers for IPC rings. ``collector_ids`` gives the global collector ID for each local ring/weight endpoint, preserving channel identity when ownership is non-contiguous. @@ -460,7 +464,7 @@ def run_learner_process( action_scale, action_bias, world_size=num_learners, - final_obs_bootstrap=final_stores is not None, + final_obs_bootstrap=final_obs_enabled, observation_spec=observation_spec, ) if resume_from: @@ -514,14 +518,22 @@ def run_learner_process( dtype=torch.float32, device=device, ) + final_store = ( + FinalObsStorage( + opts.ring_capacity, per_collector_envs, agent.rb.n_obs, agent.rb.n_critic_obs, device=device + ) + if final_obs_enabled + else None + ) rings[j] = GpuIpcTransitionRing( ring, ring_slots, schema, opts.ring_capacity, per_collector_envs, - payload_store=final_stores[j] if final_stores is not None else None, + payload_store=final_store, ) + ring_slots = (ring_slots, final_store) handshake.ship_ring_slots(collector_id, ring_slots) endpoints = [CollectorEndpoint(ring=rings[j], weight_sender=weight_txs[j]) for j in range(len(weight_txs))] @@ -578,17 +590,30 @@ def run_learner_process( # Each collector runs until its own counter reaches num_iterations; the # aggregate (sum) therefore reaches num_iterations * num_collectors. total_collector_steps = num_iterations * num_collectors - while not control.stop and control.collector_steps < total_collector_steps: + remaining_batches = num_iterations - resume_step + while remaining_batches > 0 and not control.stop: # Progress basis: full num_envs-batch equivalents — the aggregate # counter counts per-collector batches of per_collector_envs # transitions each, so dividing by num_collectors recovers the # sync-trainer "iteration collects num_envs transitions" unit # (identical to the raw counter when num_collectors == 1). All # ranks read the same shared value. - step = control.collector_steps // num_collectors + collected = control.collector_steps + if dist is not None: + progress = torch.tensor(collected, device=device) + dist.broadcast(progress, src=0) + collected = int(progress) + finished = collected >= total_collector_steps + step = collected // num_collectors control.global_step = step t_drain = time.perf_counter() ingested = learner.drain() + if finished: + while not control.stop and any(r.read_issued_count < remaining_batches for r in rings): + count = learner.drain() + ingested += count + if not count: + time.sleep(opts.idle_sleep_s) if ingested: if not start_anchored: start_time = time.time() @@ -717,6 +742,8 @@ def run_learner_process( except Full: logger.warning("learner data queue full; checkpoint notice for %s dropped", path) next_save += save_interval + if finished: + break if num_learners > 1: # All ranks have consumed the identical global step count, so the diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/buffer.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/buffer.py index 8f88457a7..67458dd46 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/buffer.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/buffer.py @@ -84,7 +84,7 @@ def __init__( self._final_slot = None self._final_capacity = 0 self._final_free: list[int] = [] - self._final_owners: list[dict[int, int]] = [{} for _ in range(cap)] + self._final_owners: list[list[int]] = [[] for _ in range(cap)] if final_obs_bootstrap: self._enable_final_storage() @@ -204,7 +204,7 @@ def _invalidate_final_slot(self, start: int, count: int) -> None: return for offset in range(count): owners = self._final_owners[(start + offset) % self._cap] - self._final_free.extend(owners.values()) + self._final_free.extend(owners) owners.clear() n = min(count, self._cap - start) self._final_slot[:, start : start + n] = -1 @@ -218,24 +218,26 @@ def write_final(self, env_ids: torch.Tensor, t_abs: int, obs_rows: torch.Tensor, Host allocation tracks live references, not episode frequency. Device tables are read by eager sampling, outside compiled gradient updates. """ - ids = torch.as_tensor(env_ids, dtype=torch.long).cpu().tolist() - if not ids: + if not env_ids.numel(): return slot = t_abs % self._cap owners = self._final_owners[slot] - for env_id in ids: - previous = owners.pop(env_id, None) - if previous is not None: - self._final_free.append(previous) - if len(self._final_free) < len(ids): - self._grow_final_storage(len(ids) - len(self._final_free)) - rows = [self._final_free.pop() for _ in ids] - owners.update(zip(ids, rows)) - device_ids = torch.tensor(ids, device=self.device, dtype=torch.long) - row_ids = torch.tensor(rows, device=self.device, dtype=torch.long) + device_ids = env_ids.to(device=self.device, dtype=torch.long) + # Normal ingest supplies every final for a slot together. A subsequent + # write to the same slot reuses rows already assigned to those envs. + new_ids = device_ids + if owners: + new_ids = device_ids[self._final_slot[device_ids, slot] < 0] + count = new_ids.numel() + if len(self._final_free) < count: + self._grow_final_storage(count - len(self._final_free)) + rows = [self._final_free.pop() for _ in range(count)] + owners.extend(rows) + allocated = torch.tensor(rows, device=self.device, dtype=torch.int32) + self._final_slot[new_ids, slot] = allocated + row_ids = self._final_slot[device_ids, slot].long() self._final_obs_table[row_ids] = obs_rows.to(self.device, torch.float) self._final_critic_table[row_ids] = critic_rows.to(self.device, torch.float) - self._final_slot[device_ids, slot] = row_ids.to(torch.int32) def _write_span(self, slot: int, fields) -> None: obs, critic_obs, actions, rewards, dones, truncations = fields @@ -271,16 +273,20 @@ def sample(self, batch_size: int) -> dict: lanes = torch.arange(self.n_env, device=self.device)[:, None] obs = self.observations[lanes, ring] next_obs = self.observations[lanes, next_ring] - critic = self.critic_observations[lanes, ring] - next_critic = self.critic_observations[lanes, next_ring] truncations = self.truncations[lanes, ring] - if self._final_slot is not None: + have_finals = len(self._final_free) < self._final_capacity + if have_finals: final_ids = self._final_slot[lanes, ring].long() has_final = truncations.bool() & (final_ids >= 0) - final_policy = self._final_obs_table[final_ids.clamp_min(0)] - final_value = self._final_critic_table[final_ids.clamp_min(0)] - next_obs = torch.where(has_final[..., None], final_policy, next_obs) - next_critic = torch.where(has_final[..., None], final_value, next_critic) + final_ids.clamp_min_(0) + next_obs = torch.where(has_final[..., None], self._final_obs_table[final_ids], next_obs) + if self._shared_observations: + critic, next_critic = obs, next_obs + else: + critic = self.critic_observations[lanes, ring] + next_critic = self.critic_observations[lanes, next_ring] + if have_finals: + next_critic = torch.where(has_final[..., None], self._final_critic_table[final_ids], next_critic) flat = self.n_env * batch_size return { "obs": obs.reshape(flat, self.n_obs), diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/config.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/config.py index 9ec0e672c..be37cc180 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/config.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/config.py @@ -77,13 +77,10 @@ class FastSacAsyncOptionsCfg: # collector. learner_cpu_cores: str | None = None collector_cpu_cores: str | None = None - # Transition-ring transport between the async collector and learner: - # "auto" places the ring slots in CUDA-IPC device memory when learner and - # collector inference share one GPU (single fused H2D on the collector, - # D2D-only learner ingest) and falls back to host shared memory otherwise; - # "on"/"off" force the device/host path ("on" warns and falls back when - # the two sides are not on the same GPU). Keep the values quoted: unquoted - # on/off parse as booleans in YAML. + # Transition-ring transport: "auto" uses CUDA IPC when learner and + # collector inference share a GPU and CUDA simulation, if used, is on it + # too. "off" uses host memory. "on" warns if the placement requires the + # host ring. Quote these values in YAML so they stay strings. transition_ipc: str = "auto" # Weight-snapshot transport between the async learner and collector: # "auto" picks CUDA-IPC device slots when both sides share one GPU and the diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py index 4c7d3a1e1..63a4829c1 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py @@ -35,16 +35,16 @@ def __init__( env_name = context.env_name self._rlcfg = context.rl_cfg self._env_name = env_name - self._env_spec = env_registry.resolve(env_name, sim=context.sim) + self._env_spec = env_registry.resolve(env_name, sim=context.sim, sim_device=context.sim_device) self._render = context.render self._resume_from = context.resume_from self._context = context # ------------------------------------------------------------------ setup - def _device(self) -> torch.device: + def _device(self, sim_device: torch.device) -> torch.device: if self._rlcfg.device: return torch.device(self._rlcfg.device) - return resolve_default_device() + return sim_device if sim_device.type == "cuda" else resolve_default_device() def _make_env( self, @@ -59,14 +59,14 @@ def _make_env( headless=render.headless if render else False, record=render.record if render else None, ) - return FastSacEnvWrap(env, self._device(), render=render) + return FastSacEnvWrap(env, self._device(env.device), render=render) def _make_agent(self, env: FastSacEnvWrap) -> FastSacAgent: inner = env.env obs_dim = inner.observation_spec.policy.space.shape[-1] critic_obs_dim = inner.observation_spec.value_or_policy.space.shape[-1] act_dim = inner.action_space.shape[-1] - device = self._device() + device = env.device low = env.action_low high = env.action_high action_scale = (high - low) / 2.0 @@ -105,6 +105,10 @@ def train(self) -> None: try: env = self._make_env(self._context.num_envs, render=self._render) + if self._context.run is not None: + from motrix_rl.runs import annotate_run + + annotate_run(self._context.run_dir, sim_device=str(env.env.device)) agent = self._make_agent(env) num_iterations = self._rlcfg.trainer.num_learning_iterations @@ -307,7 +311,9 @@ def _run_loop( # generic env metrics channel: the wrapper merges the state's # metrics snapshot into infos["metrics"], so backends log them # without hardcoding any metric name. - env_metrics = {k: float(np.mean(v)) for k, v in info.get("metrics", {}).items()} + env_metrics = { + k: float(torch.as_tensor(v).float().mean()) for k, v in info.get("metrics", {}).items() + } system = system_sampler.sample() stats = TrainingPanelStats( iteration=agent.global_step, diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/wrap.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/wrap.py index eeeb5ea26..139036683 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/wrap.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/wrap.py @@ -36,14 +36,15 @@ class FastSacEnvWrap: Wraps a Motrix environment (``ArrayEnv`` frontends) as the torch-tensor vectorized environment consumed by FastSAC. The frontend already exposes torch state and consumes torch actions; state passes through with only a - device move to the trainer device. Environments simulate on CPU, so the + device move to the trainer device. The actor maps its tanh output to the action range declared by the - environment and the wrapper clips on CPU before stepping. Done + environment and the wrapper clips on the simulation device before stepping. Done environments are auto-reset by the environment; the returned observation is therefore the post-reset observation for those environments. """ def __init__(self, env: ABEnv, device: torch.device, render: RenderConfig | None = None) -> None: + self._sim_device = env.device action_space = env.action_space if not isinstance(action_space, gym.spaces.Box): raise TypeError("FastSAC supports only Box action spaces.") @@ -51,9 +52,9 @@ def __init__(self, env: ABEnv, device: torch.device, render: RenderConfig | None self._env = env self.device = device self.num_envs = env.num_envs - # Bounds live on CPU alongside the env-bound actions clamped in step. - self._low_t = torch.as_tensor(action_space.low, dtype=torch.float32) - self._high_t = torch.as_tensor(action_space.high, dtype=torch.float32) + # Clamp actions alongside the simulator. + self._low_t = torch.as_tensor(action_space.low, dtype=torch.float32, device=self._sim_device) + self._high_t = torch.as_tensor(action_space.high, dtype=torch.float32, device=self._sim_device) self._renderer = create_renderer(env, render) @property @@ -89,15 +90,24 @@ def stage_frames(self, obs: torch.Tensor, critic_obs: torch.Tensor) -> EnvObs: def final_frames(self, result: FastSacStepResult) -> FinalObs | None: final = result.final_obs - if result.truncated.any() and final is None: - raise RuntimeError("FastSAC truncation bootstrap requires pre-reset final observations") if final is None: + message = "FastSAC truncation bootstrap requires pre-reset final observations" + if result.truncated.is_cuda: + torch._assert_async(~result.truncated.any(), message) + elif result.truncated.any(): + raise RuntimeError(message) return None return FinalObs(final.env_ids, self.stage_frames(final.obs.policy, final.obs.value_or_policy)) def step(self, actions: torch.Tensor) -> FastSacStepResult: - env_actions = torch.clamp(actions.detach().cpu(), self._low_t, self._high_t) + env_actions = torch.clamp(actions.detach().to(self._low_t.device), self._low_t, self._high_t) state = self._env.step(env_actions) + final = state.final_obs + if final is not None and final.env_ids.device != self.device: + final = FinalObs( + final.env_ids.to(self.device), + EnvObs({key: value.to(self.device) for key, value in final.obs.groups.items()}), + ) return FastSacStepResult( obs=state.obs.policy.to(self.device), critic_obs=state.obs.value_or_policy.to(self.device), @@ -106,7 +116,7 @@ def step(self, actions: torch.Tensor) -> FastSacStepResult: truncated=state.truncated.to(device=self.device, dtype=torch.bool), # None when no row truncated or the implementation does not # capture finals. - final_obs=state.final_obs, + final_obs=final, info=env_infos(state), ) diff --git a/motrix_rl_builtin/tests/test_builtin_sim_backend.py b/motrix_rl_builtin/tests/test_builtin_sim_backend.py index 2b9d42a17..fcccb23d2 100644 --- a/motrix_rl_builtin/tests/test_builtin_sim_backend.py +++ b/motrix_rl_builtin/tests/test_builtin_sim_backend.py @@ -46,6 +46,7 @@ def _make_env(): high=np.array([2.0, 3.0], dtype=np.float32), ) env = Mock(spec=DirectEnv) + env.device = torch.device("cpu") state = ArrayEnvState( obs=EnvObs({"policy": torch.zeros((_NUM_ENVS, _OBS_DIM), dtype=torch.float32)}), reward=torch.ones(_NUM_ENVS, dtype=torch.float32), @@ -114,7 +115,7 @@ class _AsyncEnv: def __init__(self, cfg: EnvCfg, num_envs: int = 1, backend=None) -> None: self._cfg = cfg self._num_envs = num_envs - self._device = torch.device("cpu") + self.device = torch.device("cpu") self._action_space = gym.spaces.Box(-1.0, 1.0, (_ACT_DIM,), dtype=np.float32) self._observation_spec = ObservationSpec( {"policy": ObservationGroupSpec(gym.spaces.Box(-np.inf, np.inf, (_OBS_DIM,), dtype=np.float32))} @@ -332,7 +333,7 @@ def test_sync_env_builder_separates_env_render_settings_and_recording(monkeypatc spec = Mock() spec.make.return_value = env device = torch.device("cpu") - instance = SimpleNamespace(_env_spec=spec, _context=SimpleNamespace(seed=7), _device=lambda: device) + instance = SimpleNamespace(_env_spec=spec, _context=SimpleNamespace(seed=7), _device=lambda sim_device: device) wrapper = Mock() monkeypatch.setattr(train, "FastSacEnvWrap", wrapper) diff --git a/motrix_rl_builtin/tests/test_fastsac_collector.py b/motrix_rl_builtin/tests/test_fastsac_collector.py index 8e8ab8a01..fc1404629 100644 --- a/motrix_rl_builtin/tests/test_fastsac_collector.py +++ b/motrix_rl_builtin/tests/test_fastsac_collector.py @@ -35,6 +35,8 @@ class _CpuEnv: """Wrapper stand-in: the collector reads the original env via ``.env``.""" + device = torch.device("cpu") + def __init__(self): self.num_envs = _NUM_ENVS self.last_actions = None @@ -383,8 +385,8 @@ def test_compiled_cuda_stochastic_actions_change_and_stay_in_bounds() -> None: assert torch.isfinite(first).all() assert torch.isfinite(second).all() assert not torch.equal(first, second) - low = collector._action_bias_cpu - collector._action_scale_cpu - high = collector._action_bias_cpu + collector._action_scale_cpu + low = collector._action_bias - collector._action_scale + high = collector._action_bias + collector._action_scale assert torch.all(first >= low) assert torch.all(first <= high) assert torch.all(second >= low) diff --git a/motrix_rl_builtin/tests/test_fastsac_final_obs.py b/motrix_rl_builtin/tests/test_fastsac_final_obs.py index 2d3dd492d..6a66b9a39 100644 --- a/motrix_rl_builtin/tests/test_fastsac_final_obs.py +++ b/motrix_rl_builtin/tests/test_fastsac_final_obs.py @@ -44,6 +44,7 @@ def test_numpy_adapter_reads_final_result_without_consuming_environment_state(): ) initial = state.replace(final_obs=None) env = SimpleNamespace( + device=torch.device("cpu"), num_envs=1, observation_spec=ObservationSpec({"policy": ObservationGroupSpec(gym.spaces.Box(-np.inf, np.inf, (1,)))}), action_space=gym.spaces.Box(-1.0, 1.0, (1,), dtype=np.float32), @@ -329,7 +330,7 @@ def _assert_live_rows(rb, tags): indices = rb._final_slot[:, absolute % rb._cap].long() torch.testing.assert_close(rb._final_obs_table[indices], torch.full((2, 1), float(tag))) torch.testing.assert_close(rb._final_critic_table[indices], torch.full((2, 1), float(tag + 100))) - live = [row for owners in rb._final_owners for row in owners.values()] + live = [row for owners in rb._final_owners for row in owners] assert len(live) == len(set(live)) assert not set(live).intersection(rb._final_free) assert len(live) + len(rb._final_free) == rb._final_capacity diff --git a/motrix_rl_builtin/tests/test_fastsac_gpu_ipc_ring.py b/motrix_rl_builtin/tests/test_fastsac_gpu_ipc_ring.py index 843be581e..604ef6b91 100644 --- a/motrix_rl_builtin/tests/test_fastsac_gpu_ipc_ring.py +++ b/motrix_rl_builtin/tests/test_fastsac_gpu_ipc_ring.py @@ -101,6 +101,39 @@ def drain_and_verify() -> None: assert expected == len(pushed) +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="cross-device stream ordering requires two GPUs") +def test_ipc_ring_publishes_cross_device_batch_and_final_observations_together(): + source = torch.device("cuda:0") + target = torch.device("cuda:1") + source_stream = torch.cuda.Stream(device=source) + target_stream = torch.cuda.Stream(device=target) + slots = torch.zeros(CAPACITY, N_ENV, FEAT, device=target) + storage = FinalObsStorage(CAPACITY, N_ENV, OBS, CRI, device=target) + ring = GpuIpcTransitionRing(RingCursors(), slots, SCHEMA, CAPACITY, N_ENV, payload_store=storage) + expected = _batch(0) + target_stream.wait_stream(torch.cuda.current_stream(target)) + with torch.cuda.stream(target_stream), torch.cuda.stream(source_stream): + fields = {name: value.to(source).add_(1) for name, value in expected.items()} + payload = FinalObsPayload( + torch.tensor([1], device=source), + fields["obs"][1:2] + 100.0, + fields["critic_obs"][1:2] + 200.0, + ) + assert ring.push(fields, payload) + target_stream.synchronize() + + assert ring.size() == 1 + count, views = ring.read_span() + assert count == 1 + for name, rows in views.items(): + torch.testing.assert_close(rows[0].cpu(), (expected[name] + 1).to(rows.dtype)) + (final,) = storage.read(0, count) + assert final is not None + assert final.env_ids.tolist() == [1] + torch.testing.assert_close(final.obs.cpu(), expected["obs"][1:2] + 101.0) + torch.testing.assert_close(final.critic_obs.cpu(), expected["critic_obs"][1:2] + 201.0) + + @cuda_only def test_ipc_ring_cursor_publishes_only_after_event(): """A pushed slot is invisible until its event completes; size() flushes.""" diff --git a/motrix_rl_builtin/tests/test_fastsac_history.py b/motrix_rl_builtin/tests/test_fastsac_history.py index e3e18506b..57a0c1214 100644 --- a/motrix_rl_builtin/tests/test_fastsac_history.py +++ b/motrix_rl_builtin/tests/test_fastsac_history.py @@ -74,6 +74,7 @@ def test_frame_views_are_copied_before_environment_buffer_reuse(with_value: bool groups["value"] = ObservationGroupSpec(gym.spaces.Box(-np.inf, np.inf, (2,)), 2) class Env: + device = torch.device("cpu") num_envs = 1 action_space = gym.spaces.Box(-1.0, 1.0, (1,), dtype=np.float32) observation_spec = ObservationSpec(groups) diff --git a/motrix_rl_builtin/tests/test_fastsac_topology.py b/motrix_rl_builtin/tests/test_fastsac_topology.py new file mode 100644 index 000000000..10d1301e9 --- /dev/null +++ b/motrix_rl_builtin/tests/test_fastsac_topology.py @@ -0,0 +1,29 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +import pytest +import torch +from motrix_rl_builtin.fastsac.async_impl.topology import resolve_fastsac_topology +from motrix_rl_builtin.fastsac.config import FastSacAsyncOptionsCfg + + +@pytest.mark.parametrize( + ("sim_device", "expected_ipc"), + [("cpu", (True, True)), ("cuda", (True, True)), ("cuda:0", (True, False)), ("cuda:1", (False, True))], +) +def test_fastsac_transition_transport_respects_simulation_placement( + sim_device, expected_ipc, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(torch.cuda, "device_count", lambda: 2) + topology = resolve_fastsac_topology( + num_envs=8, + num_collectors=2, + num_learners=2, + learner_device_specs=["cuda:0", "cuda:1"], + collector_inference_device="cuda", + default_device=torch.device("cuda:0"), + async_options=FastSacAsyncOptionsCfg(), + actor_param_numel=0, + sim_device=sim_device, + ) + assert tuple(channel.use_cuda_ipc for channel in topology.transition_channels) == expected_ipc diff --git a/motrix_rl_rslrl/src/motrix_rl_rslrl/torch/train/ppo.py b/motrix_rl_rslrl/src/motrix_rl_rslrl/torch/train/ppo.py index 7eb1218eb..8a4d995af 100644 --- a/motrix_rl_rslrl/src/motrix_rl_rslrl/torch/train/ppo.py +++ b/motrix_rl_rslrl/src/motrix_rl_rslrl/torch/train/ppo.py @@ -57,9 +57,6 @@ def train(self) -> None: Creates the environment, wraps it for RSLRL, and runs the training loop. """ - # Determine device for training - device = resolve_default_device() - # Set random seed self._set_seed(self._context.seed) @@ -67,6 +64,7 @@ def train(self) -> None: env = env_registry.make( self._env_name, sim=self._sim, + **({"sim_device": self._context.sim_device} if self._context.sim_device is not None else {}), num_envs=self._context.num_envs, mode="train", seed=self._context.seed, @@ -74,9 +72,14 @@ def train(self) -> None: record=self._render.record if self._render else None, ) + device = env.device if env.device.type == "cuda" else resolve_default_device() logger.info(f"Using device: {device}") # Wrap environment for RSLRL + if self._context.run is not None: + from motrix_rl.runs import annotate_run + + annotate_run(self._context.run_dir, sim_device=str(env.device)) vec_env = wrap_env(env, device, render=self._render) # Create RSLRL config - use to_dict() method @@ -127,9 +130,6 @@ def play(self, policy_path: str) -> None: """ import time - # Determine device for evaluation - device = resolve_default_device() - # Set random seed self._set_seed(self._context.seed) @@ -137,6 +137,7 @@ def play(self, policy_path: str) -> None: env = env_registry.make( self._env_name, sim=self._sim, + **({"sim_device": self._context.sim_device} if self._context.sim_device is not None else {}), num_envs=self._context.play_num_envs, mode="play", seed=self._context.seed, @@ -144,7 +145,7 @@ def play(self, policy_path: str) -> None: record=self._render.record if self._render else None, ) - # Wrap environment for RSLRL + device = env.device if env.device.type == "cuda" else resolve_default_device() vec_env = wrap_env(env, device, render=self._render) # Create RSLRL config (minimal for evaluation) @@ -155,7 +156,7 @@ def play(self, policy_path: str) -> None: # Load policy logger.info(f"Loading policy from {policy_path}") - runner.load(policy_path) + runner.load(policy_path, map_location=device) # Run evaluation loop logger.info("Starting evaluation loop...") diff --git a/motrix_rl_rslrl/src/motrix_rl_rslrl/torch/wrap.py b/motrix_rl_rslrl/src/motrix_rl_rslrl/torch/wrap.py index 01df0cb22..e3240e49f 100644 --- a/motrix_rl_rslrl/src/motrix_rl_rslrl/torch/wrap.py +++ b/motrix_rl_rslrl/src/motrix_rl_rslrl/torch/wrap.py @@ -26,6 +26,7 @@ class RslrlEnvWrap(VecEnv): """ def __init__(self, env: ArrayEnv, device: torch.device, render: RenderConfig | None = None): + self._sim_device = env.device """Initialize the VecEnv adapter. Args: @@ -84,7 +85,7 @@ def unwrapped(self) -> "RslrlEnvWrap": return self def step(self, actions: torch.Tensor) -> tuple[TensorDict, torch.Tensor, torch.Tensor, dict]: - state = self._env.step(actions.detach().cpu().to(torch.float32)) + state = self._env.step(actions.detach().to(device=self._sim_device, dtype=torch.float32)) self._state = state # Update episode length buffer diff --git a/motrix_rl_rslrl/tests/test_rslrl_ppo.py b/motrix_rl_rslrl/tests/test_rslrl_ppo.py index 32f3c058f..351afcc57 100644 --- a/motrix_rl_rslrl/tests/test_rslrl_ppo.py +++ b/motrix_rl_rslrl/tests/test_rslrl_ppo.py @@ -59,7 +59,7 @@ class StopAfterMakeEnv(Exception): calls = [] trainer = object.__new__(Trainer) - trainer._context = SimpleNamespace(seed=17, num_envs=2, play_num_envs=3) + trainer._context = SimpleNamespace(run=None, sim_device=None, seed=17, num_envs=2, play_num_envs=3) trainer._env_name = "demo" trainer._sim = None trainer._render = None diff --git a/motrix_rl_rslrl/tests/test_rslrl_sim_backend.py b/motrix_rl_rslrl/tests/test_rslrl_sim_backend.py index 959942bf6..e3a99e875 100644 --- a/motrix_rl_rslrl/tests/test_rslrl_sim_backend.py +++ b/motrix_rl_rslrl/tests/test_rslrl_sim_backend.py @@ -40,6 +40,7 @@ def _make_env(history_length: int = 1, value_dim: int | None = None) -> Mock: observations["value"] = torch.zeros((_NUM_ENVS, value_dim * history_length), dtype=torch.float32) observation_spec = ObservationSpec(groups) env = Mock(spec=DirectEnv) + env.device = torch.device("cpu") state = ArrayEnvState( obs=EnvObs(observations), reward=torch.ones(_NUM_ENVS, dtype=torch.float32), @@ -92,8 +93,8 @@ def test_rl_trainer_supports_sim_backend(monkeypatch, history_length: int, value renderer.close.assert_called_once_with() -@pytest.mark.parametrize("mode", ["train", "play"]) -def test_provider_applies_render_init_kwargs_before_wrapping(monkeypatch, mode): +@pytest.mark.parametrize(("mode", "sim_device"), [("train", None), ("play", None), ("play", "cuda:1")]) +def test_provider_applies_render_init_kwargs_before_wrapping(monkeypatch, mode, sim_device): pytest.importorskip("rsl_rl") module = importlib.import_module("motrix_rl_rslrl.torch.train.ppo") recording = RenderConfig( @@ -104,10 +105,11 @@ def test_provider_applies_render_init_kwargs_before_wrapping(monkeypatch, mode): _env_name="cartpole", _sim="test-sim", _render=recording, - _context=SimpleNamespace(seed=7, num_envs=4, play_num_envs=2), + _context=SimpleNamespace(run=None, sim_device=sim_device, seed=7, num_envs=4, play_num_envs=2), _set_seed=Mock(), ) - make = Mock() + device = torch.device(sim_device or "cpu") + make = Mock(return_value=SimpleNamespace(device=device)) wrapper = Mock(side_effect=RuntimeError("stop before runner creation")) monkeypatch.setattr(module.env_registry, "make", make) monkeypatch.setattr(module, "resolve_default_device", lambda: torch.device("cpu")) @@ -127,5 +129,6 @@ def test_provider_applies_render_init_kwargs_before_wrapping(monkeypatch, mode): seed=7, headless=True, record=recording.record, + **({"sim_device": sim_device} if sim_device is not None else {}), ) - wrapper.assert_called_once_with(make.return_value, torch.device("cpu"), render=recording) + wrapper.assert_called_once_with(make.return_value, device, render=recording) diff --git a/motrix_rl_skrl/src/motrix_rl_skrl/jax/train/ppo.py b/motrix_rl_skrl/src/motrix_rl_skrl/jax/train/ppo.py index 1eb9ab613..a78f6a76e 100644 --- a/motrix_rl_skrl/src/motrix_rl_skrl/jax/train/ppo.py +++ b/motrix_rl_skrl/src/motrix_rl_skrl/jax/train/ppo.py @@ -4,10 +4,11 @@ from typing import Any import flax.linen as nn +import jax import jax.numpy as jnp -import numpy as np from motrix_rl_skrl.config import SkrlCfg, SkrlMemoryCfg from motrix_rl_skrl.jax import wrap_env +from motrix_rl_skrl.jax.wrap import _as_jnp from motrix_rl_skrl.ppo import SkrlPpoTrainerBase, ppo_memory_size from skrl.agents.jax.ppo import PPO as BasePPO from skrl.envs.wrappers.jax import Wrapper @@ -52,7 +53,9 @@ def _instantiate_memory(memory_cfg: SkrlMemoryCfg, memory_size: int, num_envs: i class PPO(BasePPO): - _total_custom_rewards: dict[str, np.ndarray] = {} + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._total_custom_rewards: dict[str, jax.Array] = {} def record_transition( self, @@ -84,9 +87,7 @@ def record_transition( if "Reward" in infos: for key, value in infos["Reward"].items(): - # Manager environments hand out torch tensors; take the - # zero-copy numpy view for the JAX statistics path. - value = np.asarray(value) + value = _as_jnp(value, jnp.float32, self.device) self.tracking_data[f"Reward Instant / {key} (max)"].append(jnp.max(value)) self.tracking_data[f"Reward Instant / {key} (min)"].append(jnp.min(value)) self.tracking_data[f"Reward Instant / {key} (mean)"].append(jnp.mean(value)) @@ -111,6 +112,7 @@ def record_transition( if "metrics" in infos: for key, value in infos["metrics"].items(): + value = _as_jnp(value, jnp.float32, self.device).mean() self.tracking_data[f"metrics / {key} (max)"].append(jnp.max(value)) self.tracking_data[f"metrics / {key} (min)"].append(jnp.min(value)) self.tracking_data[f"metrics / {key} (mean)"].append(jnp.mean(value)) @@ -132,6 +134,7 @@ def _make_env(self, num_envs: int, mode: str = "train"): num_envs=num_envs, mode=mode, sim=self._sim, + **({"sim_device": self._context.sim_device} if self._context.sim_device is not None else {}), seed=self._context.seed, headless=self._render.headless if self._render else False, record=self._render.record if self._render else None, diff --git a/motrix_rl_skrl/src/motrix_rl_skrl/jax/wrap.py b/motrix_rl_skrl/src/motrix_rl_skrl/jax/wrap.py index 8647f1ad8..35ad78762 100644 --- a/motrix_rl_skrl/src/motrix_rl_skrl/jax/wrap.py +++ b/motrix_rl_skrl/src/motrix_rl_skrl/jax/wrap.py @@ -6,8 +6,8 @@ import gymnasium import jax import jax.numpy as jnp -import numpy as np import torch +from skrl import config from skrl.envs.wrappers.jax import Wrapper as SkrlWrapper from motrix_env_core.array.env import ArrayEnv @@ -16,29 +16,36 @@ from motrix_rl.utils import env_infos -def _as_jnp(value, dtype) -> jax.Array: - """Convert torch env state to a JAX array: host view plus device transfer.""" - return jnp.asarray(np.asarray(value), dtype=dtype) +def _as_jnp(value, dtype, device: jax.Device) -> jax.Array: + """Convert values on the requested JAX device, sharing storage on the same GPU.""" + if isinstance(value, torch.Tensor): + value = value.detach() + if value.is_cuda and device.platform == "gpu" and value.device.index == device.local_hardware_id: + return jax.dlpack.from_dlpack(value.contiguous(), device=device).astype(dtype) + value = value.cpu().numpy() + return jnp.asarray(value, dtype=dtype, device=device) class SkrlJaxEnvWrap(SkrlWrapper): """ Wrap the torch-state ArrayEnv (DirectEnv/ManagerEnv) for skrl's JAX path. - Manager environments expose torch state; ``np.asarray`` yields zero-copy - host views that JAX then transfers to its device. + State is placed on the wrapper's JAX device for both rollout and training. """ _env: ArrayEnv _renderer: SimRenderer | VideoRecorder | None = None def __init__(self, env: ArrayEnv, render: RenderConfig | None = None): + self._sim_device = env.device super().__init__(env) + if self._sim_device.type == "cuda": + self._device = config.jax.parse_device(str(self._sim_device)) self._renderer = create_renderer(env, render) def reset(self) -> tuple[jax.Array, Any]: state = self._env.initialize() - return _as_jnp(state.obs.policy, jnp.float32), env_infos(state) + return _as_jnp(state.obs.policy, jnp.float32, self.device), env_infos(state) def step( self, actions: jax.Array @@ -51,17 +58,17 @@ def step( ]: # ``from_dlpack`` is the direct JAX-to-torch path; ``.cpu()`` lands # GPU-resident batches on the host where the CPU frontend steps. - state = self._env.step(torch.from_dlpack(actions).cpu()) + state = self._env.step(torch.from_dlpack(actions).to(self._sim_device)) return ( - _as_jnp(state.obs.policy, jnp.float32), - _as_jnp(state.reward.reshape(-1, 1), jnp.float32), - _as_jnp(state.terminated.reshape(-1, 1), jnp.bool_), - _as_jnp(state.truncated.reshape(-1, 1), jnp.bool_), + _as_jnp(state.obs.policy, jnp.float32, self.device), + _as_jnp(state.reward.reshape(-1, 1), jnp.float32, self.device), + _as_jnp(state.terminated.reshape(-1, 1), jnp.bool_, self.device), + _as_jnp(state.truncated.reshape(-1, 1), jnp.bool_, self.device), env_infos(state), ) def state(self) -> jax.Array: - return _as_jnp(self._env.state.obs.value_or_policy, jnp.float32) + return _as_jnp(self._env.state.obs.value_or_policy, jnp.float32, self.device) def render(self, *args, **kwargs) -> bool | None: if self._renderer is None: diff --git a/motrix_rl_skrl/src/motrix_rl_skrl/ppo.py b/motrix_rl_skrl/src/motrix_rl_skrl/ppo.py index 8a8190e7e..5c00f5fb5 100644 --- a/motrix_rl_skrl/src/motrix_rl_skrl/ppo.py +++ b/motrix_rl_skrl/src/motrix_rl_skrl/ppo.py @@ -166,6 +166,10 @@ def train(self) -> None: rlcfg = self._rlcfg self._set_seed(self._context.seed) env = self._make_env(num_envs=self._context.num_envs, mode="train") + if self._context.run is not None: + from motrix_rl.runs import annotate_run + + annotate_run(self._context.run_dir, sim_device=str(env.device)) skrl_env = self._wrap_env(env, self._render) models = self._make_model(skrl_env, rlcfg) ppo_cfg = rlcfg.agent.to_dict() diff --git a/motrix_rl_skrl/src/motrix_rl_skrl/torch/train/ppo.py b/motrix_rl_skrl/src/motrix_rl_skrl/torch/train/ppo.py index 0cef814f3..e0d9da39f 100644 --- a/motrix_rl_skrl/src/motrix_rl_skrl/torch/train/ppo.py +++ b/motrix_rl_skrl/src/motrix_rl_skrl/torch/train/ppo.py @@ -1,6 +1,7 @@ # Copyright Motphys Technology Co., Ltd. 2025, 2026 # SPDX-License-Identifier: Apache-2.0 +from collections import defaultdict from typing import Any import torch @@ -51,7 +52,62 @@ def _instantiate_memory(memory_cfg: SkrlMemoryCfg, memory_size: int, num_envs: i class PPO(BasePPO): - _total_custom_rewards: dict[str, torch.Tensor] = {} + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._episode_totals: dict[str, torch.Tensor] = {} + self._tracking_window: dict[str, list[torch.Tensor]] = defaultdict(list) + self._tracking_dirty = False + + def _track_values(self, tag: str, values: torch.Tensor, done: torch.Tensor | None = None) -> None: + if done is None: + stats = torch.stack((values.amin(), values.mean(), values.amax())) + else: + count = done.sum() + lo = values.masked_fill(~done, float("inf")).amin() + hi = values.masked_fill(~done, -float("inf")).amax() + mean = values.masked_fill(~done, 0).sum() / count.clamp_min(1) + stats = torch.where(count > 0, torch.stack((lo, mean, hi)), float("nan")) + self._tracking_window[tag].append(stats) + self._tracking_dirty = True + + def _track_episode(self, tag: str, values: torch.Tensor, done: torch.Tensor) -> None: + if tag not in self._episode_totals: + self._episode_totals[tag] = torch.zeros_like(values) + total = self._episode_totals[tag] + total.add_(values) + self._track_values(tag, total, done) + total.masked_fill_(done, 0) + + def _publish_tracking(self) -> None: + if not self._tracking_dirty: + return + summaries = [] + for window in self._tracking_window.values(): + lo, mean, hi = torch.stack(window).unbind(dim=1) + summaries.append( + torch.stack( + ( + torch.nan_to_num(lo, nan=float("inf"), posinf=float("inf"), neginf=-float("inf")).amin(), + torch.nanmean(mean), + torch.nan_to_num(hi, nan=-float("inf"), posinf=float("inf"), neginf=-float("inf")).amax(), + ) + ) + ) + for tag, (lo, mean, hi) in zip(self._tracking_window, torch.stack(summaries).cpu().tolist()): + if mean == mean: + for stat, value in zip(("min", "mean", "max"), (lo, mean, hi)): + self.tracking_data[f"{tag} ({stat})"] = [value] + self._tracking_dirty = False + + def post_interaction(self, *, timestep: int, timesteps: int) -> None: + if timestep > 0 and self.checkpoint_interval > 0 and (timestep + 1) % self.checkpoint_interval == 0: + self._publish_tracking() + super().post_interaction(timestep=timestep, timesteps=timesteps) + + def write_tracking_data(self, *, timestep: int, timesteps: int) -> None: + self._publish_tracking() + super().write_tracking_data(timestep=timestep, timesteps=timesteps) + self._tracking_window.clear() def record_transition( self, @@ -67,50 +123,43 @@ def record_transition( timestep, timesteps, ) -> None: - super().record_transition( - observations=observations, - states=states, - actions=actions, - rewards=rewards, - next_observations=next_observations, - next_states=next_states, - terminated=terminated, - truncated=truncated, - infos=infos, - timestep=timestep, - timesteps=timesteps, - ) - if "Reward" in infos: - for key, value in infos["Reward"].items(): - value = torch.tensor(value, device=self.device) - self.tracking_data[f"Reward Instant / {key} (max)"].append(torch.max(value).item()) - self.tracking_data[f"Reward Instant / {key} (min)"].append(torch.min(value).item()) - self.tracking_data[f"Reward Instant / {key} (mean)"].append(torch.mean(value).item()) - if key not in self._total_custom_rewards: - self._total_custom_rewards[key] = torch.zeros_like(value) - self._total_custom_rewards[key] += value - done = terminated | truncated - done = done.reshape(-1) - if done.any(): - for key in self._total_custom_rewards: - self.tracking_data[f"Reward Total/ {key} (mean)"].append( - torch.mean(self._total_custom_rewards[key][done]).item() - ) - self.tracking_data[f"Reward Total/ {key} (min)"].append( - torch.min(self._total_custom_rewards[key][done]).item() - ) - self.tracking_data[f"Reward Total/ {key} (max)"].append( - torch.max(self._total_custom_rewards[key][done]).item() - ) - - self._total_custom_rewards[key] = self._total_custom_rewards[key] * (~done) - - if "metrics" in infos: - for key, value in infos["metrics"].items(): - tracked_value = torch.tensor(value, device=self.device) - self.tracking_data[f"metrics / {key} (max)"].append(torch.max(tracked_value).item()) - self.tracking_data[f"metrics / {key} (min)"].append(torch.min(tracked_value).item()) - self.tracking_data[f"metrics / {key} (mean)"].append(torch.mean(tracked_value).item()) + interval = self.write_interval + device_tracking = rewards.is_cuda and interval > 0 + if device_tracking: + # The native tracker performs dynamic indexing and host reads each step. + self.write_interval = 0 + try: + super().record_transition( + observations=observations, + states=states, + actions=actions, + rewards=rewards, + next_observations=next_observations, + next_states=next_states, + terminated=terminated, + truncated=truncated, + infos=infos, + timestep=timestep, + timesteps=timesteps, + ) + finally: + self.write_interval = interval + if interval <= 0: + return + + done = (terminated | truncated).reshape(-1) + if device_tracking: + values = rewards.reshape(-1).float() + self._track_values("Reward / Instantaneous reward", values) + self._track_episode("Reward / Total reward", values, done) + self._track_episode("Episode / Total timesteps", torch.ones_like(values), done) + for key, value in infos.get("Reward", {}).items(): + value = torch.as_tensor(value, device=self.device).detach().float() + self._track_values(f"Reward Instant / {key}", value) + self._track_episode(f"Reward Total/ {key}", value, done) + for key, value in infos.get("metrics", {}).items(): + mean = torch.as_tensor(value, device=self.device).detach().float().mean() + self._track_values(f"metrics / {key}", mean) class Trainer(SkrlPpoTrainerBase): @@ -128,6 +177,7 @@ def _make_env(self, num_envs: int, mode: str = "train"): num_envs=num_envs, mode=mode, sim=self._sim, + **({"sim_device": self._context.sim_device} if self._context.sim_device is not None else {}), seed=self._context.seed, headless=self._render.headless if self._render else False, record=self._render.record if self._render else None, diff --git a/motrix_rl_skrl/src/motrix_rl_skrl/torch/wrap.py b/motrix_rl_skrl/src/motrix_rl_skrl/torch/wrap.py index 183715e12..5d8080487 100644 --- a/motrix_rl_skrl/src/motrix_rl_skrl/torch/wrap.py +++ b/motrix_rl_skrl/src/motrix_rl_skrl/torch/wrap.py @@ -26,12 +26,11 @@ class SkrlTorchEnvWrap(SkrlWrapper): _renderer: SimRenderer | VideoRecorder | None = None def __init__(self, env: ArrayEnv, render: RenderConfig | None = None): + self._sim_device = env.device super().__init__(env) - # skrl's fallback for device-less envs is cuda-else-cpu; resolve with - # the shared cuda -> mps -> cpu policy so Apple Silicon trains on MPS. - # CUDA is normalized to an explicit index: skrl realizes tensors on - # cuda:, and torch.device("cuda") != torch.device("cuda:0"). - if not hasattr(env, "device"): + # Keep CUDA rollouts on the simulator GPU. CPU simulation uses the + # project's default learning device (CUDA, MPS, or CPU). + if self._sim_device.type == "cpu": device = resolve_default_device() self._device = torch.device("cuda", torch.cuda.current_device()) if device.type == "cuda" else device self._renderer = create_renderer(env, render) @@ -49,7 +48,7 @@ def step( torch.Tensor, Any, ]: - state = self._env.step(torch.as_tensor(actions, dtype=torch.float32).detach().cpu()) + state = self._env.step(torch.as_tensor(actions, dtype=torch.float32, device=self._sim_device).detach()) return ( state.obs.policy.to(device=self.device, dtype=torch.float32), state.reward.reshape(-1, 1).to(device=self.device, dtype=torch.float32), diff --git a/motrix_rl_skrl/tests/test_skrl_ppo.py b/motrix_rl_skrl/tests/test_skrl_ppo.py index e5300849a..5acb20dad 100644 --- a/motrix_rl_skrl/tests/test_skrl_ppo.py +++ b/motrix_rl_skrl/tests/test_skrl_ppo.py @@ -102,7 +102,7 @@ class StopAfterMakeEnv(Exception): calls = [] trainer = object.__new__(SkrlPpoTrainerBase) trainer._rlcfg = object() - trainer._context = SimpleNamespace(seed=17, num_envs=2, play_num_envs=3) + trainer._context = SimpleNamespace(run=None, sim_device=None, seed=17, num_envs=2, play_num_envs=3) trainer._set_seed = lambda seed: calls.append(("seed", seed)) def make_env(*, num_envs, mode): diff --git a/motrix_rl_skrl/tests/test_skrl_sim_backend.py b/motrix_rl_skrl/tests/test_skrl_sim_backend.py index 3ee503a79..f31ca80af 100644 --- a/motrix_rl_skrl/tests/test_skrl_sim_backend.py +++ b/motrix_rl_skrl/tests/test_skrl_sim_backend.py @@ -43,6 +43,7 @@ def _make_env(history_length: int = 1, value_dim: int | None = None) -> Mock: observations["value"] = torch.zeros((_NUM_ENVS, value_dim * history_length), dtype=torch.float32) observation_spec = ObservationSpec(groups) env = Mock(spec=DirectEnv) + env.device = torch.device("cpu") state = ArrayEnvState( obs=EnvObs(observations), reward=torch.ones(_NUM_ENVS, dtype=torch.float32), @@ -118,7 +119,10 @@ def test_provider_passes_render_init_kwargs_to_registry(monkeypatch, trainer): record=RecordConfig(width=640, height=480, path=Path("video.mp4"), fps=30, num_frames=60), ) instance = SimpleNamespace( - _env_name="cartpole", _sim="test-sim", _context=SimpleNamespace(seed=7), _render=recording + _env_name="cartpole", + _sim="test-sim", + _context=SimpleNamespace(run=None, sim_device=None, seed=7), + _render=recording, ) make = Mock() monkeypatch.setattr(module.env_registry, "make", make) diff --git a/motrix_rl_supermimic/src/motrix_rl_supermimic/env.py b/motrix_rl_supermimic/src/motrix_rl_supermimic/env.py index 84c003b94..85571336f 100644 --- a/motrix_rl_supermimic/src/motrix_rl_supermimic/env.py +++ b/motrix_rl_supermimic/src/motrix_rl_supermimic/env.py @@ -124,11 +124,6 @@ def world_state(self) -> WorldStateManager: def world_context(self) -> WorldContext: return self._world_context - @property - def device(self) -> torch.device: - """Device of the initialized Manager runtime and its action tensors.""" - return self._compiled_manager_program.context.env_id.device - def _init_owned_state(self) -> None: super()._init_owned_state() self._recorder = TransitionRecorder.create( diff --git a/motrix_rl_supermimic/tests/_supermimic_toy.py b/motrix_rl_supermimic/tests/_supermimic_toy.py index f0baeca95..07a9fc9fb 100644 --- a/motrix_rl_supermimic/tests/_supermimic_toy.py +++ b/motrix_rl_supermimic/tests/_supermimic_toy.py @@ -371,7 +371,7 @@ def register() -> None: if not _registered: from motrix_env_core.sim.registry import register_sim_backend - register_sim_backend(_ToyBackend.name, lambda: _ToyBackend) + register_sim_backend(_ToyBackend.name, lambda _device: _ToyBackend) registry.envcfg("supermimic-toy")(ToyEnvCfg) registry.env("supermimic-toy")(SuperMimicEnv) _registered = True diff --git a/motrixlab/src/motrixlab/benchmark/env.py b/motrixlab/src/motrixlab/benchmark/env.py index 87b73e9a6..672085501 100644 --- a/motrixlab/src/motrixlab/benchmark/env.py +++ b/motrixlab/src/motrixlab/benchmark/env.py @@ -27,6 +27,7 @@ class EnvStepConfig(BenchmarkConfig): seed: int = 20260808 zero_actions: bool = False sim_backend: str | None = None + sim_device: str | None = None breakdown: bool = False def __post_init__(self) -> None: @@ -47,6 +48,7 @@ def configure(parser: argparse.ArgumentParser) -> None: parser.add_argument("--seed", type=int, default=20260808) parser.add_argument("--zero-actions", action="store_true") parser.add_argument("--sim-backend") + parser.add_argument("--sim-device", help="Simulation device, e.g. cpu or cuda:0.") parser.add_argument("--breakdown", action="store_true") @@ -60,6 +62,7 @@ def build_config(args: argparse.Namespace) -> EnvStepConfig: seed=args.seed, zero_actions=args.zero_actions, sim_backend=args.sim_backend, + sim_device=args.sim_device, breakdown=args.breakdown, ) @@ -86,7 +89,9 @@ def _run_batch(batch_config: EnvStepConfig, num_envs: int) -> BenchmarkResult: if batch_config.breakdown: profile_env, profile_case = workload.prepare_case(batch_config, num_envs) try: - profile = runner._profile_calls(profile_env.perf, profile_case.step, batch_config.steps, "step") + profile = runner._profile_calls( + profile_env.perf, profile_case.step, batch_config.steps, "step", synchronize=profile_case.synchronize + ) finally: profile_case.close_once() print( diff --git a/motrixlab/src/motrixlab/benchmark/physics.py b/motrixlab/src/motrixlab/benchmark/physics.py index f26a32896..0fed44f29 100644 --- a/motrixlab/src/motrixlab/benchmark/physics.py +++ b/motrixlab/src/motrixlab/benchmark/physics.py @@ -37,10 +37,12 @@ import sys import tempfile from dataclasses import asdict, dataclass, field, replace +from functools import partial from pathlib import Path import motrixsim as mtx import numpy as np +import torch from motrix_bench import ( BenchmarkConfig, @@ -51,7 +53,8 @@ run_case, ) from motrix_env_core import registry -from motrix_env_core.base import SimCfg +from motrix_env_core.config.sim import SimCfg +from motrix_env_core.sim.registry import create_sim_backend from motrix_env_motrixsim.compiler import MotrixSimSceneCompiler from motrix_envs.config.scene import StandardSceneCfg, StandardSceneObjsCfg @@ -68,6 +71,7 @@ class PhysicsStepConfig(BenchmarkConfig): solver_iterations: int = 3 nstep: int = 1 out_json: str = "" + sim_device: str = "cpu" def __post_init__(self) -> None: # Direct call: zero-arg super() resolves to the pre-slots class. @@ -86,6 +90,7 @@ def __post_init__(self) -> None: def configure(parser: argparse.ArgumentParser) -> None: parser.add_argument("--robot", required=True, help="Registered robot name.") + parser.add_argument("--sim-device", default="cpu", help="Simulation device, e.g. cpu or cuda:0.") parser.add_argument("--num-envs", type=int, nargs="+", default=[2048]) parser.add_argument("--numa", choices=("single", "node", "shard", "_worker"), default="single") parser.add_argument("--node", type=int, default=0) @@ -109,6 +114,7 @@ def build_config(args: argparse.Namespace) -> PhysicsStepConfig: solver_iterations=args.solver_iterations, nstep=args.nstep, out_json=args.out_json, + sim_device=args.sim_device, ) @@ -157,7 +163,20 @@ def _prepare_with_info(config: PhysicsStepConfig) -> tuple[PreparedCase, dict]: num_envs = config.num_envs[0] robot_cfg = registry.make_robot_config(config.robot) scene = StandardSceneCfg(objs=StandardSceneObjsCfg(robot=robot_cfg)) - sim = SimCfg(dt=config.dt, solver_iterations=config.solver_iterations) + sim = SimCfg(dt=config.dt, solver_iterations=config.solver_iterations, device=config.sim_device) + sim.validate() + if torch.device(sim.device).type == "cuda": + backend = create_sim_backend("motrixsim", sim.device)(scene, sim, num_envs) + reset = backend.compile_writes({}, reset=True) + status = torch.empty(num_envs, dtype=torch.int32, device=backend.device) + case = PreparedCase( + step=partial(backend.step, config.nstep, result=status), + before_step=reset.execute, + synchronize=partial(torch.cuda.synchronize, backend.device), + items_per_step=float(num_envs * config.nstep), + unit="env steps", + ) + return case, _metadata(config, backend.num_actuators, backend.model.num_links) model = MotrixSimSceneCompiler().compile(scene, sim) data = mtx.SceneData(model, batch=[num_envs]) @@ -182,7 +201,11 @@ def reset_state() -> None: items_per_step=float(num_envs * config.nstep), unit="env steps", ) - metadata = { + return case, _metadata(config, num_actuators, num_links) + + +def _metadata(config: PhysicsStepConfig, num_actuators: int, num_links: int) -> dict: + return { "robot": config.robot, "dt": config.dt, "solver_iterations": config.solver_iterations, @@ -191,7 +214,6 @@ def reset_state() -> None: "links": num_links, "device": _device_context(), } - return case, metadata def prepare(config: PhysicsStepConfig) -> PreparedCase: @@ -222,6 +244,8 @@ def _worker_command(config: PhysicsStepConfig, node: int, num_envs: int, out_jso str(num_envs), "--robot", config.robot, + "--sim-device", + config.sim_device, "--dt", str(config.dt), "--solver-iterations", diff --git a/motrixlab/src/motrixlab/benchmark/runner.py b/motrixlab/src/motrixlab/benchmark/runner.py index 785191ded..ef80f24cd 100644 --- a/motrixlab/src/motrixlab/benchmark/runner.py +++ b/motrixlab/src/motrixlab/benchmark/runner.py @@ -20,11 +20,18 @@ class ProfileResult: root: PerfNode -def _profile_calls(perf: Perf, function: Callable[[], object], count: int, root_name: str) -> ProfileResult: +def _profile_calls( + perf: Perf, + function: Callable[[], object], + count: int, + root_name: str, + *, + synchronize: Callable[[], object] | None = None, +) -> ProfileResult: was_enabled = perf.enabled perf.reset() if not was_enabled: - perf.enable() + perf.enable(synchronize=synchronize) started = time.perf_counter() try: for _ in range(count): diff --git a/motrixlab/src/motrixlab/benchmark/workload.py b/motrixlab/src/motrixlab/benchmark/workload.py index 6be79cf9c..0ed2debc6 100644 --- a/motrixlab/src/motrixlab/benchmark/workload.py +++ b/motrixlab/src/motrixlab/benchmark/workload.py @@ -36,6 +36,8 @@ def prepare_case(config: EnvStepConfig, num_envs: int) -> tuple[object, Prepared kwargs = {"mode": config.mode, "num_envs": num_envs} if config.sim_backend is not None: kwargs["sim"] = config.sim_backend + if config.sim_device is not None: + kwargs["sim_device"] = config.sim_device env = registry.make(name, **kwargs) try: actual_num_envs = int(env.num_envs) @@ -49,13 +51,19 @@ def prepare_case(config: EnvStepConfig, num_envs: int) -> tuple[object, Prepared low = np.where(np.isfinite(space.low), space.low, -1.0) high = np.where(np.isfinite(space.high), space.high, 1.0) actions = np.random.default_rng(config.seed).uniform(low, high, size=shape).astype(space.dtype) + synchronize = None if isinstance(env, manager_env_type): import torch - actions = torch.from_numpy(np.ascontiguousarray(actions)) + actions = torch.from_numpy(np.ascontiguousarray(actions)).to(env.device) + if env.device.type == "cuda": + from functools import partial + + synchronize = partial(torch.cuda.synchronize, env.device) case = PreparedCase( step=lambda: env.step(actions), close=lambda: close_env(env), + synchronize=synchronize, items_per_step=float(actual_num_envs), unit="env steps", ) diff --git a/motrixlab/src/motrixlab/commands/view.py b/motrixlab/src/motrixlab/commands/view.py index 0f7f1236d..3bdf34369 100644 --- a/motrixlab/src/motrixlab/commands/view.py +++ b/motrixlab/src/motrixlab/commands/view.py @@ -17,7 +17,6 @@ from motrix_env_core import registry from motrix_env_core.array.env import ArrayEnv -from motrix_env_core.base import ABEnv from motrix_env_core.config import SimCfg, configclass from motrix_env_core.config.scene.base import RobotCfg, SceneCfg, SceneObjsCfg, SceneVisualCfg, SystemCameraCfg from motrix_env_core.config.scene.geometry import FlatTerrainCfg @@ -36,32 +35,24 @@ class ViewConfig: env: str | None = None robot: str | None = None sim: str | None = None + sim_device: str | None = None num_envs: int = 1 -def _sample_random_action_np(env: ABEnv) -> np.ndarray: - action_space = env.action_space - if isinstance(action_space, gym.spaces.Box): - size = (env.num_envs, *action_space.shape) - low = action_space.low - high = action_space.high - low = np.where(np.isneginf(low), -1e6, low) - high = np.where(np.isposinf(high), 1e6, high) - return np.random.uniform(low=low, high=high, size=size).astype(action_space.dtype) - else: - raise NotImplementedError("Only Box action space is supported") - - -def _run_np(env: ArrayEnv): +def _run_env(env: ArrayEnv): import torch + action_space = env.action_space + if not isinstance(action_space, gym.spaces.Box): + raise NotImplementedError("Only Box action space is supported") + shape = (env.num_envs, *action_space.shape) + low = torch.as_tensor(np.where(np.isneginf(action_space.low), -1e6, action_space.low), device=env.device) + high = torch.as_tensor(np.where(np.isposinf(action_space.high), 1e6, action_space.high), device=env.device) renderer = create_renderer(env, RenderConfig()) env_dt = env.cfg.ctrl_dt - # ArrayEnv frontends (DirectEnv and ManagerEnv alike) consume torch - # tensor actions; sample in numpy and hand the env its tensor currency. while True: t0 = time.monotonic() - actions = torch.from_numpy(_sample_random_action_np(env)) + actions = low + (high - low) * torch.rand(shape, device=env.device, dtype=low.dtype) env.step(actions) renderer.render() real_dt = time.monotonic() - t0 @@ -186,7 +177,8 @@ def run(cfg: ViewConfig) -> None: env_name = cfg.env or DEFAULT_ENV_NAME try: - env = registry.make(env_name, num_envs=cfg.num_envs) + overrides = {key: val for key, val in (("sim", cfg.sim), ("sim_device", cfg.sim_device)) if val is not None} + env = registry.make(env_name, num_envs=cfg.num_envs, **overrides) except ModuleNotFoundError as exc: # Torch-frontend environments import torch when their factory resolves the env class. if exc.name == "torch": @@ -194,7 +186,7 @@ def run(cfg: ViewConfig) -> None: raise if isinstance(env, ArrayEnv): - _run_np(env) + _run_env(env) return raise TypeError(f"Unsupported environment type '{type(env).__name__}'.") diff --git a/pyproject.toml b/pyproject.toml index d03556964..9e8ab6fb7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,6 +40,7 @@ docs = [ # installation entry points without duplicating versions or index routing. cuda = ["motrix-rl[cuda]==0.5.0"] rocm = ["motrix-rl[rocm]==0.5.0"] +sim-gpu = ["motrix-env-motrixsim[gpu]==0.5.0"] [dependency-groups] dev = [ diff --git a/tests/test_view_command.py b/tests/test_view_command.py index c5c382757..bdb79cc58 100644 --- a/tests/test_view_command.py +++ b/tests/test_view_command.py @@ -23,7 +23,7 @@ def make(name, *, num_envs): return env monkeypatch.setattr(view.registry, "make", make) - monkeypatch.setattr(view, "_run_np", run_calls.append) + monkeypatch.setattr(view, "_run_env", run_calls.append) view.run(ViewConfig()) diff --git a/uv.lock b/uv.lock index d4a46746f..aaeaf37aa 100644 --- a/uv.lock +++ b/uv.lock @@ -1485,12 +1485,19 @@ dependencies = [ { name = "numpy" }, ] +[package.optional-dependencies] +gpu = [ + { name = "motrixsim-gpu", marker = "(platform_machine == 'AMD64' and sys_platform == 'win32') or (platform_machine != 'AMD64' and extra == 'extra-10-motrix-lab-cuda' and extra == 'extra-10-motrix-lab-rocm') or (platform_machine != 'AMD64' and extra == 'extra-9-motrix-rl-cuda' and extra == 'extra-9-motrix-rl-rocm') or sys_platform == 'linux' or (sys_platform != 'win32' and extra == 'extra-10-motrix-lab-cuda' and extra == 'extra-10-motrix-lab-rocm') or (sys_platform != 'win32' and extra == 'extra-9-motrix-rl-cuda' and extra == 'extra-9-motrix-rl-rocm')" }, +] + [package.metadata] requires-dist = [ { name = "motrix-env-core", editable = "motrix_env_core" }, { name = "motrixsim-core", specifier = "===1.0.0" }, + { name = "motrixsim-gpu", marker = "(platform_machine == 'AMD64' and sys_platform == 'win32' and extra == 'gpu') or (sys_platform == 'linux' and extra == 'gpu')", specifier = "===1.0.0" }, { name = "numpy", specifier = ">=1.26" }, ] +provides-extras = ["gpu"] [[package]] name = "motrix-env-mujoco" @@ -1581,6 +1588,9 @@ rocm = [ rslrl = [ { name = "motrix-rl-rslrl" }, ] +sim-gpu = [ + { name = "motrix-env-motrixsim", extra = ["gpu"] }, +] skrl-jax = [ { name = "motrix-rl-skrl", extra = ["jax"] }, ] @@ -1615,6 +1625,7 @@ requires-dist = [ { name = "motrix-deploy-tasks", editable = "motrix_deploy_tasks" }, { name = "motrix-deploy-unitree", extras = ["native"], marker = "extra == 'unitree'", editable = "motrix_deploy_unitree" }, { name = "motrix-env-motrixsim", editable = "motrix_env_motrixsim" }, + { name = "motrix-env-motrixsim", extras = ["gpu"], marker = "extra == 'sim-gpu'", editable = "motrix_env_motrixsim" }, { name = "motrix-env-mujoco", editable = "motrix_env_mujoco" }, { name = "motrix-envs", editable = "motrix_envs" }, { name = "motrix-rl", editable = "motrix_rl" }, @@ -1635,7 +1646,7 @@ requires-dist = [ { name = "sphinxcontrib-video", marker = "extra == 'docs'" }, { name = "tensorboard", marker = "extra == 'docs'", specifier = "==2.20.0" }, ] -provides-extras = ["rslrl", "skrl-jax", "unitree", "docs", "cuda", "rocm"] +provides-extras = ["rslrl", "skrl-jax", "unitree", "docs", "cuda", "rocm", "sim-gpu"] [package.metadata.requires-dev] dev = [ @@ -1878,6 +1889,29 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ac/9c/8de1ff6bee9587d1dac325aa8087d3258d662c2724f318d125af3e4dda75/motrixsim_core-1.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:fb2cff1d11ee46b73831e9005993bf892806fc76d546b859736a3a352e2092df", size = 71778061, upload-time = "2026-11-19T04:54:27.452Z" }, ] +[[package]] +name = "motrixsim-gpu" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "motrixsim-core", marker = "sys_platform != 'darwin' or (extra == 'extra-10-motrix-lab-cuda' and extra == 'extra-10-motrix-lab-rocm') or (extra == 'extra-9-motrix-rl-cuda' and extra == 'extra-9-motrix-rl-rocm')" }, + { name = "warp-lang", marker = "sys_platform != 'darwin' or (extra == 'extra-10-motrix-lab-cuda' and extra == 'extra-10-motrix-lab-rocm') or (extra == 'extra-9-motrix-rl-cuda' and extra == 'extra-9-motrix-rl-rocm')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/5f/78391caeacdfa9ec79cb718cfb31fa38e7e6f88518de3ff9d1c3d7cd5e77/motrixsim_gpu-1.0.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c143d740b7fd52adfda7ba94fbba807bb4f98be231086acfee22a6713927e0f6", size = 69370625, upload-time = "2026-11-19T07:45:40.85Z" }, + { url = "https://files.pythonhosted.org/packages/8e/b8/11f99c1305add1868d27c9fe63e91f8f21f7b78404eda396bdc06696f17a/motrixsim_gpu-1.0.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:01661a89e4e37496287ff77b9f27b2bda2070ca60e193018434af19c51c58b99", size = 70340078, upload-time = "2026-11-19T07:41:21.179Z" }, + { url = "https://files.pythonhosted.org/packages/0a/c9/af581b5036c05424bb8cd4763ce9bd76d20ba364f1d4f9625edc35555a0b/motrixsim_gpu-1.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:3cf584a5b73f9b6df2f8426371d90d960f6ab55f12ff54a1bcfaea973ac1a811", size = 66657967, upload-time = "2026-11-19T07:40:41.974Z" }, + { url = "https://files.pythonhosted.org/packages/ec/12/5f77c33430f133c6a1d79045a9d7a8c58888cc305d6a572bbbbc1bef0527/motrixsim_gpu-1.0.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:11688ab2490f4c41dd8f3252d52c600b150133fe481e38914b623f2e326691f6", size = 69166637, upload-time = "2026-11-19T07:45:14.311Z" }, + { url = "https://files.pythonhosted.org/packages/ac/2e/2e7ba8068c26f32e2d76c9d18a1ee7cbd857dc46bc46e2fb119915e5582b/motrixsim_gpu-1.0.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9a482d998fea57619fc2cf55f7fa9f84eb2ce4b5d6aefc034ed8c270844a823c", size = 68752464, upload-time = "2026-11-19T07:44:16.68Z" }, + { url = "https://files.pythonhosted.org/packages/24/6d/5b0dfbb53b6dca09ed8ba3d2724242e87da91f181c6efd2d52bf971b5a83/motrixsim_gpu-1.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:a88126e269097c0c032a8b41dd94eac2846a81ed853d4aedd993f4b872467da2", size = 66541505, upload-time = "2026-11-19T07:42:05.838Z" }, + { url = "https://files.pythonhosted.org/packages/b7/be/28640bb40e81bd0ceea954a630be75e8cc8d9b5b8a377a5212ae20461b96/motrixsim_gpu-1.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f63fd37344e88531cc1b6877a7e336703c8f3b61ba72f829ee9914371d83d8a3", size = 68569763, upload-time = "2026-11-19T07:44:38.7Z" }, + { url = "https://files.pythonhosted.org/packages/29/32/9f1c24724807e3417877d5282be6741b994645eb71eeaf8ecfd8a5b7b1c4/motrixsim_gpu-1.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a308c750492aabc5457dde498c2b8a25430e74bfcdeb3682c33d2dc9a6131872", size = 69778123, upload-time = "2026-11-19T07:43:30.064Z" }, + { url = "https://files.pythonhosted.org/packages/e3/b7/3c523c6ccda55a1e47dbcd0b40515f1829cc7b8c721a3ad11e9bda42298d/motrixsim_gpu-1.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:277a14489309153fe7e6785a18653df905d00c68d2ef3193934e4818600d5475", size = 66062316, upload-time = "2026-11-19T07:39:01.31Z" }, + { url = "https://files.pythonhosted.org/packages/72/7c/fde51d21bb247ff894bf3639b5f5bbf804cd30e1a34d78987275ecb02344/motrixsim_gpu-1.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:42587ba2cfec27d24d05f13aa0f48786d111f7fe206ad47575ae7923292d539c", size = 68207662, upload-time = "2026-11-19T07:40:12.167Z" }, + { url = "https://files.pythonhosted.org/packages/a9/ad/8c800b36b6b0fc524aaafc9768aa2f6e54b1bdf531ca77d6c9e4b704fa6c/motrixsim_gpu-1.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bacd5ff3fb744e3131b32588602b08dff7a0bc072bbf2c21f0526e073ea118bd", size = 69365778, upload-time = "2026-11-19T07:42:40.967Z" }, + { url = "https://files.pythonhosted.org/packages/8f/5f/9187b69c8ea89e2766aeda55c17a8255a1769f15b94e43d483cf5ca357f7/motrixsim_gpu-1.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:7de69fa0a7b493c643b9df6529d3a739b621a9c246edf7f6dadaa9bf8f94be94", size = 65788253, upload-time = "2026-11-19T07:39:37.674Z" }, +] + [[package]] name = "mpmath" version = "1.3.0" @@ -4118,6 +4152,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a7/c2/fe1e52489ae3122415c51f387e221dd0773709bad6c6cdaa599e8a2c5185/urllib3-2.5.0-py3-none-any.whl", hash = "sha256:e6b01673c0fa6a13e374b50871808eb3bf7046c4b125b216f6bf1cc604cff0dc", size = 129795, upload-time = "2025-06-18T14:07:40.39Z" }, ] +[[package]] +name = "warp-lang" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", marker = "sys_platform != 'darwin' or (extra == 'extra-10-motrix-lab-cuda' and extra == 'extra-10-motrix-lab-rocm') or (extra == 'extra-9-motrix-rl-cuda' and extra == 'extra-9-motrix-rl-rocm')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/b0/9b1de407fa10b380f5ca4ed1c3e5b129be55ea26a927c7a49e45cdde14b0/warp_lang-1.17.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:f2fec43afb81caa2190c0b7fa3aaf4d869f3599839f0c40b9ead84331f91e993", size = 27544218, upload-time = "2026-08-31T05:52:29.177Z" }, + { url = "https://files.pythonhosted.org/packages/a6/a1/e11aa6898e8bbb6910e89fe31a3338fb2566f038912010875c072e6dafd1/warp_lang-1.17.0-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:47cd93636828dd16e55eeb4e77a0e3547b5fb0f383000a3d228629df68f28fd8", size = 164347636, upload-time = "2026-08-31T05:53:14.441Z" }, + { url = "https://files.pythonhosted.org/packages/6e/4f/a17b1f0ebfeabe37326f01afb6109961f20a0165c1258242f46d10a554f5/warp_lang-1.17.0-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:5051271048da956a8b94e2db9771ce60ce9591a3ac5bb49037f3d6812d1eea00", size = 172665443, upload-time = "2026-08-31T05:53:52.47Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7a/36306a503085cbfc79c35a28e441c59dd1d8070d2dd65152345ebf2dfec2/warp_lang-1.17.0-py3-none-win_amd64.whl", hash = "sha256:ca35c82242a7553046f09023bbe56750b5c3d9af72625bd1a905a56d3189771d", size = 151236515, upload-time = "2026-08-31T05:54:27.944Z" }, +] + [[package]] name = "wcwidth" version = "0.9.2" diff --git a/wiki/design/index.md b/wiki/design/index.md index e8011fcff..11c482896 100644 --- a/wiki/design/index.md +++ b/wiki/design/index.md @@ -6,6 +6,8 @@ ## 文档列表 +- [MotrixSim GPU 仿真与原生后端架构设计](./motrixsim-gpu.md) + 定义单一设备模型(前端跟随 `sim.device`)、统一后端工厂 `create_sim_backend(name, device)` 与 `EnvCfg.backend`、面向 GPU SoA 的零拷贝读视图与 `world_mask` 原生掩码写入/复位执行模型,以及 RL 单进程共置和异步 FastSAC 拓扑的设备对齐契约。 - [项目整体架构设计](./architecture.md) 系统总体分层、核心原则(Model/Data/State 分离、环境与 RL 框架解耦、注册表驱动、配置层次继承)、仿真后端抽象、RL 框架集成方式和数据流总览。 - [Manager 设计](./manager/index.md) diff --git a/wiki/design/manager/runtime.md b/wiki/design/manager/runtime.md index 7777cc77a..85e5c7fbc 100644 --- a/wiki/design/manager/runtime.md +++ b/wiki/design/manager/runtime.md @@ -191,6 +191,14 @@ WBT 在 motion clip wrap 时使用该机制。sim-reset dispatch 通过 `env_ids 直接填紧凑 `(K, *write_shape)` 的 `sim_writes`;第 j 个写入行对应 `env_ids[j]`,不能再按原始行号索引写入缓冲。 per-step 统计折叠(如 WBT 的失败计数 EMA)由 term 自行内联进 `advance` 图内。 +CUDA 的自动复位按后端与复位项特征自适应执行:支持原生掩码复位的后端可用 `(N,)` 布尔掩码复位仿真和刷新读数。 +Command term 可提供 `reset_masked(self, ctx, world_mask, episode_reset)`,用 `world_mask` 选择要重采样的行, +用 `episode_reset` 筛选参与回合统计的行;Action term 可提供 `_reset_masked(self, world_mask)`。 +声明 `stateless=True` 的纯写入 `ResetTerm`(只写 `sim_writes`、不修改 `ctx`)可与命令掩码复位合入同一张静态 +`(N,)` 编译图并通过 `execute_masked(world_mask)` 提交(当写程序不含主机侧参数表提交且未达截断步时全程零主机同步); +默认 `stateless=False` 的自定义 `ResetTerm` 则先经主机门控提取实际复位行的紧凑 `env_ids` 和对应的紧凑 `sim_writes`。 +第三方 command/action term 只提供紧凑复位钩子时,环境使用紧凑复位路径。 + ActionTerm 是 host 侧描述对象:静态 action space、canonicalized state 和批量 process/reset callback。 只有 `term.state` 进入 kernel ABI,`ctx.actions[name]` 直接取得 lane-scoped state;host 通过 `env.action_terms[name].state` 访问同一份 backing。callback 不进入 kernel data,不要求 `@dispatch`。 diff --git a/wiki/design/motrixsim-gpu.md b/wiki/design/motrixsim-gpu.md new file mode 100644 index 000000000..1ebcaa6c4 --- /dev/null +++ b/wiki/design/motrixsim-gpu.md @@ -0,0 +1,92 @@ +# MotrixSim GPU 仿真与原生后端架构设计 + +## 摘要 + +本文定义 MotrixLab 引入 NVIDIA CUDA 物理仿真(`motrixsim-gpu`)的完整架构契约:保持“环境前端张量设备始终跟随 `sim.device`”的单一设备模型,通过 `EnvCfg.backend` 与统一工厂 `create_sim_backend(name, device)` 完成后端与设备的单点解析;在后端执行层区分 CPU 暂存批处理模型与 GPU 常驻零拷贝视图/掩码执行模型;并在 `motrix_rl` 单进程与异步多进程拓扑中统一对齐 `sim_device` 局部性。验收范围见 [MotrixSim GPU 实施与验收](../plan/motrixsim-gpu.md)。 + +--- + +## 1. 单一设备模型与后端解析契约 + +### 1.1 单一设备不变量(Single-Device Invariant) + +- `SimCfg.device: str = "cpu"` 是单个环境实例唯一的设备配置源,并在 `SimCfg.validate()` 中完成合法设备语法与设备类型(`"cpu"` / `"cuda"`)校验。 +- `ArrayEnv`(含 `DirectEnv` 与 `ManagerEnv`)在构造期将 `self.device` 规范化为明确的 `torch.device`(未带索引的 `"cuda"` 解析为当前可见默认卡 `cuda:`)。环境生命周期张量、Manager 上下文与持久状态、动作输入、观测输出以及物理后端数据均驻留在同一 `self.device` 上,不拆分独立的“物理设备 vs 前端张量设备”双轴。 +- `registry.make(..., sim=..., sim_device=...)` 与 `EnvBuildSpec.make(..., sim_device=...)` 作为运行期入口覆写 `env_cfg.sim.device`,显式参数优先于环境静态默认配置(内置任务默认 `"cpu"`)。[环境注册入口](../../motrix_env_core/src/motrix_env_core/registry.py) + +### 1.2 统一后端配置与工厂派发 + +- `EnvCfg` 基类统一定义 `backend: str | None = None`(`DirectEnvCfg` 与 `ManagerBasedEnvCfg` 共享同一字段,子类不重复声明)。`DirectEnv` 与 `ManagerEnv` 均按 `sim_arg or cfg.backend or default_sim_backend_name()` 解析后端名称。 +- `motrix_env_core.sim.registry` 提供单点后端类解析入口: + +```python +def create_sim_backend( + name: str | None = None, + device: torch.device | str = "cpu", +) -> type[SimBackend]: ... +``` + +- 后端发行包通过 `motrix_env.sim_backends` entry point 注册惰性解析器 `(device: torch.device) -> type[SimBackend]`: + - `motrix-env-motrixsim` 在 `device.type == "cpu"` 时返回 `MotrixSimBackend`;在 `device.type == "cuda"` 时校验可选依赖 `motrixsim.gpu` 与目标卡可用性,直接返回 `MotrixCudaBackend`。 + - 仅安装 CPU 依赖时可正常导入插件并运行全部 CPU 任务;显式请求不支持的设备类型、缺少 `motrix-env-motrixsim[gpu]` 或卡号越界时在工厂解析期立即给出明确异常。[插件依赖声明](../../motrix_env_motrixsim/pyproject.toml) +- 所有 `SimBackend` 子类遵循统一构造签名 `(scene: SceneCfg, sim: SimCfg, num_envs: int, *, render: RenderConfig | None = None)`。 + +--- + +## 2. 双轨后端执行模型:CPU 暂存批处理 vs GPU 原生常驻掩码执行 + +任务与前端层保持统一的声明式接口(`SimDataQuery`、`ModelQuery`、`SimWrite`、`ManagerResetCfg` 及 `DirectEnv` 生命周期钩子),底层物理后端按设备内存形态采用各自的原生执行模型: + +| 维度 | CPU 后端(`MotrixSimBackend`) | GPU 原生后端(`MotrixCudaBackend`) | +| :--- | :--- | :--- | +| **底层数据形态** | C++ AoS 世界实例内存,跨语言边界访问需聚合拷贝 | Warp / CUDA SoA 批量设备数组(`gpu.SceneData`),天然与 Torch 共享显存 | +| **物理读取模型** | `mtx.query.QueryProgram` 将多字段打包拷贝至单一连续 Host NumPy Arena,暴露只读视图 | **常驻字段直接暴露 `wp.to_torch` 零拷贝设备视图**;仅非连续拼接与派生接触/传感器核写入紧凑持久缓冲,并与 Warp 核一并捕获进单一静态 CUDA Graph | +| **物理写入模型** | `mtx.write.WriteProgram` 持有 Host 暂存缓冲,单次 C++ 调用批量散射并归一化/刷新 FK | 普通写入使用暂存缓冲并保持行隔离。ActionManager 的全批专用通道可直写连续的 `data.actuator_ctrls`;球关节四元数在设备端归一化;执行器增益、连杆质量/质心与几何体滑动摩擦覆盖全部在设备端原位掩码更新并单核重算刚体惯量 | +| **局部 Reset 粒度** | 主机提取 `env_ids = nonzero(done)`(`(K,)`),仅复位 `K` 个世界以节省标量开销 | **固定形状 `world_mask: bool[N]` 原位掩码执行**:单核并行清零被选世界的 DOF/控制与双 bank 求解器缓存并按掩码刷新派生接触读数;纯写入 `ResetTerm(stateless=True)` 与命令掩码钩子合入静态 `CUDAGraph` 直接调用 `execute_masked`,仅在近截断步或存在有状态自定义 `ResetTerm` 时启用主机复位门控 | +| **流与计时边界** | `nullcontext`,CPU 单调时钟直接反映真实耗时 | `physics_stream()` 在控制步边界与调用方 Torch 流做单次进出事件交接;性能剖析可在各计时区间边界同步设备 | + +### 2.1 读侧视图生命周期契约 + +- 前端在每个控制步的 `physics_step()` 之后(`compute_transition`)以及 `reset` 之后(`compute_observation`)刷新并消费仿真读视图;前端不依赖“在 `writes.execute()` 之后、`reads.execute()` 之前旧视图仍保留写前快照”的暂存副作用。 +- 由此,GPU 后端对 `gpu.SceneData` 中布局已对齐的连续状态直接返回零拷贝张量视图;仅对需要跨列收集或物理后处理(接触合力矩、几何体碰撞对、Touch 传感器)的查询分配输出缓冲,且所有派生读取 kernel 均接受可选 `world_mask: bool[N]`,局部刷新时跳过未复位世界。MotrixSim GPU 1.0.0 的 FK 入口接收整批数据,写入和接触投影按掩码执行。 + +### 2.2 写侧与掩码 Reset 契约 + +- 声明层继续使用 `SimWrite` 与 `ResetTerm` 描述写入目标。 +- 执行层支持固定批次宽度 `N` 的布尔掩码 `world_mask: torch.Tensor`(`bool[N]`): + - CPU 后端在边界将 `world_mask` 转为紧凑 `env_ids` 调用原生 C++ 批量接口; + - CUDA Manager 使用掩码复位求解器、动作、命令和观测状态,并按掩码刷新派生读数。对声明 `stateless=True` 的纯输出 `ResetTerm`,执行器在静态 `(N,)` `CUDAGraph` 内求值并通过 `execute_masked(world_mask)` 原位掩码提交;对默认 `stateless=False` 的自定义 `ResetTerm`,经主机门控提取实际复位行的紧凑 `env_ids` 与 `sim_writes`。截断终态在近截断窗口经单次门控以紧凑快照保存。 +- 所有对 `motrixsim-gpu` 内部 `.low` 求解器域(双 bank warmstart lambdas、碰撞计数、接触冲量转力矩、增益/参数覆盖)的访问必须收敛封装在 `motrix_env_motrixsim` 单一内部原语模块中,与上层读写编译器解耦,作为未来上游 SDK 原生算子到位后的唯一替换面。 +- 模型静态元数据(`SimModel`、`BodyModel`、`KinematicTree`、`HeightFieldGrid`)在 `SimModelCompiler` 编译期直接按目标 `device` 构造张量。 + +### 2.3 每世界接触预算 + +任务通过 `SimCfg.max_contacts` 与 `SimCfg.max_contact_constraints` 配置 CUDA 接触缓冲容量。三维摩擦接触每个接触点会展开为 3–4 条单边约束行,因此内置任务按接触复杂度分类预留余量:四足、G1 WBT、平衡球和轻量抓取/插销任务采用 `128 / 384`,台阶四足、常规平地人形行走、柜体抽屉和灵巧手操作任务采用 `256 / 768`,G1 平地/起伏地形行走与常规起伏地形人形任务采用 `512 / 1536`,高密度网格自碰撞人形(Dex-EVT / K1 平地与 WBT)采用 `1024 / 4096`、起伏地形采用 `1536 / 6144`。未指定的配置使用 SDK 默认值。MotrixSim GPU 1.0.0 通过 `SceneModel.from_cmodel` 提供这两项公开设置,凸包候选对容量由 SDK 管理。 + +定标时用默认环境批量分别检查随机探索、典型跌倒和稳定策略轨迹中的逐世界引擎错误,以及峰值显存。接触预算应为瞬时接触峰值留余量,避免溢出触发异常复位并改变训练样本分布。训练吞吐按稳定训练窗口内实际采集的环境步数除以窗口墙钟时间统计。 + +--- + +## 3. RL 训练控制面与异构/同构拓扑对齐 + +### 3.1 无同步阻塞的控制步与指标归约 + +- 控制步热路径不得对环境指标(`state.metrics`、`state.reward_terms`)逐项调用 `.item()` 或 `.cpu()`。 +- CUDA 仿真下,每步指标保留为设备张量或在设备侧窗口累加器中更新,SKRL Torch 和 FastSAC 在日志窗口结束时批量归约。SKRL Torch 也在需要按回报保存 checkpoint 时读取窗口统计。 +- SKRL Torch、SKRL JAX(经 DLPack 零拷贝桥接观测、动作与奖励分解项)、RSLRL 与同步 FastSAC 在用户指定索引卡 `sim_device=cuda:k` 且未显式指定算法侧 `device` 时,默认将训练设备共置到 `cuda:k`。 + +### 3.2 异步 FastSAC 拓扑与进程隔离 + +- **父进程零 CUDA 上下文不变量**:异步训练父进程在 `mp.get_context("spawn")` 前仅在 CPU 上探测环境维度并分配主机共享内存游标;所有 CUDA 上下文、Warp 流、`GpuIpcTransitionRing` 槽位与 `FinalObsStorage` 设备缓冲均在子进程完成 CPU/NUMA 亲和性绑定后分配并通过 `StartupHandshake` 交接。[FastSAC 异步训练设计](./fastsac-async-heterogeneous-trainer.md) +- **统一设备拓扑求解**:`resolve_async_trainer_topology` 同时接收 `learner_devices`、`collector_inference_device` 与 `sim_device`,一次性确定每个 Collector 的 `(sim_device, infer_device, owner_learner, use_cuda_ipc)`: + +| 仿真设备请求 | 拓扑放置与传输行为 | +| :--- | :--- | +| `"cpu"` | 沿用 NUMA 本地 CPU 亲和性绑定;推理按 `collector_inference_device` 执行,经主机环或同卡 IPC 环送往所属 Learner。 | +| `"cuda"`(未指定卡号) | 每个 Collector 的仿真分片绑定到所属 Learner 所在 GPU;若推理也在该卡则全程设备内零主机中转(CUDA IPC Ring)。 | +| `"cuda:k"`(显式指定卡号) | 所有 Collector 仿真分片固定到 `cuda:k`;单 Learner 未显式绑卡时自动共置到 `cuda:k`,跨卡或主机环模式下 Collector 内部缓冲仍驻留 `cuda:k`,仅在跨设备边界做批量传输。仿真、推理和 Learner 同卡时使用 IPC,否则使用主机环。 | + +### 3.3 运行记录、续训与回放 + +- `metadata.json` 记录实际解析后的 `sim` 与 `sim_device`(异步多卡同时记录 `collector_sim_devices`)。 +- `mxlab play` 与 `mxlab train resume=...` 在命令行未显式传入 `sim` / `sim_device` 时,均优先继承原运行记录中的 `sim` 与 `sim_device`;旧运行记录缺失该字段时回退环境默认值。 diff --git a/wiki/plan/index.md b/wiki/plan/index.md index 4eb364f13..686398f98 100644 --- a/wiki/plan/index.md +++ b/wiki/plan/index.md @@ -13,5 +13,6 @@ ## 文档列表 +- [MotrixSim CUDA 实施与验收](./motrixsim-gpu.md) - [fastsac-async-multi-learner.md](fastsac-async-multi-learner.md) — FastSAC 单机多卡(多 learner × DDP)实施计划 - [motion-multi-clip-infra.md](motion-multi-clip-infra.md) — 多 motion clip 训练基础设施(MotionLibrary + WbtMotionCommand 原地泛化)分阶段实施计划 diff --git a/wiki/plan/motrixsim-gpu.md b/wiki/plan/motrixsim-gpu.md new file mode 100644 index 000000000..9e2167bf9 --- /dev/null +++ b/wiki/plan/motrixsim-gpu.md @@ -0,0 +1,32 @@ +# MotrixSim GPU 实施与验收 + +以 `e98888a5df951fd3c67da6cbcdfb7fc2008801e8` 为实现起点和 CPU 性能对照。本机结果记录于能力调查。设备语义和训练范围见[设计](../design/motrixsim-gpu.md),SDK 小场景与对照方法见[能力调查](../research/motrixsim-gpu-backend-review.md)。 + +## 实施顺序 + +1. **建立 CPU 对照**。从环境 registry 枚举内置 Direct 和 Manager 任务,记录任务名、配置、seed、环境数与输入。先在独立的 CPU 安装中运行构造、初始化、step 和 reset,保存可复现命令与结果。 +2. **接通首个 CUDA 场景**。验证可选依赖能单独安装,使仿真设备选择从环境入口到达 MotrixSim 插件。用无接触任务走通批量读写、物理步和局部 reset,再用接触任务与传感器检查 SDK 能力。 +3. **覆盖两类环境**。按任务实际使用的查询、写入和随机化项扩展支持。检查构造期常量、随机采样、动作和观测的设备位置,复用现有 CPU 生命周期验证。先用现有测试或一次性脚本验收;实现与提交拆分确定后,再为长期行为契约补测试。 +4. **接通训练与回放**。验证单进程 provider 后再接入异步 FastSAC 分片。将实际仿真设备写入运行记录,验证回放默认选择与显式覆盖。接口确定后同步更新中英文安装、训练和回放指南。 +5. **执行任务与性能矩阵**。CPU 和 NVIDIA CUDA 使用独立安装环境,在同一候选提交运行。对每个任务记录通过、失败或受限及具体原因;缺少硬件的跳过项保留为待验收。 + +## 验收矩阵 + +| 项目 | 执行与判定 | +| --- | --- | +| 安装与设备 | 仅装 CPU 依赖时完成 CPU 矩阵。另在 NVIDIA 主机安装可选依赖并运行真实仿真。分别验证显式请求缺依赖、不可用卡号和缺少场景能力时的诊断。 | +| 任务与回合 | 所有内置任务在 CPU 和 CUDA 上完成构造、初始化、step 和局部 reset。核对终止、截断及自动 reset 前的终态观测。代表性短训覆盖无接触、持续接触、随机化与传感器任务。 | +| 局部 reset | 在多行接触场景复位部分行,对照目标行与保留行的物理状态和回合计数。分别检查复位后、下一物理步和下一次传感器采样的可观察结果。 | +| 训练与回放 | 用原有配方运行 SKRL、RSLRL 和 FastSAC 的适用组合;核对 learner 更新、记录的仿真设备、默认回放和显式 CPU 覆盖。异步 FastSAC 在 CPU 多 NUMA 和 CUDA 多卡上另验分片归属、实际推进与样本摄入。 | +| CPU 扩展 | 在同一主机用相同任务与配方对照基线和候选提交。分别增加物理核与 NUMA 节点数,比对吞吐、近线性区间及饱和点。 | +| CUDA 扩展 | 先增加单卡环境数找出饱和区间,再增加 GPU 数。检查每卡持续推进独立分片,分别报告独立仿真、端到端训练吞吐与主机传输开销。 | + +多资源对照同时测强扩展(总环境数固定)和弱扩展(每单位资源的环境数固定)。扩展效率取相对最小布局的吞吐倍数除以资源倍数。记录基线和候选 SHA、硬件、SDK 与驱动、资源绑定、环境数、预热、计时窗口和实际命令;CUDA 计时窗口须覆盖设备完成工作所用的时间。 + +## TODO + +- [x] 记录 CPU 基线与候选的 56 项生命周期检查。 +- [x] 验证单卡 CUDA 仿真、局部接触复位、三类 Torch provider 短训与回放。 +- [x] 记录逐任务通过和受限项,保留原配方的摩擦与传感器语义。 +- [ ] 完成四卡分片、跨 NUMA、强弱扩展及传输开销验收。 +- [ ] 补齐受限的查询和参数覆盖后重新验证对应任务。 diff --git a/wiki/research/index.md b/wiki/research/index.md index 06f2ce276..747eeed69 100644 --- a/wiki/research/index.md +++ b/wiki/research/index.md @@ -6,6 +6,7 @@ ## 文档 +- [MotrixSim CUDA 能力调查与实测](./motrixsim-gpu-backend-review.md) - [SAC 与 FastSAC 算法原理入门](./sac-and-fastsac-primer.md):面向初学者解释 SAC 的 soft return、critic target、actor loss、温度系数,以及当前 FastSAC 实现中的代码对应关系。 - [NumbaWbtTask.update_state 远端 96 核扩展性研究](./numba-wbt-remote-96c-scaling.md):NumbaWbtTask 远端 EPYC 96 核瓶颈分析、融合 kernel 优化、线程调优与阶段性端到端基准。 - [FastSAC GPU 利用率分析与优化研究](./fastsac-gpu-analysis.md):异步训练 GPU 不满问题的分层评测方法(面板统计/microbenchmark/CUDA Event/双进程 trace/真实训练 A/B)、idle 根因定位、compile 粒度与 CUDA Graph 实验结论,以及评测 KPI 选择教训。 diff --git a/wiki/research/motrixsim-gpu-backend-review.md b/wiki/research/motrixsim-gpu-backend-review.md new file mode 100644 index 000000000..dfa47a02a --- /dev/null +++ b/wiki/research/motrixsim-gpu-backend-review.md @@ -0,0 +1,80 @@ +# MotrixSim GPU 能力调查 + +## 基线与调查入口 + +从 `e98888a5` 开始,先确定现有 CPU 契约,再用小场景验证 GPU SDK 能否表达相同操作。下表列出基线中可直接查阅的入口,以及需要从实验取得的证据。 + +| 入口 | 已有依据 | 需要回答的问题 | +| --- | --- | --- | +| [环境构造](../../motrix_env_core/src/motrix_env_core/registry.py) | `registry.make` 接收 `sim`、环境数和运行模式,签名中没有独立的仿真设备参数。 | Direct 和 Manager 分别在哪里分配动作、索引、随机数和持久状态?用户的设备选择如何到达这些分配点? | +| [后端契约](../../motrix_env_core/src/motrix_env_core/sim/backend.py) | 查询按声明编译;`step` 可将逐行状态写入调用方提供的张量。 | SDK 能提供哪些状态或错误信息?写入后何时可读,批次内单行异常如何报告? | +| [CPU 查询](../../motrix_env_motrixsim/src/motrix_env_motrixsim/sim_data.py) 与 [CPU 写入](../../motrix_env_motrixsim/src/motrix_env_motrixsim/write_compiler.py) | 可从现有实现核对通道布局、读数与参数写入语义。 | GPU 侧的坐标系、单位、分量顺序,以及局部写入后的生效时刻是否一致? | +| [插件依赖](../../motrix_env_motrixsim/pyproject.toml) | 插件依赖精确锁定的 `motrixsim-core===1.0.0`。 | 以 GPU SDK 1.0.0 为首个调查对象,核实可安装的平台、依赖组合和驱动要求;分别记录解析、安装与真实设备运行结果。 | +| [FastSAC 拓扑](../../motrix_rl/src/motrix_rl/topology.py) | 可从现有拓扑追踪 collector 与 learner 的归属。 | 分片在哪张卡推进?推理、样本交接与终态观测分别在哪个边界跨设备? | + +## 最小实验 + +1. **读写与流顺序**。在小场景中给两行写入可区分的关节状态和控制量,分开记录写后、单步后和多子步后的读数。用相同初态和输入对照 CPU,并检查 Torch 消费者在正常调用顺序下可见最新值。 +2. **接触与局部 reset**。让批次中的两行都进入持续接触,只复位其中一行。将目标行与相同初态的新环境对照,将其余行与未复位的对照批次比较。分别观察复位当下及下一步的位姿、速度和接触响应,以识别残留的求解器状态。 +3. **随机化与传感器**。用不同环境行验证摩擦等参数写入的作用范围。对 Raycast Camera 设置可区分的几何体,分别检查过滤、采样周期与复位后首次更新。记录具体缺失的能力和受影响的任务。 +4. **训练数据传输**。分别采集 CPU 仿真配 GPU 推理、同卡 CUDA 仿真与推理、显式跨卡放置的运行轨迹。区分普通控制步与结束回合的控制步,标出动作、观测、transition 和终态观测的传输方向及同步点。拷贝次数与耗时从实测轨迹取得。 + +记录 SDK 与驱动版本、场景、输入、对照值、误差容限及其依据。单步可对拍的字段与长时间接触轨迹分别评价。将确认过的能力和限制带入[设计](../design/motrixsim-gpu.md),再按[实施计划](../plan/motrixsim-gpu.md)扩展到任务和训练矩阵。 + +## 本机实测(2026-11-25) + +CPU 基线为 `e98888a5`。本机使用 i5-14600KF、单个 NUMA 节点和 RTX 5060 Ti,Python 3.10、Torch 2.7.0+cu128、MotrixSim Core/GPU 1.0.0。CPU 环境仅安装 Core。两端分别用独立进程构造每个注册任务,seed 183,2 行环境,初始化后执行零动作、单独复位第 1 行、再次运行零动作。CPU 基线和候选各通过全部 56 项。 + +| RTX 5060 Ti 阶段性验证结果 | 数量 | 注册任务 | +| --- | ---: | --- | +| 通过 | 42 | `acrobot`、`anymal_c_navigation_flat`、`anymalc-walk-flat`、`anymalc-walk-rough`、`bounce_ball`、`cartpole`、`dex-evt-walk-flat`、`dex-evt-walk-rough`、`dm-cheetah`、`dm-humanoid-run`、`dm-humanoid-stand`、`dm-humanoid-walk`、`dm-lqr-2-1`、`dm-lqr-6-2`、`dm-quadruped-escape`、`dm-quadruped-fetch`、`dm-quadruped-run`、`dm-quadruped-walk`、`dm-reacher`、`dm-runner`、`dm-stander`、`dm-walker`、`franka-lift-cube`、`franka-open-cabinet`、`g1-walk-rough`、`go1-walk-flat`、`go1-walk-rough`、`go2-walk-flat`、`go2-walk-rough`、`k1-walk-flat`、`k1-walk-rough`、`microduck-walk-flat`、`microduck-walk-rough`、`peg-insert`、`pendulum`、`point_mass`、`rm65-open-cabinet`、`rm65_insert_peg`、`shadow-hand-repose`、`stewart`、`stewart-disturb-xy`、`stewart-static` | +| 通过(后端适配 link 净接触力) | 6 | `dex-evt-wbt-dance`、`g1-29dof-wbt-largebox`、`g1-wbt-backflip`、`g1-wbt-dance`、`k1-wbt-freekick`、`microduck-ball-balance` | +| 初测缺少 touch 读数(后续已加入适配) | 6 | `dm-finger-spin`、`dm-finger-turn-easy`、`dm-finger-turn-hard`、`dm-hopper-hop`、`dm-hopper-stand`、`dm-manipulator-bring-ball` | +| 只支持滑动摩擦覆盖 | 1 | `g1-walk-flat` | +| 初测缺少接触传感器请求的力报告 | 1 | `go1-stairs-terrain-walk` | + +接触力适配器按物理步长将每个接触点的约束冲量换成力,输出世界坐标系下的合力和绕 link 质心的合力矩。1 kg 球体静止承重时,两端均测得 9.81 N。偏心球体在横向重力作用下,两端均测得横向力 −1.00 N、竖向力 9.81 N 和绕 y 轴力矩 −0.831 N·m。仅复位一行后,该行读数清零,保留行读数保持不变。原生 GPU 查询可用后,替换插件读取实现即可。 + +球体在重力下接触平面 100 个物理步后,只对中间一行设置位置和速度。以未复位的独立批次对照其余两行,以全新批次对照中间行。复位后立即采样,再依次推进 1、10、100 步。CPU 和 CUDA 各自的位置、速度、几何体接触状态都在绝对和相对误差 1e-5 内通过。GPU SDK 的高层碰撞查询在该场景一直返回零,按 collider pair 读取碰撞点后可检测到承重接触。 + +Cartpole 实测 SKRL PPO 和 RSLRL PPO 短训。Peg-insert 的同步 FastSAC checkpoint 中 critic、actor、温度优化器分别更新 6、2、6 次。异步 FastSAC 的两个 collector 在同一张 GPU 采样,learner 收到样本并更新。Cartpole checkpoint 分别使用记录的 CUDA 设备和显式 CPU 覆盖完成短视频回放。 + +单卡 Cartpole 的环境步吞吐在 64、256、1024、4096 行时分别约为 9.74 万、23.71 万、98.10 万、396.27 万步/秒。主机绑定 CPU 0、2、4、6,预热 50 个控制步,计时 500 步,窗口两端同步 GPU。该窗口不含 learner,单次计时,且在本机回归测试期间执行。CPU 基线在 1024 行时,绑定 1、2、4 个物理核分别为 31.22 万、58.37 万、101.73 万步/秒。 + +相同 CPU 绑定和环境数下,候选的 1024 行吞吐分别为 27.92 万、44.67 万、92.07 万步/秒。单次结果低于基线约 11%、23%、10%,尚需在隔离负载下重复计时。Raycast Camera 的 4 × 3 小场景在 CUDA 创建并推进后,GPU SDK 以名称读取原始通道时报错 `sensor 'camera' not found`。本版本将相机查询标为受限。 + +### 查询发布与流交接 + +CPU 原生批量查询把各字段发布到共享的 host arena。CPU Torch 直接读取 arena 的视图。Cartpole 接 CUDA policy 输入的单独测量中,8 次整批 policy observation 上传产生 8 次 H2D,字段数不参与这次传输。 + +CUDA 仿真在同一条非默认流上执行一个控制步。Warp 与 Torch 在控制步边界建立调用流依赖,内部查询和物理步复用该流。固定 DOF 与控制量的查询绑定设备视图,编译快照发布后捕获 CUDA Graph。含 SDK getter 或接触 kernel 的查询先获取当前设备数据,再执行编译后的投影。局部刷新只更新所选行。物理步使用 SDK 自带的 Graph。[MotrixSim 性能优化](https://motrixsim.readthedocs.io/zh-cn/latest/user_guide/gpu_version/performance_tuning.html) + +RTX 5060 Ti、1024 行 Cartpole、CPU 绑定 0/2/4/6、预热 50 个控制步后计时 500 步。各阶段单次测量,计时窗口两端同步,吞吐按环境行计算。 + +| 实现 | 万环境步/秒 | 毫秒/控制步 | +| --- | ---: | ---: | +| 修改前工作树 | 86.7 | 1.18 | +| 仅合并流交接 | 98.0 | 1.05 | +| 流交接与编译查询 | 90.0 | 1.14 | +| 固定地址查询图重放 | 99.0 | 1.03 | + +CUPTI 13.0 驱动 API 计数显示,8 个普通 CUDA 控制步共提交 24 次图启动和 16 次跨流事件等待,记录到 16 次 D2H、32 次 D2D 和 0 次 H2D。回合调度仍在主机判断截断和结束状态。使用已有编译缓存时,独立实例从构造到完成前 10 个控制步为 3.95 秒。该时间包含 SDK 初始化、编译查询、图捕获与步进。 + +分段采样中,Cartpole 单次物理调用提交 2 次图启动,单次全批查询提交 1 次。Microduck 的 Manager 任务完成 500 个控制步与单行强制截断,保存的终态观测在下一步保持稳定。Inductor 对含 CPU 输入或动态命令更新的子图报告跳过捕获,因此 Manager 的图重放覆盖范围随 term 调度而变。 + +### Manager 的 Warp 交接与 term 图重放 + +以同机 `microduck-walk-flat` 对照上一轮查询图实现。环境数 64、seed 183、零动作、CPU 绑定 0/2/4/6。独立进程预热 15 个控制步,测量 250 步,窗口两端同步;另在预热后的 8 步上用 CUPTI 13 计数。各阶段各运行一次。 + +| 指标 | 上一轮实现 | 本轮实现 | +| --- | ---: | ---: | +| 环境步/秒 | 22,479 | 24,472 | +| 流同步调用 | 56 | 40 | +| D2H / H2D | 48 / 8 | 32 / 8 | +| 创建 / 销毁 CUDA 事件 | 8 / 8 | 0 / 0 | +| 跨流事件等待 | 16 | 16 | +| 图启动 / 普通 kernel 启动 | 156 / 1,116 | 180 / 936 | + +Warp 调用流交接复用预分配事件。Manager 通过 term 声明中的持久张量标记静态地址,允许 Inductor 重放原地更新命令状态的子图。普通 CUDA 步先合并检查回合结束与 sim-only reset 请求,有请求时再选择行并保存终态观测。位置与四元数查询从同一份 SDK 世界坐标 link pose 表投影,按声明保留 link 顺序和重复项。 + +与 SDK 逐 link 读取对照,验证了全批与非连续行查询、保留行快照和四元数排列。Microduck 通过单行强制截断、终态观测生命周期及 sim-only reset 的回合计数检查。Inductor 仍报告部分含 CPU 标量输入的子图跳过捕获。