From b31e8982161379425c8e5e21e2893ac592c403ce Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Tue, 1 Dec 2026 16:47:55 -0800 Subject: [PATCH 1/3] Simplify neural actuator configuration and drift streams --- docs/source/concepts/actuators.rst | 3 +- docs/source/refs/contributing.rst | 3 + .../codex-actuator-network-config.changed.rst | 6 + .../codex-actuator-network-config.fixed.rst | 3 + .../codex-actuator-network-config.minor | 0 .../isaaclab/actuators/actuator_kernels.py | 33 ++---- .../isaaclab/actuators/actuator_net.py | 96 ++++++--------- .../isaaclab/actuators/actuator_net_cfg.py | 54 ++++++++- .../envs/reset/reset_state_sampler.py | 9 +- .../sensors/ray_caster/base_ray_caster.py | 11 +- .../sensors/ray_caster/ray_caster_cfg.py | 6 + .../isaaclab/sim/schemas/schemas_actuators.py | 84 +------------ .../isaaclab/isaaclab/utils/io/__init__.pyi | 4 +- source/isaaclab/isaaclab/utils/io/onnx.py | 111 ++++++++++++------ .../isaaclab/isaaclab/utils/io/torchscript.py | 34 ++---- .../test/actuators/test_actuator_net.py | 62 +++++++--- .../test/actuators/test_newton_adapter.py | 23 ++-- .../test/controllers/test_controller_utils.py | 5 +- .../codex-actuator-network-config.skip | 0 .../sensors/test_newton_raycast_sensor.py | 9 +- 20 files changed, 276 insertions(+), 280 deletions(-) create mode 100644 source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst create mode 100644 source/isaaclab/changelog.d/codex-actuator-network-config.fixed.rst create mode 100644 source/isaaclab/changelog.d/codex-actuator-network-config.minor create mode 100644 source/isaaclab_newton/changelog.d/codex-actuator-network-config.skip diff --git a/docs/source/concepts/actuators.rst b/docs/source/concepts/actuators.rst index 00f1b7a64955..2419aba98963 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 an ONNX model, or a -TorchScript checkpoint exported to ONNX when the actuator loads; the network runs with Warp-NN, so it must use +TorchScript checkpoint translated to an ONNX configuration before runtime setup. Both Isaac Lab and Newton +actuators use this prepared model. 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/docs/source/refs/contributing.rst b/docs/source/refs/contributing.rst index 3cc5aa051dc7..d7f734d87ad0 100644 --- a/docs/source/refs/contributing.rst +++ b/docs/source/refs/contributing.rst @@ -439,6 +439,9 @@ before changing an interface. Apply these rules when adding code or cleaning up required attribute; express optional fields explicitly in the interface. Use concrete defaults for known empty selections. Reserve ``None`` for a distinct policy or lifecycle state, such as choosing an environment's frame rate or waiting for a client to connect. +* Translate legacy neural checkpoint configurations before runtime setup and share checkpoint preparation + across Isaac Lab and Newton. Keep preprocessing validation in the actuator config's ``validate_config``. + Declare random-stream identity explicitly; do not derive it by serializing unrelated configuration fields. * Give each piece of state and validation one owner. Consumers should use the owner's contract instead of repairing results or maintaining duplicate state. Cache derived values only when their lifetime and invalidation are clear; do not expose mutable cached results for callers to modify accidentally. diff --git a/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst b/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst new file mode 100644 index 000000000000..f17fc34f5638 --- /dev/null +++ b/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst @@ -0,0 +1,6 @@ +* Consolidated neural checkpoint preparation in ``export_onnx_model`` and config resolution, replacing the + separate schema-side Torch export and ``load_onnx_model`` callback interface. Runtime setup consumed ONNX only. +* Added ``RayCasterCfg.drift_seed`` to select sensor drift streams explicitly. Set different drift seeds for + independent sensors; offsets and visualization settings no longer selected a random stream. +* Moved MLP preprocessing checks into ``validate_config``, reused actuator effort storage and paired history + clearing, and shared the RNG initialization kernel with reset-state sampling. diff --git a/source/isaaclab/changelog.d/codex-actuator-network-config.fixed.rst b/source/isaaclab/changelog.d/codex-actuator-network-config.fixed.rst new file mode 100644 index 000000000000..b656c5191306 --- /dev/null +++ b/source/isaaclab/changelog.d/codex-actuator-network-config.fixed.rst @@ -0,0 +1,3 @@ +* Fixed single-environment, single-joint neural actuators failing to prepare squeezed torque outputs. +* Fixed ONNX checkpoint configuration on the default Newton actuator path by sharing checkpoint preparation. +* Kept ray-caster drift streams stable when unrelated sensor configuration changed. diff --git a/source/isaaclab/changelog.d/codex-actuator-network-config.minor b/source/isaaclab/changelog.d/codex-actuator-network-config.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/actuators/actuator_kernels.py b/source/isaaclab/isaaclab/actuators/actuator_kernels.py index f7d3faefea6f..b86e8c9594a2 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_kernels.py +++ b/source/isaaclab/isaaclab/actuators/actuator_kernels.py @@ -155,22 +155,6 @@ def compute_implicit_actuator_batch( """ -@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 @@ -192,14 +176,11 @@ def scale_and_clip_torque( 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], - ) + vel = wp.clamp(joint_vel[env_id, joint], -vel_at_effort_lim[env_id, joint], vel_at_effort_lim[env_id, joint]) + speed = vel / velocity_limit[env_id, joint] + upper = wp.min(saturation_effort[env_id, joint] * (1.0 - speed), effort_limit[env_id, joint]) + lower = wp.max(saturation_effort[env_id, joint] * (-1.0 - speed), -effort_limit[env_id, joint]) + applied_effort[env_id, joint] = wp.clamp(effort, lower, upper) @wp.kernel(enable_backward=False) @@ -217,8 +198,8 @@ def write_lstm_input( """ 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[0, row, 0] = joint_pos_target[env_id, joint] - joint_pos[env_id, joint] + network_input[0, row, 1] = joint_vel[env_id, joint] @wp.func diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 83509cf6c9b7..a8fc497ddcda 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -15,39 +15,40 @@ from __future__ import annotations 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.io import load_onnx_model from ..utils.types import ArticulationActions -from ..utils.warp.memory import make_masked_fill +from ..utils.warp.memory import make_clear_pair, make_masked_fill from .actuator_kernels import scale_and_clip_torque, update_mlp_history, write_lstm_input +from .actuator_net_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg, resolve_network_config from .actuator_pd import DCMotor -if TYPE_CHECKING: - from .actuator_net_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg - 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. + Warp kernels write into the base actuator's preallocated effort buffers through cached Warp views. """ - 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 __init__( + self, + cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, + joint_names: list[str], + joint_ids: slice | torch.Tensor, + num_envs: int, + device: str, + *args, + **kwargs, + ): + cfg = resolve_network_config(cfg, num_envs * len(joint_names), device) + super().__init__(cfg, joint_names, joint_ids, num_envs, device, *args, **kwargs) + self.network = OnnxRuntime(self.cfg.network_file, device=self._device) + self._computed_effort = wp.from_torch(self.computed_effort) + self._applied_effort = wp.from_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) @@ -102,26 +103,12 @@ 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) - 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] # 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._network_input = wp.zeros((1, batch, 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) @@ -129,7 +116,7 @@ def sample_inputs(module: torch.jit.ScriptModule) -> tuple: # 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) + self.sea_input = wp.to_torch(self._network_input).transpose(0, 1) 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) @@ -204,26 +191,10 @@ def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): 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 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 = 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 @@ -235,23 +206,26 @@ 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) # 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}) + self._network_inputs = {self.network.inputs[0].name: self._network_input} + self.network.prepare(self._network_inputs) """ Operations. """ def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: - # 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(history.dtype, 3), - dim=history.shape, - inputs=[0.0, env_mask, None, history], - device=self._device, - ) - else: + if env_mask is not None: + shape = (self._num_envs, -1) + position = self._joint_pos_error_history.reshape(shape) + velocity = self._joint_vel_history.reshape(shape) + wp.launch( + make_clear_pair(wp.float32, 2), + dim=position.shape, + inputs=[env_mask, position, velocity], + device=self._device, + ) + else: + for history in (self._joint_pos_error_history, self._joint_vel_history): index_fill_(wp.to_torch(history), env_ids, 0.0) def compute( @@ -274,6 +248,6 @@ def compute( device=self._device, ) # run network inference - torque = self.network({self._network_input_name: self._network_input})[self._network_output_name] + torque = self.network(self._network_inputs)[self._network_output_name] # scale the torque and clip it based on the motor limits 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 5bc9d5d9f0a1..1eaade254385 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py @@ -6,7 +6,8 @@ from collections.abc import Iterable from typing import TYPE_CHECKING, Literal -from ..utils import configclass +from ..utils import configclass, replace +from ..utils.io import export_onnx_model from .actuator_pd_cfg import DCMotorCfg if TYPE_CHECKING: @@ -26,6 +27,17 @@ class ActuatorNetLSTMCfg(DCMotorCfg): """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).""" + batch_first: bool = True + """Whether an ONNX source checkpoint takes ``(batch, 1, 2)`` input. False selects ``(1, batch, 2)``. + + Legacy TorchScript checkpoints declare their layout in the serialized LSTM. Resolved configs use sequence first. + """ + + def validate_config(self, *, require_network: bool = False) -> None: + """Require a checkpoint when constructing an Isaac Lab network actuator.""" + if require_network and self.network_file is None: + raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") + @configclass class ActuatorNetMLPCfg(DCMotorCfg): @@ -65,7 +77,7 @@ class ActuatorNetMLPCfg(DCMotorCfg): time-step in the past. The allocated history length is `max(input_idx) + 1`. """ - def validate_config(self) -> None: + def validate_config(self, *, require_network: bool = False) -> None: """Require MLP preprocessing settings together with a replacement checkpoint. Raises: @@ -78,6 +90,8 @@ def validate_config(self) -> None: "vel_scale": self.vel_scale, "torque_scale": self.torque_scale, } + if require_network and self.network_file is None: + raise ValueError("network_file must be provided for the Isaac Lab neural actuator model.") if self.network_file is None: if any(value is not None for value in metadata.values()): raise ValueError("network_file is required when configuring MLP checkpoint metadata.") @@ -85,3 +99,39 @@ def validate_config(self) -> None: missing = [name for name, value in metadata.items() if value is None] if missing: raise ValueError(f"network_file requires MLP metadata fields: {', '.join(missing)}.") + + history_length = max(self.input_idx) + 1 + if min(self.input_idx) < -history_length: + raise IndexError(f"MLP actuator history indices must be at least {-history_length}.") + if self.input_order not in ("pos_vel", "vel_pos"): + raise ValueError( + f"Invalid input order for MLP actuator net: {self.input_order}. Must be 'pos_vel' or 'vel_pos'." + ) + + +def resolve_network_config( + cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, batch: int = 3, device: str = "cpu" +) -> ActuatorNetLSTMCfg | ActuatorNetMLPCfg: + """Validate and translate a checkpoint config to the ONNX config consumed by either runtime. + + Args: + cfg: Authored network configuration, left unchanged. + batch: Example batch size for checkpoint export. + device: Device used to prepare a legacy checkpoint. + + Returns: + A copy referring to the prepared ONNX checkpoint. + """ + cfg.validate_config(require_network=True) + if isinstance(cfg, ActuatorNetMLPCfg): + metadata = dict( + model_type="mlp", + input_order=cfg.input_order, + input_idx=list(cfg.input_idx), + pos_scale=cfg.pos_scale, + vel_scale=cfg.vel_scale, + torque_scale=cfg.torque_scale, + ) + return replace(cfg, network_file=export_onnx_model(cfg.network_file, metadata, batch, device)) + metadata = {"model_type": "lstm", "batch_first": cfg.batch_first} + return replace(cfg, network_file=export_onnx_model(cfg.network_file, metadata, batch, device), batch_first=False) diff --git a/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py index 891241206dec..1ab90295cacb 100644 --- a/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py +++ b/source/isaaclab/isaaclab/envs/reset/reset_state_sampler.py @@ -23,6 +23,7 @@ from isaaclab.utils.warp import ProxyArray from isaaclab.utils.warp.memory import resolve_1d_mask +from ...utils.warp.kernels import initialize_rng_state from .reset_state_sampler_cfg import ResetStateSamplerCfg from .sampling_scores import SamplingScore @@ -156,7 +157,7 @@ def reseed(self, seed: int) -> None: Assignments, outcome history, metric values, and the configured initial seed remain unchanged. """ seed = (int(seed) + 2**31) % 2**32 - 2**31 - wp.launch(_initialize_rng, self.num_envs, [seed, self._rng], device=self.device) + wp.launch(initialize_rng_state, self.num_envs, [seed, self._rng], device=self.device) def reset( self, @@ -340,12 +341,6 @@ def _input(self, value: wp.array | ProxyArray | torch.Tensor, size: int) -> wp.a return result -@wp.kernel -def _initialize_rng(seed: int, states: wp.array(dtype=wp.uint32)): - i = wp.tid() - states[i] = wp.rand_init(seed, i) - - @wp.kernel def _resolve_requests( mask: wp.array(dtype=wp.bool), 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..cc04afc2f834 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/base_ray_caster.py @@ -5,9 +5,7 @@ from __future__ import annotations -import json import logging -import zlib from collections.abc import Sequence from typing import TYPE_CHECKING, Any, ClassVar @@ -80,8 +78,6 @@ 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 - # 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: @@ -272,10 +268,9 @@ 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 configuration's drift stream. + """Seed drift from the environment seed and the explicitly configured drift seed. - 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 + 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. @@ -284,7 +279,7 @@ def _seed_drift(self, seed: int) -> None: wp.launch( initialize_rng_state, dim=self._view_count, - inputs=[(seed ^ self._drift_stream) & 0x7FFFFFFF], + inputs=[(seed ^ self.cfg.drift_seed) & 0x7FFFFFFF], outputs=[self._drift_rng_state], device=self._device, ) diff --git a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_cfg.py b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_cfg.py index 259d73a6735b..693a8a3bbb93 100644 --- a/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_cfg.py +++ b/source/isaaclab/isaaclab/sensors/ray_caster/ray_caster_cfg.py @@ -81,6 +81,12 @@ class OffsetCfg: CPU queries and the static Warp-mesh implementations run eagerly. """ + drift_seed: int = 0 + """Seed mixed with the environment seed for drift. Set different values for independent sensor streams. + + Visualization, offsets, and other sensor settings do not change the stream. + """ + drift_range: tuple[float, float] = (0.0, 0.0) """The range of drift (in meters) to add to the ray starting positions (xyz) in world frame. Defaults to (0.0, 0.0). diff --git a/source/isaaclab/isaaclab/sim/schemas/schemas_actuators.py b/source/isaaclab/isaaclab/sim/schemas/schemas_actuators.py index 35ef1c3df9e1..fc7de050a99a 100644 --- a/source/isaaclab/isaaclab/sim/schemas/schemas_actuators.py +++ b/source/isaaclab/isaaclab/sim/schemas/schemas_actuators.py @@ -20,24 +20,20 @@ from __future__ import annotations -import json import logging -import tempfile import warnings from collections.abc import Callable from dataclasses import dataclass from operator import attrgetter from typing import Any -import torch - from pxr import Sdf, Usd, UsdPhysics from ...actuators.actuator_bam_cfg import BAM_DRIVE_API, BAM_MODEL_FLAGS, BamActuatorCfg from ...actuators.actuator_base import ActuatorBase from ...actuators.actuator_base_cfg import ActuatorBaseCfg, _is_implicit_actuator_cfg from ...actuators.actuator_net import ActuatorNetLSTM, ActuatorNetMLP -from ...actuators.actuator_net_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg +from ...actuators.actuator_net_cfg import ActuatorNetLSTMCfg, ActuatorNetMLPCfg, resolve_network_config from ...actuators.actuator_pd import DCMotor, DelayedPDActuator, IdealPDActuator, RemotizedPDActuator from ...actuators.actuator_pd_cfg import ( DCMotorCfg, @@ -46,7 +42,6 @@ RemotizedPDActuatorCfg, ) from ...utils import validate -from ...utils.assets import retrieve_file_path from ...utils.backend_utils import FactoryBase from ...utils.string import ( find_unique_string_name, @@ -476,17 +471,8 @@ def _exported_model_path(cfg: ActuatorNetMLPCfg | ActuatorNetLSTMCfg, joint_name """Return a configured neural checkpoint for every joint, or no overrides when the checkpoint is unset.""" if cfg.network_file is None: return {} - meta: dict[str, Any] = {} - if isinstance(cfg, ActuatorNetMLPCfg): - meta["model_type"] = "mlp" - meta["input_order"] = cfg.input_order - meta["input_idx"] = list(cfg.input_idx) - meta["pos_scale"] = cfg.pos_scale - meta["vel_scale"] = cfg.vel_scale - meta["torque_scale"] = cfg.torque_scale - else: - meta["model_type"] = "lstm" - return dict.fromkeys(joint_names, Sdf.AssetPath(resave_checkpoint_with_metadata(cfg.network_file, meta))) + resolved = resolve_network_config(cfg) + return dict.fromkeys(joint_names, Sdf.AssetPath(resolved.network_file)) def _bam_value( @@ -603,67 +589,3 @@ def _bam_effort_limits(cfg: BamActuatorCfg, joint_names: list[str]) -> dict[str, def _actuator_layout(cfg: ActuatorBaseCfg) -> ActuatorLayout | None: """Return the Newton actuator layout of *cfg*'s type, or None if Newton cannot author it.""" return next((_ACTUATOR_LAYOUTS[cls] for cls in type(cfg).__mro__ if cls in _ACTUATOR_LAYOUTS), None) - - -def resave_checkpoint_with_metadata(original_path: str, metadata: dict[str, Any]) -> str: - """Re-save a neural-network checkpoint with updated metadata. - - Resolves the configured path through the shared asset cache, loads the - original TorchScript checkpoint, merges *metadata* into any existing - metadata (Lab config values take precedence), and exports Newton's ``.pt2`` - format with a dynamic batch dimension. The temporary file persists for the - lifetime of the process. - - Args: - original_path: Path or URL of a TorchScript actuator checkpoint. - metadata: Overrides for the checkpoint's metadata. The merged metadata must include - ``model_type`` (``"mlp"`` or ``"lstm"``) and, for MLP models, ``input_idx``. - - Returns: - Path to the temporary ``.pt2`` checkpoint. - """ - # Deferred: importing the converter loads torch._dynamo, which adds seconds to every articulation spawn. - from torch._export.converter import TS2EPConverter # noqa: PLC0415 - - local_path = retrieve_file_path(original_path) - - extra_files: dict[str, str] = {"metadata.json": ""} - try: - net = torch.jit.load(local_path, map_location="cpu", _extra_files=extra_files) - existing_meta = json.loads(extra_files["metadata.json"]) if extra_files["metadata.json"] else {} - except Exception as exc: - raise ValueError(f"Cannot load checkpoint at '{original_path}'; expected a TorchScript archive") from exc - - merged = {**existing_meta, **metadata} - batch = torch.export.Dim("batch") - if merged["model_type"] == "lstm": - weights = net.lstm.state_dict() - merged["num_layers"] = len(weights) // 4 - merged["hidden_size"] = weights["weight_hh_l0"].shape[1] - state_shape = (merged["num_layers"], 3, merged["hidden_size"]) - inputs = (torch.zeros(3, 1, 2), (torch.zeros(state_shape), torch.zeros(state_shape))) - dynamic_shapes = ({0: batch}, ({1: batch}, {1: batch})) - else: - inputs = (torch.zeros(3, 2 * len(merged["input_idx"])),) - dynamic_shapes = ({0: batch},) - - converter = TS2EPConverter(net.eval(), inputs) - # Fold TorchScript's rank checks before converting LSTM control flow. - torch._C._jit_pass_peephole(converter.ts_graph, False) - torch._C._jit_pass_constant_propagation(converter.ts_graph) - program = converter.convert() - graph = program.module(check_guards=False) - # Lifted LSTM weights must move with the module when Newton selects its device. - for name, tensor in program.constants.items(): - if isinstance(tensor, torch.Tensor): - delattr(graph, name) - graph.register_buffer(name, tensor) - # The converter specializes LSTM batches; export the graph with an explicit batch contract. - program = torch.export.export(graph, inputs, dynamic_shapes=dynamic_shapes) - - with tempfile.NamedTemporaryFile(suffix=".pt2", delete=False) as tmp: - tmp_path = tmp.name - extra_out = {"metadata.json": json.dumps(merged)} - torch.export.save(program, tmp_path, extra_files=extra_out) - - return tmp_path diff --git a/source/isaaclab/isaaclab/utils/io/__init__.pyi b/source/isaaclab/isaaclab/utils/io/__init__.pyi index 91692a594c16..313c0780da56 100644 --- a/source/isaaclab/isaaclab/utils/io/__init__.pyi +++ b/source/isaaclab/isaaclab/utils/io/__init__.pyi @@ -4,12 +4,12 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ - "load_onnx_model", + "export_onnx_model", "load_torchscript_model", "dump_yaml", "load_yaml", ] -from .onnx import load_onnx_model +from .onnx import export_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..f10ffab8dc31 100644 --- a/source/isaaclab/isaaclab/utils/io/onnx.py +++ b/source/isaaclab/isaaclab/utils/io/onnx.py @@ -3,52 +3,95 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""ONNX I/O utilities.""" +"""ONNX checkpoint preparation shared by Isaac Lab and Newton actuators.""" import io -from collections.abc import Callable +import json +import tempfile +from typing import Any +import onnx import torch +from onnx import helper from ..assets import read_file +from .torchscript import load_torchscript_model -def load_onnx_model( - model_path: str, - sample_inputs: tuple | Callable[[torch.jit.ScriptModule], tuple], - *, - device: str, - input_names: list[str], - output_names: list[str], -) -> io.BytesIO: - """Load a network file as an ONNX model. +def export_onnx_model(model_path: str, metadata: dict[str, Any], batch: int = 3, device: str = "cpu") -> str: + """Prepare a neural-actuator checkpoint as ONNX, preserving metadata and applying config overrides. - 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. + TorchScript checkpoints are translated once at the configuration boundary. The ONNX model has dynamic batch + axes, and a terminal torque squeeze becomes a flatten so a one-joint batch keeps a non-scalar output. 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. - input_names: Names of the exported model's inputs. - output_names: Names of the exported model's outputs. + model_path: ONNX or TorchScript checkpoint path, local or remote. + metadata: Actuator metadata overrides, including ``model_type`` and, for MLPs, ``input_idx``. + batch: Example batch size for TorchScript export. + device: Device used for TorchScript export. Returns: - The ONNX model. An ``.onnx`` file keeps its own input and output names. + Temporary ONNX checkpoint path, retained for the process lifetime. """ - 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(module) if callable(sample_inputs) else sample_inputs, - model, - input_names=input_names, - output_names=output_names, - dynamo=False, - ) - model.seek(0) - return model + model = onnx.load_model(read_file(model_path)) + props = {prop.key: prop.value for prop in model.metadata_props} + metadata = {**json.loads(props.get("metadata", "{}")), **metadata} + else: + extra = {"metadata.json": ""} + module = load_torchscript_model(model_path, device, extra_files=extra) + metadata = {**json.loads(extra["metadata.json"] or "{}"), **metadata} + batch = max(batch, 2) + if metadata["model_type"] == "lstm": + state = torch.zeros(module.lstm.num_layers, batch, module.lstm.hidden_size, device=device) + metadata["batch_first"] = module.lstm.batch_first + shape = (batch, 1, 2) if module.lstm.batch_first else (1, batch, 2) + inputs = (torch.zeros(shape, device=device), (state, state)) + names, outputs = ["input", "h0", "c0"], ["torque", "h1", "c1"] + axes = { + "input": {0 if module.lstm.batch_first else 1: "batch"}, + "torque": {0: "batch"}, + **{name: {1: "batch"} for name in names[1:] + outputs[1:]}, + } + else: + inputs = (torch.zeros(batch, 2 * len(metadata["input_idx"]), device=device),) + names, outputs = ["input"], ["torque"] + axes = {name: {0: "batch"} for name in names + outputs} + exported = io.BytesIO() + torch.onnx.export( + module, inputs, exported, input_names=names, output_names=outputs, dynamic_axes=axes, dynamo=False + ) + model = onnx.load_model_from_string(exported.getvalue()) + props = {} + if metadata["model_type"] == "lstm" and metadata["batch_first"]: + original_name = model.graph.input[0].name + input_name = original_name + "__sequence_first" + model.graph.node.insert(0, helper.make_node("Transpose", [input_name], [original_name], perm=[1, 0, 2])) + model.graph.input[0].CopyFrom( + helper.make_tensor_value_info(input_name, onnx.TensorProto.FLOAT, [1, "batch", 2]) + ) + metadata["batch_first"] = False + metadata.update(input_name=model.graph.input[0].name, output_name=model.graph.output[0].name) + if metadata["model_type"] == "lstm": + metadata.update( + hidden_in_name=model.graph.input[1].name, + cell_in_name=model.graph.input[2].name, + hidden_out_name=model.graph.output[1].name, + cell_out_name=model.graph.output[2].name, + ) + dimensions = model.graph.input[1].type.tensor_type.shape.dim + metadata.update(num_layers=dimensions[0].dim_value, hidden_size=dimensions[2].dim_value) + torque = model.graph.output[0] + for node in model.graph.node: + if node.op_type == "Squeeze" and torque.name in node.output: + node.op_type = "Flatten" + del node.input[1:] + del node.attribute[:] + node.attribute.append(helper.make_attribute("axis", 1)) + torque.type.tensor_type.shape.ClearField("dim") + torque.type.tensor_type.shape.dim.add().dim_param = "batch" + torque.type.tensor_type.shape.dim.add().dim_value = 1 + onnx.helper.set_model_props(model, {**props, "metadata": json.dumps(metadata)}) + with tempfile.NamedTemporaryFile(suffix=".onnx", delete=False) as checkpoint: + onnx.save_model(model, checkpoint.name) + return checkpoint.name diff --git a/source/isaaclab/isaaclab/utils/io/torchscript.py b/source/isaaclab/isaaclab/utils/io/torchscript.py index 444b69c84262..ad30da7fbd98 100644 --- a/source/isaaclab/isaaclab/utils/io/torchscript.py +++ b/source/isaaclab/isaaclab/utils/io/torchscript.py @@ -6,36 +6,22 @@ """TorchScript I/O utilities.""" -import os - import torch +from ..assets import read_file -def load_torchscript_model(model_path: str, device: str = "cpu") -> torch.nn.Module: - """Load a TorchScript model from the specified path. - This function only loads TorchScript models (.pt or .pth files created with torch.jit.save). - It will not work with raw PyTorch checkpoints (.pth files created with torch.save). +def load_torchscript_model( + model_path: str, device: str = "cpu", *, extra_files: dict[str, str] | None = None +) -> torch.jit.ScriptModule: + """Load an evaluation-mode TorchScript checkpoint through the shared local or remote asset reader. Args: - model_path (str): Path to the TorchScript model file (.pt or .pth) - device (str, optional): Device to load the model on. Defaults to 'cpu'. + model_path: TorchScript checkpoint path, local or remote. + device: Device on which to load the module. + extra_files: Optional mapping populated with embedded files, such as actuator metadata. Returns: - torch.nn.Module: The loaded TorchScript model in evaluation mode - - Raises: - FileNotFoundError: If the model file does not exist. - RuntimeError: If the file cannot be loaded as a TorchScript model. + The loaded TorchScript module in evaluation mode. """ - if not os.path.exists(model_path): - raise FileNotFoundError(f"TorchScript model file not found: {model_path}") - - try: - model = torch.jit.load(model_path, map_location=device) - except Exception as exc: - raise RuntimeError(f"Failed to load TorchScript model from {model_path}") from exc - - model.eval() - print(f"Successfully loaded TorchScript model from {model_path}") - return model + return torch.jit.load(read_file(model_path), map_location=device, _extra_files=extra_files).eval() diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index b396de6cb236..d8bcc5fadd69 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -5,6 +5,8 @@ """Resets of the neural-network actuators by environment mask, recorded in a CUDA graph.""" +import ast + import pytest import torch import warp as wp @@ -56,7 +58,8 @@ 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): +def _actuator(cfg_class, network, tmp_path, device, network_format="pt", shape=(3, 2), **cfg): + num_envs, num_joints = shape network_file = tmp_path / f"network.{network_format}" if network_format == "onnx": _export_onnx(network, network_file) @@ -70,7 +73,13 @@ def _actuator(cfg_class, network: torch.nn.Module, tmp_path, device: str, networ actuator_velocity_limit=7.5, **cfg, ) - return instantiate(cfg, joint_names=["joint_0", "joint_1"], joint_ids=[0, 1], num_envs=3, device=device) + return instantiate( + cfg, + joint_names=[f"joint_{i}" for i in range(num_joints)], + joint_ids=list(range(num_joints)), + num_envs=num_envs, + device=device, + ) def _record_masked_reset(actuator, mask: wp.array) -> wp.Graph: @@ -176,49 +185,56 @@ 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"]) -def test_lstm_state_carries_across_steps(tmp_path, device, network_format): +@pytest.mark.parametrize( + "num_envs,num_joints,network_format", [(3, 2, "pt"), (3, 2, "onnx"), (1, 1, "pt"), (1, 1, "onnx")] +) +def test_lstm_state_carries_across_steps(tmp_path, device, num_envs, num_joints, 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) + actuator = _actuator(ActuatorNetLSTMCfg, network, tmp_path, device, network_format, shape=(num_envs, num_joints)) 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) + state_shape = (2, num_envs * num_joints, 4) + state = (torch.zeros(state_shape, device=device), torch.zeros(state_shape, device=device)) + joints = torch.arange(float(num_envs * num_joints), device=device).reshape(num_envs, num_joints) for step in range(6): if step == 3: - actuator.reset(env_ids=torch.tensor([0, 2], dtype=torch.int32, device=device)) + actuator.reset(env_ids=torch.arange(0, num_envs, 2, dtype=torch.int32, device=device)) for s in state: - s.view(2, 3, 2, 4)[:, [0, 2]] = 0.0 + s.view(2, num_envs, num_joints, 4)[:, ::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) + expected = torque.reshape(num_envs, num_joints) actuator.compute(ArticulationActions(joint_positions=desired), position, velocity) + torch.testing.assert_close(actuator.sea_input, x) 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.""" +@pytest.mark.parametrize( + "input_idx,input_order,error", [([0, -2], "pos_vel", IndexError), ([0], "invalid", ValueError)] +) +def test_mlp_config_rejects_invalid_preprocessing(tmp_path, input_idx, input_order, error): + """Preprocessing is rejected by configuration validation before checkpoint I/O or actuator construction.""" 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], + input_idx=input_idx, pos_scale=1.0, vel_scale=1.0, torque_scale=1.0, - input_order="pos_vel", + input_order=input_order, ) - 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") + with pytest.raises(error): + cfg.validate() @pytest.mark.parametrize("device", test_devices()) @@ -279,3 +295,17 @@ def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order, 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 + + +def test_runtime_keeps_configuration_validation_and_checkpoint_translation_outside(source_checkout_root): + """Runtime setup consumes resolved config; validation and legacy conversion stay with their owners.""" + path = source_checkout_root / "source/isaaclab/isaaclab/actuators/actuator_net.py" + tree = ast.parse(path.read_text()) + assert not any(isinstance(node, ast.Raise) for node in ast.walk(tree)) + assert not any( + isinstance(node, ast.Attribute) + and isinstance(node.value, ast.Name) + and node.value.id == "torch" + and node.attr in {"jit", "onnx"} + for node in ast.walk(tree) + ) diff --git a/source/isaaclab/test/actuators/test_newton_adapter.py b/source/isaaclab/test/actuators/test_newton_adapter.py index 4caaaa102787..975a3d81507c 100644 --- a/source/isaaclab/test/actuators/test_newton_adapter.py +++ b/source/isaaclab/test/actuators/test_newton_adapter.py @@ -42,10 +42,10 @@ from isaaclab.sim.schemas.schemas_actuators import ( author_actuator_prims, define_actuator_properties, - resave_checkpoint_with_metadata, ) from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.test.utils.actuator_equivalence import make_dummy_lstm_checkpoint, make_dummy_mlp_checkpoint +from isaaclab.utils.io import export_onnx_model _JOINT_NAMES = ["pd_a", "pd_b", "dc_a", "dc_b", "remote_a", "remote_b"] @@ -165,8 +165,8 @@ def test_checkpoint_metadata_rejects_pickle_without_deserializing(monkeypatch, t torch.save({"model": _PickleMarker(str(marker_path))}, checkpoint_path) monkeypatch.setattr("isaaclab.utils.assets.retrieve_file_path", lambda _: str(checkpoint_path)) - with pytest.raises(ValueError, match="expected a TorchScript archive"): - resave_checkpoint_with_metadata(str(checkpoint_path), {}) + with pytest.raises(RuntimeError): + export_onnx_model(str(checkpoint_path), {}) assert not marker_path.exists() @@ -205,9 +205,9 @@ def test_checkpoint_export_preserves_metadata_and_variable_batches(kind, device) converted_path = None try: original = torch.jit.load(path).eval() - converted_path = resave_checkpoint_with_metadata(path, {"model_type": kind, "torque_scale": 3.0}) - converted, metadata = load_checkpoint(converted_path) - original, converted = original.to(device), converted.to(device) + converted_path = export_onnx_model(path, {"model_type": kind, "torque_scale": 3.0}) + converted, metadata = load_checkpoint(converted_path, device=device) + original = original.to(device) assert metadata["model_type"] == kind assert metadata["torque_scale"] == 3.0 if kind == "mlp": @@ -222,7 +222,12 @@ def test_checkpoint_export_preserves_metadata_and_variable_batches(kind, device) hidden = torch.randn(1, batch_size, 4, device=device) cell = torch.randn_like(hidden) args = (torch.randn(batch_size, 1, 2, device=device), (hidden, cell)) - torch.testing.assert_close(converted(*args), original(*args)) + buffers = [args[0]] if kind == "mlp" else [args[0].reshape(1, batch_size, 2), *args[1]] + actual = converted({spec.name: wp.from_torch(value) for spec, value in zip(converted.inputs, buffers)}) + expected = original(*args) + values = [expected] if kind == "mlp" else [expected[0], *expected[1]] + for spec, value in zip(converted.outputs, values): + torch.testing.assert_close(wp.to_torch(actual[spec.name]), value.reshape(actual[spec.name].shape)) finally: Path(path).unlink() if converted_path is not None: @@ -339,10 +344,10 @@ def test_configuration_overrides_only_the_values_it_sets(tmp_path, caplog): asset.GetPrimAtPath("/World/Robot/remote_keep_actuator").GetRelationship("newton:targets").SetTargets( ["/World/Robot/remote_keep"] ) - checkpoint = tmp_path / "mlp.pt2" + checkpoint = tmp_path / "mlp.onnx" original = make_dummy_mlp_checkpoint() try: - Path(resave_checkpoint_with_metadata(original, {"model_type": "mlp"})).replace(checkpoint) + Path(export_onnx_model(original, {"model_type": "mlp"})).replace(checkpoint) finally: Path(original).unlink() joint = UsdPhysics.RevoluteJoint.Define(asset, "/World/Robot/mlp") diff --git a/source/isaaclab/test/controllers/test_controller_utils.py b/source/isaaclab/test/controllers/test_controller_utils.py index bddbbee4b8e5..34d8dc56d194 100644 --- a/source/isaaclab/test/controllers/test_controller_utils.py +++ b/source/isaaclab/test/controllers/test_controller_utils.py @@ -263,8 +263,5 @@ def test_load_torchscript_model_invalid_file(content, tmp_path): model_path = tmp_path / "model.pt" model_path.write_bytes(content) - with pytest.raises(RuntimeError, match="Failed to load TorchScript model") as exc_info: + with pytest.raises(RuntimeError): load_torchscript_model(str(model_path)) - - assert str(model_path) in str(exc_info.value) - assert isinstance(exc_info.value.__cause__, RuntimeError) diff --git a/source/isaaclab_newton/changelog.d/codex-actuator-network-config.skip b/source/isaaclab_newton/changelog.d/codex-actuator-network-config.skip new file mode 100644 index 000000000000..e69de29bb2d1 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..479ce5cfa224 100644 --- a/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_newton_raycast_sensor.py @@ -260,15 +260,14 @@ 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 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 of the current seed again. Different configured drift seeds produce independent streams. + Offsets and visualization settings do not change a stream; another sensor with the same drift seed repeats it. """ 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_cfg.raycast_twin = replace(scene_cfg.raycast, offset=twin_offset, drift_seed=1) + scene_cfg.raycast_copy = replace(scene_cfg.raycast, offset=twin_offset, debug_vis=True) scene = InteractiveScene(scene_cfg) sim.reset() sensor: NewtonRaycastSensor = scene["raycast"] From fc22c57b458b75024d420cd33ef6e0007426ff11 Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Tue, 1 Dec 2026 17:19:41 -0800 Subject: [PATCH 2/3] Consolidate actuator checkpoint preparation in config translation --- docs/source/refs/contributing.rst | 4 +- .../codex-actuator-network-config.changed.rst | 5 +- .../isaaclab/actuators/actuator_net.py | 14 +-- .../isaaclab/actuators/actuator_net_cfg.py | 98 ++++++++++++++++--- .../isaaclab/isaaclab/utils/io/__init__.pyi | 2 - source/isaaclab/isaaclab/utils/io/onnx.py | 97 ------------------ .../test/actuators/test_actuator_net.py | 2 + .../test/actuators/test_newton_adapter.py | 39 ++++++-- 8 files changed, 125 insertions(+), 136 deletions(-) delete mode 100644 source/isaaclab/isaaclab/utils/io/onnx.py diff --git a/docs/source/refs/contributing.rst b/docs/source/refs/contributing.rst index d7f734d87ad0..02657c65fe8d 100644 --- a/docs/source/refs/contributing.rst +++ b/docs/source/refs/contributing.rst @@ -440,7 +440,9 @@ before changing an interface. Apply these rules when adding code or cleaning up Use concrete defaults for known empty selections. Reserve ``None`` for a distinct policy or lifecycle state, such as choosing an environment's frame rate or waiting for a client to connect. * Translate legacy neural checkpoint configurations before runtime setup and share checkpoint preparation - across Isaac Lab and Newton. Keep preprocessing validation in the actuator config's ``validate_config``. + across Isaac Lab and Newton in the actuator config translation. Keep the actuator checkpoint contract out + of generic IO utilities and independent of simulation device and environment count. Keep preprocessing + validation in the actuator config's ``validate_config``. Declare random-stream identity explicitly; do not derive it by serializing unrelated configuration fields. * Give each piece of state and validation one owner. Consumers should use the owner's contract instead of repairing results or maintaining duplicate state. Cache derived values only when their lifetime and diff --git a/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst b/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst index f17fc34f5638..b7fa00b05dc6 100644 --- a/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst +++ b/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst @@ -1,5 +1,6 @@ -* Consolidated neural checkpoint preparation in ``export_onnx_model`` and config resolution, replacing the - separate schema-side Torch export and ``load_onnx_model`` callback interface. Runtime setup consumed ONNX only. +* Consolidated neural checkpoint preparation in ``resolve_network_config``, replacing the + separate schema-side Torch export and ``load_onnx_model`` callback interface. Checkpoint conversion used + a fixed CPU example batch with dynamic batch axes; runtime setup consumed ONNX only. * Added ``RayCasterCfg.drift_seed`` to select sensor drift streams explicitly. Set different drift seeds for independent sensors; offsets and visualization settings no longer selected a random stream. * Moved MLP preprocessing checks into ``validate_config``, reused actuator effort storage and paired history diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index a8fc497ddcda..8d66123985df 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -34,18 +34,8 @@ class _NetworkActuator(DCMotor): Warp kernels write into the base actuator's preallocated effort buffers through cached Warp views. """ - def __init__( - self, - cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, - joint_names: list[str], - joint_ids: slice | torch.Tensor, - num_envs: int, - device: str, - *args, - **kwargs, - ): - cfg = resolve_network_config(cfg, num_envs * len(joint_names), device) - super().__init__(cfg, joint_names, joint_ids, num_envs, device, *args, **kwargs) + def __init__(self, cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, *args, **kwargs): + super().__init__(resolve_network_config(cfg), *args, **kwargs) self.network = OnnxRuntime(self.cfg.network_file, device=self._device) self._computed_effort = wp.from_torch(self.computed_effort) self._applied_effort = wp.from_torch(self.applied_effort) diff --git a/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py b/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py index 1eaade254385..782dd39a3eeb 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net_cfg.py @@ -3,11 +3,19 @@ # # SPDX-License-Identifier: BSD-3-Clause +import io +import json +import tempfile from collections.abc import Iterable from typing import TYPE_CHECKING, Literal +import onnx +import torch +from onnx import helper + from ..utils import configclass, replace -from ..utils.io import export_onnx_model +from ..utils.assets import read_file +from ..utils.io import load_torchscript_model from .actuator_pd_cfg import DCMotorCfg if TYPE_CHECKING: @@ -109,21 +117,16 @@ def validate_config(self, *, require_network: bool = False) -> None: ) -def resolve_network_config( - cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, batch: int = 3, device: str = "cpu" -) -> ActuatorNetLSTMCfg | ActuatorNetMLPCfg: - """Validate and translate a checkpoint config to the ONNX config consumed by either runtime. - - Args: - cfg: Authored network configuration, left unchanged. - batch: Example batch size for checkpoint export. - device: Device used to prepare a legacy checkpoint. +def resolve_network_config(cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg) -> ActuatorNetLSTMCfg | ActuatorNetMLPCfg: + """Translate an authored actuator config to the metadata-bearing ONNX config consumed by either runtime. - Returns: - A copy referring to the prepared ONNX checkpoint. + Legacy TorchScript export uses a fixed CPU example batch with dynamic batch axes. LSTM inputs become + sequence first, and terminal torque squeezes become flattens so a one-joint batch keeps a non-scalar output. + The authored configuration is left unchanged. """ cfg.validate_config(require_network=True) - if isinstance(cfg, ActuatorNetMLPCfg): + is_mlp = isinstance(cfg, ActuatorNetMLPCfg) + if is_mlp: metadata = dict( model_type="mlp", input_order=cfg.input_order, @@ -132,6 +135,69 @@ def resolve_network_config( vel_scale=cfg.vel_scale, torque_scale=cfg.torque_scale, ) - return replace(cfg, network_file=export_onnx_model(cfg.network_file, metadata, batch, device)) - metadata = {"model_type": "lstm", "batch_first": cfg.batch_first} - return replace(cfg, network_file=export_onnx_model(cfg.network_file, metadata, batch, device), batch_first=False) + else: + metadata = {"model_type": "lstm", "batch_first": cfg.batch_first} + if cfg.network_file.endswith(".onnx"): + model = onnx.load_model(read_file(cfg.network_file)) + props = {prop.key: prop.value for prop in model.metadata_props} + metadata = {**json.loads(props.get("metadata", "{}")), **metadata} + else: + extra = {"metadata.json": ""} + module = load_torchscript_model(cfg.network_file, extra_files=extra) + metadata = {**json.loads(extra["metadata.json"] or "{}"), **metadata} + batch = 3 # A non-singleton example keeps legacy squeezes from specializing to scalars. + if not is_mlp: + state = torch.zeros(module.lstm.num_layers, batch, module.lstm.hidden_size, device="cpu") + metadata["batch_first"] = module.lstm.batch_first + shape = (batch, 1, 2) if module.lstm.batch_first else (1, batch, 2) + inputs = (torch.zeros(shape, device="cpu"), (state, state)) + names, outputs = ["input", "h0", "c0"], ["torque", "h1", "c1"] + axes = { + "input": {0 if module.lstm.batch_first else 1: "batch"}, + "torque": {0: "batch"}, + **{name: {1: "batch"} for name in names[1:] + outputs[1:]}, + } + else: + inputs = (torch.zeros(batch, 2 * len(cfg.input_idx), device="cpu"),) + names, outputs = ["input"], ["torque"] + axes = {name: {0: "batch"} for name in names + outputs} + exported = io.BytesIO() + torch.onnx.export( + module, inputs, exported, input_names=names, output_names=outputs, dynamic_axes=axes, dynamo=False + ) + model = onnx.load_model_from_string(exported.getvalue()) + props = {} + if not is_mlp and metadata["batch_first"]: + original_name = model.graph.input[0].name + input_name = original_name + "__sequence_first" + model.graph.node.insert(0, helper.make_node("Transpose", [input_name], [original_name], perm=[1, 0, 2])) + model.graph.input[0].CopyFrom( + helper.make_tensor_value_info(input_name, onnx.TensorProto.FLOAT, [1, "batch", 2]) + ) + metadata["batch_first"] = False + metadata.update(input_name=model.graph.input[0].name, output_name=model.graph.output[0].name) + if not is_mlp: + metadata.update( + hidden_in_name=model.graph.input[1].name, + cell_in_name=model.graph.input[2].name, + hidden_out_name=model.graph.output[1].name, + cell_out_name=model.graph.output[2].name, + ) + dimensions = model.graph.input[1].type.tensor_type.shape.dim + metadata.update(num_layers=dimensions[0].dim_value, hidden_size=dimensions[2].dim_value) + torque = model.graph.output[0] + for node in model.graph.node: + if node.op_type == "Squeeze" and torque.name in node.output: + node.op_type = "Flatten" + del node.input[1:] + del node.attribute[:] + node.attribute.append(helper.make_attribute("axis", 1)) + torque.type.tensor_type.shape.ClearField("dim") + torque.type.tensor_type.shape.dim.add().dim_param = "batch" + torque.type.tensor_type.shape.dim.add().dim_value = 1 + onnx.helper.set_model_props(model, {**props, "metadata": json.dumps(metadata)}) + with tempfile.NamedTemporaryFile(suffix=".onnx", delete=False) as checkpoint: + onnx.save_model(model, checkpoint.name) + if is_mlp: + return replace(cfg, network_file=checkpoint.name) + return replace(cfg, network_file=checkpoint.name, batch_first=False) diff --git a/source/isaaclab/isaaclab/utils/io/__init__.pyi b/source/isaaclab/isaaclab/utils/io/__init__.pyi index 313c0780da56..3d61292f55a7 100644 --- a/source/isaaclab/isaaclab/utils/io/__init__.pyi +++ b/source/isaaclab/isaaclab/utils/io/__init__.pyi @@ -4,12 +4,10 @@ # SPDX-License-Identifier: BSD-3-Clause __all__ = [ - "export_onnx_model", "load_torchscript_model", "dump_yaml", "load_yaml", ] -from .onnx import export_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 deleted file mode 100644 index f10ffab8dc31..000000000000 --- a/source/isaaclab/isaaclab/utils/io/onnx.py +++ /dev/null @@ -1,97 +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 - -"""ONNX checkpoint preparation shared by Isaac Lab and Newton actuators.""" - -import io -import json -import tempfile -from typing import Any - -import onnx -import torch -from onnx import helper - -from ..assets import read_file -from .torchscript import load_torchscript_model - - -def export_onnx_model(model_path: str, metadata: dict[str, Any], batch: int = 3, device: str = "cpu") -> str: - """Prepare a neural-actuator checkpoint as ONNX, preserving metadata and applying config overrides. - - TorchScript checkpoints are translated once at the configuration boundary. The ONNX model has dynamic batch - axes, and a terminal torque squeeze becomes a flatten so a one-joint batch keeps a non-scalar output. - - Args: - model_path: ONNX or TorchScript checkpoint path, local or remote. - metadata: Actuator metadata overrides, including ``model_type`` and, for MLPs, ``input_idx``. - batch: Example batch size for TorchScript export. - device: Device used for TorchScript export. - - Returns: - Temporary ONNX checkpoint path, retained for the process lifetime. - """ - if model_path.endswith(".onnx"): - model = onnx.load_model(read_file(model_path)) - props = {prop.key: prop.value for prop in model.metadata_props} - metadata = {**json.loads(props.get("metadata", "{}")), **metadata} - else: - extra = {"metadata.json": ""} - module = load_torchscript_model(model_path, device, extra_files=extra) - metadata = {**json.loads(extra["metadata.json"] or "{}"), **metadata} - batch = max(batch, 2) - if metadata["model_type"] == "lstm": - state = torch.zeros(module.lstm.num_layers, batch, module.lstm.hidden_size, device=device) - metadata["batch_first"] = module.lstm.batch_first - shape = (batch, 1, 2) if module.lstm.batch_first else (1, batch, 2) - inputs = (torch.zeros(shape, device=device), (state, state)) - names, outputs = ["input", "h0", "c0"], ["torque", "h1", "c1"] - axes = { - "input": {0 if module.lstm.batch_first else 1: "batch"}, - "torque": {0: "batch"}, - **{name: {1: "batch"} for name in names[1:] + outputs[1:]}, - } - else: - inputs = (torch.zeros(batch, 2 * len(metadata["input_idx"]), device=device),) - names, outputs = ["input"], ["torque"] - axes = {name: {0: "batch"} for name in names + outputs} - exported = io.BytesIO() - torch.onnx.export( - module, inputs, exported, input_names=names, output_names=outputs, dynamic_axes=axes, dynamo=False - ) - model = onnx.load_model_from_string(exported.getvalue()) - props = {} - if metadata["model_type"] == "lstm" and metadata["batch_first"]: - original_name = model.graph.input[0].name - input_name = original_name + "__sequence_first" - model.graph.node.insert(0, helper.make_node("Transpose", [input_name], [original_name], perm=[1, 0, 2])) - model.graph.input[0].CopyFrom( - helper.make_tensor_value_info(input_name, onnx.TensorProto.FLOAT, [1, "batch", 2]) - ) - metadata["batch_first"] = False - metadata.update(input_name=model.graph.input[0].name, output_name=model.graph.output[0].name) - if metadata["model_type"] == "lstm": - metadata.update( - hidden_in_name=model.graph.input[1].name, - cell_in_name=model.graph.input[2].name, - hidden_out_name=model.graph.output[1].name, - cell_out_name=model.graph.output[2].name, - ) - dimensions = model.graph.input[1].type.tensor_type.shape.dim - metadata.update(num_layers=dimensions[0].dim_value, hidden_size=dimensions[2].dim_value) - torque = model.graph.output[0] - for node in model.graph.node: - if node.op_type == "Squeeze" and torque.name in node.output: - node.op_type = "Flatten" - del node.input[1:] - del node.attribute[:] - node.attribute.append(helper.make_attribute("axis", 1)) - torque.type.tensor_type.shape.ClearField("dim") - torque.type.tensor_type.shape.dim.add().dim_param = "batch" - torque.type.tensor_type.shape.dim.add().dim_value = 1 - onnx.helper.set_model_props(model, {**props, "metadata": json.dumps(metadata)}) - with tempfile.NamedTemporaryFile(suffix=".onnx", delete=False) as checkpoint: - onnx.save_model(model, checkpoint.name) - return checkpoint.name diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index d8bcc5fadd69..beee5ef6104d 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -299,6 +299,8 @@ def test_mlp_history_keeps_its_window(tmp_path, device, input_idx, input_order, def test_runtime_keeps_configuration_validation_and_checkpoint_translation_outside(source_checkout_root): """Runtime setup consumes resolved config; validation and legacy conversion stay with their owners.""" + # Checkpoint preparation belongs to actuator config, with no separate generic ONNX IO owner. + assert not (source_checkout_root / "source/isaaclab/isaaclab/utils/io/onnx.py").exists() path = source_checkout_root / "source/isaaclab/isaaclab/actuators/actuator_net.py" tree = ast.parse(path.read_text()) assert not any(isinstance(node, ast.Raise) for node in ast.walk(tree)) diff --git a/source/isaaclab/test/actuators/test_newton_adapter.py b/source/isaaclab/test/actuators/test_newton_adapter.py index 975a3d81507c..246e18b5abf2 100644 --- a/source/isaaclab/test/actuators/test_newton_adapter.py +++ b/source/isaaclab/test/actuators/test_newton_adapter.py @@ -5,6 +5,7 @@ """Tests for the PhysX-side Newton actuator adapter and its host runtime.""" +import json import logging from pathlib import Path from types import SimpleNamespace @@ -29,6 +30,7 @@ from isaaclab.actuators import ( ActuatorBaseCfg, + ActuatorNetLSTMCfg, ActuatorNetMLPCfg, DCMotor, DCMotorCfg, @@ -36,6 +38,7 @@ IdealPDActuatorCfg, RemotizedPDActuatorCfg, ) +from isaaclab.actuators.actuator_net_cfg import resolve_network_config from isaaclab.actuators.newton import NewtonActuatorAdapter from isaaclab.actuators.newton.physx_runtime import PhysxActuatorRuntime from isaaclab.sim import SimulationCfg, SimulationContext @@ -45,7 +48,6 @@ ) from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.test.utils.actuator_equivalence import make_dummy_lstm_checkpoint, make_dummy_mlp_checkpoint -from isaaclab.utils.io import export_onnx_model _JOINT_NAMES = ["pd_a", "pd_b", "dc_a", "dc_b", "remote_a", "remote_b"] @@ -166,7 +168,7 @@ def test_checkpoint_metadata_rejects_pickle_without_deserializing(monkeypatch, t monkeypatch.setattr("isaaclab.utils.assets.retrieve_file_path", lambda _: str(checkpoint_path)) with pytest.raises(RuntimeError): - export_onnx_model(str(checkpoint_path), {}) + resolve_network_config(ActuatorNetLSTMCfg(network_file=str(checkpoint_path))) assert not marker_path.exists() @@ -204,13 +206,30 @@ def test_checkpoint_export_preserves_metadata_and_variable_batches(kind, device) path = make_dummy_mlp_checkpoint() if kind == "mlp" else make_dummy_lstm_checkpoint() converted_path = None try: - original = torch.jit.load(path).eval() - converted_path = export_onnx_model(path, {"model_type": kind, "torque_scale": 3.0}) + extra = {"metadata.json": ""} + original = torch.jit.load(path, _extra_files=extra).eval() + source_metadata = {**json.loads(extra["metadata.json"]), "training_run": "fixture"} + torch.jit.save(original, path, _extra_files={"metadata.json": json.dumps(source_metadata)}) + cfg = ( + ActuatorNetMLPCfg( + network_file=path, + input_order="pos_vel", + input_idx=[0, 1, 2], + pos_scale=1.0, + vel_scale=0.5, + torque_scale=3.0, + ) + if kind == "mlp" + else ActuatorNetLSTMCfg(network_file=path) + ) + converted_path = resolve_network_config(cfg).network_file + assert cfg.network_file == path converted, metadata = load_checkpoint(converted_path, device=device) original = original.to(device) assert metadata["model_type"] == kind - assert metadata["torque_scale"] == 3.0 + assert metadata["training_run"] == "fixture" if kind == "mlp": + assert metadata["torque_scale"] == 3.0 assert metadata["input_idx"] == [0, 1, 2] assert metadata["vel_scale"] == 0.5 else: @@ -347,7 +366,15 @@ def test_configuration_overrides_only_the_values_it_sets(tmp_path, caplog): checkpoint = tmp_path / "mlp.onnx" original = make_dummy_mlp_checkpoint() try: - Path(export_onnx_model(original, {"model_type": "mlp"})).replace(checkpoint) + cfg = ActuatorNetMLPCfg( + network_file=original, + input_order="pos_vel", + input_idx=[0, 1, 2], + pos_scale=1.0, + vel_scale=0.5, + torque_scale=2.0, + ) + Path(resolve_network_config(cfg).network_file).replace(checkpoint) finally: Path(original).unlink() joint = UsdPhysics.RevoluteJoint.Define(asset, "/World/Robot/mlp") From 25ef738c0b860b96f741ad03938e30f1c163be35 Mon Sep 17 00:00:00 2001 From: Octi Zhang Date: Tue, 1 Dec 2026 17:30:53 -0800 Subject: [PATCH 3/3] Keep neural actuator lifecycles in direct DC motor subclasses --- docs/source/refs/contributing.rst | 2 + .../codex-actuator-network-config.changed.rst | 2 + .../isaaclab/actuators/actuator_net.py | 120 +++++++++--------- .../test/actuators/test_actuator_net.py | 7 + 4 files changed, 73 insertions(+), 58 deletions(-) diff --git a/docs/source/refs/contributing.rst b/docs/source/refs/contributing.rst index 02657c65fe8d..fa1469b12224 100644 --- a/docs/source/refs/contributing.rst +++ b/docs/source/refs/contributing.rst @@ -430,6 +430,8 @@ before changing an interface. Apply these rules when adding code or cleaning up a one-line helper merely to rename an obvious operation. Introduce a helper when it removes meaningful duplication or gives a coherent, non-trivial operation a useful name; its benefit should outweigh the need to jump to another definition to understand the caller. + Keep concrete actuator lifecycles direct. Do not introduce an intermediate base class solely to share + short initialization and kernel-launch wiring; reuse the computation kernel directly. When retiring a workflow, remove its unused helper chains and tests that only preserve those helpers. Name nontrivial predicates when that makes a branch easier to read, keeping the operation inline. Avoid aliases such as ``cfg = visualizer.cfg`` that only shorten direct attribute access. diff --git a/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst b/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst index b7fa00b05dc6..09a6607a9a2b 100644 --- a/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst +++ b/source/isaaclab/changelog.d/codex-actuator-network-config.changed.rst @@ -5,3 +5,5 @@ independent sensors; offsets and visualization settings no longer selected a random stream. * Moved MLP preprocessing checks into ``validate_config``, reused actuator effort storage and paired history clearing, and shared the RNG initialization kernel with reset-state sampling. +* Kept MLP and LSTM as direct ``DCMotor`` subclasses with their own setup and torque application, + sharing the clipping kernel without an intermediate network base class or torque-application helper. diff --git a/source/isaaclab/isaaclab/actuators/actuator_net.py b/source/isaaclab/isaaclab/actuators/actuator_net.py index 8d66123985df..7795d41c197d 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_net.py +++ b/source/isaaclab/isaaclab/actuators/actuator_net.py @@ -28,51 +28,7 @@ from .actuator_pd import 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. - - Warp kernels write into the base actuator's preallocated effort buffers through cached Warp views. - """ - - def __init__(self, cfg: ActuatorNetLSTMCfg | ActuatorNetMLPCfg, *args, **kwargs): - super().__init__(resolve_network_config(cfg), *args, **kwargs) - self.network = OnnxRuntime(self.cfg.network_file, device=self._device) - self._computed_effort = wp.from_torch(self.computed_effort) - self._applied_effort = wp.from_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 - ) -> 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, - *self._motor_limits, - ], - 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 - - -class ActuatorNetLSTM(_NetworkActuator): +class ActuatorNetLSTM(DCMotor): """Actuator model based on recurrent neural network (LSTM). Unlike the MLP implementation :cite:t:`hwangbo2019learning`, this class implements @@ -89,13 +45,22 @@ class ActuatorNetLSTM(_NetworkActuator): """The configuration of the actuator model.""" def __init__(self, cfg: ActuatorNetLSTMCfg, *args, **kwargs): - super().__init__(cfg, *args, **kwargs) + super().__init__(resolve_network_config(cfg), *args, **kwargs) + self.network = OnnxRuntime(self.cfg.network_file, device=self._device) + self._effort_buffers = [wp.from_torch(effort) for effort in (self.computed_effort, 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, + ) + ) batch = self._num_envs * self.num_joints - # 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((1, batch, 2), dtype=wp.float32, device=self._device) @@ -148,14 +113,29 @@ def compute( ) # 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) + torque, hidden_state, cell_state = (outputs[spec.name] for spec in self.network.outputs) 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) + 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), + 1.0, + *self._motor_limits, + ], + outputs=self._effort_buffers, + device=self._device, + ) + control_action.joint_efforts = self.applied_effort + control_action.joint_positions = None + control_action.joint_velocities = None + return control_action -class ActuatorNetMLP(_NetworkActuator): +class ActuatorNetMLP(DCMotor): """Actuator model based on multi-layer perceptron and joint history. Many times the analytical model is not sufficient to capture the actuator dynamics, the @@ -178,15 +158,24 @@ class ActuatorNetMLP(_NetworkActuator): """The configuration of the actuator model.""" def __init__(self, cfg: ActuatorNetMLPCfg, *args, **kwargs): - super().__init__(cfg, *args, **kwargs) + super().__init__(resolve_network_config(cfg), *args, **kwargs) + self.network = OnnxRuntime(self.cfg.network_file, device=self._device) + self._effort_buffers = [wp.from_torch(effort) for effort in (self.computed_effort, 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, + ) + ) history_length = max(self.cfg.input_idx) + 1 # 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] - # an ONNX file keeps the input and output names it was exported with - 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) self._joint_pos_error_history = wp.zeros(history_shape, dtype=wp.float32, device=self._device) @@ -238,6 +227,21 @@ def compute( device=self._device, ) # run network inference - torque = self.network(self._network_inputs)[self._network_output_name] + torque = self.network(self._network_inputs)[self.network.outputs[0].name] # scale the torque and clip it based on the motor limits - return self._apply_torque(control_action, torque, joint_vel, self.cfg.torque_scale) + 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), + self.cfg.torque_scale, + *self._motor_limits, + ], + outputs=self._effort_buffers, + device=self._device, + ) + control_action.joint_efforts = self.applied_effort + control_action.joint_positions = None + control_action.joint_velocities = None + return control_action diff --git a/source/isaaclab/test/actuators/test_actuator_net.py b/source/isaaclab/test/actuators/test_actuator_net.py index beee5ef6104d..08f0eeddb86b 100644 --- a/source/isaaclab/test/actuators/test_actuator_net.py +++ b/source/isaaclab/test/actuators/test_actuator_net.py @@ -303,6 +303,13 @@ def test_runtime_keeps_configuration_validation_and_checkpoint_translation_outsi assert not (source_checkout_root / "source/isaaclab/isaaclab/utils/io/onnx.py").exists() path = source_checkout_root / "source/isaaclab/isaaclab/actuators/actuator_net.py" tree = ast.parse(path.read_text()) + classes = [node for node in tree.body if isinstance(node, ast.ClassDef)] + assert {node.name for node in classes} == {"ActuatorNetLSTM", "ActuatorNetMLP"} + assert all( + len(node.bases) == 1 and isinstance(node.bases[0], ast.Name) and node.bases[0].id == "DCMotor" + for node in classes + ) + assert not any(isinstance(node, ast.FunctionDef) and node.name == "_apply_torque" for node in ast.walk(tree)) assert not any(isinstance(node, ast.Raise) for node in ast.walk(tree)) assert not any( isinstance(node, ast.Attribute)