From 3c8340f83eecda0da75f0972a66d48ee7f32561a Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Fri, 13 Nov 2026 14:45:14 -0800 Subject: [PATCH 01/31] Reset the actuator networks by mask in Warp kernels and keep the MLP history at one address --- ...chuanh-actuator-net-mask-reset.changed.rst | 8 + ...jichuanh-actuator-net-mask-reset.fixed.rst | 2 + .../isaaclab/actuators/actuator_net.py | 51 +++++- .../test/actuators/test_actuator_net.py | 156 ++++++++++++++++++ 4 files changed, 209 insertions(+), 8 deletions(-) create mode 100644 source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst create mode 100644 source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.fixed.rst create mode 100644 source/isaaclab/test/actuators/test_actuator_net.py diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst new file mode 100644 index 000000000000..4d42c16f1362 --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -0,0 +1,8 @@ +* Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` to clear + the state of the environments a boolean Warp mask selects with a Warp kernel, so a reset recorded in a CUDA graph + clears it on every replay. :class:`~isaaclab.actuators.ActuatorNetMLP` updates its history buffers in place. +* Changed the ray-caster drift resampling on reset to draw from per-environment Warp random states, so a reset + recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded + once from the environment seed when the sensor initializes, and drift no longer draws from Torch's generator: a + later :func:`~isaaclab.utils.seed.configure_seed` does not restart the drift sequence. The drift ranges are + unchanged; the drawn values differ. diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.fixed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.fixed.rst new file mode 100644 index 000000000000..7cba789b5c1e --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.fixed.rst @@ -0,0 +1,2 @@ +* Fixed :meth:`~isaaclab.actuators.ActuatorCollection.reset` of a CUDA collection failing for an ``env_mask`` on the + host; the mask is copied to the collection's device once. diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 70f4120c8eba..c114685c8437 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -23,6 +23,7 @@ from ..utils import index_fill_ from ..utils.assets import read_file from ..utils.types import ArticulationActions +from ..utils.warp.memory import make_masked_fill from .actuator_pd import DCMotor if TYPE_CHECKING: @@ -70,11 +71,25 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): """ def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: - selection = env_ids if env_mask is None else wp.to_torch(env_mask) + if env_mask is not None: + if env_mask.device != wp.get_device(self._device): + # a mask from another device (e.g. the host) is copied once; a mask on this device is used as given + env_mask = env_mask.to(self._device) + # a mask resets with a Warp launch, which a CUDA graph recording of the reset holds + for state in (self.sea_hidden_state_per_env, self.sea_cell_state_per_env): + for layer in state: + values = wp.from_torch(layer.view(self._num_envs, -1)) + wp.launch( + make_masked_fill(wp.float32, 2), + dim=values.shape, + inputs=[0.0, env_mask, None, values], + device=self._device, + ) + return # reset the hidden and cell states for the specified environments with torch.no_grad(): - index_fill_(self.sea_hidden_state_per_env, selection, 0.0, dim=1) - index_fill_(self.sea_cell_state_per_env, selection, 0.0, dim=1) + index_fill_(self.sea_hidden_state_per_env, env_ids, 0.0, dim=1) + index_fill_(self.sea_cell_state_per_env, env_ids, 0.0, dim=1) def compute( self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor @@ -135,26 +150,46 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): self._num_envs, history_length, self.num_joints, device=self._device ) self._joint_vel_history = torch.zeros(self._num_envs, history_length, self.num_joints, device=self._device) + # each history shifts through a scratch buffer and is copied back, so it stays at one address + self._history_scratch = torch.zeros_like(self._joint_pos_error_history) + self._history_shift = torch.tensor( + [(i - 1) % history_length for i in range(history_length)], device=self._device + ) """ Operations. """ def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: - selection = env_ids if env_mask is None else wp.to_torch(env_mask) + if env_mask is not None: + if env_mask.device != wp.get_device(self._device): + # a mask from another device (e.g. the host) is copied once; a mask on this device is used as given + env_mask = env_mask.to(self._device) + # a mask resets with a Warp launch, which a CUDA graph recording of the reset holds + for history in (self._joint_pos_error_history, self._joint_vel_history): + values = wp.from_torch(history.view(self._num_envs, -1)) + wp.launch( + make_masked_fill(wp.float32, 2), + dim=values.shape, + inputs=[0.0, env_mask, None, values], + device=self._device, + ) + return # reset the history for the specified environments - index_fill_(self._joint_pos_error_history, selection, 0.0) - index_fill_(self._joint_vel_history, selection, 0.0) + index_fill_(self._joint_pos_error_history, env_ids, 0.0) + index_fill_(self._joint_vel_history, env_ids, 0.0) def compute( self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor ) -> ArticulationActions: # move history queue by 1 and update top of history # -- positions - self._joint_pos_error_history = self._joint_pos_error_history.roll(1, 1) + torch.index_select(self._joint_pos_error_history, 1, self._history_shift, out=self._history_scratch) + self._joint_pos_error_history.copy_(self._history_scratch) self._joint_pos_error_history[:, 0] = control_action.joint_positions - joint_pos # -- velocity - self._joint_vel_history = self._joint_vel_history.roll(1, 1) + torch.index_select(self._joint_vel_history, 1, self._history_shift, out=self._history_scratch) + self._joint_vel_history.copy_(self._history_scratch) self._joint_vel_history[:, 0] = joint_vel # compute network inputs # -- positions diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py new file mode 100644 index 000000000000..c3c498da9b6e --- /dev/null +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -0,0 +1,156 @@ +# Copyright (c) 2025-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Resets of the neural-network actuators by environment mask, recorded in a CUDA graph.""" + +import pytest +import torch +import warp as wp + +from isaaclab.actuators import ActuatorNetLSTMCfg, ActuatorNetMLPCfg +from isaaclab.test.utils import DeviceScope, test_devices +from isaaclab.utils import instantiate +from isaaclab.utils.types import ArticulationActions + +pytestmark = pytest.mark.kitless + + +class _ZeroTorqueLSTM(torch.nn.Module): + """LSTM-shaped network that requests no torque and keeps its state.""" + + def __init__(self): + super().__init__() + self.lstm = torch.nn.LSTM(input_size=2, hidden_size=4, num_layers=2, batch_first=True) + + def forward( + self, x: torch.Tensor, hc: tuple[torch.Tensor, torch.Tensor] + ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: + return torch.zeros(x.shape[0], 1, device=x.device), hc + + +class _ZeroTorqueMLP(torch.nn.Module): + """MLP-shaped network that requests no torque.""" + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return torch.zeros(x.shape[0], 1, device=x.device) + + +def _actuator(cfg_class, network: torch.nn.Module, tmp_path, device: str, **cfg): + network_file = tmp_path / "network.pt" + torch.jit.script(network).save(str(network_file)) + cfg = cfg_class( + joint_names_expr=["joint_.*"], + network_file=str(network_file), + saturation_effort=120.0, + actuator_effort_limit=80.0, + actuator_velocity_limit=7.5, + **cfg, + ) + return instantiate(cfg, joint_names=["joint_0", "joint_1"], joint_ids=[0, 1], num_envs=3, device=device) + + +def _record_masked_reset(actuator, mask: wp.array) -> wp.Graph: + """A CUDA graph of the actuator's reset of the masked environments; the graph reads ``mask`` when it replays.""" + with wp.ScopedCapture(mask.device) as capture: + actuator.reset(env_mask=mask) + return capture.graph + + +def _assert_masked_zero(state: torch.Tensor, env_dim: int): + """Environments 0 and 2 (masked) are zero and environment 1 keeps its value of one.""" + masked, kept = state.index_select(env_dim, torch.tensor([0, 2], device=state.device)), state.select(env_dim, 1) + assert torch.equal(masked, torch.zeros_like(masked)) + assert torch.equal(kept, torch.ones_like(kept)) + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) +def test_lstm_masked_reset_replays_from_a_cuda_graph(tmp_path, device): + actuator = _actuator(ActuatorNetLSTMCfg, _ZeroTorqueLSTM(), tmp_path, device) + mask = wp.array([True, False, True], dtype=wp.bool, device=device) + graph = _record_masked_reset(actuator, mask) + for _ in range(3): + actuator.sea_hidden_state.fill_(1.0) + actuator.sea_cell_state.fill_(1.0) + wp.capture_launch(graph) + _assert_masked_zero(actuator.sea_hidden_state_per_env, env_dim=1) + _assert_masked_zero(actuator.sea_cell_state_per_env, env_dim=1) + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) +def test_mlp_masked_reset_replays_from_a_cuda_graph_while_the_history_moves(tmp_path, device): + """The history shifts every compute; the recorded reset still clears the masked environments of it.""" + actuator = _actuator( + ActuatorNetMLPCfg, + _ZeroTorqueMLP(), + tmp_path, + device, + input_idx=[0, 1, 2], + pos_scale=1.0, + vel_scale=1.0, + torque_scale=1.0, + input_order="pos_vel", + ) + mask = wp.array([True, False, True], dtype=wp.bool, device=device) + graph = _record_masked_reset(actuator, mask) + zeros = torch.zeros(3, 2, device=device) + for _ in range(3): + actuator.compute(ArticulationActions(joint_positions=zeros), zeros, zeros) + actuator._joint_pos_error_history.fill_(1.0) + actuator._joint_vel_history.fill_(1.0) + wp.capture_launch(graph) + _assert_masked_zero(actuator._joint_pos_error_history, env_dim=0) + _assert_masked_zero(actuator._joint_vel_history, env_dim=0) + + +@pytest.mark.parametrize("device", test_devices()) +def test_mlp_history_keeps_its_address_and_window(tmp_path, device): + """Each compute shifts the history by one step in place: entry i holds the input from i computes ago.""" + actuator = _actuator( + ActuatorNetMLPCfg, + _ZeroTorqueMLP(), + tmp_path, + device, + input_idx=[0, 1, 2], + pos_scale=1.0, + vel_scale=1.0, + torque_scale=1.0, + input_order="pos_vel", + ) + addresses = (actuator._joint_pos_error_history.data_ptr(), actuator._joint_vel_history.data_ptr()) + zeros = torch.zeros(3, 2, device=device) + for step in range(5): + velocity = torch.full((3, 2), float(step), device=device) + actuator.compute(ArticulationActions(joint_positions=zeros), zeros, velocity) + assert (actuator._joint_pos_error_history.data_ptr(), actuator._joint_vel_history.data_ptr()) == addresses + expected = torch.tensor([4.0, 3.0, 2.0], device=device).view(1, 3, 1).expand(3, 3, 2) + torch.testing.assert_close(actuator._joint_vel_history, expected) + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) +def test_masked_reset_accepts_a_host_mask(tmp_path, device): + """A host mask resets the same environments of a CUDA network actuator as a mask on its device.""" + host_mask = wp.array([True, False, True], dtype=wp.bool, device="cpu") + lstm = _actuator(ActuatorNetLSTMCfg, _ZeroTorqueLSTM(), tmp_path, device) + lstm.sea_hidden_state.fill_(1.0) + lstm.sea_cell_state.fill_(1.0) + lstm.reset(env_mask=host_mask) + _assert_masked_zero(lstm.sea_hidden_state_per_env, env_dim=1) + _assert_masked_zero(lstm.sea_cell_state_per_env, env_dim=1) + mlp = _actuator( + ActuatorNetMLPCfg, + _ZeroTorqueMLP(), + tmp_path, + device, + input_idx=[0, 1, 2], + pos_scale=1.0, + vel_scale=1.0, + torque_scale=1.0, + input_order="pos_vel", + ) + mlp._joint_pos_error_history.fill_(1.0) + mlp._joint_vel_history.fill_(1.0) + mlp.reset(env_mask=host_mask) + _assert_masked_zero(mlp._joint_pos_error_history, env_dim=0) + _assert_masked_zero(mlp._joint_vel_history, env_dim=0) From 660eeb2199b74d3f8c74cd885969d94e677934f3 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Fri, 13 Nov 2026 14:46:02 -0800 Subject: [PATCH 02/31] Copy a host env_mask to the actuator collection's device before resetting --- .../isaaclab/actuators/actuator_collection.py | 6 ++++- .../actuators/test_actuator_collection.py | 22 ++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/source/isaaclab/isaaclab/actuators/actuator_collection.py b/source/isaaclab/isaaclab/actuators/actuator_collection.py index 6143d0c97422..461a67560e77 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_collection.py +++ b/source/isaaclab/isaaclab/actuators/actuator_collection.py @@ -188,8 +188,12 @@ def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array Args: env_ids: Environment indices to reset. Defaults to all environments. env_mask: Boolean mask of the environments to reset. Shape is (num_instances,). Takes precedence over - ``env_ids`` and does not synchronize the device. Defaults to None. + ``env_ids`` and does not synchronize the device. A mask on another device is copied to the + collection's device first. Defaults to None. """ + if env_mask is not None and env_mask.device != wp.get_device(self.device): + # a mask from another device (e.g. the host) is copied once; a mask on this device is used as given + env_mask = env_mask.to(self.device) group_env_ids = None if env_mask is not None else self._control._normalize_index_sequence(env_ids) for actuator in self._groups.values(): # Newton-executed groups are reset through the backend below. diff --git a/source/isaaclab/test/actuators/test_actuator_collection.py b/source/isaaclab/test/actuators/test_actuator_collection.py index 062514cb45f0..4682f26efe6f 100644 --- a/source/isaaclab/test/actuators/test_actuator_collection.py +++ b/source/isaaclab/test/actuators/test_actuator_collection.py @@ -29,7 +29,7 @@ ) from isaaclab.actuators.actuator_control import ArticulationActuatorControl from isaaclab.actuators.newton import read_group_parameter, write_group_parameter -from isaaclab.test.utils import test_devices +from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.warp import ProxyArray @@ -934,3 +934,23 @@ def test_masked_reset_leaves_unselected_envs_untouched(device): for delay_buffer in buffers: torch.testing.assert_close(delay_buffer.time_lags, torch.where(env_mask, 2, 1).to(torch.int)) torch.testing.assert_close(delay_buffer.num_pushes, torch.where(env_mask, 0, 3)) + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) +def test_masked_reset_accepts_a_host_mask(device): + """A host mask resets the same environments of a CUDA collection as a mask on its device.""" + control = FakeActuatorControl(num_envs=4, device=device) + cfg = DelayedPDActuatorCfg(joint_names_expr=[".*"], stiffness=1.0, damping=0.0, min_delay=2, max_delay=2) + collection = ActuatorCollection({"delayed": cfg}, control) + buffers = collection["delayed"]._delay_buffers + for delay_buffer in buffers: + delay_buffer.set_time_lag(1) + for _ in range(3): + collection.compute() + + collection.reset(env_mask=wp.array([False, True, False, True], dtype=wp.bool, device="cpu")) + + env_mask = torch.tensor([False, True, False, True], device=device) + for delay_buffer in buffers: + torch.testing.assert_close(delay_buffer.time_lags, torch.where(env_mask, 2, 1).to(torch.int)) + torch.testing.assert_close(delay_buffer.num_pushes, torch.where(env_mask, 0, 3)) From 1a3ef00daac107596034140a6a36633fec2a5f65 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Fri, 13 Nov 2026 14:50:52 -0800 Subject: [PATCH 03/31] Resample the ray-caster drift from per-environment Warp random states, share one initialize_rng_state, and test masked resets across assets --- ...jichuanh-actuator-net-mask-reset.added.rst | 2 + .../jichuanh-actuator-net-mask-reset.minor | 0 .../sensors/ray_caster/base_ray_caster.py | 54 +++--- .../isaaclab/sensors/ray_caster/kernels.py | 43 +++++ .../isaaclab/isaaclab/utils/warp/kernels.py | 20 +++ .../actuators/test_actuator_collection.py | 20 +++ .../test/scene/test_interactive_scene.py | 28 +++ .../test/sensors/test_ray_caster_kernels.py | 67 ++++++- .../jichuanh-actuator-net-mask-reset.skip | 0 .../test/assets/test_multirotor.py | 25 +++ .../jichuanh-actuator-net-mask-reset.skip | 0 .../envs/manager_based_env_warp.py | 12 +- .../utils/noise/noise_model.py | 4 +- .../jichuanh-actuator-net-mask-reset.skip | 0 .../assets/test_newton_actuators_newton.py | 168 ++++++++++++------ .../test/assets/test_rigid_object.py | 18 +- .../sensors/test_newton_raycast_sensor.py | 81 ++++++++- .../jichuanh-actuator-net-mask-reset.skip | 0 .../test/assets/test_articulation.py | 7 + .../jichuanh-actuator-net-mask-reset.skip | 0 .../assets/test_newton_actuators_physx.py | 16 +- .../test/assets/test_rigid_object.py | 47 +++-- .../test/assets/test_surface_gripper.py | 29 +++ .../jichuanh-actuator-net-mask-reset.skip | 0 .../core/reorient/reorient_warp_env.py | 13 +- 25 files changed, 525 insertions(+), 129 deletions(-) create mode 100644 source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst create mode 100644 source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.minor create mode 100644 source/isaaclab_contrib/changelog.d/jichuanh-actuator-net-mask-reset.skip create mode 100644 source/isaaclab_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip create mode 100644 source/isaaclab_newton/changelog.d/jichuanh-actuator-net-mask-reset.skip create mode 100644 source/isaaclab_ov/changelog.d/jichuanh-actuator-net-mask-reset.skip create mode 100644 source/isaaclab_physx/changelog.d/jichuanh-actuator-net-mask-reset.skip create mode 100644 source/isaaclab_tasks_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst new file mode 100644 index 000000000000..6dd11924d229 --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst @@ -0,0 +1,2 @@ +* Added :func:`~isaaclab.utils.warp.kernels.initialize_rng_state`, which seeds one Warp random number generator + state per environment for kernels that draw per-environment random numbers. diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.minor b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py index 01437661e289..9c6e552a1704 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py @@ -6,6 +6,7 @@ from __future__ import annotations import logging +import zlib from collections.abc import Sequence from typing import TYPE_CHECKING, Any, ClassVar @@ -21,7 +22,7 @@ from ...utils import math as math_utils from ...utils.mesh import convert_faces_to_triangles from ...utils.warp import ProxyArray, convert_to_warp_mesh -from ...utils.warp.kernels import raycast_mesh_masked_kernel +from ...utils.warp.kernels import initialize_rng_state, raycast_mesh_masked_kernel from ..sensor_base import SensorBase from . import kernels as ray_caster_kernels from .ray_caster_data import RayCasterData @@ -75,8 +76,6 @@ def __init__(self, cfg: RayCasterCfg): super().__init__(cfg) self._data = RayCasterData() self._drift_sampled = False - self._ray_cast_drift_range_list: tuple[tuple[float, float], ...] | None = None - self._ray_cast_drift_ranges: torch.Tensor | None = None def __str__(self) -> str: """Returns: A string containing information about the instance.""" @@ -123,26 +122,22 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None self._drift_sampled |= sample_drift or sample_ray_cast_drift if not self._drift_sampled: return - # resample drift for every sensor and keep it only where selected, so the selection stays on the device - selected = wp.to_torch(reset_mask)[:, None] - if sample_drift: - drift = torch.empty(self._view_count, 3, device=self.device).uniform_(*self.cfg.drift_range) - torch.where(selected, drift, self.drift.torch, out=self.drift.torch) - else: - self.drift.torch.masked_fill_(selected, 0.0) - # resample the ray cast drift - if sample_ray_cast_drift: - # Upload the ranges to the device only when the configuration changes. - if ray_cast_range_list != self._ray_cast_drift_range_list: - self._ray_cast_drift_range_list = ray_cast_range_list - self._ray_cast_drift_ranges = torch.tensor(ray_cast_range_list, device=self.device) - ranges = self._ray_cast_drift_ranges - ray_cast_drift = math_utils.sample_uniform( - ranges[:, 0], ranges[:, 1], (self._view_count, 3), device=self.device - ) - torch.where(selected, ray_cast_drift, self.ray_cast_drift.torch, out=self.ray_cast_drift.torch) - else: - self.ray_cast_drift.torch.masked_fill_(selected, 0.0) + # Resample in a kernel from per-environment random states with the ranges as launch arguments, so the + # reset neither synchronizes nor allocates and can be captured. A zero range draws zero, which clears + # drift that was sampled before it was disabled. + wp.launch( + ray_caster_kernels.resample_drift_masked_kernel, + dim=self._view_count, + inputs=[ + reset_mask, + wp.vec2f(*self.cfg.drift_range), + wp.vec3f(*(low for low, _ in ray_cast_range_list)), + wp.vec3f(*(high for _, high in ray_cast_range_list)), + self._drift_rng_state, + ], + outputs=[self.drift.warp, self.ray_cast_drift.warp], + device=self._device, + ) """ Implementation. @@ -246,9 +241,20 @@ def _initialize_rays_impl(self): self.ray_starts = ProxyArray(wp.from_torch(ray_starts_torch, dtype=wp.vec3f)) self.ray_directions = ProxyArray(wp.from_torch(ray_directions_torch, dtype=wp.vec3f)) - # Drift buffers are warp-first; reset uses explicit .torch views for sampling. + # Drift buffers are warp-first; reset resamples them in a Warp kernel. self.drift = ProxyArray(wp.zeros(self._view_count, dtype=wp.vec3f, device=self._device)) self.ray_cast_drift = ProxyArray(wp.zeros(self._view_count, dtype=wp.vec3f, device=self._device)) + # Per-environment random states for drift resampling, seeded once from the environment seed (which + # configure_seed stores as torch's initial seed; reading it draws nothing) mixed with the prim path, so + # each ray caster draws its own drift; resets only draw from them. + self._drift_rng_state = wp.empty(self._view_count, dtype=wp.uint32, device=self._device) + wp.launch( + initialize_rng_state, + dim=self._view_count, + inputs=[(torch.initial_seed() ^ zlib.crc32(self.cfg.prim_path.encode())) & 0x7FFFFFFF], + outputs=[self._drift_rng_state], + device=self._device, + ) # World-frame ray buffers self._ray_starts_w = wp.empty((self._view_count, self.num_rays), dtype=wp.vec3f, device=self._device) diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/kernels.py b/source/isaaclab/isaaclab/sensors/ray_caster/kernels.py index 866b9eabf0ef..85fab539d1ff 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/kernels.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/kernels.py @@ -347,3 +347,46 @@ def compute_distance_to_image_plane_to_image_masked_kernel( row = ray // width col = ray - row * width dst[env, row, col, 0] = value + + +@wp.kernel(enable_backward=False) +def resample_drift_masked_kernel( + # input + env_mask: wp.array(dtype=wp.bool), + drift_range: wp.vec2f, + ray_cast_drift_min: wp.vec3f, + ray_cast_drift_max: wp.vec3f, + # input/output + rng_state: wp.array(dtype=wp.uint32), + # output + drift: wp.array(dtype=wp.vec3f), + ray_cast_drift: wp.array(dtype=wp.vec3f), +): + """Resample the position drift and ray-cast drift of the masked environments. + + Launch with dim=(num_envs,). + + Args: + env_mask: Boolean mask for which environments to resample. Shape is (num_envs,). + drift_range: Uniform range of every position drift component [m]. + ray_cast_drift_min: Per-axis lower bound of the ray-cast drift [m]. + ray_cast_drift_max: Per-axis upper bound of the ray-cast drift [m]. + rng_state: Random number generator states, advanced for the resampled environments. Shape is (num_envs,). + drift: Position drift [m]. Shape is (num_envs,). + ray_cast_drift: Ray-cast drift [m]. Shape is (num_envs,). + """ + env = wp.tid() + if not env_mask[env]: + return + state = rng_state[env] + drift[env] = wp.vec3f( + wp.randf(state, drift_range[0], drift_range[1]), + wp.randf(state, drift_range[0], drift_range[1]), + wp.randf(state, drift_range[0], drift_range[1]), + ) + ray_cast_drift[env] = wp.vec3f( + wp.randf(state, ray_cast_drift_min[0], ray_cast_drift_max[0]), + wp.randf(state, ray_cast_drift_min[1], ray_cast_drift_max[1]), + wp.randf(state, ray_cast_drift_min[2], ray_cast_drift_max[2]), + ) + rng_state[env] = state diff --git a/source/isaaclab/isaaclab/utils/warp/kernels.py b/source/isaaclab/isaaclab/utils/warp/kernels.py index 5d4635e4e3a5..127b807dd3bd 100644 --- a/source/isaaclab/isaaclab/utils/warp/kernels.py +++ b/source/isaaclab/isaaclab/utils/warp/kernels.py @@ -485,5 +485,25 @@ def gather_subtract_2d_kernel(env_ids: "wp.array | torch.Tensor", item_ids: "wp. return _GATHER_SUBTRACT_2D_DISPATCHER.select(env_ids, item_ids) +@wp.kernel(enable_backward=False) +def initialize_rng_state( + # input + seed: wp.int32, + # output + state: wp.array(dtype=wp.uint32), +): + """Initialize one random number generator state per environment. + + Launch with ``dim=(num_envs,)``. Kernels that draw from ``state[i]`` should store the advanced state back, + so the next launch or graph replay draws new numbers. + + Args: + seed: Seed shared by all environments; each environment uses its index as the offset. + state: Random number generator states. Shape is (num_envs,). + """ + env_id = wp.tid() + state[env_id] = wp.rand_init(seed, env_id) + + # Include deprecated names in star imports without eagerly creating their kernels. __all__ = [name for name in globals() if not name.startswith("_")] + list(_DEPRECATED_WRENCH_NAMES) diff --git a/source/isaaclab/test/actuators/test_actuator_collection.py b/source/isaaclab/test/actuators/test_actuator_collection.py index 4682f26efe6f..9cb772556c0d 100644 --- a/source/isaaclab/test/actuators/test_actuator_collection.py +++ b/source/isaaclab/test/actuators/test_actuator_collection.py @@ -46,6 +46,13 @@ def compute(self, control_action, joint_pos, joint_vel): return super().compute(control_action, joint_pos, joint_vel) +class ResetRecordingActuator(ImplicitActuator): + """Custom actuator that records the selection supplied to :meth:`reset`.""" + + def reset(self, env_ids=None, env_mask=None): + self.reset_selection = (env_ids, env_mask) + + def _ideal_cfg(joints: list[str], *, stiffness: float, damping: float, effort_limit: float): return IdealPDActuatorCfg( joint_names_expr=joints, @@ -910,6 +917,19 @@ def test_write_command_mask_uses_full_sized_value(command_name): setter(value=value, env_mask=wp.array([1, 0], dtype=wp.int32, device="cpu"), joint_mask=joint_mask) +def test_index_and_mask_resets_pass_both_selections_to_models(): + cfg = _implicit_cfg() + cfg.class_type = ResetRecordingActuator + collection = ActuatorCollection({"all": cfg}, FakeActuatorControl()) + + collection.reset([1]) + assert collection["all"].reset_selection == ([1], None) + + collection.reset(env_mask=wp.array([False, True], dtype=wp.bool, device="cpu")) + env_ids, env_mask = collection["all"].reset_selection + assert env_ids is None and env_mask.numpy().tolist() == [False, True] + + @pytest.mark.parametrize("device", test_devices()) def test_masked_reset_leaves_unselected_envs_untouched(device): """A mask reset redraws the masked environments' delays without a device sync and keeps the others.""" diff --git a/source/isaaclab/test/scene/test_interactive_scene.py b/source/isaaclab/test/scene/test_interactive_scene.py index 40946843a879..b06b6dcd627a 100644 --- a/source/isaaclab/test/scene/test_interactive_scene.py +++ b/source/isaaclab/test/scene/test_interactive_scene.py @@ -12,6 +12,7 @@ import numpy as np import pytest import torch +import warp as wp from isaaclab_physx.sim.schemas import PhysxRigidBodyCfg import isaaclab.sim as sim_utils @@ -184,6 +185,33 @@ def test_relative_deformable_state(): torch.testing.assert_close(written_state["env_ids"], env_ids) +def test_masked_reset_reaches_every_entity(): + """Resets by ids and by mask pass both selections to every asset and sensor.""" + groups = ( + "_articulations", + "_cable_objects", + "_deformable_objects", + "_rigid_objects", + "_surface_grippers", + "_rigid_object_collections", + "_sensors", + ) + calls = {} + + def entity(group): + return SimpleNamespace(reset=lambda env_ids=None, env_mask=None: calls.update({group: (env_ids, env_mask)})) + + scene = SimpleNamespace(**{group: {"entity": entity(group)} for group in groups}) + env_mask = wp.array([True, False, True], dtype=wp.bool, device="cpu") + + InteractiveScene.reset(scene, env_mask=env_mask) + assert calls == dict.fromkeys(groups, (None, env_mask)) + + calls.clear() + InteractiveScene.reset(scene, env_ids=[1]) + assert calls == dict.fromkeys(groups, ([1], None)) + + def test_scene_publishes_plan_before_replicate(monkeypatch: pytest.MonkeyPatch): """A cfg-driven scene publishes the exact plan it forwards to replication.""" import isaaclab.cloner.replicate_session as replicate_session_module diff --git a/source/isaaclab/test/sensors/test_ray_caster_kernels.py b/source/isaaclab/test/sensors/test_ray_caster_kernels.py index 1504115f3ca9..83a452d5ff55 100644 --- a/source/isaaclab/test/sensors/test_ray_caster_kernels.py +++ b/source/isaaclab/test/sensors/test_ray_caster_kernels.py @@ -33,8 +33,13 @@ compute_distance_to_image_plane_to_image_masked_kernel, copy_float2d_to_image1_depth_clipped_masked_kernel, fill_ray_hits_distance_inf_kernel, + resample_drift_masked_kernel, +) +from isaaclab.utils.warp.kernels import ( + initialize_rng_state, + raycast_dynamic_meshes_kernel, + raycast_mesh_masked_kernel, ) -from isaaclab.utils.warp.kernels import raycast_dynamic_meshes_kernel, raycast_mesh_masked_kernel from isaaclab.utils.warp.ops import convert_to_warp_mesh # --------------------------------------------------------------------------- @@ -671,3 +676,63 @@ def test_with_pitch_roll(self): expected = [[0.0, 0.0, math.sin(yaw / 2), math.cos(yaw / 2)] for _, _, yaw in cases] np.testing.assert_allclose(_to_numpy(q_out), expected, atol=ATOL) + + +# --------------------------------------------------------------------------- +# resample_drift_masked_kernel +# --------------------------------------------------------------------------- + + +def _rng_state(num_envs: int = 4, seed: int = 7) -> wp.array: + """Per-environment random states seeded by :func:`initialize_rng_state`.""" + state = wp.empty(num_envs, dtype=wp.uint32, device=DEVICE) + wp.launch(initialize_rng_state, dim=num_envs, inputs=[seed], outputs=[state], device=DEVICE) + return state + + +def _resample_drift(env_mask, drift_range, ray_cast_min, ray_cast_max, rng_state): + """Resample drift buffers that start at -1 and return them as numpy arrays.""" + num_envs = env_mask.shape[0] + drift = wp.array(np.full((num_envs, 3), -1.0, dtype=np.float32), dtype=wp.vec3f, device=DEVICE) + ray_cast_drift = wp.array(np.full((num_envs, 3), -1.0, dtype=np.float32), dtype=wp.vec3f, device=DEVICE) + wp.launch( + resample_drift_masked_kernel, + dim=num_envs, + inputs=[env_mask, wp.vec2f(*drift_range), wp.vec3f(*ray_cast_min), wp.vec3f(*ray_cast_max), rng_state], + outputs=[drift, ray_cast_drift], + device=DEVICE, + ) + wp.synchronize_device(DEVICE) + return drift.numpy(), ray_cast_drift.numpy() + + +class TestResampleDriftMaskedKernel: + """Tests for :func:`resample_drift_masked_kernel`.""" + + def test_only_masked_envs_change(self): + env_mask = wp.array([True, False, True, False], dtype=wp.bool, device=DEVICE) + drift, ray_cast_drift = _resample_drift(env_mask, (0.1, 0.2), (0.1, 0.1, 0.1), (0.2, 0.2, 0.2), _rng_state()) + for values in (drift, ray_cast_drift): + np.testing.assert_array_equal(values[[1, 3]], -1.0) + assert (values[[0, 2]] >= 0.1).all() + + def test_draws_stay_in_their_ranges(self): + env_mask = wp.array([True] * 64, dtype=wp.bool, device=DEVICE) + drift, ray_cast_drift = _resample_drift( + env_mask, (-0.5, 0.25), (-0.1, 0.0, 0.3), (0.1, 0.2, 0.4), _rng_state(64) + ) + assert ((drift >= -0.5) & (drift <= 0.25)).all() + assert ((ray_cast_drift >= [-0.1, 0.0, 0.3]) & (ray_cast_drift <= [0.1, 0.2, 0.4])).all() + + def test_zero_range_draws_zero(self): + env_mask = wp.array([True] * 4, dtype=wp.bool, device=DEVICE) + drift, ray_cast_drift = _resample_drift(env_mask, (0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), _rng_state()) + np.testing.assert_array_equal(drift, 0.0) + np.testing.assert_array_equal(ray_cast_drift, 0.0) + + def test_state_advances_between_launches(self): + env_mask = wp.array([True] * 4, dtype=wp.bool, device=DEVICE) + rng_state = _rng_state() + first, _ = _resample_drift(env_mask, (-1.0, 1.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), rng_state) + second, _ = _resample_drift(env_mask, (-1.0, 1.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), rng_state) + assert not np.array_equal(first, second) diff --git a/source/isaaclab_contrib/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_contrib/changelog.d/jichuanh-actuator-net-mask-reset.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_contrib/test/assets/test_multirotor.py b/source/isaaclab_contrib/test/assets/test_multirotor.py index 5d195eeffe7a..2baf668c9379 100644 --- a/source/isaaclab_contrib/test/assets/test_multirotor.py +++ b/source/isaaclab_contrib/test/assets/test_multirotor.py @@ -18,6 +18,8 @@ import pytest import torch +import warp as wp +from isaaclab_physx.assets.articulation import Articulation from isaaclab_physx.physics import PhysxCfg import isaaclab.sim.utils.prims as prim_utils @@ -156,6 +158,29 @@ def test_set_thrust_target_env_slice_unit(): assert torch.allclose(m._data.thrust_target[3], original[3]) +@pytest.mark.parametrize("selection", ["ids", "mask"]) +def test_reset_restores_selected_thrust_targets_unit(selection, monkeypatch): + """Resets by ids and by mask reach the articulation and restore the selected thrust targets only.""" + parent_resets = [] + monkeypatch.setattr( + Articulation, "reset", lambda self, env_ids=None, env_mask=None: parent_resets.append((env_ids, env_mask)) + ) + m = Multirotor.__new__(Multirotor) + m._device = "cpu" + m._ALL_INDICES = wp.array([0, 1, 2, 3], dtype=wp.int32, device="cpu") + m._data = types.SimpleNamespace(thrust_target=torch.ones(4, 2), default_thruster_rps=torch.zeros(4, 2)) + env_mask = wp.array([True, False, True, False], dtype=wp.bool, device="cpu") + + if selection == "ids": + m.reset(env_ids=[0, 2]) + assert parent_resets == [([0, 2], None)] + else: + m.reset(env_mask=env_mask) + assert parent_resets == [(None, env_mask)] + expected = torch.tensor([[0.0, 0.0], [1.0, 1.0], [0.0, 0.0], [1.0, 1.0]]) + torch.testing.assert_close(m._data.thrust_target, expected) + + def generate_multirotor( multirotor_cfg: MultirotorCfg, num_multirotors: int, device: str ) -> tuple[Multirotor, torch.Tensor]: diff --git a/source/isaaclab_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py index 2fe63fdf9920..60af28f80b40 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py @@ -39,6 +39,7 @@ from isaaclab.utils import validate from isaaclab.utils.seed import configure_seed from isaaclab.utils.timer import Timer +from isaaclab.utils.warp.kernels import initialize_rng_state from isaaclab.utils.warp.memory import resolve_1d_mask from isaaclab_experimental.utils.manager_call_switch import ManagerCallMode, ManagerCallSwitch @@ -47,17 +48,6 @@ logger = logging.getLogger(__name__) -@wp.kernel -def initialize_rng_state( - # input - seed: wp.int32, - # output - state: wp.array(dtype=wp.uint32), -): - env_id = wp.tid() - state[env_id] = wp.rand_init(seed, wp.int32(env_id)) - - class ManagerBasedEnvWarp: """The base environment for the manager-based workflow (experimental fork). diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py index acba926ea488..ae08913730ef 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py @@ -12,8 +12,8 @@ Random noise kernels (gaussian, uniform) consume the shared per-env Warp RNG state (``rng_state_wp``) that is set on the config at manager prep time from -``env.rng_state_wp``. See :func:`initialize_rng_state` in -``isaaclab_experimental.envs.manager_based_env_warp`` for the initialization pattern. +``env.rng_state_wp``. See :func:`isaaclab.utils.warp.kernels.initialize_rng_state` for the initialization +pattern. """ from __future__ import annotations diff --git a/source/isaaclab_newton/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_newton/changelog.d/jichuanh-actuator-net-mask-reset.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_newton/test/assets/test_newton_actuators_newton.py b/source/isaaclab_newton/test/assets/test_newton_actuators_newton.py index 27a7b38e9546..75d871ab671a 100644 --- a/source/isaaclab_newton/test/assets/test_newton_actuators_newton.py +++ b/source/isaaclab_newton/test/assets/test_newton_actuators_newton.py @@ -383,32 +383,92 @@ def _run( return _Run(sim=sim, articulations=articulations, results=results) -def _record_lab_state_reset(run: _Run) -> dict[str, tuple[torch.Tensor, torch.Tensor]]: - """Reset one Lab-path environment of the delayed island and record each group's effort and PD demand. +_RESET_SELECTORS = ("env_ids", "env_mask") + + +def _reset_env_0(articulation: Articulation, selector: str) -> None: + """Reset environment 0 alone through the given selector.""" + if selector == "env_ids": + articulation.reset(env_ids=torch.tensor([0], device=articulation.device, dtype=torch.long)) + else: + env_mask = torch.arange(articulation.num_instances, device=articulation.device) == 0 + articulation.reset(env_mask=wp.from_torch(env_mask)) + + +def _warm_delayed_island(run: _Run) -> list: + """Step the delayed island until its delay buffers hold history and return its delayed actuators' state pairs. + + Only the reset articulation's own delayed actuators are returned. The adapter is model-wide, so the other + islands' actuators share its state buffers; their state is not part of this articulation's contract. + """ + articulation = run.articulations["delayed"] + for _ in range(3): + articulation.write_data_to_sim() + run.sim.step() + articulation.update(DT) + adapter = run.sim.backend_manager.backend.actuators + assert adapter is not None + own_actuators = [] + for group_name in articulation.actuators._native_group_names: + group_actuators = articulation.actuators[group_name] + own_actuators.extend(group_actuators if isinstance(group_actuators, tuple) else (group_actuators,)) + stateful_pairs = [ + (act, st) + for act, st in zip(adapter.actuators, adapter._states_a) + if any(act is own for own in own_actuators) and st is not None and st.delay_state is not None + ] + assert len(stateful_pairs) > 0, "expected at least one DelayedPD actuator with delay_state" + for act, state in stateful_pairs: + pushes_before = state.delay_state.num_pushes.numpy() + assert (pushes_before > 0).all(), "expected non-zero num_pushes for all DOFs after warmup" + return stateful_pairs + + +def _assert_delay_state_cleared_for_env_0_only(run: _Run, stateful_pairs: list) -> None: + """Assert ``num_pushes`` is zero for environment 0's DOFs and positive for every other environment's DOFs.""" + # Map each entry of ``act.indices`` to its env via the adapter's per-env DOF count. The adapter is + # model-wide (includes free-joint DOFs on floating-base articulations), so ``adapter.num_joints`` is the + # stride. + adapter = run.sim.backend_manager.backend.actuators + for act, state in stateful_pairs: + pushes_after = state.delay_state.num_pushes.numpy() + indices_np = act.indices.numpy() + for i, global_dof in enumerate(indices_np): + env = int(global_dof) // adapter.num_joints + if env == 0: + assert int(pushes_after[i]) == 0, f"DOF {i} (env {env}) should be reset to 0, got {pushes_after[i]}" + else: + assert int(pushes_after[i]) > 0, f"DOF {i} (env {env}) was NOT in the reset selection but is 0" + + +def _record_lab_state_reset(run: _Run) -> dict[str, dict[str, tuple[torch.Tensor, torch.Tensor]]]: + """Reset one Lab-path environment of the delayed island per selector and record each group's effort and PD demand. Reset environments must accept fresh commands while the remaining environments retain their delay history. """ articulation = run.articulations["delayed"] commands = articulation.actuators.target_command old_target = commands.position.torch.clone() - # Episode reset samples the configured lag; construction alone leaves actuator lag at zero. - articulation.reset() - commands.set_position_index(value=old_target) - articulation.write_data_to_sim() new_target = old_target + 0.02 - articulation.reset(env_ids=torch.tensor([0], device=articulation.device)) - commands.set_position_index(value=new_target) - articulation.write_data_to_sim() expected_target = old_target.clone() expected_target[0] = new_target[0] recorded = {} - for name, actuator in articulation.actuators.items(): - joints = actuator.joint_indices - demand = ( - actuator.stiffness * (expected_target[:, joints] - articulation.data.joint_pos.torch[:, joints]) - - actuator.damping * articulation.data.joint_vel.torch[:, joints] - ) - recorded[name] = (actuator.computed_effort.clone(), demand) + for selector in _RESET_SELECTORS: + # Episode reset samples the configured lag; construction alone leaves actuator lag at zero. + articulation.reset() + commands.set_position_index(value=old_target) + articulation.write_data_to_sim() + _reset_env_0(articulation, selector) + commands.set_position_index(value=new_target) + articulation.write_data_to_sim() + recorded[selector] = {} + for name, actuator in articulation.actuators.items(): + joints = actuator.joint_indices + demand = ( + actuator.stiffness * (expected_target[:, joints] - articulation.data.joint_pos.torch[:, joints]) + - actuator.damping * articulation.data.joint_vel.torch[:, joints] + ) + recorded[selector][name] = (actuator.computed_effort.clone(), demand) return recorded @@ -449,10 +509,33 @@ def decimated_runs(device: str) -> dict[str, dict]: @pytest.fixture(scope="module") -def newton_run(device: str, lab_run: dict, decimated_runs: dict) -> Iterator[_Run]: +def masked_replay_run(device: str) -> list[tuple[np.ndarray, np.ndarray]]: + """Record a masked reset of environment 0 in a CUDA graph and replay it after the delay buffers refill. + + The scene holds only the delayed island: the adapter resets every actuator of the model, and Newton's neural + actuator state reset cannot be recorded into a graph. Returns, per delayed actuator, its ``num_pushes`` after the + replay and the environment of each of its DOFs. + """ + sim_cfg = newton_sim_cfg(device, dt=DT, use_newton_actuators=True, solver_cfg=_solver_cfg()) + with build_simulation_context(sim_cfg=sim_cfg) as sim: + run = _run(sim, {"delayed": _islands()["delayed"]}, use_newton_actuators=True) + articulation = run.articulations["delayed"] + env_mask = wp.from_torch(torch.arange(articulation.num_instances, device=device) == 0) + # Allocating inside the capture raises while the memory pool is disabled. + with wp.ScopedMempool(device, False), wp.ScopedCapture(device) as capture: + articulation.reset(env_mask=env_mask) + # Repopulate the delay buffers, so the replay rather than the capture must clear environment 0. + stateful_pairs = _warm_delayed_island(run) + wp.capture_launch(capture.graph) + stride = run.sim.backend_manager.backend.actuators.num_joints + return [(state.delay_state.num_pushes.numpy(), act.indices.numpy() // stride) for act, state in stateful_pairs] + + +@pytest.fixture(scope="module") +def newton_run(device: str, lab_run: dict, decimated_runs: dict, masked_replay_run: list) -> Iterator[_Run]: """Roll out every island on the Newton actuator path and keep the scene alive. - Depends on the Lab-path and decimated runs so their scenes are built and closed first. + Depends on the Lab-path, decimated and masked-replay runs so their scenes are built and closed first. """ mlp_path = make_dummy_mlp_checkpoint() lstm_path = make_dummy_lstm_checkpoint() @@ -946,46 +1029,21 @@ def gains(name: str) -> torch.Tensor: def test_newton_state_reset_isolated_to_reset_env(newton_run: _Run) -> None: - """Newton: ``num_pushes`` zeroes for env 0's DOFs only after reset of [0]. + """Newton: ``num_pushes`` zeroes for env 0's DOFs only after a partial reset of env 0.""" + stateful_pairs = _warm_delayed_island(newton_run) + _reset_env_0(newton_run.articulations["delayed"], "env_ids") + _assert_delay_state_cleared_for_env_0_only(newton_run, stateful_pairs) - Only the reset articulation's own delayed actuators are checked. The adapter is model-wide, so the other - islands' actuators share its state buffers; their state is not part of this articulation's contract. - """ - articulation = newton_run.articulations["delayed"] - adapter = newton_run.sim.backend_manager.backend.actuators - assert adapter is not None - own_actuators = [] - for group_name in articulation.actuators._native_group_names: - group_actuators = articulation.actuators[group_name] - own_actuators.extend(group_actuators if isinstance(group_actuators, tuple) else (group_actuators,)) - stateful_pairs = [ - (act, st) - for act, st in zip(adapter.actuators, adapter._states_a) - if any(act is own for own in own_actuators) and st is not None and st.delay_state is not None - ] - assert len(stateful_pairs) > 0, "expected at least one DelayedPD actuator with delay_state" - - for act, state in stateful_pairs: - pushes_before = state.delay_state.num_pushes.numpy() - assert (pushes_before > 0).all(), "expected non-zero num_pushes for all DOFs after warmup" - - articulation.reset(env_ids=torch.tensor([0], device=articulation.device, dtype=torch.long)) - # Map each entry of ``act.indices`` to its env via the adapter's per-env DOF count. The adapter is - # model-wide (includes free-joint DOFs on floating-base articulations), so ``adapter.num_joints`` is the - # stride. - for act, state in stateful_pairs: - pushes_after = state.delay_state.num_pushes.numpy() - indices_np = act.indices.numpy() - for i, global_dof in enumerate(indices_np): - env = int(global_dof) // adapter.num_joints - if env == 0: - assert int(pushes_after[i]) == 0, f"DOF {i} (env {env}) should be reset to 0, got {pushes_after[i]}" - else: - assert int(pushes_after[i]) > 0, f"DOF {i} (env {env}) was NOT in reset env_ids but num_pushes is 0" +def test_newton_masked_reset_replays_from_cuda_graph_without_allocation(masked_replay_run: list) -> None: + """A masked reset records into a CUDA graph without allocating and, on replay, clears only the masked env.""" + for pushes, envs in masked_replay_run: + assert (pushes[envs == 0] == 0).all() + assert (pushes[envs != 0] > 0).all() -def test_lab_state_reset_isolated_to_reset_env(lab_run: dict) -> None: +@pytest.mark.parametrize("selector", _RESET_SELECTORS) +def test_lab_state_reset_isolated_to_reset_env(lab_run: dict, selector: str) -> None: """Reset environments accept fresh commands while the remaining environments retain their history.""" - for computed_effort, demand in lab_run["state_reset"].values(): + for computed_effort, demand in lab_run["state_reset"][selector].values(): torch.testing.assert_close(computed_effort, demand) diff --git a/source/isaaclab_newton/test/assets/test_rigid_object.py b/source/isaaclab_newton/test/assets/test_rigid_object.py index 7257c28f8a0f..d426343ec909 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object.py @@ -385,7 +385,8 @@ def test_external_force_on_single_body(scene: _Scene) -> None: """A permanent wrench reaches the solver in the local and the global frame, and a reset clears it. Cube 0 receives a force equal to its weight and hovers while cube 1 falls. Cube 0 then receives a force set - and added 1 m off its center along y and must turn about x while cube 1 keeps falling. + and added 1 m off its center along y and must turn about x while cube 1 keeps falling. A masked reset clears + the wrench of the selected environment only. """ cube = scene.cube composer = cube.permanent_wrench_composer @@ -414,6 +415,12 @@ def test_external_force_on_single_body(scene: _Scene) -> None: assert cube.data.root_ang_vel_b.torch[0, 0].abs() > 0.1 assert cube.data.root_pos_w.torch[1, 2] < 1.0 + ones = torch.ones_like(zeros) + composer.set_forces_and_torques_index(forces=ones, torques=ones) + cube.reset(env_mask=wp.from_torch(torch.arange(cube.num_instances, device=scene.device) == 0)) + assert torch.count_nonzero(composer.out_force_b.torch[0]) == 0 + assert torch.count_nonzero(composer.out_force_b.torch[1:]) == composer.out_force_b.torch[1:].numel() + @pytest.mark.isaacsim_ci def test_rigid_body_set_material_properties(scene: _Scene) -> None: @@ -904,7 +911,8 @@ def test_collection_external_force_on_single_body(scene: _Scene) -> None: """A permanent wrench reaches the solver in the local and the global frame, and a reset clears it. Every other cube receives a force equal to its weight and hovers while the rest fall. Those cubes then - receive a force set and added 1 m off their centers along y and must turn about x. + receive a force set and added 1 m off their centers along y and must turn about x. A masked reset clears the + wrenches of the selected environment only. """ collection = scene.collection composer = collection.permanent_wrench_composer @@ -933,6 +941,12 @@ def test_collection_external_force_on_single_body(scene: _Scene) -> None: assert torch.all(collection.data.body_com_ang_vel_b.torch[:, 0::2, 0] > 0.1) assert torch.all(height[:, 1::2] < 1.0) + ones = torch.ones_like(zeros) + composer.set_forces_and_torques_index(forces=ones, torques=ones) + collection.reset(env_mask=wp.from_torch(torch.arange(collection.num_instances, device=scene.device) == 0)) + assert torch.count_nonzero(composer.out_force_b.torch[0]) == 0 + assert torch.count_nonzero(composer.out_force_b.torch[1:]) == composer.out_force_b.torch[1:].numel() + @pytest.mark.isaacsim_ci def test_collection_gravity_vec_w_tracks_model_gravity(scene: _Scene) -> None: diff --git a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py index 0aba47cf0fd0..083bda829c19 100644 --- a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py @@ -39,7 +39,7 @@ from isaaclab.sensors.ray_caster.patterns import GridPatternCfg from isaaclab.sim import SimulationCfg from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils import configclass +from isaaclab.utils import configclass, replace SENSOR_HEIGHT = 2.0 RAY_OFFSET = 0.2 @@ -226,6 +226,73 @@ def test_legacy_multi_mesh_tracks_ad_hoc_regex_target(sim): torch.testing.assert_close(sensor.data.pos_w.torch, pose[:, :3]) +@pytest.mark.parametrize("sim", [pytest.param(False, id="eager")], indirect=True) +def test_partial_reset_resamples_drift_of_selected_envs_only(sim, monkeypatch): + """Slice, host-mask and replayed masked resets resample the drift of the selected environments only.""" + scene_cfg = RaycastTestSceneCfg(num_envs=3) + scene_cfg.raycast.drift_range = (0.01, 0.05) + scene_cfg.raycast.ray_cast_drift_range = {"z": (0.1, 0.2)} + scene = InteractiveScene(scene_cfg) + sim.reset() + sensor: NewtonRaycastSensor = scene["raycast"] + sensor.reset() + + drift = sensor.drift.torch.clone() + sensor.reset(env_ids=slice(2, None)) + torch.testing.assert_close(sensor.drift.torch[:2], drift[:2]) + assert not torch.allclose(sensor.drift.torch[2], drift[2]) + + # The masked reset records into a CUDA graph without allocating (the disabled memory pool makes an + # allocation raise), and every replay draws new drift for the masked environment only. + env_mask = wp.array([True, False, False], dtype=wp.bool, device=sensor.device) + with wp.ScopedMempool(sensor.device, False), wp.ScopedCapture(sensor.device) as capture: + sensor.reset(env_mask=env_mask) + for _ in range(2): + drift = sensor.drift.torch.clone() + ray_cast_drift = sensor.ray_cast_drift.torch.clone() + wp.capture_launch(capture.graph) + torch.testing.assert_close(sensor.drift.torch[1:], drift[1:]) + torch.testing.assert_close(sensor.ray_cast_drift.torch[1:], ray_cast_drift[1:]) + assert not torch.allclose(sensor.drift.torch[0], drift[0]) + assert not torch.allclose(sensor.ray_cast_drift.torch[0, 2], ray_cast_drift[0, 2]) + assert ((sensor.drift.torch >= 0.01) & (sensor.drift.torch <= 0.05)).all() + assert ((sensor.ray_cast_drift.torch[:, 2] >= 0.1) & (sensor.ray_cast_drift.torch[:, 2] <= 0.2)).all() + + # A host mask reaches the drift kernel on the sensor device. Strict launches reject a host array that + # GPUs with heterogeneous memory management would otherwise read silently. + monkeypatch.setattr(wp.config, "launch_array_access_mode", wp.config.LaunchArrayAccessMode.STRICT) + drift = sensor.drift.torch.clone() + sensor.reset(env_mask=wp.array([False, True, False], dtype=wp.bool, device="cpu")) + torch.testing.assert_close(sensor.drift.torch[[0, 2]], drift[[0, 2]]) + assert not torch.allclose(sensor.drift.torch[1], drift[1]) + + +@pytest.mark.parametrize("sim", [pytest.param(False, id="eager")], indirect=True) +def test_drift_is_seeded_once_from_the_environment_seed(sim): + """The drift states are seeded from the environment seed when the rays initialize; resets only draw from them. + + Neither initialization nor resets draw from torch's global generator, and new storage, as after a simulation + stop and play, starts the same drift sequence again. + """ + scene_cfg = RaycastTestSceneCfg(num_envs=2) + scene_cfg.raycast.drift_range = (0.01, 0.05) + scene = InteractiveScene(scene_cfg) + sim.reset() + sensor: NewtonRaycastSensor = scene["raycast"] + state = torch.get_rng_state() + + sensor._initialize_rays_impl() + sensor.reset() + first = sensor.drift.torch.clone() + sensor.reset() + assert not torch.allclose(sensor.drift.torch, first) + sensor._initialize_rays_impl() + sensor.reset() + torch.testing.assert_close(sensor.drift.torch, first) + assert ((first >= 0.01) & (first <= 0.05)).all() + assert torch.equal(torch.get_rng_state(), state) + + @configclass class MultiMeshTargetSceneCfg(RaycastTestSceneCfg): """Read the same box through a static target and a tracked target.""" @@ -396,3 +463,15 @@ def test_renderer_and_raycast_share_backend_with_independent_query_graphs(sim): assert camera._renderer.backend is raycast.backend is sim.backend_manager.backend assert (raycast._graph is not None) == cfg.raycast.use_cuda_graph assert (camera._render_data.graph is not None) == cfg.camera.renderer_cfg.use_cuda_graph + + +@pytest.mark.parametrize("sim", [pytest.param(False, id="eager")], indirect=True) +def test_ray_casters_draw_independent_drift(sim): + """Two ray casters with the same drift ranges draw different drift: each mixes its prim path into the seed.""" + scene_cfg = RaycastTestSceneCfg(num_envs=2) + scene_cfg.raycast.drift_range = (0.01, 0.05) + scene_cfg.raycast_box = replace(scene_cfg.raycast, prim_path="{ENV_REGEX_NS}/Box") + scene = InteractiveScene(scene_cfg) + sim.reset() + scene.reset() + assert not torch.allclose(scene["raycast"].drift.torch, scene["raycast_box"].drift.torch) diff --git a/source/isaaclab_ov/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_ov/changelog.d/jichuanh-actuator-net-mask-reset.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_ov/test/assets/test_articulation.py b/source/isaaclab_ov/test/assets/test_articulation.py index 1c18f8f81023..c1892fd109bb 100644 --- a/source/isaaclab_ov/test/assets/test_articulation.py +++ b/source/isaaclab_ov/test/assets/test_articulation.py @@ -1636,6 +1636,13 @@ def __getitem__(self, name): # The delay state is flattened environment-major over the group's joints. assert stateful_pairs[0].delay_state.num_pushes.numpy().tolist() == [0] * num_joints + [1] * num_joints + scene.step(articulation) + articulation.reset(env_mask=wp.array([False, True], dtype=wp.bool, device=device)) + stateful_pairs = [ + state for state in adapter._states_a if state is not None and getattr(state, "delay_state", None) is not None + ] + assert stateful_pairs[0].delay_state.num_pushes.numpy().tolist() == [1] * num_joints + [0] * num_joints + env = Env(articulation) asset_cfg = SceneEntityCfg("robot") event_params = { diff --git a/source/isaaclab_physx/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_physx/changelog.d/jichuanh-actuator-net-mask-reset.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_physx/test/assets/test_newton_actuators_physx.py b/source/isaaclab_physx/test/assets/test_newton_actuators_physx.py index 3e84d69abcec..066e1ffb6e5a 100644 --- a/source/isaaclab_physx/test/assets/test_newton_actuators_physx.py +++ b/source/isaaclab_physx/test/assets/test_newton_actuators_physx.py @@ -296,9 +296,16 @@ def test_network_actuators_drive_haa_joints(rollouts: _Rollouts, robot: str) -> assert not torch.allclose(trace["applied_effort"][0][:, haa_ids], trace["applied_effort"][-1][:, haa_ids]) -def test_reset_clears_actuator_state_of_selected_envs(rollouts: _Rollouts) -> None: - """Resetting environment 0 clears the delay history of its DoFs only.""" +@pytest.mark.parametrize("selector", ["env_ids", "env_mask"]) +def test_reset_clears_actuator_state_of_selected_envs(rollouts: _Rollouts, selector: str) -> None: + """Resetting environment 0 by indices or by mask clears the delay history of its DoFs only.""" articulation = rollouts.robots["delayed"] + # Refill the delay history that a previous reset cleared. + sim = SimulationContext.instance() + for _ in range(3): + articulation.write_data_to_sim() + sim.step() + articulation.update(DT) adapter = articulation.newton_actuator_adapter delay_states = [ (actuator, state.delay_state) @@ -308,7 +315,10 @@ def test_reset_clears_actuator_state_of_selected_envs(rollouts: _Rollouts) -> No assert delay_states assert all((delay_state.num_pushes.numpy() > 0).all() for _, delay_state in delay_states) - articulation.reset(env_ids=torch.tensor([0], device=articulation.device)) + if selector == "env_ids": + articulation.reset(env_ids=torch.tensor([0], device=articulation.device)) + else: + articulation.reset(env_mask=wp.from_torch(torch.arange(NUM_ENVS, device=articulation.device) == 0)) for actuator, delay_state in delay_states: env_of_dof = actuator.indices.numpy() // adapter.num_joints pushes = delay_state.num_pushes.numpy() diff --git a/source/isaaclab_physx/test/assets/test_rigid_object.py b/source/isaaclab_physx/test/assets/test_rigid_object.py index 764e54ff941d..95c0ae2d8f76 100644 --- a/source/isaaclab_physx/test/assets/test_rigid_object.py +++ b/source/isaaclab_physx/test/assets/test_rigid_object.py @@ -644,17 +644,23 @@ def test_rigid_object_wrench_delivery_and_reset(scene: _Scene) -> None: > 0.99 ) - # A partial reset clears only the selected environment; a full reset deactivates the composers. + # A partial reset by indices or by mask clears only the selected environment; a full reset deactivates the + # composers. composers = (cube_object.instantaneous_wrench_composer, cube_object.permanent_wrench_composer) ones = torch.ones((_NUM_ENVS, 1, 3), device=device) - cube_object.permanent_wrench_composer.set_forces_and_torques_index(forces=ones, torques=ones) - cube_object.instantaneous_wrench_composer.add_forces_and_torques_index(forces=ones, torques=ones) - cube_object.reset(env_ids=torch.tensor([0], device=device)) - for composer in composers: - assert composer.active - for buffer in (composer.out_force_b.torch, composer.out_torque_b.torch): - assert torch.count_nonzero(buffer[0]) == 0 - assert torch.count_nonzero(buffer[1:]) == buffer[1:].numel() + resets = { + "env_ids": lambda: cube_object.reset(env_ids=torch.tensor([0], device=device)), + "env_mask": lambda: cube_object.reset(env_mask=wp.from_torch(torch.arange(_NUM_ENVS, device=device) == 0)), + } + for selector, reset in resets.items(): + cube_object.permanent_wrench_composer.set_forces_and_torques_index(forces=ones, torques=ones) + cube_object.instantaneous_wrench_composer.add_forces_and_torques_index(forces=ones, torques=ones) + reset() + for composer in composers: + assert composer.active + for buffer in (composer.out_force_b.torch, composer.out_torque_b.torch): + assert torch.count_nonzero(buffer[0]) == 0, selector + assert torch.count_nonzero(buffer[1:]) == buffer[1:].numel(), selector cube_object.reset() for composer in composers: assert not composer.active @@ -834,17 +840,22 @@ def test_collection_wrench_delivery_and_reset(scene: _Scene) -> None: ) assert torch.all(heading[..., 1] > 0.99) - # A partial reset clears the external wrenches of the selected environments only. + # A partial reset by indices or by mask clears the external wrenches of the selected environments only. composers = (collection.instantaneous_wrench_composer, collection.permanent_wrench_composer) ones = torch.ones((_NUM_ENVS, _NUM_CUBES, 3), device=device) - collection.permanent_wrench_composer.set_forces_and_torques_index(forces=ones, torques=ones) - collection.instantaneous_wrench_composer.add_forces_and_torques_index(forces=ones, torques=ones) - collection.reset(env_ids=torch.tensor([0], device=device)) - for composer in composers: - assert composer.active - for buffer in (composer.out_force_b.torch, composer.out_torque_b.torch): - assert torch.count_nonzero(buffer[0]) == 0 - assert torch.count_nonzero(buffer[1:]) == buffer[1:].numel() + resets = { + "env_ids": lambda: collection.reset(env_ids=torch.tensor([0], device=device)), + "env_mask": lambda: collection.reset(env_mask=wp.from_torch(torch.arange(_NUM_ENVS, device=device) == 0)), + } + for selector, reset in resets.items(): + collection.permanent_wrench_composer.set_forces_and_torques_index(forces=ones, torques=ones) + collection.instantaneous_wrench_composer.add_forces_and_torques_index(forces=ones, torques=ones) + reset() + for composer in composers: + assert composer.active + for buffer in (composer.out_force_b.torch, composer.out_torque_b.torch): + assert torch.count_nonzero(buffer[0]) == 0, selector + assert torch.count_nonzero(buffer[1:]) == buffer[1:].numel(), selector # A full reset clears every environment collection.reset() diff --git a/source/isaaclab_physx/test/assets/test_surface_gripper.py b/source/isaaclab_physx/test/assets/test_surface_gripper.py index 729282e55e5a..b6816ade3d95 100644 --- a/source/isaaclab_physx/test/assets/test_surface_gripper.py +++ b/source/isaaclab_physx/test/assets/test_surface_gripper.py @@ -194,3 +194,32 @@ def test_command_filter_and_partial_property_update_use_literal_view_payloads() "retry_interval": [0.0, 0.0, 0.0], "indices": [2, 0], } + + +def test_reset_by_mask_matches_reset_by_ids() -> None: + """A masked reset opens the same grippers as the equivalent index reset.""" + results = [] + resets = ( + lambda gripper: gripper.reset(env_ids=[1]), + lambda gripper: gripper.reset(env_mask=wp.array([False, True, False], dtype=wp.bool, device="cpu")), + ) + for reset in resets: + # Skip USD initialization: a three-environment CPU gripper, closed everywhere, around a recording view. + gripper = object.__new__(SurfaceGripper) + gripper._device = "cpu" + gripper._ALL_INDICES = wp.array([0, 1, 2], dtype=wp.int32, device="cpu") + gripper._gripper_command = wp.ones(3, dtype=wp.float32, device="cpu") + gripper._gripper_state = wp.ones(3, dtype=wp.float32, device="cpu") + gripper._gripper_view = SimpleNamespace(apply_gripper_action=Mock()) + + reset(gripper) + + results.append( + ( + gripper.gripper_view.apply_gripper_action.call_args, + gripper._gripper_command.numpy().tolist(), + gripper._gripper_state.numpy().tolist(), + ) + ) + assert results[0] == results[1] + assert results[0][1:] == ([1.0, 0.0, 1.0], [1.0, -1.0, 1.0]) diff --git a/source/isaaclab_tasks_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_tasks_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py index c42cdaa053d7..2034ac5f541a 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py @@ -13,24 +13,13 @@ import warp as wp from isaaclab_experimental.envs import DirectRLEnvWarp +from isaaclab.utils.warp.kernels import initialize_rng_state from isaaclab.utils.warp.math import quat_error_magnitude if TYPE_CHECKING: from isaaclab_tasks.core.reorient.config.allegro_hand.allegro_hand_direct_env_cfg import AllegroHandEnvCfg -@wp.kernel -def initialize_rng_state( - # input - seed: wp.int32, - # output - state: wp.array(dtype=wp.uint32), -): - """Initialize each env's random number generator state from the seed.""" - env_id = wp.tid() - state[env_id] = wp.rand_init(seed, wp.int32(env_id)) - - @wp.kernel def apply_actions_to_targets( # input From a40fdc8ca23d36c7d0f7d192f0233f35784e6b56 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 16:46:01 -0800 Subject: [PATCH 04/31] Keep the reset tests to the behavior this change adds Drop the tests of mask resets that this change does not touch (scene, assets, grippers, multirotor, native actuators) with their skip fragments, the call-shape test of the collection reset, and the two drift-kernel tests the ray-caster sensor test already covers. Fold the host-mask collection reset into the existing masked-reset test, and drop the network actuators' own host-mask copy: they are reset only through the collection, which copies a host mask first. --- .../isaaclab/actuators/actuator_net.py | 6 - .../actuators/test_actuator_collection.py | 67 ++----- .../test/actuators/test_actuator_net.py | 28 --- .../test/scene/test_interactive_scene.py | 28 --- .../test/sensors/test_ray_caster_kernels.py | 14 -- .../jichuanh-actuator-net-mask-reset.skip | 0 .../test/assets/test_multirotor.py | 25 --- .../assets/test_newton_actuators_newton.py | 168 ++++++------------ .../test/assets/test_rigid_object.py | 18 +- .../jichuanh-actuator-net-mask-reset.skip | 0 .../test/assets/test_articulation.py | 7 - .../jichuanh-actuator-net-mask-reset.skip | 0 .../assets/test_newton_actuators_physx.py | 16 +- .../test/assets/test_rigid_object.py | 47 ++--- .../test/assets/test_surface_gripper.py | 29 --- 15 files changed, 95 insertions(+), 358 deletions(-) delete mode 100644 source/isaaclab_contrib/changelog.d/jichuanh-actuator-net-mask-reset.skip delete mode 100644 source/isaaclab_ov/changelog.d/jichuanh-actuator-net-mask-reset.skip delete mode 100644 source/isaaclab_physx/changelog.d/jichuanh-actuator-net-mask-reset.skip diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index c114685c8437..eff707232b87 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -72,9 +72,6 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: if env_mask is not None: - if env_mask.device != wp.get_device(self._device): - # a mask from another device (e.g. the host) is copied once; a mask on this device is used as given - env_mask = env_mask.to(self._device) # a mask resets with a Warp launch, which a CUDA graph recording of the reset holds for state in (self.sea_hidden_state_per_env, self.sea_cell_state_per_env): for layer in state: @@ -162,9 +159,6 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: if env_mask is not None: - if env_mask.device != wp.get_device(self._device): - # a mask from another device (e.g. the host) is copied once; a mask on this device is used as given - env_mask = env_mask.to(self._device) # a mask resets with a Warp launch, which a CUDA graph recording of the reset holds for history in (self._joint_pos_error_history, self._joint_vel_history): values = wp.from_torch(history.view(self._num_envs, -1)) diff --git a/source/isaaclab/test/actuators/test_actuator_collection.py b/source/isaaclab/test/actuators/test_actuator_collection.py index 9cb772556c0d..e8e2dac1ad55 100644 --- a/source/isaaclab/test/actuators/test_actuator_collection.py +++ b/source/isaaclab/test/actuators/test_actuator_collection.py @@ -29,7 +29,7 @@ ) from isaaclab.actuators.actuator_control import ArticulationActuatorControl from isaaclab.actuators.newton import read_group_parameter, write_group_parameter -from isaaclab.test.utils import DeviceScope, test_devices +from isaaclab.test.utils import test_devices from isaaclab.utils.warp import ProxyArray @@ -46,13 +46,6 @@ def compute(self, control_action, joint_pos, joint_vel): return super().compute(control_action, joint_pos, joint_vel) -class ResetRecordingActuator(ImplicitActuator): - """Custom actuator that records the selection supplied to :meth:`reset`.""" - - def reset(self, env_ids=None, env_mask=None): - self.reset_selection = (env_ids, env_mask) - - def _ideal_cfg(joints: list[str], *, stiffness: float, damping: float, effort_limit: float): return IdealPDActuatorCfg( joint_names_expr=joints, @@ -917,22 +910,13 @@ def test_write_command_mask_uses_full_sized_value(command_name): setter(value=value, env_mask=wp.array([1, 0], dtype=wp.int32, device="cpu"), joint_mask=joint_mask) -def test_index_and_mask_resets_pass_both_selections_to_models(): - cfg = _implicit_cfg() - cfg.class_type = ResetRecordingActuator - collection = ActuatorCollection({"all": cfg}, FakeActuatorControl()) - - collection.reset([1]) - assert collection["all"].reset_selection == ([1], None) - - collection.reset(env_mask=wp.array([False, True], dtype=wp.bool, device="cpu")) - env_ids, env_mask = collection["all"].reset_selection - assert env_ids is None and env_mask.numpy().tolist() == [False, True] - - +@pytest.mark.parametrize("host_mask", [False, True], ids=["device_mask", "host_mask"]) @pytest.mark.parametrize("device", test_devices()) -def test_masked_reset_leaves_unselected_envs_untouched(device): - """A mask reset redraws the masked environments' delays without a device sync and keeps the others.""" +def test_masked_reset_leaves_unselected_envs_untouched(device, host_mask): + """A mask reset redraws the masked environments' delays and keeps the others: a mask on the collection's device + without a device sync, a mask on the host after one copy to the device.""" + if host_mask and not device.startswith("cuda"): + pytest.skip("on the CPU a host mask is on the collection's device") control = FakeActuatorControl(num_envs=4, device=device) cfg = DelayedPDActuatorCfg(joint_names_expr=[".*"], stiffness=1.0, damping=0.0, min_delay=2, max_delay=2) collection = ActuatorCollection({"delayed": cfg}, control) @@ -943,34 +927,17 @@ def test_masked_reset_leaves_unselected_envs_untouched(device): collection.compute() env_mask = torch.tensor([False, True, False, True], device=device) - if device.startswith("cuda"): - torch.cuda.synchronize(device) - torch.cuda.set_sync_debug_mode("error") - try: - collection.reset(env_mask=wp.from_torch(env_mask, dtype=wp.bool)) - finally: - torch.cuda.set_sync_debug_mode("default") - - for delay_buffer in buffers: - torch.testing.assert_close(delay_buffer.time_lags, torch.where(env_mask, 2, 1).to(torch.int)) - torch.testing.assert_close(delay_buffer.num_pushes, torch.where(env_mask, 0, 3)) + if host_mask: + collection.reset(env_mask=wp.from_torch(env_mask.cpu(), dtype=wp.bool)) + else: + if device.startswith("cuda"): + torch.cuda.synchronize(device) + torch.cuda.set_sync_debug_mode("error") + try: + collection.reset(env_mask=wp.from_torch(env_mask, dtype=wp.bool)) + finally: + torch.cuda.set_sync_debug_mode("default") - -@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) -def test_masked_reset_accepts_a_host_mask(device): - """A host mask resets the same environments of a CUDA collection as a mask on its device.""" - control = FakeActuatorControl(num_envs=4, device=device) - cfg = DelayedPDActuatorCfg(joint_names_expr=[".*"], stiffness=1.0, damping=0.0, min_delay=2, max_delay=2) - collection = ActuatorCollection({"delayed": cfg}, control) - buffers = collection["delayed"]._delay_buffers - for delay_buffer in buffers: - delay_buffer.set_time_lag(1) - for _ in range(3): - collection.compute() - - collection.reset(env_mask=wp.array([False, True, False, True], dtype=wp.bool, device="cpu")) - - env_mask = torch.tensor([False, True, False, True], device=device) for delay_buffer in buffers: torch.testing.assert_close(delay_buffer.time_lags, torch.where(env_mask, 2, 1).to(torch.int)) torch.testing.assert_close(delay_buffer.num_pushes, torch.where(env_mask, 0, 3)) diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index c3c498da9b6e..478a05562215 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -126,31 +126,3 @@ def test_mlp_history_keeps_its_address_and_window(tmp_path, device): assert (actuator._joint_pos_error_history.data_ptr(), actuator._joint_vel_history.data_ptr()) == addresses expected = torch.tensor([4.0, 3.0, 2.0], device=device).view(1, 3, 1).expand(3, 3, 2) torch.testing.assert_close(actuator._joint_vel_history, expected) - - -@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) -def test_masked_reset_accepts_a_host_mask(tmp_path, device): - """A host mask resets the same environments of a CUDA network actuator as a mask on its device.""" - host_mask = wp.array([True, False, True], dtype=wp.bool, device="cpu") - lstm = _actuator(ActuatorNetLSTMCfg, _ZeroTorqueLSTM(), tmp_path, device) - lstm.sea_hidden_state.fill_(1.0) - lstm.sea_cell_state.fill_(1.0) - lstm.reset(env_mask=host_mask) - _assert_masked_zero(lstm.sea_hidden_state_per_env, env_dim=1) - _assert_masked_zero(lstm.sea_cell_state_per_env, env_dim=1) - mlp = _actuator( - ActuatorNetMLPCfg, - _ZeroTorqueMLP(), - tmp_path, - device, - input_idx=[0, 1, 2], - pos_scale=1.0, - vel_scale=1.0, - torque_scale=1.0, - input_order="pos_vel", - ) - mlp._joint_pos_error_history.fill_(1.0) - mlp._joint_vel_history.fill_(1.0) - mlp.reset(env_mask=host_mask) - _assert_masked_zero(mlp._joint_pos_error_history, env_dim=0) - _assert_masked_zero(mlp._joint_vel_history, env_dim=0) diff --git a/source/isaaclab/test/scene/test_interactive_scene.py b/source/isaaclab/test/scene/test_interactive_scene.py index b06b6dcd627a..40946843a879 100644 --- a/source/isaaclab/test/scene/test_interactive_scene.py +++ b/source/isaaclab/test/scene/test_interactive_scene.py @@ -12,7 +12,6 @@ import numpy as np import pytest import torch -import warp as wp from isaaclab_physx.sim.schemas import PhysxRigidBodyCfg import isaaclab.sim as sim_utils @@ -185,33 +184,6 @@ def test_relative_deformable_state(): torch.testing.assert_close(written_state["env_ids"], env_ids) -def test_masked_reset_reaches_every_entity(): - """Resets by ids and by mask pass both selections to every asset and sensor.""" - groups = ( - "_articulations", - "_cable_objects", - "_deformable_objects", - "_rigid_objects", - "_surface_grippers", - "_rigid_object_collections", - "_sensors", - ) - calls = {} - - def entity(group): - return SimpleNamespace(reset=lambda env_ids=None, env_mask=None: calls.update({group: (env_ids, env_mask)})) - - scene = SimpleNamespace(**{group: {"entity": entity(group)} for group in groups}) - env_mask = wp.array([True, False, True], dtype=wp.bool, device="cpu") - - InteractiveScene.reset(scene, env_mask=env_mask) - assert calls == dict.fromkeys(groups, (None, env_mask)) - - calls.clear() - InteractiveScene.reset(scene, env_ids=[1]) - assert calls == dict.fromkeys(groups, ([1], None)) - - def test_scene_publishes_plan_before_replicate(monkeypatch: pytest.MonkeyPatch): """A cfg-driven scene publishes the exact plan it forwards to replication.""" import isaaclab.cloner.replicate_session as replicate_session_module diff --git a/source/isaaclab/test/sensors/test_ray_caster_kernels.py b/source/isaaclab/test/sensors/test_ray_caster_kernels.py index 83a452d5ff55..6e104d8fde95 100644 --- a/source/isaaclab/test/sensors/test_ray_caster_kernels.py +++ b/source/isaaclab/test/sensors/test_ray_caster_kernels.py @@ -709,13 +709,6 @@ def _resample_drift(env_mask, drift_range, ray_cast_min, ray_cast_max, rng_state class TestResampleDriftMaskedKernel: """Tests for :func:`resample_drift_masked_kernel`.""" - def test_only_masked_envs_change(self): - env_mask = wp.array([True, False, True, False], dtype=wp.bool, device=DEVICE) - drift, ray_cast_drift = _resample_drift(env_mask, (0.1, 0.2), (0.1, 0.1, 0.1), (0.2, 0.2, 0.2), _rng_state()) - for values in (drift, ray_cast_drift): - np.testing.assert_array_equal(values[[1, 3]], -1.0) - assert (values[[0, 2]] >= 0.1).all() - def test_draws_stay_in_their_ranges(self): env_mask = wp.array([True] * 64, dtype=wp.bool, device=DEVICE) drift, ray_cast_drift = _resample_drift( @@ -729,10 +722,3 @@ def test_zero_range_draws_zero(self): drift, ray_cast_drift = _resample_drift(env_mask, (0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), _rng_state()) np.testing.assert_array_equal(drift, 0.0) np.testing.assert_array_equal(ray_cast_drift, 0.0) - - def test_state_advances_between_launches(self): - env_mask = wp.array([True] * 4, dtype=wp.bool, device=DEVICE) - rng_state = _rng_state() - first, _ = _resample_drift(env_mask, (-1.0, 1.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), rng_state) - second, _ = _resample_drift(env_mask, (-1.0, 1.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), rng_state) - assert not np.array_equal(first, second) diff --git a/source/isaaclab_contrib/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_contrib/changelog.d/jichuanh-actuator-net-mask-reset.skip deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab_contrib/test/assets/test_multirotor.py b/source/isaaclab_contrib/test/assets/test_multirotor.py index 2baf668c9379..5d195eeffe7a 100644 --- a/source/isaaclab_contrib/test/assets/test_multirotor.py +++ b/source/isaaclab_contrib/test/assets/test_multirotor.py @@ -18,8 +18,6 @@ import pytest import torch -import warp as wp -from isaaclab_physx.assets.articulation import Articulation from isaaclab_physx.physics import PhysxCfg import isaaclab.sim.utils.prims as prim_utils @@ -158,29 +156,6 @@ def test_set_thrust_target_env_slice_unit(): assert torch.allclose(m._data.thrust_target[3], original[3]) -@pytest.mark.parametrize("selection", ["ids", "mask"]) -def test_reset_restores_selected_thrust_targets_unit(selection, monkeypatch): - """Resets by ids and by mask reach the articulation and restore the selected thrust targets only.""" - parent_resets = [] - monkeypatch.setattr( - Articulation, "reset", lambda self, env_ids=None, env_mask=None: parent_resets.append((env_ids, env_mask)) - ) - m = Multirotor.__new__(Multirotor) - m._device = "cpu" - m._ALL_INDICES = wp.array([0, 1, 2, 3], dtype=wp.int32, device="cpu") - m._data = types.SimpleNamespace(thrust_target=torch.ones(4, 2), default_thruster_rps=torch.zeros(4, 2)) - env_mask = wp.array([True, False, True, False], dtype=wp.bool, device="cpu") - - if selection == "ids": - m.reset(env_ids=[0, 2]) - assert parent_resets == [([0, 2], None)] - else: - m.reset(env_mask=env_mask) - assert parent_resets == [(None, env_mask)] - expected = torch.tensor([[0.0, 0.0], [1.0, 1.0], [0.0, 0.0], [1.0, 1.0]]) - torch.testing.assert_close(m._data.thrust_target, expected) - - def generate_multirotor( multirotor_cfg: MultirotorCfg, num_multirotors: int, device: str ) -> tuple[Multirotor, torch.Tensor]: diff --git a/source/isaaclab_newton/test/assets/test_newton_actuators_newton.py b/source/isaaclab_newton/test/assets/test_newton_actuators_newton.py index 75d871ab671a..27a7b38e9546 100644 --- a/source/isaaclab_newton/test/assets/test_newton_actuators_newton.py +++ b/source/isaaclab_newton/test/assets/test_newton_actuators_newton.py @@ -383,92 +383,32 @@ def _run( return _Run(sim=sim, articulations=articulations, results=results) -_RESET_SELECTORS = ("env_ids", "env_mask") - - -def _reset_env_0(articulation: Articulation, selector: str) -> None: - """Reset environment 0 alone through the given selector.""" - if selector == "env_ids": - articulation.reset(env_ids=torch.tensor([0], device=articulation.device, dtype=torch.long)) - else: - env_mask = torch.arange(articulation.num_instances, device=articulation.device) == 0 - articulation.reset(env_mask=wp.from_torch(env_mask)) - - -def _warm_delayed_island(run: _Run) -> list: - """Step the delayed island until its delay buffers hold history and return its delayed actuators' state pairs. - - Only the reset articulation's own delayed actuators are returned. The adapter is model-wide, so the other - islands' actuators share its state buffers; their state is not part of this articulation's contract. - """ - articulation = run.articulations["delayed"] - for _ in range(3): - articulation.write_data_to_sim() - run.sim.step() - articulation.update(DT) - adapter = run.sim.backend_manager.backend.actuators - assert adapter is not None - own_actuators = [] - for group_name in articulation.actuators._native_group_names: - group_actuators = articulation.actuators[group_name] - own_actuators.extend(group_actuators if isinstance(group_actuators, tuple) else (group_actuators,)) - stateful_pairs = [ - (act, st) - for act, st in zip(adapter.actuators, adapter._states_a) - if any(act is own for own in own_actuators) and st is not None and st.delay_state is not None - ] - assert len(stateful_pairs) > 0, "expected at least one DelayedPD actuator with delay_state" - for act, state in stateful_pairs: - pushes_before = state.delay_state.num_pushes.numpy() - assert (pushes_before > 0).all(), "expected non-zero num_pushes for all DOFs after warmup" - return stateful_pairs - - -def _assert_delay_state_cleared_for_env_0_only(run: _Run, stateful_pairs: list) -> None: - """Assert ``num_pushes`` is zero for environment 0's DOFs and positive for every other environment's DOFs.""" - # Map each entry of ``act.indices`` to its env via the adapter's per-env DOF count. The adapter is - # model-wide (includes free-joint DOFs on floating-base articulations), so ``adapter.num_joints`` is the - # stride. - adapter = run.sim.backend_manager.backend.actuators - for act, state in stateful_pairs: - pushes_after = state.delay_state.num_pushes.numpy() - indices_np = act.indices.numpy() - for i, global_dof in enumerate(indices_np): - env = int(global_dof) // adapter.num_joints - if env == 0: - assert int(pushes_after[i]) == 0, f"DOF {i} (env {env}) should be reset to 0, got {pushes_after[i]}" - else: - assert int(pushes_after[i]) > 0, f"DOF {i} (env {env}) was NOT in the reset selection but is 0" - - -def _record_lab_state_reset(run: _Run) -> dict[str, dict[str, tuple[torch.Tensor, torch.Tensor]]]: - """Reset one Lab-path environment of the delayed island per selector and record each group's effort and PD demand. +def _record_lab_state_reset(run: _Run) -> dict[str, tuple[torch.Tensor, torch.Tensor]]: + """Reset one Lab-path environment of the delayed island and record each group's effort and PD demand. Reset environments must accept fresh commands while the remaining environments retain their delay history. """ articulation = run.articulations["delayed"] commands = articulation.actuators.target_command old_target = commands.position.torch.clone() + # Episode reset samples the configured lag; construction alone leaves actuator lag at zero. + articulation.reset() + commands.set_position_index(value=old_target) + articulation.write_data_to_sim() new_target = old_target + 0.02 + articulation.reset(env_ids=torch.tensor([0], device=articulation.device)) + commands.set_position_index(value=new_target) + articulation.write_data_to_sim() expected_target = old_target.clone() expected_target[0] = new_target[0] recorded = {} - for selector in _RESET_SELECTORS: - # Episode reset samples the configured lag; construction alone leaves actuator lag at zero. - articulation.reset() - commands.set_position_index(value=old_target) - articulation.write_data_to_sim() - _reset_env_0(articulation, selector) - commands.set_position_index(value=new_target) - articulation.write_data_to_sim() - recorded[selector] = {} - for name, actuator in articulation.actuators.items(): - joints = actuator.joint_indices - demand = ( - actuator.stiffness * (expected_target[:, joints] - articulation.data.joint_pos.torch[:, joints]) - - actuator.damping * articulation.data.joint_vel.torch[:, joints] - ) - recorded[selector][name] = (actuator.computed_effort.clone(), demand) + for name, actuator in articulation.actuators.items(): + joints = actuator.joint_indices + demand = ( + actuator.stiffness * (expected_target[:, joints] - articulation.data.joint_pos.torch[:, joints]) + - actuator.damping * articulation.data.joint_vel.torch[:, joints] + ) + recorded[name] = (actuator.computed_effort.clone(), demand) return recorded @@ -509,33 +449,10 @@ def decimated_runs(device: str) -> dict[str, dict]: @pytest.fixture(scope="module") -def masked_replay_run(device: str) -> list[tuple[np.ndarray, np.ndarray]]: - """Record a masked reset of environment 0 in a CUDA graph and replay it after the delay buffers refill. - - The scene holds only the delayed island: the adapter resets every actuator of the model, and Newton's neural - actuator state reset cannot be recorded into a graph. Returns, per delayed actuator, its ``num_pushes`` after the - replay and the environment of each of its DOFs. - """ - sim_cfg = newton_sim_cfg(device, dt=DT, use_newton_actuators=True, solver_cfg=_solver_cfg()) - with build_simulation_context(sim_cfg=sim_cfg) as sim: - run = _run(sim, {"delayed": _islands()["delayed"]}, use_newton_actuators=True) - articulation = run.articulations["delayed"] - env_mask = wp.from_torch(torch.arange(articulation.num_instances, device=device) == 0) - # Allocating inside the capture raises while the memory pool is disabled. - with wp.ScopedMempool(device, False), wp.ScopedCapture(device) as capture: - articulation.reset(env_mask=env_mask) - # Repopulate the delay buffers, so the replay rather than the capture must clear environment 0. - stateful_pairs = _warm_delayed_island(run) - wp.capture_launch(capture.graph) - stride = run.sim.backend_manager.backend.actuators.num_joints - return [(state.delay_state.num_pushes.numpy(), act.indices.numpy() // stride) for act, state in stateful_pairs] - - -@pytest.fixture(scope="module") -def newton_run(device: str, lab_run: dict, decimated_runs: dict, masked_replay_run: list) -> Iterator[_Run]: +def newton_run(device: str, lab_run: dict, decimated_runs: dict) -> Iterator[_Run]: """Roll out every island on the Newton actuator path and keep the scene alive. - Depends on the Lab-path, decimated and masked-replay runs so their scenes are built and closed first. + Depends on the Lab-path and decimated runs so their scenes are built and closed first. """ mlp_path = make_dummy_mlp_checkpoint() lstm_path = make_dummy_lstm_checkpoint() @@ -1029,21 +946,46 @@ def gains(name: str) -> torch.Tensor: def test_newton_state_reset_isolated_to_reset_env(newton_run: _Run) -> None: - """Newton: ``num_pushes`` zeroes for env 0's DOFs only after a partial reset of env 0.""" - stateful_pairs = _warm_delayed_island(newton_run) - _reset_env_0(newton_run.articulations["delayed"], "env_ids") - _assert_delay_state_cleared_for_env_0_only(newton_run, stateful_pairs) + """Newton: ``num_pushes`` zeroes for env 0's DOFs only after reset of [0]. + Only the reset articulation's own delayed actuators are checked. The adapter is model-wide, so the other + islands' actuators share its state buffers; their state is not part of this articulation's contract. + """ + articulation = newton_run.articulations["delayed"] + adapter = newton_run.sim.backend_manager.backend.actuators + assert adapter is not None + own_actuators = [] + for group_name in articulation.actuators._native_group_names: + group_actuators = articulation.actuators[group_name] + own_actuators.extend(group_actuators if isinstance(group_actuators, tuple) else (group_actuators,)) + stateful_pairs = [ + (act, st) + for act, st in zip(adapter.actuators, adapter._states_a) + if any(act is own for own in own_actuators) and st is not None and st.delay_state is not None + ] + assert len(stateful_pairs) > 0, "expected at least one DelayedPD actuator with delay_state" + + for act, state in stateful_pairs: + pushes_before = state.delay_state.num_pushes.numpy() + assert (pushes_before > 0).all(), "expected non-zero num_pushes for all DOFs after warmup" + + articulation.reset(env_ids=torch.tensor([0], device=articulation.device, dtype=torch.long)) -def test_newton_masked_reset_replays_from_cuda_graph_without_allocation(masked_replay_run: list) -> None: - """A masked reset records into a CUDA graph without allocating and, on replay, clears only the masked env.""" - for pushes, envs in masked_replay_run: - assert (pushes[envs == 0] == 0).all() - assert (pushes[envs != 0] > 0).all() + # Map each entry of ``act.indices`` to its env via the adapter's per-env DOF count. The adapter is + # model-wide (includes free-joint DOFs on floating-base articulations), so ``adapter.num_joints`` is the + # stride. + for act, state in stateful_pairs: + pushes_after = state.delay_state.num_pushes.numpy() + indices_np = act.indices.numpy() + for i, global_dof in enumerate(indices_np): + env = int(global_dof) // adapter.num_joints + if env == 0: + assert int(pushes_after[i]) == 0, f"DOF {i} (env {env}) should be reset to 0, got {pushes_after[i]}" + else: + assert int(pushes_after[i]) > 0, f"DOF {i} (env {env}) was NOT in reset env_ids but num_pushes is 0" -@pytest.mark.parametrize("selector", _RESET_SELECTORS) -def test_lab_state_reset_isolated_to_reset_env(lab_run: dict, selector: str) -> None: +def test_lab_state_reset_isolated_to_reset_env(lab_run: dict) -> None: """Reset environments accept fresh commands while the remaining environments retain their history.""" - for computed_effort, demand in lab_run["state_reset"][selector].values(): + for computed_effort, demand in lab_run["state_reset"].values(): torch.testing.assert_close(computed_effort, demand) diff --git a/source/isaaclab_newton/test/assets/test_rigid_object.py b/source/isaaclab_newton/test/assets/test_rigid_object.py index d426343ec909..7257c28f8a0f 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object.py @@ -385,8 +385,7 @@ def test_external_force_on_single_body(scene: _Scene) -> None: """A permanent wrench reaches the solver in the local and the global frame, and a reset clears it. Cube 0 receives a force equal to its weight and hovers while cube 1 falls. Cube 0 then receives a force set - and added 1 m off its center along y and must turn about x while cube 1 keeps falling. A masked reset clears - the wrench of the selected environment only. + and added 1 m off its center along y and must turn about x while cube 1 keeps falling. """ cube = scene.cube composer = cube.permanent_wrench_composer @@ -415,12 +414,6 @@ def test_external_force_on_single_body(scene: _Scene) -> None: assert cube.data.root_ang_vel_b.torch[0, 0].abs() > 0.1 assert cube.data.root_pos_w.torch[1, 2] < 1.0 - ones = torch.ones_like(zeros) - composer.set_forces_and_torques_index(forces=ones, torques=ones) - cube.reset(env_mask=wp.from_torch(torch.arange(cube.num_instances, device=scene.device) == 0)) - assert torch.count_nonzero(composer.out_force_b.torch[0]) == 0 - assert torch.count_nonzero(composer.out_force_b.torch[1:]) == composer.out_force_b.torch[1:].numel() - @pytest.mark.isaacsim_ci def test_rigid_body_set_material_properties(scene: _Scene) -> None: @@ -911,8 +904,7 @@ def test_collection_external_force_on_single_body(scene: _Scene) -> None: """A permanent wrench reaches the solver in the local and the global frame, and a reset clears it. Every other cube receives a force equal to its weight and hovers while the rest fall. Those cubes then - receive a force set and added 1 m off their centers along y and must turn about x. A masked reset clears the - wrenches of the selected environment only. + receive a force set and added 1 m off their centers along y and must turn about x. """ collection = scene.collection composer = collection.permanent_wrench_composer @@ -941,12 +933,6 @@ def test_collection_external_force_on_single_body(scene: _Scene) -> None: assert torch.all(collection.data.body_com_ang_vel_b.torch[:, 0::2, 0] > 0.1) assert torch.all(height[:, 1::2] < 1.0) - ones = torch.ones_like(zeros) - composer.set_forces_and_torques_index(forces=ones, torques=ones) - collection.reset(env_mask=wp.from_torch(torch.arange(collection.num_instances, device=scene.device) == 0)) - assert torch.count_nonzero(composer.out_force_b.torch[0]) == 0 - assert torch.count_nonzero(composer.out_force_b.torch[1:]) == composer.out_force_b.torch[1:].numel() - @pytest.mark.isaacsim_ci def test_collection_gravity_vec_w_tracks_model_gravity(scene: _Scene) -> None: diff --git a/source/isaaclab_ov/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_ov/changelog.d/jichuanh-actuator-net-mask-reset.skip deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab_ov/test/assets/test_articulation.py b/source/isaaclab_ov/test/assets/test_articulation.py index c1892fd109bb..1c18f8f81023 100644 --- a/source/isaaclab_ov/test/assets/test_articulation.py +++ b/source/isaaclab_ov/test/assets/test_articulation.py @@ -1636,13 +1636,6 @@ def __getitem__(self, name): # The delay state is flattened environment-major over the group's joints. assert stateful_pairs[0].delay_state.num_pushes.numpy().tolist() == [0] * num_joints + [1] * num_joints - scene.step(articulation) - articulation.reset(env_mask=wp.array([False, True], dtype=wp.bool, device=device)) - stateful_pairs = [ - state for state in adapter._states_a if state is not None and getattr(state, "delay_state", None) is not None - ] - assert stateful_pairs[0].delay_state.num_pushes.numpy().tolist() == [1] * num_joints + [0] * num_joints - env = Env(articulation) asset_cfg = SceneEntityCfg("robot") event_params = { diff --git a/source/isaaclab_physx/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_physx/changelog.d/jichuanh-actuator-net-mask-reset.skip deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab_physx/test/assets/test_newton_actuators_physx.py b/source/isaaclab_physx/test/assets/test_newton_actuators_physx.py index 066e1ffb6e5a..3e84d69abcec 100644 --- a/source/isaaclab_physx/test/assets/test_newton_actuators_physx.py +++ b/source/isaaclab_physx/test/assets/test_newton_actuators_physx.py @@ -296,16 +296,9 @@ def test_network_actuators_drive_haa_joints(rollouts: _Rollouts, robot: str) -> assert not torch.allclose(trace["applied_effort"][0][:, haa_ids], trace["applied_effort"][-1][:, haa_ids]) -@pytest.mark.parametrize("selector", ["env_ids", "env_mask"]) -def test_reset_clears_actuator_state_of_selected_envs(rollouts: _Rollouts, selector: str) -> None: - """Resetting environment 0 by indices or by mask clears the delay history of its DoFs only.""" +def test_reset_clears_actuator_state_of_selected_envs(rollouts: _Rollouts) -> None: + """Resetting environment 0 clears the delay history of its DoFs only.""" articulation = rollouts.robots["delayed"] - # Refill the delay history that a previous reset cleared. - sim = SimulationContext.instance() - for _ in range(3): - articulation.write_data_to_sim() - sim.step() - articulation.update(DT) adapter = articulation.newton_actuator_adapter delay_states = [ (actuator, state.delay_state) @@ -315,10 +308,7 @@ def test_reset_clears_actuator_state_of_selected_envs(rollouts: _Rollouts, selec assert delay_states assert all((delay_state.num_pushes.numpy() > 0).all() for _, delay_state in delay_states) - if selector == "env_ids": - articulation.reset(env_ids=torch.tensor([0], device=articulation.device)) - else: - articulation.reset(env_mask=wp.from_torch(torch.arange(NUM_ENVS, device=articulation.device) == 0)) + articulation.reset(env_ids=torch.tensor([0], device=articulation.device)) for actuator, delay_state in delay_states: env_of_dof = actuator.indices.numpy() // adapter.num_joints pushes = delay_state.num_pushes.numpy() diff --git a/source/isaaclab_physx/test/assets/test_rigid_object.py b/source/isaaclab_physx/test/assets/test_rigid_object.py index 95c0ae2d8f76..764e54ff941d 100644 --- a/source/isaaclab_physx/test/assets/test_rigid_object.py +++ b/source/isaaclab_physx/test/assets/test_rigid_object.py @@ -644,23 +644,17 @@ def test_rigid_object_wrench_delivery_and_reset(scene: _Scene) -> None: > 0.99 ) - # A partial reset by indices or by mask clears only the selected environment; a full reset deactivates the - # composers. + # A partial reset clears only the selected environment; a full reset deactivates the composers. composers = (cube_object.instantaneous_wrench_composer, cube_object.permanent_wrench_composer) ones = torch.ones((_NUM_ENVS, 1, 3), device=device) - resets = { - "env_ids": lambda: cube_object.reset(env_ids=torch.tensor([0], device=device)), - "env_mask": lambda: cube_object.reset(env_mask=wp.from_torch(torch.arange(_NUM_ENVS, device=device) == 0)), - } - for selector, reset in resets.items(): - cube_object.permanent_wrench_composer.set_forces_and_torques_index(forces=ones, torques=ones) - cube_object.instantaneous_wrench_composer.add_forces_and_torques_index(forces=ones, torques=ones) - reset() - for composer in composers: - assert composer.active - for buffer in (composer.out_force_b.torch, composer.out_torque_b.torch): - assert torch.count_nonzero(buffer[0]) == 0, selector - assert torch.count_nonzero(buffer[1:]) == buffer[1:].numel(), selector + cube_object.permanent_wrench_composer.set_forces_and_torques_index(forces=ones, torques=ones) + cube_object.instantaneous_wrench_composer.add_forces_and_torques_index(forces=ones, torques=ones) + cube_object.reset(env_ids=torch.tensor([0], device=device)) + for composer in composers: + assert composer.active + for buffer in (composer.out_force_b.torch, composer.out_torque_b.torch): + assert torch.count_nonzero(buffer[0]) == 0 + assert torch.count_nonzero(buffer[1:]) == buffer[1:].numel() cube_object.reset() for composer in composers: assert not composer.active @@ -840,22 +834,17 @@ def test_collection_wrench_delivery_and_reset(scene: _Scene) -> None: ) assert torch.all(heading[..., 1] > 0.99) - # A partial reset by indices or by mask clears the external wrenches of the selected environments only. + # A partial reset clears the external wrenches of the selected environments only. composers = (collection.instantaneous_wrench_composer, collection.permanent_wrench_composer) ones = torch.ones((_NUM_ENVS, _NUM_CUBES, 3), device=device) - resets = { - "env_ids": lambda: collection.reset(env_ids=torch.tensor([0], device=device)), - "env_mask": lambda: collection.reset(env_mask=wp.from_torch(torch.arange(_NUM_ENVS, device=device) == 0)), - } - for selector, reset in resets.items(): - collection.permanent_wrench_composer.set_forces_and_torques_index(forces=ones, torques=ones) - collection.instantaneous_wrench_composer.add_forces_and_torques_index(forces=ones, torques=ones) - reset() - for composer in composers: - assert composer.active - for buffer in (composer.out_force_b.torch, composer.out_torque_b.torch): - assert torch.count_nonzero(buffer[0]) == 0, selector - assert torch.count_nonzero(buffer[1:]) == buffer[1:].numel(), selector + collection.permanent_wrench_composer.set_forces_and_torques_index(forces=ones, torques=ones) + collection.instantaneous_wrench_composer.add_forces_and_torques_index(forces=ones, torques=ones) + collection.reset(env_ids=torch.tensor([0], device=device)) + for composer in composers: + assert composer.active + for buffer in (composer.out_force_b.torch, composer.out_torque_b.torch): + assert torch.count_nonzero(buffer[0]) == 0 + assert torch.count_nonzero(buffer[1:]) == buffer[1:].numel() # A full reset clears every environment collection.reset() diff --git a/source/isaaclab_physx/test/assets/test_surface_gripper.py b/source/isaaclab_physx/test/assets/test_surface_gripper.py index b6816ade3d95..729282e55e5a 100644 --- a/source/isaaclab_physx/test/assets/test_surface_gripper.py +++ b/source/isaaclab_physx/test/assets/test_surface_gripper.py @@ -194,32 +194,3 @@ def test_command_filter_and_partial_property_update_use_literal_view_payloads() "retry_interval": [0.0, 0.0, 0.0], "indices": [2, 0], } - - -def test_reset_by_mask_matches_reset_by_ids() -> None: - """A masked reset opens the same grippers as the equivalent index reset.""" - results = [] - resets = ( - lambda gripper: gripper.reset(env_ids=[1]), - lambda gripper: gripper.reset(env_mask=wp.array([False, True, False], dtype=wp.bool, device="cpu")), - ) - for reset in resets: - # Skip USD initialization: a three-environment CPU gripper, closed everywhere, around a recording view. - gripper = object.__new__(SurfaceGripper) - gripper._device = "cpu" - gripper._ALL_INDICES = wp.array([0, 1, 2], dtype=wp.int32, device="cpu") - gripper._gripper_command = wp.ones(3, dtype=wp.float32, device="cpu") - gripper._gripper_state = wp.ones(3, dtype=wp.float32, device="cpu") - gripper._gripper_view = SimpleNamespace(apply_gripper_action=Mock()) - - reset(gripper) - - results.append( - ( - gripper.gripper_view.apply_gripper_action.call_args, - gripper._gripper_command.numpy().tolist(), - gripper._gripper_state.numpy().tolist(), - ) - ) - assert results[0] == results[1] - assert results[0][1:] == ([1.0, 0.0, 1.0], [1.0, -1.0, 1.0]) From 4b9dd927aa27e9910ad77026c5ace71f8f5d8d4d Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:05:30 -0800 Subject: [PATCH 05/31] Reseed the ray-caster drift states on every configure_seed An explicit seed now restarts the drift sequence, so two env.reset(seed=...) calls with the same seed repeat the drift and the height scan, as on main; unseeded resets keep advancing it. configure_seed calls the listeners added with add_seed_listener, held as weak methods, and every ray caster registers the method that seeds its drift states. The reseed runs on the host where the seed is set, never inside a recorded reset. --- ...jichuanh-actuator-net-mask-reset.added.rst | 3 ++ ...chuanh-actuator-net-mask-reset.changed.rst | 7 ++-- .../sensors/ray_caster/base_ray_caster.py | 34 +++++++++++++------ source/isaaclab/isaaclab/utils/seed.py | 21 +++++++++++- .../sensors/test_newton_raycast_sensor.py | 18 ++++++---- 5 files changed, 62 insertions(+), 21 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst index 6dd11924d229..2fb21a09b811 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst @@ -1,2 +1,5 @@ * Added :func:`~isaaclab.utils.warp.kernels.initialize_rng_state`, which seeds one Warp random number generator state per environment for kernels that draw per-environment random numbers. +* Added :func:`~isaaclab.utils.seed.add_seed_listener`, which calls a bound method with the seed on every + :func:`~isaaclab.utils.seed.configure_seed`, so random states kept outside the global generators follow an + explicit seed such as ``env.reset(seed=...)``. diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index 4d42c16f1362..38f446a10458 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -3,6 +3,7 @@ clears it on every replay. :class:`~isaaclab.actuators.ActuatorNetMLP` updates its history buffers in place. * Changed the ray-caster drift resampling on reset to draw from per-environment Warp random states, so a reset recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded - once from the environment seed when the sensor initializes, and drift no longer draws from Torch's generator: a - later :func:`~isaaclab.utils.seed.configure_seed` does not restart the drift sequence. The drift ranges are - unchanged; the drawn values differ. + from the environment seed when the sensor initializes and again by every + :func:`~isaaclab.utils.seed.configure_seed`, including the one ``env.reset(seed=...)`` makes, so a seeded reset + repeats the drift and unseeded resets keep advancing it. Drift no longer draws from Torch's generator. The drift + ranges are unchanged; the drawn values differ. diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py index 9c6e552a1704..3ebddef2dbad 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py @@ -21,6 +21,7 @@ from ...terrains.trimesh.utils import make_plane from ...utils import math as math_utils from ...utils.mesh import convert_faces_to_triangles +from ...utils.seed import add_seed_listener from ...utils.warp import ProxyArray, convert_to_warp_mesh from ...utils.warp.kernels import initialize_rng_state, raycast_mesh_masked_kernel from ..sensor_base import SensorBase @@ -76,6 +77,9 @@ def __init__(self, cfg: RayCasterCfg): super().__init__(cfg) self._data = RayCasterData() self._drift_sampled = False + # Drift random states, allocated when the rays initialize; every configure_seed reseeds them. + self._drift_rng_state: wp.array | None = None + add_seed_listener(self._seed_drift) def __str__(self) -> str: """Returns: A string containing information about the instance.""" @@ -244,17 +248,10 @@ def _initialize_rays_impl(self): # Drift buffers are warp-first; reset resamples them in a Warp kernel. self.drift = ProxyArray(wp.zeros(self._view_count, dtype=wp.vec3f, device=self._device)) self.ray_cast_drift = ProxyArray(wp.zeros(self._view_count, dtype=wp.vec3f, device=self._device)) - # Per-environment random states for drift resampling, seeded once from the environment seed (which - # configure_seed stores as torch's initial seed; reading it draws nothing) mixed with the prim path, so - # each ray caster draws its own drift; resets only draw from them. + # Per-environment random states for drift resampling, seeded from the environment seed (which + # configure_seed stores as torch's initial seed; reading it draws nothing); resets only draw from them. self._drift_rng_state = wp.empty(self._view_count, dtype=wp.uint32, device=self._device) - wp.launch( - initialize_rng_state, - dim=self._view_count, - inputs=[(torch.initial_seed() ^ zlib.crc32(self.cfg.prim_path.encode())) & 0x7FFFFFFF], - outputs=[self._drift_rng_state], - device=self._device, - ) + self._seed_drift(torch.initial_seed()) # World-frame ray buffers self._ray_starts_w = wp.empty((self._view_count, self.num_rays), dtype=wp.vec3f, device=self._device) @@ -271,6 +268,23 @@ def _initialize_rays_impl(self): self._dummy_ray_distance = wp.empty((1, 1), dtype=wp.float32, device=self._device) self._dummy_ray_normal = wp.empty((1, 1), dtype=wp.vec3f, device=self._device) + def _seed_drift(self, seed: int) -> None: + """Seed the drift random states from ``seed`` mixed with the prim path, so each ray caster draws its own drift. + + Runs when the rays initialize and on every :func:`~isaaclab.utils.seed.configure_seed`, on the host where + the seed is set, never inside a recorded reset. + """ + # No states before the rays initialize, and none in the ray-caster cameras, which do not resample drift. + if self._drift_rng_state is None: + return + wp.launch( + initialize_rng_state, + dim=self._view_count, + inputs=[(seed ^ zlib.crc32(self.cfg.prim_path.encode())) & 0x7FFFFFFF], + outputs=[self._drift_rng_state], + device=self._device, + ) + def _get_view_transforms_wp(self) -> wp.array: """Get world transforms from the frame view as a warp array of ``wp.transformf``. diff --git a/source/isaaclab/isaaclab/utils/seed.py b/source/isaaclab/isaaclab/utils/seed.py index 535789305164..568c5838e317 100644 --- a/source/isaaclab/isaaclab/utils/seed.py +++ b/source/isaaclab/isaaclab/utils/seed.py @@ -5,14 +5,28 @@ import os import random +import weakref +from collections.abc import Callable import numpy as np import torch import warp as wp +_seed_listeners: list[weakref.WeakMethod] = [] + + +def add_seed_listener(listener: Callable[[int], None]) -> None: + """Call a bound method with the seed after every :func:`configure_seed`. + + Args: + listener: Bound method that reseeds its object's random state. The object is held weakly, so the listener + stops when the object is deleted. + """ + _seed_listeners.append(weakref.WeakMethod(listener)) + def configure_seed(seed: int | None, torch_deterministic: bool = False) -> int: - """Set seed across all random number generators (torch, numpy, random, warp). + """Set seed across all random number generators (torch, numpy, random, warp) and pass it to the seed listeners. Args: seed: The random seed value. If None, generates a random seed. @@ -32,6 +46,11 @@ def configure_seed(seed: int | None, torch_deterministic: bool = False) -> int: torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) wp.rand_init(seed) + for listener_ref in list(_seed_listeners): + if (listener := listener_ref()) is None: + _seed_listeners.remove(listener_ref) + else: + listener(seed) if torch_deterministic: # refer to https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility diff --git a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py index 083bda829c19..0e8b4949c2ec 100644 --- a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py @@ -40,6 +40,7 @@ from isaaclab.sim import SimulationCfg from isaaclab.terrains import TerrainImporterCfg from isaaclab.utils import configclass, replace +from isaaclab.utils.seed import configure_seed SENSOR_HEIGHT = 2.0 RAY_OFFSET = 0.2 @@ -268,29 +269,32 @@ def test_partial_reset_resamples_drift_of_selected_envs_only(sim, monkeypatch): @pytest.mark.parametrize("sim", [pytest.param(False, id="eager")], indirect=True) -def test_drift_is_seeded_once_from_the_environment_seed(sim): - """The drift states are seeded from the environment seed when the rays initialize; resets only draw from them. +def test_drift_follows_the_environment_seed(sim): + """An explicit seed, as ``env.reset(seed=...)`` sets, restarts the drift sequence; unseeded resets advance it. - Neither initialization nor resets draw from torch's global generator, and new storage, as after a simulation - stop and play, starts the same drift sequence again. + Resets do not draw from torch's generator, and new storage, as after a simulation stop and play, starts the + drift sequence of the current seed again. """ scene_cfg = RaycastTestSceneCfg(num_envs=2) scene_cfg.raycast.drift_range = (0.01, 0.05) scene = InteractiveScene(scene_cfg) sim.reset() sensor: NewtonRaycastSensor = scene["raycast"] - state = torch.get_rng_state() - sensor._initialize_rays_impl() + configure_seed(123) sensor.reset() first = sensor.drift.torch.clone() sensor.reset() assert not torch.allclose(sensor.drift.torch, first) + configure_seed(123) + state = torch.cuda.get_rng_state(sensor.device) + sensor.reset() + torch.testing.assert_close(sensor.drift.torch, first) sensor._initialize_rays_impl() sensor.reset() torch.testing.assert_close(sensor.drift.torch, first) assert ((first >= 0.01) & (first <= 0.05)).all() - assert torch.equal(torch.get_rng_state(), state) + assert torch.equal(torch.cuda.get_rng_state(sensor.device), state) @configclass From 9ad50a6687e0ec05ab05d170df4111b4daec0fa6 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:32:03 -0800 Subject: [PATCH 06/31] Keep the experimental Warp environments on their own random state kernels The ray caster needs initialize_rng_state in isaaclab.utils.warp.kernels; the experimental manager-based environment and the Allegro reorient task keep their copies as on main. --- .../jichuanh-actuator-net-mask-reset.skip | 0 .../envs/manager_based_env_warp.py | 12 +++++++++++- .../utils/noise/noise_model.py | 4 ++-- .../jichuanh-actuator-net-mask-reset.skip | 0 .../core/reorient/reorient_warp_env.py | 13 ++++++++++++- 5 files changed, 25 insertions(+), 4 deletions(-) delete mode 100644 source/isaaclab_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip delete mode 100644 source/isaaclab_tasks_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip diff --git a/source/isaaclab_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py index 60af28f80b40..2fe63fdf9920 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py @@ -39,7 +39,6 @@ from isaaclab.utils import validate from isaaclab.utils.seed import configure_seed from isaaclab.utils.timer import Timer -from isaaclab.utils.warp.kernels import initialize_rng_state from isaaclab.utils.warp.memory import resolve_1d_mask from isaaclab_experimental.utils.manager_call_switch import ManagerCallMode, ManagerCallSwitch @@ -48,6 +47,17 @@ logger = logging.getLogger(__name__) +@wp.kernel +def initialize_rng_state( + # input + seed: wp.int32, + # output + state: wp.array(dtype=wp.uint32), +): + env_id = wp.tid() + state[env_id] = wp.rand_init(seed, wp.int32(env_id)) + + class ManagerBasedEnvWarp: """The base environment for the manager-based workflow (experimental fork). diff --git a/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py index ae08913730ef..acba926ea488 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py +++ b/source/isaaclab_experimental/isaaclab_experimental/utils/noise/noise_model.py @@ -12,8 +12,8 @@ Random noise kernels (gaussian, uniform) consume the shared per-env Warp RNG state (``rng_state_wp``) that is set on the config at manager prep time from -``env.rng_state_wp``. See :func:`isaaclab.utils.warp.kernels.initialize_rng_state` for the initialization -pattern. +``env.rng_state_wp``. See :func:`initialize_rng_state` in +``isaaclab_experimental.envs.manager_based_env_warp`` for the initialization pattern. """ from __future__ import annotations diff --git a/source/isaaclab_tasks_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_tasks_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py index 2034ac5f541a..c42cdaa053d7 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py @@ -13,13 +13,24 @@ import warp as wp from isaaclab_experimental.envs import DirectRLEnvWarp -from isaaclab.utils.warp.kernels import initialize_rng_state from isaaclab.utils.warp.math import quat_error_magnitude if TYPE_CHECKING: from isaaclab_tasks.core.reorient.config.allegro_hand.allegro_hand_direct_env_cfg import AllegroHandEnvCfg +@wp.kernel +def initialize_rng_state( + # input + seed: wp.int32, + # output + state: wp.array(dtype=wp.uint32), +): + """Initialize each env's random number generator state from the seed.""" + env_id = wp.tid() + state[env_id] = wp.rand_init(seed, wp.int32(env_id)) + + @wp.kernel def apply_actions_to_targets( # input From 09d7e81d377f9a935a93465cf7786bdacde844b4 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:32:17 -0800 Subject: [PATCH 07/31] Drop the drift resampling kernel tests that the ray-caster reset test covers test_ray_caster_reset_resamples_drift in test_ray_caster_sensor.py already checks the per-axis drift ranges and that a zero range draws zero. --- .../test/sensors/test_ray_caster_kernels.py | 53 +------------------ 1 file changed, 1 insertion(+), 52 deletions(-) diff --git a/source/isaaclab/test/sensors/test_ray_caster_kernels.py b/source/isaaclab/test/sensors/test_ray_caster_kernels.py index 6e104d8fde95..1504115f3ca9 100644 --- a/source/isaaclab/test/sensors/test_ray_caster_kernels.py +++ b/source/isaaclab/test/sensors/test_ray_caster_kernels.py @@ -33,13 +33,8 @@ compute_distance_to_image_plane_to_image_masked_kernel, copy_float2d_to_image1_depth_clipped_masked_kernel, fill_ray_hits_distance_inf_kernel, - resample_drift_masked_kernel, -) -from isaaclab.utils.warp.kernels import ( - initialize_rng_state, - raycast_dynamic_meshes_kernel, - raycast_mesh_masked_kernel, ) +from isaaclab.utils.warp.kernels import raycast_dynamic_meshes_kernel, raycast_mesh_masked_kernel from isaaclab.utils.warp.ops import convert_to_warp_mesh # --------------------------------------------------------------------------- @@ -676,49 +671,3 @@ def test_with_pitch_roll(self): expected = [[0.0, 0.0, math.sin(yaw / 2), math.cos(yaw / 2)] for _, _, yaw in cases] np.testing.assert_allclose(_to_numpy(q_out), expected, atol=ATOL) - - -# --------------------------------------------------------------------------- -# resample_drift_masked_kernel -# --------------------------------------------------------------------------- - - -def _rng_state(num_envs: int = 4, seed: int = 7) -> wp.array: - """Per-environment random states seeded by :func:`initialize_rng_state`.""" - state = wp.empty(num_envs, dtype=wp.uint32, device=DEVICE) - wp.launch(initialize_rng_state, dim=num_envs, inputs=[seed], outputs=[state], device=DEVICE) - return state - - -def _resample_drift(env_mask, drift_range, ray_cast_min, ray_cast_max, rng_state): - """Resample drift buffers that start at -1 and return them as numpy arrays.""" - num_envs = env_mask.shape[0] - drift = wp.array(np.full((num_envs, 3), -1.0, dtype=np.float32), dtype=wp.vec3f, device=DEVICE) - ray_cast_drift = wp.array(np.full((num_envs, 3), -1.0, dtype=np.float32), dtype=wp.vec3f, device=DEVICE) - wp.launch( - resample_drift_masked_kernel, - dim=num_envs, - inputs=[env_mask, wp.vec2f(*drift_range), wp.vec3f(*ray_cast_min), wp.vec3f(*ray_cast_max), rng_state], - outputs=[drift, ray_cast_drift], - device=DEVICE, - ) - wp.synchronize_device(DEVICE) - return drift.numpy(), ray_cast_drift.numpy() - - -class TestResampleDriftMaskedKernel: - """Tests for :func:`resample_drift_masked_kernel`.""" - - def test_draws_stay_in_their_ranges(self): - env_mask = wp.array([True] * 64, dtype=wp.bool, device=DEVICE) - drift, ray_cast_drift = _resample_drift( - env_mask, (-0.5, 0.25), (-0.1, 0.0, 0.3), (0.1, 0.2, 0.4), _rng_state(64) - ) - assert ((drift >= -0.5) & (drift <= 0.25)).all() - assert ((ray_cast_drift >= [-0.1, 0.0, 0.3]) & (ray_cast_drift <= [0.1, 0.2, 0.4])).all() - - def test_zero_range_draws_zero(self): - env_mask = wp.array([True] * 4, dtype=wp.bool, device=DEVICE) - drift, ray_cast_drift = _resample_drift(env_mask, (0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), _rng_state()) - np.testing.assert_array_equal(drift, 0.0) - np.testing.assert_array_equal(ray_cast_drift, 0.0) From b1b963fa2044db52703f5c13afe725721ca4bd1a Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:32:48 -0800 Subject: [PATCH 08/31] Keep the Newton ray-caster partial reset test to the replayed mask The shared mask resolution tests already cover slices and host masks on their way to the drift kernel. --- .../test/sensors/test_newton_raycast_sensor.py | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py index 0e8b4949c2ec..202a75c64131 100644 --- a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py @@ -228,8 +228,8 @@ def test_legacy_multi_mesh_tracks_ad_hoc_regex_target(sim): @pytest.mark.parametrize("sim", [pytest.param(False, id="eager")], indirect=True) -def test_partial_reset_resamples_drift_of_selected_envs_only(sim, monkeypatch): - """Slice, host-mask and replayed masked resets resample the drift of the selected environments only.""" +def test_partial_reset_resamples_drift_of_selected_envs_only(sim): + """A replayed masked reset resamples the drift of the selected environments only.""" scene_cfg = RaycastTestSceneCfg(num_envs=3) scene_cfg.raycast.drift_range = (0.01, 0.05) scene_cfg.raycast.ray_cast_drift_range = {"z": (0.1, 0.2)} @@ -238,11 +238,6 @@ def test_partial_reset_resamples_drift_of_selected_envs_only(sim, monkeypatch): sensor: NewtonRaycastSensor = scene["raycast"] sensor.reset() - drift = sensor.drift.torch.clone() - sensor.reset(env_ids=slice(2, None)) - torch.testing.assert_close(sensor.drift.torch[:2], drift[:2]) - assert not torch.allclose(sensor.drift.torch[2], drift[2]) - # The masked reset records into a CUDA graph without allocating (the disabled memory pool makes an # allocation raise), and every replay draws new drift for the masked environment only. env_mask = wp.array([True, False, False], dtype=wp.bool, device=sensor.device) @@ -259,14 +254,6 @@ def test_partial_reset_resamples_drift_of_selected_envs_only(sim, monkeypatch): assert ((sensor.drift.torch >= 0.01) & (sensor.drift.torch <= 0.05)).all() assert ((sensor.ray_cast_drift.torch[:, 2] >= 0.1) & (sensor.ray_cast_drift.torch[:, 2] <= 0.2)).all() - # A host mask reaches the drift kernel on the sensor device. Strict launches reject a host array that - # GPUs with heterogeneous memory management would otherwise read silently. - monkeypatch.setattr(wp.config, "launch_array_access_mode", wp.config.LaunchArrayAccessMode.STRICT) - drift = sensor.drift.torch.clone() - sensor.reset(env_mask=wp.array([False, True, False], dtype=wp.bool, device="cpu")) - torch.testing.assert_close(sensor.drift.torch[[0, 2]], drift[[0, 2]]) - assert not torch.allclose(sensor.drift.torch[1], drift[1]) - @pytest.mark.parametrize("sim", [pytest.param(False, id="eager")], indirect=True) def test_drift_follows_the_environment_seed(sim): From 1cbb382eeba1976321511d8aca08af928c703b1c Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:33:07 -0800 Subject: [PATCH 09/31] Fold the independent drift check into the drift seeding test The seeding test builds the same scene; a second ray caster seeded alike must draw different drift. --- .../test/sensors/test_newton_raycast_sensor.py | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py index 202a75c64131..3e68f1610b85 100644 --- a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py @@ -260,10 +260,12 @@ def test_drift_follows_the_environment_seed(sim): """An explicit seed, as ``env.reset(seed=...)`` sets, restarts the drift sequence; unseeded resets advance it. Resets do not draw from torch's generator, and new storage, as after a simulation stop and play, starts the - drift sequence of the current seed again. + drift sequence of the current seed again. Two ray casters with the same drift ranges draw different drift: + each mixes its prim path into the seed. """ scene_cfg = RaycastTestSceneCfg(num_envs=2) scene_cfg.raycast.drift_range = (0.01, 0.05) + scene_cfg.raycast_box = replace(scene_cfg.raycast, prim_path="{ENV_REGEX_NS}/Box") scene = InteractiveScene(scene_cfg) sim.reset() sensor: NewtonRaycastSensor = scene["raycast"] @@ -271,6 +273,8 @@ def test_drift_follows_the_environment_seed(sim): configure_seed(123) sensor.reset() first = sensor.drift.torch.clone() + scene["raycast_box"].reset() + assert not torch.allclose(scene["raycast_box"].drift.torch, first) sensor.reset() assert not torch.allclose(sensor.drift.torch, first) configure_seed(123) @@ -454,15 +458,3 @@ def test_renderer_and_raycast_share_backend_with_independent_query_graphs(sim): assert camera._renderer.backend is raycast.backend is sim.backend_manager.backend assert (raycast._graph is not None) == cfg.raycast.use_cuda_graph assert (camera._render_data.graph is not None) == cfg.camera.renderer_cfg.use_cuda_graph - - -@pytest.mark.parametrize("sim", [pytest.param(False, id="eager")], indirect=True) -def test_ray_casters_draw_independent_drift(sim): - """Two ray casters with the same drift ranges draw different drift: each mixes its prim path into the seed.""" - scene_cfg = RaycastTestSceneCfg(num_envs=2) - scene_cfg.raycast.drift_range = (0.01, 0.05) - scene_cfg.raycast_box = replace(scene_cfg.raycast, prim_path="{ENV_REGEX_NS}/Box") - scene = InteractiveScene(scene_cfg) - sim.reset() - scene.reset() - assert not torch.allclose(scene["raycast"].drift.torch, scene["raycast_box"].drift.torch) From 61c5ed593d2a99d297003f8a91d64a7130c23124 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:33:23 -0800 Subject: [PATCH 10/31] Drop the MLP history address assertions The CUDA graph replay test of the MLP masked reset fails when compute moves the history, so the window test checks only the window. --- source/isaaclab/test/actuators/test_actuator_net.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index 478a05562215..ea31c7342fc0 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -105,8 +105,8 @@ def test_mlp_masked_reset_replays_from_a_cuda_graph_while_the_history_moves(tmp_ @pytest.mark.parametrize("device", test_devices()) -def test_mlp_history_keeps_its_address_and_window(tmp_path, device): - """Each compute shifts the history by one step in place: entry i holds the input from i computes ago.""" +def test_mlp_history_keeps_its_window(tmp_path, device): + """Each compute shifts the history by one step: entry i holds the input from i computes ago.""" actuator = _actuator( ActuatorNetMLPCfg, _ZeroTorqueMLP(), @@ -118,11 +118,9 @@ def test_mlp_history_keeps_its_address_and_window(tmp_path, device): torque_scale=1.0, input_order="pos_vel", ) - addresses = (actuator._joint_pos_error_history.data_ptr(), actuator._joint_vel_history.data_ptr()) zeros = torch.zeros(3, 2, device=device) for step in range(5): velocity = torch.full((3, 2), float(step), device=device) actuator.compute(ArticulationActions(joint_positions=zeros), zeros, velocity) - assert (actuator._joint_pos_error_history.data_ptr(), actuator._joint_vel_history.data_ptr()) == addresses expected = torch.tensor([4.0, 3.0, 2.0], device=device).view(1, 3, 1).expand(3, 3, 2) torch.testing.assert_close(actuator._joint_vel_history, expected) From abd4a77c442bfb12bcfbbb817e43823ea97e38d2 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:50:23 -0800 Subject: [PATCH 11/31] Mix the ray-caster creation index into the drift seed Two ray casters on the same prim seeded identical drift states from the prim path alone, so they drew the same drift. Each ray caster now also mixes in its creation index, which it keeps across reseeds and rays re-initialization. --- .../jichuanh-actuator-net-mask-reset.changed.rst | 4 ++-- .../isaaclab/sensors/ray_caster/base_ray_caster.py | 14 ++++++++++---- .../test/sensors/test_newton_raycast_sensor.py | 14 +++++++++----- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index 38f446a10458..c60329c7ed00 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -5,5 +5,5 @@ recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded from the environment seed when the sensor initializes and again by every :func:`~isaaclab.utils.seed.configure_seed`, including the one ``env.reset(seed=...)`` makes, so a seeded reset - repeats the drift and unseeded resets keep advancing it. Drift no longer draws from Torch's generator. The drift - ranges are unchanged; the drawn values differ. + repeats the drift and unseeded resets keep advancing it. Each ray caster draws its own drift. Drift no longer draws + from Torch's generator. The drift ranges are unchanged; the drawn values differ. diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py index 3ebddef2dbad..f55ddcbdda1c 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py @@ -66,6 +66,8 @@ class BaseRayCaster(SensorBase): (e.g. CUDA) when multiple simulation contexts or tests use different devices in the same Python process.""" _instance_count: ClassVar[int] = 0 """A counter to track the number of RayCaster instances, used to manage class variable lifecycle.""" + _num_created: ClassVar[int] = 0 + """The number of ray casters constructed so far; each takes the count as its creation index.""" def __init__(self, cfg: RayCasterCfg): """Initializes the ray-caster object. @@ -79,6 +81,9 @@ def __init__(self, cfg: RayCasterCfg): self._drift_sampled = False # Drift random states, allocated when the rays initialize; every configure_seed reseeds them. self._drift_rng_state: wp.array | None = None + # The scene constructs sensors in config order, so the creation index is stable for a given scene. + self._creation_index = BaseRayCaster._num_created + BaseRayCaster._num_created += 1 add_seed_listener(self._seed_drift) def __str__(self) -> str: @@ -269,10 +274,11 @@ def _initialize_rays_impl(self): self._dummy_ray_normal = wp.empty((1, 1), dtype=wp.vec3f, device=self._device) def _seed_drift(self, seed: int) -> None: - """Seed the drift random states from ``seed`` mixed with the prim path, so each ray caster draws its own drift. + """Seed the drift random states from ``seed`` mixed with the prim path and the creation index. - Runs when the rays initialize and on every :func:`~isaaclab.utils.seed.configure_seed`, on the host where - the seed is set, never inside a recorded reset. + Each ray caster draws its own drift, including ray casters mounted on the same prim. Runs when the rays + initialize and on every :func:`~isaaclab.utils.seed.configure_seed`, on the host where the seed is set, never + inside a recorded reset. """ # No states before the rays initialize, and none in the ray-caster cameras, which do not resample drift. if self._drift_rng_state is None: @@ -280,7 +286,7 @@ def _seed_drift(self, seed: int) -> None: wp.launch( initialize_rng_state, dim=self._view_count, - inputs=[(seed ^ zlib.crc32(self.cfg.prim_path.encode())) & 0x7FFFFFFF], + inputs=[(seed ^ zlib.crc32(self.cfg.prim_path.encode()) ^ self._creation_index) & 0x7FFFFFFF], outputs=[self._drift_rng_state], device=self._device, ) diff --git a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py index 3e68f1610b85..6dc3b5cc0c56 100644 --- a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py @@ -260,27 +260,31 @@ def test_drift_follows_the_environment_seed(sim): """An explicit seed, as ``env.reset(seed=...)`` sets, restarts the drift sequence; unseeded resets advance it. Resets do not draw from torch's generator, and new storage, as after a simulation stop and play, starts the - drift sequence of the current seed again. Two ray casters with the same drift ranges draw different drift: - each mixes its prim path into the seed. + drift sequence of the current seed again. Two ray casters on the same prim with the same drift ranges draw + different drift after every seed. """ scene_cfg = RaycastTestSceneCfg(num_envs=2) scene_cfg.raycast.drift_range = (0.01, 0.05) - scene_cfg.raycast_box = replace(scene_cfg.raycast, prim_path="{ENV_REGEX_NS}/Box") + twin_offset = NewtonRaycastSensorCfg.OffsetCfg(pos=(0.1, 0.0, -RAY_OFFSET)) + scene_cfg.raycast_twin = replace(scene_cfg.raycast, offset=twin_offset) scene = InteractiveScene(scene_cfg) sim.reset() sensor: NewtonRaycastSensor = scene["raycast"] + twin: NewtonRaycastSensor = scene["raycast_twin"] configure_seed(123) sensor.reset() first = sensor.drift.torch.clone() - scene["raycast_box"].reset() - assert not torch.allclose(scene["raycast_box"].drift.torch, first) + twin.reset() + assert not torch.allclose(twin.drift.torch, first) sensor.reset() assert not torch.allclose(sensor.drift.torch, first) configure_seed(123) state = torch.cuda.get_rng_state(sensor.device) sensor.reset() torch.testing.assert_close(sensor.drift.torch, first) + twin.reset() + assert not torch.allclose(twin.drift.torch, first) sensor._initialize_rays_impl() sensor.reset() torch.testing.assert_close(sensor.drift.torch, first) From e7c807e32264f46e425753285f3c9e9cffde5123 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:55:54 -0800 Subject: [PATCH 12/31] Seed each ray caster's drift from its configuration, not its creation order A process-wide creation index made a ray caster's drift depend on how many ray casters the process built before it, so a second environment instance with the same seed drew different drift. Each ray caster now hashes its configuration (callables written by name) into its drift seed, which repeats across processes and instances; ray casters on one prim at different offsets still draw different drift. --- ...ichuanh-actuator-net-mask-reset.changed.rst | 5 +++-- .../sensors/ray_caster/base_ray_caster.py | 18 ++++++++---------- .../test/sensors/test_newton_raycast_sensor.py | 6 +++++- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index c60329c7ed00..ffa8ce2dc109 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -5,5 +5,6 @@ recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded from the environment seed when the sensor initializes and again by every :func:`~isaaclab.utils.seed.configure_seed`, including the one ``env.reset(seed=...)`` makes, so a seeded reset - repeats the drift and unseeded resets keep advancing it. Each ray caster draws its own drift. Drift no longer draws - from Torch's generator. The drift ranges are unchanged; the drawn values differ. + repeats the drift and unseeded resets keep advancing it. Ray casters with different configurations draw different + drift; identical configurations draw the same drift. Drift no longer draws from Torch's generator. The drift ranges + are unchanged; the drawn values differ. diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py index f55ddcbdda1c..e3594b99209e 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py @@ -5,6 +5,7 @@ from __future__ import annotations +import json import logging import zlib from collections.abc import Sequence @@ -66,8 +67,6 @@ class BaseRayCaster(SensorBase): (e.g. CUDA) when multiple simulation contexts or tests use different devices in the same Python process.""" _instance_count: ClassVar[int] = 0 """A counter to track the number of RayCaster instances, used to manage class variable lifecycle.""" - _num_created: ClassVar[int] = 0 - """The number of ray casters constructed so far; each takes the count as its creation index.""" def __init__(self, cfg: RayCasterCfg): """Initializes the ray-caster object. @@ -81,9 +80,8 @@ def __init__(self, cfg: RayCasterCfg): self._drift_sampled = False # Drift random states, allocated when the rays initialize; every configure_seed reseeds them. self._drift_rng_state: wp.array | None = None - # The scene constructs sensors in config order, so the creation index is stable for a given scene. - self._creation_index = BaseRayCaster._num_created - BaseRayCaster._num_created += 1 + # A drift stream from the configuration, which writes callables by name, so it repeats across processes. + self._drift_stream = zlib.crc32(json.dumps(self.cfg.to_dict(), sort_keys=True, default=str).encode()) add_seed_listener(self._seed_drift) def __str__(self) -> str: @@ -274,11 +272,11 @@ def _initialize_rays_impl(self): self._dummy_ray_normal = wp.empty((1, 1), dtype=wp.vec3f, device=self._device) def _seed_drift(self, seed: int) -> None: - """Seed the drift random states from ``seed`` mixed with the prim path and the creation index. + """Seed the drift random states from ``seed`` mixed with the configuration's drift stream. - Each ray caster draws its own drift, including ray casters mounted on the same prim. Runs when the rays - initialize and on every :func:`~isaaclab.utils.seed.configure_seed`, on the host where the seed is set, never - inside a recorded reset. + Ray casters with different configurations, including ray casters on one prim at different offsets, draw + different drift; identical configurations draw the same drift. Runs when the rays initialize and on every + :func:`~isaaclab.utils.seed.configure_seed`, on the host where the seed is set, never inside a recorded reset. """ # No states before the rays initialize, and none in the ray-caster cameras, which do not resample drift. if self._drift_rng_state is None: @@ -286,7 +284,7 @@ def _seed_drift(self, seed: int) -> None: wp.launch( initialize_rng_state, dim=self._view_count, - inputs=[(seed ^ zlib.crc32(self.cfg.prim_path.encode()) ^ self._creation_index) & 0x7FFFFFFF], + inputs=[(seed ^ self._drift_stream) & 0x7FFFFFFF], outputs=[self._drift_rng_state], device=self._device, ) diff --git a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py index 6dc3b5cc0c56..ef0822648121 100644 --- a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py @@ -261,12 +261,14 @@ def test_drift_follows_the_environment_seed(sim): Resets do not draw from torch's generator, and new storage, as after a simulation stop and play, starts the drift sequence of the current seed again. Two ray casters on the same prim with the same drift ranges draw - different drift after every seed. + different drift after every seed, and a ray caster built later with the same configuration, as in a second + environment instance, repeats the drift. """ scene_cfg = RaycastTestSceneCfg(num_envs=2) scene_cfg.raycast.drift_range = (0.01, 0.05) twin_offset = NewtonRaycastSensorCfg.OffsetCfg(pos=(0.1, 0.0, -RAY_OFFSET)) scene_cfg.raycast_twin = replace(scene_cfg.raycast, offset=twin_offset) + scene_cfg.raycast_copy = scene_cfg.raycast.copy() scene = InteractiveScene(scene_cfg) sim.reset() sensor: NewtonRaycastSensor = scene["raycast"] @@ -277,6 +279,8 @@ def test_drift_follows_the_environment_seed(sim): first = sensor.drift.torch.clone() twin.reset() assert not torch.allclose(twin.drift.torch, first) + scene["raycast_copy"].reset() + torch.testing.assert_close(scene["raycast_copy"].drift.torch, first) sensor.reset() assert not torch.allclose(sensor.drift.torch, first) configure_seed(123) From 19701d9581f117e49bc1e0e56c2215865695449f Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Wed, 18 Nov 2026 09:45:00 -0800 Subject: [PATCH 13/31] Use the shared RNG seeding kernel in the Warp reorient environment The reorient environment kept its own copy of initialize_rng_state; it now imports the one in isaaclab.utils.warp.kernels. --- .../jichuanh-actuator-net-mask-reset.skip | 0 .../core/reorient/reorient_warp_env.py | 13 +------------ 2 files changed, 1 insertion(+), 12 deletions(-) create mode 100644 source/isaaclab_tasks_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip diff --git a/source/isaaclab_tasks_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip b/source/isaaclab_tasks_experimental/changelog.d/jichuanh-actuator-net-mask-reset.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py index c42cdaa053d7..2034ac5f541a 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py @@ -13,24 +13,13 @@ import warp as wp from isaaclab_experimental.envs import DirectRLEnvWarp +from isaaclab.utils.warp.kernels import initialize_rng_state from isaaclab.utils.warp.math import quat_error_magnitude if TYPE_CHECKING: from isaaclab_tasks.core.reorient.config.allegro_hand.allegro_hand_direct_env_cfg import AllegroHandEnvCfg -@wp.kernel -def initialize_rng_state( - # input - seed: wp.int32, - # output - state: wp.array(dtype=wp.uint32), -): - """Initialize each env's random number generator state from the seed.""" - env_id = wp.tid() - state[env_id] = wp.rand_init(seed, wp.int32(env_id)) - - @wp.kernel def apply_actions_to_targets( # input From 6c27eb313a7bb4e6677222c6a9eef26fdc87f726 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 22 Nov 2026 23:57:13 -0800 Subject: [PATCH 14/31] Keep the ActuatorNetMLP history in Warp and run its network with Warp-NN --- pyproject.toml | 1 + ...chuanh-actuator-net-mask-reset.changed.rst | 9 +- .../isaaclab/actuators/actuator_net.py | 167 +++++++++++------- .../test/actuators/test_actuator_net.py | 135 ++++++++++---- uv.lock | 32 ++-- 5 files changed, 231 insertions(+), 113 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 8f20b74dcc18..9ee586dab430 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,6 +47,7 @@ dependencies = [ "transformers==5.10.4", "einops", "warp-lang==1.17.0", + "warp-nn>=0.4.1", "matplotlib>=3.10.3", # pillow: floor, not exact — an exact pin below Isaac Sim's prebundled version forces a # downgrade that deletes the prebundled copy other extensions symlink into (nvbugs 6410989). diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index ffa8ce2dc109..95eba0b5f032 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -1,6 +1,9 @@ -* Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` to clear - the state of the environments a boolean Warp mask selects with a Warp kernel, so a reset recorded in a CUDA graph - clears it on every replay. :class:`~isaaclab.actuators.ActuatorNetMLP` updates its history buffers in place. +* Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` to reset by a + Warp kernel when given an environment mask, so a CUDA graph can record the reset. +* Changed :class:`~isaaclab.actuators.ActuatorNetMLP` to run its network with Warp-NN, a new dependency, on an ONNX + export of the TorchScript network made when the actuator loads; the network must export to operators that Warp-NN + supports. One Warp kernel updates the joint history and writes the network input, so a CUDA graph can record the + whole torque computation. * Changed the ray-caster drift resampling on reset to draw from per-environment Warp random states, so a reset recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded from the environment seed when the sensor initializes and again by every diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 6a955d360cbf..8019eaec2fb5 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -14,11 +14,13 @@ from __future__ import annotations +import io from collections.abc import Sequence from typing import TYPE_CHECKING import torch import warp as wp +from warp_nn.runtime import OnnxRuntime from ..utils import index_fill_ from ..utils.assets import read_file @@ -74,16 +76,14 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: if env_mask is not None: - # a mask resets with a Warp launch, which a CUDA graph recording of the reset holds for state in (self.sea_hidden_state_per_env, self.sea_cell_state_per_env): - for layer in state: - values = wp.from_torch(layer.view(self._num_envs, -1)) - wp.launch( - make_masked_fill(wp.float32, 2), - dim=values.shape, - inputs=[0.0, env_mask, None, values], - device=self._device, - ) + values = wp.from_torch(state.flatten(2)) + wp.launch( + make_masked_fill(values.dtype, 3), + dim=values.shape, + inputs=[0.0, None, env_mask, values], + device=self._device, + ) return # reset the hidden and cell states for the specified environments with torch.no_grad(): @@ -114,6 +114,48 @@ def compute( return control_action +@wp.func +def _push_newest(history: wp.array3d(dtype=wp.float32), env_id: int, joint: int, sample: wp.float32): + """Move the history of one (env, joint) back by one step and write ``sample`` as its newest entry.""" + for t in range(history.shape[1] - 1): + k = history.shape[1] - 1 - t + history[env_id, k, joint] = history[env_id, k - 1, joint] + history[env_id, 0, joint] = sample + + +@wp.kernel(enable_backward=False) +def _update_mlp_history( + # input + joint_pos_target: wp.array2d(dtype=wp.float32), + joint_pos: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + history_indices: wp.array(dtype=wp.int32), + pos_scale: wp.float32, + vel_scale: wp.float32, + pos_first: bool, + # output + joint_pos_error_history: wp.array3d(dtype=wp.float32), + joint_vel_history: wp.array3d(dtype=wp.float32), + network_input: wp.array2d(dtype=wp.float32), +): + """Record the newest joint position error and velocity, then write the scaled samples the network reads. + + Each row of ``network_input`` belongs to one (env, joint): its position errors, then its velocities when + ``pos_first``, otherwise the reverse. Launch with ``dim=(num_envs, num_joints)``. + """ + env_id, joint = wp.tid() + _push_newest(joint_pos_error_history, env_id, joint, joint_pos_target[env_id, joint] - joint_pos[env_id, joint]) + _push_newest(joint_vel_history, env_id, joint, joint_vel[env_id, joint]) + num_samples = history_indices.shape[0] + row = env_id * joint_pos.shape[1] + joint + pos_column = wp.where(pos_first, 0, num_samples) + vel_column = num_samples - pos_column + for i in range(num_samples): + index = history_indices[i] + network_input[row, pos_column + i] = pos_scale * joint_pos_error_history[env_id, index, joint] + network_input[row, vel_column + i] = vel_scale * joint_vel_history[env_id, index, joint] + + class ActuatorNetMLP(DCMotor): """Actuator model based on multi-layer perceptron and joint history. @@ -141,74 +183,81 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") super().__init__(cfg, *args, **kwargs) + history_length = max(self.cfg.input_idx) + 1 + if min(self.cfg.input_idx) < -history_length: + raise IndexError(f"MLP actuator history indices must be at least {-history_length}.") + if self.cfg.input_order not in ("pos_vel", "vel_pos"): + raise ValueError( + f"Invalid input order for MLP actuator net: {self.cfg.input_order}. Must be 'pos_vel' or 'vel_pos'." + ) + # the history samples the network reads; negative indices count back from the oldest sample + indices = [index % history_length for index in self.cfg.input_idx] + # load the model from JIT file file_bytes = read_file(self.cfg.network_file) self.network = torch.jit.load(file_bytes, map_location=self._device).eval() - - # create buffers for MLP history - history_length = max(self.cfg.input_idx) + 1 - self._joint_pos_error_history = torch.zeros( - self._num_envs, history_length, self.num_joints, device=self._device - ) - self._joint_vel_history = torch.zeros(self._num_envs, history_length, self.num_joints, device=self._device) - # each history shifts through a scratch buffer and is copied back, so it stays at one address - self._history_scratch = torch.zeros_like(self._joint_pos_error_history) - self._history_shift = torch.tensor( - [(i - 1) % history_length for i in range(history_length)], device=self._device + # run it with Warp-NN, through an ONNX export in memory, so that a CUDA graph can record the inference + model = io.BytesIO() + torch.onnx.export( + self.network, + (torch.zeros(1, 2 * len(indices), device=self._device),), + model, + input_names=["input"], + output_names=["torque"], + dynamic_axes={"input": {0: "batch"}, "torque": {0: "batch"}}, + dynamo=False, ) + model.seek(0) + self._runtime = OnnxRuntime(model, device=self._device) + + # create buffers for MLP history, newest sample first + history_shape = (self._num_envs, history_length, self.num_joints) + self._joint_pos_error_history = wp.zeros(history_shape, dtype=wp.float32, device=self._device) + self._joint_vel_history = wp.zeros(history_shape, dtype=wp.float32, device=self._device) + self._history_indices = wp.array(indices, dtype=wp.int32, device=self._device) + # the network input, one row per (env, joint), and the network outputs it allocates once + input_shape = (self._num_envs * self.num_joints, 2 * len(indices)) + self._network_input = wp.zeros(input_shape, dtype=wp.float32, device=self._device) + self._runtime.prepare({"input": self._network_input}) """ Operations. """ def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: - if env_mask is not None: - # a mask resets with a Warp launch, which a CUDA graph recording of the reset holds - for history in (self._joint_pos_error_history, self._joint_vel_history): - values = wp.from_torch(history.view(self._num_envs, -1)) + # reset the history for the specified environments + for history in (self._joint_pos_error_history, self._joint_vel_history): + if env_mask is not None: wp.launch( - make_masked_fill(wp.float32, 2), - dim=values.shape, - inputs=[0.0, env_mask, None, values], + make_masked_fill(history.dtype, 3), + dim=history.shape, + inputs=[0.0, env_mask, None, history], device=self._device, ) - return - # reset the history for the specified environments - index_fill_(self._joint_pos_error_history, env_ids, 0.0) - index_fill_(self._joint_vel_history, env_ids, 0.0) + else: + index_fill_(wp.to_torch(history), env_ids, 0.0) def compute( self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor ) -> ArticulationActions: - # move history queue by 1 and update top of history - # -- positions - torch.index_select(self._joint_pos_error_history, 1, self._history_shift, out=self._history_scratch) - self._joint_pos_error_history.copy_(self._history_scratch) - self._joint_pos_error_history[:, 0] = control_action.joint_positions - joint_pos - # -- velocity - torch.index_select(self._joint_vel_history, 1, self._history_shift, out=self._history_scratch) - self._joint_vel_history.copy_(self._history_scratch) - self._joint_vel_history[:, 0] = joint_vel - # compute network inputs - # -- positions - pos_input = torch.cat([self._joint_pos_error_history[:, i].unsqueeze(2) for i in self.cfg.input_idx], dim=2) - pos_input = pos_input.view(self._num_envs * self.num_joints, -1) - # -- velocity - vel_input = torch.cat([self._joint_vel_history[:, i].unsqueeze(2) for i in self.cfg.input_idx], dim=2) - vel_input = vel_input.view(self._num_envs * self.num_joints, -1) - # -- scale and concatenate inputs - if self.cfg.input_order == "pos_vel": - network_input = torch.cat([pos_input * self.cfg.pos_scale, vel_input * self.cfg.vel_scale], dim=1) - elif self.cfg.input_order == "vel_pos": - network_input = torch.cat([vel_input * self.cfg.vel_scale, pos_input * self.cfg.pos_scale], dim=1) - else: - raise ValueError( - f"Invalid input order for MLP actuator net: {self.cfg.input_order}. Must be 'pos_vel' or 'vel_pos'." - ) - + # move history queue by 1, update top of history and write the scaled network input + wp.launch( + _update_mlp_history, + dim=(self._num_envs, self.num_joints), + inputs=[ + wp.from_torch(control_action.joint_positions), + wp.from_torch(joint_pos), + wp.from_torch(joint_vel), + self._history_indices, + self.cfg.pos_scale, + self.cfg.vel_scale, + self.cfg.input_order == "pos_vel", + ], + outputs=[self._joint_pos_error_history, self._joint_vel_history, self._network_input], + device=self._device, + ) # run network inference - with torch.inference_mode(): - torques = self.network(network_input).view(self._num_envs, self.num_joints) + torques = wp.to_torch(self._runtime({"input": self._network_input})["torque"]) self.computed_effort = torques.view(self._num_envs, self.num_joints) * self.cfg.torque_scale # clip the computed effort based on the motor limits diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index ea31c7342fc0..746d94f17921 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -30,11 +30,13 @@ def forward( return torch.zeros(x.shape[0], 1, device=x.device), hc -class _ZeroTorqueMLP(torch.nn.Module): - """MLP-shaped network that requests no torque.""" - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return torch.zeros(x.shape[0], 1, device=x.device) +def _feature_torque_mlp(num_features: int) -> torch.nn.Linear: + """A linear network that gives every packed history feature a distinct weight in the requested torque.""" + network = torch.nn.Linear(num_features, 1) + with torch.no_grad(): + network.weight.copy_(torch.arange(1.0, num_features + 1).unsqueeze(0)) + network.bias.zero_() + return network def _actuator(cfg_class, network: torch.nn.Module, tmp_path, device: str, **cfg): @@ -80,47 +82,108 @@ def test_lstm_masked_reset_replays_from_a_cuda_graph(tmp_path, device): @pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) def test_mlp_masked_reset_replays_from_a_cuda_graph_while_the_history_moves(tmp_path, device): - """The history shifts every compute; the recorded reset still clears the masked environments of it.""" - actuator = _actuator( - ActuatorNetMLPCfg, - _ZeroTorqueMLP(), - tmp_path, - device, - input_idx=[0, 1, 2], + """A recorded reset changes the next computed torque only for the environments in its current mask.""" + torch_stream = torch.cuda.Stream(device=device) + stream = wp.stream_from_torch(torch_stream) + with torch.cuda.stream(torch_stream), wp.ScopedStream(stream): + actuator = _actuator( + ActuatorNetMLPCfg, + _feature_torque_mlp(6), + tmp_path, + device, + input_idx=[0, 1, 2], + pos_scale=1.0, + vel_scale=1.0, + torque_scale=1.0, + input_order="pos_vel", + ) + mask = torch.tensor([True, False, True], device=device) + capture_stream = wp.Stream(device=device) + # The reset belongs to the Warp capture even though Torch is on a different stream. + capture_stream.wait_stream(stream) + with wp.ScopedStream(capture_stream, sync_enter=False): + graph = _record_masked_reset(actuator, wp.from_torch(mask)) + zeros = torch.zeros(3, 2, device=device) + ones = torch.ones_like(zeros) + for _ in range(3): + # Fill the history with ones before replaying the same reset graph with a different mask. + for _ in range(3): + actuator.compute(ArticulationActions(joint_positions=ones), zeros, ones) + mask.logical_not_() + capture_stream.wait_stream(stream) + wp.capture_launch(graph, stream=capture_stream) + stream.wait_stream(capture_stream) + actuator.compute(ArticulationActions(joint_positions=zeros), zeros, zeros) + # The new sample is zero. The two older samples contribute 2 + 3 + 5 + 6 when kept. + expected = torch.where(mask, 0.0, 16.0).unsqueeze(1).expand(-1, 2) + torch.testing.assert_close(actuator.computed_effort, expected) + + +def test_mlp_rejects_invalid_history_before_loading_checkpoint(tmp_path): + """The configured history error takes precedence over checkpoint I/O.""" + cfg = ActuatorNetMLPCfg( + joint_names_expr=["joint_.*"], + network_file=str(tmp_path / "missing-network.pt"), + saturation_effort=120.0, + actuator_effort_limit=80.0, + actuator_velocity_limit=7.5, + input_idx=[0, -2], pos_scale=1.0, vel_scale=1.0, torque_scale=1.0, input_order="pos_vel", ) - mask = wp.array([True, False, True], dtype=wp.bool, device=device) - graph = _record_masked_reset(actuator, mask) - zeros = torch.zeros(3, 2, device=device) - for _ in range(3): - actuator.compute(ArticulationActions(joint_positions=zeros), zeros, zeros) - actuator._joint_pos_error_history.fill_(1.0) - actuator._joint_vel_history.fill_(1.0) - wp.capture_launch(graph) - _assert_masked_zero(actuator._joint_pos_error_history, env_dim=0) - _assert_masked_zero(actuator._joint_vel_history, env_dim=0) + with pytest.raises(IndexError, match="MLP actuator history indices"): + instantiate(cfg, joint_names=["joint_0", "joint_1"], joint_ids=[0, 1], num_envs=3, device="cpu") @pytest.mark.parametrize("device", test_devices()) -def test_mlp_history_keeps_its_window(tmp_path, device): - """Each compute shifts the history by one step: entry i holds the input from i computes ago.""" +@pytest.mark.parametrize("input_idx,input_order", [([0, 1, 2], "pos_vel"), ([3, 0, -2, 3], "vel_pos")]) +def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order): + """Computed torque follows the selected zero-padded history across wraparound and partial resets.""" + network = _feature_torque_mlp(2 * len(input_idx)) actuator = _actuator( ActuatorNetMLPCfg, - _ZeroTorqueMLP(), + network, tmp_path, device, - input_idx=[0, 1, 2], - pos_scale=1.0, - vel_scale=1.0, - torque_scale=1.0, - input_order="pos_vel", + input_idx=input_idx, + pos_scale=-0.3, + vel_scale=1.25, + torque_scale=0.5, + input_order=input_order, ) - zeros = torch.zeros(3, 2, device=device) - for step in range(5): - velocity = torch.full((3, 2), float(step), device=device) - actuator.compute(ArticulationActions(joint_positions=zeros), zeros, velocity) - expected = torch.tensor([4.0, 3.0, 2.0], device=device).view(1, 3, 1).expand(3, 3, 2) - torch.testing.assert_close(actuator._joint_vel_history, expected) + network = network.to(device) + length = max(input_idx) + 1 + position_history = torch.zeros(3, length, 2, device=device) + velocity_history = torch.zeros_like(position_history) + joints = torch.arange(6.0, device=device).reshape(3, 2) + pos_scale, vel_scale = -0.3, 1.25 + for step in range(8): + if step == 3: + actuator.reset(env_ids=torch.tensor([0, 2], dtype=torch.int32, device=device)) + position_history[[0, 2]] = 0.0 + velocity_history[[0, 2]] = 0.0 + elif step == 5: + actuator.reset(env_ids=slice(1, None)) + position_history[1:] = 0.0 + velocity_history[1:] = 0.0 + elif step == 6: + pos_scale, vel_scale = 0.6, -0.75 + actuator.cfg.pos_scale, actuator.cfg.vel_scale = pos_scale, vel_scale + position = joints * 0.1 + step * 0.05 + desired = position + joints * 0.03 + step * 0.07 + velocity = joints * 0.2 - step * 0.03 + position_history = position_history.roll(1, 1) + velocity_history = velocity_history.roll(1, 1) + position_history[:, 0] = desired - position + velocity_history[:, 0] = velocity + pos_features = torch.stack([position_history[:, index] for index in input_idx], dim=2).reshape(6, -1) + vel_features = torch.stack([velocity_history[:, index] for index in input_idx], dim=2).reshape(6, -1) + if input_order == "pos_vel": + features = torch.cat([pos_features * pos_scale, vel_features * vel_scale], dim=1) + else: + features = torch.cat([vel_features * vel_scale, pos_features * pos_scale], dim=1) + expected = network(features).detach().reshape(3, 2) * 0.5 + actuator.compute(ArticulationActions(joint_positions=desired), position, velocity) + torch.testing.assert_close(actuator.computed_effort, expected) diff --git a/uv.lock b/uv.lock index 15161ac8e229..6a9a0d7d27eb 100644 --- a/uv.lock +++ b/uv.lock @@ -1795,16 +1795,16 @@ source = { editable = "source/isaaclab_assets" } dependencies = [ { name = "isaaclab" }, { name = "isaaclab-contrib" }, - { name = "isaaclab-newton" }, { name = "isaaclab-isaacsim" }, + { name = "isaaclab-newton" }, ] [package.metadata] requires-dist = [ { name = "isaaclab", editable = "source/isaaclab" }, { name = "isaaclab-contrib", editable = "source/isaaclab_contrib" }, - { name = "isaaclab-newton", editable = "source/isaaclab_newton" }, { name = "isaaclab-isaacsim", editable = "source/isaaclab_isaacsim" }, + { name = "isaaclab-newton", editable = "source/isaaclab_newton" }, ] [[package]] @@ -1840,9 +1840,9 @@ dependencies = [ { name = "isaaclab-assets" }, { name = "isaaclab-contrib" }, { name = "isaaclab-experimental" }, + { name = "isaaclab-isaacsim" }, { name = "isaaclab-newton" }, { name = "isaaclab-ov" }, - { name = "isaaclab-isaacsim" }, { name = "isaaclab-ppisp" }, { name = "isaaclab-rl" }, { name = "isaaclab-tasks" }, @@ -1885,6 +1885,7 @@ dependencies = [ { name = "urllib3" }, { name = "usd-exchange" }, { name = "warp-lang" }, + { name = "warp-nn" }, ] [package.optional-dependencies] @@ -2075,11 +2076,11 @@ requires-dist = [ { name = "isaaclab-dev", extras = ["sb3", "skrl", "rl-games", "rsl-rl", "viser", "rerun", "ov"], marker = "extra == 'all'" }, { name = "isaaclab-dev", extras = ["test"], marker = "extra == 'dev'" }, { name = "isaaclab-experimental", editable = "source/isaaclab_experimental" }, + { name = "isaaclab-isaacsim", editable = "source/isaaclab_isaacsim" }, { name = "isaaclab-mimic", marker = "extra == 'mimic'", editable = "source/isaaclab_mimic" }, { name = "isaaclab-mimic", marker = "extra == 'teleop'", editable = "source/isaaclab_mimic" }, { name = "isaaclab-newton", editable = "source/isaaclab_newton" }, { name = "isaaclab-ov", editable = "source/isaaclab_ov" }, - { name = "isaaclab-isaacsim", editable = "source/isaaclab_isaacsim" }, { name = "isaaclab-ppisp", editable = "source/isaaclab_ppisp" }, { name = "isaaclab-rl", editable = "source/isaaclab_rl" }, { name = "isaaclab-tasks", editable = "source/isaaclab_tasks" }, @@ -2177,6 +2178,7 @@ requires-dist = [ { name = "viser", marker = "extra == 'viser'", specifier = ">=1.0.16" }, { name = "wandb", marker = "extra == 'wandb'", specifier = ">=0.13.11" }, { name = "warp-lang", specifier = "==1.17.0" }, + { name = "warp-nn", specifier = ">=0.4.1" }, ] provides-extras = ["tetrahedralization", "video", "optix", "importers", "test", "dev", "sb3", "skrl", "skrl-jax", "rl-games", "wandb", "rsl-rl", "torchrl", "viser", "rerun", "isaacsim", "ov", "ovphysx", "ovrtx", "mimic", "teleop", "ovxr", "rlinf", "leapp", "all"] @@ -2195,6 +2197,17 @@ requires-dist = [ { name = "isaaclab-newton", editable = "source/isaaclab_newton" }, ] +[[package]] +name = "isaaclab-isaacsim" +version = "13.2.0" +source = { editable = "source/isaaclab_isaacsim" } +dependencies = [ + { name = "isaaclab" }, +] + +[package.metadata] +requires-dist = [{ name = "isaaclab", editable = "source/isaaclab" }] + [[package]] name = "isaaclab-mimic" version = "2.1.7" @@ -2238,17 +2251,6 @@ requires-dist = [ { name = "ovstage", specifier = "==0.4.0.1794520352" }, ] -[[package]] -name = "isaaclab-isaacsim" -version = "13.2.0" -source = { editable = "source/isaaclab_isaacsim" } -dependencies = [ - { name = "isaaclab" }, -] - -[package.metadata] -requires-dist = [{ name = "isaaclab", editable = "source/isaaclab" }] - [[package]] name = "isaaclab-ppisp" version = "0.3.2" From 0ef4971028a75771be62f5ac031e3ca5d039c8bd Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 22 Nov 2026 22:39:41 -0800 Subject: [PATCH 15/31] Load the MLP actuator network from an ONNX file or a TorchScript file --- ...jichuanh-actuator-net-mask-reset.added.rst | 2 + ...chuanh-actuator-net-mask-reset.changed.rst | 7 ++- .../isaaclab/actuators/actuator_net.py | 27 ++++----- .../isaaclab/actuators/actuator_net_cfg.py | 3 +- .../isaaclab/isaaclab/utils/io/__init__.pyi | 2 + source/isaaclab/isaaclab/utils/io/onnx.py | 55 +++++++++++++++++++ .../test/actuators/test_actuator_net.py | 29 ++++++++-- 7 files changed, 100 insertions(+), 25 deletions(-) create mode 100644 source/isaaclab/isaaclab/utils/io/onnx.py diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst index 2fb21a09b811..9a0fb2194333 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst @@ -3,3 +3,5 @@ * Added :func:`~isaaclab.utils.seed.add_seed_listener`, which calls a bound method with the seed on every :func:`~isaaclab.utils.seed.configure_seed`, so random states kept outside the global generators follow an explicit seed such as ``env.reset(seed=...)``. +* Added :func:`~isaaclab.utils.io.load_onnx_model`, which loads a network file as an ONNX model: an ONNX file as it + is, or a TorchScript module exported to ONNX in memory. diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index 95eba0b5f032..a174daff22fc 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -1,8 +1,9 @@ * Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` to reset by a Warp kernel when given an environment mask, so a CUDA graph can record the reset. -* Changed :class:`~isaaclab.actuators.ActuatorNetMLP` to run its network with Warp-NN, a new dependency, on an ONNX - export of the TorchScript network made when the actuator loads; the network must export to operators that Warp-NN - supports. One Warp kernel updates the joint history and writes the network input, so a CUDA graph can record the +* Changed :class:`~isaaclab.actuators.ActuatorNetMLP` to run its network with Warp-NN, a new dependency. The network + file may be an ONNX model, read as it is, or a TorchScript module, exported to ONNX when the actuator loads; the + network must use operators that Warp-NN supports. ``network`` is now the Warp-NN runtime instead of the TorchScript + module. One Warp kernel updates the joint history and writes the network input, so a CUDA graph can record the whole torque computation. * Changed the ray-caster drift resampling on reset to draw from per-environment Warp random states, so a reset recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 8019eaec2fb5..280dc4e2211f 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -14,7 +14,6 @@ from __future__ import annotations -import io from collections.abc import Sequence from typing import TYPE_CHECKING @@ -24,6 +23,7 @@ from ..utils import index_fill_ from ..utils.assets import read_file +from ..utils.io import load_onnx_model from ..utils.types import ArticulationActions from ..utils.warp.memory import make_masked_fill from .actuator_pd import DCMotor @@ -168,7 +168,7 @@ class ActuatorNetMLP(DCMotor): This class implements the learned model as a neural network based on the work from :cite:t:`hwangbo2019learning`. The class stores the history of the joint positions errors and velocities which are used to provide input to the neural network. The model is loaded - as a TorchScript. + from an ONNX file, or from a TorchScript file exported to ONNX, and runs with Warp-NN. Note: Only the desired joint positions are used as inputs to the network. @@ -193,22 +193,19 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): # the history samples the network reads; negative indices count back from the oldest sample indices = [index % history_length for index in self.cfg.input_idx] - # load the model from JIT file - file_bytes = read_file(self.cfg.network_file) - self.network = torch.jit.load(file_bytes, map_location=self._device).eval() - # run it with Warp-NN, through an ONNX export in memory, so that a CUDA graph can record the inference - model = io.BytesIO() - torch.onnx.export( - self.network, + # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference + model = load_onnx_model( + self.cfg.network_file, (torch.zeros(1, 2 * len(indices), device=self._device),), - model, + device=self._device, input_names=["input"], output_names=["torque"], dynamic_axes={"input": {0: "batch"}, "torque": {0: "batch"}}, - dynamo=False, ) - model.seek(0) - self._runtime = OnnxRuntime(model, device=self._device) + self.network = OnnxRuntime(model, device=self._device) + # an ONNX file keeps the input and output names it was exported with + self._network_input_name = self.network.inputs[0].name + self._network_output_name = self.network.outputs[0].name # create buffers for MLP history, newest sample first history_shape = (self._num_envs, history_length, self.num_joints) @@ -218,7 +215,7 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): # the network input, one row per (env, joint), and the network outputs it allocates once input_shape = (self._num_envs * self.num_joints, 2 * len(indices)) self._network_input = wp.zeros(input_shape, dtype=wp.float32, device=self._device) - self._runtime.prepare({"input": self._network_input}) + self.network.prepare({self._network_input_name: self._network_input}) """ Operations. @@ -257,7 +254,7 @@ def compute( device=self._device, ) # run network inference - torques = wp.to_torch(self._runtime({"input": self._network_input})["torque"]) + torques = wp.to_torch(self.network({self._network_input_name: self._network_input})[self._network_output_name]) self.computed_effort = torques.view(self._num_envs, self.num_joints) * self.cfg.torque_scale # clip the computed effort based on the motor limits diff --git a/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py b/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py index bfb04aff8e9e..957df94f38a2 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py @@ -37,7 +37,8 @@ class ActuatorNetMLPCfg(DCMotorCfg): damping = None network_file: str | None = None - """TorchScript checkpoint path. Required unless a USD actuator provides one (``use_newton_actuators`` only).""" + """Checkpoint path: an ONNX model (``.onnx``), or a TorchScript module exported to ONNX when the actuator loads. + Required unless a USD actuator provides one (``use_newton_actuators`` only).""" pos_scale: float | None = None """Scaling of the joint position errors input to the network.""" diff --git a/source/isaaclab/isaaclab/utils/io/__init__.pyi b/source/isaaclab/isaaclab/utils/io/__init__.pyi index 3d61292f55a7..91692a594c16 100644 --- a/source/isaaclab/isaaclab/utils/io/__init__.pyi +++ b/source/isaaclab/isaaclab/utils/io/__init__.pyi @@ -4,10 +4,12 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "load_onnx_model", "load_torchscript_model", "dump_yaml", "load_yaml", ] +from .onnx import load_onnx_model from .torchscript import load_torchscript_model from .yaml import dump_yaml, load_yaml diff --git a/source/isaaclab/isaaclab/utils/io/onnx.py b/source/isaaclab/isaaclab/utils/io/onnx.py new file mode 100644 index 000000000000..299f5f8c9807 --- /dev/null +++ b/source/isaaclab/isaaclab/utils/io/onnx.py @@ -0,0 +1,55 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""ONNX I/O utilities.""" + +import io + +import torch + +from ..assets import read_file + + +def load_onnx_model( + model_path: str, + sample_inputs: tuple, + *, + device: str, + input_names: list[str], + output_names: list[str], + dynamic_axes: dict[str, dict[int, str]] | None = None, +) -> io.BytesIO: + """Load a network file as an ONNX model. + + An ``.onnx`` file is read as it is. Any other file is loaded as a TorchScript module and exported to ONNX in + memory, with the TorchScript exporter since the dynamo exporter does not accept TorchScript modules. + + Args: + model_path: Path to the network file, local or on the Nucleus server. + sample_inputs: Inputs that trace the TorchScript module for the export, on ``device``. + device: Device to load the TorchScript module on. + input_names: Names of the exported model's inputs. + output_names: Names of the exported model's outputs. + dynamic_axes: Dynamic axes of the exported model's inputs and outputs, by name. Defaults to None. + + Returns: + The ONNX model. An ``.onnx`` file keeps its own input and output names. + """ + file_bytes = read_file(model_path) + if model_path.endswith(".onnx"): + return file_bytes + module = torch.jit.load(file_bytes, map_location=device).eval() + model = io.BytesIO() + torch.onnx.export( + module, + sample_inputs, + model, + input_names=input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + dynamo=False, + ) + model.seek(0) + return model diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index 746d94f17921..8d498fec32c2 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -39,9 +39,22 @@ def _feature_torque_mlp(num_features: int) -> torch.nn.Linear: return network -def _actuator(cfg_class, network: torch.nn.Module, tmp_path, device: str, **cfg): - network_file = tmp_path / "network.pt" - torch.jit.script(network).save(str(network_file)) +def _actuator(cfg_class, network: torch.nn.Module, tmp_path, device: str, network_format: str = "pt", **cfg): + network_file = tmp_path / f"network.{network_format}" + if network_format == "onnx": + # names other than the ones the actuator exports TorchScript with + num_features = network.in_features + torch.onnx.export( + network, + (torch.zeros(1, num_features),), + str(network_file), + input_names=["obs"], + output_names=["act"], + dynamic_axes={"obs": {0: "batch"}, "act": {0: "batch"}}, + dynamo=False, + ) + else: + torch.jit.script(network).save(str(network_file)) cfg = cfg_class( joint_names_expr=["joint_.*"], network_file=str(network_file), @@ -138,15 +151,19 @@ def test_mlp_rejects_invalid_history_before_loading_checkpoint(tmp_path): @pytest.mark.parametrize("device", test_devices()) -@pytest.mark.parametrize("input_idx,input_order", [([0, 1, 2], "pos_vel"), ([3, 0, -2, 3], "vel_pos")]) -def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order): - """Computed torque follows the selected zero-padded history across wraparound and partial resets.""" +@pytest.mark.parametrize( + "input_idx,input_order,network_format", [([0, 1, 2], "pos_vel", "pt"), ([3, 0, -2, 3], "vel_pos", "onnx")] +) +def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order, network_format): + """Computed torque follows the selected zero-padded history across wraparound and partial resets, with a + TorchScript or an ONNX network file.""" network = _feature_torque_mlp(2 * len(input_idx)) actuator = _actuator( ActuatorNetMLPCfg, network, tmp_path, device, + network_format, input_idx=input_idx, pos_scale=-0.3, vel_scale=1.25, From 4634d7863fa6ad3560deed94bd9c76e014d280c4 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 22 Nov 2026 23:16:23 -0800 Subject: [PATCH 16/31] Scale and clip the MLP actuator torque in a Warp kernel --- ...chuanh-actuator-net-mask-reset.changed.rst | 4 +- .../isaaclab/actuators/actuator_kernels.py | 16 +++++ .../isaaclab/actuators/actuator_net.py | 60 +++++++++++++++++-- .../test/actuators/test_actuator_net.py | 37 ++++++++++-- 4 files changed, 106 insertions(+), 11 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index a174daff22fc..acc7cfa61095 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -3,8 +3,8 @@ * Changed :class:`~isaaclab.actuators.ActuatorNetMLP` to run its network with Warp-NN, a new dependency. The network file may be an ONNX model, read as it is, or a TorchScript module, exported to ONNX when the actuator loads; the network must use operators that Warp-NN supports. ``network`` is now the Warp-NN runtime instead of the TorchScript - module. One Warp kernel updates the joint history and writes the network input, so a CUDA graph can record the - whole torque computation. + module. One Warp kernel updates the joint history and writes the network input, and another scales the torque and + clips it to the DC motor limits, so a Warp graph alone can record the whole torque computation. * Changed the ray-caster drift resampling on reset to draw from per-environment Warp random states, so a reset recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded from the environment seed when the sensor initializes and again by every diff --git a/source/isaaclab/isaaclab/actuators/actuator_kernels.py b/source/isaaclab/isaaclab/actuators/actuator_kernels.py index 52c92f803e9c..ac9c0aba3766 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_kernels.py +++ b/source/isaaclab/isaaclab/actuators/actuator_kernels.py @@ -15,6 +15,22 @@ from ..utils.warp.index_kernel import IndexKernelDispatcher +@wp.func +def dc_motor_clip( + effort: wp.float32, + joint_vel: wp.float32, + saturation_effort: wp.float32, + vel_at_effort_lim: wp.float32, + velocity_limit: wp.float32, + effort_limit: wp.float32, +) -> wp.float32: + """Clip an effort to the DC motor's torque-speed limits, as ``DCMotor._clip_effort`` does.""" + vel = wp.min(wp.max(joint_vel, -vel_at_effort_lim), vel_at_effort_lim) + max_effort = wp.min(saturation_effort * (1.0 - vel / velocity_limit), effort_limit) + min_effort = wp.max(saturation_effort * (-1.0 - vel / velocity_limit), -effort_limit) + return wp.min(wp.max(effort, min_effort), max_effort) + + @wp.kernel(enable_backward=False) def write_2d_float_with_indices( source: wp.array2d(dtype=wp.float32), diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 280dc4e2211f..e956d3126df1 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -26,6 +26,7 @@ from ..utils.io import load_onnx_model from ..utils.types import ArticulationActions from ..utils.warp.memory import make_masked_fill +from .actuator_kernels import dc_motor_clip from .actuator_pd import DCMotor if TYPE_CHECKING: @@ -156,6 +157,37 @@ def _update_mlp_history( network_input[row, vel_column + i] = vel_scale * joint_vel_history[env_id, index, joint] +@wp.kernel(enable_backward=False) +def _scale_and_clip_mlp_torque( + # input + torque: wp.array(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + torque_scale: wp.float32, + saturation_effort: wp.array2d(dtype=wp.float32), + vel_at_effort_lim: wp.array2d(dtype=wp.float32), + velocity_limit: wp.array2d(dtype=wp.float32), + effort_limit: wp.array2d(dtype=wp.float32), + # output + computed_effort: wp.array2d(dtype=wp.float32), + applied_effort: wp.array2d(dtype=wp.float32), +): + """Scale the network torque of each (env, joint) and clip it to the DC motor limits. + + ``torque`` holds one value per (env, joint), row-major. Launch with ``dim=(num_envs, num_joints)``. + """ + env_id, joint = wp.tid() + effort = torque[env_id * computed_effort.shape[1] + joint] * torque_scale + computed_effort[env_id, joint] = effort + applied_effort[env_id, joint] = dc_motor_clip( + effort, + joint_vel[env_id, joint], + saturation_effort[env_id, joint], + vel_at_effort_lim[env_id, joint], + velocity_limit[env_id, joint], + effort_limit[env_id, joint], + ) + + class ActuatorNetMLP(DCMotor): """Actuator model based on multi-layer perceptron and joint history. @@ -216,6 +248,12 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): input_shape = (self._num_envs * self.num_joints, 2 * len(indices)) self._network_input = wp.zeros(input_shape, dtype=wp.float32, device=self._device) self.network.prepare({self._network_input_name: self._network_input}) + # the efforts are written by a Warp kernel; the actuator's effort attributes are Torch views of them + effort_shape = (self._num_envs, self.num_joints) + self._computed_effort = wp.zeros(effort_shape, dtype=wp.float32, device=self._device) + self._applied_effort = wp.zeros(effort_shape, dtype=wp.float32, device=self._device) + self.computed_effort = wp.to_torch(self._computed_effort) + self.applied_effort = wp.to_torch(self._applied_effort) """ Operations. @@ -254,11 +292,23 @@ def compute( device=self._device, ) # run network inference - torques = wp.to_torch(self.network({self._network_input_name: self._network_input})[self._network_output_name]) - self.computed_effort = torques.view(self._num_envs, self.num_joints) * self.cfg.torque_scale - - # clip the computed effort based on the motor limits - self.applied_effort = self._clip_effort(self.computed_effort, joint_vel) + torque = self.network({self._network_input_name: self._network_input})[self._network_output_name] + # scale the torque and clip it based on the motor limits + wp.launch( + _scale_and_clip_mlp_torque, + dim=(self._num_envs, self.num_joints), + inputs=[ + torque.reshape((self._num_envs * self.num_joints,)), + wp.from_torch(joint_vel), + self.cfg.torque_scale, + wp.from_torch(self._saturation_effort), + wp.from_torch(self._vel_at_effort_lim), + wp.from_torch(self.actuator_velocity_limit), + wp.from_torch(self.actuator_effort_limit), + ], + outputs=[self._computed_effort, self._applied_effort], + device=self._device, + ) # return torques control_action.joint_efforts = self.applied_effort diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index 8d498fec32c2..11886e9b813e 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -9,7 +9,7 @@ import torch import warp as wp -from isaaclab.actuators import ActuatorNetLSTMCfg, ActuatorNetMLPCfg +from isaaclab.actuators import ActuatorNetLSTMCfg, ActuatorNetMLPCfg, DCMotor from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils import instantiate from isaaclab.utils.types import ArticulationActions @@ -132,6 +132,31 @@ def test_mlp_masked_reset_replays_from_a_cuda_graph_while_the_history_moves(tmp_ torch.testing.assert_close(actuator.computed_effort, expected) +@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) +def test_mlp_compute_replays_from_a_warp_graph(tmp_path, device): + """A Warp graph records the whole torque computation, network and clip included, with no Torch work in it. + + The graph is recorded on Warp's own stream, apart from Torch's, so any Torch operation in ``compute`` would run + once at recording time instead of being replayed. + """ + cfg = {"input_idx": [0, 1, 2], "pos_scale": 1.0, "vel_scale": 1.0, "torque_scale": 40.0, "input_order": "pos_vel"} + eager = _actuator(ActuatorNetMLPCfg, _feature_torque_mlp(6), tmp_path, device, **cfg) + recorded = _actuator(ActuatorNetMLPCfg, _feature_torque_mlp(6), tmp_path, device, **cfg) + target, position, velocity = (torch.zeros(3, 2, device=device) for _ in range(3)) + torch.cuda.synchronize(device) + with wp.ScopedCapture(device) as capture: + recorded.compute(ArticulationActions(joint_positions=target), position, velocity) + for _ in range(4): + for tensor in (target, position, velocity): + tensor.copy_(torch.randn(3, 2, device=device)) + eager.compute(ArticulationActions(joint_positions=target.clone()), position, velocity) + torch.cuda.synchronize(device) + wp.capture_launch(capture.graph) + wp.synchronize_device(device) + torch.testing.assert_close(recorded.computed_effort, eager.computed_effort) + torch.testing.assert_close(recorded.applied_effort, eager.applied_effort) + + def test_mlp_rejects_invalid_history_before_loading_checkpoint(tmp_path): """The configured history error takes precedence over checkpoint I/O.""" cfg = ActuatorNetMLPCfg( @@ -156,7 +181,7 @@ def test_mlp_rejects_invalid_history_before_loading_checkpoint(tmp_path): ) def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order, network_format): """Computed torque follows the selected zero-padded history across wraparound and partial resets, with a - TorchScript or an ONNX network file.""" + TorchScript or an ONNX network file; the applied torque is clipped as the Torch DC motor clips it.""" network = _feature_torque_mlp(2 * len(input_idx)) actuator = _actuator( ActuatorNetMLPCfg, @@ -167,10 +192,11 @@ def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order, input_idx=input_idx, pos_scale=-0.3, vel_scale=1.25, - torque_scale=0.5, + torque_scale=20.0, input_order=input_order, ) network = network.to(device) + clipped = False length = max(input_idx) + 1 position_history = torch.zeros(3, length, 2, device=device) velocity_history = torch.zeros_like(position_history) @@ -201,6 +227,9 @@ def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order, features = torch.cat([pos_features * pos_scale, vel_features * vel_scale], dim=1) else: features = torch.cat([vel_features * vel_scale, pos_features * pos_scale], dim=1) - expected = network(features).detach().reshape(3, 2) * 0.5 + expected = network(features).detach().reshape(3, 2) * 20.0 actuator.compute(ArticulationActions(joint_positions=desired), position, velocity) torch.testing.assert_close(actuator.computed_effort, expected) + torch.testing.assert_close(actuator.applied_effort, DCMotor._clip_effort(actuator, expected, velocity)) + clipped |= not torch.equal(actuator.applied_effort, actuator.computed_effort) + assert clipped From 19d9aab324778d5c566e50dc5f6a1dd8aa98d22f Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 30 Nov 2026 01:24:25 -0800 Subject: [PATCH 17/31] Require warp-nn 0.5.0 warp-nn 0.5.0 is the first release with the faster module kernels that the recorded ActuatorNetMLP compute is measured with. --- pyproject.toml | 2 +- uv.lock | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 55d5b4f88afb..8b6de4807e7c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,7 +48,7 @@ dependencies = [ "transformers==5.10.4", "einops", "warp-lang==1.17.0", - "warp-nn>=0.4.1", + "warp-nn>=0.5.0", "matplotlib>=3.10.3", # pillow: floor, not exact — an exact pin below Isaac Sim's prebundled version forces a # downgrade that deletes the prebundled copy other extensions symlink into (nvbugs 6410989). diff --git a/uv.lock b/uv.lock index 7bde8d6f9719..d0e705e8326e 100644 --- a/uv.lock +++ b/uv.lock @@ -2215,7 +2215,7 @@ requires-dist = [ { name = "viser", marker = "extra == 'viser'", specifier = ">=1.0.16" }, { name = "wandb", marker = "extra == 'wandb'", specifier = ">=0.13.11" }, { name = "warp-lang", specifier = "==1.17.0" }, - { name = "warp-nn", specifier = ">=0.4.1" }, + { name = "warp-nn", specifier = ">=0.5.0" }, ] provides-extras = ["tetrahedralization", "video", "optix", "newton-neural", "importers", "test", "dev", "sb3", "skrl", "skrl-jax", "rl-games", "wandb", "rsl-rl", "torchrl", "viser", "rerun", "isaacsim", "ov", "ovphysx", "ovrtx", "mimic", "teleop", "ovxr", "rlinf", "leapp", "fovi", "all"] @@ -6300,13 +6300,13 @@ wheels = [ [[package]] name = "warp-nn" -version = "0.4.1" +version = "0.5.0" source = { registry = "https://pypi.nvidia.com/" } dependencies = [ { name = "warp-lang" }, ] wheels = [ - { url = "https://pypi.nvidia.com/warp-nn/warp_nn-0.4.1-py3-none-any.whl", hash = "sha256:5a598043603f9a7c30ee5f02d832ac3c2065b9621d5c57f3a2dd8b64bb3be387" }, + { url = "https://pypi.nvidia.com/warp-nn/warp_nn-0.5.0-py3-none-any.whl", hash = "sha256:d1910309d238f5ff6e9656c5b914355310c5ceb6f5a1431d3c2f2befad83f83b" }, ] [[package]] From 6f4030a888998724c81594e238958765a7513dac Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 30 Nov 2026 01:55:33 -0800 Subject: [PATCH 18/31] Export TorchScript actuator networks for the actuator's batch The exported ONNX model takes inputs of the sample inputs' shapes, so the actuator traces with its own (env, joint) batch and declares no dynamic axes. --- source/isaaclab/isaaclab/actuators/actuator_net.py | 3 +-- source/isaaclab/isaaclab/utils/io/onnx.py | 6 ++---- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 642f90a60862..35b1635482c3 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -232,11 +232,10 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference model = load_onnx_model( self.cfg.network_file, - (torch.zeros(1, 2 * len(indices), device=self._device),), + (torch.zeros(self._num_envs * self.num_joints, 2 * len(indices), device=self._device),), device=self._device, input_names=["input"], output_names=["torque"], - dynamic_axes={"input": {0: "batch"}, "torque": {0: "batch"}}, ) self.network = OnnxRuntime(model, device=self._device) # an ONNX file keeps the input and output names it was exported with diff --git a/source/isaaclab/isaaclab/utils/io/onnx.py b/source/isaaclab/isaaclab/utils/io/onnx.py index 299f5f8c9807..a15de023a9fa 100644 --- a/source/isaaclab/isaaclab/utils/io/onnx.py +++ b/source/isaaclab/isaaclab/utils/io/onnx.py @@ -19,7 +19,6 @@ def load_onnx_model( device: str, input_names: list[str], output_names: list[str], - dynamic_axes: dict[str, dict[int, str]] | None = None, ) -> io.BytesIO: """Load a network file as an ONNX model. @@ -28,11 +27,11 @@ def load_onnx_model( Args: model_path: Path to the network file, local or on the Nucleus server. - sample_inputs: Inputs that trace the TorchScript module for the export, on ``device``. + sample_inputs: Inputs that trace the TorchScript module for the export, on ``device``. The exported model + takes inputs of their shapes. device: Device to load the TorchScript module on. input_names: Names of the exported model's inputs. output_names: Names of the exported model's outputs. - dynamic_axes: Dynamic axes of the exported model's inputs and outputs, by name. Defaults to None. Returns: The ONNX model. An ``.onnx`` file keeps its own input and output names. @@ -48,7 +47,6 @@ def load_onnx_model( model, input_names=input_names, output_names=output_names, - dynamic_axes=dynamic_axes, dynamo=False, ) model.seek(0) From d98b83c5b1229a562b52152a4c8517b246402fc3 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 30 Nov 2026 01:55:45 -0800 Subject: [PATCH 19/31] Mark ActuatorNetMLP capturable Its compute and masked reset are Warp kernels and Warp-NN on fixed buffers, so it inherits capturable from DCMotor instead of opting out. --- .../changelog.d/jichuanh-actuator-net-mask-reset.changed.rst | 3 ++- source/isaaclab/isaaclab/actuators/actuator_net.py | 2 -- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index acc7cfa61095..f7f0a9788b5c 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -4,7 +4,8 @@ file may be an ONNX model, read as it is, or a TorchScript module, exported to ONNX when the actuator loads; the network must use operators that Warp-NN supports. ``network`` is now the Warp-NN runtime instead of the TorchScript module. One Warp kernel updates the joint history and writes the network input, and another scales the torque and - clips it to the DC motor limits, so a Warp graph alone can record the whole torque computation. + clips it to the DC motor limits, so a Warp graph alone can record the whole torque computation. The actuator is + now :attr:`~isaaclab.actuators.ActuatorBase.capturable`. * Changed the ray-caster drift resampling on reset to draw from per-environment Warp random states, so a reset recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded from the environment seed when the sensor initializes and again by every diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 35b1635482c3..6faa5de779ab 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -212,8 +212,6 @@ class ActuatorNetMLP(DCMotor): cfg: ActuatorNetMLPCfg """The configuration of the actuator model.""" - capturable: ClassVar[bool] = False # The histories are assigned anew at every step, which a graph cannot follow - def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): if cfg.network_file is None: raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") From e5c4d2fcd964c8d015f86ca294b939c871085b26 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 30 Nov 2026 01:55:54 -0800 Subject: [PATCH 20/31] Describe the MLP actuator's ONNX network file in the actuator concepts --- docs/source/concepts/actuators.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/source/concepts/actuators.rst b/docs/source/concepts/actuators.rst index 20e0c4db14fd..86569ffcb718 100644 --- a/docs/source/concepts/actuators.rst +++ b/docs/source/concepts/actuators.rst @@ -113,7 +113,8 @@ for linkages whose effective lever arm changes through their range of motion. **ActuatorNetMLP / ActuatorNetLSTM.** Learned torque models that use joint-position error and velocity history and clip output with the DC-motor envelope. ``network_file`` is a TorchScript -checkpoint. See the :mod:`isaaclab.actuators` API reference for configuration details. +checkpoint; the MLP's may also be an ONNX model, and the MLP runs its network with Warp-NN, so the network must use +operators that Warp-NN supports. See the :mod:`isaaclab.actuators` API reference for configuration details. **BamActuatorCfg.** A parameter-identified model of a small voltage-controlled servo, described in :ref:`actuators-bam`. Unlike the PD models it takes no stiffness or damping: its position loop is From 3a8360a89d99aedcf82796d0e645bd544be92047 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 30 Nov 2026 02:00:06 -0800 Subject: [PATCH 21/31] Run ActuatorNetLSTM with Warp-NN The LSTM network is loaded as ONNX (TorchScript is exported at load for the actuator's batch) and runs with Warp-NN, like ActuatorNetMLP: a Warp kernel writes the network input and the hidden and cell states carry over in Warp buffers, so a Warp graph alone records the compute. The two network actuators share their effort buffers and torque clip in a private base class, and both are capturable. --- docs/source/concepts/actuators.rst | 4 +- ...huanh-actuator-net-lstm-warpnn.changed.rst | 6 + .../jichuanh-actuator-net-lstm-warpnn.minor | 0 .../isaaclab/actuators/actuator_net.py | 250 ++++++++++-------- .../isaaclab/actuators/actuator_net_cfg.py | 3 +- .../test/utils/actuator_equivalence.py | 3 +- source/isaaclab/isaaclab/utils/io/onnx.py | 9 +- .../test/actuators/test_actuator_net.py | 86 ++++-- .../isaaclab/test/actuators/test_dc_motor.py | 9 +- 9 files changed, 235 insertions(+), 135 deletions(-) create mode 100644 source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.changed.rst create mode 100644 source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.minor diff --git a/docs/source/concepts/actuators.rst b/docs/source/concepts/actuators.rst index 86569ffcb718..00f1b7a64955 100644 --- a/docs/source/concepts/actuators.rst +++ b/docs/source/concepts/actuators.rst @@ -112,8 +112,8 @@ The delay is sampled uniformly from ``[min_delay, max_delay]`` at reset. for linkages whose effective lever arm changes through their range of motion. **ActuatorNetMLP / ActuatorNetLSTM.** Learned torque models that use joint-position error and -velocity history and clip output with the DC-motor envelope. ``network_file`` is a TorchScript -checkpoint; the MLP's may also be an ONNX model, and the MLP runs its network with Warp-NN, so the network must use +velocity history and clip output with the DC-motor envelope. ``network_file`` is an ONNX model, or a +TorchScript checkpoint exported to ONNX when the actuator loads; the network runs with Warp-NN, so it must use operators that Warp-NN supports. See the :mod:`isaaclab.actuators` API reference for configuration details. **BamActuatorCfg.** A parameter-identified model of a small voltage-controlled servo, described in diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.changed.rst new file mode 100644 index 000000000000..2340c4a61bd4 --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.changed.rst @@ -0,0 +1,6 @@ +* Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` to run its network with Warp-NN, as + :class:`~isaaclab.actuators.ActuatorNetMLP` does. The network file may be an ONNX model, read as it is, or a + TorchScript module, exported to ONNX when the actuator loads; the network must use operators that Warp-NN supports. + ``network`` is now the Warp-NN runtime instead of the TorchScript module. The hidden and cell states carry over in + Warp buffers, whose Torch views keep the ``sea_*`` attributes, so a Warp graph alone can record the whole torque + computation. The actuator is now :attr:`~isaaclab.actuators.ActuatorBase.capturable`. diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.minor b/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 6faa5de779ab..579193b2df3c 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -15,14 +15,13 @@ from __future__ import annotations from collections.abc import Sequence -from typing import TYPE_CHECKING, ClassVar +from typing import TYPE_CHECKING import torch import warp as wp from warp_nn.runtime import OnnxRuntime from ..utils import index_fill_ -from ..utils.assets import read_file from ..utils.io import load_onnx_model from ..utils.types import ArticulationActions from ..utils.warp.memory import make_masked_fill @@ -33,13 +32,87 @@ from .actuator_net_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg -class ActuatorNetLSTM(DCMotor): +class _NetworkActuator(DCMotor): + """A DC motor whose torque comes from a network that Warp-NN runs, so a Warp graph can record its compute. + + The efforts are written by a Warp kernel into preallocated Warp buffers; the actuator's effort attributes are + Torch views of them. + """ + + def __init__(self, cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, *args, **kwargs): + if cfg.network_file is None: + raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") + super().__init__(cfg, *args, **kwargs) + effort_shape = (self._num_envs, self.num_joints) + self._computed_effort = wp.zeros(effort_shape, dtype=wp.float32, device=self._device) + self._applied_effort = wp.zeros(effort_shape, dtype=wp.float32, device=self._device) + self.computed_effort = wp.to_torch(self._computed_effort) + self.applied_effort = wp.to_torch(self._applied_effort) + + def _apply_torque( + self, control_action: ArticulationActions, torque: wp.array, joint_vel: torch.Tensor, torque_scale: float + ) -> ArticulationActions: + """Scale the network torque, clip it to the motor limits, and return it as the joint efforts.""" + wp.launch( + _scale_and_clip_torque, + dim=(self._num_envs, self.num_joints), + inputs=[ + torque.reshape((self._num_envs * self.num_joints,)), + wp.from_torch(joint_vel), + torque_scale, + wp.from_torch(self._saturation_effort), + wp.from_torch(self._vel_at_effort_lim), + wp.from_torch(self.actuator_velocity_limit), + wp.from_torch(self.actuator_effort_limit), + ], + outputs=[self._computed_effort, self._applied_effort], + device=self._device, + ) + control_action.joint_efforts = self.applied_effort + control_action.joint_positions = None + control_action.joint_velocities = None + return control_action + + +@wp.kernel(enable_backward=False) +def _scale_and_clip_torque( + # input + torque: wp.array(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + torque_scale: wp.float32, + saturation_effort: wp.array2d(dtype=wp.float32), + vel_at_effort_lim: wp.array2d(dtype=wp.float32), + velocity_limit: wp.array2d(dtype=wp.float32), + effort_limit: wp.array2d(dtype=wp.float32), + # output + computed_effort: wp.array2d(dtype=wp.float32), + applied_effort: wp.array2d(dtype=wp.float32), +): + """Scale the network torque of each (env, joint) and clip it to the DC motor limits. + + ``torque`` holds one value per (env, joint), row-major. Launch with ``dim=(num_envs, num_joints)``. + """ + env_id, joint = wp.tid() + effort = torque[env_id * computed_effort.shape[1] + joint] * torque_scale + computed_effort[env_id, joint] = effort + applied_effort[env_id, joint] = dc_motor_clip( + effort, + joint_vel[env_id, joint], + saturation_effort[env_id, joint], + vel_at_effort_lim[env_id, joint], + velocity_limit[env_id, joint], + effort_limit[env_id, joint], + ) + + +class ActuatorNetLSTM(_NetworkActuator): """Actuator model based on recurrent neural network (LSTM). Unlike the MLP implementation :cite:t:`hwangbo2019learning`, this class implements the learned model as a temporal neural network (LSTM) based on the work from :cite:t:`rudin2022learning`. This removes the need of storing a history as the - hidden states of the recurrent network captures the history. + hidden states of the recurrent network captures the history. The model is loaded + from an ONNX file, or from a TorchScript file exported to ONNX, and runs with Warp-NN. Note: Only the desired joint positions are used as inputs to the network. @@ -48,27 +121,34 @@ class ActuatorNetLSTM(DCMotor): cfg: ActuatorNetLSTMCfg """The configuration of the actuator model.""" - capturable: ClassVar[bool] = False # Not checked in replayed graphs, so not inherited from DCMotor - def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): - if cfg.network_file is None: - raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") super().__init__(cfg, *args, **kwargs) - # load the model from JIT file - file_bytes = read_file(self.cfg.network_file) - self.network = torch.jit.load(file_bytes, map_location=self._device).eval() - - # extract number of lstm layers and hidden dim from the shape of weights - num_layers = len(self.network.lstm.state_dict()) // 4 - hidden_dim = self.network.lstm.state_dict()["weight_hh_l0"].shape[1] - # create buffers for storing LSTM inputs - self.sea_input = torch.zeros(self._num_envs * self.num_joints, 1, 2, device=self._device) - self.sea_hidden_state = torch.zeros( - num_layers, self._num_envs * self.num_joints, hidden_dim, device=self._device + # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference + batch = self._num_envs * self.num_joints + model = load_onnx_model( + self.cfg.network_file, + lambda module: _lstm_sample_inputs(module, batch, self._device), + device=self._device, + input_names=["input", "h0", "c0"], + output_names=["torque", "h1", "c1"], ) - self.sea_cell_state = torch.zeros(num_layers, self._num_envs * self.num_joints, hidden_dim, device=self._device) - # reshape via views (doesn't change the actual memory layout) + self.network = OnnxRuntime(model, device=self._device) + # an ONNX file keeps the names it was exported with: the input, the hidden state, then the cell state + self._network_output_names = [spec.name for spec in self.network.outputs] + + # create buffers for the network input and the LSTM states, one row per (env, joint) + num_layers, _, hidden_dim = self.network.inputs[1].shape + self._network_input = wp.zeros((batch, 1, 2), dtype=wp.float32, device=self._device) + self._hidden_state = wp.zeros((num_layers, batch, hidden_dim), dtype=wp.float32, device=self._device) + self._cell_state = wp.zeros_like(self._hidden_state) + buffers = (self._network_input, self._hidden_state, self._cell_state) + self._network_inputs = {spec.name: buffer for spec, buffer in zip(self.network.inputs, buffers)} + self.network.prepare(self._network_inputs) + # Torch views of the buffers; the per-env views reshape without changing the memory layout + self.sea_input = wp.to_torch(self._network_input) + self.sea_hidden_state = wp.to_torch(self._hidden_state) + self.sea_cell_state = wp.to_torch(self._cell_state) layer_shape_per_env = (num_layers, self._num_envs, self.num_joints, hidden_dim) self.sea_hidden_state_per_env = self.sea_hidden_state.view(layer_shape_per_env) self.sea_cell_state_per_env = self.sea_cell_state.view(layer_shape_per_env) @@ -78,8 +158,9 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): """ def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: - if env_mask is not None: - for state in (self.sea_hidden_state_per_env, self.sea_cell_state_per_env): + # reset the hidden and cell states for the specified environments + for state in (self.sea_hidden_state_per_env, self.sea_cell_state_per_env): + if env_mask is not None: values = wp.from_torch(state.flatten(2)) wp.launch( make_masked_fill(values.dtype, 3), @@ -87,34 +168,52 @@ def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array inputs=[0.0, None, env_mask, values], device=self._device, ) - return - # reset the hidden and cell states for the specified environments - with torch.no_grad(): - index_fill_(self.sea_hidden_state_per_env, env_ids, 0.0, dim=1) - index_fill_(self.sea_cell_state_per_env, env_ids, 0.0, dim=1) + else: + index_fill_(state, env_ids, 0.0, dim=1) def compute( self, control_action: ArticulationActions, joint_pos: torch.Tensor, joint_vel: torch.Tensor ) -> ArticulationActions: - # compute network inputs - self.sea_input[:, 0, 0] = (control_action.joint_positions - joint_pos).flatten() - self.sea_input[:, 0, 1] = joint_vel.flatten() + # write the network input + wp.launch( + _write_lstm_input, + dim=(self._num_envs, self.num_joints), + inputs=[wp.from_torch(control_action.joint_positions), wp.from_torch(joint_pos), wp.from_torch(joint_vel)], + outputs=[self._network_input], + device=self._device, + ) + # run network inference; its new states are the ones the next step reads + outputs = self.network(self._network_inputs) + torque, hidden_state, cell_state = (outputs[name] for name in self._network_output_names) + wp.copy(self._hidden_state, hidden_state) + wp.copy(self._cell_state, cell_state) + # clip the torque based on the motor limits + return self._apply_torque(control_action, torque, joint_vel, 1.0) - # run network inference - with torch.inference_mode(): - torques, (self.sea_hidden_state[:], self.sea_cell_state[:]) = self.network( - self.sea_input, (self.sea_hidden_state, self.sea_cell_state) - ) - self.computed_effort = torques.reshape(self._num_envs, self.num_joints) - # clip the computed effort based on the motor limits - self.applied_effort = self._clip_effort(self.computed_effort, joint_vel) +def _lstm_sample_inputs(module: torch.jit.ScriptModule, batch: int, device: str) -> tuple: + """Inputs that trace an LSTM actuator network for its ONNX export: one sample and zero states per row.""" + state = torch.zeros(module.lstm.num_layers, batch, module.lstm.hidden_size, device=device) + return torch.zeros(batch, 1, 2, device=device), (state, state) - # return torques - control_action.joint_efforts = self.applied_effort - control_action.joint_positions = None - control_action.joint_velocities = None - return control_action + +@wp.kernel(enable_backward=False) +def _write_lstm_input( + # input + joint_pos_target: wp.array2d(dtype=wp.float32), + joint_pos: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + # output + network_input: wp.array3d(dtype=wp.float32), +): + """Write the joint position error and velocity of each (env, joint) as its network input row. + + Launch with ``dim=(num_envs, num_joints)``. + """ + env_id, joint = wp.tid() + row = env_id * joint_pos.shape[1] + joint + network_input[row, 0, 0] = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] + network_input[row, 0, 1] = joint_vel[env_id, joint] @wp.func @@ -159,38 +258,7 @@ def _update_mlp_history( network_input[row, vel_column + i] = vel_scale * joint_vel_history[env_id, index, joint] -@wp.kernel(enable_backward=False) -def _scale_and_clip_mlp_torque( - # input - torque: wp.array(dtype=wp.float32), - joint_vel: wp.array2d(dtype=wp.float32), - torque_scale: wp.float32, - saturation_effort: wp.array2d(dtype=wp.float32), - vel_at_effort_lim: wp.array2d(dtype=wp.float32), - velocity_limit: wp.array2d(dtype=wp.float32), - effort_limit: wp.array2d(dtype=wp.float32), - # output - computed_effort: wp.array2d(dtype=wp.float32), - applied_effort: wp.array2d(dtype=wp.float32), -): - """Scale the network torque of each (env, joint) and clip it to the DC motor limits. - - ``torque`` holds one value per (env, joint), row-major. Launch with ``dim=(num_envs, num_joints)``. - """ - env_id, joint = wp.tid() - effort = torque[env_id * computed_effort.shape[1] + joint] * torque_scale - computed_effort[env_id, joint] = effort - applied_effort[env_id, joint] = dc_motor_clip( - effort, - joint_vel[env_id, joint], - saturation_effort[env_id, joint], - vel_at_effort_lim[env_id, joint], - velocity_limit[env_id, joint], - effort_limit[env_id, joint], - ) - - -class ActuatorNetMLP(DCMotor): +class ActuatorNetMLP(_NetworkActuator): """Actuator model based on multi-layer perceptron and joint history. Many times the analytical model is not sufficient to capture the actuator dynamics, the @@ -213,8 +281,6 @@ class ActuatorNetMLP(DCMotor): """The configuration of the actuator model.""" def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): - if cfg.network_file is None: - raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") super().__init__(cfg, *args, **kwargs) history_length = max(self.cfg.input_idx) + 1 @@ -249,12 +315,6 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): input_shape = (self._num_envs * self.num_joints, 2 * len(indices)) self._network_input = wp.zeros(input_shape, dtype=wp.float32, device=self._device) self.network.prepare({self._network_input_name: self._network_input}) - # the efforts are written by a Warp kernel; the actuator's effort attributes are Torch views of them - effort_shape = (self._num_envs, self.num_joints) - self._computed_effort = wp.zeros(effort_shape, dtype=wp.float32, device=self._device) - self._applied_effort = wp.zeros(effort_shape, dtype=wp.float32, device=self._device) - self.computed_effort = wp.to_torch(self._computed_effort) - self.applied_effort = wp.to_torch(self._applied_effort) """ Operations. @@ -295,24 +355,4 @@ def compute( # run network inference torque = self.network({self._network_input_name: self._network_input})[self._network_output_name] # scale the torque and clip it based on the motor limits - wp.launch( - _scale_and_clip_mlp_torque, - dim=(self._num_envs, self.num_joints), - inputs=[ - torque.reshape((self._num_envs * self.num_joints,)), - wp.from_torch(joint_vel), - self.cfg.torque_scale, - wp.from_torch(self._saturation_effort), - wp.from_torch(self._vel_at_effort_lim), - wp.from_torch(self.actuator_velocity_limit), - wp.from_torch(self.actuator_effort_limit), - ], - outputs=[self._computed_effort, self._applied_effort], - device=self._device, - ) - - # return torques - control_action.joint_efforts = self.applied_effort - control_action.joint_positions = None - control_action.joint_velocities = None - return control_action + return self._apply_torque(control_action, torque, joint_vel, self.cfg.torque_scale) diff --git a/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py b/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py index 957df94f38a2..5bc9d5d9f0a1 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py @@ -23,7 +23,8 @@ class ActuatorNetLSTMCfg(DCMotorCfg): damping = None network_file: str | None = None - """TorchScript checkpoint path. Required unless a USD actuator provides one (``use_newton_actuators`` only).""" + """Checkpoint path: an ONNX model (``.onnx``), or a TorchScript module exported to ONNX when the actuator loads. + Required unless a USD actuator provides one (``use_newton_actuators`` only).""" @configclass diff --git a/source/isaaclab/isaaclab/test/utils/actuator_equivalence.py b/source/isaaclab/isaaclab/test/utils/actuator_equivalence.py index b0be65b12ede..4c202504f0bb 100644 --- a/source/isaaclab/isaaclab/test/utils/actuator_equivalence.py +++ b/source/isaaclab/isaaclab/test/utils/actuator_equivalence.py @@ -227,7 +227,8 @@ def forward( hc: tuple[torch.Tensor, torch.Tensor], ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: out, hc_new = self.lstm(x, hc) - return self.fc(out[:, -1, :]), hc_new + # one time step per call; squeezing it exports to an operator Warp-NN runs (indexing exports to Gather) + return self.fc(out.squeeze(1)), hc_new def make_dummy_lstm_checkpoint(device: str = "cpu") -> str: diff --git a/source/isaaclab/isaaclab/utils/io/onnx.py b/source/isaaclab/isaaclab/utils/io/onnx.py index a15de023a9fa..e8bc643d411c 100644 --- a/source/isaaclab/isaaclab/utils/io/onnx.py +++ b/source/isaaclab/isaaclab/utils/io/onnx.py @@ -6,6 +6,7 @@ """ONNX I/O utilities.""" import io +from collections.abc import Callable import torch @@ -14,7 +15,7 @@ def load_onnx_model( model_path: str, - sample_inputs: tuple, + sample_inputs: tuple | Callable[[torch.jit.ScriptModule], tuple], *, device: str, input_names: list[str], @@ -27,8 +28,8 @@ def load_onnx_model( Args: model_path: Path to the network file, local or on the Nucleus server. - sample_inputs: Inputs that trace the TorchScript module for the export, on ``device``. The exported model - takes inputs of their shapes. + sample_inputs: Inputs that trace the TorchScript module for the export, on ``device``, or a function that + returns them from the loaded module. The exported model takes inputs of their shapes. device: Device to load the TorchScript module on. input_names: Names of the exported model's inputs. output_names: Names of the exported model's outputs. @@ -43,7 +44,7 @@ def load_onnx_model( model = io.BytesIO() torch.onnx.export( module, - sample_inputs, + sample_inputs(module) if callable(sample_inputs) else sample_inputs, model, input_names=input_names, output_names=output_names, diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index 11886e9b813e..b396de6cb236 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -17,17 +17,20 @@ pytestmark = pytest.mark.kitless -class _ZeroTorqueLSTM(torch.nn.Module): - """LSTM-shaped network that requests no torque and keeps its state.""" +class _TorqueLSTM(torch.nn.Module): + """LSTM network shaped like the ANYdrive checkpoints: two LSTM layers and a linear torque head.""" def __init__(self): super().__init__() + torch.manual_seed(0) self.lstm = torch.nn.LSTM(input_size=2, hidden_size=4, num_layers=2, batch_first=True) + self.linear = torch.nn.Linear(4, 1) def forward( self, x: torch.Tensor, hc: tuple[torch.Tensor, torch.Tensor] ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: - return torch.zeros(x.shape[0], 1, device=x.device), hc + y, hc = self.lstm(x, hc) + return torch.squeeze(self.linear(y)), hc def _feature_torque_mlp(num_features: int) -> torch.nn.Linear: @@ -39,20 +42,24 @@ def _feature_torque_mlp(num_features: int) -> torch.nn.Linear: return network +def _export_onnx(network: torch.nn.Module, path): + """Export ``network`` to ONNX with names other than the ones the actuator exports TorchScript with.""" + if isinstance(network, torch.nn.Linear): + sample, inputs, outputs = (torch.zeros(1, network.in_features),), ["obs"], ["act"] + else: + state = torch.zeros(network.lstm.num_layers, 1, network.lstm.hidden_size) + sample, inputs, outputs = (torch.zeros(1, 1, 2), (state, state)), ["obs", "h", "c"], ["act", "h_next", "c_next"] + # the LSTM states put their batch second, after the layers + axes = {name: {1 if name[0] in "hc" else 0: "batch"} for name in inputs + outputs} + torch.onnx.export( + network, sample, str(path), input_names=inputs, output_names=outputs, dynamic_axes=axes, dynamo=False + ) + + def _actuator(cfg_class, network: torch.nn.Module, tmp_path, device: str, network_format: str = "pt", **cfg): network_file = tmp_path / f"network.{network_format}" if network_format == "onnx": - # names other than the ones the actuator exports TorchScript with - num_features = network.in_features - torch.onnx.export( - network, - (torch.zeros(1, num_features),), - str(network_file), - input_names=["obs"], - output_names=["act"], - dynamic_axes={"obs": {0: "batch"}, "act": {0: "batch"}}, - dynamo=False, - ) + _export_onnx(network, network_file) else: torch.jit.script(network).save(str(network_file)) cfg = cfg_class( @@ -82,7 +89,7 @@ def _assert_masked_zero(state: torch.Tensor, env_dim: int): @pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) def test_lstm_masked_reset_replays_from_a_cuda_graph(tmp_path, device): - actuator = _actuator(ActuatorNetLSTMCfg, _ZeroTorqueLSTM(), tmp_path, device) + actuator = _actuator(ActuatorNetLSTMCfg, _TorqueLSTM(), tmp_path, device) mask = wp.array([True, False, True], dtype=wp.bool, device=device) graph = _record_masked_reset(actuator, mask) for _ in range(3): @@ -133,15 +140,26 @@ def test_mlp_masked_reset_replays_from_a_cuda_graph_while_the_history_moves(tmp_ @pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) -def test_mlp_compute_replays_from_a_warp_graph(tmp_path, device): +@pytest.mark.parametrize("model", ["mlp", "lstm"]) +def test_compute_replays_from_a_warp_graph(tmp_path, device, model): """A Warp graph records the whole torque computation, network and clip included, with no Torch work in it. The graph is recorded on Warp's own stream, apart from Torch's, so any Torch operation in ``compute`` would run - once at recording time instead of being replayed. + once at recording time instead of being replayed. The LSTM states carry over from one replay to the next. """ - cfg = {"input_idx": [0, 1, 2], "pos_scale": 1.0, "vel_scale": 1.0, "torque_scale": 40.0, "input_order": "pos_vel"} - eager = _actuator(ActuatorNetMLPCfg, _feature_torque_mlp(6), tmp_path, device, **cfg) - recorded = _actuator(ActuatorNetMLPCfg, _feature_torque_mlp(6), tmp_path, device, **cfg) + if model == "mlp": + cfg_class, network = ActuatorNetMLPCfg, _feature_torque_mlp(6) + cfg = { + "input_idx": [0, 1, 2], + "pos_scale": 1.0, + "vel_scale": 1.0, + "torque_scale": 40.0, + "input_order": "pos_vel", + } + else: + cfg_class, network, cfg = ActuatorNetLSTMCfg, _TorqueLSTM(), {} + eager = _actuator(cfg_class, network, tmp_path, device, **cfg) + recorded = _actuator(cfg_class, network, tmp_path, device, **cfg) target, position, velocity = (torch.zeros(3, 2, device=device) for _ in range(3)) torch.cuda.synchronize(device) with wp.ScopedCapture(device) as capture: @@ -157,6 +175,34 @@ def test_mlp_compute_replays_from_a_warp_graph(tmp_path, device): torch.testing.assert_close(recorded.applied_effort, eager.applied_effort) +@pytest.mark.parametrize("device", test_devices()) +@pytest.mark.parametrize("network_format", ["pt", "onnx"]) +def test_lstm_state_carries_across_steps(tmp_path, device, network_format): + """Computed torque follows the network with its hidden and cell states carried from step to step and zeroed by + partial resets, with a TorchScript or an ONNX network file; the applied torque is clipped as the Torch DC motor + clips it.""" + network = _TorqueLSTM() + actuator = _actuator(ActuatorNetLSTMCfg, network, tmp_path, device, network_format) + network = network.to(device) + state = (torch.zeros(2, 6, 4, device=device), torch.zeros(2, 6, 4, device=device)) + joints = torch.arange(6.0, device=device).reshape(3, 2) + for step in range(6): + if step == 3: + actuator.reset(env_ids=torch.tensor([0, 2], dtype=torch.int32, device=device)) + for s in state: + s.view(2, 3, 2, 4)[:, [0, 2]] = 0.0 + position = joints * 0.1 + step * 0.05 + desired = position + joints * 0.03 + step * 0.07 + velocity = joints * 0.2 - step * 0.03 + x = torch.stack([(desired - position).flatten(), velocity.flatten()], dim=1).unsqueeze(1) + with torch.no_grad(): + torque, state = network(x, state) + expected = torque.reshape(3, 2) + actuator.compute(ArticulationActions(joint_positions=desired), position, velocity) + torch.testing.assert_close(actuator.computed_effort, expected) + torch.testing.assert_close(actuator.applied_effort, DCMotor._clip_effort(actuator, expected, velocity)) + + def test_mlp_rejects_invalid_history_before_loading_checkpoint(tmp_path): """The configured history error takes precedence over checkpoint I/O.""" cfg = ActuatorNetMLPCfg( diff --git a/source/isaaclab/test/actuators/test_dc_motor.py b/source/isaaclab/test/actuators/test_dc_motor.py index b84bfe5e688a..e322de4e4782 100644 --- a/source/isaaclab/test/actuators/test_dc_motor.py +++ b/source/isaaclab/test/actuators/test_dc_motor.py @@ -176,16 +176,21 @@ def test_dc_motor_clip_with_per_joint_saturation_effort(): class _ConstantTorqueLSTM(torch.nn.Module): - """LSTM-shaped network that always requests 100 N·m.""" + """LSTM network that always requests 100 N·m: its torque head has no weights and a bias of 100.""" def __init__(self): super().__init__() self.lstm = torch.nn.LSTM(input_size=2, hidden_size=4, num_layers=1, batch_first=True) + self.linear = torch.nn.Linear(4, 1) + with torch.no_grad(): + self.linear.weight.zero_() + self.linear.bias.fill_(100.0) def forward( self, x: torch.Tensor, hc: tuple[torch.Tensor, torch.Tensor] ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: - return torch.full((x.shape[0], 1), 100.0), hc + y, hc = self.lstm(x, hc) + return torch.squeeze(self.linear(y)), hc def test_lstm_actuator_clips_with_torque_speed_curve(tmp_path): From 5d49b8dd94edd15aaa1ad87041c0762d6776dd65 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 30 Nov 2026 10:33:55 -0800 Subject: [PATCH 22/31] Make the network actuators' Warp views once at construction The motor limits and the LSTM states are buffers the actuator owns and writes in place, so their Warp views are made in __init__ instead of on every compute and masked reset; only the tensors a caller passes in are converted per call. The LSTM's sample inputs for the ONNX export become a local function of __init__, and a comment says why the network runs once before any capture. --- .../isaaclab/actuators/actuator_net.py | 53 ++++++++++++------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 579193b2df3c..5264f6738693 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -48,6 +48,16 @@ def __init__(self, cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, *args, **kwargs) self._applied_effort = wp.zeros(effort_shape, dtype=wp.float32, device=self._device) self.computed_effort = wp.to_torch(self._computed_effort) self.applied_effort = wp.to_torch(self._applied_effort) + # Warp views of the motor limits the clip reads; the limits are written in place, so the views stay valid + self._motor_limits = tuple( + wp.from_torch(limit) + for limit in ( + self._saturation_effort, + self._vel_at_effort_lim, + self.actuator_velocity_limit, + self.actuator_effort_limit, + ) + ) def _apply_torque( self, control_action: ArticulationActions, torque: wp.array, joint_vel: torch.Tensor, torque_scale: float @@ -60,10 +70,7 @@ def _apply_torque( torque.reshape((self._num_envs * self.num_joints,)), wp.from_torch(joint_vel), torque_scale, - wp.from_torch(self._saturation_effort), - wp.from_torch(self._vel_at_effort_lim), - wp.from_torch(self.actuator_velocity_limit), - wp.from_torch(self.actuator_effort_limit), + *self._motor_limits, ], outputs=[self._computed_effort, self._applied_effort], device=self._device, @@ -124,11 +131,17 @@ class ActuatorNetLSTM(_NetworkActuator): def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): super().__init__(cfg, *args, **kwargs) - # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference batch = self._num_envs * self.num_joints + + def sample_inputs(module: torch.jit.ScriptModule) -> tuple: + # inputs that trace a TorchScript network for its ONNX export: one sample and zero states per row + state = torch.zeros(module.lstm.num_layers, batch, module.lstm.hidden_size, device=self._device) + return torch.zeros(batch, 1, 2, device=self._device), (state, state) + + # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference model = load_onnx_model( self.cfg.network_file, - lambda module: _lstm_sample_inputs(module, batch, self._device), + sample_inputs, device=self._device, input_names=["input", "h0", "c0"], output_names=["torque", "h1", "c1"], @@ -144,6 +157,7 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): self._cell_state = wp.zeros_like(self._hidden_state) buffers = (self._network_input, self._hidden_state, self._cell_state) self._network_inputs = {spec.name: buffer for spec, buffer in zip(self.network.inputs, buffers)} + # run the network once: Warp-NN allocates its outputs and loads its kernels, which a CUDA graph cannot record self.network.prepare(self._network_inputs) # Torch views of the buffers; the per-env views reshape without changing the memory layout self.sea_input = wp.to_torch(self._network_input) @@ -152,6 +166,10 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): layer_shape_per_env = (num_layers, self._num_envs, self.num_joints, hidden_dim) self.sea_hidden_state_per_env = self.sea_hidden_state.view(layer_shape_per_env) self.sea_cell_state_per_env = self.sea_cell_state.view(layer_shape_per_env) + # Warp views of the states per env, (layers, envs, joints * hidden), for the masked reset + self._states_per_env = tuple( + state.reshape((num_layers, self._num_envs, -1)) for state in (self._hidden_state, self._cell_state) + ) """ Operations. @@ -159,16 +177,16 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: # reset the hidden and cell states for the specified environments - for state in (self.sea_hidden_state_per_env, self.sea_cell_state_per_env): - if env_mask is not None: - values = wp.from_torch(state.flatten(2)) + if env_mask is not None: + for state in self._states_per_env: wp.launch( - make_masked_fill(values.dtype, 3), - dim=values.shape, - inputs=[0.0, None, env_mask, values], + make_masked_fill(state.dtype, 3), + dim=state.shape, + inputs=[0.0, None, env_mask, state], device=self._device, ) - else: + else: + for state in (self.sea_hidden_state_per_env, self.sea_cell_state_per_env): index_fill_(state, env_ids, 0.0, dim=1) def compute( @@ -191,12 +209,6 @@ def compute( return self._apply_torque(control_action, torque, joint_vel, 1.0) -def _lstm_sample_inputs(module: torch.jit.ScriptModule, batch: int, device: str) -> tuple: - """Inputs that trace an LSTM actuator network for its ONNX export: one sample and zero states per row.""" - state = torch.zeros(module.lstm.num_layers, batch, module.lstm.hidden_size, device=device) - return torch.zeros(batch, 1, 2, device=device), (state, state) - - @wp.kernel(enable_backward=False) def _write_lstm_input( # input @@ -311,9 +323,10 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): self._joint_pos_error_history = wp.zeros(history_shape, dtype=wp.float32, device=self._device) self._joint_vel_history = wp.zeros(history_shape, dtype=wp.float32, device=self._device) self._history_indices = wp.array(indices, dtype=wp.int32, device=self._device) - # the network input, one row per (env, joint), and the network outputs it allocates once + # the network input, one row per (env, joint) input_shape = (self._num_envs * self.num_joints, 2 * len(indices)) self._network_input = wp.zeros(input_shape, dtype=wp.float32, device=self._device) + # run the network once: Warp-NN allocates its outputs and loads its kernels, which a CUDA graph cannot record self.network.prepare({self._network_input_name: self._network_input}) """ From 83b89b8875b0d1ee3677ac7d51ec4d0ad4f529ca Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 30 Nov 2026 10:34:15 -0800 Subject: [PATCH 23/31] Combine the LSTM changelog entry with the network actuators' entry ActuatorNetLSTM and ActuatorNetMLP now share one Warp-NN entry in the PR's fragment. --- .../jichuanh-actuator-net-lstm-warpnn.changed.rst | 6 ------ .../jichuanh-actuator-net-lstm-warpnn.minor | 0 .../jichuanh-actuator-net-mask-reset.changed.rst | 14 ++++++++------ 3 files changed, 8 insertions(+), 12 deletions(-) delete mode 100644 source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.changed.rst delete mode 100644 source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.minor diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.changed.rst deleted file mode 100644 index 2340c4a61bd4..000000000000 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.changed.rst +++ /dev/null @@ -1,6 +0,0 @@ -* Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` to run its network with Warp-NN, as - :class:`~isaaclab.actuators.ActuatorNetMLP` does. The network file may be an ONNX model, read as it is, or a - TorchScript module, exported to ONNX when the actuator loads; the network must use operators that Warp-NN supports. - ``network`` is now the Warp-NN runtime instead of the TorchScript module. The hidden and cell states carry over in - Warp buffers, whose Torch views keep the ``sea_*`` attributes, so a Warp graph alone can record the whole torque - computation. The actuator is now :attr:`~isaaclab.actuators.ActuatorBase.capturable`. diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.minor b/source/isaaclab/changelog.d/jichuanh-actuator-net-lstm-warpnn.minor deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index f7f0a9788b5c..31d1f118de83 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -1,11 +1,13 @@ * Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` to reset by a Warp kernel when given an environment mask, so a CUDA graph can record the reset. -* Changed :class:`~isaaclab.actuators.ActuatorNetMLP` to run its network with Warp-NN, a new dependency. The network - file may be an ONNX model, read as it is, or a TorchScript module, exported to ONNX when the actuator loads; the - network must use operators that Warp-NN supports. ``network`` is now the Warp-NN runtime instead of the TorchScript - module. One Warp kernel updates the joint history and writes the network input, and another scales the torque and - clips it to the DC motor limits, so a Warp graph alone can record the whole torque computation. The actuator is - now :attr:`~isaaclab.actuators.ActuatorBase.capturable`. +* Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` to run their + networks with Warp-NN, a new dependency. The network file may be an ONNX model, read as it is, or a TorchScript + module, exported to ONNX when the actuator loads; the network must use operators that Warp-NN supports. ``network`` + is now the Warp-NN runtime instead of the TorchScript module. Warp kernels write the network input (for the MLP, + after updating the joint history) and scale the torque and clip it to the DC motor limits; the LSTM's hidden and + cell states carry over in Warp buffers, whose Torch views keep the ``sea_*`` attributes. A Warp graph alone can + therefore record the whole torque computation, and both actuators are now + :attr:`~isaaclab.actuators.ActuatorBase.capturable`. * Changed the ray-caster drift resampling on reset to draw from per-environment Warp random states, so a reset recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded from the environment seed when the sensor initializes and again by every From ec5dc495c89747d6e4153a97b1a5bf0bb57f88d2 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 30 Nov 2026 11:21:10 -0800 Subject: [PATCH 24/31] Move the network actuators' Warp kernels into actuator_kernels.py The actuators package keeps its Warp kernels in actuator_kernels.py; the network actuators' input, history and clip kernels join dc_motor_clip there under a section of their own, and actuator_net.py keeps only the classes. --- .../isaaclab/actuators/actuator_kernels.py | 133 +++++++++++++++--- .../isaaclab/actuators/actuator_net.py | 100 +------------ 2 files changed, 121 insertions(+), 112 deletions(-) diff --git a/source/isaaclab/isaaclab/actuators/actuator_kernels.py b/source/isaaclab/isaaclab/actuators/actuator_kernels.py index ac9c0aba3766..f7d3faefea6f 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_kernels.py +++ b/source/isaaclab/isaaclab/actuators/actuator_kernels.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Warp kernels used by actuator collections.""" +"""Warp kernels used by actuators and actuator collections.""" from __future__ import annotations @@ -14,21 +14,9 @@ from ..utils.warp.index_kernel import IndexKernelDispatcher - -@wp.func -def dc_motor_clip( - effort: wp.float32, - joint_vel: wp.float32, - saturation_effort: wp.float32, - vel_at_effort_lim: wp.float32, - velocity_limit: wp.float32, - effort_limit: wp.float32, -) -> wp.float32: - """Clip an effort to the DC motor's torque-speed limits, as ``DCMotor._clip_effort`` does.""" - vel = wp.min(wp.max(joint_vel, -vel_at_effort_lim), vel_at_effort_lim) - max_effort = wp.min(saturation_effort * (1.0 - vel / velocity_limit), effort_limit) - min_effort = wp.max(saturation_effort * (-1.0 - vel / velocity_limit), -effort_limit) - return wp.min(wp.max(effort, min_effort), max_effort) +""" +Actuator collection kernels. +""" @wp.kernel(enable_backward=False) @@ -160,3 +148,116 @@ def compute_implicit_actuator_batch( computed_effort[env_id, joint_id] = effort applied_effort[env_id, joint_id] = clamped_effort soft_velocity_limit[env_id, joint_id] = velocity_limit[env_id, batch_joint_id] + + +""" +Network actuator kernels. +""" + + +@wp.func +def dc_motor_clip( + effort: wp.float32, + joint_vel: wp.float32, + saturation_effort: wp.float32, + vel_at_effort_lim: wp.float32, + velocity_limit: wp.float32, + effort_limit: wp.float32, +) -> wp.float32: + """Clip an effort to the DC motor's torque-speed limits, as ``DCMotor._clip_effort`` does.""" + vel = wp.min(wp.max(joint_vel, -vel_at_effort_lim), vel_at_effort_lim) + max_effort = wp.min(saturation_effort * (1.0 - vel / velocity_limit), effort_limit) + min_effort = wp.max(saturation_effort * (-1.0 - vel / velocity_limit), -effort_limit) + return wp.min(wp.max(effort, min_effort), max_effort) + + +@wp.kernel(enable_backward=False) +def scale_and_clip_torque( + # input + torque: wp.array(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + torque_scale: wp.float32, + saturation_effort: wp.array2d(dtype=wp.float32), + vel_at_effort_lim: wp.array2d(dtype=wp.float32), + velocity_limit: wp.array2d(dtype=wp.float32), + effort_limit: wp.array2d(dtype=wp.float32), + # output + computed_effort: wp.array2d(dtype=wp.float32), + applied_effort: wp.array2d(dtype=wp.float32), +): + """Scale the network torque of each (env, joint) and clip it to the DC motor limits. + + ``torque`` holds one value per (env, joint), row-major. Launch with ``dim=(num_envs, num_joints)``. + """ + env_id, joint = wp.tid() + effort = torque[env_id * computed_effort.shape[1] + joint] * torque_scale + computed_effort[env_id, joint] = effort + applied_effort[env_id, joint] = dc_motor_clip( + effort, + joint_vel[env_id, joint], + saturation_effort[env_id, joint], + vel_at_effort_lim[env_id, joint], + velocity_limit[env_id, joint], + effort_limit[env_id, joint], + ) + + +@wp.kernel(enable_backward=False) +def write_lstm_input( + # input + joint_pos_target: wp.array2d(dtype=wp.float32), + joint_pos: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + # output + network_input: wp.array3d(dtype=wp.float32), +): + """Write the joint position error and velocity of each (env, joint) as its network input row. + + Launch with ``dim=(num_envs, num_joints)``. + """ + env_id, joint = wp.tid() + row = env_id * joint_pos.shape[1] + joint + network_input[row, 0, 0] = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] + network_input[row, 0, 1] = joint_vel[env_id, joint] + + +@wp.func +def _push_newest(history: wp.array3d(dtype=wp.float32), env_id: int, joint: int, sample: wp.float32): + """Move the history of one (env, joint) back by one step and write ``sample`` as its newest entry.""" + for t in range(history.shape[1] - 1): + k = history.shape[1] - 1 - t + history[env_id, k, joint] = history[env_id, k - 1, joint] + history[env_id, 0, joint] = sample + + +@wp.kernel(enable_backward=False) +def update_mlp_history( + # input + joint_pos_target: wp.array2d(dtype=wp.float32), + joint_pos: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + history_indices: wp.array(dtype=wp.int32), + pos_scale: wp.float32, + vel_scale: wp.float32, + pos_first: bool, + # output + joint_pos_error_history: wp.array3d(dtype=wp.float32), + joint_vel_history: wp.array3d(dtype=wp.float32), + network_input: wp.array2d(dtype=wp.float32), +): + """Record the newest joint position error and velocity, then write the scaled samples the network reads. + + Each row of ``network_input`` belongs to one (env, joint): its position errors, then its velocities when + ``pos_first``, otherwise the reverse. Launch with ``dim=(num_envs, num_joints)``. + """ + env_id, joint = wp.tid() + _push_newest(joint_pos_error_history, env_id, joint, joint_pos_target[env_id, joint] - joint_pos[env_id, joint]) + _push_newest(joint_vel_history, env_id, joint, joint_vel[env_id, joint]) + num_samples = history_indices.shape[0] + row = env_id * joint_pos.shape[1] + joint + pos_column = wp.where(pos_first, 0, num_samples) + vel_column = num_samples - pos_column + for i in range(num_samples): + index = history_indices[i] + network_input[row, pos_column + i] = pos_scale * joint_pos_error_history[env_id, index, joint] + network_input[row, vel_column + i] = vel_scale * joint_vel_history[env_id, index, joint] diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 5264f6738693..83509cf6c9b7 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -25,7 +25,7 @@ from ..utils.io import load_onnx_model from ..utils.types import ArticulationActions from ..utils.warp.memory import make_masked_fill -from .actuator_kernels import dc_motor_clip +from .actuator_kernels import scale_and_clip_torque, update_mlp_history, write_lstm_input from .actuator_pd import DCMotor if TYPE_CHECKING: @@ -64,7 +64,7 @@ def _apply_torque( ) -> ArticulationActions: """Scale the network torque, clip it to the motor limits, and return it as the joint efforts.""" wp.launch( - _scale_and_clip_torque, + scale_and_clip_torque, dim=(self._num_envs, self.num_joints), inputs=[ torque.reshape((self._num_envs * self.num_joints,)), @@ -81,37 +81,6 @@ def _apply_torque( return control_action -@wp.kernel(enable_backward=False) -def _scale_and_clip_torque( - # input - torque: wp.array(dtype=wp.float32), - joint_vel: wp.array2d(dtype=wp.float32), - torque_scale: wp.float32, - saturation_effort: wp.array2d(dtype=wp.float32), - vel_at_effort_lim: wp.array2d(dtype=wp.float32), - velocity_limit: wp.array2d(dtype=wp.float32), - effort_limit: wp.array2d(dtype=wp.float32), - # output - computed_effort: wp.array2d(dtype=wp.float32), - applied_effort: wp.array2d(dtype=wp.float32), -): - """Scale the network torque of each (env, joint) and clip it to the DC motor limits. - - ``torque`` holds one value per (env, joint), row-major. Launch with ``dim=(num_envs, num_joints)``. - """ - env_id, joint = wp.tid() - effort = torque[env_id * computed_effort.shape[1] + joint] * torque_scale - computed_effort[env_id, joint] = effort - applied_effort[env_id, joint] = dc_motor_clip( - effort, - joint_vel[env_id, joint], - saturation_effort[env_id, joint], - vel_at_effort_lim[env_id, joint], - velocity_limit[env_id, joint], - effort_limit[env_id, joint], - ) - - class ActuatorNetLSTM(_NetworkActuator): """Actuator model based on recurrent neural network (LSTM). @@ -194,7 +163,7 @@ def compute( ) -> ArticulationActions: # write the network input wp.launch( - _write_lstm_input, + write_lstm_input, dim=(self._num_envs, self.num_joints), inputs=[wp.from_torch(control_action.joint_positions), wp.from_torch(joint_pos), wp.from_torch(joint_vel)], outputs=[self._network_input], @@ -209,67 +178,6 @@ def compute( return self._apply_torque(control_action, torque, joint_vel, 1.0) -@wp.kernel(enable_backward=False) -def _write_lstm_input( - # input - joint_pos_target: wp.array2d(dtype=wp.float32), - joint_pos: wp.array2d(dtype=wp.float32), - joint_vel: wp.array2d(dtype=wp.float32), - # output - network_input: wp.array3d(dtype=wp.float32), -): - """Write the joint position error and velocity of each (env, joint) as its network input row. - - Launch with ``dim=(num_envs, num_joints)``. - """ - env_id, joint = wp.tid() - row = env_id * joint_pos.shape[1] + joint - network_input[row, 0, 0] = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] - network_input[row, 0, 1] = joint_vel[env_id, joint] - - -@wp.func -def _push_newest(history: wp.array3d(dtype=wp.float32), env_id: int, joint: int, sample: wp.float32): - """Move the history of one (env, joint) back by one step and write ``sample`` as its newest entry.""" - for t in range(history.shape[1] - 1): - k = history.shape[1] - 1 - t - history[env_id, k, joint] = history[env_id, k - 1, joint] - history[env_id, 0, joint] = sample - - -@wp.kernel(enable_backward=False) -def _update_mlp_history( - # input - joint_pos_target: wp.array2d(dtype=wp.float32), - joint_pos: wp.array2d(dtype=wp.float32), - joint_vel: wp.array2d(dtype=wp.float32), - history_indices: wp.array(dtype=wp.int32), - pos_scale: wp.float32, - vel_scale: wp.float32, - pos_first: bool, - # output - joint_pos_error_history: wp.array3d(dtype=wp.float32), - joint_vel_history: wp.array3d(dtype=wp.float32), - network_input: wp.array2d(dtype=wp.float32), -): - """Record the newest joint position error and velocity, then write the scaled samples the network reads. - - Each row of ``network_input`` belongs to one (env, joint): its position errors, then its velocities when - ``pos_first``, otherwise the reverse. Launch with ``dim=(num_envs, num_joints)``. - """ - env_id, joint = wp.tid() - _push_newest(joint_pos_error_history, env_id, joint, joint_pos_target[env_id, joint] - joint_pos[env_id, joint]) - _push_newest(joint_vel_history, env_id, joint, joint_vel[env_id, joint]) - num_samples = history_indices.shape[0] - row = env_id * joint_pos.shape[1] + joint - pos_column = wp.where(pos_first, 0, num_samples) - vel_column = num_samples - pos_column - for i in range(num_samples): - index = history_indices[i] - network_input[row, pos_column + i] = pos_scale * joint_pos_error_history[env_id, index, joint] - network_input[row, vel_column + i] = vel_scale * joint_vel_history[env_id, index, joint] - - class ActuatorNetMLP(_NetworkActuator): """Actuator model based on multi-layer perceptron and joint history. @@ -351,7 +259,7 @@ def compute( ) -> ArticulationActions: # move history queue by 1, update top of history and write the scaled network input wp.launch( - _update_mlp_history, + update_mlp_history, dim=(self._num_envs, self.num_joints), inputs=[ wp.from_torch(control_action.joint_positions), From ac3553dfd46e047fe84d67e49ba9f76e04fec5d2 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 1 Dec 2026 19:19:22 -0800 Subject: [PATCH 25/31] Load network actuators by name and share the DC motor clip Read the LSTM layer count and hidden size from the weights, so traced TorchScript checkpoints load. Split load_onnx_model (reads .onnx files) from the new export_torchscript_to_onnx; a TorchScript network_file is still exported when the actuator loads, with a warning that points to the new offline converter, scripts/tools/convert_actuator_net_to_onnx.py. The LSTM looks its inputs and outputs up by name and rejects an ONNX file without them. A network with an operator Warp-NN does not support fails with an error naming the file and the fix. Index the network kernels per environment and joint, compile the MLP history samples and column order into a cached kernel, and rename the shared base class to ActuatorNetBase. DCMotor clips its effort with the same dc_motor_clip kernel function the network actuators use, into a preallocated applied-effort buffer. --- docs/source/concepts/actuators.rst | 3 +- scripts/tools/convert_actuator_net_to_onnx.py | 92 ++++++++++++ ...jichuanh-actuator-net-mask-reset.added.rst | 4 +- ...chuanh-actuator-net-mask-reset.changed.rst | 21 ++- .../isaaclab/actuators/actuator_kernels.py | 117 ++++++++++----- .../isaaclab/actuators/actuator_net.py | 140 +++++++++++------- .../isaaclab/actuators/actuator_pd.py | 36 +++-- .../isaaclab/isaaclab/utils/io/__init__.pyi | 3 +- source/isaaclab/isaaclab/utils/io/onnx.py | 48 ++++-- .../test/actuators/test_actuator_net.py | 69 +++++++-- 10 files changed, 387 insertions(+), 146 deletions(-) create mode 100644 scripts/tools/convert_actuator_net_to_onnx.py diff --git a/docs/source/concepts/actuators.rst b/docs/source/concepts/actuators.rst index 00f1b7a64955..cd0d5b1032e2 100644 --- a/docs/source/concepts/actuators.rst +++ b/docs/source/concepts/actuators.rst @@ -114,7 +114,8 @@ for linkages whose effective lever arm changes through their range of motion. **ActuatorNetMLP / ActuatorNetLSTM.** Learned torque models that use joint-position error and velocity history and clip output with the DC-motor envelope. ``network_file`` is an ONNX model, or a TorchScript checkpoint exported to ONNX when the actuator loads; the network runs with Warp-NN, so it must use -operators that Warp-NN supports. See the :mod:`isaaclab.actuators` API reference for configuration details. +operators that Warp-NN supports. ``scripts/tools/convert_actuator_net_to_onnx.py`` exports a checkpoint to ONNX once. +See the :mod:`isaaclab.actuators` API reference for configuration details. **BamActuatorCfg.** A parameter-identified model of a small voltage-controlled servo, described in :ref:`actuators-bam`. Unlike the PD models it takes no stiffness or damping: its position loop is diff --git a/scripts/tools/convert_actuator_net_to_onnx.py b/scripts/tools/convert_actuator_net_to_onnx.py new file mode 100644 index 000000000000..d161d2066034 --- /dev/null +++ b/scripts/tools/convert_actuator_net_to_onnx.py @@ -0,0 +1,92 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Convert a TorchScript actuator network to the ONNX model that the Isaac Lab network actuators load. + +:class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` run their networks with +Warp-NN from an ONNX model. A TorchScript ``network_file`` is exported to ONNX each time the actuator loads; this script +exports it once, with a batch dimension of any size, so that ``network_file`` can point to the ``.onnx`` file instead. +The script then runs the ONNX model with Warp-NN and compares it with the TorchScript module, so a network that uses an +operator Warp-NN does not support fails here. + +Examples: + +.. code-block:: bash + + ./isaaclab.sh -p scripts/tools/convert_actuator_net_to_onnx.py lstm anydrive_3_lstm_jit.pt anydrive_3_lstm.onnx + ./isaaclab.sh -p scripts/tools/convert_actuator_net_to_onnx.py mlp unitree_go1.pt unitree_go1.onnx + +""" + +import argparse +import io + +import torch +import warp as wp +from warp_nn.runtime import OnnxRuntime + +from isaaclab.utils.assets import read_file +from isaaclab.utils.io import export_torchscript_to_onnx + +# Names the actuators look up; the LSTM states put their batch second, after the layers. +NAMES = { + "lstm": (["input", "h0", "c0"], ["torque", "h1", "c1"]), + "mlp": (["input"], ["torque"]), +} + + +def sample_inputs(kind: str, batch: int): + """Return a function that builds zero inputs of ``batch`` rows for a loaded TorchScript network.""" + + def build(module: torch.jit.ScriptModule) -> tuple: + if kind == "lstm": + weights = module.lstm.state_dict() + state = torch.zeros(len(weights) // 4, batch, weights["weight_hh_l0"].shape[1]) + return torch.zeros(batch, 1, 2), (state, state) + # the first weight matrix is the first layer's, whose columns are the input features + num_features = next(value for value in module.state_dict().values() if value.ndim == 2).shape[1] + return (torch.zeros(batch, num_features),) + + return build + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("kind", choices=sorted(NAMES), help="Network type: the actuator that loads it.") + parser.add_argument("checkpoint", help="TorchScript network file, local or on the Nucleus server.") + parser.add_argument("output", help="Path of the ONNX model to write.") + args = parser.parse_args() + + input_names, output_names = NAMES[args.kind] + batch_axes = {name: {1 if name[0] in "hc" else 0: "batch"} for name in input_names + output_names} + model = export_torchscript_to_onnx( + args.checkpoint, + sample_inputs(args.kind, batch=2), + device="cpu", + input_names=input_names, + output_names=output_names, + dynamic_axes=batch_axes, + ) + with open(args.output, "wb") as file: + file.write(model.getvalue()) + + # run the model with Warp-NN at another batch size and compare it with the TorchScript module + module = torch.jit.load(read_file(args.checkpoint), map_location="cpu").eval() + sample = sample_inputs(args.kind, batch=5)(module) + flat = [torch.randn_like(x) for x in ((sample[0], *sample[1]) if args.kind == "lstm" else sample)] + with torch.no_grad(): + result = module(flat[0], (flat[1], flat[2])) if args.kind == "lstm" else module(flat[0]) + expected = (result[0], *result[1]) if args.kind == "lstm" else (result,) + runtime = OnnxRuntime(io.BytesIO(model.getvalue()), device="cpu") + outputs = runtime({name: wp.from_torch(x) for name, x in zip(input_names, flat)}) + error = max( + (wp.to_torch(outputs[name]).reshape(value.shape) - value).abs().max().item() + for name, value in zip(output_names, expected) + ) + print(f"Wrote {args.output}; max difference from the TorchScript module at batch 5: {error:.2e}") + + +if __name__ == "__main__": + main() diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst index 9a0fb2194333..727c497c5841 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst @@ -3,5 +3,5 @@ * Added :func:`~isaaclab.utils.seed.add_seed_listener`, which calls a bound method with the seed on every :func:`~isaaclab.utils.seed.configure_seed`, so random states kept outside the global generators follow an explicit seed such as ``env.reset(seed=...)``. -* Added :func:`~isaaclab.utils.io.load_onnx_model`, which loads a network file as an ONNX model: an ONNX file as it - is, or a TorchScript module exported to ONNX in memory. +* Added :func:`~isaaclab.utils.io.load_onnx_model`, which reads an ONNX model file, and + :func:`~isaaclab.utils.io.export_torchscript_to_onnx`, which exports a TorchScript module to an ONNX model in memory. diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index 31d1f118de83..93a2bceab5c6 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -1,13 +1,20 @@ * Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` to reset by a Warp kernel when given an environment mask, so a CUDA graph can record the reset. * Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` to run their - networks with Warp-NN, a new dependency. The network file may be an ONNX model, read as it is, or a TorchScript - module, exported to ONNX when the actuator loads; the network must use operators that Warp-NN supports. ``network`` - is now the Warp-NN runtime instead of the TorchScript module. Warp kernels write the network input (for the MLP, - after updating the joint history) and scale the torque and clip it to the DC motor limits; the LSTM's hidden and - cell states carry over in Warp buffers, whose Torch views keep the ``sea_*`` attributes. A Warp graph alone can - therefore record the whole torque computation, and both actuators are now - :attr:`~isaaclab.actuators.ActuatorBase.capturable`. + networks with Warp-NN, a new dependency. The network file may be an ONNX model whose inputs and outputs carry the + names the actuator looks up (the LSTM's ``input``, ``h0`` and ``c0``, and ``torque``, ``h1`` and ``c1``; the MLP's + single input and output under any names), or a TorchScript module, which is exported to ONNX each time the actuator + loads, with a warning; ``scripts/tools/convert_actuator_net_to_onnx.py`` exports it once. ``network`` is now the + Warp-NN runtime instead of the TorchScript module. Warp kernels write the network input (for the MLP, after + updating the joint history) and scale the torque and clip it to the DC motor limits; the LSTM's hidden and cell + states carry over in Warp buffers, whose Torch views keep the ``sea_*`` attributes. A Warp graph alone can therefore + record the whole torque computation, and both actuators are now :attr:`~isaaclab.actuators.ActuatorBase.capturable`. +* Changed the network actuators to reject a network that uses an operator Warp-NN does not support, with an error + that names the network file and the operator; Torch ran such networks before. A common case is an LSTM head that + takes its time step by indexing, ``out[:, -1]``, which exports to ``Gather``: take the step with ``out.squeeze(1)`` + and save the network again. +* Changed :class:`~isaaclab.actuators.DCMotor` to clip its effort in the Warp kernel that the network actuators use; + its ``applied_effort`` is now a view of a preallocated buffer that every step writes in place. * Changed the ray-caster drift resampling on reset to draw from per-environment Warp random states, so a reset recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded from the environment seed when the sensor initializes and again by every diff --git a/source/isaaclab/isaaclab/actuators/actuator_kernels.py b/source/isaaclab/isaaclab/actuators/actuator_kernels.py index f7d3faefea6f..e74a4039f027 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_kernels.py +++ b/source/isaaclab/isaaclab/actuators/actuator_kernels.py @@ -7,6 +7,7 @@ from __future__ import annotations +from functools import cache from typing import Any import torch @@ -151,7 +152,7 @@ def compute_implicit_actuator_batch( """ -Network actuator kernels. +DC motor and network actuator kernels. """ @@ -164,17 +165,41 @@ def dc_motor_clip( velocity_limit: wp.float32, effort_limit: wp.float32, ) -> wp.float32: - """Clip an effort to the DC motor's torque-speed limits, as ``DCMotor._clip_effort`` does.""" + """Clip an effort to the DC motor's torque-speed limits (see :class:`~isaaclab.actuators.DCMotor`).""" vel = wp.min(wp.max(joint_vel, -vel_at_effort_lim), vel_at_effort_lim) max_effort = wp.min(saturation_effort * (1.0 - vel / velocity_limit), effort_limit) min_effort = wp.max(saturation_effort * (-1.0 - vel / velocity_limit), -effort_limit) return wp.min(wp.max(effort, min_effort), max_effort) +@wp.kernel(enable_backward=False) +def clip_dc_motor_effort( + # input + effort: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + saturation_effort: wp.array2d(dtype=wp.float32), + vel_at_effort_lim: wp.array2d(dtype=wp.float32), + velocity_limit: wp.array2d(dtype=wp.float32), + effort_limit: wp.array2d(dtype=wp.float32), + # output + applied_effort: wp.array2d(dtype=wp.float32), +): + """Clip the effort of each (env, joint) to the DC motor limits. Launch with ``dim=(num_envs, num_joints)``.""" + env_id, joint = wp.tid() + applied_effort[env_id, joint] = dc_motor_clip( + effort[env_id, joint], + joint_vel[env_id, joint], + saturation_effort[env_id, joint], + vel_at_effort_lim[env_id, joint], + velocity_limit[env_id, joint], + effort_limit[env_id, joint], + ) + + @wp.kernel(enable_backward=False) def scale_and_clip_torque( # input - torque: wp.array(dtype=wp.float32), + torque: wp.array2d(dtype=wp.float32), joint_vel: wp.array2d(dtype=wp.float32), torque_scale: wp.float32, saturation_effort: wp.array2d(dtype=wp.float32), @@ -187,10 +212,10 @@ def scale_and_clip_torque( ): """Scale the network torque of each (env, joint) and clip it to the DC motor limits. - ``torque`` holds one value per (env, joint), row-major. Launch with ``dim=(num_envs, num_joints)``. + Launch with ``dim=(num_envs, num_joints)``. """ env_id, joint = wp.tid() - effort = torque[env_id * computed_effort.shape[1] + joint] * torque_scale + effort = torque[env_id, joint] * torque_scale computed_effort[env_id, joint] = effort applied_effort[env_id, joint] = dc_motor_clip( effort, @@ -211,14 +236,13 @@ def write_lstm_input( # output network_input: wp.array3d(dtype=wp.float32), ): - """Write the joint position error and velocity of each (env, joint) as its network input row. + """Write the joint position error and velocity of each (env, joint) as its network input. - Launch with ``dim=(num_envs, num_joints)``. + Launch with ``dim=(num_envs, num_joints)``; ``network_input`` has shape ``(num_envs, num_joints, 2)``. """ env_id, joint = wp.tid() - row = env_id * joint_pos.shape[1] + joint - network_input[row, 0, 0] = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] - network_input[row, 0, 1] = joint_vel[env_id, joint] + network_input[env_id, joint, 0] = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] + network_input[env_id, joint, 1] = joint_vel[env_id, joint] @wp.func @@ -230,34 +254,51 @@ def _push_newest(history: wp.array3d(dtype=wp.float32), env_id: int, joint: int, history[env_id, 0, joint] = sample -@wp.kernel(enable_backward=False) -def update_mlp_history( - # input - joint_pos_target: wp.array2d(dtype=wp.float32), - joint_pos: wp.array2d(dtype=wp.float32), - joint_vel: wp.array2d(dtype=wp.float32), - history_indices: wp.array(dtype=wp.int32), - pos_scale: wp.float32, - vel_scale: wp.float32, - pos_first: bool, - # output - joint_pos_error_history: wp.array3d(dtype=wp.float32), - joint_vel_history: wp.array3d(dtype=wp.float32), - network_input: wp.array2d(dtype=wp.float32), -): - """Record the newest joint position error and velocity, then write the scaled samples the network reads. +@cache +def make_update_mlp_history(history_indices: tuple[int, ...], pos_first: bool) -> wp.Kernel: + """Build the kernel that records the newest joint position error and velocity, then writes the scaled samples + the network reads. + + The samples the network reads and the order of its input columns are fixed when the actuator is built, so the + kernel compiles them in; one kernel is built per distinct pair of arguments. + + Args: + history_indices: History samples the network reads, counted from the newest (zero). + pos_first: Whether each network input row holds its position errors before its velocities. - Each row of ``network_input`` belongs to one (env, joint): its position errors, then its velocities when - ``pos_first``, otherwise the reverse. Launch with ``dim=(num_envs, num_joints)``. + Returns: + The kernel. Launch it with ``dim=(num_envs, num_joints)``; its ``network_input`` has shape + ``(num_envs, num_joints, 2 * len(history_indices))``. """ - env_id, joint = wp.tid() - _push_newest(joint_pos_error_history, env_id, joint, joint_pos_target[env_id, joint] - joint_pos[env_id, joint]) - _push_newest(joint_vel_history, env_id, joint, joint_vel[env_id, joint]) - num_samples = history_indices.shape[0] - row = env_id * joint_pos.shape[1] + joint - pos_column = wp.where(pos_first, 0, num_samples) + num_samples = len(history_indices) + sample_indices = wp.types.vector(num_samples, wp.int32)(*history_indices) + pos_column = 0 if pos_first else num_samples vel_column = num_samples - pos_column - for i in range(num_samples): - index = history_indices[i] - network_input[row, pos_column + i] = pos_scale * joint_pos_error_history[env_id, index, joint] - network_input[row, vel_column + i] = vel_scale * joint_vel_history[env_id, index, joint] + + @wp.kernel(enable_backward=False, module="unique") + def update_mlp_history( + # input + joint_pos_target: wp.array2d(dtype=wp.float32), + joint_pos: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + pos_scale: wp.float32, + vel_scale: wp.float32, + # output + joint_pos_error_history: wp.array3d(dtype=wp.float32), + joint_vel_history: wp.array3d(dtype=wp.float32), + network_input: wp.array3d(dtype=wp.float32), + ): + env_id, joint = wp.tid() + error = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] + _push_newest(joint_pos_error_history, env_id, joint, error) + _push_newest(joint_vel_history, env_id, joint, joint_vel[env_id, joint]) + for i in range(wp.static(num_samples)): + index = wp.static(sample_indices)[i] + network_input[env_id, joint, wp.static(pos_column) + i] = ( + pos_scale * joint_pos_error_history[env_id, index, joint] + ) + network_input[env_id, joint, wp.static(vel_column) + i] = ( + vel_scale * joint_vel_history[env_id, index, joint] + ) + + return update_mlp_history diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 83509cf6c9b7..943a3cb59c22 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -14,7 +14,8 @@ from __future__ import annotations -from collections.abc import Sequence +import logging +from collections.abc import Callable, Sequence from typing import TYPE_CHECKING import torch @@ -22,20 +23,22 @@ from warp_nn.runtime import OnnxRuntime from ..utils import index_fill_ -from ..utils.io import load_onnx_model +from ..utils.io import export_torchscript_to_onnx, load_onnx_model from ..utils.types import ArticulationActions from ..utils.warp.memory import make_masked_fill -from .actuator_kernels import scale_and_clip_torque, update_mlp_history, write_lstm_input +from .actuator_kernels import make_update_mlp_history, scale_and_clip_torque, write_lstm_input from .actuator_pd import DCMotor if TYPE_CHECKING: from .actuator_net_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg +logger = logging.getLogger(__name__) -class _NetworkActuator(DCMotor): + +class ActuatorNetBase(DCMotor): """A DC motor whose torque comes from a network that Warp-NN runs, so a Warp graph can record its compute. - The efforts are written by a Warp kernel into preallocated Warp buffers; the actuator's effort attributes are + The efforts are written by Warp kernels into preallocated Warp buffers; the actuator's effort attributes are Torch views of them. """ @@ -43,21 +46,43 @@ def __init__(self, cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, *args, **kwargs) if cfg.network_file is None: raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") super().__init__(cfg, *args, **kwargs) - effort_shape = (self._num_envs, self.num_joints) - self._computed_effort = wp.zeros(effort_shape, dtype=wp.float32, device=self._device) - self._applied_effort = wp.zeros(effort_shape, dtype=wp.float32, device=self._device) + self._computed_effort = wp.zeros((self._num_envs, self.num_joints), dtype=wp.float32, device=self._device) self.computed_effort = wp.to_torch(self._computed_effort) - self.applied_effort = wp.to_torch(self._applied_effort) - # Warp views of the motor limits the clip reads; the limits are written in place, so the views stay valid - self._motor_limits = tuple( - wp.from_torch(limit) - for limit in ( - self._saturation_effort, - self._vel_at_effort_lim, - self.actuator_velocity_limit, - self.actuator_effort_limit, + + def _load_network( + self, + sample_inputs: Callable[[torch.jit.ScriptModule], tuple], + input_names: list[str], + output_names: list[str], + ) -> OnnxRuntime: + """Build the Warp-NN runtime of the network file. + + An ONNX file is read as it is. A TorchScript file is exported to ONNX with ``input_names`` and + ``output_names``, for the batch of ``sample_inputs``, each time the actuator loads; + ``scripts/tools/convert_actuator_net_to_onnx.py`` exports it once instead. + + Raises: + ValueError: If Warp-NN does not support an operator of the network. + """ + network_file = self.cfg.network_file + if network_file.endswith(".onnx"): + model = load_onnx_model(network_file) + else: + logger.warning( + f"Exporting the TorchScript network '{network_file}' to ONNX while the actuator loads. Convert it once" + " with scripts/tools/convert_actuator_net_to_onnx.py and set network_file to the ONNX file instead." ) - ) + model = export_torchscript_to_onnx( + network_file, sample_inputs, device=self._device, input_names=input_names, output_names=output_names + ) + try: + return OnnxRuntime(model, device=self._device) + except NotImplementedError as error: + raise ValueError( + f"Warp-NN cannot run the network in '{network_file}': {error}. Rewrite the operation and export the" + " network again; for example, an LSTM head that takes its time step by indexing (out[:, -1]) exports" + " to Gather, while out.squeeze(1) exports to Squeeze." + ) from error def _apply_torque( self, control_action: ArticulationActions, torque: wp.array, joint_vel: torch.Tensor, torque_scale: float @@ -67,7 +92,7 @@ def _apply_torque( scale_and_clip_torque, dim=(self._num_envs, self.num_joints), inputs=[ - torque.reshape((self._num_envs * self.num_joints,)), + torque.reshape((self._num_envs, self.num_joints)), wp.from_torch(joint_vel), torque_scale, *self._motor_limits, @@ -81,7 +106,7 @@ def _apply_torque( return control_action -class ActuatorNetLSTM(_NetworkActuator): +class ActuatorNetLSTM(ActuatorNetBase): """Actuator model based on recurrent neural network (LSTM). Unlike the MLP implementation :cite:t:`hwangbo2019learning`, this class implements @@ -103,31 +128,33 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): batch = self._num_envs * self.num_joints def sample_inputs(module: torch.jit.ScriptModule) -> tuple: - # inputs that trace a TorchScript network for its ONNX export: one sample and zero states per row - state = torch.zeros(module.lstm.num_layers, batch, module.lstm.hidden_size, device=self._device) + # one sample and zero states per row; the layer count and hidden size come from the weights, which a + # traced module keeps while it drops the LSTM's attributes + weights = module.lstm.state_dict() + state = torch.zeros(len(weights) // 4, batch, weights["weight_hh_l0"].shape[1], device=self._device) return torch.zeros(batch, 1, 2, device=self._device), (state, state) # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference - model = load_onnx_model( - self.cfg.network_file, - sample_inputs, - device=self._device, - input_names=["input", "h0", "c0"], - output_names=["torque", "h1", "c1"], - ) - self.network = OnnxRuntime(model, device=self._device) - # an ONNX file keeps the names it was exported with: the input, the hidden state, then the cell state - self._network_output_names = [spec.name for spec in self.network.outputs] + input_names, output_names = ["input", "h0", "c0"], ["torque", "h1", "c1"] + self.network = self._load_network(sample_inputs, input_names, output_names) + # the inputs and outputs are looked up by name: the input, then the hidden and cell states and their updates + found = [spec.name for spec in self.network.inputs], [spec.name for spec in self.network.outputs] + if (set(found[0]), set(found[1])) != (set(input_names), set(output_names)): + raise ValueError( + f"The LSTM network in '{cfg.network_file}' must take the inputs {input_names} and return the outputs" + f" {output_names}; it takes {found[0]} and returns {found[1]}." + ) # create buffers for the network input and the LSTM states, one row per (env, joint) - num_layers, _, hidden_dim = self.network.inputs[1].shape + num_layers, _, hidden_dim = next(spec for spec in self.network.inputs if spec.name == "h0").shape self._network_input = wp.zeros((batch, 1, 2), dtype=wp.float32, device=self._device) self._hidden_state = wp.zeros((num_layers, batch, hidden_dim), dtype=wp.float32, device=self._device) self._cell_state = wp.zeros_like(self._hidden_state) - buffers = (self._network_input, self._hidden_state, self._cell_state) - self._network_inputs = {spec.name: buffer for spec, buffer in zip(self.network.inputs, buffers)} + self._network_inputs = {"input": self._network_input, "h0": self._hidden_state, "c0": self._cell_state} # run the network once: Warp-NN allocates its outputs and loads its kernels, which a CUDA graph cannot record self.network.prepare(self._network_inputs) + # the network input per (env, joint), which the input kernel writes + self._network_input_per_env = self._network_input.reshape((self._num_envs, self.num_joints, 2)) # Torch views of the buffers; the per-env views reshape without changing the memory layout self.sea_input = wp.to_torch(self._network_input) self.sea_hidden_state = wp.to_torch(self._hidden_state) @@ -166,19 +193,18 @@ def compute( write_lstm_input, dim=(self._num_envs, self.num_joints), inputs=[wp.from_torch(control_action.joint_positions), wp.from_torch(joint_pos), wp.from_torch(joint_vel)], - outputs=[self._network_input], + outputs=[self._network_input_per_env], device=self._device, ) # run network inference; its new states are the ones the next step reads outputs = self.network(self._network_inputs) - torque, hidden_state, cell_state = (outputs[name] for name in self._network_output_names) - wp.copy(self._hidden_state, hidden_state) - wp.copy(self._cell_state, cell_state) + wp.copy(self._hidden_state, outputs["h1"]) + wp.copy(self._cell_state, outputs["c1"]) # clip the torque based on the motor limits - return self._apply_torque(control_action, torque, joint_vel, 1.0) + return self._apply_torque(control_action, outputs["torque"], joint_vel, 1.0) -class ActuatorNetMLP(_NetworkActuator): +class ActuatorNetMLP(ActuatorNetBase): """Actuator model based on multi-layer perceptron and joint history. Many times the analytical model is not sufficient to capture the actuator dynamics, the @@ -211,31 +237,33 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): f"Invalid input order for MLP actuator net: {self.cfg.input_order}. Must be 'pos_vel' or 'vel_pos'." ) # the history samples the network reads; negative indices count back from the oldest sample - indices = [index % history_length for index in self.cfg.input_idx] + indices = tuple(index % history_length for index in self.cfg.input_idx) + input_shape = (self._num_envs * self.num_joints, 2 * len(indices)) # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference - model = load_onnx_model( - self.cfg.network_file, - (torch.zeros(self._num_envs * self.num_joints, 2 * len(indices), device=self._device),), - device=self._device, - input_names=["input"], - output_names=["torque"], + self.network = self._load_network( + lambda module: (torch.zeros(input_shape, device=self._device),), ["input"], ["torque"] ) - self.network = OnnxRuntime(model, device=self._device) - # an ONNX file keeps the input and output names it was exported with + # one input and one output, whatever an ONNX file names them + if len(self.network.inputs) != 1 or len(self.network.outputs) != 1: + raise ValueError( + f"The MLP network in '{cfg.network_file}' must take one input and return one output; it takes" + f" {len(self.network.inputs)} and returns {len(self.network.outputs)}." + ) self._network_input_name = self.network.inputs[0].name self._network_output_name = self.network.outputs[0].name - # create buffers for MLP history, newest sample first + # create buffers for MLP history, newest sample first, and the kernel that updates it history_shape = (self._num_envs, history_length, self.num_joints) self._joint_pos_error_history = wp.zeros(history_shape, dtype=wp.float32, device=self._device) self._joint_vel_history = wp.zeros(history_shape, dtype=wp.float32, device=self._device) - self._history_indices = wp.array(indices, dtype=wp.int32, device=self._device) + self._update_history = make_update_mlp_history(indices, self.cfg.input_order == "pos_vel") # the network input, one row per (env, joint) - input_shape = (self._num_envs * self.num_joints, 2 * len(indices)) self._network_input = wp.zeros(input_shape, dtype=wp.float32, device=self._device) # run the network once: Warp-NN allocates its outputs and loads its kernels, which a CUDA graph cannot record self.network.prepare({self._network_input_name: self._network_input}) + # the network input per (env, joint), which the history kernel writes + self._network_input_per_env = self._network_input.reshape((self._num_envs, self.num_joints, input_shape[1])) """ Operations. @@ -259,18 +287,16 @@ def compute( ) -> ArticulationActions: # move history queue by 1, update top of history and write the scaled network input wp.launch( - update_mlp_history, + self._update_history, dim=(self._num_envs, self.num_joints), inputs=[ wp.from_torch(control_action.joint_positions), wp.from_torch(joint_pos), wp.from_torch(joint_vel), - self._history_indices, self.cfg.pos_scale, self.cfg.vel_scale, - self.cfg.input_order == "pos_vel", ], - outputs=[self._joint_pos_error_history, self._joint_vel_history, self._network_input], + outputs=[self._joint_pos_error_history, self._joint_vel_history, self._network_input_per_env], device=self._device, ) # run network inference diff --git a/source/isaaclab/isaaclab/actuators/actuator_pd.py b/source/isaaclab/isaaclab/actuators/actuator_pd.py index a7cb32e4a78d..ca65fdd9b087 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_pd.py +++ b/source/isaaclab/isaaclab/actuators/actuator_pd.py @@ -15,6 +15,7 @@ from ..utils import DelayBuffer, LinearInterpolation from ..utils.types import ArticulationActions +from . import actuator_kernels from .actuator_base import ActuatorBase, resolve_joint_parameter if TYPE_CHECKING: @@ -458,24 +459,35 @@ def __init__(self, cfg: DCMotorCfg, *args, **kwargs): self._vel_at_effort_lim = self.actuator_velocity_limit * ( 1 + self.actuator_effort_limit / self._saturation_effort ) + # Warp views of the motor limits the clip reads; the limits are written in place, so the views stay valid + self._motor_limits = tuple( + wp.from_torch(limit) + for limit in ( + self._saturation_effort, + self._vel_at_effort_lim, + self.actuator_velocity_limit, + self.actuator_effort_limit, + ) + ) + # the clipped effort, written in place by a Warp kernel; applied_effort is its Torch view + self._applied_effort = wp.zeros((self._num_envs, self.num_joints), dtype=wp.float32, device=self._device) + self.applied_effort = wp.to_torch(self._applied_effort) """ Helper functions. """ def _clip_effort(self, effort: torch.Tensor, joint_vel: torch.Tensor) -> torch.Tensor: - # Clamp the local value without modifying the measured joint velocity. - joint_vel = torch.clip(joint_vel, min=-self._vel_at_effort_lim, max=self._vel_at_effort_lim) - # compute torque limits - torque_speed_top = self._saturation_effort * (1.0 - joint_vel / self.actuator_velocity_limit) - torque_speed_bottom = self._saturation_effort * (-1.0 - joint_vel / self.actuator_velocity_limit) - # -- max limit - max_effort = torch.clip(torque_speed_top, max=self.actuator_effort_limit) - # -- min limit - min_effort = torch.clip(torque_speed_bottom, min=-self.actuator_effort_limit) - # clip the torques based on the motor limits - clamped = torch.clip(effort, min=min_effort, max=max_effort) - return clamped + # clip to the torque-speed curve in the Warp kernel the network actuators share; the measured joint velocity + # is only read + wp.launch( + actuator_kernels.clip_dc_motor_effort, + dim=(self._num_envs, self.num_joints), + inputs=[wp.from_torch(effort), wp.from_torch(joint_vel), *self._motor_limits], + outputs=[self._applied_effort], + device=self._device, + ) + return self.applied_effort class DelayedPDActuator(_DelayedActuator, IdealPDActuator): diff --git a/source/isaaclab/isaaclab/utils/io/__init__.pyi b/source/isaaclab/isaaclab/utils/io/__init__.pyi index 91692a594c16..47f24213c74c 100644 --- a/source/isaaclab/isaaclab/utils/io/__init__.pyi +++ b/source/isaaclab/isaaclab/utils/io/__init__.pyi @@ -4,12 +4,13 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ + "export_torchscript_to_onnx", "load_onnx_model", "load_torchscript_model", "dump_yaml", "load_yaml", ] -from .onnx import load_onnx_model +from .onnx import export_torchscript_to_onnx, load_onnx_model from .torchscript import load_torchscript_model from .yaml import dump_yaml, load_yaml diff --git a/source/isaaclab/isaaclab/utils/io/onnx.py b/source/isaaclab/isaaclab/utils/io/onnx.py index e8bc643d411c..be95d4d89bfb 100644 --- a/source/isaaclab/isaaclab/utils/io/onnx.py +++ b/source/isaaclab/isaaclab/utils/io/onnx.py @@ -13,41 +13,59 @@ from ..assets import read_file -def load_onnx_model( +def load_onnx_model(model_path: str) -> io.BytesIO: + """Read an ONNX model file. + + Args: + model_path: Path to the ``.onnx`` file, local or on the Nucleus server. + + Returns: + The ONNX model. + + Raises: + ValueError: If the file is not an ``.onnx`` file. + """ + if not model_path.endswith(".onnx"): + raise ValueError(f"Expected an ONNX model file (.onnx), got '{model_path}'.") + return read_file(model_path) + + +def export_torchscript_to_onnx( model_path: str, - sample_inputs: tuple | Callable[[torch.jit.ScriptModule], tuple], + sample_inputs: Callable[[torch.jit.ScriptModule], tuple], *, device: str, input_names: list[str], output_names: list[str], + dynamic_axes: dict[str, dict[int, str]] | None = None, ) -> io.BytesIO: - """Load a network file as an ONNX model. + """Load a TorchScript module and export it to an ONNX model in memory. - An ``.onnx`` file is read as it is. Any other file is loaded as a TorchScript module and exported to ONNX in - memory, with the TorchScript exporter since the dynamo exporter does not accept TorchScript modules. + The module is exported with the TorchScript exporter, since the dynamo exporter does not accept TorchScript + modules. Args: - model_path: Path to the network file, local or on the Nucleus server. - sample_inputs: Inputs that trace the TorchScript module for the export, on ``device``, or a function that - returns them from the loaded module. The exported model takes inputs of their shapes. - device: Device to load the TorchScript module on. + model_path: Path to the TorchScript file, local or on the Nucleus server. + sample_inputs: Function that returns, from the loaded module, the inputs that trace it for the export, on + ``device``. The exported model takes inputs of their shapes, except along ``dynamic_axes``. + device: Device to load the module on. input_names: Names of the exported model's inputs. output_names: Names of the exported model's outputs. + dynamic_axes: Axes of the named inputs and outputs that take any size, as :func:`torch.onnx.export` takes + them. Defaults to None, in which case every axis keeps the size of the sample inputs. Returns: - The ONNX model. An ``.onnx`` file keeps its own input and output names. + The ONNX model. """ - file_bytes = read_file(model_path) - if model_path.endswith(".onnx"): - return file_bytes - module = torch.jit.load(file_bytes, map_location=device).eval() + module = torch.jit.load(read_file(model_path), map_location=device).eval() model = io.BytesIO() torch.onnx.export( module, - sample_inputs(module) if callable(sample_inputs) else sample_inputs, + sample_inputs(module), model, input_names=input_names, output_names=output_names, + dynamic_axes=dynamic_axes, dynamo=False, ) model.seek(0) diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index b396de6cb236..25d39ca773f0 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -9,7 +9,7 @@ import torch import warp as wp -from isaaclab.actuators import ActuatorNetLSTMCfg, ActuatorNetMLPCfg, DCMotor +from isaaclab.actuators import ActuatorNetLSTMCfg, ActuatorNetMLPCfg from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils import instantiate from isaaclab.utils.types import ArticulationActions @@ -42,13 +42,27 @@ def _feature_torque_mlp(num_features: int) -> torch.nn.Linear: return network -def _export_onnx(network: torch.nn.Module, path): - """Export ``network`` to ONNX with names other than the ones the actuator exports TorchScript with.""" +class _IndexedHeadLSTM(_TorqueLSTM): + """The LSTM with a head that takes its time step by indexing, which exports to an operator Warp-NN lacks.""" + + def forward( + self, x: torch.Tensor, hc: tuple[torch.Tensor, torch.Tensor] + ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: + y, hc = self.lstm(x, hc) + return self.linear(y[:, -1, :]).squeeze(-1), hc + + +def _lstm_sample(network: torch.nn.Module, batch: int) -> tuple: + state = torch.zeros(network.lstm.num_layers, batch, network.lstm.hidden_size) + return torch.zeros(batch, 1, 2), (state, state) + + +def _export_onnx(network: torch.nn.Module, path, lstm_names=(["input", "h0", "c0"], ["torque", "h1", "c1"])): + """Export ``network`` to ONNX: an MLP with names of its own, an LSTM with ``lstm_names``.""" if isinstance(network, torch.nn.Linear): - sample, inputs, outputs = (torch.zeros(1, network.in_features),), ["obs"], ["act"] + sample, (inputs, outputs) = (torch.zeros(1, network.in_features),), (["obs"], ["act"]) else: - state = torch.zeros(network.lstm.num_layers, 1, network.lstm.hidden_size) - sample, inputs, outputs = (torch.zeros(1, 1, 2), (state, state)), ["obs", "h", "c"], ["act", "h_next", "c_next"] + sample, (inputs, outputs) = _lstm_sample(network, batch=1), lstm_names # the LSTM states put their batch second, after the layers axes = {name: {1 if name[0] in "hc" else 0: "batch"} for name in inputs + outputs} torch.onnx.export( @@ -57,9 +71,15 @@ def _export_onnx(network: torch.nn.Module, path): def _actuator(cfg_class, network: torch.nn.Module, tmp_path, device: str, network_format: str = "pt", **cfg): - network_file = tmp_path / f"network.{network_format}" + """Build the actuator from ``network`` saved as a scripted (``pt``) or ``traced`` TorchScript file, or as an ONNX + file with the names the actuator looks up (``onnx``) or with other names (``misnamed_onnx``).""" + network_file = tmp_path / ("network.onnx" if network_format.endswith("onnx") else "network.pt") if network_format == "onnx": _export_onnx(network, network_file) + elif network_format == "misnamed_onnx": + _export_onnx(network, network_file, (["obs", "h", "c"], ["act", "h_next", "c_next"])) + elif network_format == "traced": + torch.jit.trace(network, _lstm_sample(network, batch=2)).save(str(network_file)) else: torch.jit.script(network).save(str(network_file)) cfg = cfg_class( @@ -73,6 +93,16 @@ def _actuator(cfg_class, network: torch.nn.Module, tmp_path, device: str, networ return instantiate(cfg, joint_names=["joint_0", "joint_1"], joint_ids=[0, 1], num_envs=3, device=device) +def _dc_motor_clip(actuator, effort: torch.Tensor, joint_vel: torch.Tensor) -> torch.Tensor: + """The DC motor's torque-speed clip, written with Torch as a reference independent of the actuator's kernel.""" + vel = joint_vel.clamp(-actuator._vel_at_effort_lim, actuator._vel_at_effort_lim) + top = actuator._saturation_effort * (1.0 - vel / actuator.actuator_velocity_limit) + bottom = actuator._saturation_effort * (-1.0 - vel / actuator.actuator_velocity_limit) + return effort.clamp( + bottom.clamp(min=-actuator.actuator_effort_limit), top.clamp(max=actuator.actuator_effort_limit) + ) + + def _record_masked_reset(actuator, mask: wp.array) -> wp.Graph: """A CUDA graph of the actuator's reset of the masked environments; the graph reads ``mask`` when it replays.""" with wp.ScopedCapture(mask.device) as capture: @@ -176,11 +206,11 @@ def test_compute_replays_from_a_warp_graph(tmp_path, device, model): @pytest.mark.parametrize("device", test_devices()) -@pytest.mark.parametrize("network_format", ["pt", "onnx"]) +@pytest.mark.parametrize("network_format", ["pt", "traced", "onnx"]) def test_lstm_state_carries_across_steps(tmp_path, device, network_format): """Computed torque follows the network with its hidden and cell states carried from step to step and zeroed by - partial resets, with a TorchScript or an ONNX network file; the applied torque is clipped as the Torch DC motor - clips it.""" + partial resets, with a scripted or traced TorchScript or an ONNX network file; the applied torque is clipped to + the DC motor's torque-speed curve.""" network = _TorqueLSTM() actuator = _actuator(ActuatorNetLSTMCfg, network, tmp_path, device, network_format) network = network.to(device) @@ -200,7 +230,20 @@ def test_lstm_state_carries_across_steps(tmp_path, device, network_format): expected = torque.reshape(3, 2) actuator.compute(ArticulationActions(joint_positions=desired), position, velocity) torch.testing.assert_close(actuator.computed_effort, expected) - torch.testing.assert_close(actuator.applied_effort, DCMotor._clip_effort(actuator, expected, velocity)) + torch.testing.assert_close(actuator.applied_effort, _dc_motor_clip(actuator, expected, velocity)) + + +@pytest.mark.parametrize( + ("network", "network_format", "message"), + [(_IndexedHeadLSTM, "pt", "Gather"), (_TorqueLSTM, "misnamed_onnx", "must take the inputs")], + ids=["unsupported_operator", "misnamed_onnx"], +) +def test_lstm_rejects_a_network_it_cannot_run(tmp_path, network, network_format, message): + """A network with an operator Warp-NN does not support, or an ONNX file without the names the actuator looks up, + fails to load with an error that names the network file.""" + with pytest.raises(ValueError, match=message) as error: + _actuator(ActuatorNetLSTMCfg, network(), tmp_path, "cpu", network_format) + assert str(tmp_path) in str(error.value) def test_mlp_rejects_invalid_history_before_loading_checkpoint(tmp_path): @@ -227,7 +270,7 @@ def test_mlp_rejects_invalid_history_before_loading_checkpoint(tmp_path): ) def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order, network_format): """Computed torque follows the selected zero-padded history across wraparound and partial resets, with a - TorchScript or an ONNX network file; the applied torque is clipped as the Torch DC motor clips it.""" + TorchScript or an ONNX network file; the applied torque is clipped to the DC motor's torque-speed curve.""" network = _feature_torque_mlp(2 * len(input_idx)) actuator = _actuator( ActuatorNetMLPCfg, @@ -276,6 +319,6 @@ def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order, expected = network(features).detach().reshape(3, 2) * 20.0 actuator.compute(ArticulationActions(joint_positions=desired), position, velocity) torch.testing.assert_close(actuator.computed_effort, expected) - torch.testing.assert_close(actuator.applied_effort, DCMotor._clip_effort(actuator, expected, velocity)) + torch.testing.assert_close(actuator.applied_effort, _dc_motor_clip(actuator, expected, velocity)) clipped |= not torch.equal(actuator.applied_effort, actuator.computed_effort) assert clipped From 55d930dbd1aa8558551c78829b9b1fba1522dcec Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 1 Dec 2026 19:19:32 -0800 Subject: [PATCH 26/31] Keep the env_mask device check out of ActuatorCollection.reset The collection, like the other reset paths, takes a mask on its own device; drop the copy of a mask from another device, its test case and its changelog entry. --- ...jichuanh-actuator-net-mask-reset.fixed.rst | 2 -- .../isaaclab/actuators/actuator_collection.py | 6 +---- .../actuators/test_actuator_collection.py | 25 +++++++------------ 3 files changed, 10 insertions(+), 23 deletions(-) delete mode 100644 source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.fixed.rst diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.fixed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.fixed.rst deleted file mode 100644 index 7cba789b5c1e..000000000000 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.fixed.rst +++ /dev/null @@ -1,2 +0,0 @@ -* Fixed :meth:`~isaaclab.actuators.ActuatorCollection.reset` of a CUDA collection failing for an ``env_mask`` on the - host; the mask is copied to the collection's device once. diff --git a/source/isaaclab/isaaclab/actuators/actuator_collection.py b/source/isaaclab/isaaclab/actuators/actuator_collection.py index 0b594dd64c58..e2810985dcad 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_collection.py +++ b/source/isaaclab/isaaclab/actuators/actuator_collection.py @@ -196,12 +196,8 @@ def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array Args: env_ids: Environment indices to reset. Defaults to all environments. env_mask: Boolean mask of the environments to reset. Shape is (num_instances,). Takes precedence over - ``env_ids`` and does not synchronize the device. A mask on another device is copied to the - collection's device first. Defaults to None. + ``env_ids`` and does not synchronize the device. Defaults to None. """ - if env_mask is not None and env_mask.device != wp.get_device(self.device): - # a mask from another device (e.g. the host) is copied once; a mask on this device is used as given - env_mask = env_mask.to(self.device) group_env_ids = None if env_mask is not None else self._control._normalize_index_sequence(env_ids) for actuator in self._groups.values(): # Newton-executed groups are reset through the backend below. diff --git a/source/isaaclab/test/actuators/test_actuator_collection.py b/source/isaaclab/test/actuators/test_actuator_collection.py index 28ccf27369bf..2ab078d58581 100644 --- a/source/isaaclab/test/actuators/test_actuator_collection.py +++ b/source/isaaclab/test/actuators/test_actuator_collection.py @@ -1014,16 +1014,12 @@ def test_write_command_mask_uses_full_sized_value(command_name): setter(value=value, env_mask=wp.array([1, 0], dtype=wp.int32, device="cpu"), joint_mask=joint_mask) -@pytest.mark.parametrize("host_mask", [False, True], ids=["device_mask", "host_mask"]) @pytest.mark.parametrize( ("device", "delay"), [(device, 2) for device in test_devices()] + [pytest.param("cpu", None, id="cpu-default-delay")], ) -def test_masked_reset_leaves_unselected_envs_untouched(device, delay, host_mask): - """A mask reset redraws the masked environments' delays and keeps the others: a mask on the collection's device - without a device sync, a mask on the host after one copy to the device.""" - if host_mask and not device.startswith("cuda"): - pytest.skip("on the CPU a host mask is on the collection's device") +def test_masked_reset_leaves_unselected_envs_untouched(device, delay): + """A mask reset redraws the masked environments' delays without a device sync and keeps the others.""" control = FakeActuatorControl(num_envs=4, device=device) # The default max_delay of None runs without delay. cfg = DelayedPDActuatorCfg( @@ -1038,16 +1034,13 @@ def test_masked_reset_leaves_unselected_envs_untouched(device, delay, host_mask) collection.compute() env_mask = torch.tensor([False, True, False, True], device=device) - if host_mask: - collection.reset(env_mask=wp.from_torch(env_mask.cpu(), dtype=wp.bool)) - else: - if device.startswith("cuda"): - torch.cuda.synchronize(device) - torch.cuda.set_sync_debug_mode("error") - try: - collection.reset(env_mask=wp.from_torch(env_mask, dtype=wp.bool)) - finally: - torch.cuda.set_sync_debug_mode("default") + if device.startswith("cuda"): + torch.cuda.synchronize(device) + torch.cuda.set_sync_debug_mode("error") + try: + collection.reset(env_mask=wp.from_torch(env_mask, dtype=wp.bool)) + finally: + torch.cuda.set_sync_debug_mode("default") for delay_buffer in buffers: torch.testing.assert_close( From e07b99f286d4a586766e553a21ec2d186a09550c Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 1 Dec 2026 19:19:42 -0800 Subject: [PATCH 27/31] Seed ray-caster drift once when the rays initialize Seed the per-environment drift states from the environment seed when the rays initialize, and key each sensor's stream on its prim path and offset instead of a hash of its whole configuration, so unrelated fields no longer change the drift and configurations with callables such as functools.partial patterns build. Remove the configure_seed listener registry; a later env.reset(seed=...) no longer restarts the drift sequence. --- ...jichuanh-actuator-net-mask-reset.added.rst | 3 -- ...chuanh-actuator-net-mask-reset.changed.rst | 9 ++-- .../sensors/ray_caster/base_ray_caster.py | 41 +++++++------------ source/isaaclab/isaaclab/utils/seed.py | 21 +--------- .../sensors/test_newton_raycast_sensor.py | 16 +++----- 5 files changed, 24 insertions(+), 66 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst index 727c497c5841..b3468fddfeee 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.added.rst @@ -1,7 +1,4 @@ * Added :func:`~isaaclab.utils.warp.kernels.initialize_rng_state`, which seeds one Warp random number generator state per environment for kernels that draw per-environment random numbers. -* Added :func:`~isaaclab.utils.seed.add_seed_listener`, which calls a bound method with the seed on every - :func:`~isaaclab.utils.seed.configure_seed`, so random states kept outside the global generators follow an - explicit seed such as ``env.reset(seed=...)``. * Added :func:`~isaaclab.utils.io.load_onnx_model`, which reads an ONNX model file, and :func:`~isaaclab.utils.io.export_torchscript_to_onnx`, which exports a TorchScript module to an ONNX model in memory. diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index 93a2bceab5c6..ecdd96ecee00 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -17,8 +17,7 @@ its ``applied_effort`` is now a view of a preallocated buffer that every step writes in place. * Changed the ray-caster drift resampling on reset to draw from per-environment Warp random states, so a reset recorded in a CUDA graph resamples the drift of the selected environments on every replay. The states are seeded - from the environment seed when the sensor initializes and again by every - :func:`~isaaclab.utils.seed.configure_seed`, including the one ``env.reset(seed=...)`` makes, so a seeded reset - repeats the drift and unseeded resets keep advancing it. Ray casters with different configurations draw different - drift; identical configurations draw the same drift. Drift no longer draws from Torch's generator. The drift ranges - are unchanged; the drawn values differ. + once, when the sensor initializes, from the environment seed and the sensor's prim path and offset: ray casters on + one prim at different offsets draw different drift, and a sensor draws the same drift in every process with the + same seed. A later ``env.reset(seed=...)`` does not restart the drift sequence. Drift no longer draws from Torch's + generator. The drift ranges are unchanged; the drawn values differ. diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py index e3594b99209e..0e4d5560bc04 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py @@ -5,7 +5,6 @@ from __future__ import annotations -import json import logging import zlib from collections.abc import Sequence @@ -22,7 +21,6 @@ from ...terrains.trimesh.utils import make_plane from ...utils import math as math_utils from ...utils.mesh import convert_faces_to_triangles -from ...utils.seed import add_seed_listener from ...utils.warp import ProxyArray, convert_to_warp_mesh from ...utils.warp.kernels import initialize_rng_state, raycast_mesh_masked_kernel from ..sensor_base import SensorBase @@ -78,11 +76,11 @@ def __init__(self, cfg: RayCasterCfg): super().__init__(cfg) self._data = RayCasterData() self._drift_sampled = False - # Drift random states, allocated when the rays initialize; every configure_seed reseeds them. + # Drift random states, allocated and seeded when the rays initialize. self._drift_rng_state: wp.array | None = None - # A drift stream from the configuration, which writes callables by name, so it repeats across processes. - self._drift_stream = zlib.crc32(json.dumps(self.cfg.to_dict(), sort_keys=True, default=str).encode()) - add_seed_listener(self._seed_drift) + # A drift stream per prim and offset, so ray casters on one prim at different offsets draw different drift, + # and the same sensor draws the same drift in every process. + self._drift_stream = zlib.crc32(f"{self.cfg.prim_path}|{self.cfg.offset.pos}|{self.cfg.offset.rot}".encode()) def __str__(self) -> str: """Returns: A string containing information about the instance.""" @@ -251,10 +249,17 @@ def _initialize_rays_impl(self): # Drift buffers are warp-first; reset resamples them in a Warp kernel. self.drift = ProxyArray(wp.zeros(self._view_count, dtype=wp.vec3f, device=self._device)) self.ray_cast_drift = ProxyArray(wp.zeros(self._view_count, dtype=wp.vec3f, device=self._device)) - # Per-environment random states for drift resampling, seeded from the environment seed (which - # configure_seed stores as torch's initial seed; reading it draws nothing); resets only draw from them. + # Per-environment random states for drift resampling, seeded once from the environment seed (which + # configure_seed stores as torch's initial seed; reading it draws nothing) mixed with the drift stream; + # resets only draw from them. self._drift_rng_state = wp.empty(self._view_count, dtype=wp.uint32, device=self._device) - self._seed_drift(torch.initial_seed()) + wp.launch( + initialize_rng_state, + dim=self._view_count, + inputs=[(torch.initial_seed() ^ self._drift_stream) & 0x7FFFFFFF], + outputs=[self._drift_rng_state], + device=self._device, + ) # World-frame ray buffers self._ray_starts_w = wp.empty((self._view_count, self.num_rays), dtype=wp.vec3f, device=self._device) @@ -271,24 +276,6 @@ def _initialize_rays_impl(self): self._dummy_ray_distance = wp.empty((1, 1), dtype=wp.float32, device=self._device) self._dummy_ray_normal = wp.empty((1, 1), dtype=wp.vec3f, device=self._device) - def _seed_drift(self, seed: int) -> None: - """Seed the drift random states from ``seed`` mixed with the configuration's drift stream. - - Ray casters with different configurations, including ray casters on one prim at different offsets, draw - different drift; identical configurations draw the same drift. Runs when the rays initialize and on every - :func:`~isaaclab.utils.seed.configure_seed`, on the host where the seed is set, never inside a recorded reset. - """ - # No states before the rays initialize, and none in the ray-caster cameras, which do not resample drift. - if self._drift_rng_state is None: - return - wp.launch( - initialize_rng_state, - dim=self._view_count, - inputs=[(seed ^ self._drift_stream) & 0x7FFFFFFF], - outputs=[self._drift_rng_state], - device=self._device, - ) - def _get_view_transforms_wp(self) -> wp.array: """Get world transforms from the frame view as a warp array of ``wp.transformf``. diff --git a/source/isaaclab/isaaclab/utils/seed.py b/source/isaaclab/isaaclab/utils/seed.py index 568c5838e317..535789305164 100644 --- a/source/isaaclab/isaaclab/utils/seed.py +++ b/source/isaaclab/isaaclab/utils/seed.py @@ -5,28 +5,14 @@ import os import random -import weakref -from collections.abc import Callable import numpy as np import torch import warp as wp -_seed_listeners: list[weakref.WeakMethod] = [] - - -def add_seed_listener(listener: Callable[[int], None]) -> None: - """Call a bound method with the seed after every :func:`configure_seed`. - - Args: - listener: Bound method that reseeds its object's random state. The object is held weakly, so the listener - stops when the object is deleted. - """ - _seed_listeners.append(weakref.WeakMethod(listener)) - def configure_seed(seed: int | None, torch_deterministic: bool = False) -> int: - """Set seed across all random number generators (torch, numpy, random, warp) and pass it to the seed listeners. + """Set seed across all random number generators (torch, numpy, random, warp). Args: seed: The random seed value. If None, generates a random seed. @@ -46,11 +32,6 @@ def configure_seed(seed: int | None, torch_deterministic: bool = False) -> int: torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) wp.rand_init(seed) - for listener_ref in list(_seed_listeners): - if (listener := listener_ref()) is None: - _seed_listeners.remove(listener_ref) - else: - listener(seed) if torch_deterministic: # refer to https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility diff --git a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py index ef0822648121..7235e2661f33 100644 --- a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py @@ -257,12 +257,11 @@ def test_partial_reset_resamples_drift_of_selected_envs_only(sim): @pytest.mark.parametrize("sim", [pytest.param(False, id="eager")], indirect=True) def test_drift_follows_the_environment_seed(sim): - """An explicit seed, as ``env.reset(seed=...)`` sets, restarts the drift sequence; unseeded resets advance it. + """The environment seed fixes each ray caster's drift sequence when its rays initialize; resets advance it. Resets do not draw from torch's generator, and new storage, as after a simulation stop and play, starts the - drift sequence of the current seed again. Two ray casters on the same prim with the same drift ranges draw - different drift after every seed, and a ray caster built later with the same configuration, as in a second - environment instance, repeats the drift. + drift sequence again. Two ray casters on the same prim at different offsets draw different drift, and a ray + caster on the same prim at the same offset, as in a second environment instance, repeats the drift. """ scene_cfg = RaycastTestSceneCfg(num_envs=2) scene_cfg.raycast.drift_range = (0.01, 0.05) @@ -270,11 +269,12 @@ def test_drift_follows_the_environment_seed(sim): scene_cfg.raycast_twin = replace(scene_cfg.raycast, offset=twin_offset) scene_cfg.raycast_copy = scene_cfg.raycast.copy() scene = InteractiveScene(scene_cfg) + configure_seed(123) sim.reset() sensor: NewtonRaycastSensor = scene["raycast"] twin: NewtonRaycastSensor = scene["raycast_twin"] - configure_seed(123) + state = torch.cuda.get_rng_state(sensor.device) sensor.reset() first = sensor.drift.torch.clone() twin.reset() @@ -283,12 +283,6 @@ def test_drift_follows_the_environment_seed(sim): torch.testing.assert_close(scene["raycast_copy"].drift.torch, first) sensor.reset() assert not torch.allclose(sensor.drift.torch, first) - configure_seed(123) - state = torch.cuda.get_rng_state(sensor.device) - sensor.reset() - torch.testing.assert_close(sensor.drift.torch, first) - twin.reset() - assert not torch.allclose(twin.drift.torch, first) sensor._initialize_rays_impl() sensor.reset() torch.testing.assert_close(sensor.drift.torch, first) From 8f2987c8ae8c1f92899985deb80bd03510e2ea10 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 1 Dec 2026 20:00:46 -0800 Subject: [PATCH 28/31] Index network buffers by row and pass the MLP history samples as arguments The networks take one row per (environment, joint): the ONNX LSTM operator has a single batch axis and the MLP's first layer is a Gemm. Keep the network input and torque in that layout and index them by row in the kernels, instead of holding a second per-environment view of the same memory. Pass the MLP history samples and column order to the kernel as arguments again; compiling them into a kernel per configuration measured no faster. --- .../isaaclab/actuators/actuator_kernels.py | 89 ++++++++----------- .../isaaclab/actuators/actuator_net.py | 20 ++--- 2 files changed, 45 insertions(+), 64 deletions(-) diff --git a/source/isaaclab/isaaclab/actuators/actuator_kernels.py b/source/isaaclab/isaaclab/actuators/actuator_kernels.py index e74a4039f027..00d757c14285 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_kernels.py +++ b/source/isaaclab/isaaclab/actuators/actuator_kernels.py @@ -7,7 +7,6 @@ from __future__ import annotations -from functools import cache from typing import Any import torch @@ -199,7 +198,7 @@ def clip_dc_motor_effort( @wp.kernel(enable_backward=False) def scale_and_clip_torque( # input - torque: wp.array2d(dtype=wp.float32), + torque: wp.array(dtype=wp.float32), joint_vel: wp.array2d(dtype=wp.float32), torque_scale: wp.float32, saturation_effort: wp.array2d(dtype=wp.float32), @@ -212,10 +211,10 @@ def scale_and_clip_torque( ): """Scale the network torque of each (env, joint) and clip it to the DC motor limits. - Launch with ``dim=(num_envs, num_joints)``. + ``torque`` holds one value per (env, joint), row-major. Launch with ``dim=(num_envs, num_joints)``. """ env_id, joint = wp.tid() - effort = torque[env_id, joint] * torque_scale + effort = torque[env_id * computed_effort.shape[1] + joint] * torque_scale computed_effort[env_id, joint] = effort applied_effort[env_id, joint] = dc_motor_clip( effort, @@ -236,13 +235,14 @@ def write_lstm_input( # output network_input: wp.array3d(dtype=wp.float32), ): - """Write the joint position error and velocity of each (env, joint) as its network input. + """Write the joint position error and velocity of each (env, joint) as its network input row. - Launch with ``dim=(num_envs, num_joints)``; ``network_input`` has shape ``(num_envs, num_joints, 2)``. + Launch with ``dim=(num_envs, num_joints)``. """ env_id, joint = wp.tid() - network_input[env_id, joint, 0] = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] - network_input[env_id, joint, 1] = joint_vel[env_id, joint] + row = env_id * joint_pos.shape[1] + joint + network_input[row, 0, 0] = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] + network_input[row, 0, 1] = joint_vel[env_id, joint] @wp.func @@ -254,51 +254,34 @@ def _push_newest(history: wp.array3d(dtype=wp.float32), env_id: int, joint: int, history[env_id, 0, joint] = sample -@cache -def make_update_mlp_history(history_indices: tuple[int, ...], pos_first: bool) -> wp.Kernel: - """Build the kernel that records the newest joint position error and velocity, then writes the scaled samples - the network reads. - - The samples the network reads and the order of its input columns are fixed when the actuator is built, so the - kernel compiles them in; one kernel is built per distinct pair of arguments. - - Args: - history_indices: History samples the network reads, counted from the newest (zero). - pos_first: Whether each network input row holds its position errors before its velocities. +@wp.kernel(enable_backward=False) +def update_mlp_history( + # input + joint_pos_target: wp.array2d(dtype=wp.float32), + joint_pos: wp.array2d(dtype=wp.float32), + joint_vel: wp.array2d(dtype=wp.float32), + history_indices: wp.array(dtype=wp.int32), + pos_scale: wp.float32, + vel_scale: wp.float32, + pos_first: bool, + # output + joint_pos_error_history: wp.array3d(dtype=wp.float32), + joint_vel_history: wp.array3d(dtype=wp.float32), + network_input: wp.array2d(dtype=wp.float32), +): + """Record the newest joint position error and velocity, then write the scaled samples the network reads. - Returns: - The kernel. Launch it with ``dim=(num_envs, num_joints)``; its ``network_input`` has shape - ``(num_envs, num_joints, 2 * len(history_indices))``. + Each row of ``network_input`` belongs to one (env, joint): its position errors, then its velocities when + ``pos_first``, otherwise the reverse. Launch with ``dim=(num_envs, num_joints)``. """ - num_samples = len(history_indices) - sample_indices = wp.types.vector(num_samples, wp.int32)(*history_indices) - pos_column = 0 if pos_first else num_samples + env_id, joint = wp.tid() + _push_newest(joint_pos_error_history, env_id, joint, joint_pos_target[env_id, joint] - joint_pos[env_id, joint]) + _push_newest(joint_vel_history, env_id, joint, joint_vel[env_id, joint]) + num_samples = history_indices.shape[0] + row = env_id * joint_pos.shape[1] + joint + pos_column = wp.where(pos_first, 0, num_samples) vel_column = num_samples - pos_column - - @wp.kernel(enable_backward=False, module="unique") - def update_mlp_history( - # input - joint_pos_target: wp.array2d(dtype=wp.float32), - joint_pos: wp.array2d(dtype=wp.float32), - joint_vel: wp.array2d(dtype=wp.float32), - pos_scale: wp.float32, - vel_scale: wp.float32, - # output - joint_pos_error_history: wp.array3d(dtype=wp.float32), - joint_vel_history: wp.array3d(dtype=wp.float32), - network_input: wp.array3d(dtype=wp.float32), - ): - env_id, joint = wp.tid() - error = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] - _push_newest(joint_pos_error_history, env_id, joint, error) - _push_newest(joint_vel_history, env_id, joint, joint_vel[env_id, joint]) - for i in range(wp.static(num_samples)): - index = wp.static(sample_indices)[i] - network_input[env_id, joint, wp.static(pos_column) + i] = ( - pos_scale * joint_pos_error_history[env_id, index, joint] - ) - network_input[env_id, joint, wp.static(vel_column) + i] = ( - vel_scale * joint_vel_history[env_id, index, joint] - ) - - return update_mlp_history + for i in range(num_samples): + index = history_indices[i] + network_input[row, pos_column + i] = pos_scale * joint_pos_error_history[env_id, index, joint] + network_input[row, vel_column + i] = vel_scale * joint_vel_history[env_id, index, joint] diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 943a3cb59c22..5679f9c946b9 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -26,7 +26,7 @@ from ..utils.io import export_torchscript_to_onnx, load_onnx_model from ..utils.types import ArticulationActions from ..utils.warp.memory import make_masked_fill -from .actuator_kernels import make_update_mlp_history, scale_and_clip_torque, write_lstm_input +from .actuator_kernels import scale_and_clip_torque, update_mlp_history, write_lstm_input from .actuator_pd import DCMotor if TYPE_CHECKING: @@ -92,7 +92,7 @@ def _apply_torque( scale_and_clip_torque, dim=(self._num_envs, self.num_joints), inputs=[ - torque.reshape((self._num_envs, self.num_joints)), + torque.reshape((self._num_envs * self.num_joints,)), wp.from_torch(joint_vel), torque_scale, *self._motor_limits, @@ -153,8 +153,6 @@ def sample_inputs(module: torch.jit.ScriptModule) -> tuple: self._network_inputs = {"input": self._network_input, "h0": self._hidden_state, "c0": self._cell_state} # run the network once: Warp-NN allocates its outputs and loads its kernels, which a CUDA graph cannot record self.network.prepare(self._network_inputs) - # the network input per (env, joint), which the input kernel writes - self._network_input_per_env = self._network_input.reshape((self._num_envs, self.num_joints, 2)) # Torch views of the buffers; the per-env views reshape without changing the memory layout self.sea_input = wp.to_torch(self._network_input) self.sea_hidden_state = wp.to_torch(self._hidden_state) @@ -193,7 +191,7 @@ def compute( write_lstm_input, dim=(self._num_envs, self.num_joints), inputs=[wp.from_torch(control_action.joint_positions), wp.from_torch(joint_pos), wp.from_torch(joint_vel)], - outputs=[self._network_input_per_env], + outputs=[self._network_input], device=self._device, ) # run network inference; its new states are the ones the next step reads @@ -253,17 +251,15 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): self._network_input_name = self.network.inputs[0].name self._network_output_name = self.network.outputs[0].name - # create buffers for MLP history, newest sample first, and the kernel that updates it + # create buffers for MLP history, newest sample first history_shape = (self._num_envs, history_length, self.num_joints) self._joint_pos_error_history = wp.zeros(history_shape, dtype=wp.float32, device=self._device) self._joint_vel_history = wp.zeros(history_shape, dtype=wp.float32, device=self._device) - self._update_history = make_update_mlp_history(indices, self.cfg.input_order == "pos_vel") + self._history_indices = wp.array(indices, dtype=wp.int32, device=self._device) # the network input, one row per (env, joint) self._network_input = wp.zeros(input_shape, dtype=wp.float32, device=self._device) # run the network once: Warp-NN allocates its outputs and loads its kernels, which a CUDA graph cannot record self.network.prepare({self._network_input_name: self._network_input}) - # the network input per (env, joint), which the history kernel writes - self._network_input_per_env = self._network_input.reshape((self._num_envs, self.num_joints, input_shape[1])) """ Operations. @@ -287,16 +283,18 @@ def compute( ) -> ArticulationActions: # move history queue by 1, update top of history and write the scaled network input wp.launch( - self._update_history, + update_mlp_history, dim=(self._num_envs, self.num_joints), inputs=[ wp.from_torch(control_action.joint_positions), wp.from_torch(joint_pos), wp.from_torch(joint_vel), + self._history_indices, self.cfg.pos_scale, self.cfg.vel_scale, + self.cfg.input_order == "pos_vel", ], - outputs=[self._joint_pos_error_history, self._joint_vel_history, self._network_input_per_env], + outputs=[self._joint_pos_error_history, self._joint_vel_history, self._network_input], device=self._device, ) # run network inference From b052598eb74e89ca1516c3f1f9115eed9688183e Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 1 Dec 2026 20:02:11 -0800 Subject: [PATCH 29/31] Load network files in the actuators without a callable Each network actuator reads an .onnx file, or loads its TorchScript file, builds the sample inputs from the loaded module and exports it with export_torchscript_to_onnx, which now takes the module and the inputs. Drop the shared loader that took a sample-input function and the warning on every TorchScript load; a small helper only names the network file when Warp-NN cannot run it. --- scripts/tools/convert_actuator_net_to_onnx.py | 31 ++++----- ...chuanh-actuator-net-mask-reset.changed.rst | 2 +- .../isaaclab/actuators/actuator_net.py | 67 ++++++++----------- source/isaaclab/isaaclab/utils/io/onnx.py | 18 ++--- 4 files changed, 48 insertions(+), 70 deletions(-) diff --git a/scripts/tools/convert_actuator_net_to_onnx.py b/scripts/tools/convert_actuator_net_to_onnx.py index d161d2066034..3253b916a071 100644 --- a/scripts/tools/convert_actuator_net_to_onnx.py +++ b/scripts/tools/convert_actuator_net_to_onnx.py @@ -37,19 +37,15 @@ } -def sample_inputs(kind: str, batch: int): - """Return a function that builds zero inputs of ``batch`` rows for a loaded TorchScript network.""" - - def build(module: torch.jit.ScriptModule) -> tuple: - if kind == "lstm": - weights = module.lstm.state_dict() - state = torch.zeros(len(weights) // 4, batch, weights["weight_hh_l0"].shape[1]) - return torch.zeros(batch, 1, 2), (state, state) - # the first weight matrix is the first layer's, whose columns are the input features - num_features = next(value for value in module.state_dict().values() if value.ndim == 2).shape[1] - return (torch.zeros(batch, num_features),) - - return build +def sample_inputs(kind: str, module: torch.jit.ScriptModule, batch: int) -> tuple: + """Zero inputs of ``batch`` rows for the TorchScript network.""" + if kind == "lstm": + weights = module.lstm.state_dict() + state = torch.zeros(len(weights) // 4, batch, weights["weight_hh_l0"].shape[1]) + return torch.zeros(batch, 1, 2), (state, state) + # the first weight matrix is the first layer's, whose columns are the input features + num_features = next(value for value in module.state_dict().values() if value.ndim == 2).shape[1] + return (torch.zeros(batch, num_features),) def main(): @@ -61,10 +57,10 @@ def main(): input_names, output_names = NAMES[args.kind] batch_axes = {name: {1 if name[0] in "hc" else 0: "batch"} for name in input_names + output_names} + module = torch.jit.load(read_file(args.checkpoint), map_location="cpu").eval() model = export_torchscript_to_onnx( - args.checkpoint, - sample_inputs(args.kind, batch=2), - device="cpu", + module, + sample_inputs(args.kind, module, batch=2), input_names=input_names, output_names=output_names, dynamic_axes=batch_axes, @@ -73,8 +69,7 @@ def main(): file.write(model.getvalue()) # run the model with Warp-NN at another batch size and compare it with the TorchScript module - module = torch.jit.load(read_file(args.checkpoint), map_location="cpu").eval() - sample = sample_inputs(args.kind, batch=5)(module) + sample = sample_inputs(args.kind, module, batch=5) flat = [torch.randn_like(x) for x in ((sample[0], *sample[1]) if args.kind == "lstm" else sample)] with torch.no_grad(): result = module(flat[0], (flat[1], flat[2])) if args.kind == "lstm" else module(flat[0]) diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index ecdd96ecee00..a864ae0b43a6 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -4,7 +4,7 @@ networks with Warp-NN, a new dependency. The network file may be an ONNX model whose inputs and outputs carry the names the actuator looks up (the LSTM's ``input``, ``h0`` and ``c0``, and ``torque``, ``h1`` and ``c1``; the MLP's single input and output under any names), or a TorchScript module, which is exported to ONNX each time the actuator - loads, with a warning; ``scripts/tools/convert_actuator_net_to_onnx.py`` exports it once. ``network`` is now the + loads; ``scripts/tools/convert_actuator_net_to_onnx.py`` exports it once. ``network`` is now the Warp-NN runtime instead of the TorchScript module. Warp kernels write the network input (for the MLP, after updating the joint history) and scale the torque and clip it to the DC motor limits; the LSTM's hidden and cell states carry over in Warp buffers, whose Torch views keep the ``sea_*`` attributes. A Warp graph alone can therefore diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 5679f9c946b9..6fec6feedfcc 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -14,8 +14,8 @@ from __future__ import annotations -import logging -from collections.abc import Callable, Sequence +import io +from collections.abc import Sequence from typing import TYPE_CHECKING import torch @@ -23,6 +23,7 @@ from warp_nn.runtime import OnnxRuntime from ..utils import index_fill_ +from ..utils.assets import read_file from ..utils.io import export_torchscript_to_onnx, load_onnx_model from ..utils.types import ArticulationActions from ..utils.warp.memory import make_masked_fill @@ -32,8 +33,6 @@ if TYPE_CHECKING: from .actuator_net_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg -logger = logging.getLogger(__name__) - class ActuatorNetBase(DCMotor): """A DC motor whose torque comes from a network that Warp-NN runs, so a Warp graph can record its compute. @@ -49,39 +48,19 @@ def __init__(self, cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, *args, **kwargs) self._computed_effort = wp.zeros((self._num_envs, self.num_joints), dtype=wp.float32, device=self._device) self.computed_effort = wp.to_torch(self._computed_effort) - def _load_network( - self, - sample_inputs: Callable[[torch.jit.ScriptModule], tuple], - input_names: list[str], - output_names: list[str], - ) -> OnnxRuntime: - """Build the Warp-NN runtime of the network file. - - An ONNX file is read as it is. A TorchScript file is exported to ONNX with ``input_names`` and - ``output_names``, for the batch of ``sample_inputs``, each time the actuator loads; - ``scripts/tools/convert_actuator_net_to_onnx.py`` exports it once instead. + def _warp_nn_runtime(self, model: io.BytesIO) -> OnnxRuntime: + """Build the Warp-NN runtime of the network, naming the network file if Warp-NN cannot run it. Raises: ValueError: If Warp-NN does not support an operator of the network. """ - network_file = self.cfg.network_file - if network_file.endswith(".onnx"): - model = load_onnx_model(network_file) - else: - logger.warning( - f"Exporting the TorchScript network '{network_file}' to ONNX while the actuator loads. Convert it once" - " with scripts/tools/convert_actuator_net_to_onnx.py and set network_file to the ONNX file instead." - ) - model = export_torchscript_to_onnx( - network_file, sample_inputs, device=self._device, input_names=input_names, output_names=output_names - ) try: return OnnxRuntime(model, device=self._device) except NotImplementedError as error: raise ValueError( - f"Warp-NN cannot run the network in '{network_file}': {error}. Rewrite the operation and export the" - " network again; for example, an LSTM head that takes its time step by indexing (out[:, -1]) exports" - " to Gather, while out.squeeze(1) exports to Squeeze." + f"Warp-NN cannot run the network in '{self.cfg.network_file}': {error}. Rewrite the operation and" + " export the network again; for example, an LSTM head that takes its time step by indexing" + " (out[:, -1]) exports to Gather, while out.squeeze(1) exports to Squeeze." ) from error def _apply_torque( @@ -126,17 +105,20 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): super().__init__(cfg, *args, **kwargs) batch = self._num_envs * self.num_joints + input_names, output_names = ["input", "h0", "c0"], ["torque", "h1", "c1"] - def sample_inputs(module: torch.jit.ScriptModule) -> tuple: - # one sample and zero states per row; the layer count and hidden size come from the weights, which a - # traced module keeps while it drops the LSTM's attributes + # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference + if cfg.network_file.endswith(".onnx"): + model = load_onnx_model(cfg.network_file) + else: + # export a TorchScript network for this batch: one sample and zero states per row; the layer count and + # hidden size come from the weights, which a traced module keeps while it drops the LSTM's attributes + module = torch.jit.load(read_file(cfg.network_file), map_location=self._device).eval() weights = module.lstm.state_dict() state = torch.zeros(len(weights) // 4, batch, weights["weight_hh_l0"].shape[1], device=self._device) - return torch.zeros(batch, 1, 2, device=self._device), (state, state) - - # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference - input_names, output_names = ["input", "h0", "c0"], ["torque", "h1", "c1"] - self.network = self._load_network(sample_inputs, input_names, output_names) + sample = (torch.zeros(batch, 1, 2, device=self._device), (state, state)) + model = export_torchscript_to_onnx(module, sample, input_names=input_names, output_names=output_names) + self.network = self._warp_nn_runtime(model) # the inputs and outputs are looked up by name: the input, then the hidden and cell states and their updates found = [spec.name for spec in self.network.inputs], [spec.name for spec in self.network.outputs] if (set(found[0]), set(found[1])) != (set(input_names), set(output_names)): @@ -239,9 +221,14 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): input_shape = (self._num_envs * self.num_joints, 2 * len(indices)) # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference - self.network = self._load_network( - lambda module: (torch.zeros(input_shape, device=self._device),), ["input"], ["torque"] - ) + if cfg.network_file.endswith(".onnx"): + model = load_onnx_model(cfg.network_file) + else: + # export a TorchScript network for this batch, one row per (env, joint) + module = torch.jit.load(read_file(cfg.network_file), map_location=self._device).eval() + sample = (torch.zeros(input_shape, device=self._device),) + model = export_torchscript_to_onnx(module, sample, input_names=["input"], output_names=["torque"]) + self.network = self._warp_nn_runtime(model) # one input and one output, whatever an ONNX file names them if len(self.network.inputs) != 1 or len(self.network.outputs) != 1: raise ValueError( diff --git a/source/isaaclab/isaaclab/utils/io/onnx.py b/source/isaaclab/isaaclab/utils/io/onnx.py index be95d4d89bfb..9d9ff2e1b93d 100644 --- a/source/isaaclab/isaaclab/utils/io/onnx.py +++ b/source/isaaclab/isaaclab/utils/io/onnx.py @@ -6,7 +6,6 @@ """ONNX I/O utilities.""" import io -from collections.abc import Callable import torch @@ -31,24 +30,22 @@ def load_onnx_model(model_path: str) -> io.BytesIO: def export_torchscript_to_onnx( - model_path: str, - sample_inputs: Callable[[torch.jit.ScriptModule], tuple], + module: torch.jit.ScriptModule, + sample_inputs: tuple, *, - device: str, input_names: list[str], output_names: list[str], dynamic_axes: dict[str, dict[int, str]] | None = None, ) -> io.BytesIO: - """Load a TorchScript module and export it to an ONNX model in memory. + """Export a TorchScript module to an ONNX model in memory. The module is exported with the TorchScript exporter, since the dynamo exporter does not accept TorchScript modules. Args: - model_path: Path to the TorchScript file, local or on the Nucleus server. - sample_inputs: Function that returns, from the loaded module, the inputs that trace it for the export, on - ``device``. The exported model takes inputs of their shapes, except along ``dynamic_axes``. - device: Device to load the module on. + module: The TorchScript module. + sample_inputs: Inputs that trace the module for the export, on its device. The exported model takes inputs of + their shapes, except along ``dynamic_axes``. input_names: Names of the exported model's inputs. output_names: Names of the exported model's outputs. dynamic_axes: Axes of the named inputs and outputs that take any size, as :func:`torch.onnx.export` takes @@ -57,11 +54,10 @@ def export_torchscript_to_onnx( Returns: The ONNX model. """ - module = torch.jit.load(read_file(model_path), map_location=device).eval() model = io.BytesIO() torch.onnx.export( module, - sample_inputs(module), + sample_inputs, model, input_names=input_names, output_names=output_names, From beb29c1cf1ae9ac04d2acbea9cdbb73a0abbaf9c Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 1 Dec 2026 20:13:44 -0800 Subject: [PATCH 30/31] Share the network loading in the base and look up LSTM inputs by name ActuatorNetBase loads the network file once for both actuators; each actuator only builds the sample inputs that trace its TorchScript network for the export. The LSTM checks and reads its inputs through a dictionary keyed by name. --- .../isaaclab/actuators/actuator_net.py | 60 +++++++++++-------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 6fec6feedfcc..8bfb7d3aca88 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -14,7 +14,6 @@ from __future__ import annotations -import io from collections.abc import Sequence from typing import TYPE_CHECKING @@ -48,12 +47,21 @@ def __init__(self, cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, *args, **kwargs) self._computed_effort = wp.zeros((self._num_envs, self.num_joints), dtype=wp.float32, device=self._device) self.computed_effort = wp.to_torch(self._computed_effort) - def _warp_nn_runtime(self, model: io.BytesIO) -> OnnxRuntime: - """Build the Warp-NN runtime of the network, naming the network file if Warp-NN cannot run it. + def _load_network(self, input_names: list[str], output_names: list[str]) -> OnnxRuntime: + """Load the network file as an ONNX model and build its Warp-NN runtime. + + An ONNX file is read as it is. A TorchScript file is exported to ONNX with ``input_names`` and + ``output_names``, traced with the inputs :meth:`_export_sample` builds for this actuator. Raises: ValueError: If Warp-NN does not support an operator of the network. """ + if self.cfg.network_file.endswith(".onnx"): + model = load_onnx_model(self.cfg.network_file) + else: + module = torch.jit.load(read_file(self.cfg.network_file), map_location=self._device).eval() + sample = self._export_sample(module) + model = export_torchscript_to_onnx(module, sample, input_names=input_names, output_names=output_names) try: return OnnxRuntime(model, device=self._device) except NotImplementedError as error: @@ -63,6 +71,10 @@ def _warp_nn_runtime(self, model: io.BytesIO) -> OnnxRuntime: " (out[:, -1]) exports to Gather, while out.squeeze(1) exports to Squeeze." ) from error + def _export_sample(self, module: torch.jit.ScriptModule) -> tuple: + """Inputs that trace the TorchScript network for its ONNX export, sized for this actuator.""" + raise NotImplementedError + def _apply_torque( self, control_action: ArticulationActions, torque: wp.array, joint_vel: torch.Tensor, torque_scale: float ) -> ArticulationActions: @@ -108,27 +120,18 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): input_names, output_names = ["input", "h0", "c0"], ["torque", "h1", "c1"] # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference - if cfg.network_file.endswith(".onnx"): - model = load_onnx_model(cfg.network_file) - else: - # export a TorchScript network for this batch: one sample and zero states per row; the layer count and - # hidden size come from the weights, which a traced module keeps while it drops the LSTM's attributes - module = torch.jit.load(read_file(cfg.network_file), map_location=self._device).eval() - weights = module.lstm.state_dict() - state = torch.zeros(len(weights) // 4, batch, weights["weight_hh_l0"].shape[1], device=self._device) - sample = (torch.zeros(batch, 1, 2, device=self._device), (state, state)) - model = export_torchscript_to_onnx(module, sample, input_names=input_names, output_names=output_names) - self.network = self._warp_nn_runtime(model) + self.network = self._load_network(input_names, output_names) # the inputs and outputs are looked up by name: the input, then the hidden and cell states and their updates - found = [spec.name for spec in self.network.inputs], [spec.name for spec in self.network.outputs] - if (set(found[0]), set(found[1])) != (set(input_names), set(output_names)): + inputs = {spec.name: spec for spec in self.network.inputs} + outputs = {spec.name for spec in self.network.outputs} + if set(inputs) != set(input_names) or outputs != set(output_names): raise ValueError( f"The LSTM network in '{cfg.network_file}' must take the inputs {input_names} and return the outputs" - f" {output_names}; it takes {found[0]} and returns {found[1]}." + f" {output_names}; it takes {list(inputs)} and returns {sorted(outputs)}." ) # create buffers for the network input and the LSTM states, one row per (env, joint) - num_layers, _, hidden_dim = next(spec for spec in self.network.inputs if spec.name == "h0").shape + num_layers, _, hidden_dim = inputs["h0"].shape self._network_input = wp.zeros((batch, 1, 2), dtype=wp.float32, device=self._device) self._hidden_state = wp.zeros((num_layers, batch, hidden_dim), dtype=wp.float32, device=self._device) self._cell_state = wp.zeros_like(self._hidden_state) @@ -147,6 +150,14 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): state.reshape((num_layers, self._num_envs, -1)) for state in (self._hidden_state, self._cell_state) ) + def _export_sample(self, module: torch.jit.ScriptModule) -> tuple: + # one sample and zero states per (env, joint); the layer count and hidden size come from the weights, which + # a traced module keeps while it drops the LSTM's attributes + batch = self._num_envs * self.num_joints + weights = module.lstm.state_dict() + state = torch.zeros(len(weights) // 4, batch, weights["weight_hh_l0"].shape[1], device=self._device) + return torch.zeros(batch, 1, 2, device=self._device), (state, state) + """ Operations. """ @@ -221,14 +232,7 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): input_shape = (self._num_envs * self.num_joints, 2 * len(indices)) # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference - if cfg.network_file.endswith(".onnx"): - model = load_onnx_model(cfg.network_file) - else: - # export a TorchScript network for this batch, one row per (env, joint) - module = torch.jit.load(read_file(cfg.network_file), map_location=self._device).eval() - sample = (torch.zeros(input_shape, device=self._device),) - model = export_torchscript_to_onnx(module, sample, input_names=["input"], output_names=["torque"]) - self.network = self._warp_nn_runtime(model) + self.network = self._load_network(["input"], ["torque"]) # one input and one output, whatever an ONNX file names them if len(self.network.inputs) != 1 or len(self.network.outputs) != 1: raise ValueError( @@ -248,6 +252,10 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): # run the network once: Warp-NN allocates its outputs and loads its kernels, which a CUDA graph cannot record self.network.prepare({self._network_input_name: self._network_input}) + def _export_sample(self, module: torch.jit.ScriptModule) -> tuple: + # one input row per (env, joint): the position errors and velocities of the history samples it reads + return (torch.zeros(self._num_envs * self.num_joints, 2 * len(self.cfg.input_idx), device=self._device),) + """ Operations. """ From b4175b1a588115ef8045c4bd67ae97f3a1d8bbe6 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 1 Dec 2026 20:32:23 -0800 Subject: [PATCH 31/31] Drop the ONNX converter script and the network name checks Converting checkpoints offline belongs with the change that moves both actuator paths to ONNX files, so remove the converter script and the export's dynamic-axes option it alone used. Warp-NN already checks the input names when it prepares the network, so drop the actuators' own name and count checks and the base class's placeholder for the export sample. --- docs/source/concepts/actuators.rst | 3 +- scripts/tools/convert_actuator_net_to_onnx.py | 87 ------------------- ...chuanh-actuator-net-mask-reset.changed.rst | 3 +- .../isaaclab/actuators/actuator_net.py | 27 ++---- source/isaaclab/isaaclab/utils/io/onnx.py | 6 +- .../test/actuators/test_actuator_net.py | 26 ++---- 6 files changed, 17 insertions(+), 135 deletions(-) delete mode 100644 scripts/tools/convert_actuator_net_to_onnx.py diff --git a/docs/source/concepts/actuators.rst b/docs/source/concepts/actuators.rst index cd0d5b1032e2..00f1b7a64955 100644 --- a/docs/source/concepts/actuators.rst +++ b/docs/source/concepts/actuators.rst @@ -114,8 +114,7 @@ for linkages whose effective lever arm changes through their range of motion. **ActuatorNetMLP / ActuatorNetLSTM.** Learned torque models that use joint-position error and velocity history and clip output with the DC-motor envelope. ``network_file`` is an ONNX model, or a TorchScript checkpoint exported to ONNX when the actuator loads; the network runs with Warp-NN, so it must use -operators that Warp-NN supports. ``scripts/tools/convert_actuator_net_to_onnx.py`` exports a checkpoint to ONNX once. -See the :mod:`isaaclab.actuators` API reference for configuration details. +operators that Warp-NN supports. See the :mod:`isaaclab.actuators` API reference for configuration details. **BamActuatorCfg.** A parameter-identified model of a small voltage-controlled servo, described in :ref:`actuators-bam`. Unlike the PD models it takes no stiffness or damping: its position loop is diff --git a/scripts/tools/convert_actuator_net_to_onnx.py b/scripts/tools/convert_actuator_net_to_onnx.py deleted file mode 100644 index 3253b916a071..000000000000 --- a/scripts/tools/convert_actuator_net_to_onnx.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Convert a TorchScript actuator network to the ONNX model that the Isaac Lab network actuators load. - -:class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` run their networks with -Warp-NN from an ONNX model. A TorchScript ``network_file`` is exported to ONNX each time the actuator loads; this script -exports it once, with a batch dimension of any size, so that ``network_file`` can point to the ``.onnx`` file instead. -The script then runs the ONNX model with Warp-NN and compares it with the TorchScript module, so a network that uses an -operator Warp-NN does not support fails here. - -Examples: - -.. code-block:: bash - - ./isaaclab.sh -p scripts/tools/convert_actuator_net_to_onnx.py lstm anydrive_3_lstm_jit.pt anydrive_3_lstm.onnx - ./isaaclab.sh -p scripts/tools/convert_actuator_net_to_onnx.py mlp unitree_go1.pt unitree_go1.onnx - -""" - -import argparse -import io - -import torch -import warp as wp -from warp_nn.runtime import OnnxRuntime - -from isaaclab.utils.assets import read_file -from isaaclab.utils.io import export_torchscript_to_onnx - -# Names the actuators look up; the LSTM states put their batch second, after the layers. -NAMES = { - "lstm": (["input", "h0", "c0"], ["torque", "h1", "c1"]), - "mlp": (["input"], ["torque"]), -} - - -def sample_inputs(kind: str, module: torch.jit.ScriptModule, batch: int) -> tuple: - """Zero inputs of ``batch`` rows for the TorchScript network.""" - if kind == "lstm": - weights = module.lstm.state_dict() - state = torch.zeros(len(weights) // 4, batch, weights["weight_hh_l0"].shape[1]) - return torch.zeros(batch, 1, 2), (state, state) - # the first weight matrix is the first layer's, whose columns are the input features - num_features = next(value for value in module.state_dict().values() if value.ndim == 2).shape[1] - return (torch.zeros(batch, num_features),) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - parser.add_argument("kind", choices=sorted(NAMES), help="Network type: the actuator that loads it.") - parser.add_argument("checkpoint", help="TorchScript network file, local or on the Nucleus server.") - parser.add_argument("output", help="Path of the ONNX model to write.") - args = parser.parse_args() - - input_names, output_names = NAMES[args.kind] - batch_axes = {name: {1 if name[0] in "hc" else 0: "batch"} for name in input_names + output_names} - module = torch.jit.load(read_file(args.checkpoint), map_location="cpu").eval() - model = export_torchscript_to_onnx( - module, - sample_inputs(args.kind, module, batch=2), - input_names=input_names, - output_names=output_names, - dynamic_axes=batch_axes, - ) - with open(args.output, "wb") as file: - file.write(model.getvalue()) - - # run the model with Warp-NN at another batch size and compare it with the TorchScript module - sample = sample_inputs(args.kind, module, batch=5) - flat = [torch.randn_like(x) for x in ((sample[0], *sample[1]) if args.kind == "lstm" else sample)] - with torch.no_grad(): - result = module(flat[0], (flat[1], flat[2])) if args.kind == "lstm" else module(flat[0]) - expected = (result[0], *result[1]) if args.kind == "lstm" else (result,) - runtime = OnnxRuntime(io.BytesIO(model.getvalue()), device="cpu") - outputs = runtime({name: wp.from_torch(x) for name, x in zip(input_names, flat)}) - error = max( - (wp.to_torch(outputs[name]).reshape(value.shape) - value).abs().max().item() - for name, value in zip(output_names, expected) - ) - print(f"Wrote {args.output}; max difference from the TorchScript module at batch 5: {error:.2e}") - - -if __name__ == "__main__": - main() diff --git a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst index a864ae0b43a6..4d1182b392b3 100644 --- a/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-actuator-net-mask-reset.changed.rst @@ -3,8 +3,7 @@ * Changed :class:`~isaaclab.actuators.ActuatorNetLSTM` and :class:`~isaaclab.actuators.ActuatorNetMLP` to run their networks with Warp-NN, a new dependency. The network file may be an ONNX model whose inputs and outputs carry the names the actuator looks up (the LSTM's ``input``, ``h0`` and ``c0``, and ``torque``, ``h1`` and ``c1``; the MLP's - single input and output under any names), or a TorchScript module, which is exported to ONNX each time the actuator - loads; ``scripts/tools/convert_actuator_net_to_onnx.py`` exports it once. ``network`` is now the + single input and output under any names), or a TorchScript module, which is exported to ONNX when the actuator loads. ``network`` is now the Warp-NN runtime instead of the TorchScript module. Warp kernels write the network input (for the MLP, after updating the joint history) and scale the torque and clip it to the DC motor limits; the LSTM's hidden and cell states carry over in Warp buffers, whose Torch views keep the ``sea_*`` attributes. A Warp graph alone can therefore diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 8bfb7d3aca88..d528f16e9366 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -71,10 +71,6 @@ def _load_network(self, input_names: list[str], output_names: list[str]) -> Onnx " (out[:, -1]) exports to Gather, while out.squeeze(1) exports to Squeeze." ) from error - def _export_sample(self, module: torch.jit.ScriptModule) -> tuple: - """Inputs that trace the TorchScript network for its ONNX export, sized for this actuator.""" - raise NotImplementedError - def _apply_torque( self, control_action: ArticulationActions, torque: wp.array, joint_vel: torch.Tensor, torque_scale: float ) -> ArticulationActions: @@ -117,21 +113,13 @@ def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): super().__init__(cfg, *args, **kwargs) batch = self._num_envs * self.num_joints - input_names, output_names = ["input", "h0", "c0"], ["torque", "h1", "c1"] # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference - self.network = self._load_network(input_names, output_names) - # the inputs and outputs are looked up by name: the input, then the hidden and cell states and their updates - inputs = {spec.name: spec for spec in self.network.inputs} - outputs = {spec.name for spec in self.network.outputs} - if set(inputs) != set(input_names) or outputs != set(output_names): - raise ValueError( - f"The LSTM network in '{cfg.network_file}' must take the inputs {input_names} and return the outputs" - f" {output_names}; it takes {list(inputs)} and returns {sorted(outputs)}." - ) + self.network = self._load_network(["input", "h0", "c0"], ["torque", "h1", "c1"]) - # create buffers for the network input and the LSTM states, one row per (env, joint) - num_layers, _, hidden_dim = inputs["h0"].shape + # create buffers for the network input and the LSTM states, one row per (env, joint); Warp-NN checks the + # input names when it prepares + num_layers, _, hidden_dim = {spec.name: spec for spec in self.network.inputs}["h0"].shape self._network_input = wp.zeros((batch, 1, 2), dtype=wp.float32, device=self._device) self._hidden_state = wp.zeros((num_layers, batch, hidden_dim), dtype=wp.float32, device=self._device) self._cell_state = wp.zeros_like(self._hidden_state) @@ -233,12 +221,7 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): # load the network as an ONNX model and run it with Warp-NN, so that a CUDA graph can record the inference self.network = self._load_network(["input"], ["torque"]) - # one input and one output, whatever an ONNX file names them - if len(self.network.inputs) != 1 or len(self.network.outputs) != 1: - raise ValueError( - f"The MLP network in '{cfg.network_file}' must take one input and return one output; it takes" - f" {len(self.network.inputs)} and returns {len(self.network.outputs)}." - ) + # an ONNX file keeps the input and output names it was exported with self._network_input_name = self.network.inputs[0].name self._network_output_name = self.network.outputs[0].name diff --git a/source/isaaclab/isaaclab/utils/io/onnx.py b/source/isaaclab/isaaclab/utils/io/onnx.py index 9d9ff2e1b93d..458d1e4a7b43 100644 --- a/source/isaaclab/isaaclab/utils/io/onnx.py +++ b/source/isaaclab/isaaclab/utils/io/onnx.py @@ -35,7 +35,6 @@ def export_torchscript_to_onnx( *, input_names: list[str], output_names: list[str], - dynamic_axes: dict[str, dict[int, str]] | None = None, ) -> io.BytesIO: """Export a TorchScript module to an ONNX model in memory. @@ -45,11 +44,9 @@ def export_torchscript_to_onnx( Args: module: The TorchScript module. sample_inputs: Inputs that trace the module for the export, on its device. The exported model takes inputs of - their shapes, except along ``dynamic_axes``. + their shapes. input_names: Names of the exported model's inputs. output_names: Names of the exported model's outputs. - dynamic_axes: Axes of the named inputs and outputs that take any size, as :func:`torch.onnx.export` takes - them. Defaults to None, in which case every axis keeps the size of the sample inputs. Returns: The ONNX model. @@ -61,7 +58,6 @@ def export_torchscript_to_onnx( model, input_names=input_names, output_names=output_names, - dynamic_axes=dynamic_axes, dynamo=False, ) model.seek(0) diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index 25d39ca773f0..c37cf913417c 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -57,12 +57,12 @@ def _lstm_sample(network: torch.nn.Module, batch: int) -> tuple: return torch.zeros(batch, 1, 2), (state, state) -def _export_onnx(network: torch.nn.Module, path, lstm_names=(["input", "h0", "c0"], ["torque", "h1", "c1"])): - """Export ``network`` to ONNX: an MLP with names of its own, an LSTM with ``lstm_names``.""" +def _export_onnx(network: torch.nn.Module, path): + """Export ``network`` to ONNX: an MLP with names of its own, an LSTM with the names the actuator looks up.""" if isinstance(network, torch.nn.Linear): sample, (inputs, outputs) = (torch.zeros(1, network.in_features),), (["obs"], ["act"]) else: - sample, (inputs, outputs) = _lstm_sample(network, batch=1), lstm_names + sample, (inputs, outputs) = _lstm_sample(network, batch=1), (["input", "h0", "c0"], ["torque", "h1", "c1"]) # the LSTM states put their batch second, after the layers axes = {name: {1 if name[0] in "hc" else 0: "batch"} for name in inputs + outputs} torch.onnx.export( @@ -72,12 +72,10 @@ def _export_onnx(network: torch.nn.Module, path, lstm_names=(["input", "h0", "c0 def _actuator(cfg_class, network: torch.nn.Module, tmp_path, device: str, network_format: str = "pt", **cfg): """Build the actuator from ``network`` saved as a scripted (``pt``) or ``traced`` TorchScript file, or as an ONNX - file with the names the actuator looks up (``onnx``) or with other names (``misnamed_onnx``).""" - network_file = tmp_path / ("network.onnx" if network_format.endswith("onnx") else "network.pt") + file (``onnx``).""" + network_file = tmp_path / f"network.{'onnx' if network_format == 'onnx' else 'pt'}" if network_format == "onnx": _export_onnx(network, network_file) - elif network_format == "misnamed_onnx": - _export_onnx(network, network_file, (["obs", "h", "c"], ["act", "h_next", "c_next"])) elif network_format == "traced": torch.jit.trace(network, _lstm_sample(network, batch=2)).save(str(network_file)) else: @@ -233,16 +231,10 @@ def test_lstm_state_carries_across_steps(tmp_path, device, network_format): torch.testing.assert_close(actuator.applied_effort, _dc_motor_clip(actuator, expected, velocity)) -@pytest.mark.parametrize( - ("network", "network_format", "message"), - [(_IndexedHeadLSTM, "pt", "Gather"), (_TorqueLSTM, "misnamed_onnx", "must take the inputs")], - ids=["unsupported_operator", "misnamed_onnx"], -) -def test_lstm_rejects_a_network_it_cannot_run(tmp_path, network, network_format, message): - """A network with an operator Warp-NN does not support, or an ONNX file without the names the actuator looks up, - fails to load with an error that names the network file.""" - with pytest.raises(ValueError, match=message) as error: - _actuator(ActuatorNetLSTMCfg, network(), tmp_path, "cpu", network_format) +def test_lstm_names_the_network_file_warp_nn_cannot_run(tmp_path): + """A network with an operator Warp-NN does not support fails to load with an error that names the network file.""" + with pytest.raises(ValueError, match="Gather") as error: + _actuator(ActuatorNetLSTMCfg, _IndexedHeadLSTM(), tmp_path, "cpu") assert str(tmp_path) in str(error.value)