From aab89609c2c036a1a050659b7c69fd4cdaa2863d Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Tue, 3 Nov 2026 21:00:32 -0800 Subject: [PATCH 01/21] Run the environment's actions and asset writes inside the Newton step ManagerBasedEnv binds its action terms and the scene's asset writes to the physics step through PhysicsManager.bind_control. Newton registers them as control callbacks, re-stages body forces after them, and runs the whole decimation loop in one captured step when every term and asset can be recorded. Action terms declare supports_graph_capture and apply_every_physics_step, and Newton keeps the loop in the environment when an unbound term must run before every physics step. Wrench composers record merge, composition and reset independent of host flags once used, and capture the step again at their first write. --- .../extending_newton_solvers.rst | 14 ++++- .../newton-redesign-3-env-control.added.rst | 11 ++++ .../newton-redesign-3-env-control.changed.rst | 3 + .../newton-redesign-3-env-control.minor | 0 .../isaaclab/actuators/actuator_collection.py | 5 ++ source/isaaclab/isaaclab/assets/asset_base.py | 3 + .../isaaclab/envs/manager_based_env.py | 15 +++-- .../isaaclab/envs/manager_based_rl_env.py | 13 ++-- .../envs/mdp/actions/binary_joint_actions.py | 20 +++---- .../envs/mdp/actions/joint_actions.py | 16 ++++- .../mdp/actions/joint_actions_to_limits.py | 12 ++-- .../mdp/actions/surface_gripper_actions.py | 2 + .../envs/mdp/actions/tendon_actions.py | 2 + .../isaaclab/managers/action_manager.py | 19 +++++- .../isaaclab/physics/physics_manager.py | 16 +++++ .../isaaclab/scene/interactive_scene.py | 32 ++++++---- .../isaaclab/utils/wrench_composer.py | 31 +++++++++- source/isaaclab/test/envs/mdp/test_actions.py | 30 +++++++++- .../test/utils/test_wrench_composer.py | 38 ++++++++++++ .../newton-redesign-3-env-control.added.rst | 5 ++ .../newton-redesign-3-env-control.changed.rst | 5 ++ .../newton-redesign-3-env-control.minor | 0 .../assets/articulation/articulation.py | 14 ++++- .../assets/rigid_object/rigid_object.py | 9 ++- .../rigid_object_collection.py | 9 ++- .../isaaclab_newton/physics/newton_backend.py | 23 +++++-- .../isaaclab_newton/physics/newton_manager.py | 40 ++++++++++++- .../test/physics/test_newton_manager.py | 60 +++++++++++++++++++ 28 files changed, 384 insertions(+), 63 deletions(-) create mode 100644 source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst create mode 100644 source/isaaclab/changelog.d/newton-redesign-3-env-control.changed.rst create mode 100644 source/isaaclab/changelog.d/newton-redesign-3-env-control.minor create mode 100644 source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst create mode 100644 source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst create mode 100644 source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.minor diff --git a/docs/source/developer-tools/extending_newton_solvers.rst b/docs/source/developer-tools/extending_newton_solvers.rst index 4df80e6fe243..84930fe75d52 100644 --- a/docs/source/developer-tools/extending_newton_solvers.rst +++ b/docs/source/developer-tools/extending_newton_solvers.rst @@ -125,12 +125,20 @@ The Step -------- Each :meth:`~isaaclab_newton.physics.NewtonManager.step` covers the whole decimation loop when the manager handles -decimation (:meth:`~isaaclab_newton.physics.NewtonManager.handles_decimation`: an articulation runs its Newton -actuators in the step), and one physics step otherwise. Every physics step runs ``collide -> pre-actuator callbacks --> Newton actuators -> post-actuator callbacks -> substeps``, and post-step callbacks and sensors run once at the end. +decimation (:meth:`~isaaclab_newton.physics.NewtonManager.handles_decimation`), and one physics step otherwise. It +does when the environment's control is bound to the step, or when an articulation runs its Newton actuators in the +step and every action term holds its command for the whole environment step (``apply_every_physics_step = False``). +Every physics step runs ``collide -> pre-actuator callbacks -> Newton actuators -> post-actuator callbacks -> +substeps``, and post-step callbacks and sensors run once at the end. Every substep runs ``staged body forces -> state-force callbacks -> step``, and ``pre_step`` and ``post_step`` run around each physics step's substeps. +:meth:`~isaaclab_newton.physics.NewtonManager.bind_control` binds the environment's control: each action term's +``apply_actions`` and the scene's ``write_data_to_sim`` become pre-actuator callbacks, followed by +:meth:`~isaaclab_newton.physics.NewtonBackend.stage_body_forces`, so they run before every physics step as in the +environment's own loop. It binds only when every action term and written asset sets ``supports_graph_capture``. +Wrench composers record their work once forces are first written, which captures the step again. + Every physics step ends in ``state_0``, so ``manager.backend.state_0`` is always the same object. The captured step records the callbacks, so they must be graph-safe. Consumers register them with :meth:`~isaaclab_newton.physics.NewtonManager.register_post_step_callback` and its siblings while ``PHYSICS_READY`` diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst new file mode 100644 index 000000000000..6cd22e28de5e --- /dev/null +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -0,0 +1,11 @@ +* Added :meth:`PhysicsManager.bind_control `, which let a physics + backend run the environment's actions and asset writes inside its step. :class:`~isaaclab.envs.ManagerBasedEnv` + called it after loading its managers and skipped the actions and asset writes that the step ran. +* Added ``supports_graph_capture`` and ``apply_every_physics_step`` to + :class:`~isaaclab.managers.ActionTerm`, ``supports_graph_capture`` to :class:`~isaaclab.assets.AssetBase`, + :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`, and + ``apply_every_physics_step`` to :class:`~isaaclab.managers.ActionManager`. Joint, joint-to-limits and binary joint + action terms set them. +* Added :attr:`WrenchComposer.pending ` and + ``WrenchComposer.on_first_use``. Once forces were written, wrench work recorded into a CUDA graph no longer + depended on host flags. diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.changed.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.changed.rst new file mode 100644 index 000000000000..671a0bdb9149 --- /dev/null +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.changed.rst @@ -0,0 +1,3 @@ +* Changed joint, joint-to-limits and binary joint action terms to write their processed actions in place, so a + recorded :meth:`~isaaclab.managers.ActionTerm.apply_actions` read the current actions. +* Changed :class:`~isaaclab.envs.ManagerBasedEnv` to set the physics decimation after loading its managers. diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.minor b/source/isaaclab/changelog.d/newton-redesign-3-env-control.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/actuators/actuator_collection.py b/source/isaaclab/isaaclab/actuators/actuator_collection.py index e949fc01b6c2..762ab85e1b92 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_collection.py +++ b/source/isaaclab/isaaclab/actuators/actuator_collection.py @@ -160,6 +160,11 @@ def device(self) -> str: """Warp/Torch device string.""" return self._control.device + @property + def supports_graph_capture(self) -> bool: + """Whether :meth:`compute` launches only Warp work, i.e. no Isaac Lab actuator model runs in Torch.""" + return not self._execution_actuators + @property def has_implicit_actuators(self) -> bool: """Whether any configured actuator group is implicit.""" diff --git a/source/isaaclab/isaaclab/assets/asset_base.py b/source/isaaclab/isaaclab/assets/asset_base.py index d859eb29fd15..5c04cfb3b8ea 100644 --- a/source/isaaclab/isaaclab/assets/asset_base.py +++ b/source/isaaclab/isaaclab/assets/asset_base.py @@ -78,6 +78,9 @@ class AssetBase(Asset, ABC): _check_shapes: bool = __debug__ """Class-level default for shape validation. Overridden per-instance in ``__init__``.""" + supports_graph_capture: bool = False + """Whether :meth:`write_data_to_sim` launches only Warp work whose recording does not depend on host state.""" + def __init__(self, cfg: AssetBaseCfg): """Initialize the asset base. diff --git a/source/isaaclab/isaaclab/envs/manager_based_env.py b/source/isaaclab/isaaclab/envs/manager_based_env.py index 04d50fe2e735..995509ef2666 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env.py @@ -94,6 +94,7 @@ def __init__(self, cfg: ManagerBasedEnvCfg): self.cfg = cfg # initialize internal variables self._physics_handles_decimation = False + self._physics_handles_actions = False # set the seed for the environment if self.cfg.seed is not None: @@ -202,14 +203,15 @@ def _init_sim(self): self.scene.update(dt=self.physics_dt) self.video_recorders: list[VideoRecorder] = [VideoRecorder(cfg, self) for cfg in self.cfg.video_recorders] - # let the physics backend know about the env decimation so it can - # fold the full loop into a single step() when possible - self.sim.backend_manager.set_decimation(self.cfg.decimation) - self._physics_handles_decimation = self.sim.backend_manager.handles_decimation() # add timeline event to load managers report_activity("Setting up managers") self.load_managers() report_activity(None) + # let the physics backend run the actions and asset writes inside its step, and fold the full loop + # into a single step() when possible + self._physics_handles_actions = self.sim.backend_manager.bind_control(self.action_manager, self.scene) + self.sim.backend_manager.set_decimation(self.cfg.decimation) + self._physics_handles_decimation = self.sim.backend_manager.handles_decimation() # Wire live plots into all active visualizers (Newton, Rerun, Viser) and create # Kit omni.ui ManagerLiveVisualizer widgets when a GUI window is present. @@ -555,8 +557,9 @@ def step(self, action: torch.Tensor) -> tuple[VecEnvObs, dict]: steps_per_call = self.cfg.decimation if self._physics_handles_decimation else 1 for _ in range(self.cfg.decimation // steps_per_call): self._sim_step_counter += steps_per_call - self.action_manager.apply_action() - self.scene.write_data_to_sim() + if not self._physics_handles_actions: + self.action_manager.apply_action() + self.scene.write_data_to_sim() self.sim.step(render=False) # render_enabled=False skips Kit (camera/GUI); standalone visualizers still update if self._sim_step_counter % self.cfg.sim.render_interval == 0 and is_rendering: diff --git a/source/isaaclab/isaaclab/envs/manager_based_rl_env.py b/source/isaaclab/isaaclab/envs/manager_based_rl_env.py index a7bbe2de7e1e..d8e3a82688fd 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_rl_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_rl_env.py @@ -157,9 +157,11 @@ def setup_manager_visualizers(self): } scalars = { "episode": { - "mean_reward": lambda: float(getattr(self, "reward_buf", None).mean()) - if getattr(self, "reward_buf", None) is not None - else 0.0, + "mean_reward": lambda: ( + float(getattr(self, "reward_buf", None).mean()) + if getattr(self, "reward_buf", None) is not None + else 0.0 + ), "episode_length": lambda: float(self.episode_length_buf.float().mean()), } } @@ -217,8 +219,9 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: steps_per_call = self.cfg.decimation if self._physics_handles_decimation else 1 for _ in range(self.cfg.decimation // steps_per_call): self._sim_step_counter += steps_per_call - self.action_manager.apply_action() - self.scene.write_data_to_sim() + if not self._physics_handles_actions: + self.action_manager.apply_action() + self.scene.write_data_to_sim() self.sim.step(render=False) self.recorder_manager.record_post_physics_decimation_step() # render_enabled=False skips Kit (camera/GUI); standalone visualizers still update diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py index d2f2db2e8d8d..cda3ee70a4d0 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py @@ -41,6 +41,10 @@ class BinaryJointAction(ActionTerm): add such constraints to the gripper. """ + supports_graph_capture = True + + apply_every_physics_step = False + cfg: actions_cfg.BinaryJointActionCfg """The configuration of the action term.""" _asset: Articulation @@ -136,12 +140,10 @@ def process_actions(self, actions: torch.Tensor): close_mask = ~actions else: close_mask = actions < 0 - # compute the command - self._processed_actions = torch.where(close_mask, self._close_command, self._open_command) + # compute the command in place: a recorded apply_actions reads this buffer + torch.where(close_mask, self._close_command, self._open_command, out=self._processed_actions) if self.cfg.clip is not None: - self._processed_actions = torch.clamp( - self._processed_actions, min=self._clip[:, :, 0], max=self._clip[:, :, 1] - ) + self._processed_actions.clamp_(min=self._clip[:, :, 0], max=self._clip[:, :, 1]) def reset(self, env_ids: Sequence[int] | None = None) -> None: index_fill_(self._raw_actions, env_ids, 0.0) @@ -189,12 +191,10 @@ def process_actions(self, actions: torch.Tensor): else: # true: close 0.0, false: open 0.785 binary_mask = actions < self.cfg.threshold - # compute the command - self._processed_actions = torch.where(binary_mask, self._open_command, self._close_command) + # compute the command in place: a recorded apply_actions reads this buffer + torch.where(binary_mask, self._open_command, self._close_command, out=self._processed_actions) if self.cfg.clip is not None: - self._processed_actions = torch.clamp( - self._processed_actions, min=self._clip[:, :, 0], max=self._clip[:, :, 1] - ) + self._processed_actions.clamp_(min=self._clip[:, :, 0], max=self._clip[:, :, 1]) def apply_actions(self): self._asset.set_joint_position_target_index(target=self._processed_actions, joint_ids=self._joint_ids) diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py index 63e86b0a3b70..2f58e6f7e26f 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py @@ -169,8 +169,8 @@ def IO_descriptor(self) -> GenericActionIODescriptor: def process_actions(self, actions: torch.Tensor): # store the raw actions self._raw_actions[:] = actions - # apply the affine transformations - self._processed_actions = self._raw_actions * self._scale + # apply the affine transformations in place: a recorded apply_actions reads this buffer + torch.mul(self._raw_actions, self._scale, out=self._processed_actions) self._processed_actions.add_(self._offset) # clip actions if self.cfg.clip is not None: @@ -183,6 +183,10 @@ def reset(self, env_ids: Sequence[int] | None = None) -> None: class JointPositionAction(JointAction): """Joint action term that applies the processed actions to the articulation's joints as position commands.""" + supports_graph_capture = True + + apply_every_physics_step = False + cfg: actions_cfg.JointPositionActionCfg """The configuration of the action term.""" @@ -234,6 +238,10 @@ def apply_actions(self): class JointVelocityAction(JointAction): """Joint action term that applies the processed actions to the articulation's joints as velocity commands.""" + supports_graph_capture = True + + apply_every_physics_step = False + cfg: actions_cfg.JointVelocityActionCfg """The configuration of the action term.""" @@ -252,6 +260,10 @@ def apply_actions(self): class JointEffortAction(JointAction): """Joint action term that applies the processed actions to the articulation's joints as effort commands.""" + supports_graph_capture = True + + apply_every_physics_step = False + cfg: actions_cfg.JointEffortActionCfg """The configuration of the action term.""" diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py index ec18160b56e3..25d7b6a1ac1a 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py @@ -41,6 +41,10 @@ class JointPositionToLimitsAction(ActionTerm): The processed actions are then sent as position commands to the articulation's joints. """ + supports_graph_capture = True + + apply_every_physics_step = False + cfg: actions_cfg.JointPositionToLimitsActionCfg """The configuration of the action term.""" _asset: Articulation @@ -154,12 +158,10 @@ def IO_descriptor(self) -> GenericActionIODescriptor: def process_actions(self, actions: torch.Tensor): # store the raw actions self._raw_actions[:] = actions - # apply affine transformations - self._processed_actions = self._raw_actions * self._scale + # apply affine transformations in place: a recorded apply_actions reads this buffer + torch.mul(self._raw_actions, self._scale, out=self._processed_actions) if self.cfg.clip is not None: - self._processed_actions = torch.clamp( - self._processed_actions, min=self._clip[:, :, 0], max=self._clip[:, :, 1] - ) + self._processed_actions.clamp_(min=self._clip[:, :, 0], max=self._clip[:, :, 1]) # rescale the position targets if configured # this is useful when the input actions are in the range [-1, 1] if self.cfg.rescale_to_limits: diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/surface_gripper_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/surface_gripper_actions.py index ea1a4c6f8e06..eb874cd4aa1f 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/surface_gripper_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/surface_gripper_actions.py @@ -42,6 +42,8 @@ class SurfaceGripperBinaryAction(ActionTerm): interface than joint-based grippers. """ + apply_every_physics_step = False + cfg: actions_cfg.SurfaceGripperBinaryActionCfg """The configuration of the action term.""" _asset: SurfaceGripper diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/tendon_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/tendon_actions.py index 2775a92dc3ee..0f7957a467fd 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/tendon_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/tendon_actions.py @@ -38,6 +38,8 @@ class FixedTendonPositionAction(ActionTerm): articulation decides how a tendon target reaches its solver, so this term is backend-neutral. """ + apply_every_physics_step = False + cfg: actions_cfg.FixedTendonPositionActionCfg """The configuration of the action term.""" _scale: torch.Tensor | float diff --git a/source/isaaclab/isaaclab/managers/action_manager.py b/source/isaaclab/isaaclab/managers/action_manager.py index 0a7bf089b8f3..dae22fba4b40 100644 --- a/source/isaaclab/isaaclab/managers/action_manager.py +++ b/source/isaaclab/isaaclab/managers/action_manager.py @@ -11,7 +11,7 @@ import re from abc import abstractmethod from collections.abc import Sequence -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, ClassVar import torch from prettytable import PrettyTable @@ -39,6 +39,18 @@ class ActionTerm(ManagerTermBase): responsible for applying the processed actions to the asset managed by the term. """ + supports_graph_capture: ClassVar[bool] = False + """Whether :meth:`apply_actions` launches only Warp work on fixed buffers, so it can be recorded into a CUDA graph. + + Terms that set it write their processed actions in place. + """ + + apply_every_physics_step: ClassVar[bool] = True + """Whether :meth:`apply_actions` must run before every physics step. + + Terms whose applied command depends only on the processed actions, not on the asset's state, set it to ``False``. + """ + def __init__(self, cfg: ActionTermCfg, env: ManagerBasedEnv): """Initialize the action term. @@ -274,6 +286,11 @@ def prev_action(self) -> torch.Tensor: """The previous actions sent to the environment. Shape is (num_envs, total_action_dim).""" return self._prev_action + @property + def apply_every_physics_step(self) -> bool: + """Whether any term must apply its actions before every physics step.""" + return any(term.apply_every_physics_step for term in self._terms.values()) + @property def has_debug_vis_implementation(self) -> bool: """Whether the command terms have debug visualization implemented.""" diff --git a/source/isaaclab/isaaclab/physics/physics_manager.py b/source/isaaclab/isaaclab/physics/physics_manager.py index 8a2db5aaef58..cf0e7d3c6cac 100644 --- a/source/isaaclab/isaaclab/physics/physics_manager.py +++ b/source/isaaclab/isaaclab/physics/physics_manager.py @@ -21,6 +21,8 @@ if TYPE_CHECKING: from ..cloner import ReplicateContext + from ..managers import ActionManager + from ..scene import InteractiveScene from ..scene_data import SceneDataBackend from ..sim.simulation_context import SimulationContext from .physics_manager_cfg import PhysicsCfg @@ -669,6 +671,20 @@ def handles_decimation(self) -> bool: """ return False + def bind_control(self, actions: ActionManager, scene: InteractiveScene) -> bool: + """Run the environment's actions and asset writes inside :meth:`step`, before every physics step. + + The default implementation binds nothing. + + Args: + actions: Environment action manager. + scene: Scene whose assets write to the simulation. + + Returns: + Whether :meth:`step` now applies the actions and writes the assets. + """ + return False + def get_backend(self) -> str: """Get the tensor backend being used ("numpy" or "torch").""" return "torch" if "cuda" in self._device else "numpy" diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index 2cb70929c1bb..6ce6a196a72b 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -15,6 +15,7 @@ if TYPE_CHECKING: from isaaclab_physx.assets import SurfaceGripper + from ..assets import AssetBase from ..terrains.terrain_importer import TerrainImporter import torch @@ -439,21 +440,26 @@ def reset(self, env_ids: Sequence[int] | None = None): for sensor in self._sensors.values(): sensor.reset(env_ids) + @property + def supports_graph_capture(self) -> bool: + """Whether :meth:`write_data_to_sim` can be recorded into a CUDA graph.""" + return all(asset.supports_graph_capture for asset in self._sim_writers()) + def write_data_to_sim(self): """Writes the data of the scene entities to the simulation.""" - # -- assets - for articulation in self._articulations.values(): - articulation.write_data_to_sim() - for cable_object in self._cable_objects.values(): - cable_object.write_data_to_sim() - for deformable_object in self._deformable_objects.values(): - deformable_object.write_data_to_sim() - for rigid_object in self._rigid_objects.values(): - rigid_object.write_data_to_sim() - for surface_gripper in self._surface_grippers.values(): - surface_gripper.write_data_to_sim() - for rigid_object_collection in self._rigid_object_collections.values(): - rigid_object_collection.write_data_to_sim() + for asset in self._sim_writers(): + asset.write_data_to_sim() + + def _sim_writers(self) -> tuple[AssetBase, ...]: + """Assets that write to the simulation, in write order.""" + return ( + *self._articulations.values(), + *self._cable_objects.values(), + *self._deformable_objects.values(), + *self._rigid_objects.values(), + *self._surface_grippers.values(), + *self._rigid_object_collections.values(), + ) def update(self, dt: float) -> None: """Update the scene entities. diff --git a/source/isaaclab/isaaclab/utils/wrench_composer.py b/source/isaaclab/isaaclab/utils/wrench_composer.py index b7963591c2e8..8b82b6976c8c 100644 --- a/source/isaaclab/isaaclab/utils/wrench_composer.py +++ b/source/isaaclab/isaaclab/utils/wrench_composer.py @@ -6,7 +6,7 @@ from __future__ import annotations import warnings -from collections.abc import Sequence +from collections.abc import Callable, Sequence from typing import TYPE_CHECKING import numpy as np @@ -67,6 +67,9 @@ def __init__( self._asset = asset self._active = False self._dirty = False + self._used = False + self.on_first_use: Callable[[], None] | None = None + """Called at the first write of forces or torques, e.g. to record the wrench work into a captured step.""" self._supports_world_at_com = supports_world_at_com # Conservative until a full reset; partial resets do not scan the remaining buffers. self._has_local_wrench = False @@ -115,6 +118,21 @@ def active(self) -> bool: """ return self._active + @property + def pending(self) -> bool: + """Whether a writer must apply the buffered wrench now. + + Outside graph capture this is :attr:`active`. While a CUDA graph is recorded on the composer's device, it is + whether forces or torques were ever written, and the recorded work no longer depends on host flags: every + replay adds, composes and clears the buffers whatever they hold. + """ + return self._recording or self._active + + @property + def _recording(self) -> bool: + """Whether a CUDA graph records this composer's work after its first write.""" + return self._used and wp.get_device(self.device).is_capturing + @property def global_force_w(self) -> wp.array: """Global force buffer [N] (world frame), dtype ``wp.vec3f``. Shape: ``(num_envs, num_bodies)``. @@ -456,7 +474,7 @@ def add_raw_buffers_from(self, other: WrenchComposer): Args: other: Another WrenchComposer whose input buffers will be added into this one. """ - if not other._active: + if not other._active and not self._recording: return if __debug__: if other.num_envs != self.num_envs or other.num_bodies != self.num_bodies: @@ -534,6 +552,9 @@ def get_forces_and_torques(self) -> tuple[wp.array, wp.array, bool]: ``(num_envs, num_bodies)`` with dtype ``wp.vec3f``. The arrays are owned by the composer and stay valid until the next mutating call. """ + if self._recording: + self.compose_to_body_frame() + return self._out_force_b, self._out_torque_b, False if not self._has_global_wrench: return self._local_force_b, self._local_torque_b, False if self._supports_world_at_com and not self._has_local_wrench and not self._has_global_positions: @@ -559,7 +580,7 @@ def reset( env_ids: Environment indices. Defaults to None (all environments). env_mask: Environment mask. Defaults to None (all environments). """ - if not self._active: + if not self._active and not self._recording: return full_reset = env_mask is None and (env_ids is None or (isinstance(env_ids, slice) and env_ids == slice(None))) if full_reset: @@ -654,6 +675,10 @@ def _prepare_write(self, forces, positions, is_global: bool) -> tuple[wp.array, """ self._active = True self._dirty = True + if not self._used: + self._used = True + if self.on_first_use is not None: + self.on_first_use() if is_global: self._has_global_wrench = True self._has_global_positions = self._has_global_positions or (forces is not None and positions is not None) diff --git a/source/isaaclab/test/envs/mdp/test_actions.py b/source/isaaclab/test/envs/mdp/test_actions.py index a92f54133a67..45b67577a642 100644 --- a/source/isaaclab/test/envs/mdp/test_actions.py +++ b/source/isaaclab/test/envs/mdp/test_actions.py @@ -15,9 +15,13 @@ AbsBinaryJointPositionActionCfg, BinaryJointPositionActionCfg, DifferentialInverseKinematicsActionCfg, + JointEffortActionCfg, + JointPositionToLimitsActionCfg, OperationalSpaceControllerActionCfg, ) from isaaclab.envs.mdp.actions.binary_joint_actions import AbsBinaryJointPositionAction, BinaryJointPositionAction +from isaaclab.envs.mdp.actions.joint_actions import JointEffortAction +from isaaclab.envs.mdp.actions.joint_actions_to_limits import JointPositionToLimitsAction from isaaclab.envs.mdp.actions.task_space_actions import ( DifferentialInverseKinematicsAction, OperationalSpaceControllerAction, @@ -33,7 +37,7 @@ class _JointIds: """Stand-in for the proxy returned by ``find_joints(..., as_proxy=True)``.""" def __init__(self, count: int): - self.warp = torch.arange(count, dtype=torch.int32) + self.warp = self.torch = torch.arange(count, dtype=torch.int32) def __len__(self) -> int: return len(self.warp) @@ -231,3 +235,27 @@ def test_osc_controller_limits_bound_clip() -> None: action._preprocess_actions(raw) torch.testing.assert_close(action.processed_actions[:, 6:12], torch.full((NUM_ENVS, 6), 500.0)) + + +@pytest.mark.parametrize( + "action_cls, cfg", + [ + ( + BinaryJointPositionAction, + BinaryJointPositionActionCfg(open_command_expr={".*": 1.0}, close_command_expr={".*": -1.0}), + ), + (JointEffortAction, JointEffortActionCfg(scale=2.0, clip={".*": (-1.0, 1.0)})), + (JointPositionToLimitsAction, JointPositionToLimitsActionCfg(scale=2.0, rescale_to_limits=False)), + ], +) +def test_recordable_joint_actions_process_into_the_same_buffer(action_cls, cfg) -> None: + """A step that records ``apply_actions`` reads the processed buffer, so processing writes it in place.""" + cfg.asset_name, cfg.joint_names = "robot", [".*"] + action = action_cls(cfg, _make_env(["a", "b"])) + assert action_cls.supports_graph_capture and not action_cls.apply_every_physics_step + processed = action.processed_actions + + action.process_actions(torch.full((2, action.action_dim), -0.25)) + + assert action.processed_actions is processed + assert torch.all(processed < 0.0) diff --git a/source/isaaclab/test/utils/test_wrench_composer.py b/source/isaaclab/test/utils/test_wrench_composer.py index 7ca8d22f8168..7e540a29e1d3 100644 --- a/source/isaaclab/test/utils/test_wrench_composer.py +++ b/source/isaaclab/test/utils/test_wrench_composer.py @@ -543,6 +543,44 @@ def write_and_compose(): ) +@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) +def test_recorded_wrench_work_applies_wrenches_written_after_capture(device): + """Once used, a recorded merge, composition and reset no longer depend on host flags, as in a captured step.""" + com, quat = _poses(quat={(0, 0): _HALF_TURN_Z}) + asset = SimpleNamespace( + num_instances=2, num_bodies=2, device=device, data=_AssetData(com.to(device), quat.to(device)) + ) + instantaneous, permanent = WrenchComposer(asset), WrenchComposer(asset) + first_uses = [] + for composer in (instantaneous, permanent): + composer.on_first_use = lambda composer=composer: first_uses.append(composer) + with wp.ScopedDevice(device): + local = wp.array([[[1.0, 0.0, 0.0]]], dtype=wp.vec3f) + instantaneous.add_forces_and_torques_index(local, env_ids=[0], body_ids=[0]) + instantaneous.reset() + permanent.add_forces_and_torques_index( + wp.array([[[0.0, 2.0, 0.0]]], dtype=wp.vec3f), env_ids=[0], body_ids=[0], is_global=True + ) + force = wp.zeros((2, 2), dtype=wp.vec3f) + assert not instantaneous.active and instantaneous.pending is False + + def write(): + if instantaneous.pending: + instantaneous.add_raw_buffers_from(permanent) + wp.copy(force, instantaneous.get_forces_and_torques()[0]) + instantaneous.reset() + + with wp.ScopedCapture(device=device) as capture: + write() + # A wrench written after the capture reaches the next replay, and the replay clears it. + instantaneous.add_forces_and_torques_index(local, env_ids=[0], body_ids=[0]) + wp.capture_launch(capture.graph) + _assert_vectors(force, _grid({(0, 0): (1.0, -2.0, 0.0)}).to(device)) + wp.capture_launch(capture.graph) + _assert_vectors(force, _grid({(0, 0): (0.0, -2.0, 0.0)}).to(device)) + assert first_uses == [instantaneous, permanent] + + @pytest.mark.parametrize( "name", [ diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst new file mode 100644 index 000000000000..32099529d427 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst @@ -0,0 +1,5 @@ +* Added :meth:`NewtonManager.bind_control `. When every action + term and written asset could be recorded, the environment's actions and asset writes ran as pre-actuator callbacks + before every physics step, and one step advanced the whole decimation loop. Hard resets bound them again. +* Added ``NewtonBackend.control_bound``, ``NewtonBackend.control_every_physics_step`` and the public + :meth:`NewtonBackend.stage_body_forces `. diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst new file mode 100644 index 000000000000..33c508256291 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst @@ -0,0 +1,5 @@ +* Changed :meth:`NewtonBackend.handles_decimation ` to keep + the decimation loop in the environment when Newton actuators run in the step but an action term must be applied + before every physics step and could not be bound. +* Changed Newton articulations, rigid objects and rigid object collections to record their wrench work into a + captured step only once a wrench composer was used, which captured the step again. diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.minor b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py index 5f1a1262fbeb..7de95443661e 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py @@ -386,6 +386,11 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None self._instantaneous_wrench_composer.reset(env_ids, env_mask) self._permanent_wrench_composer.reset(env_ids, env_mask) + @property + def supports_graph_capture(self) -> bool: + """Whether :meth:`write_data_to_sim` can be recorded: no actuator model runs in Torch and no fixed tendon.""" + return self.actuators.supports_graph_capture and self._fixed_tendon_control is None + def write_data_to_sim(self): """Write external wrenches and joint commands to the simulation. @@ -397,8 +402,8 @@ def write_data_to_sim(self): This ensures that the external wrench is applied at every simulation step. """ # write external wrench - if self._instantaneous_wrench_composer.active or self._permanent_wrench_composer.active: - if self._instantaneous_wrench_composer.active: + if self._instantaneous_wrench_composer.pending or self._permanent_wrench_composer.pending: + if self._instantaneous_wrench_composer.pending: composer = self._instantaneous_wrench_composer composer.add_raw_buffers_from(self._permanent_wrench_composer) else: @@ -438,7 +443,7 @@ def write_data_to_sim(self): self._ALL_BODY_MASK, ], ) - if self._instantaneous_wrench_composer.active: + if self._instantaneous_wrench_composer.pending: self._instantaneous_wrench_composer.reset() # Compute processed actuator commands (native path is a no-op here) and @@ -3300,6 +3305,9 @@ def _create_buffers(self): # external wrench composer self._instantaneous_wrench_composer = WrenchComposer(self) self._permanent_wrench_composer = WrenchComposer(self) + for composer in (self._instantaneous_wrench_composer, self._permanent_wrench_composer): + # a captured step records wrench work only once forces are written, so it is captured again then + composer.on_first_use = self._backend_manager.backend.invalidate_graph # asset named data self._resolve_and_install_ordering_maps() diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py index ffd509fe7691..d74b82c9c681 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py @@ -132,6 +132,8 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None self._instantaneous_wrench_composer.reset(env_ids) self._permanent_wrench_composer.reset(env_ids) + supports_graph_capture = True + def write_data_to_sim(self) -> None: """Write external wrench to the simulation. @@ -140,8 +142,8 @@ def write_data_to_sim(self) -> None: This ensures that the external wrench is applied at every simulation step. """ # write external wrench - if self._instantaneous_wrench_composer.active or self._permanent_wrench_composer.active: - if self._instantaneous_wrench_composer.active: + if self._instantaneous_wrench_composer.pending or self._permanent_wrench_composer.pending: + if self._instantaneous_wrench_composer.pending: composer = self._instantaneous_wrench_composer composer.add_raw_buffers_from(self._permanent_wrench_composer) else: @@ -1021,6 +1023,9 @@ def _create_buffers(self): # external wrench composer self._instantaneous_wrench_composer = WrenchComposer(self) self._permanent_wrench_composer = WrenchComposer(self) + for composer in (self._instantaneous_wrench_composer, self._permanent_wrench_composer): + # a captured step records wrench work only once forces are written, so it is captured again then + composer.on_first_use = self._backend_manager.backend.invalidate_graph # set information about rigid body into data self._data.body_names = self.body_names diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py index 8339c3a20f39..b1e00372bacf 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py @@ -178,6 +178,8 @@ def reset( self._instantaneous_wrench_composer.reset(env_ids) self._permanent_wrench_composer.reset(env_ids) + supports_graph_capture = True + def write_data_to_sim(self) -> None: """Write external wrench to the simulation. @@ -186,8 +188,8 @@ def write_data_to_sim(self) -> None: This ensures that the external wrench is applied at every simulation step. """ # write external wrench - if self._instantaneous_wrench_composer.active or self._permanent_wrench_composer.active: - if self._instantaneous_wrench_composer.active: + if self._instantaneous_wrench_composer.pending or self._permanent_wrench_composer.pending: + if self._instantaneous_wrench_composer.pending: composer = self._instantaneous_wrench_composer composer.add_raw_buffers_from(self._permanent_wrench_composer) else: @@ -1199,6 +1201,9 @@ def _create_buffers(self): # external wrench composer self._instantaneous_wrench_composer = WrenchComposer(self) self._permanent_wrench_composer = WrenchComposer(self) + for composer in (self._instantaneous_wrench_composer, self._permanent_wrench_composer): + # a captured step records wrench work only once forces are written, so it is captured again then + composer.on_first_use = self._backend_manager.backend.invalidate_graph # Temporary 2D wrench buffer for write_data_to_sim self._wrench_buffer = wp.zeros( diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index 5dc20539612e..464480631b95 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -210,6 +210,10 @@ def __init__(self, cfg: NewtonBackendCfg, builder: ModelBuilder | None = None, * """Newton actuators run inside the step, or ``None``.""" self.actuators_active = False """Whether an articulation runs its Newton actuators in the step (:meth:`activate_actuators`).""" + self.control_bound = False + """Whether the environment's actions and asset writes run as pre-actuator callbacks of every physics step.""" + self.control_every_physics_step = False + """Whether the environment applies an action that must run before every physics step.""" self.pre_actuator_callbacks: list[Callable[[], None]] = [] """Run before the Newton actuators of every physics step.""" self.post_actuator_callbacks: list[Callable[[], None]] = [] @@ -461,8 +465,12 @@ def add_imu_sensor(self, sites: list[int]) -> SensorIMU: return sensor def handles_decimation(self) -> bool: - """Whether one :meth:`step` runs the whole decimation loop: once an articulation runs Newton actuators in it.""" - return self.actuators_active + """Whether one :meth:`step` runs the whole decimation loop. + + It does once the environment's control runs in the step (:attr:`control_bound`), or once an articulation runs + Newton actuators in it and the environment's actions hold for the whole environment step. + """ + return self.control_bound or (self.actuators_active and not self.control_every_physics_step) def set_decimation(self, decimation: int) -> None: """Set the physics steps per environment step.""" @@ -494,7 +502,7 @@ def step(self) -> bool: else: if self.device.is_capturing: raise RuntimeError("Newton actuators that cannot be captured prevent recording the step.") - self._stage_body_forces() + self.stage_body_forces() for i in range(steps): self._launch("before_actuators", self._before_actuators) actuators.step(self.state_0, self.control, self.dt) @@ -606,7 +614,7 @@ def _launch(self, key: str | tuple[str, int], fn: Callable[[], None]) -> None: def _simulate(self, steps: int) -> None: """Run ``steps`` physics steps with the Newton actuators, then finish the step.""" actuators = self.actuators - self._stage_body_forces() + self.stage_body_forces() for i in range(steps): self._before_actuators() if actuators is not None: @@ -637,8 +645,11 @@ def _finish_step(self) -> None: callback() self._update_sensors() - def _stage_body_forces(self) -> None: - """Copy the body forces written to ``state_0`` before the step, so that every solver substep applies them.""" + def stage_body_forces(self) -> None: + """Copy the body forces written to ``state_0``, so that every following solver substep applies them. + + The step stages the forces written before it; pre-actuator callbacks that write body forces stage them again. + """ if self.staged_body_f is not None: wp.copy(self.staged_body_f, self.state_0.body_f) diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index 7699ee1ee665..d9d009d08439 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -42,7 +42,9 @@ if TYPE_CHECKING: from isaaclab.assets import BaseArticulation + from isaaclab.managers import ActionManager from isaaclab.renderers.base_renderer import VisualMaterialBatch + from isaaclab.scene import InteractiveScene logger = logging.getLogger(__name__) @@ -231,6 +233,7 @@ def clear(self): """Clear all Newton-specific state (callbacks cleared by super().close()).""" self._close_backend(dispatch_stop=False) self._decimation = 1 + self._control: tuple[ActionManager, InteractiveScene] | None = None # Site requests and replication outputs survive hard resets. # (body_pattern, per_world, xform floats) -> (label, transform) self._site_requests: dict[tuple[str | None, bool, tuple[float, ...]], tuple[str, wp.transform]] = {} @@ -490,6 +493,8 @@ def initialize_solver(self) -> None: device=self.get_device(), ): backend.init_solver(None if plan is None else plan.env_template, relaxed_capture=self._relaxed_capture) + if self._control is not None: + self._bind_control() self._mark_transforms_changed() def _relaxed_capture(self) -> bool: @@ -584,7 +589,7 @@ def unregister_post_step_callback(self, callback: Callable[[], None]) -> None: def set_decimation(self, decimation: int) -> None: """Set the decimation count; see :meth:`NewtonBackend.set_decimation`. - Once Newton actuators run in the step, one :meth:`step` advances the whole decimation loop. + :meth:`handles_decimation` tells whether one :meth:`step` advances the whole decimation loop. """ self._decimation = max(1, decimation) if self.backend is not None: @@ -594,6 +599,39 @@ def handles_decimation(self) -> bool: """Whether :meth:`step` executes the full decimation loop; see :meth:`NewtonBackend.handles_decimation`.""" return self.backend.handles_decimation() + def bind_control(self, actions: ActionManager, scene: InteractiveScene) -> bool: + """Run the environment's actions and asset writes as pre-actuator callbacks of every physics step. + + They are bound when every action term and every written asset can be recorded into the captured step + (``supports_graph_capture``); one :meth:`step` then advances the whole decimation loop. Hard resets bind them + again on the new backend. + + Args: + actions: Environment action manager. + scene: Scene whose assets write to the simulation. + + Returns: + Whether the step now applies the actions and writes the assets. + """ + self._control = (actions, scene) + self._bind_control() + return self.backend.control_bound + + def _bind_control(self) -> None: + """Register the bound control on the current backend, in the environment's order.""" + actions, scene = self._control + backend = self.backend + terms = [actions.get_term(name) for name in actions.active_terms] + backend.control_every_physics_step = actions.apply_every_physics_step + if not all(term.supports_graph_capture for term in terms) or not scene.supports_graph_capture: + return + for term in terms: + self.register_pre_actuator_callback(term.apply_actions) + self.register_pre_actuator_callback(scene.write_data_to_sim) + # Asset writes replace the body forces staged before the step. + self.register_pre_actuator_callback(backend.stage_body_forces) + backend.control_bound = True + def add_contact_sensor( self, body_names_expr: str | list[str] | None = None, diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index a2b99c3e678d..bdffa8808e27 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -282,6 +282,8 @@ def check_step(self, captured, debug): solver_dt=0.002 / num_substeps, actuators=None, actuators_active=False, + control_bound=False, + control_every_physics_step=False, contact_sensors={}, imu_sensors=[], world_mask=wp.zeros(2, dtype=wp.bool, device=device), @@ -930,3 +932,61 @@ def test_stateful_actuators_replay_like_eager_steps_across_decimation_changes(mo ) trajectories.append(np.asarray(samples)) np.testing.assert_allclose(trajectories[1], trajectories[0], atol=1e-6, rtol=1e-5) + + +@wp.kernel +def _damp_body(body_qd: wp.array(dtype=wp.spatial_vector), body_f: wp.array(dtype=wp.spatial_vector)): + # a state-dependent command: it changes between the physics steps of one environment step + body_f[0] = wp.spatial_vector(0.0, 0.0, -20.0 * body_qd[0][2], 0.0, 0.0, 0.0) + + +def _bound_control(manager: NewtonManager, *, graphable: bool): + """An action term that damps a free body and a scene, both bound to ``manager``'s step when ``graphable``.""" + applied = [] + term = SimpleNamespace( + supports_graph_capture=graphable, + apply_actions=lambda: ( + applied.append(None), + wp.launch(_damp_body, 1, inputs=[manager.backend.state_0.body_qd, manager.backend.state_0.body_f]), + ), + ) + actions = SimpleNamespace(active_terms=["damp"], get_term=lambda _: term, apply_every_physics_step=True) + scene = SimpleNamespace(supports_graph_capture=True, write_data_to_sim=lambda: None) + return actions, scene, applied + + +def test_bound_control_runs_before_every_physics_step_like_the_environment_loop(): + """Bound actions run before every physics step of one captured step, also after a hard reset. + + Actions that cannot be recorded and must run every physics step keep the loop in the environment, which the bound + step matches. + """ + decimation, num_steps, velocities = 3, 4, [] + for bound in (True, False): + sim_cfg = SimulationCfg(dt=0.01, device="cuda:0", physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())) + with build_simulation_context(sim_cfg=sim_cfg) as sim: + builder = sim.get_or_create_backend(NewtonBuilderCfg(physics_cfg=sim.cfg.physics)) + builder.add_body(mass=1.0) + sim.reset() + manager = sim.backend_manager + manager.activate_newton_actuator_path() + manager.set_decimation(decimation) + actions, scene, applied = _bound_control(manager, graphable=bound) + assert manager.bind_control(actions, scene) is bound + assert manager.handles_decimation() is bound + for reset in (False, True): + if reset: + sim.reset() + assert manager.backend.control_bound is bound + applied.clear() + for _ in range(num_steps): + for _ in range(1 if bound else decimation): + if not bound: + actions.get_term("damp").apply_actions() + sim.step(render=False) + # bound steps record the actions once per physics step and then replay them + assert len(applied) == (2 * decimation if bound else num_steps * decimation) + velocities.append(manager.backend.state_0.body_qd.numpy().copy()) + np.testing.assert_allclose(velocities[:2], velocities[2:], rtol=1e-5, atol=1e-6) + # damping holds the body well below free-fall speed + assert velocities[0][0, 2] > -0.5 * 9.81 * num_steps * decimation * 0.01 From 1e3e57a55047bacc6488a94c3539bf0990583058 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Tue, 3 Nov 2026 21:14:46 -0800 Subject: [PATCH 02/21] Restore the unrelated reward lambda formatting --- source/isaaclab/isaaclab/envs/manager_based_rl_env.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/source/isaaclab/isaaclab/envs/manager_based_rl_env.py b/source/isaaclab/isaaclab/envs/manager_based_rl_env.py index d8e3a82688fd..2150eb903531 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_rl_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_rl_env.py @@ -157,11 +157,9 @@ def setup_manager_visualizers(self): } scalars = { "episode": { - "mean_reward": lambda: ( - float(getattr(self, "reward_buf", None).mean()) - if getattr(self, "reward_buf", None) is not None - else 0.0 - ), + "mean_reward": lambda: float(getattr(self, "reward_buf", None).mean()) + if getattr(self, "reward_buf", None) is not None + else 0.0, "episode_length": lambda: float(self.episode_length_buf.float().mean()), } } From e5a9b1534a976d083eea4b89c1171621a32f0f78 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 6 Nov 2026 11:46:52 -0800 Subject: [PATCH 03/21] Pass the wrench composer's first-use hook at construction --- .../isaaclab/isaaclab/utils/wrench_composer.py | 18 +++++++++--------- .../test/utils/test_wrench_composer.py | 7 +++---- .../assets/articulation/articulation.py | 11 +++++------ .../assets/rigid_object/rigid_object.py | 13 ++++++------- .../rigid_object_collection.py | 13 ++++++------- 5 files changed, 29 insertions(+), 33 deletions(-) diff --git a/source/isaaclab/isaaclab/utils/wrench_composer.py b/source/isaaclab/isaaclab/utils/wrench_composer.py index 8b82b6976c8c..6d5150ca2973 100644 --- a/source/isaaclab/isaaclab/utils/wrench_composer.py +++ b/source/isaaclab/isaaclab/utils/wrench_composer.py @@ -32,6 +32,7 @@ def __init__( asset: BaseArticulation | BaseRigidObject | BaseRigidObjectCollection, *, supports_world_at_com: bool = False, + on_first_use: Callable[[], None] | None = None, ) -> None: """Wrench composer with dual-buffer architecture. @@ -60,6 +61,8 @@ def __init__( supports_world_at_com: Whether the consumer can apply a world-frame wrench at the body's center of mass. When False, :meth:`get_forces_and_torques` always returns a body-frame wrench. Defaults to False. + on_first_use: Called at the first write of forces or torques, e.g. to capture the step again with the + wrench work. Defaults to None. """ self.num_envs = asset.num_instances self.num_bodies = asset.num_bodies @@ -68,8 +71,7 @@ def __init__( self._active = False self._dirty = False self._used = False - self.on_first_use: Callable[[], None] | None = None - """Called at the first write of forces or torques, e.g. to record the wrench work into a captured step.""" + self._on_first_use = on_first_use self._supports_world_at_com = supports_world_at_com # Conservative until a full reset; partial resets do not scan the remaining buffers. self._has_local_wrench = False @@ -120,17 +122,15 @@ def active(self) -> bool: @property def pending(self) -> bool: - """Whether a writer must apply the buffered wrench now. + """Whether a writer must apply the wrench now: :attr:`active`, or always while recording after first use. - Outside graph capture this is :attr:`active`. While a CUDA graph is recorded on the composer's device, it is - whether forces or torques were ever written, and the recorded work no longer depends on host flags: every - replay adds, composes and clears the buffers whatever they hold. + Recorded wrench work does not depend on host flags; every replay adds, composes and clears the buffers. """ return self._recording or self._active @property def _recording(self) -> bool: - """Whether a CUDA graph records this composer's work after its first write.""" + """Whether a CUDA graph is recording this composer's work after its first write.""" return self._used and wp.get_device(self.device).is_capturing @property @@ -677,8 +677,8 @@ def _prepare_write(self, forces, positions, is_global: bool) -> tuple[wp.array, self._dirty = True if not self._used: self._used = True - if self.on_first_use is not None: - self.on_first_use() + if self._on_first_use is not None: + self._on_first_use() if is_global: self._has_global_wrench = True self._has_global_positions = self._has_global_positions or (forces is not None and positions is not None) diff --git a/source/isaaclab/test/utils/test_wrench_composer.py b/source/isaaclab/test/utils/test_wrench_composer.py index 7e540a29e1d3..1a0abb0fe743 100644 --- a/source/isaaclab/test/utils/test_wrench_composer.py +++ b/source/isaaclab/test/utils/test_wrench_composer.py @@ -550,10 +550,9 @@ def test_recorded_wrench_work_applies_wrenches_written_after_capture(device): asset = SimpleNamespace( num_instances=2, num_bodies=2, device=device, data=_AssetData(com.to(device), quat.to(device)) ) - instantaneous, permanent = WrenchComposer(asset), WrenchComposer(asset) first_uses = [] - for composer in (instantaneous, permanent): - composer.on_first_use = lambda composer=composer: first_uses.append(composer) + instantaneous = WrenchComposer(asset, on_first_use=lambda: first_uses.append("instantaneous")) + permanent = WrenchComposer(asset, on_first_use=lambda: first_uses.append("permanent")) with wp.ScopedDevice(device): local = wp.array([[[1.0, 0.0, 0.0]]], dtype=wp.vec3f) instantaneous.add_forces_and_torques_index(local, env_ids=[0], body_ids=[0]) @@ -578,7 +577,7 @@ def write(): _assert_vectors(force, _grid({(0, 0): (1.0, -2.0, 0.0)}).to(device)) wp.capture_launch(capture.graph) _assert_vectors(force, _grid({(0, 0): (0.0, -2.0, 0.0)}).to(device)) - assert first_uses == [instantaneous, permanent] + assert first_uses == ["instantaneous", "permanent"] @pytest.mark.parametrize( diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py index 7de95443661e..5942c3d75b58 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py @@ -388,7 +388,7 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None @property def supports_graph_capture(self) -> bool: - """Whether :meth:`write_data_to_sim` can be recorded: no actuator model runs in Torch and no fixed tendon.""" + """Whether :meth:`write_data_to_sim` can be recorded: no Torch actuators and no fixed tendons.""" return self.actuators.supports_graph_capture and self._fixed_tendon_control is None def write_data_to_sim(self): @@ -3303,11 +3303,10 @@ def _create_buffers(self): self._num_shapes_per_body_backend: list[int] | None = None # external wrench composer - self._instantaneous_wrench_composer = WrenchComposer(self) - self._permanent_wrench_composer = WrenchComposer(self) - for composer in (self._instantaneous_wrench_composer, self._permanent_wrench_composer): - # a captured step records wrench work only once forces are written, so it is captured again then - composer.on_first_use = self._backend_manager.backend.invalidate_graph + # a captured step records wrench work only once forces are written, so it is captured again then + invalidate_graph = self._backend_manager.backend.invalidate_graph + self._instantaneous_wrench_composer = WrenchComposer(self, on_first_use=invalidate_graph) + self._permanent_wrench_composer = WrenchComposer(self, on_first_use=invalidate_graph) # asset named data self._resolve_and_install_ordering_maps() diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py index d74b82c9c681..d2c3e5ec1441 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py @@ -51,6 +51,8 @@ class RigidObject(BaseRigidObject): __backend_name__: str = "newton" """The name of the backend for the rigid object.""" + supports_graph_capture = True + def __init__(self, cfg: RigidObjectCfg): """Initialize the rigid object. @@ -132,8 +134,6 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None self._instantaneous_wrench_composer.reset(env_ids) self._permanent_wrench_composer.reset(env_ids) - supports_graph_capture = True - def write_data_to_sim(self) -> None: """Write external wrench to the simulation. @@ -1021,11 +1021,10 @@ def _create_buffers(self): self._ALL_BODY_MASK = wp.ones((self.num_bodies,), dtype=wp.bool, device=self.device) # external wrench composer - self._instantaneous_wrench_composer = WrenchComposer(self) - self._permanent_wrench_composer = WrenchComposer(self) - for composer in (self._instantaneous_wrench_composer, self._permanent_wrench_composer): - # a captured step records wrench work only once forces are written, so it is captured again then - composer.on_first_use = self._backend_manager.backend.invalidate_graph + # a captured step records wrench work only once forces are written, so it is captured again then + invalidate_graph = self._backend_manager.backend.invalidate_graph + self._instantaneous_wrench_composer = WrenchComposer(self, on_first_use=invalidate_graph) + self._permanent_wrench_composer = WrenchComposer(self, on_first_use=invalidate_graph) # set information about rigid body into data self._data.body_names = self.body_names diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py index b1e00372bacf..2383ac320350 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py @@ -60,6 +60,8 @@ class RigidObjectCollection(BaseRigidObjectCollection): __backend_name__: str = "newton" """The name of the backend for the rigid object.""" + supports_graph_capture = True + def __init__(self, cfg: RigidObjectCollectionCfg): """Initialize the rigid object collection. @@ -178,8 +180,6 @@ def reset( self._instantaneous_wrench_composer.reset(env_ids) self._permanent_wrench_composer.reset(env_ids) - supports_graph_capture = True - def write_data_to_sim(self) -> None: """Write external wrench to the simulation. @@ -1199,11 +1199,10 @@ def _create_buffers(self): self._index_body_mask = wp.zeros((self.num_bodies,), dtype=wp.bool, device=self.device) # external wrench composer - self._instantaneous_wrench_composer = WrenchComposer(self) - self._permanent_wrench_composer = WrenchComposer(self) - for composer in (self._instantaneous_wrench_composer, self._permanent_wrench_composer): - # a captured step records wrench work only once forces are written, so it is captured again then - composer.on_first_use = self._backend_manager.backend.invalidate_graph + # a captured step records wrench work only once forces are written, so it is captured again then + invalidate_graph = self._backend_manager.backend.invalidate_graph + self._instantaneous_wrench_composer = WrenchComposer(self, on_first_use=invalidate_graph) + self._permanent_wrench_composer = WrenchComposer(self, on_first_use=invalidate_graph) # Temporary 2D wrench buffer for write_data_to_sim self._wrench_buffer = wp.zeros( From 12d4f64c3a82c620c56abf60ef5b188054e41d06 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 6 Nov 2026 11:46:53 -0800 Subject: [PATCH 04/21] Declare graph capture support on every manager term and trim comments --- .../developer-tools/extending_newton_solvers.rst | 9 ++++----- .../newton-redesign-3-env-control.added.rst | 14 +++++++------- .../isaaclab/actuators/actuator_collection.py | 2 +- source/isaaclab/isaaclab/assets/asset_base.py | 2 +- .../isaaclab/isaaclab/envs/manager_based_env.py | 3 +-- .../isaaclab/isaaclab/managers/action_manager.py | 16 ++++++---------- .../isaaclab/isaaclab/managers/manager_base.py | 5 ++++- .../isaaclab_newton/physics/newton_backend.py | 11 ++--------- .../isaaclab_newton/physics/newton_manager.py | 11 ++++------- .../test/physics/test_newton_manager.py | 16 ++++++---------- 10 files changed, 36 insertions(+), 53 deletions(-) diff --git a/docs/source/developer-tools/extending_newton_solvers.rst b/docs/source/developer-tools/extending_newton_solvers.rst index 84930fe75d52..df4569ec665a 100644 --- a/docs/source/developer-tools/extending_newton_solvers.rst +++ b/docs/source/developer-tools/extending_newton_solvers.rst @@ -133,11 +133,10 @@ substeps``, and post-step callbacks and sensors run once at the end. Every substep runs ``staged body forces -> state-force callbacks -> step``, and ``pre_step`` and ``post_step`` run around each physics step's substeps. -:meth:`~isaaclab_newton.physics.NewtonManager.bind_control` binds the environment's control: each action term's -``apply_actions`` and the scene's ``write_data_to_sim`` become pre-actuator callbacks, followed by -:meth:`~isaaclab_newton.physics.NewtonBackend.stage_body_forces`, so they run before every physics step as in the -environment's own loop. It binds only when every action term and written asset sets ``supports_graph_capture``. -Wrench composers record their work once forces are first written, which captures the step again. +:meth:`~isaaclab_newton.physics.NewtonManager.bind_control` makes the action manager's ``apply_action``, the scene's +``write_data_to_sim`` and :meth:`~isaaclab_newton.physics.NewtonBackend.stage_body_forces` pre-actuator callbacks, so +they run before every physics step as in the environment's own loop. It binds only when both report +``supports_graph_capture``. The first wrench written to an asset captures the step again with the wrench work. Every physics step ends in ``state_0``, so ``manager.backend.state_0`` is always the same object. The captured step records the callbacks, so they must be graph-safe. Consumers register them with diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index 6cd22e28de5e..52728b159e53 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,11 +1,11 @@ * Added :meth:`PhysicsManager.bind_control `, which let a physics backend run the environment's actions and asset writes inside its step. :class:`~isaaclab.envs.ManagerBasedEnv` called it after loading its managers and skipped the actions and asset writes that the step ran. -* Added ``supports_graph_capture`` and ``apply_every_physics_step`` to - :class:`~isaaclab.managers.ActionTerm`, ``supports_graph_capture`` to :class:`~isaaclab.assets.AssetBase`, +* Added ``supports_graph_capture`` to :class:`~isaaclab.managers.ManagerTermBase`, + :class:`~isaaclab.managers.ActionManager`, :class:`~isaaclab.assets.AssetBase`, :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`, and - ``apply_every_physics_step`` to :class:`~isaaclab.managers.ActionManager`. Joint, joint-to-limits and binary joint - action terms set them. -* Added :attr:`WrenchComposer.pending ` and - ``WrenchComposer.on_first_use``. Once forces were written, wrench work recorded into a CUDA graph no longer - depended on host flags. + ``apply_every_physics_step`` to :class:`~isaaclab.managers.ActionTerm` and :class:`~isaaclab.managers.ActionManager`. + Joint, joint-to-limits and binary joint action terms set them. +* Added :attr:`WrenchComposer.pending ` and the + ``on_first_use`` argument of :class:`~isaaclab.utils.wrench_composer.WrenchComposer`. Once forces were written, + wrench work recorded into a CUDA graph no longer depended on host flags. diff --git a/source/isaaclab/isaaclab/actuators/actuator_collection.py b/source/isaaclab/isaaclab/actuators/actuator_collection.py index 762ab85e1b92..7d5de92963e8 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_collection.py +++ b/source/isaaclab/isaaclab/actuators/actuator_collection.py @@ -162,7 +162,7 @@ def device(self) -> str: @property def supports_graph_capture(self) -> bool: - """Whether :meth:`compute` launches only Warp work, i.e. no Isaac Lab actuator model runs in Torch.""" + """Whether :meth:`compute` can be recorded into a CUDA graph: no Isaac Lab actuator model runs in Torch.""" return not self._execution_actuators @property diff --git a/source/isaaclab/isaaclab/assets/asset_base.py b/source/isaaclab/isaaclab/assets/asset_base.py index 5c04cfb3b8ea..1f95827e30b4 100644 --- a/source/isaaclab/isaaclab/assets/asset_base.py +++ b/source/isaaclab/isaaclab/assets/asset_base.py @@ -79,7 +79,7 @@ class AssetBase(Asset, ABC): """Class-level default for shape validation. Overridden per-instance in ``__init__``.""" supports_graph_capture: bool = False - """Whether :meth:`write_data_to_sim` launches only Warp work whose recording does not depend on host state.""" + """Whether :meth:`write_data_to_sim` can be recorded into a CUDA graph.""" def __init__(self, cfg: AssetBaseCfg): """Initialize the asset base. diff --git a/source/isaaclab/isaaclab/envs/manager_based_env.py b/source/isaaclab/isaaclab/envs/manager_based_env.py index 995509ef2666..7a5f797548f0 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env.py @@ -207,8 +207,7 @@ def _init_sim(self): report_activity("Setting up managers") self.load_managers() report_activity(None) - # let the physics backend run the actions and asset writes inside its step, and fold the full loop - # into a single step() when possible + # let the physics backend run the actions, asset writes and decimation loop inside its step when it can self._physics_handles_actions = self.sim.backend_manager.bind_control(self.action_manager, self.scene) self.sim.backend_manager.set_decimation(self.cfg.decimation) self._physics_handles_decimation = self.sim.backend_manager.handles_decimation() diff --git a/source/isaaclab/isaaclab/managers/action_manager.py b/source/isaaclab/isaaclab/managers/action_manager.py index dae22fba4b40..e79c7fa7de27 100644 --- a/source/isaaclab/isaaclab/managers/action_manager.py +++ b/source/isaaclab/isaaclab/managers/action_manager.py @@ -39,17 +39,8 @@ class ActionTerm(ManagerTermBase): responsible for applying the processed actions to the asset managed by the term. """ - supports_graph_capture: ClassVar[bool] = False - """Whether :meth:`apply_actions` launches only Warp work on fixed buffers, so it can be recorded into a CUDA graph. - - Terms that set it write their processed actions in place. - """ - apply_every_physics_step: ClassVar[bool] = True - """Whether :meth:`apply_actions` must run before every physics step. - - Terms whose applied command depends only on the processed actions, not on the asset's state, set it to ``False``. - """ + """Whether :meth:`apply_actions` must run before every physics step because its command depends on asset state.""" def __init__(self, cfg: ActionTermCfg, env: ManagerBasedEnv): """Initialize the action term. @@ -286,6 +277,11 @@ def prev_action(self) -> torch.Tensor: """The previous actions sent to the environment. Shape is (num_envs, total_action_dim).""" return self._prev_action + @property + def supports_graph_capture(self) -> bool: + """Whether :meth:`apply_action` can be recorded into a CUDA graph.""" + return all(term.supports_graph_capture for term in self._terms.values()) + @property def apply_every_physics_step(self) -> bool: """Whether any term must apply its actions before every physics step.""" diff --git a/source/isaaclab/isaaclab/managers/manager_base.py b/source/isaaclab/isaaclab/managers/manager_base.py index dd0ebb0f437b..c0b9d3f79bfb 100644 --- a/source/isaaclab/isaaclab/managers/manager_base.py +++ b/source/isaaclab/isaaclab/managers/manager_base.py @@ -11,7 +11,7 @@ from abc import ABC, abstractmethod from collections.abc import Callable, Sequence from dataclasses import fields -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, ClassVar from ..physics import PhysicsEvent, PhysicsManager from ..utils import string as string_utils @@ -54,6 +54,9 @@ class MyManagerCfg: """ + supports_graph_capture: ClassVar[bool] = False + """Whether the term launches only Warp work on fixed buffers, so it can be recorded into a CUDA graph.""" + def __init__(self, cfg: ManagerTermBaseCfg, env: ManagerBasedEnv): """Initialize the manager term. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index 464480631b95..c205ac029ee3 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -465,11 +465,7 @@ def add_imu_sensor(self, sites: list[int]) -> SensorIMU: return sensor def handles_decimation(self) -> bool: - """Whether one :meth:`step` runs the whole decimation loop. - - It does once the environment's control runs in the step (:attr:`control_bound`), or once an articulation runs - Newton actuators in it and the environment's actions hold for the whole environment step. - """ + """Whether one :meth:`step` runs the whole decimation loop: bound control, or actuators with held actions.""" return self.control_bound or (self.actuators_active and not self.control_every_physics_step) def set_decimation(self, decimation: int) -> None: @@ -646,10 +642,7 @@ def _finish_step(self) -> None: self._update_sensors() def stage_body_forces(self) -> None: - """Copy the body forces written to ``state_0``, so that every following solver substep applies them. - - The step stages the forces written before it; pre-actuator callbacks that write body forces stage them again. - """ + """Copy the body forces written to ``state_0``, so that every following solver substep applies them.""" if self.staged_body_f is not None: wp.copy(self.staged_body_f, self.state_0.body_f) diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index d9d009d08439..b1e5eca32f30 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -602,9 +602,8 @@ def handles_decimation(self) -> bool: def bind_control(self, actions: ActionManager, scene: InteractiveScene) -> bool: """Run the environment's actions and asset writes as pre-actuator callbacks of every physics step. - They are bound when every action term and every written asset can be recorded into the captured step - (``supports_graph_capture``); one :meth:`step` then advances the whole decimation loop. Hard resets bind them - again on the new backend. + Binds only when both support graph capture; one :meth:`step` then advances the whole decimation loop. Hard + resets bind again on the new backend. Args: actions: Environment action manager. @@ -621,12 +620,10 @@ def _bind_control(self) -> None: """Register the bound control on the current backend, in the environment's order.""" actions, scene = self._control backend = self.backend - terms = [actions.get_term(name) for name in actions.active_terms] backend.control_every_physics_step = actions.apply_every_physics_step - if not all(term.supports_graph_capture for term in terms) or not scene.supports_graph_capture: + if not (actions.supports_graph_capture and scene.supports_graph_capture): return - for term in terms: - self.register_pre_actuator_callback(term.apply_actions) + self.register_pre_actuator_callback(actions.apply_action) self.register_pre_actuator_callback(scene.write_data_to_sim) # Asset writes replace the body forces staged before the step. self.register_pre_actuator_callback(backend.stage_body_forces) diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index bdffa8808e27..29eb59a98619 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -941,26 +941,22 @@ def _damp_body(body_qd: wp.array(dtype=wp.spatial_vector), body_f: wp.array(dtyp def _bound_control(manager: NewtonManager, *, graphable: bool): - """An action term that damps a free body and a scene, both bound to ``manager``'s step when ``graphable``.""" + """Actions that damp a free body, and an empty scene; both support graph capture when ``graphable``.""" applied = [] - term = SimpleNamespace( + actions = SimpleNamespace( supports_graph_capture=graphable, - apply_actions=lambda: ( + apply_every_physics_step=True, + apply_action=lambda: ( applied.append(None), wp.launch(_damp_body, 1, inputs=[manager.backend.state_0.body_qd, manager.backend.state_0.body_f]), ), ) - actions = SimpleNamespace(active_terms=["damp"], get_term=lambda _: term, apply_every_physics_step=True) scene = SimpleNamespace(supports_graph_capture=True, write_data_to_sim=lambda: None) return actions, scene, applied def test_bound_control_runs_before_every_physics_step_like_the_environment_loop(): - """Bound actions run before every physics step of one captured step, also after a hard reset. - - Actions that cannot be recorded and must run every physics step keep the loop in the environment, which the bound - step matches. - """ + """Bound actions run before every physics step of one captured step, also after a hard reset, like the env loop.""" decimation, num_steps, velocities = 3, 4, [] for bound in (True, False): sim_cfg = SimulationCfg(dt=0.01, device="cuda:0", physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())) @@ -982,7 +978,7 @@ def test_bound_control_runs_before_every_physics_step_like_the_environment_loop( for _ in range(num_steps): for _ in range(1 if bound else decimation): if not bound: - actions.get_term("damp").apply_actions() + actions.apply_action() sim.step(render=False) # bound steps record the actions once per physics step and then replay them assert len(applied) == (2 * decimation if bound else num_steps * decimation) From fdb7f39346c43f2febd6fbdb6be8b3009c2966b4 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 6 Nov 2026 14:16:25 -0800 Subject: [PATCH 05/21] Keep supports_graph_capture on action terms only --- .../changelog.d/newton-redesign-3-env-control.added.rst | 2 +- source/isaaclab/isaaclab/managers/action_manager.py | 3 +++ source/isaaclab/isaaclab/managers/manager_base.py | 5 +---- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index 52728b159e53..af9c9ddd8404 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,7 +1,7 @@ * Added :meth:`PhysicsManager.bind_control `, which let a physics backend run the environment's actions and asset writes inside its step. :class:`~isaaclab.envs.ManagerBasedEnv` called it after loading its managers and skipped the actions and asset writes that the step ran. -* Added ``supports_graph_capture`` to :class:`~isaaclab.managers.ManagerTermBase`, +* Added ``supports_graph_capture`` to :class:`~isaaclab.managers.ActionTerm`, :class:`~isaaclab.managers.ActionManager`, :class:`~isaaclab.assets.AssetBase`, :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`, and ``apply_every_physics_step`` to :class:`~isaaclab.managers.ActionTerm` and :class:`~isaaclab.managers.ActionManager`. diff --git a/source/isaaclab/isaaclab/managers/action_manager.py b/source/isaaclab/isaaclab/managers/action_manager.py index e79c7fa7de27..5bf5e1be6098 100644 --- a/source/isaaclab/isaaclab/managers/action_manager.py +++ b/source/isaaclab/isaaclab/managers/action_manager.py @@ -39,6 +39,9 @@ class ActionTerm(ManagerTermBase): responsible for applying the processed actions to the asset managed by the term. """ + supports_graph_capture: ClassVar[bool] = False + """Whether :meth:`apply_actions` can be recorded into a CUDA graph, i.e. it writes from fixed buffers.""" + apply_every_physics_step: ClassVar[bool] = True """Whether :meth:`apply_actions` must run before every physics step because its command depends on asset state.""" diff --git a/source/isaaclab/isaaclab/managers/manager_base.py b/source/isaaclab/isaaclab/managers/manager_base.py index c0b9d3f79bfb..dd0ebb0f437b 100644 --- a/source/isaaclab/isaaclab/managers/manager_base.py +++ b/source/isaaclab/isaaclab/managers/manager_base.py @@ -11,7 +11,7 @@ from abc import ABC, abstractmethod from collections.abc import Callable, Sequence from dataclasses import fields -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any from ..physics import PhysicsEvent, PhysicsManager from ..utils import string as string_utils @@ -54,9 +54,6 @@ class MyManagerCfg: """ - supports_graph_capture: ClassVar[bool] = False - """Whether the term launches only Warp work on fixed buffers, so it can be recorded into a CUDA graph.""" - def __init__(self, cfg: ManagerTermBaseCfg, env: ManagerBasedEnv): """Initialize the manager term. From fee9e1f27b75250150f91674f4abe2564e08181c Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 6 Nov 2026 14:43:44 -0800 Subject: [PATCH 06/21] Stop action subclasses from inheriting graph capture flags --- .../newton-redesign-3-env-control.added.rst | 3 ++- .../envs/mdp/actions/binary_joint_actions.py | 16 +++++++++---- .../isaaclab/managers/action_manager.py | 7 ++++++ source/isaaclab/test/envs/mdp/test_actions.py | 22 ++++++++++++++++++ .../newton-redesign-3-env-control.changed.rst | 2 ++ .../newton-redesign-3-env-control.fixed.rst | 2 ++ .../contrib/franka_pour/mdp/actions.py | 6 ++--- .../contrib/microduck/mdp/actions.py | 2 ++ .../test/contrib/test_franka_pour_env_cfg.py | 23 +++++++++++++++++++ 9 files changed, 75 insertions(+), 8 deletions(-) create mode 100644 source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.changed.rst create mode 100644 source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.fixed.rst diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index af9c9ddd8404..f321d105898f 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -5,7 +5,8 @@ :class:`~isaaclab.managers.ActionManager`, :class:`~isaaclab.assets.AssetBase`, :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`, and ``apply_every_physics_step`` to :class:`~isaaclab.managers.ActionTerm` and :class:`~isaaclab.managers.ActionManager`. - Joint, joint-to-limits and binary joint action terms set them. + Joint, joint-to-limits and binary joint action terms set them. A subclass that overrode + :meth:`~isaaclab.managers.ActionTerm.apply_actions` did not inherit them. * Added :attr:`WrenchComposer.pending ` and the ``on_first_use`` argument of :class:`~isaaclab.utils.wrench_composer.WrenchComposer`. Once forces were written, wrench work recorded into a CUDA graph no longer depended on host flags. diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py index cda3ee70a4d0..fc1e398c118b 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py @@ -41,10 +41,6 @@ class BinaryJointAction(ActionTerm): add such constraints to the gripper. """ - supports_graph_capture = True - - apply_every_physics_step = False - cfg: actions_cfg.BinaryJointActionCfg """The configuration of the action term.""" _asset: Articulation @@ -152,6 +148,10 @@ def reset(self, env_ids: Sequence[int] | None = None) -> None: class BinaryJointPositionAction(BinaryJointAction): """Binary joint action that sets the binary action into joint position targets.""" + supports_graph_capture = True + + apply_every_physics_step = False + cfg: actions_cfg.BinaryJointPositionActionCfg """The configuration of the action term.""" @@ -162,6 +162,10 @@ def apply_actions(self): class BinaryJointVelocityAction(BinaryJointAction): """Binary joint action that sets the binary action into joint velocity targets.""" + supports_graph_capture = True + + apply_every_physics_step = False + cfg: actions_cfg.BinaryJointVelocityActionCfg """The configuration of the action term.""" @@ -178,6 +182,10 @@ class AbsBinaryJointPositionAction(BinaryJointAction): closed joint-position target. """ + supports_graph_capture = True + + apply_every_physics_step = False + cfg: actions_cfg.AbsBinaryJointPositionActionCfg """The configuration of the action term.""" diff --git a/source/isaaclab/isaaclab/managers/action_manager.py b/source/isaaclab/isaaclab/managers/action_manager.py index 5bf5e1be6098..5be1e8ca831a 100644 --- a/source/isaaclab/isaaclab/managers/action_manager.py +++ b/source/isaaclab/isaaclab/managers/action_manager.py @@ -45,6 +45,13 @@ class ActionTerm(ManagerTermBase): apply_every_physics_step: ClassVar[bool] = True """Whether :meth:`apply_actions` must run before every physics step because its command depends on asset state.""" + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + # A subclass that overrides apply_actions declares its own flags; it does not inherit them. + if "apply_actions" in cls.__dict__: + cls.supports_graph_capture = cls.__dict__.get("supports_graph_capture", False) + cls.apply_every_physics_step = cls.__dict__.get("apply_every_physics_step", True) + def __init__(self, cfg: ActionTermCfg, env: ManagerBasedEnv): """Initialize the action term. diff --git a/source/isaaclab/test/envs/mdp/test_actions.py b/source/isaaclab/test/envs/mdp/test_actions.py index 45b67577a642..906e9c264a04 100644 --- a/source/isaaclab/test/envs/mdp/test_actions.py +++ b/source/isaaclab/test/envs/mdp/test_actions.py @@ -259,3 +259,25 @@ def test_recordable_joint_actions_process_into_the_same_buffer(action_cls, cfg) assert action.processed_actions is processed assert torch.all(processed < 0.0) + + +def test_subclass_overriding_apply_actions_does_not_inherit_capture_flags() -> None: + """A subclass with its own ``apply_actions`` is neither recorded nor folded unless it says so.""" + + class Applies(JointEffortAction): + def apply_actions(self): + pass + + class Declares(Applies): + apply_every_physics_step = False + + def apply_actions(self): + pass + + class Processes(JointEffortAction): + def process_actions(self, actions): + super().process_actions(actions) + + assert not Applies.supports_graph_capture and Applies.apply_every_physics_step + assert not Declares.supports_graph_capture and not Declares.apply_every_physics_step + assert Processes.supports_graph_capture and not Processes.apply_every_physics_step diff --git a/source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.changed.rst b/source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.changed.rst new file mode 100644 index 000000000000..d028f92d0799 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.changed.rst @@ -0,0 +1,2 @@ +* Changed the MicroDuck encoder-bias joint position action to hold its command for the whole environment step, so + Newton still ran the decimation loop in one step. diff --git a/source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.fixed.rst b/source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.fixed.rst new file mode 100644 index 000000000000..938372ccf065 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.fixed.rst @@ -0,0 +1,2 @@ +* Fixed the Franka Pour curriculum gripper filtering each command against itself once joint actions processed in + place. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py index 6ad4001eccc5..a6809d0966cf 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py @@ -82,6 +82,7 @@ def __init__(self, cfg: CurriculumGripperPositionActionCfg, env: ManagerBasedEnv if not math.isfinite(self._contact_min_deflection) or self._contact_min_deflection <= 0.0: raise ValueError("contact_min_deflection must be finite and positive.") self._processed_actions.fill_(default_position) + self._previous_target = torch.empty_like(self._processed_actions) @property def commanded_position(self) -> torch.Tensor: @@ -137,7 +138,6 @@ def set_reset_position( self._processed_actions[selected] = expanded def process_actions(self, actions: torch.Tensor) -> None: - previous_target = self._processed_actions + self._previous_target.copy_(self._processed_actions) super().process_actions(actions) - previous_target.lerp_(self._processed_actions, self._alpha) - self._processed_actions = previous_target + torch.lerp(self._previous_target, self._processed_actions, self._alpha, out=self._processed_actions) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/microduck/mdp/actions.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/microduck/mdp/actions.py index 318c89aa308b..2dd0047d33da 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/microduck/mdp/actions.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/microduck/mdp/actions.py @@ -22,6 +22,8 @@ class BiasedJointPositionAction(JointPositionAction): """Joint position action that compensates the joint-encoder calibration error.""" + apply_every_physics_step = False + cfg: BiasedJointPositionActionCfg """The configuration of the action term.""" diff --git a/source/isaaclab_tasks/test/contrib/test_franka_pour_env_cfg.py b/source/isaaclab_tasks/test/contrib/test_franka_pour_env_cfg.py index 998b4d008459..4c56c98fcf0a 100644 --- a/source/isaaclab_tasks/test/contrib/test_franka_pour_env_cfg.py +++ b/source/isaaclab_tasks/test/contrib/test_franka_pour_env_cfg.py @@ -5,13 +5,19 @@ """Tests for the single-stage Franka Pour task configuration.""" +from types import SimpleNamespace + import pytest +import torch +import warp as wp from isaaclab.utils import update_from_dict, validate from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR from isaaclab_tasks.contrib.franka_pour import pour_env from isaaclab_tasks.contrib.franka_pour.geometry import SOURCE_CUP_GEOMETRY +from isaaclab_tasks.contrib.franka_pour.mdp.actions import CurriculumGripperPositionAction +from isaaclab_tasks.contrib.franka_pour.mdp.actions_cfg import CurriculumGripperPositionActionCfg from isaaclab_tasks.contrib.franka_pour.media import media_particle_count from isaaclab_tasks.contrib.franka_pour.pour_env_cfg import ( _MEDIA_FILL_RESOLUTION, @@ -187,3 +193,20 @@ def test_constant_mdp_parameters_are_validated_before_stepping(term_path, parame with pytest.raises((TypeError, ValueError), match=message): validate(cfg) + + +def test_gripper_target_moves_a_fraction_of_the_way_to_each_command(): + """The filtered finger target keeps its history although the binary command is processed in place.""" + + class JointIds(list): + warp = wp.array([0, 1], dtype=wp.int32, device="cpu") + torch = wp.to_torch(warp) + + robot = SimpleNamespace(num_joints=2, find_joints=lambda *_a, **_k: (JointIds([0, 1]), ["finger_l", "finger_r"])) + env = SimpleNamespace(num_envs=1, device="cpu", scene={"robot": robot}) + cfg = CurriculumGripperPositionActionCfg(asset_name="robot", joint_names=["finger_.*"], alpha=0.5) + action = CurriculumGripperPositionAction(cfg, env) + + for expected in (0.0125, 0.01875): + action.process_actions(torch.ones(1, 1)) + torch.testing.assert_close(action.processed_actions, torch.full((1, 2), expected)) From aeb98ed716393710af28ea039a1a6ba8fd1466ba Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 6 Nov 2026 16:18:45 -0800 Subject: [PATCH 07/21] Address review comments on member order and processed action aliasing --- .../newton-redesign-3-env-control.changed.rst | 5 ++- source/isaaclab/isaaclab/assets/asset_base.py | 4 +- .../isaaclab/managers/action_manager.py | 5 ++- .../isaaclab/scene/interactive_scene.py | 45 +++++++++++-------- .../assets/articulation/articulation.py | 10 ++--- .../isaaclab_newton/physics/newton_backend.py | 10 ++--- 6 files changed, 46 insertions(+), 33 deletions(-) diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.changed.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.changed.rst index 671a0bdb9149..5f9972f2e0e5 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.changed.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.changed.rst @@ -1,3 +1,6 @@ * Changed joint, joint-to-limits and binary joint action terms to write their processed actions in place, so a - recorded :meth:`~isaaclab.managers.ActionTerm.apply_actions` read the current actions. + recorded :meth:`~isaaclab.managers.ActionTerm.apply_actions` read the current actions. A reference to + :attr:`~isaaclab.managers.ActionTerm.processed_actions` now saw later commands; code that kept the previous + command cloned it or copied it into its own buffer before the next + :meth:`~isaaclab.managers.ActionTerm.process_actions`. * Changed :class:`~isaaclab.envs.ManagerBasedEnv` to set the physics decimation after loading its managers. diff --git a/source/isaaclab/isaaclab/assets/asset_base.py b/source/isaaclab/isaaclab/assets/asset_base.py index 1f95827e30b4..f15606753023 100644 --- a/source/isaaclab/isaaclab/assets/asset_base.py +++ b/source/isaaclab/isaaclab/assets/asset_base.py @@ -10,7 +10,7 @@ from abc import ABC, abstractmethod from collections import OrderedDict from collections.abc import Sequence -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, ClassVar, Literal import torch import warp as wp @@ -78,7 +78,7 @@ class AssetBase(Asset, ABC): _check_shapes: bool = __debug__ """Class-level default for shape validation. Overridden per-instance in ``__init__``.""" - supports_graph_capture: bool = False + supports_graph_capture: ClassVar[bool] = False """Whether :meth:`write_data_to_sim` can be recorded into a CUDA graph.""" def __init__(self, cfg: AssetBaseCfg): diff --git a/source/isaaclab/isaaclab/managers/action_manager.py b/source/isaaclab/isaaclab/managers/action_manager.py index 5be1e8ca831a..4fd8055a9f16 100644 --- a/source/isaaclab/isaaclab/managers/action_manager.py +++ b/source/isaaclab/isaaclab/managers/action_manager.py @@ -98,7 +98,10 @@ def raw_actions(self) -> torch.Tensor: @property @abstractmethod def processed_actions(self) -> torch.Tensor: - """The actions computed by the term after applying any processing.""" + """The actions computed by the term after applying any processing. + + Terms that support graph capture update this tensor in place, so a held reference sees later commands. + """ raise NotImplementedError @property diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index 6ce6a196a72b..787d381196a7 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -15,7 +15,6 @@ if TYPE_CHECKING: from isaaclab_physx.assets import SurfaceGripper - from ..assets import AssetBase from ..terrains.terrain_importer import TerrainImporter import torch @@ -412,6 +411,19 @@ def state(self) -> dict[str, dict[str, dict[str, torch.Tensor]]]: """ return self.get_state(is_relative=False) + @property + def supports_graph_capture(self) -> bool: + """Whether :meth:`write_data_to_sim` can be recorded into a CUDA graph.""" + writers = ( + self._articulations, + self._cable_objects, + self._deformable_objects, + self._rigid_objects, + self._surface_grippers, + self._rigid_object_collections, + ) + return all(asset.supports_graph_capture for assets in writers for asset in assets.values()) + """ Operations. """ @@ -440,26 +452,21 @@ def reset(self, env_ids: Sequence[int] | None = None): for sensor in self._sensors.values(): sensor.reset(env_ids) - @property - def supports_graph_capture(self) -> bool: - """Whether :meth:`write_data_to_sim` can be recorded into a CUDA graph.""" - return all(asset.supports_graph_capture for asset in self._sim_writers()) - def write_data_to_sim(self): """Writes the data of the scene entities to the simulation.""" - for asset in self._sim_writers(): - asset.write_data_to_sim() - - def _sim_writers(self) -> tuple[AssetBase, ...]: - """Assets that write to the simulation, in write order.""" - return ( - *self._articulations.values(), - *self._cable_objects.values(), - *self._deformable_objects.values(), - *self._rigid_objects.values(), - *self._surface_grippers.values(), - *self._rigid_object_collections.values(), - ) + # -- assets + for articulation in self._articulations.values(): + articulation.write_data_to_sim() + for cable_object in self._cable_objects.values(): + cable_object.write_data_to_sim() + for deformable_object in self._deformable_objects.values(): + deformable_object.write_data_to_sim() + for rigid_object in self._rigid_objects.values(): + rigid_object.write_data_to_sim() + for surface_gripper in self._surface_grippers.values(): + surface_gripper.write_data_to_sim() + for rigid_object_collection in self._rigid_object_collections.values(): + rigid_object_collection.write_data_to_sim() def update(self, dt: float) -> None: """Update the scene entities. diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py index 5942c3d75b58..b6e5c43557e5 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py @@ -362,6 +362,11 @@ def permanent_wrench_composer(self) -> WrenchComposer: """ return self._permanent_wrench_composer + @property + def supports_graph_capture(self) -> bool: + """Whether :meth:`write_data_to_sim` can be recorded: no Torch actuators and no fixed tendons.""" + return self.actuators.supports_graph_capture and self._fixed_tendon_control is None + """ Operations. """ @@ -386,11 +391,6 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None self._instantaneous_wrench_composer.reset(env_ids, env_mask) self._permanent_wrench_composer.reset(env_ids, env_mask) - @property - def supports_graph_capture(self) -> bool: - """Whether :meth:`write_data_to_sim` can be recorded: no Torch actuators and no fixed tendons.""" - return self.actuators.supports_graph_capture and self._fixed_tendon_control is None - def write_data_to_sim(self): """Write external wrenches and joint commands to the simulation. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index c205ac029ee3..4120c9311724 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -515,6 +515,11 @@ def step(self) -> bool: self.solver_ops.check_step(captured, self.cfg.debug_mode) return captured + def stage_body_forces(self) -> None: + """Copy the body forces written to ``state_0``, so that every following solver substep applies them.""" + if self.staged_body_f is not None: + wp.copy(self.staged_body_f, self.state_0.body_f) + def state_pointers(self) -> tuple[int, int]: """Addresses of :attr:`state_0`'s body and particle arrays, ``0`` for an absent array. @@ -641,11 +646,6 @@ def _finish_step(self) -> None: callback() self._update_sensors() - def stage_body_forces(self) -> None: - """Copy the body forces written to ``state_0``, so that every following solver substep applies them.""" - if self.staged_body_f is not None: - wp.copy(self.staged_body_f, self.state_0.body_f) - def _run_solver_substeps(self, contacts: Contacts | None, *, observables: SolverBase.Observables | None) -> None: """Run the solver substeps of one physics step, ending in :attr:`state_0`. From 5cee6fc61bc664894401ecb04da249310e96cf5d Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 6 Nov 2026 16:27:20 -0800 Subject: [PATCH 08/21] Keep the environment's loop when renders or recorders run between physics steps --- .../newton-redesign-3-env-control.added.rst | 4 +++- .../isaaclab/isaaclab/envs/manager_based_env.py | 6 ++++-- .../isaaclab/managers/recorder_manager.py | 6 ++++++ .../test/managers/test_recorder_manager.py | 15 +++++++++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index f321d105898f..ae8cae0467bc 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,6 +1,8 @@ * Added :meth:`PhysicsManager.bind_control `, which let a physics backend run the environment's actions and asset writes inside its step. :class:`~isaaclab.envs.ManagerBasedEnv` - called it after loading its managers and skipped the actions and asset writes that the step ran. + called it after loading its managers, unless its render interval was not a multiple of the decimation or a recorder + term recorded after every physics step, and skipped the actions and asset writes that the step ran. +* Added :attr:`RecorderManager.records_physics_steps `. * Added ``supports_graph_capture`` to :class:`~isaaclab.managers.ActionTerm`, :class:`~isaaclab.managers.ActionManager`, :class:`~isaaclab.assets.AssetBase`, :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`, and diff --git a/source/isaaclab/isaaclab/envs/manager_based_env.py b/source/isaaclab/isaaclab/envs/manager_based_env.py index 7a5f797548f0..60841de3247c 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env.py @@ -207,8 +207,10 @@ def _init_sim(self): report_activity("Setting up managers") self.load_managers() report_activity(None) - # let the physics backend run the actions, asset writes and decimation loop inside its step when it can - self._physics_handles_actions = self.sim.backend_manager.bind_control(self.action_manager, self.scene) + # let the physics backend run the actions, asset writes and decimation loop inside its step when it can, + # unless renders or recorders must run between the physics steps of one environment step + if self.cfg.sim.render_interval % self.cfg.decimation == 0 and not self.recorder_manager.records_physics_steps: + self._physics_handles_actions = self.sim.backend_manager.bind_control(self.action_manager, self.scene) self.sim.backend_manager.set_decimation(self.cfg.decimation) self._physics_handles_decimation = self.sim.backend_manager.handles_decimation() diff --git a/source/isaaclab/isaaclab/managers/recorder_manager.py b/source/isaaclab/isaaclab/managers/recorder_manager.py index 894bb1ff290f..bf9cab409c8f 100644 --- a/source/isaaclab/isaaclab/managers/recorder_manager.py +++ b/source/isaaclab/isaaclab/managers/recorder_manager.py @@ -218,6 +218,12 @@ def active_terms(self) -> list[str]: """Name of active recorder terms.""" return self._term_names + @property + def records_physics_steps(self) -> bool: + """Whether a term records after every physics step of the decimation loop.""" + hook = RecorderTerm.record_post_physics_decimation_step + return any(type(term).record_post_physics_decimation_step is not hook for term in self._terms.values()) + @property def exported_successful_episode_count(self) -> int: """Number of successful episodes.""" diff --git a/source/isaaclab/test/managers/test_recorder_manager.py b/source/isaaclab/test/managers/test_recorder_manager.py index f37214334707..99ff07dbf85e 100644 --- a/source/isaaclab/test/managers/test_recorder_manager.py +++ b/source/isaaclab/test/managers/test_recorder_manager.py @@ -117,6 +117,21 @@ def test_record(tmp_path): manager.close() +class DummyPhysicsStepRecorderTerm(RecorderTerm): + """Dummy recorder term that records after every physics step.""" + + def record_post_physics_decimation_step(self) -> tuple[str | None, torch.Tensor | None]: + return "record_post_physics_decimation_step", torch.ones(self._env.num_envs, 1, device=self._env.device) + + +def test_records_physics_steps_only_with_a_physics_step_term(tmp_path): + """The environment keeps its decimation loop only for terms that record between physics steps.""" + cfg = DummyRecorderManagerCfg(dataset_export_dir_path=str(tmp_path), dataset_filename="dataset.hdf5") + assert not RecorderManager(cfg, create_dummy_env()).records_physics_steps + cfg.record_physics_term = RecorderTermCfg(class_type=DummyPhysicsStepRecorderTerm) + assert RecorderManager(cfg, create_dummy_env()).records_physics_steps + + def test_batched_episode_indices_and_ownership(monkeypatch): """Asynchronous resets, field cadence, growth and snapshots must preserve exact samples.""" cfg = DummyRecorderManagerCfg(dataset_export_mode=DatasetExportMode.EXPORT_NONE, buffer_initial_capacity=2) From 2490ca4ddf4160c5bcc4f5ea78cf959d61a07448 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Fri, 6 Nov 2026 16:40:55 -0800 Subject: [PATCH 09/21] Stage bound body forces inside the backend step --- .../extending_newton_solvers.rst | 7 +++---- .../newton-redesign-3-env-control.added.rst | 4 ++-- .../isaaclab_newton/physics/newton_backend.py | 17 ++++++++++------- .../isaaclab_newton/physics/newton_manager.py | 2 -- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/source/developer-tools/extending_newton_solvers.rst b/docs/source/developer-tools/extending_newton_solvers.rst index df4569ec665a..3f95de800566 100644 --- a/docs/source/developer-tools/extending_newton_solvers.rst +++ b/docs/source/developer-tools/extending_newton_solvers.rst @@ -133,10 +133,9 @@ substeps``, and post-step callbacks and sensors run once at the end. Every substep runs ``staged body forces -> state-force callbacks -> step``, and ``pre_step`` and ``post_step`` run around each physics step's substeps. -:meth:`~isaaclab_newton.physics.NewtonManager.bind_control` makes the action manager's ``apply_action``, the scene's -``write_data_to_sim`` and :meth:`~isaaclab_newton.physics.NewtonBackend.stage_body_forces` pre-actuator callbacks, so -they run before every physics step as in the environment's own loop. It binds only when both report -``supports_graph_capture``. The first wrench written to an asset captures the step again with the wrench work. +:meth:`~isaaclab_newton.physics.NewtonManager.bind_control` makes the action manager's ``apply_action`` and the +scene's ``write_data_to_sim`` pre-actuator callbacks, so they run before every physics step as in the environment's +own loop, and the step stages the body forces they write. It binds only when both report ``supports_graph_capture``. The first wrench written to an asset captures the step again with the wrench work. Every physics step ends in ``state_0``, so ``manager.backend.state_0`` is always the same object. The captured step records the callbacks, so they must be graph-safe. Consumers register them with diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst index 32099529d427..53da9ead69a7 100644 --- a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,5 +1,5 @@ * Added :meth:`NewtonManager.bind_control `. When every action term and written asset could be recorded, the environment's actions and asset writes ran as pre-actuator callbacks before every physics step, and one step advanced the whole decimation loop. Hard resets bound them again. -* Added ``NewtonBackend.control_bound``, ``NewtonBackend.control_every_physics_step`` and the public - :meth:`NewtonBackend.stage_body_forces `. +* Added ``NewtonBackend.control_bound`` and ``NewtonBackend.control_every_physics_step``. With bound control, every + physics step staged the body forces that the asset writes produced. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index 4120c9311724..1b8ef0a98007 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -498,7 +498,7 @@ def step(self) -> bool: else: if self.device.is_capturing: raise RuntimeError("Newton actuators that cannot be captured prevent recording the step.") - self.stage_body_forces() + self._stage_body_forces() for i in range(steps): self._launch("before_actuators", self._before_actuators) actuators.step(self.state_0, self.control, self.dt) @@ -515,11 +515,6 @@ def step(self) -> bool: self.solver_ops.check_step(captured, self.cfg.debug_mode) return captured - def stage_body_forces(self) -> None: - """Copy the body forces written to ``state_0``, so that every following solver substep applies them.""" - if self.staged_body_f is not None: - wp.copy(self.staged_body_f, self.state_0.body_f) - def state_pointers(self) -> tuple[int, int]: """Addresses of :attr:`state_0`'s body and particle arrays, ``0`` for an absent array. @@ -615,7 +610,7 @@ def _launch(self, key: str | tuple[str, int], fn: Callable[[], None]) -> None: def _simulate(self, steps: int) -> None: """Run ``steps`` physics steps with the Newton actuators, then finish the step.""" actuators = self.actuators - self.stage_body_forces() + self._stage_body_forces() for i in range(steps): self._before_actuators() if actuators is not None: @@ -632,6 +627,9 @@ def _before_actuators(self) -> None: self.collision_pipeline.collide(self.state_0, self.contacts) for callback in self.pre_actuator_callbacks: callback() + if self.control_bound: + # bound asset writes replace the body forces staged before the step + self._stage_body_forces() def _after_actuators(self, observables: SolverBase.Observables | None) -> None: """Run the post-actuator callbacks and the solver substeps of one physics step.""" @@ -646,6 +644,11 @@ def _finish_step(self) -> None: callback() self._update_sensors() + def _stage_body_forces(self) -> None: + """Copy the body forces written to ``state_0`` before the step, so that every solver substep applies them.""" + if self.staged_body_f is not None: + wp.copy(self.staged_body_f, self.state_0.body_f) + def _run_solver_substeps(self, contacts: Contacts | None, *, observables: SolverBase.Observables | None) -> None: """Run the solver substeps of one physics step, ending in :attr:`state_0`. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index b1e5eca32f30..926e5fc219b4 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -625,8 +625,6 @@ def _bind_control(self) -> None: return self.register_pre_actuator_callback(actions.apply_action) self.register_pre_actuator_callback(scene.write_data_to_sim) - # Asset writes replace the body forces staged before the step. - self.register_pre_actuator_callback(backend.stage_body_forces) backend.control_bound = True def add_contact_sensor( From 0e6f5cfcb50b378227e9365f2576c2df243827dd Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sat, 7 Nov 2026 10:34:41 -0800 Subject: [PATCH 10/21] Keep bound control consistent with sensors, reordered state and wrench merges --- .../newton-redesign-3-env-control.added.rst | 8 +++++--- .../isaaclab/envs/manager_based_env.py | 13 +++++++++++-- .../isaaclab/utils/wrench_composer.py | 19 +++++++++++-------- .../test/utils/test_wrench_composer.py | 17 +++++++++++++++++ .../newton-redesign-3-env-control.added.rst | 3 ++- .../isaaclab_newton/physics/newton_backend.py | 4 ++++ .../isaaclab_newton/physics/newton_manager.py | 3 ++- .../test/physics/test_newton_manager.py | 16 ++++++++++++---- 8 files changed, 64 insertions(+), 19 deletions(-) diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index ae8cae0467bc..92e89de4a56c 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,7 +1,8 @@ * Added :meth:`PhysicsManager.bind_control `, which let a physics backend run the environment's actions and asset writes inside its step. :class:`~isaaclab.envs.ManagerBasedEnv` - called it after loading its managers, unless its render interval was not a multiple of the decimation or a recorder - term recorded after every physics step, and skipped the actions and asset writes that the step ran. + called it after loading its managers, unless its render interval was not a multiple of the decimation, a recorder + term recorded after every physics step, or a sensor sampled more often than once per environment step, and skipped + the actions and asset writes that the step ran. * Added :attr:`RecorderManager.records_physics_steps `. * Added ``supports_graph_capture`` to :class:`~isaaclab.managers.ActionTerm`, :class:`~isaaclab.managers.ActionManager`, :class:`~isaaclab.assets.AssetBase`, @@ -10,5 +11,6 @@ Joint, joint-to-limits and binary joint action terms set them. A subclass that overrode :meth:`~isaaclab.managers.ActionTerm.apply_actions` did not inherit them. * Added :attr:`WrenchComposer.pending ` and the - ``on_first_use`` argument of :class:`~isaaclab.utils.wrench_composer.WrenchComposer`. Once forces were written, + ``on_first_use`` argument of :class:`~isaaclab.utils.wrench_composer.WrenchComposer`, called at the first force + write or :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.add_raw_buffers_from` merge. Once forces were written, wrench work recorded into a CUDA graph no longer depended on host flags. diff --git a/source/isaaclab/isaaclab/envs/manager_based_env.py b/source/isaaclab/isaaclab/envs/manager_based_env.py index 60841de3247c..a91442bbd2a1 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env.py @@ -208,8 +208,17 @@ def _init_sim(self): self.load_managers() report_activity(None) # let the physics backend run the actions, asset writes and decimation loop inside its step when it can, - # unless renders or recorders must run between the physics steps of one environment step - if self.cfg.sim.render_interval % self.cfg.decimation == 0 and not self.recorder_manager.records_physics_steps: + # unless renders, recorders or sensors must run between the physics steps of one environment step + eager_sensors = not self.scene.cfg.lazy_sensor_update + sensors_sample_physics_steps = any( + (eager_sensors or getattr(sensor.cfg, "history_length", 0) > 0) and sensor.cfg.update_period < self.step_dt + for sensor in self.scene.sensors.values() + ) + if ( + self.cfg.sim.render_interval % self.cfg.decimation == 0 + and not self.recorder_manager.records_physics_steps + and not sensors_sample_physics_steps + ): self._physics_handles_actions = self.sim.backend_manager.bind_control(self.action_manager, self.scene) self.sim.backend_manager.set_decimation(self.cfg.decimation) self._physics_handles_decimation = self.sim.backend_manager.handles_decimation() diff --git a/source/isaaclab/isaaclab/utils/wrench_composer.py b/source/isaaclab/isaaclab/utils/wrench_composer.py index 6d5150ca2973..22f105106102 100644 --- a/source/isaaclab/isaaclab/utils/wrench_composer.py +++ b/source/isaaclab/isaaclab/utils/wrench_composer.py @@ -483,8 +483,7 @@ def add_raw_buffers_from(self, other: WrenchComposer): f"into composer with shape ({self.num_envs}, {self.num_bodies})." ) - self._active = True - self._dirty = True + self._mark_active() self._has_local_wrench = self._has_local_wrench or other._has_local_wrench self._has_global_wrench = self._has_global_wrench or other._has_global_wrench self._has_global_positions = self._has_global_positions or other._has_global_positions @@ -673,12 +672,7 @@ def _prepare_write(self, forces, positions, is_global: bool) -> tuple[wp.array, Frame and argument presence are launch-time choices, fixed during graph capture. Selection contents and force/torque values remain device inputs on every replay. """ - self._active = True - self._dirty = True - if not self._used: - self._used = True - if self._on_first_use is not None: - self._on_first_use() + self._mark_active() if is_global: self._has_global_wrench = True self._has_global_positions = self._has_global_positions or (forces is not None and positions is not None) @@ -687,6 +681,15 @@ def _prepare_write(self, forces, positions, is_global: bool) -> tuple[wp.array, self._has_local_wrench = True return self._local_force_b, self._local_torque_b + def _mark_active(self) -> None: + """Mark pending contributions, calling :attr:`_on_first_use` at the first one.""" + self._active = True + self._dirty = True + if not self._used: + self._used = True + if self._on_first_use is not None: + self._on_first_use() + def _resolve_env_ids(self, env_ids: wp.array | torch.Tensor | list | slice | None) -> wp.array | torch.Tensor: """Resolve environment IDs. diff --git a/source/isaaclab/test/utils/test_wrench_composer.py b/source/isaaclab/test/utils/test_wrench_composer.py index 1a0abb0fe743..47de8c4a44db 100644 --- a/source/isaaclab/test/utils/test_wrench_composer.py +++ b/source/isaaclab/test/utils/test_wrench_composer.py @@ -580,6 +580,23 @@ def write(): assert first_uses == ["instantaneous", "permanent"] +@pytest.mark.parametrize("device", test_devices()) +def test_raw_buffer_merge_is_the_first_use_of_its_destination(device): + """A merge into an unused composer calls its first-use callback, as a force write would.""" + com, quat = _poses() + asset = SimpleNamespace( + num_instances=2, num_bodies=2, device=device, data=_AssetData(com.to(device), quat.to(device)) + ) + first_uses = [] + source = WrenchComposer(asset) + destination = WrenchComposer(asset, on_first_use=lambda: first_uses.append("destination")) + with wp.ScopedDevice(device): + source.add_forces_and_torques_index(wp.array([[[3.0, 0.0, 0.0]]], dtype=wp.vec3f), env_ids=[0], body_ids=[0]) + destination.add_raw_buffers_from(source) + destination.add_raw_buffers_from(source) + assert first_uses == ["destination"] + + @pytest.mark.parametrize( "name", [ diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst index 53da9ead69a7..f5aef042abcc 100644 --- a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst @@ -2,4 +2,5 @@ term and written asset could be recorded, the environment's actions and asset writes ran as pre-actuator callbacks before every physics step, and one step advanced the whole decimation loop. Hard resets bound them again. * Added ``NewtonBackend.control_bound`` and ``NewtonBackend.control_every_physics_step``. With bound control, every - physics step staged the body forces that the asset writes produced. + physics step ran the post-step callbacks before the asset writes, so they read the current reordered state, and + staged the body forces that the writes produced. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index 1b8ef0a98007..9628fd378bfc 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -625,6 +625,10 @@ def _before_actuators(self) -> None: self.solver_ops.pre_step(self.state_0) if self.collision_pipeline is not None: self.collision_pipeline.collide(self.state_0, self.contacts) + if self.control_bound: + # bound asset writes read the state that the post-step callbacks publish + for callback in self.post_step_callbacks: + callback() for callback in self.pre_actuator_callbacks: callback() if self.control_bound: diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index 926e5fc219b4..15e2a864a72b 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -573,7 +573,8 @@ def register_state_force_callback(self, callback: Callable[[State], None]) -> No def register_post_step_callback(self, callback: Callable[[], None]) -> None: """Append a hook invoked once per :meth:`step`, after the last solver substep and before sensors update. - The hook reflects the state after all decimation iterations of the step. Callbacks must be graph-safe (fixed + The hook reflects the state after all decimation iterations of the step; with bound control it also runs before + every physics step, ahead of the bound writes. Callbacks must be graph-safe (fixed shapes, no host branching on device data) because they are recorded into the captured step. Hard resets discard these hooks; register them again when the new model is ready. """ diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index 29eb59a98619..2ac86c1c0d7b 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -947,7 +947,7 @@ def _bound_control(manager: NewtonManager, *, graphable: bool): supports_graph_capture=graphable, apply_every_physics_step=True, apply_action=lambda: ( - applied.append(None), + applied.append("action"), wp.launch(_damp_body, 1, inputs=[manager.backend.state_0.body_qd, manager.backend.state_0.body_f]), ), ) @@ -956,7 +956,10 @@ def _bound_control(manager: NewtonManager, *, graphable: bool): def test_bound_control_runs_before_every_physics_step_like_the_environment_loop(): - """Bound actions run before every physics step of one captured step, also after a hard reset, like the env loop.""" + """Bound actions run before every physics step of one captured step, also after a hard reset, like the env loop. + + Each bound action reads the state that the post-step callbacks publish after the previous physics step. + """ decimation, num_steps, velocities = 3, 4, [] for bound in (True, False): sim_cfg = SimulationCfg(dt=0.01, device="cuda:0", physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())) @@ -974,14 +977,19 @@ def test_bound_control_runs_before_every_physics_step_like_the_environment_loop( if reset: sim.reset() assert manager.backend.control_bound is bound + # hard resets discard the post-step callbacks + manager.register_post_step_callback(lambda: applied.append("publish")) applied.clear() for _ in range(num_steps): for _ in range(1 if bound else decimation): if not bound: actions.apply_action() sim.step(render=False) - # bound steps record the actions once per physics step and then replay them - assert len(applied) == (2 * decimation if bound else num_steps * decimation) + # bound steps record the actions after the published state of every physics step, then replay them + if bound: + assert applied == (["publish", "action"] * decimation + ["publish"]) * 2 + else: + assert applied.count("action") == num_steps * decimation velocities.append(manager.backend.state_0.body_qd.numpy().copy()) np.testing.assert_allclose(velocities[:2], velocities[2:], rtol=1e-5, atol=1e-6) # damping holds the body well below free-fall speed From 19d951f8ea0d0ca057acd42229734cba71c37dc9 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sat, 7 Nov 2026 17:19:45 -0800 Subject: [PATCH 11/21] Remove apply_every_physics_step from action terms --- .../developer-tools/extending_newton_solvers.rst | 13 +++++++------ .../newton-redesign-3-env-control.added.rst | 7 +++---- .../envs/mdp/actions/binary_joint_actions.py | 6 ------ .../isaaclab/envs/mdp/actions/joint_actions.py | 6 ------ .../envs/mdp/actions/joint_actions_to_limits.py | 2 -- .../envs/mdp/actions/surface_gripper_actions.py | 2 -- .../isaaclab/envs/mdp/actions/tendon_actions.py | 2 -- source/isaaclab/isaaclab/managers/action_manager.py | 11 +---------- source/isaaclab/test/envs/mdp/test_actions.py | 12 ++++++------ .../newton-redesign-3-env-control.added.rst | 5 ++--- .../newton-redesign-3-env-control.changed.rst | 5 ++--- .../isaaclab_newton/physics/newton_backend.py | 6 ++---- .../isaaclab_newton/physics/newton_manager.py | 4 +--- .../test/physics/test_newton_manager.py | 3 --- .../newton-redesign-3-env-control.changed.rst | 2 -- .../isaaclab_tasks/contrib/microduck/mdp/actions.py | 2 -- 16 files changed, 24 insertions(+), 64 deletions(-) delete mode 100644 source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.changed.rst diff --git a/docs/source/developer-tools/extending_newton_solvers.rst b/docs/source/developer-tools/extending_newton_solvers.rst index 3f95de800566..2d0ed477b197 100644 --- a/docs/source/developer-tools/extending_newton_solvers.rst +++ b/docs/source/developer-tools/extending_newton_solvers.rst @@ -125,17 +125,18 @@ The Step -------- Each :meth:`~isaaclab_newton.physics.NewtonManager.step` covers the whole decimation loop when the manager handles -decimation (:meth:`~isaaclab_newton.physics.NewtonManager.handles_decimation`), and one physics step otherwise. It -does when the environment's control is bound to the step, or when an articulation runs its Newton actuators in the -step and every action term holds its command for the whole environment step (``apply_every_physics_step = False``). -Every physics step runs ``collide -> pre-actuator callbacks -> Newton actuators -> post-actuator callbacks -> -substeps``, and post-step callbacks and sensors run once at the end. +decimation (:meth:`~isaaclab_newton.physics.NewtonManager.handles_decimation`: the environment's control is bound to +the step, or an articulation runs its Newton actuators in the step), and one physics step otherwise. Every physics step +runs ``collide -> pre-actuator callbacks -> Newton actuators -> post-actuator callbacks -> substeps``, and post-step +callbacks and sensors run once at the end. Every substep runs ``staged body forces -> state-force callbacks -> step``, and ``pre_step`` and ``post_step`` run around each physics step's substeps. :meth:`~isaaclab_newton.physics.NewtonManager.bind_control` makes the action manager's ``apply_action`` and the scene's ``write_data_to_sim`` pre-actuator callbacks, so they run before every physics step as in the environment's -own loop, and the step stages the body forces they write. It binds only when both report ``supports_graph_capture``. The first wrench written to an asset captures the step again with the wrench work. +own loop. Before them, the post-step callbacks republish the asset state they read, and after them, the step stages +the body forces they write. It binds only when both report ``supports_graph_capture``. The first wrench written to an +asset captures the step again with the wrench work. Every physics step ends in ``state_0``, so ``manager.backend.state_0`` is always the same object. The captured step records the callbacks, so they must be graph-safe. Consumers register them with diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index 92e89de4a56c..e2c10c6b0c58 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -6,10 +6,9 @@ * Added :attr:`RecorderManager.records_physics_steps `. * Added ``supports_graph_capture`` to :class:`~isaaclab.managers.ActionTerm`, :class:`~isaaclab.managers.ActionManager`, :class:`~isaaclab.assets.AssetBase`, - :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`, and - ``apply_every_physics_step`` to :class:`~isaaclab.managers.ActionTerm` and :class:`~isaaclab.managers.ActionManager`. - Joint, joint-to-limits and binary joint action terms set them. A subclass that overrode - :meth:`~isaaclab.managers.ActionTerm.apply_actions` did not inherit them. + :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`. Joint, joint-to-limits + and binary joint action terms set it. A subclass that overrode :meth:`~isaaclab.managers.ActionTerm.apply_actions` + did not inherit it. * Added :attr:`WrenchComposer.pending ` and the ``on_first_use`` argument of :class:`~isaaclab.utils.wrench_composer.WrenchComposer`, called at the first force write or :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.add_raw_buffers_from` merge. Once forces were written, diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py index fc1e398c118b..ecf26d92b603 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py @@ -150,8 +150,6 @@ class BinaryJointPositionAction(BinaryJointAction): supports_graph_capture = True - apply_every_physics_step = False - cfg: actions_cfg.BinaryJointPositionActionCfg """The configuration of the action term.""" @@ -164,8 +162,6 @@ class BinaryJointVelocityAction(BinaryJointAction): supports_graph_capture = True - apply_every_physics_step = False - cfg: actions_cfg.BinaryJointVelocityActionCfg """The configuration of the action term.""" @@ -184,8 +180,6 @@ class AbsBinaryJointPositionAction(BinaryJointAction): supports_graph_capture = True - apply_every_physics_step = False - cfg: actions_cfg.AbsBinaryJointPositionActionCfg """The configuration of the action term.""" diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py index 2f58e6f7e26f..495fb8a6799f 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py @@ -185,8 +185,6 @@ class JointPositionAction(JointAction): supports_graph_capture = True - apply_every_physics_step = False - cfg: actions_cfg.JointPositionActionCfg """The configuration of the action term.""" @@ -240,8 +238,6 @@ class JointVelocityAction(JointAction): supports_graph_capture = True - apply_every_physics_step = False - cfg: actions_cfg.JointVelocityActionCfg """The configuration of the action term.""" @@ -262,8 +258,6 @@ class JointEffortAction(JointAction): supports_graph_capture = True - apply_every_physics_step = False - cfg: actions_cfg.JointEffortActionCfg """The configuration of the action term.""" diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py index 25d7b6a1ac1a..1d984f502688 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py @@ -43,8 +43,6 @@ class JointPositionToLimitsAction(ActionTerm): supports_graph_capture = True - apply_every_physics_step = False - cfg: actions_cfg.JointPositionToLimitsActionCfg """The configuration of the action term.""" _asset: Articulation diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/surface_gripper_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/surface_gripper_actions.py index eb874cd4aa1f..ea1a4c6f8e06 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/surface_gripper_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/surface_gripper_actions.py @@ -42,8 +42,6 @@ class SurfaceGripperBinaryAction(ActionTerm): interface than joint-based grippers. """ - apply_every_physics_step = False - cfg: actions_cfg.SurfaceGripperBinaryActionCfg """The configuration of the action term.""" _asset: SurfaceGripper diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/tendon_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/tendon_actions.py index 0f7957a467fd..2775a92dc3ee 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/tendon_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/tendon_actions.py @@ -38,8 +38,6 @@ class FixedTendonPositionAction(ActionTerm): articulation decides how a tendon target reaches its solver, so this term is backend-neutral. """ - apply_every_physics_step = False - cfg: actions_cfg.FixedTendonPositionActionCfg """The configuration of the action term.""" _scale: torch.Tensor | float diff --git a/source/isaaclab/isaaclab/managers/action_manager.py b/source/isaaclab/isaaclab/managers/action_manager.py index 4fd8055a9f16..b4131788a67c 100644 --- a/source/isaaclab/isaaclab/managers/action_manager.py +++ b/source/isaaclab/isaaclab/managers/action_manager.py @@ -42,15 +42,11 @@ class ActionTerm(ManagerTermBase): supports_graph_capture: ClassVar[bool] = False """Whether :meth:`apply_actions` can be recorded into a CUDA graph, i.e. it writes from fixed buffers.""" - apply_every_physics_step: ClassVar[bool] = True - """Whether :meth:`apply_actions` must run before every physics step because its command depends on asset state.""" - def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) - # A subclass that overrides apply_actions declares its own flags; it does not inherit them. + # A subclass that overrides apply_actions declares its own flag; it does not inherit it. if "apply_actions" in cls.__dict__: cls.supports_graph_capture = cls.__dict__.get("supports_graph_capture", False) - cls.apply_every_physics_step = cls.__dict__.get("apply_every_physics_step", True) def __init__(self, cfg: ActionTermCfg, env: ManagerBasedEnv): """Initialize the action term. @@ -295,11 +291,6 @@ def supports_graph_capture(self) -> bool: """Whether :meth:`apply_action` can be recorded into a CUDA graph.""" return all(term.supports_graph_capture for term in self._terms.values()) - @property - def apply_every_physics_step(self) -> bool: - """Whether any term must apply its actions before every physics step.""" - return any(term.apply_every_physics_step for term in self._terms.values()) - @property def has_debug_vis_implementation(self) -> bool: """Whether the command terms have debug visualization implemented.""" diff --git a/source/isaaclab/test/envs/mdp/test_actions.py b/source/isaaclab/test/envs/mdp/test_actions.py index 906e9c264a04..59039b1f1079 100644 --- a/source/isaaclab/test/envs/mdp/test_actions.py +++ b/source/isaaclab/test/envs/mdp/test_actions.py @@ -252,7 +252,7 @@ def test_recordable_joint_actions_process_into_the_same_buffer(action_cls, cfg) """A step that records ``apply_actions`` reads the processed buffer, so processing writes it in place.""" cfg.asset_name, cfg.joint_names = "robot", [".*"] action = action_cls(cfg, _make_env(["a", "b"])) - assert action_cls.supports_graph_capture and not action_cls.apply_every_physics_step + assert action_cls.supports_graph_capture processed = action.processed_actions action.process_actions(torch.full((2, action.action_dim), -0.25)) @@ -262,14 +262,14 @@ def test_recordable_joint_actions_process_into_the_same_buffer(action_cls, cfg) def test_subclass_overriding_apply_actions_does_not_inherit_capture_flags() -> None: - """A subclass with its own ``apply_actions`` is neither recorded nor folded unless it says so.""" + """A subclass with its own ``apply_actions`` is not recorded unless it says so.""" class Applies(JointEffortAction): def apply_actions(self): pass class Declares(Applies): - apply_every_physics_step = False + supports_graph_capture = True def apply_actions(self): pass @@ -278,6 +278,6 @@ class Processes(JointEffortAction): def process_actions(self, actions): super().process_actions(actions) - assert not Applies.supports_graph_capture and Applies.apply_every_physics_step - assert not Declares.supports_graph_capture and not Declares.apply_every_physics_step - assert Processes.supports_graph_capture and not Processes.apply_every_physics_step + assert not Applies.supports_graph_capture + assert Declares.supports_graph_capture + assert Processes.supports_graph_capture diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst index f5aef042abcc..622f7e3763b1 100644 --- a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,6 +1,5 @@ * Added :meth:`NewtonManager.bind_control `. When every action term and written asset could be recorded, the environment's actions and asset writes ran as pre-actuator callbacks before every physics step, and one step advanced the whole decimation loop. Hard resets bound them again. -* Added ``NewtonBackend.control_bound`` and ``NewtonBackend.control_every_physics_step``. With bound control, every - physics step ran the post-step callbacks before the asset writes, so they read the current reordered state, and - staged the body forces that the writes produced. +* Added ``NewtonBackend.control_bound``. With bound control, every physics step ran the post-step callbacks before the + asset writes, so they read the current reordered state, and staged the body forces that the writes produced. diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst index 33c508256291..3df42cf6a2ba 100644 --- a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst +++ b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst @@ -1,5 +1,4 @@ -* Changed :meth:`NewtonBackend.handles_decimation ` to keep - the decimation loop in the environment when Newton actuators run in the step but an action term must be applied - before every physics step and could not be bound. +* Changed :meth:`NewtonBackend.handles_decimation ` to also + run the decimation loop in one step when the environment's control is bound. * Changed Newton articulations, rigid objects and rigid object collections to record their wrench work into a captured step only once a wrench composer was used, which captured the step again. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index 9628fd378bfc..b692f6379122 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -212,8 +212,6 @@ def __init__(self, cfg: NewtonBackendCfg, builder: ModelBuilder | None = None, * """Whether an articulation runs its Newton actuators in the step (:meth:`activate_actuators`).""" self.control_bound = False """Whether the environment's actions and asset writes run as pre-actuator callbacks of every physics step.""" - self.control_every_physics_step = False - """Whether the environment applies an action that must run before every physics step.""" self.pre_actuator_callbacks: list[Callable[[], None]] = [] """Run before the Newton actuators of every physics step.""" self.post_actuator_callbacks: list[Callable[[], None]] = [] @@ -465,8 +463,8 @@ def add_imu_sensor(self, sites: list[int]) -> SensorIMU: return sensor def handles_decimation(self) -> bool: - """Whether one :meth:`step` runs the whole decimation loop: bound control, or actuators with held actions.""" - return self.control_bound or (self.actuators_active and not self.control_every_physics_step) + """Whether one :meth:`step` runs the whole decimation loop: with bound control or Newton actuators.""" + return self.control_bound or self.actuators_active def set_decimation(self, decimation: int) -> None: """Set the physics steps per environment step.""" diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index 15e2a864a72b..7cfbb945b22b 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -620,13 +620,11 @@ def bind_control(self, actions: ActionManager, scene: InteractiveScene) -> bool: def _bind_control(self) -> None: """Register the bound control on the current backend, in the environment's order.""" actions, scene = self._control - backend = self.backend - backend.control_every_physics_step = actions.apply_every_physics_step if not (actions.supports_graph_capture and scene.supports_graph_capture): return self.register_pre_actuator_callback(actions.apply_action) self.register_pre_actuator_callback(scene.write_data_to_sim) - backend.control_bound = True + self.backend.control_bound = True def add_contact_sensor( self, diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index 2ac86c1c0d7b..11570ac06dce 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -283,7 +283,6 @@ def check_step(self, captured, debug): actuators=None, actuators_active=False, control_bound=False, - control_every_physics_step=False, contact_sensors={}, imu_sensors=[], world_mask=wp.zeros(2, dtype=wp.bool, device=device), @@ -945,7 +944,6 @@ def _bound_control(manager: NewtonManager, *, graphable: bool): applied = [] actions = SimpleNamespace( supports_graph_capture=graphable, - apply_every_physics_step=True, apply_action=lambda: ( applied.append("action"), wp.launch(_damp_body, 1, inputs=[manager.backend.state_0.body_qd, manager.backend.state_0.body_f]), @@ -968,7 +966,6 @@ def test_bound_control_runs_before_every_physics_step_like_the_environment_loop( builder.add_body(mass=1.0) sim.reset() manager = sim.backend_manager - manager.activate_newton_actuator_path() manager.set_decimation(decimation) actions, scene, applied = _bound_control(manager, graphable=bound) assert manager.bind_control(actions, scene) is bound diff --git a/source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.changed.rst b/source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.changed.rst deleted file mode 100644 index d028f92d0799..000000000000 --- a/source/isaaclab_tasks/changelog.d/newton-redesign-3-env-control.changed.rst +++ /dev/null @@ -1,2 +0,0 @@ -* Changed the MicroDuck encoder-bias joint position action to hold its command for the whole environment step, so - Newton still ran the decimation loop in one step. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/microduck/mdp/actions.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/microduck/mdp/actions.py index 2dd0047d33da..318c89aa308b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/microduck/mdp/actions.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/microduck/mdp/actions.py @@ -22,8 +22,6 @@ class BiasedJointPositionAction(JointPositionAction): """Joint position action that compensates the joint-encoder calibration error.""" - apply_every_physics_step = False - cfg: BiasedJointPositionActionCfg """The configuration of the action term.""" From 697f1f85a4ba6756891d8d6852ad3db413330dac Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Sat, 7 Nov 2026 17:37:17 -0800 Subject: [PATCH 12/21] Rename supports_graph_capture to is_graphable --- .../developer-tools/extending_newton_solvers.rst | 2 +- .../newton-redesign-3-env-control.added.rst | 2 +- .../isaaclab/isaaclab/actuators/actuator_collection.py | 2 +- source/isaaclab/isaaclab/assets/asset_base.py | 2 +- .../isaaclab/envs/mdp/actions/binary_joint_actions.py | 6 +++--- .../isaaclab/envs/mdp/actions/joint_actions.py | 6 +++--- .../envs/mdp/actions/joint_actions_to_limits.py | 2 +- source/isaaclab/isaaclab/managers/action_manager.py | 8 ++++---- source/isaaclab/isaaclab/scene/interactive_scene.py | 4 ++-- source/isaaclab/test/envs/mdp/test_actions.py | 10 +++++----- .../assets/articulation/articulation.py | 4 ++-- .../assets/rigid_object/rigid_object.py | 2 +- .../rigid_object_collection/rigid_object_collection.py | 2 +- .../isaaclab_newton/physics/newton_manager.py | 2 +- .../test/physics/test_newton_manager.py | 4 ++-- 15 files changed, 29 insertions(+), 29 deletions(-) diff --git a/docs/source/developer-tools/extending_newton_solvers.rst b/docs/source/developer-tools/extending_newton_solvers.rst index 2d0ed477b197..9fcc948ffc51 100644 --- a/docs/source/developer-tools/extending_newton_solvers.rst +++ b/docs/source/developer-tools/extending_newton_solvers.rst @@ -135,7 +135,7 @@ around each physics step's substeps. :meth:`~isaaclab_newton.physics.NewtonManager.bind_control` makes the action manager's ``apply_action`` and the scene's ``write_data_to_sim`` pre-actuator callbacks, so they run before every physics step as in the environment's own loop. Before them, the post-step callbacks republish the asset state they read, and after them, the step stages -the body forces they write. It binds only when both report ``supports_graph_capture``. The first wrench written to an +the body forces they write. It binds only when both report ``is_graphable``. The first wrench written to an asset captures the step again with the wrench work. Every physics step ends in ``state_0``, so ``manager.backend.state_0`` is always the same object. The captured step diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index e2c10c6b0c58..e7812cb23487 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -4,7 +4,7 @@ term recorded after every physics step, or a sensor sampled more often than once per environment step, and skipped the actions and asset writes that the step ran. * Added :attr:`RecorderManager.records_physics_steps `. -* Added ``supports_graph_capture`` to :class:`~isaaclab.managers.ActionTerm`, +* Added ``is_graphable`` to :class:`~isaaclab.managers.ActionTerm`, :class:`~isaaclab.managers.ActionManager`, :class:`~isaaclab.assets.AssetBase`, :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`. Joint, joint-to-limits and binary joint action terms set it. A subclass that overrode :meth:`~isaaclab.managers.ActionTerm.apply_actions` diff --git a/source/isaaclab/isaaclab/actuators/actuator_collection.py b/source/isaaclab/isaaclab/actuators/actuator_collection.py index 7d5de92963e8..93302010b237 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_collection.py +++ b/source/isaaclab/isaaclab/actuators/actuator_collection.py @@ -161,7 +161,7 @@ def device(self) -> str: return self._control.device @property - def supports_graph_capture(self) -> bool: + def is_graphable(self) -> bool: """Whether :meth:`compute` can be recorded into a CUDA graph: no Isaac Lab actuator model runs in Torch.""" return not self._execution_actuators diff --git a/source/isaaclab/isaaclab/assets/asset_base.py b/source/isaaclab/isaaclab/assets/asset_base.py index f15606753023..1b93dfd10a5c 100644 --- a/source/isaaclab/isaaclab/assets/asset_base.py +++ b/source/isaaclab/isaaclab/assets/asset_base.py @@ -78,7 +78,7 @@ class AssetBase(Asset, ABC): _check_shapes: bool = __debug__ """Class-level default for shape validation. Overridden per-instance in ``__init__``.""" - supports_graph_capture: ClassVar[bool] = False + is_graphable: ClassVar[bool] = False """Whether :meth:`write_data_to_sim` can be recorded into a CUDA graph.""" def __init__(self, cfg: AssetBaseCfg): diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py index ecf26d92b603..d6a32939a384 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py @@ -148,7 +148,7 @@ def reset(self, env_ids: Sequence[int] | None = None) -> None: class BinaryJointPositionAction(BinaryJointAction): """Binary joint action that sets the binary action into joint position targets.""" - supports_graph_capture = True + is_graphable = True cfg: actions_cfg.BinaryJointPositionActionCfg """The configuration of the action term.""" @@ -160,7 +160,7 @@ def apply_actions(self): class BinaryJointVelocityAction(BinaryJointAction): """Binary joint action that sets the binary action into joint velocity targets.""" - supports_graph_capture = True + is_graphable = True cfg: actions_cfg.BinaryJointVelocityActionCfg """The configuration of the action term.""" @@ -178,7 +178,7 @@ class AbsBinaryJointPositionAction(BinaryJointAction): closed joint-position target. """ - supports_graph_capture = True + is_graphable = True cfg: actions_cfg.AbsBinaryJointPositionActionCfg """The configuration of the action term.""" diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py index 495fb8a6799f..d2e458d60ebe 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py @@ -183,7 +183,7 @@ def reset(self, env_ids: Sequence[int] | None = None) -> None: class JointPositionAction(JointAction): """Joint action term that applies the processed actions to the articulation's joints as position commands.""" - supports_graph_capture = True + is_graphable = True cfg: actions_cfg.JointPositionActionCfg """The configuration of the action term.""" @@ -236,7 +236,7 @@ def apply_actions(self): class JointVelocityAction(JointAction): """Joint action term that applies the processed actions to the articulation's joints as velocity commands.""" - supports_graph_capture = True + is_graphable = True cfg: actions_cfg.JointVelocityActionCfg """The configuration of the action term.""" @@ -256,7 +256,7 @@ def apply_actions(self): class JointEffortAction(JointAction): """Joint action term that applies the processed actions to the articulation's joints as effort commands.""" - supports_graph_capture = True + is_graphable = True cfg: actions_cfg.JointEffortActionCfg """The configuration of the action term.""" diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py index 1d984f502688..27c10a7a619b 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py @@ -41,7 +41,7 @@ class JointPositionToLimitsAction(ActionTerm): The processed actions are then sent as position commands to the articulation's joints. """ - supports_graph_capture = True + is_graphable = True cfg: actions_cfg.JointPositionToLimitsActionCfg """The configuration of the action term.""" diff --git a/source/isaaclab/isaaclab/managers/action_manager.py b/source/isaaclab/isaaclab/managers/action_manager.py index b4131788a67c..72d40e46bec5 100644 --- a/source/isaaclab/isaaclab/managers/action_manager.py +++ b/source/isaaclab/isaaclab/managers/action_manager.py @@ -39,14 +39,14 @@ class ActionTerm(ManagerTermBase): responsible for applying the processed actions to the asset managed by the term. """ - supports_graph_capture: ClassVar[bool] = False + is_graphable: ClassVar[bool] = False """Whether :meth:`apply_actions` can be recorded into a CUDA graph, i.e. it writes from fixed buffers.""" def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) # A subclass that overrides apply_actions declares its own flag; it does not inherit it. if "apply_actions" in cls.__dict__: - cls.supports_graph_capture = cls.__dict__.get("supports_graph_capture", False) + cls.is_graphable = cls.__dict__.get("is_graphable", False) def __init__(self, cfg: ActionTermCfg, env: ManagerBasedEnv): """Initialize the action term. @@ -287,9 +287,9 @@ def prev_action(self) -> torch.Tensor: return self._prev_action @property - def supports_graph_capture(self) -> bool: + def is_graphable(self) -> bool: """Whether :meth:`apply_action` can be recorded into a CUDA graph.""" - return all(term.supports_graph_capture for term in self._terms.values()) + return all(term.is_graphable for term in self._terms.values()) @property def has_debug_vis_implementation(self) -> bool: diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index 787d381196a7..1c0fa1335909 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -412,7 +412,7 @@ def state(self) -> dict[str, dict[str, dict[str, torch.Tensor]]]: return self.get_state(is_relative=False) @property - def supports_graph_capture(self) -> bool: + def is_graphable(self) -> bool: """Whether :meth:`write_data_to_sim` can be recorded into a CUDA graph.""" writers = ( self._articulations, @@ -422,7 +422,7 @@ def supports_graph_capture(self) -> bool: self._surface_grippers, self._rigid_object_collections, ) - return all(asset.supports_graph_capture for assets in writers for asset in assets.values()) + return all(asset.is_graphable for assets in writers for asset in assets.values()) """ Operations. diff --git a/source/isaaclab/test/envs/mdp/test_actions.py b/source/isaaclab/test/envs/mdp/test_actions.py index 59039b1f1079..04f5c56ef672 100644 --- a/source/isaaclab/test/envs/mdp/test_actions.py +++ b/source/isaaclab/test/envs/mdp/test_actions.py @@ -252,7 +252,7 @@ def test_recordable_joint_actions_process_into_the_same_buffer(action_cls, cfg) """A step that records ``apply_actions`` reads the processed buffer, so processing writes it in place.""" cfg.asset_name, cfg.joint_names = "robot", [".*"] action = action_cls(cfg, _make_env(["a", "b"])) - assert action_cls.supports_graph_capture + assert action_cls.is_graphable processed = action.processed_actions action.process_actions(torch.full((2, action.action_dim), -0.25)) @@ -269,7 +269,7 @@ def apply_actions(self): pass class Declares(Applies): - supports_graph_capture = True + is_graphable = True def apply_actions(self): pass @@ -278,6 +278,6 @@ class Processes(JointEffortAction): def process_actions(self, actions): super().process_actions(actions) - assert not Applies.supports_graph_capture - assert Declares.supports_graph_capture - assert Processes.supports_graph_capture + assert not Applies.is_graphable + assert Declares.is_graphable + assert Processes.is_graphable diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py index b6e5c43557e5..7dd05d8e344e 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py @@ -363,9 +363,9 @@ def permanent_wrench_composer(self) -> WrenchComposer: return self._permanent_wrench_composer @property - def supports_graph_capture(self) -> bool: + def is_graphable(self) -> bool: """Whether :meth:`write_data_to_sim` can be recorded: no Torch actuators and no fixed tendons.""" - return self.actuators.supports_graph_capture and self._fixed_tendon_control is None + return self.actuators.is_graphable and self._fixed_tendon_control is None """ Operations. diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py index d2c3e5ec1441..62de70a1710b 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object.py @@ -51,7 +51,7 @@ class RigidObject(BaseRigidObject): __backend_name__: str = "newton" """The name of the backend for the rigid object.""" - supports_graph_capture = True + is_graphable = True def __init__(self, cfg: RigidObjectCfg): """Initialize the rigid object. diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py index 2383ac320350..84ddad4958c9 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection.py @@ -60,7 +60,7 @@ class RigidObjectCollection(BaseRigidObjectCollection): __backend_name__: str = "newton" """The name of the backend for the rigid object.""" - supports_graph_capture = True + is_graphable = True def __init__(self, cfg: RigidObjectCollectionCfg): """Initialize the rigid object collection. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index 7cfbb945b22b..52a5568ff967 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -620,7 +620,7 @@ def bind_control(self, actions: ActionManager, scene: InteractiveScene) -> bool: def _bind_control(self) -> None: """Register the bound control on the current backend, in the environment's order.""" actions, scene = self._control - if not (actions.supports_graph_capture and scene.supports_graph_capture): + if not (actions.is_graphable and scene.is_graphable): return self.register_pre_actuator_callback(actions.apply_action) self.register_pre_actuator_callback(scene.write_data_to_sim) diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index 11570ac06dce..8e2d53166889 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -943,13 +943,13 @@ def _bound_control(manager: NewtonManager, *, graphable: bool): """Actions that damp a free body, and an empty scene; both support graph capture when ``graphable``.""" applied = [] actions = SimpleNamespace( - supports_graph_capture=graphable, + is_graphable=graphable, apply_action=lambda: ( applied.append("action"), wp.launch(_damp_body, 1, inputs=[manager.backend.state_0.body_qd, manager.backend.state_0.body_f]), ), ) - scene = SimpleNamespace(supports_graph_capture=True, write_data_to_sim=lambda: None) + scene = SimpleNamespace(is_graphable=True, write_data_to_sim=lambda: None) return actions, scene, applied From dfdf54f48f0bc6eb2a87f930c80ac683f34ab02d Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 9 Nov 2026 10:56:59 -0800 Subject: [PATCH 13/21] Keep post-step callbacks, sensor cadence and custom action processing unchanged under bound control --- .../extending_newton_solvers.rst | 6 +-- .../newton-redesign-3-env-control.added.rst | 8 ++-- .../isaaclab/envs/manager_based_env.py | 13 +++++-- .../mdp/actions/joint_actions_to_limits.py | 2 + .../isaaclab/managers/action_manager.py | 6 +-- source/isaaclab/test/envs/mdp/test_actions.py | 20 ++++++---- .../newton-redesign-3-env-control.added.rst | 5 ++- .../assets/articulation/articulation.py | 3 ++ .../isaaclab_newton/physics/newton_backend.py | 4 -- .../isaaclab_newton/physics/newton_manager.py | 3 +- .../test/assets/test_articulation.py | 37 +++++++++++++++++++ .../test/physics/test_newton_manager.py | 6 +-- .../contrib/franka_pour/mdp/actions.py | 2 + 13 files changed, 82 insertions(+), 33 deletions(-) diff --git a/docs/source/developer-tools/extending_newton_solvers.rst b/docs/source/developer-tools/extending_newton_solvers.rst index 9fcc948ffc51..44b493b8ab1f 100644 --- a/docs/source/developer-tools/extending_newton_solvers.rst +++ b/docs/source/developer-tools/extending_newton_solvers.rst @@ -134,9 +134,9 @@ around each physics step's substeps. :meth:`~isaaclab_newton.physics.NewtonManager.bind_control` makes the action manager's ``apply_action`` and the scene's ``write_data_to_sim`` pre-actuator callbacks, so they run before every physics step as in the environment's -own loop. Before them, the post-step callbacks republish the asset state they read, and after them, the step stages -the body forces they write. It binds only when both report ``is_graphable``. The first wrench written to an -asset captures the step again with the wrench work. +own loop, and the step stages the body forces they write. Post-step callbacks still run once at the end of the step, +so articulations republish the reordered state they read before writing. It binds only when both report +``is_graphable``. The first wrench written to an asset captures the step again with the wrench work. Every physics step ends in ``state_0``, so ``manager.backend.state_0`` is always the same object. The captured step records the callbacks, so they must be graph-safe. Consumers register them with diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index e7812cb23487..7b5f253a49c3 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,14 +1,14 @@ * Added :meth:`PhysicsManager.bind_control `, which let a physics backend run the environment's actions and asset writes inside its step. :class:`~isaaclab.envs.ManagerBasedEnv` called it after loading its managers, unless its render interval was not a multiple of the decimation, a recorder - term recorded after every physics step, or a sensor sampled more often than once per environment step, and skipped - the actions and asset writes that the step ran. + term recorded after every physics step, or a sensor sampled at times other than whole environment steps, and + skipped the actions and asset writes that the step ran. * Added :attr:`RecorderManager.records_physics_steps `. * Added ``is_graphable`` to :class:`~isaaclab.managers.ActionTerm`, :class:`~isaaclab.managers.ActionManager`, :class:`~isaaclab.assets.AssetBase`, :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`. Joint, joint-to-limits - and binary joint action terms set it. A subclass that overrode :meth:`~isaaclab.managers.ActionTerm.apply_actions` - did not inherit it. + and binary joint action terms set it. A subclass that overrode :meth:`~isaaclab.managers.ActionTerm.process_actions` + or :meth:`~isaaclab.managers.ActionTerm.apply_actions` did not inherit it. * Added :attr:`WrenchComposer.pending ` and the ``on_first_use`` argument of :class:`~isaaclab.utils.wrench_composer.WrenchComposer`, called at the first force write or :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.add_raw_buffers_from` merge. Once forces were written, diff --git a/source/isaaclab/isaaclab/envs/manager_based_env.py b/source/isaaclab/isaaclab/envs/manager_based_env.py index a91442bbd2a1..2232b6dfa96e 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env.py @@ -7,6 +7,7 @@ import builtins import logging +import math import sys import warnings from typing import Any @@ -210,10 +211,14 @@ def _init_sim(self): # let the physics backend run the actions, asset writes and decimation loop inside its step when it can, # unless renders, recorders or sensors must run between the physics steps of one environment step eager_sensors = not self.scene.cfg.lazy_sensor_update - sensors_sample_physics_steps = any( - (eager_sensors or getattr(sensor.cfg, "history_length", 0) > 0) and sensor.cfg.update_period < self.step_dt - for sensor in self.scene.sensors.values() - ) + sensors_sample_physics_steps = False + for sensor in self.scene.sensors.values(): + # a sensor that refreshes on update samples between env steps unless its period spans whole env steps + periods = sensor.cfg.update_period / self.step_dt + if (eager_sensors or getattr(sensor.cfg, "history_length", 0) > 0) and ( + round(periods) == 0 or not math.isclose(periods, round(periods), abs_tol=1e-6) + ): + sensors_sample_physics_steps = True if ( self.cfg.sim.render_interval % self.cfg.decimation == 0 and not self.recorder_manager.records_physics_steps diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py index 27c10a7a619b..aa4614807a7f 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py @@ -205,6 +205,8 @@ class EMAJointPositionToLimitsAction(JointPositionToLimitsAction): On reset, the previous action is initialized to the current joint positions of the articulation's joints. """ + is_graphable = True + cfg: actions_cfg.EMAJointPositionToLimitsActionCfg """The configuration of the action term.""" diff --git a/source/isaaclab/isaaclab/managers/action_manager.py b/source/isaaclab/isaaclab/managers/action_manager.py index 72d40e46bec5..790ce3613e30 100644 --- a/source/isaaclab/isaaclab/managers/action_manager.py +++ b/source/isaaclab/isaaclab/managers/action_manager.py @@ -40,12 +40,12 @@ class ActionTerm(ManagerTermBase): """ is_graphable: ClassVar[bool] = False - """Whether :meth:`apply_actions` can be recorded into a CUDA graph, i.e. it writes from fixed buffers.""" + """Whether :meth:`apply_actions` can be recorded into a CUDA graph: it writes from buffers updated in place.""" def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) - # A subclass that overrides apply_actions declares its own flag; it does not inherit it. - if "apply_actions" in cls.__dict__: + # A subclass that overrides how actions are processed or applied declares its own flag; it does not inherit it. + if "apply_actions" in cls.__dict__ or "process_actions" in cls.__dict__: cls.is_graphable = cls.__dict__.get("is_graphable", False) def __init__(self, cfg: ActionTermCfg, env: ManagerBasedEnv): diff --git a/source/isaaclab/test/envs/mdp/test_actions.py b/source/isaaclab/test/envs/mdp/test_actions.py index 04f5c56ef672..55573c3b564a 100644 --- a/source/isaaclab/test/envs/mdp/test_actions.py +++ b/source/isaaclab/test/envs/mdp/test_actions.py @@ -261,23 +261,27 @@ def test_recordable_joint_actions_process_into_the_same_buffer(action_cls, cfg) assert torch.all(processed < 0.0) -def test_subclass_overriding_apply_actions_does_not_inherit_capture_flags() -> None: - """A subclass with its own ``apply_actions`` is not recorded unless it says so.""" +def test_subclass_overriding_action_methods_does_not_inherit_is_graphable() -> None: + """A subclass with its own ``process_actions`` or ``apply_actions`` is not recorded unless it says so.""" class Applies(JointEffortAction): def apply_actions(self): pass - class Declares(Applies): - is_graphable = True + class Processes(JointEffortAction): + def process_actions(self, actions): + self._processed_actions = actions.clamp(-1.0, 1.0) - def apply_actions(self): - pass + class Declares(Processes): + is_graphable = True - class Processes(JointEffortAction): def process_actions(self, actions): super().process_actions(actions) + class Inherits(JointEffortAction): + pass + assert not Applies.is_graphable + assert not Processes.is_graphable assert Declares.is_graphable - assert Processes.is_graphable + assert Inherits.is_graphable diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst index 622f7e3763b1..07d2e3706486 100644 --- a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,5 +1,6 @@ * Added :meth:`NewtonManager.bind_control `. When every action term and written asset could be recorded, the environment's actions and asset writes ran as pre-actuator callbacks before every physics step, and one step advanced the whole decimation loop. Hard resets bound them again. -* Added ``NewtonBackend.control_bound``. With bound control, every physics step ran the post-step callbacks before the - asset writes, so they read the current reordered state, and staged the body forces that the writes produced. +* Added ``NewtonBackend.control_bound``. With bound control, every physics step staged the body forces that the asset + writes produced, and reordered or ball-jointed articulations republished their state before writing, so the writes + read the current physics step. diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py index 7dd05d8e344e..3e4af479ed1e 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py @@ -401,6 +401,9 @@ def write_data_to_sim(self): We write external wrench to the simulation here since this function is called before the simulation step. This ensures that the external wrench is applied at every simulation step. """ + if self._post_step_callback is not None and self._backend_manager.backend.control_bound: + # bound writes run between physics steps, before the post-step callbacks republish the reordered state + self._post_step_callback() # write external wrench if self._instantaneous_wrench_composer.pending or self._permanent_wrench_composer.pending: if self._instantaneous_wrench_composer.pending: diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index b692f6379122..0590ae90f868 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -623,10 +623,6 @@ def _before_actuators(self) -> None: self.solver_ops.pre_step(self.state_0) if self.collision_pipeline is not None: self.collision_pipeline.collide(self.state_0, self.contacts) - if self.control_bound: - # bound asset writes read the state that the post-step callbacks publish - for callback in self.post_step_callbacks: - callback() for callback in self.pre_actuator_callbacks: callback() if self.control_bound: diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index 52a5568ff967..f1b42869d0a2 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -573,8 +573,7 @@ def register_state_force_callback(self, callback: Callable[[State], None]) -> No def register_post_step_callback(self, callback: Callable[[], None]) -> None: """Append a hook invoked once per :meth:`step`, after the last solver substep and before sensors update. - The hook reflects the state after all decimation iterations of the step; with bound control it also runs before - every physics step, ahead of the bound writes. Callbacks must be graph-safe (fixed + The hook reflects the state after all decimation iterations of the step. Callbacks must be graph-safe (fixed shapes, no host branching on device data) because they are recorded into the captured step. Hard resets discard these hooks; register them again when the new model is ready. """ diff --git a/source/isaaclab_newton/test/assets/test_articulation.py b/source/isaaclab_newton/test/assets/test_articulation.py index d434eabf300e..39d9fc16c260 100644 --- a/source/isaaclab_newton/test/assets/test_articulation.py +++ b/source/isaaclab_newton/test/assets/test_articulation.py @@ -837,6 +837,43 @@ def test_newton_ordered_state_publishes_inside_captured_cuda_graph(device: str) np.testing.assert_allclose(sampled_heading.numpy(), yaw, atol=1e-5) +@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) +def test_bound_writes_read_the_reordered_state_of_the_current_physics_step(device: str) -> None: + """A bound asset write runs between the physics steps of one step and reads the current reordered body poses.""" + articulation_cfg = ArticulationCfg( + prim_path="/World/Env_[^/]*/Robot", + spawn=local_usd("floating_two_leg.usda"), + init_state=ArticulationCfg.InitialStateCfg(pos=(0.0, 0.0, 1.0)), + actuators={"legs": ImplicitActuatorCfg(joint_names_expr=[".*"], stiffness=40.0, damping=5.0)}, + joint_ordering=_LEG_PUBLIC_JOINT_NAMES, + body_ordering=_LEG_PUBLIC_BODY_NAMES, + ) + sim_cfg = newton_sim_cfg(device, use_newton_actuators=False, use_cuda_graph=True) + with build_simulation_context(sim_cfg=sim_cfg) as sim: + articulation = spawn_assets({"robot": articulation_cfg})["robot"] + sim.reset() + data = articulation.data + body_u2b = np.asarray(articulation.body_ordering.user_to_backend_indices) + read, backend = wp.clone(data._body_link_pose_w_user), wp.clone(data._sim_bind_body_link_pose_w) + + def write_data_to_sim(): + articulation.write_data_to_sim() + wp.copy(read, data._body_link_pose_w_user) + wp.copy(backend, data._sim_bind_body_link_pose_w) + + manager = sim.backend_manager + manager.set_decimation(3) + actions = SimpleNamespace(is_graphable=True, apply_action=lambda: None) + assert manager.bind_control(actions, SimpleNamespace(is_graphable=True, write_data_to_sim=write_data_to_sim)) + # a spinning robot moves during the step, so a pose from before the step cannot pass for the current one + spin = torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0, 5.0]], device=device).repeat(articulation.num_instances, 1) + articulation.write_root_velocity_to_sim_index(root_velocity=spin) + for _ in range(3): + sim.step(render=False) + assert not np.allclose(backend.numpy()[:, body_u2b], data._body_link_pose_w_user.numpy()) + np.testing.assert_allclose(read.numpy(), backend.numpy()[:, body_u2b]) + + ## # Composite scene. ## diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index 8e2d53166889..ad44636b1054 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -956,7 +956,7 @@ def _bound_control(manager: NewtonManager, *, graphable: bool): def test_bound_control_runs_before_every_physics_step_like_the_environment_loop(): """Bound actions run before every physics step of one captured step, also after a hard reset, like the env loop. - Each bound action reads the state that the post-step callbacks publish after the previous physics step. + The post-step callbacks still run once per step, after its last physics step. """ decimation, num_steps, velocities = 3, 4, [] for bound in (True, False): @@ -982,9 +982,9 @@ def test_bound_control_runs_before_every_physics_step_like_the_environment_loop( if not bound: actions.apply_action() sim.step(render=False) - # bound steps record the actions after the published state of every physics step, then replay them + # bound steps record the actions once per physics step and then replay them if bound: - assert applied == (["publish", "action"] * decimation + ["publish"]) * 2 + assert applied == (["action"] * decimation + ["publish"]) * 2 else: assert applied.count("action") == num_steps * decimation velocities.append(manager.backend.state_0.body_qd.numpy().copy()) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py index a6809d0966cf..64acc5f5de21 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py @@ -56,6 +56,8 @@ def reset(self, env_ids: Sequence[int] | torch.Tensor | slice | None = None) -> class CurriculumGripperPositionAction(BinaryJointPositionAction): """Filtered binary symmetric finger-position command with grasp-contact state.""" + is_graphable = True + cfg: CurriculumGripperPositionActionCfg def __init__(self, cfg: CurriculumGripperPositionActionCfg, env: ManagerBasedEnv) -> None: From c1262c0b0f0712be0cf2ff771cbb59e2aa6af52f Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 9 Nov 2026 11:14:25 -0800 Subject: [PATCH 14/21] Rename control_bound to handles_actions and bind_control to handle_actions --- .../extending_newton_solvers.rst | 8 +++--- .../newton-redesign-3-env-control.added.rst | 2 +- .../isaaclab/envs/manager_based_env.py | 2 +- .../isaaclab/physics/physics_manager.py | 4 +-- .../newton-redesign-3-env-control.added.rst | 10 +++---- .../newton-redesign-3-env-control.changed.rst | 2 +- .../assets/articulation/articulation.py | 4 +-- .../isaaclab_newton/physics/newton_backend.py | 10 +++---- .../isaaclab_newton/physics/newton_manager.py | 26 +++++++++---------- .../test/assets/test_articulation.py | 6 ++--- .../test/physics/test_newton_manager.py | 26 +++++++++---------- 11 files changed, 50 insertions(+), 50 deletions(-) diff --git a/docs/source/developer-tools/extending_newton_solvers.rst b/docs/source/developer-tools/extending_newton_solvers.rst index 44b493b8ab1f..d9d704cf69e6 100644 --- a/docs/source/developer-tools/extending_newton_solvers.rst +++ b/docs/source/developer-tools/extending_newton_solvers.rst @@ -125,17 +125,17 @@ The Step -------- Each :meth:`~isaaclab_newton.physics.NewtonManager.step` covers the whole decimation loop when the manager handles -decimation (:meth:`~isaaclab_newton.physics.NewtonManager.handles_decimation`: the environment's control is bound to -the step, or an articulation runs its Newton actuators in the step), and one physics step otherwise. Every physics step +decimation (:meth:`~isaaclab_newton.physics.NewtonManager.handles_decimation`: the step handles the environment's +actions, or an articulation runs its Newton actuators in the step), and one physics step otherwise. Every physics step runs ``collide -> pre-actuator callbacks -> Newton actuators -> post-actuator callbacks -> substeps``, and post-step callbacks and sensors run once at the end. Every substep runs ``staged body forces -> state-force callbacks -> step``, and ``pre_step`` and ``post_step`` run around each physics step's substeps. -:meth:`~isaaclab_newton.physics.NewtonManager.bind_control` makes the action manager's ``apply_action`` and the +:meth:`~isaaclab_newton.physics.NewtonManager.handle_actions` makes the action manager's ``apply_action`` and the scene's ``write_data_to_sim`` pre-actuator callbacks, so they run before every physics step as in the environment's own loop, and the step stages the body forces they write. Post-step callbacks still run once at the end of the step, -so articulations republish the reordered state they read before writing. It binds only when both report +so articulations republish the reordered state they read before writing. It does so only when both report ``is_graphable``. The first wrench written to an asset captures the step again with the wrench work. Every physics step ends in ``state_0``, so ``manager.backend.state_0`` is always the same object. The captured step diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index 7b5f253a49c3..0a2b0234540e 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,4 +1,4 @@ -* Added :meth:`PhysicsManager.bind_control `, which let a physics +* Added :meth:`PhysicsManager.handle_actions `, which let a physics backend run the environment's actions and asset writes inside its step. :class:`~isaaclab.envs.ManagerBasedEnv` called it after loading its managers, unless its render interval was not a multiple of the decimation, a recorder term recorded after every physics step, or a sensor sampled at times other than whole environment steps, and diff --git a/source/isaaclab/isaaclab/envs/manager_based_env.py b/source/isaaclab/isaaclab/envs/manager_based_env.py index 2232b6dfa96e..d3b3d422273c 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env.py @@ -224,7 +224,7 @@ def _init_sim(self): and not self.recorder_manager.records_physics_steps and not sensors_sample_physics_steps ): - self._physics_handles_actions = self.sim.backend_manager.bind_control(self.action_manager, self.scene) + self._physics_handles_actions = self.sim.backend_manager.handle_actions(self.action_manager, self.scene) self.sim.backend_manager.set_decimation(self.cfg.decimation) self._physics_handles_decimation = self.sim.backend_manager.handles_decimation() diff --git a/source/isaaclab/isaaclab/physics/physics_manager.py b/source/isaaclab/isaaclab/physics/physics_manager.py index cf0e7d3c6cac..85b4cd9384be 100644 --- a/source/isaaclab/isaaclab/physics/physics_manager.py +++ b/source/isaaclab/isaaclab/physics/physics_manager.py @@ -671,10 +671,10 @@ def handles_decimation(self) -> bool: """ return False - def bind_control(self, actions: ActionManager, scene: InteractiveScene) -> bool: + def handle_actions(self, actions: ActionManager, scene: InteractiveScene) -> bool: """Run the environment's actions and asset writes inside :meth:`step`, before every physics step. - The default implementation binds nothing. + The default implementation handles nothing. Args: actions: Environment action manager. diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst index 07d2e3706486..7e119ac260f0 100644 --- a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,6 +1,6 @@ -* Added :meth:`NewtonManager.bind_control `. When every action +* Added :meth:`NewtonManager.handle_actions `. When every action term and written asset could be recorded, the environment's actions and asset writes ran as pre-actuator callbacks - before every physics step, and one step advanced the whole decimation loop. Hard resets bound them again. -* Added ``NewtonBackend.control_bound``. With bound control, every physics step staged the body forces that the asset - writes produced, and reordered or ball-jointed articulations republished their state before writing, so the writes - read the current physics step. + before every physics step, and one step advanced the whole decimation loop. Hard resets registered them again. +* Added ``NewtonBackend.handles_actions``. When the step handled actions, every physics step staged the body forces + that the asset writes produced, and reordered or ball-jointed articulations republished their state before writing, + so the writes read the current physics step. diff --git a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst index 3df42cf6a2ba..add6b5fa01ec 100644 --- a/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst +++ b/source/isaaclab_newton/changelog.d/newton-redesign-3-env-control.changed.rst @@ -1,4 +1,4 @@ * Changed :meth:`NewtonBackend.handles_decimation ` to also - run the decimation loop in one step when the environment's control is bound. + run the decimation loop in one step when it handled the environment's actions. * Changed Newton articulations, rigid objects and rigid object collections to record their wrench work into a captured step only once a wrench composer was used, which captured the step again. diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py index 3e4af479ed1e..ccaba56d1b59 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py @@ -401,8 +401,8 @@ def write_data_to_sim(self): We write external wrench to the simulation here since this function is called before the simulation step. This ensures that the external wrench is applied at every simulation step. """ - if self._post_step_callback is not None and self._backend_manager.backend.control_bound: - # bound writes run between physics steps, before the post-step callbacks republish the reordered state + if self._post_step_callback is not None and self._backend_manager.backend.handles_actions: + # handled writes run between physics steps, before the post-step callbacks republish the reordered state self._post_step_callback() # write external wrench if self._instantaneous_wrench_composer.pending or self._permanent_wrench_composer.pending: diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index 0590ae90f868..6c1bc7bd2e44 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -210,7 +210,7 @@ def __init__(self, cfg: NewtonBackendCfg, builder: ModelBuilder | None = None, * """Newton actuators run inside the step, or ``None``.""" self.actuators_active = False """Whether an articulation runs its Newton actuators in the step (:meth:`activate_actuators`).""" - self.control_bound = False + self.handles_actions = False """Whether the environment's actions and asset writes run as pre-actuator callbacks of every physics step.""" self.pre_actuator_callbacks: list[Callable[[], None]] = [] """Run before the Newton actuators of every physics step.""" @@ -463,8 +463,8 @@ def add_imu_sensor(self, sites: list[int]) -> SensorIMU: return sensor def handles_decimation(self) -> bool: - """Whether one :meth:`step` runs the whole decimation loop: with bound control or Newton actuators.""" - return self.control_bound or self.actuators_active + """Whether one :meth:`step` runs the whole decimation loop: when it handles actions or runs Newton actuators.""" + return self.handles_actions or self.actuators_active def set_decimation(self, decimation: int) -> None: """Set the physics steps per environment step.""" @@ -625,8 +625,8 @@ def _before_actuators(self) -> None: self.collision_pipeline.collide(self.state_0, self.contacts) for callback in self.pre_actuator_callbacks: callback() - if self.control_bound: - # bound asset writes replace the body forces staged before the step + if self.handles_actions: + # the asset writes replace the body forces staged before the step self._stage_body_forces() def _after_actuators(self, observables: SolverBase.Observables | None) -> None: diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index f1b42869d0a2..e8b08b5990a3 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -233,7 +233,7 @@ def clear(self): """Clear all Newton-specific state (callbacks cleared by super().close()).""" self._close_backend(dispatch_stop=False) self._decimation = 1 - self._control: tuple[ActionManager, InteractiveScene] | None = None + self._handled_actions: tuple[ActionManager, InteractiveScene] | None = None # Site requests and replication outputs survive hard resets. # (body_pattern, per_world, xform floats) -> (label, transform) self._site_requests: dict[tuple[str | None, bool, tuple[float, ...]], tuple[str, wp.transform]] = {} @@ -493,8 +493,8 @@ def initialize_solver(self) -> None: device=self.get_device(), ): backend.init_solver(None if plan is None else plan.env_template, relaxed_capture=self._relaxed_capture) - if self._control is not None: - self._bind_control() + if self._handled_actions is not None: + self._handle_actions() self._mark_transforms_changed() def _relaxed_capture(self) -> bool: @@ -599,11 +599,11 @@ def handles_decimation(self) -> bool: """Whether :meth:`step` executes the full decimation loop; see :meth:`NewtonBackend.handles_decimation`.""" return self.backend.handles_decimation() - def bind_control(self, actions: ActionManager, scene: InteractiveScene) -> bool: + def handle_actions(self, actions: ActionManager, scene: InteractiveScene) -> bool: """Run the environment's actions and asset writes as pre-actuator callbacks of every physics step. - Binds only when both support graph capture; one :meth:`step` then advances the whole decimation loop. Hard - resets bind again on the new backend. + Only when both support graph capture; one :meth:`step` then advances the whole decimation loop. Hard resets + register them again on the new backend. Args: actions: Environment action manager. @@ -612,18 +612,18 @@ def bind_control(self, actions: ActionManager, scene: InteractiveScene) -> bool: Returns: Whether the step now applies the actions and writes the assets. """ - self._control = (actions, scene) - self._bind_control() - return self.backend.control_bound + self._handled_actions = (actions, scene) + self._handle_actions() + return self.backend.handles_actions - def _bind_control(self) -> None: - """Register the bound control on the current backend, in the environment's order.""" - actions, scene = self._control + def _handle_actions(self) -> None: + """Register the handled actions and asset writes on the current backend, in the environment's order.""" + actions, scene = self._handled_actions if not (actions.is_graphable and scene.is_graphable): return self.register_pre_actuator_callback(actions.apply_action) self.register_pre_actuator_callback(scene.write_data_to_sim) - self.backend.control_bound = True + self.backend.handles_actions = True def add_contact_sensor( self, diff --git a/source/isaaclab_newton/test/assets/test_articulation.py b/source/isaaclab_newton/test/assets/test_articulation.py index 39d9fc16c260..5faf13a9969e 100644 --- a/source/isaaclab_newton/test/assets/test_articulation.py +++ b/source/isaaclab_newton/test/assets/test_articulation.py @@ -838,8 +838,8 @@ def test_newton_ordered_state_publishes_inside_captured_cuda_graph(device: str) @pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) -def test_bound_writes_read_the_reordered_state_of_the_current_physics_step(device: str) -> None: - """A bound asset write runs between the physics steps of one step and reads the current reordered body poses.""" +def test_handled_writes_read_the_reordered_state_of_the_current_physics_step(device: str) -> None: + """A handled asset write runs between the physics steps of one step and reads the current reordered body poses.""" articulation_cfg = ArticulationCfg( prim_path="/World/Env_[^/]*/Robot", spawn=local_usd("floating_two_leg.usda"), @@ -864,7 +864,7 @@ def write_data_to_sim(): manager = sim.backend_manager manager.set_decimation(3) actions = SimpleNamespace(is_graphable=True, apply_action=lambda: None) - assert manager.bind_control(actions, SimpleNamespace(is_graphable=True, write_data_to_sim=write_data_to_sim)) + assert manager.handle_actions(actions, SimpleNamespace(is_graphable=True, write_data_to_sim=write_data_to_sim)) # a spinning robot moves during the step, so a pose from before the step cannot pass for the current one spin = torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0, 5.0]], device=device).repeat(articulation.num_instances, 1) articulation.write_root_velocity_to_sim_index(root_velocity=spin) diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index ad44636b1054..86bb28e0c57e 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -282,7 +282,7 @@ def check_step(self, captured, debug): solver_dt=0.002 / num_substeps, actuators=None, actuators_active=False, - control_bound=False, + handles_actions=False, contact_sensors={}, imu_sensors=[], world_mask=wp.zeros(2, dtype=wp.bool, device=device), @@ -939,7 +939,7 @@ def _damp_body(body_qd: wp.array(dtype=wp.spatial_vector), body_f: wp.array(dtyp body_f[0] = wp.spatial_vector(0.0, 0.0, -20.0 * body_qd[0][2], 0.0, 0.0, 0.0) -def _bound_control(manager: NewtonManager, *, graphable: bool): +def _handled_actions(manager: NewtonManager, *, graphable: bool): """Actions that damp a free body, and an empty scene; both support graph capture when ``graphable``.""" applied = [] actions = SimpleNamespace( @@ -953,13 +953,13 @@ def _bound_control(manager: NewtonManager, *, graphable: bool): return actions, scene, applied -def test_bound_control_runs_before_every_physics_step_like_the_environment_loop(): - """Bound actions run before every physics step of one captured step, also after a hard reset, like the env loop. +def test_handled_actions_run_before_every_physics_step_like_the_environment_loop(): + """Handled actions run before every physics step of one captured step, also after a hard reset, like the env loop. The post-step callbacks still run once per step, after its last physics step. """ decimation, num_steps, velocities = 3, 4, [] - for bound in (True, False): + for handled in (True, False): sim_cfg = SimulationCfg(dt=0.01, device="cuda:0", physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())) with build_simulation_context(sim_cfg=sim_cfg) as sim: builder = sim.get_or_create_backend(NewtonBuilderCfg(physics_cfg=sim.cfg.physics)) @@ -967,23 +967,23 @@ def test_bound_control_runs_before_every_physics_step_like_the_environment_loop( sim.reset() manager = sim.backend_manager manager.set_decimation(decimation) - actions, scene, applied = _bound_control(manager, graphable=bound) - assert manager.bind_control(actions, scene) is bound - assert manager.handles_decimation() is bound + actions, scene, applied = _handled_actions(manager, graphable=handled) + assert manager.handle_actions(actions, scene) is handled + assert manager.handles_decimation() is handled for reset in (False, True): if reset: sim.reset() - assert manager.backend.control_bound is bound + assert manager.backend.handles_actions is handled # hard resets discard the post-step callbacks manager.register_post_step_callback(lambda: applied.append("publish")) applied.clear() for _ in range(num_steps): - for _ in range(1 if bound else decimation): - if not bound: + for _ in range(1 if handled else decimation): + if not handled: actions.apply_action() sim.step(render=False) - # bound steps record the actions once per physics step and then replay them - if bound: + # steps that handle actions record the actions once per physics step and then replay them + if handled: assert applied == (["action"] * decimation + ["publish"]) * 2 else: assert applied.count("action") == num_steps * decimation From 0d340c5b711feb854f8a8ff18f8810ae1341dbc3 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 9 Nov 2026 11:21:58 -0800 Subject: [PATCH 15/21] Accept joint lookup options in the action test environment --- source/isaaclab/test/envs/mdp/test_actions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/isaaclab/test/envs/mdp/test_actions.py b/source/isaaclab/test/envs/mdp/test_actions.py index 55573c3b564a..3482e332fb8b 100644 --- a/source/isaaclab/test/envs/mdp/test_actions.py +++ b/source/isaaclab/test/envs/mdp/test_actions.py @@ -48,7 +48,7 @@ def _make_env(joint_names: list[str] | None = None, num_envs: int = NUM_ENVS) -> if joint_names is None: joint_names = JOINT_NAMES - def find_joints(_names, *, as_proxy: bool = False): + def find_joints(_names, *, as_proxy: bool = False, **_kwargs): joint_ids = _JointIds(len(joint_names)) if as_proxy else list(range(len(joint_names))) return joint_ids, list(joint_names) From e3e6d9d107eb82a94e4b9d991277169da481e86f Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 9 Nov 2026 14:12:35 -0800 Subject: [PATCH 16/21] Keep in-place action processing traceable by LEAPP export --- .../isaaclab/envs/mdp/actions/binary_joint_actions.py | 4 ++-- source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py | 2 +- .../isaaclab/envs/mdp/actions/joint_actions_to_limits.py | 2 +- .../isaaclab_tasks/contrib/franka_pour/mdp/actions.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py index d6a32939a384..eb6ee52b2e49 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/binary_joint_actions.py @@ -137,7 +137,7 @@ def process_actions(self, actions: torch.Tensor): else: close_mask = actions < 0 # compute the command in place: a recorded apply_actions reads this buffer - torch.where(close_mask, self._close_command, self._open_command, out=self._processed_actions) + self._processed_actions[:] = torch.where(close_mask, self._close_command, self._open_command) if self.cfg.clip is not None: self._processed_actions.clamp_(min=self._clip[:, :, 0], max=self._clip[:, :, 1]) @@ -194,7 +194,7 @@ def process_actions(self, actions: torch.Tensor): # true: close 0.0, false: open 0.785 binary_mask = actions < self.cfg.threshold # compute the command in place: a recorded apply_actions reads this buffer - torch.where(binary_mask, self._open_command, self._close_command, out=self._processed_actions) + self._processed_actions[:] = torch.where(binary_mask, self._open_command, self._close_command) if self.cfg.clip is not None: self._processed_actions.clamp_(min=self._clip[:, :, 0], max=self._clip[:, :, 1]) diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py index d2e458d60ebe..fee45aca1e6d 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions.py @@ -170,7 +170,7 @@ def process_actions(self, actions: torch.Tensor): # store the raw actions self._raw_actions[:] = actions # apply the affine transformations in place: a recorded apply_actions reads this buffer - torch.mul(self._raw_actions, self._scale, out=self._processed_actions) + self._processed_actions[:] = self._raw_actions * self._scale self._processed_actions.add_(self._offset) # clip actions if self.cfg.clip is not None: diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py index aa4614807a7f..ebfbec1cec85 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/joint_actions_to_limits.py @@ -157,7 +157,7 @@ def process_actions(self, actions: torch.Tensor): # store the raw actions self._raw_actions[:] = actions # apply affine transformations in place: a recorded apply_actions reads this buffer - torch.mul(self._raw_actions, self._scale, out=self._processed_actions) + self._processed_actions[:] = self._raw_actions * self._scale if self.cfg.clip is not None: self._processed_actions.clamp_(min=self._clip[:, :, 0], max=self._clip[:, :, 1]) # rescale the position targets if configured diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py index 64acc5f5de21..81dd2dc86f0d 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/actions.py @@ -142,4 +142,4 @@ def set_reset_position( def process_actions(self, actions: torch.Tensor) -> None: self._previous_target.copy_(self._processed_actions) super().process_actions(actions) - torch.lerp(self._previous_target, self._processed_actions, self._alpha, out=self._processed_actions) + self._processed_actions[:] = torch.lerp(self._previous_target, self._processed_actions, self._alpha) From c98d5f9835e4f06319e74e6414a217e243d890ff Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 9 Nov 2026 14:12:36 -0800 Subject: [PATCH 17/21] Initialize the post-step callback slot on the Newton contract articulation --- source/isaaclab/test/assets/contract/articulation_factory.py | 1 + 1 file changed, 1 insertion(+) diff --git a/source/isaaclab/test/assets/contract/articulation_factory.py b/source/isaaclab/test/assets/contract/articulation_factory.py index d4f182698d8b..e684995bf46e 100644 --- a/source/isaaclab/test/assets/contract/articulation_factory.py +++ b/source/isaaclab/test/assets/contract/articulation_factory.py @@ -228,6 +228,7 @@ def _newton_articulation(N, J, B, FT, ST, device, is_fixed_base, joint_ordering, articulation._device = device articulation._clamped_default_count = wp.zeros(1, dtype=wp.int32, device=device) articulation._backend_manager = manager + articulation._post_step_callback = None articulation._data = newton_assets.ArticulationData(view, device, backend_manager=manager) # The solver builds this adapter; the shell has no model, so it stays absent. articulation._fixed_tendon_control = None From 05d779ab1bf917c486456b9a1985975c5aa5b9b8 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 9 Nov 2026 17:31:47 -0800 Subject: [PATCH 18/21] Decide physics action handling on the first step so export can opt out --- .../newton-redesign-3-env-control.added.rst | 10 +-- .../isaaclab/envs/manager_based_env.py | 58 +++++++++++------ .../isaaclab/envs/manager_based_rl_env.py | 2 + .../isaaclab/managers/action_manager.py | 13 +++- .../isaaclab/utils/leapp/export_annotator.py | 2 + .../test/envs/test_action_handling.py | 64 +++++++++++++++++++ 6 files changed, 124 insertions(+), 25 deletions(-) create mode 100644 source/isaaclab_newton/test/envs/test_action_handling.py diff --git a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst index 0a2b0234540e..0a9ef86026a0 100644 --- a/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst +++ b/source/isaaclab/changelog.d/newton-redesign-3-env-control.added.rst @@ -1,14 +1,16 @@ * Added :meth:`PhysicsManager.handle_actions `, which let a physics backend run the environment's actions and asset writes inside its step. :class:`~isaaclab.envs.ManagerBasedEnv` - called it after loading its managers, unless its render interval was not a multiple of the decimation, a recorder - term recorded after every physics step, or a sensor sampled at times other than whole environment steps, and - skipped the actions and asset writes that the step ran. + called it on its first step, unless its render interval was not a multiple of the decimation, a recorder term + recorded after every physics step, or a sensor sampled at times other than whole environment steps, and skipped the + actions and asset writes that the step ran. * Added :attr:`RecorderManager.records_physics_steps `. * Added ``is_graphable`` to :class:`~isaaclab.managers.ActionTerm`, :class:`~isaaclab.managers.ActionManager`, :class:`~isaaclab.assets.AssetBase`, :class:`~isaaclab.actuators.ActuatorCollection` and :class:`~isaaclab.scene.InteractiveScene`. Joint, joint-to-limits and binary joint action terms set it. A subclass that overrode :meth:`~isaaclab.managers.ActionTerm.process_actions` - or :meth:`~isaaclab.managers.ActionTerm.apply_actions` did not inherit it. + or :meth:`~isaaclab.managers.ActionTerm.apply_actions` did not inherit it. Setting + :attr:`ActionManager.is_graphable ` to False before the first step + kept the actions in the environment's loop, as LEAPP export did for its wrapped ``apply_action``. * Added :attr:`WrenchComposer.pending ` and the ``on_first_use`` argument of :class:`~isaaclab.utils.wrench_composer.WrenchComposer`, called at the first force write or :meth:`~isaaclab.utils.wrench_composer.WrenchComposer.add_raw_buffers_from` merge. Once forces were written, diff --git a/source/isaaclab/isaaclab/envs/manager_based_env.py b/source/isaaclab/isaaclab/envs/manager_based_env.py index d3b3d422273c..9968ebf864f6 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_env.py @@ -34,6 +34,31 @@ logger = logging.getLogger(__name__) +def _physics_can_handle_actions(env: ManagerBasedEnv) -> bool: + """Whether nothing runs between the physics steps of one environment step. + + Renders, recorder terms that record every physics step, and sensors that refresh on update at times other than + whole environment steps all run there. + + Args: + env: Environment with its managers loaded. + + Returns: + Whether the physics backend may run the environment's actions and decimation loop inside its step. + """ + if env.cfg.sim.render_interval % env.cfg.decimation != 0 or env.recorder_manager.records_physics_steps: + return False + eager_sensors = not env.scene.cfg.lazy_sensor_update + for sensor in env.scene.sensors.values(): + # a sensor that refreshes on update samples between env steps unless its period spans whole env steps + periods = sensor.cfg.update_period / env.step_dt + if (eager_sensors or getattr(sensor.cfg, "history_length", 0) > 0) and ( + round(periods) == 0 or not math.isclose(periods, round(periods), abs_tol=1e-6) + ): + return False + return True + + class ManagerBasedEnv: """The base environment encapsulates the simulation scene and the environment managers for the manager-based workflow. @@ -95,7 +120,8 @@ def __init__(self, cfg: ManagerBasedEnvCfg): self.cfg = cfg # initialize internal variables self._physics_handles_decimation = False - self._physics_handles_actions = False + # decided on the first step + self._physics_handles_actions: bool | None = None # set the seed for the environment if self.cfg.seed is not None: @@ -208,25 +234,7 @@ def _init_sim(self): report_activity("Setting up managers") self.load_managers() report_activity(None) - # let the physics backend run the actions, asset writes and decimation loop inside its step when it can, - # unless renders, recorders or sensors must run between the physics steps of one environment step - eager_sensors = not self.scene.cfg.lazy_sensor_update - sensors_sample_physics_steps = False - for sensor in self.scene.sensors.values(): - # a sensor that refreshes on update samples between env steps unless its period spans whole env steps - periods = sensor.cfg.update_period / self.step_dt - if (eager_sensors or getattr(sensor.cfg, "history_length", 0) > 0) and ( - round(periods) == 0 or not math.isclose(periods, round(periods), abs_tol=1e-6) - ): - sensors_sample_physics_steps = True - if ( - self.cfg.sim.render_interval % self.cfg.decimation == 0 - and not self.recorder_manager.records_physics_steps - and not sensors_sample_physics_steps - ): - self._physics_handles_actions = self.sim.backend_manager.handle_actions(self.action_manager, self.scene) self.sim.backend_manager.set_decimation(self.cfg.decimation) - self._physics_handles_decimation = self.sim.backend_manager.handles_decimation() # Wire live plots into all active visualizers (Newton, Rerun, Viser) and create # Kit omni.ui ManagerLiveVisualizer widgets when a GUI window is present. @@ -534,6 +542,16 @@ def reset_to( # return observations return self.obs_buf, self.extras + def _handle_physics_actions(self): + """Let the physics backend run the actions, asset writes and decimation loop inside its step when it can. + + Decided on the first step, so code that wraps the action manager after construction can mark it not graphable. + """ + self._physics_handles_actions = _physics_can_handle_actions(self) and self.sim.backend_manager.handle_actions( + self.action_manager, self.scene + ) + self._physics_handles_decimation = self.sim.backend_manager.handles_decimation() + def step(self, action: torch.Tensor) -> tuple[VecEnvObs, dict]: """Execute one time-step of the environment's dynamics. @@ -561,6 +579,8 @@ def step(self, action: torch.Tensor) -> tuple[VecEnvObs, dict]: A tuple containing the observations and extras. """ self.action_manager.process_action(action.to(self.device)) + if self._physics_handles_actions is None: + self._handle_physics_actions() self.recorder_manager.record_pre_step() diff --git a/source/isaaclab/isaaclab/envs/manager_based_rl_env.py b/source/isaaclab/isaaclab/envs/manager_based_rl_env.py index 2150eb903531..55f7f27f09af 100644 --- a/source/isaaclab/isaaclab/envs/manager_based_rl_env.py +++ b/source/isaaclab/isaaclab/envs/manager_based_rl_env.py @@ -206,6 +206,8 @@ def step(self, action: torch.Tensor) -> VecEnvStepReturn: A tuple containing the observations, rewards, resets (terminated and truncated) and extras. """ self.action_manager.process_action(action.to(self.device)) + if self._physics_handles_actions is None: + self._handle_physics_actions() self.recorder_manager.record_pre_step() diff --git a/source/isaaclab/isaaclab/managers/action_manager.py b/source/isaaclab/isaaclab/managers/action_manager.py index 790ce3613e30..fa48ed34edec 100644 --- a/source/isaaclab/isaaclab/managers/action_manager.py +++ b/source/isaaclab/isaaclab/managers/action_manager.py @@ -225,6 +225,7 @@ def __init__(self, cfg: object, env: ManagerBasedEnv): # call the base class constructor (this prepares the terms) super().__init__(cfg, env) + self._graphable = True # fixed once the terms are built self._action_term_dim = [term.action_dim for term in self._terms.values()] self._total_action_dim = sum(self._action_term_dim) @@ -288,8 +289,16 @@ def prev_action(self) -> torch.Tensor: @property def is_graphable(self) -> bool: - """Whether :meth:`apply_action` can be recorded into a CUDA graph.""" - return all(term.is_graphable for term in self._terms.values()) + """Whether :meth:`apply_action` can be recorded into a CUDA graph. + + True when all terms are. Set it to False before the environment's first step to keep :meth:`apply_action` in + the environment's loop, for example when wrapping it in Python. + """ + return self._graphable and all(term.is_graphable for term in self._terms.values()) + + @is_graphable.setter + def is_graphable(self, value: bool): + self._graphable = value @property def has_debug_vis_implementation(self) -> bool: diff --git a/source/isaaclab/isaaclab/utils/leapp/export_annotator.py b/source/isaaclab/isaaclab/utils/leapp/export_annotator.py index 3677dede8229..f54a7c402253 100644 --- a/source/isaaclab/isaaclab/utils/leapp/export_annotator.py +++ b/source/isaaclab/isaaclab/utils/leapp/export_annotator.py @@ -497,6 +497,8 @@ def _patch_action_manager_methods(self, action_manager): action_manager: Action manager whose instance methods should be wrapped. """ + # the patched apply_action runs Python, so it stays in the environment's loop + action_manager.is_graphable = False original_process = action_manager.process_action original_apply = action_manager.apply_action task_name = self.task_name diff --git a/source/isaaclab_newton/test/envs/test_action_handling.py b/source/isaaclab_newton/test/envs/test_action_handling.py new file mode 100644 index 000000000000..8e1867d1209b --- /dev/null +++ b/source/isaaclab_newton/test/envs/test_action_handling.py @@ -0,0 +1,64 @@ +# 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 + +"""Newton running a manager-based environment's actions inside its step.""" + +from pathlib import Path + +import pytest +import torch +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg +from isaaclab.envs import ManagerBasedEnv, ManagerBasedEnvCfg +from isaaclab.envs.mdp import JointEffortActionCfg, joint_pos +from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sim import SimulationCfg +from isaaclab.utils import configclass + + +@configclass +class ActionsCfg: + effort = JointEffortActionCfg(asset_name="robot", joint_names=[".*"]) + + +@pytest.mark.parametrize("opted_out", [False, True], ids=["graphable", "opted-out"]) +def test_actions_wrapped_after_construction_stay_in_the_environment_loop(opted_out: bool): + """Physics takes the actions on the first step, unless the action manager was marked not graphable before it.""" + scene_cfg = InteractiveSceneCfg(num_envs=2, env_spacing=5.0) + scene_cfg.robot = ArticulationCfg( + prim_path="{ENV_REGEX_NS}/Robot", + spawn=sim_utils.UsdFileCfg( + usd_path=str(Path(__file__).parents[1] / "assets/data/articulation_ordering_branching.usda") + ), + actuators={}, + ) + observations = ObservationGroupCfg() + observations.joints = ObservationTermCfg(func=joint_pos) + cfg = ManagerBasedEnvCfg( + sim=SimulationCfg(dt=0.01, render_interval=2, device="cuda:0", physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())), + scene=scene_cfg, + decimation=2, + observations={"policy": observations}, + actions=ActionsCfg(), + seed=7, + ) + env = ManagerBasedEnv(cfg) + try: + env.reset() + applied = [] + if opted_out: + # a Python wrapper installed after construction, as export does + apply_action = env.action_manager.apply_action + env.action_manager.apply_action = lambda: (applied.append(None), apply_action()) + env.action_manager.is_graphable = False + for _ in range(3): + env.step(torch.zeros(env.num_envs, env.action_manager.total_action_dim, device=env.device)) + assert env.sim.backend_manager.backend.handles_actions is not opted_out + assert len(applied) == (3 * cfg.decimation if opted_out else 0) + finally: + env.close() From 51b0bc4711e07a7ff8b5b9676aa451fde068945b Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 9 Nov 2026 17:31:48 -0800 Subject: [PATCH 19/21] Test when physics handles a manager-based environment's actions --- .../test/envs/test_physics_action_handling.py | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 source/isaaclab/test/envs/test_physics_action_handling.py diff --git a/source/isaaclab/test/envs/test_physics_action_handling.py b/source/isaaclab/test/envs/test_physics_action_handling.py new file mode 100644 index 000000000000..89dbd3230f53 --- /dev/null +++ b/source/isaaclab/test/envs/test_physics_action_handling.py @@ -0,0 +1,52 @@ +# 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 + +"""Unit tests for when a manager-based environment lets physics handle its actions.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from isaaclab.envs.manager_based_env import _physics_can_handle_actions + +pytestmark = pytest.mark.unit + + +def _env(*, render_interval=2, records_physics_steps=False, lazy_sensor_update=False, sensor=None): + """An environment stepping 2 physics steps of 0.01 s per environment step, with at most one sensor.""" + return SimpleNamespace( + cfg=SimpleNamespace(sim=SimpleNamespace(render_interval=render_interval), decimation=2), + step_dt=0.02, + recorder_manager=SimpleNamespace(records_physics_steps=records_physics_steps), + scene=SimpleNamespace( + cfg=SimpleNamespace(lazy_sensor_update=lazy_sensor_update), + sensors={} if sensor is None else {"sensor": SimpleNamespace(cfg=SimpleNamespace(**sensor))}, + ), + ) + + +@pytest.mark.parametrize( + ("env", "handled"), + [ + pytest.param(_env(), True, id="renders-once-per-env-step"), + pytest.param(_env(render_interval=1), False, id="renders-every-physics-step"), + pytest.param(_env(records_physics_steps=True), False, id="records-every-physics-step"), + pytest.param(_env(sensor={"update_period": 0.02}), True, id="sensor-every-env-step"), + pytest.param(_env(sensor={"update_period": 0.04}), True, id="sensor-every-other-env-step"), + pytest.param(_env(sensor={"update_period": 0.0}), False, id="sensor-every-physics-step"), + pytest.param(_env(sensor={"update_period": 0.01}), False, id="sensor-mid-env-step"), + pytest.param(_env(lazy_sensor_update=True, sensor={"update_period": 0.0}), True, id="lazy-sensor"), + pytest.param( + _env(lazy_sensor_update=True, sensor={"update_period": 0.0, "history_length": 2}), + False, + id="lazy-sensor-with-history", + ), + ], +) +def test_physics_handles_actions_only_when_nothing_runs_between_physics_steps(env, handled): + """Renders, per-physics-step recorders and sensors sampled within an environment step keep actions in the loop.""" + assert _physics_can_handle_actions(env) is handled From 17be97fb8f7b4dc0417e7b01d54ff196d71f46b6 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 9 Nov 2026 17:36:21 -0800 Subject: [PATCH 20/21] Drop the Newton environment test of first-step action handling --- .../test/envs/test_action_handling.py | 64 ------------------- 1 file changed, 64 deletions(-) delete mode 100644 source/isaaclab_newton/test/envs/test_action_handling.py diff --git a/source/isaaclab_newton/test/envs/test_action_handling.py b/source/isaaclab_newton/test/envs/test_action_handling.py deleted file mode 100644 index 8e1867d1209b..000000000000 --- a/source/isaaclab_newton/test/envs/test_action_handling.py +++ /dev/null @@ -1,64 +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 - -"""Newton running a manager-based environment's actions inside its step.""" - -from pathlib import Path - -import pytest -import torch -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg -from isaaclab.envs import ManagerBasedEnv, ManagerBasedEnvCfg -from isaaclab.envs.mdp import JointEffortActionCfg, joint_pos -from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.utils import configclass - - -@configclass -class ActionsCfg: - effort = JointEffortActionCfg(asset_name="robot", joint_names=[".*"]) - - -@pytest.mark.parametrize("opted_out", [False, True], ids=["graphable", "opted-out"]) -def test_actions_wrapped_after_construction_stay_in_the_environment_loop(opted_out: bool): - """Physics takes the actions on the first step, unless the action manager was marked not graphable before it.""" - scene_cfg = InteractiveSceneCfg(num_envs=2, env_spacing=5.0) - scene_cfg.robot = ArticulationCfg( - prim_path="{ENV_REGEX_NS}/Robot", - spawn=sim_utils.UsdFileCfg( - usd_path=str(Path(__file__).parents[1] / "assets/data/articulation_ordering_branching.usda") - ), - actuators={}, - ) - observations = ObservationGroupCfg() - observations.joints = ObservationTermCfg(func=joint_pos) - cfg = ManagerBasedEnvCfg( - sim=SimulationCfg(dt=0.01, render_interval=2, device="cuda:0", physics=NewtonCfg(solver_cfg=MJWarpSolverCfg())), - scene=scene_cfg, - decimation=2, - observations={"policy": observations}, - actions=ActionsCfg(), - seed=7, - ) - env = ManagerBasedEnv(cfg) - try: - env.reset() - applied = [] - if opted_out: - # a Python wrapper installed after construction, as export does - apply_action = env.action_manager.apply_action - env.action_manager.apply_action = lambda: (applied.append(None), apply_action()) - env.action_manager.is_graphable = False - for _ in range(3): - env.step(torch.zeros(env.num_envs, env.action_manager.total_action_dim, device=env.device)) - assert env.sim.backend_manager.backend.handles_actions is not opted_out - assert len(applied) == (3 * cfg.decimation if opted_out else 0) - finally: - env.close() From 22f4b6516989c24d5934184ae59a217680d06ac6 Mon Sep 17 00:00:00 2001 From: Mustafa Haiderbhai Date: Mon, 9 Nov 2026 17:43:37 -0800 Subject: [PATCH 21/21] Trim the action handling and wrench composer tests --- source/isaaclab/test/envs/mdp/test_actions.py | 6 ----- .../test/envs/test_physics_action_handling.py | 2 -- .../test/utils/test_wrench_composer.py | 23 ++++------------- .../test/physics/test_newton_manager.py | 25 ++++++++----------- 4 files changed, 15 insertions(+), 41 deletions(-) diff --git a/source/isaaclab/test/envs/mdp/test_actions.py b/source/isaaclab/test/envs/mdp/test_actions.py index 3482e332fb8b..494f30fc0ec6 100644 --- a/source/isaaclab/test/envs/mdp/test_actions.py +++ b/source/isaaclab/test/envs/mdp/test_actions.py @@ -252,7 +252,6 @@ def test_recordable_joint_actions_process_into_the_same_buffer(action_cls, cfg) """A step that records ``apply_actions`` reads the processed buffer, so processing writes it in place.""" cfg.asset_name, cfg.joint_names = "robot", [".*"] action = action_cls(cfg, _make_env(["a", "b"])) - assert action_cls.is_graphable processed = action.processed_actions action.process_actions(torch.full((2, action.action_dim), -0.25)) @@ -264,10 +263,6 @@ def test_recordable_joint_actions_process_into_the_same_buffer(action_cls, cfg) def test_subclass_overriding_action_methods_does_not_inherit_is_graphable() -> None: """A subclass with its own ``process_actions`` or ``apply_actions`` is not recorded unless it says so.""" - class Applies(JointEffortAction): - def apply_actions(self): - pass - class Processes(JointEffortAction): def process_actions(self, actions): self._processed_actions = actions.clamp(-1.0, 1.0) @@ -281,7 +276,6 @@ def process_actions(self, actions): class Inherits(JointEffortAction): pass - assert not Applies.is_graphable assert not Processes.is_graphable assert Declares.is_graphable assert Inherits.is_graphable diff --git a/source/isaaclab/test/envs/test_physics_action_handling.py b/source/isaaclab/test/envs/test_physics_action_handling.py index 89dbd3230f53..f21be482fd2e 100644 --- a/source/isaaclab/test/envs/test_physics_action_handling.py +++ b/source/isaaclab/test/envs/test_physics_action_handling.py @@ -32,11 +32,9 @@ def _env(*, render_interval=2, records_physics_steps=False, lazy_sensor_update=F @pytest.mark.parametrize( ("env", "handled"), [ - pytest.param(_env(), True, id="renders-once-per-env-step"), pytest.param(_env(render_interval=1), False, id="renders-every-physics-step"), pytest.param(_env(records_physics_steps=True), False, id="records-every-physics-step"), pytest.param(_env(sensor={"update_period": 0.02}), True, id="sensor-every-env-step"), - pytest.param(_env(sensor={"update_period": 0.04}), True, id="sensor-every-other-env-step"), pytest.param(_env(sensor={"update_period": 0.0}), False, id="sensor-every-physics-step"), pytest.param(_env(sensor={"update_period": 0.01}), False, id="sensor-mid-env-step"), pytest.param(_env(lazy_sensor_update=True, sensor={"update_period": 0.0}), True, id="lazy-sensor"), diff --git a/source/isaaclab/test/utils/test_wrench_composer.py b/source/isaaclab/test/utils/test_wrench_composer.py index 47de8c4a44db..f18fdf9745d5 100644 --- a/source/isaaclab/test/utils/test_wrench_composer.py +++ b/source/isaaclab/test/utils/test_wrench_composer.py @@ -553,6 +553,7 @@ def test_recorded_wrench_work_applies_wrenches_written_after_capture(device): first_uses = [] instantaneous = WrenchComposer(asset, on_first_use=lambda: first_uses.append("instantaneous")) permanent = WrenchComposer(asset, on_first_use=lambda: first_uses.append("permanent")) + merged = WrenchComposer(asset, on_first_use=lambda: first_uses.append("merged")) with wp.ScopedDevice(device): local = wp.array([[[1.0, 0.0, 0.0]]], dtype=wp.vec3f) instantaneous.add_forces_and_torques_index(local, env_ids=[0], body_ids=[0]) @@ -560,6 +561,9 @@ def test_recorded_wrench_work_applies_wrenches_written_after_capture(device): permanent.add_forces_and_torques_index( wp.array([[[0.0, 2.0, 0.0]]], dtype=wp.vec3f), env_ids=[0], body_ids=[0], is_global=True ) + # a merge is a first use too, called once + merged.add_raw_buffers_from(permanent) + merged.add_raw_buffers_from(permanent) force = wp.zeros((2, 2), dtype=wp.vec3f) assert not instantaneous.active and instantaneous.pending is False @@ -577,24 +581,7 @@ def write(): _assert_vectors(force, _grid({(0, 0): (1.0, -2.0, 0.0)}).to(device)) wp.capture_launch(capture.graph) _assert_vectors(force, _grid({(0, 0): (0.0, -2.0, 0.0)}).to(device)) - assert first_uses == ["instantaneous", "permanent"] - - -@pytest.mark.parametrize("device", test_devices()) -def test_raw_buffer_merge_is_the_first_use_of_its_destination(device): - """A merge into an unused composer calls its first-use callback, as a force write would.""" - com, quat = _poses() - asset = SimpleNamespace( - num_instances=2, num_bodies=2, device=device, data=_AssetData(com.to(device), quat.to(device)) - ) - first_uses = [] - source = WrenchComposer(asset) - destination = WrenchComposer(asset, on_first_use=lambda: first_uses.append("destination")) - with wp.ScopedDevice(device): - source.add_forces_and_torques_index(wp.array([[[3.0, 0.0, 0.0]]], dtype=wp.vec3f), env_ids=[0], body_ids=[0]) - destination.add_raw_buffers_from(source) - destination.add_raw_buffers_from(source) - assert first_uses == ["destination"] + assert first_uses == ["instantaneous", "permanent", "merged"] @pytest.mark.parametrize( diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index 86bb28e0c57e..d662ae380807 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -939,20 +939,6 @@ def _damp_body(body_qd: wp.array(dtype=wp.spatial_vector), body_f: wp.array(dtyp body_f[0] = wp.spatial_vector(0.0, 0.0, -20.0 * body_qd[0][2], 0.0, 0.0, 0.0) -def _handled_actions(manager: NewtonManager, *, graphable: bool): - """Actions that damp a free body, and an empty scene; both support graph capture when ``graphable``.""" - applied = [] - actions = SimpleNamespace( - is_graphable=graphable, - apply_action=lambda: ( - applied.append("action"), - wp.launch(_damp_body, 1, inputs=[manager.backend.state_0.body_qd, manager.backend.state_0.body_f]), - ), - ) - scene = SimpleNamespace(is_graphable=True, write_data_to_sim=lambda: None) - return actions, scene, applied - - def test_handled_actions_run_before_every_physics_step_like_the_environment_loop(): """Handled actions run before every physics step of one captured step, also after a hard reset, like the env loop. @@ -967,7 +953,16 @@ def test_handled_actions_run_before_every_physics_step_like_the_environment_loop sim.reset() manager = sim.backend_manager manager.set_decimation(decimation) - actions, scene, applied = _handled_actions(manager, graphable=handled) + applied = [] + # actions that damp the free body, recorded into the step only when handled + actions = SimpleNamespace( + is_graphable=handled, + apply_action=lambda: ( + applied.append("action"), + wp.launch(_damp_body, 1, inputs=[manager.backend.state_0.body_qd, manager.backend.state_0.body_f]), + ), + ) + scene = SimpleNamespace(is_graphable=True, write_data_to_sim=lambda: None) assert manager.handle_actions(actions, scene) is handled assert manager.handles_decimation() is handled for reset in (False, True):