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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/source/concepts/actuators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions docs/source/refs/contributing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -439,6 +441,11 @@ 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 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
invalidation are clear; do not expose mutable cached results for callers to modify accidentally.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
* 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
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.
Original file line number Diff line number Diff line change
@@ -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.
Empty file.
33 changes: 7 additions & 26 deletions source/isaaclab/isaaclab/actuators/actuator_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand Down
192 changes: 80 additions & 112 deletions source/isaaclab/isaaclab/actuators/actuator_net.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,73 +15,20 @@
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.
"""

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)
# 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
Expand All @@ -98,38 +45,33 @@ 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

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)
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)
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)
Expand Down Expand Up @@ -171,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
Expand All @@ -201,31 +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
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
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)
Expand All @@ -235,23 +185,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(
Expand All @@ -274,6 +227,21 @@ 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.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
Loading