From ff3ebd95e14784413fdfd40e6f7b7a7411c6fbe9 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Fri, 13 Nov 2026 17:10:44 -0800 Subject: [PATCH 01/30] Add the recording utilities and keep lazy data correct under recording --- docs/source/api/lab/isaaclab.utils.rst | 7 + .../jichuanh-warp-recording-utils.added.rst | 13 + .../jichuanh-warp-recording-utils.fixed.rst | 4 + .../jichuanh-warp-recording-utils.minor | 0 .../scene_data/scene_data_provider.py | 4 +- .../isaaclab/isaaclab/sensors/sensor_base.py | 9 +- .../utils/buffers/timestamped_buffer.py | 46 ++- .../isaaclab/isaaclab/utils/warp/capture.py | 333 ++++++++++++++++++ .../isaaclab/visualizers/image_view.py | 2 +- .../contract/test_articulation_contract.py | 83 +++++ .../sensors/test_sensor_update_schedule.py | 63 ++++ ...test_newton_manager_visualization_state.py | 1 + .../test/utils/test_timestamped_buffer.py | 124 +++++++ .../isaaclab/test/utils/warp/test_capture.py | 261 ++++++++++++++ .../jichuanh-warp-recording-utils.skip | 0 .../envs/mdp/observations.py | 8 +- .../isaaclab_experimental/envs/mdp/rewards.py | 8 +- .../jichuanh-warp-recording-utils.changed.rst | 4 + .../jichuanh-warp-recording-utils.fixed.rst | 9 + .../assets/articulation/articulation.py | 2 + .../assets/articulation/articulation_data.py | 77 ++-- .../assets/rigid_object/rigid_object.py | 2 + .../assets/rigid_object/rigid_object_data.py | 40 +-- .../rigid_object_collection.py | 2 + .../rigid_object_collection_data.py | 38 +- .../isaaclab_newton/physics/newton_backend.py | 11 +- .../isaaclab_newton/physics/newton_manager.py | 15 +- .../test/fixtures/mock_newton.py | 1 + .../test/assets/test_articulation.py | 18 + .../test/assets/test_joint_coordinates.py | 1 + .../test/assets/test_rigid_object.py | 13 + .../test/physics/test_newton_manager.py | 4 + .../test/physics/test_newton_solver_reset.py | 50 +++ .../jichuanh-warp-recording-utils.fixed.rst | 3 + .../assets/articulation/articulation_data.py | 60 +++- .../assets/rigid_object/rigid_object_data.py | 4 +- .../isaaclab_ov/physics/ovphysx_manager.py | 8 +- .../test/assets/test_articulation.py | 7 +- .../jichuanh-warp-recording-utils.fixed.rst | 3 + .../isaaclab_physx/renderers/fabric.py | 8 +- .../jichuanh-warp-recording-utils.skip | 0 .../core/locomotion/mdp/observations.py | 6 +- .../core/locomotion/mdp/rewards.py | 8 +- 43 files changed, 1217 insertions(+), 143 deletions(-) create mode 100644 source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst create mode 100644 source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst create mode 100644 source/isaaclab/changelog.d/jichuanh-warp-recording-utils.minor create mode 100644 source/isaaclab/isaaclab/utils/warp/capture.py create mode 100644 source/isaaclab/test/utils/test_timestamped_buffer.py create mode 100644 source/isaaclab/test/utils/warp/test_capture.py create mode 100644 source/isaaclab_experimental/changelog.d/jichuanh-warp-recording-utils.skip create mode 100644 source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst create mode 100644 source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst create mode 100644 source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst create mode 100644 source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst create mode 100644 source/isaaclab_tasks_experimental/changelog.d/jichuanh-warp-recording-utils.skip diff --git a/docs/source/api/lab/isaaclab.utils.rst b/docs/source/api/lab/isaaclab.utils.rst index ea781743bde8..438d602d87f2 100644 --- a/docs/source/api/lab/isaaclab.utils.rst +++ b/docs/source/api/lab/isaaclab.utils.rst @@ -348,6 +348,13 @@ so callers must not retain a scratch result across another resolution using the .. automodule:: isaaclab.utils.warp.memory :members: +Warp CUDA graph capture +^^^^^^^^^^^^^^^^^^^^^^^ + +.. automodule:: isaaclab.utils.warp.capture + :members: + :show-inheritance: + Warp Fabric kernels ^^^^^^^^^^^^^^^^^^^ diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst new file mode 100644 index 000000000000..ad043f683a79 --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst @@ -0,0 +1,13 @@ +* Added :mod:`isaaclab.utils.warp.capture`. :class:`~isaaclab.utils.warp.capture.GraphedCallable` records a call as + a CUDA graph on its first run with a given argument layout and replays it after; it records again for another + layout or when the physics backend rebinds its buffers. +* Added :func:`~isaaclab.utils.warp.capture.eager` for calls that cannot be recorded inside a recorded part. While + the part records, the call ends the current CUDA graph and runs eagerly before the next graph starts. Every replay + repeats the call at the same place with the same arguments. +* Added :func:`~isaaclab.utils.warp.capture.record_at_end` to record a call once at the end of the + :class:`~isaaclab.utils.warp.capture.GraphedCallable` being recorded. +* Added the ``update_in_graph`` argument to :class:`~isaaclab.utils.buffers.TimestampedBuffer`. While a + :class:`~isaaclab.utils.warp.capture.GraphedCallable` records, a buffer's + :attr:`~isaaclab.utils.buffers.TimestampedBuffer.timestamp` now reads as stale until the buffer is updated in that + recording, so a lazily cached value read in a recording is recomputed on every replay; ``update_in_graph=False`` + keeps the plain timestamp rule, as does any other CUDA graph capture. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst new file mode 100644 index 000000000000..6cdc982ed6d0 --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -0,0 +1,4 @@ +* Fixed sensors read inside a recorded CUDA graph after a reset keeping their data from before the recording: + :class:`~isaaclab.sensors.SensorBase` now records the buffer refresh whenever a + :class:`~isaaclab.utils.warp.capture.GraphedCallable` records, so each replay refreshes the environments whose + data is outdated. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.minor b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/scene_data/scene_data_provider.py b/source/isaaclab/isaaclab/scene_data/scene_data_provider.py index a5144286217c..4b26b3c500f1 100644 --- a/source/isaaclab/isaaclab/scene_data/scene_data_provider.py +++ b/source/isaaclab/isaaclab/scene_data/scene_data_provider.py @@ -156,7 +156,7 @@ def get_transforms( ) if allow_passthrough: if cached is None: - cached = self._cache[key] = TimestampedBuffer() + cached = self._cache[key] = TimestampedBuffer(update_in_graph=False) # Shared requests own the result; Fabric owns its destination, not SDP. cached.data, cached.timestamp = (layout if fabric else result), timestamp for name in output_format.vars: @@ -382,7 +382,7 @@ def get_geometry_points( jobs.append((source_indices, destination_indices, buffer, transfer)) if offsets is not None and bound != offsets.keys(): raise KeyError(f"Geometry destinations have no native publication: {offsets.keys() - bound}") - cached = self._cache[key] = TimestampedBuffer((views, jobs, offsets)) + cached = self._cache[key] = TimestampedBuffer((views, jobs, offsets), update_in_graph=False) views, jobs, _ = cached.data timestamp = self.backend.geometry_timestamp diff --git a/source/isaaclab/isaaclab/sensors/sensor_base.py b/source/isaaclab/isaaclab/sensors/sensor_base.py index 6f4d15db2768..91fcef79b9bc 100644 --- a/source/isaaclab/isaaclab/sensors/sensor_base.py +++ b/source/isaaclab/isaaclab/sensors/sensor_base.py @@ -30,6 +30,7 @@ from ..physics import PhysicsEvent, PhysicsManager from ..sim.utils.queries import get_first_matching_ancestor_prim from ..sim.utils.transforms import resolve_prim_pose +from ..utils.buffers import TimestampedBuffer from ..utils.warp.memory import resolve_1d_mask from .kernels import invalidate_buffers_kernel, reset_envs_kernel, update_outdated_envs_kernel, update_timestamp_kernel @@ -465,6 +466,8 @@ def _create_timing_buffers(self) -> None: # A negative timestamp means no backend sample has been read since initialization/reset. self._timestamp_last_update = wp.full(self._num_envs, -1.0, dtype=wp.float32, device=self._device) self._elapsed_since_update = wp.zeros(self._num_envs, dtype=wp.float64, device=self._device) + # the time of the last refresh, which reads stale in each new graph recording + self._refreshed = TimestampedBuffer(timestamp=0.0) def _invalidate_buffers(self, env_mask: wp.array | None = None) -> None: """Invalidate selected results without advancing sampling clocks; None selects all environments.""" @@ -478,7 +481,10 @@ def _invalidate_buffers(self, env_mask: wp.array | None = None) -> None: def _update_outdated_buffers(self) -> None: """Fills the sensor data for the outdated sensors.""" - if not self._data_dirty: + # a CUDA graph replays without this check, so the refresh timestamp reads stale in each new GraphedCallable + # recording, which then holds the refresh (see TimestampedBuffer); the outdated mask selects the environments + # each replay updates + if not self._data_dirty and self._refreshed.timestamp >= 0.0: return self._update_buffers_impl(self._is_outdated) self._mark_buffers_updated() @@ -493,6 +499,7 @@ def _mark_buffers_updated(self) -> None: device=self._device, ) self._data_dirty = False + self._refreshed.timestamp = 0.0 @staticmethod def _process_batch(sensors: Sequence[SensorBase]) -> None: diff --git a/source/isaaclab/isaaclab/utils/buffers/timestamped_buffer.py b/source/isaaclab/isaaclab/utils/buffers/timestamped_buffer.py index 04c360494b36..bc0b790e6a21 100644 --- a/source/isaaclab/isaaclab/utils/buffers/timestamped_buffer.py +++ b/source/isaaclab/isaaclab/utils/buffers/timestamped_buffer.py @@ -4,9 +4,10 @@ # SPDX-License-Identifier: BSD-3-Clause from collections.abc import Iterable -from dataclasses import dataclass from typing import Any +from ..warp.capture import GraphedCallable + def reset_timestamps(buffers: Iterable["TimestampedBuffer | None"]) -> None: """Invalidate cached values, skipping unallocated or unaffected buffers. @@ -19,16 +20,49 @@ def reset_timestamps(buffers: Iterable["TimestampedBuffer | None"]) -> None: buffer.timestamp = -1.0 -@dataclass class TimestampedBuffer: """Cached data and its last successful update timestamp. The owner supplies storage and updates the timestamp after computing the value. Array caches accept Torch or Warp arrays directly; no conversion is performed. + + While a :class:`~isaaclab.utils.warp.capture.GraphedCallable` records, :attr:`timestamp` reads -1 (stale) until + the data is updated in that recording: a graph replays without the owner's timestamp check, so a recording that + reads the data must hold its update for every replay to recompute it. Data whose update a recording must not hold, + such as a value its owner fetches through a host call or a cache that records its own graph, opts out with + ``update_in_graph=False``. Any other CUDA graph capture keeps the plain timestamp rule. """ - data: Any = None - """Cached array, native-format struct, or grouped data; None before allocation.""" + __slots__ = ("data", "update_in_graph", "_timestamp", "_recording") + + def __init__(self, data: Any = None, timestamp: float = -1.0, *, update_in_graph: bool = True): + """Initialize the buffer. + + Args: + data: Cached array, native-format struct, or grouped data. Defaults to None, before allocation. + timestamp: Source timestamp represented by the data. Defaults to -1, which marks it stale. + update_in_graph: Whether a :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording that reads the + data updates it. Defaults to True. + """ + self.data = data + self.update_in_graph = update_in_graph + self._timestamp = timestamp + self._recording: object = None + + @property + def timestamp(self) -> float: + """Source timestamp represented by the data; -1 marks it stale.""" + # is_recording(), inlined: every lazy data read checks it + recording = GraphedCallable._recording + if recording is not None and recording.capturing and self.update_in_graph: + if self._recording is not recording.token: + return -1.0 + return self._timestamp - timestamp: float = -1.0 - """Source timestamp represented by the data; -1 marks it stale.""" + @timestamp.setter + def timestamp(self, value: float) -> None: + self._timestamp = value + recording = GraphedCallable._recording + if recording is not None and recording.capturing: + # the recording in progress now holds the update; invalidating clears it, so a later read records it again + self._recording = recording.token if value >= 0 else None diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py new file mode 100644 index 000000000000..492fd4db689b --- /dev/null +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -0,0 +1,333 @@ +# 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 + +"""CUDA graph recording of the Warp frontend: :class:`GraphedCallable` records a call as CUDA graphs and replays it, +and :func:`eager` runs a call that cannot be recorded at its place in the recording. +""" + +from __future__ import annotations + +import contextlib +import functools +import gc +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, ClassVar + +import torch +import warp as wp +import warp._src.context as _warp_context + +from ..version import has_kit + +if TYPE_CHECKING: + from ...physics import PhysicsManager + + +def capturing(device: wp.Device | str | None = None) -> bool: + """Whether a CUDA graph is being recorded on ``device`` (the current device by default). + + It reads Warp's table of the recordings in progress first, which costs ~20x less than ``Device.is_capturing``, so + outside a recording the check spares the CUDA query; every recording in Isaac Lab starts through Warp. + """ + runtime = _warp_context.runtime + return runtime is not None and bool(runtime.captures) and wp.get_device(device).is_capturing + + +def is_recording() -> bool: + """Whether a :class:`GraphedCallable` records, so that an :func:`eager` call repeats on each of its replays.""" + recording = GraphedCallable._recording + return recording is not None and recording.capturing + + +def record_at_end(fn: Callable[[], None]) -> bool: + """Record ``fn`` at the end of the :class:`GraphedCallable` being recorded, once however often it is requested. + + Returns: + Whether a :class:`GraphedCallable` records; without one, the caller handles the replays itself. + """ + recording = GraphedCallable._recording + if recording is None: + return False + if fn not in recording.end_calls: + recording.end_calls.append(fn) + return True + + +def eager(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + """Call a function that cannot be recorded from inside a :class:`GraphedCallable`. + + Outside a recording this is a plain call. While a :class:`GraphedCallable` records, the call ends the current + graph, runs eagerly and starts the next graph, and every replay repeats it at the same place with the same + arguments, so the arguments must stay valid across calls like the arrays a graph reads. Replays discard its result. + + Args: + fn: The function to call. + *args: Positional arguments of the call. + **kwargs: Keyword arguments of the call. + + Returns: + The result of the call. + + Raises: + RuntimeError: If the current device is capturing a graph that no :class:`GraphedCallable` records. + """ + recording = GraphedCallable._recording + if recording is not None and recording.capturing: + return recording.split(fn, args, kwargs) + if capturing(): + name = getattr(fn, "__qualname__", type(fn).__name__) + raise RuntimeError( + f"'{name}' cannot be recorded, so it cannot run inside a graph capture that no GraphedCallable started." + ) + return fn(*args, **kwargs) + + +def eager_method(method: Callable[..., Any]) -> Callable[..., Any]: + """Run a method that cannot be recorded through :func:`eager`. + + A :class:`GraphedCallable` recording a call to the method replays it eagerly with the same arguments. An override + in a subclass is decorated again. + + Args: + method: The method to wrap. + + Returns: + The wrapped method. + """ + + @functools.wraps(method) + def wrapper(self, *args: Any, **kwargs: Any) -> Any: + return eager(method, self, *args, **kwargs) + + return wrapper + + +class GraphedCallable: + """A callable recorded as CUDA graphs on its first call with a given argument layout and replayed after. + + * The first call with a given argument layout records without an eager warm-up: the recording is its first + execution. Later calls with the same array pointers and scalar values replay that recording and return the + result of the recording call, so the callable returns buffers its owner keeps. + * Calls that cannot be recorded go through :func:`eager`. A recording ends its graph at each of them, runs the + call and starts the next graph; a replay launches the graphs and repeats the calls with their recorded + arguments, in the recorded order. + * :attr:`enabled` turns recording off process-wide, to run every part eagerly; it is on by default. A callable on + a CPU device always runs eagerly. + * :attr:`generation` advances when the terms change or the physics backend rebinds its buffers or stops (see + :meth:`watch`), and every callable records again on its next call. + * Called inside a graph capture that something else started, it runs inline, so its kernels become part of that + capture. + """ + + enabled: ClassVar[bool] = True + """Whether callables record CUDA graphs. Turn it off to run every recorded part eagerly.""" + + generation: ClassVar[int] = 0 + """Counter of term changes, physics rebinds and stops; a callable recorded under an older value records again.""" + + _callback_handles: ClassVar[list] = [] + + _settle: ClassVar[Callable[[], None] | None] = None + """The watched physics backend's forward, run before each recording (see :meth:`watch`).""" + + _recording: ClassVar[_Recording | None] = None + """The recording in progress, which :func:`eager` calls split.""" + + def __init__(self, fn: Callable[..., Any], device: wp.DeviceLike): + """Initialize the callable. + + Args: + fn: Callable to record. Its GPU work must be capturable, except for :func:`eager` calls. + device: Warp device that runs the callable. + """ + self._fn = fn + self._device = wp.get_device(device) + self._recordings: dict[tuple, tuple[list, Any]] = {} + self._generation = GraphedCallable.generation + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + """Run the callable and return its result.""" + if capturing(self._device): + return self._fn(*args, **kwargs) + if not (GraphedCallable.enabled and self._device.is_cuda): + return self._fn(*args, **kwargs) + if self._generation != GraphedCallable.generation: + self.reset() + self._generation = GraphedCallable.generation + key = _argument_key(args, kwargs) + recorded = self._recordings.get(key) + if recorded is None: + self._recordings[key] = recorded = self._record(args, kwargs) + return recorded[1] + steps, result = recorded + _replay(steps) + return result + + def reset(self) -> None: + """Drop the recordings; the callable records again on its next call.""" + if self._recordings: + # graphs may still be executing; drain the device before releasing them + wp.synchronize_device(self._device) + self._recordings.clear() + + @classmethod + def watch(cls, backend_manager: PhysicsManager) -> None: + """Record every callable again after the physics backend rebinds its buffers or stops, and settle the backend + before each recording: work it queued before (model changes, kinematics) runs then, once, so a recording holds + only the work of its own calls. + + Args: + backend_manager: Physics manager that dispatches the lifecycle events. + """ + # imported here so that the utilities do not load the physics package + from ...physics import PhysicsEvent + + cls.unwatch() + cls._settle = backend_manager.forward + cls._callback_handles = [ + backend_manager.register_callback(cls.invalidate, event) + for event in (PhysicsEvent.PHYSICS_READY, PhysicsEvent.STOP) + ] + + @classmethod + def unwatch(cls) -> None: + """Stop following the physics backend.""" + for handle in cls._callback_handles: + handle.deregister() + cls._callback_handles = [] + cls._settle = None + + @classmethod + def invalidate(cls, payload: Any = None) -> None: + """Record every callable again on its next call.""" + cls.generation += 1 + + def _record(self, args: tuple, kwargs: dict[str, Any]) -> tuple[list, Any]: + """Record the callable as its first run and return the recorded steps and the result.""" + with _record_calls(self._device) as recording: + result = self._fn(*args, **kwargs) + return recording.steps, result + + +@contextlib.contextmanager +def _record_calls(device: wp.Device): + """Record the calls made inside as CUDA graphs split around :func:`eager` calls; the recording is their first run. + + Yields: + The recording, whose steps replay the calls (see :func:`_replay`). + """ + if GraphedCallable._settle is not None: + # physics work queued before the recording runs now, once, instead of on every replay + GraphedCallable._settle() + recording = _Recording(device) + enclosing, GraphedCallable._recording = GraphedCallable._recording, recording + try: + with _paused_gc(), wp.ScopedStream(recording.capture_stream): + recording.begin() + try: + yield recording + for fn in recording.end_calls: + fn() + except BaseException: + recording.abort() + raise + recording.end() + finally: + GraphedCallable._recording = enclosing + + +def _replay(steps: list) -> None: + """Launch the graphs of a recording and repeat its eager calls, in the recorded order.""" + for step in steps: + if isinstance(step, wp.Graph): + wp.capture_launch(step) + else: + fn, args, kwargs = step + fn(*args, **kwargs) + + +class _Recording: + """The steps of one recording: CUDA graphs split around :func:`eager` calls, launched as they end.""" + + def __init__(self, device: wp.Device): + # graphs are captured on the capture stream and launched on the stream the callable runs on + self.stream = wp.get_stream(device) + self.capture_stream = self.stream + self.mode = wp.CaptureMode.THREAD_LOCAL + if has_kit(): + # RTX uses the legacy CUDA stream. A nonblocking stream avoids implicit synchronization. + self.capture_stream = wp.stream_from_torch(torch.cuda.Stream(device=device.alias)) + self.mode = wp.CaptureMode.RELAXED + self.steps: list = [] + # calls recorded after the recorded function (see record_at_end) + self.end_calls: list = [] + self.capturing = False + # identifies the recording to the buffers it refreshes, without keeping its graphs alive + self.token = object() + + def begin(self) -> None: + """Start the next graph.""" + wp.capture_begin(stream=self.capture_stream, capture_mode=self.mode) + self.capturing = True + + def end(self) -> None: + """End the current graph and launch it, since the recording is the first run of the callable.""" + self.capturing = False + graph = wp.capture_end(stream=self.capture_stream) + wp.capture_launch(graph, stream=self.stream) + self.steps.append(graph) + + def abort(self) -> None: + """End the current graph without launching it, after the callable raised.""" + if self.capturing: + self.capturing = False + with contextlib.suppress(Exception): + wp.capture_end(stream=self.capture_stream) + + def split(self, fn: Callable[..., Any], args: tuple, kwargs: dict[str, Any]) -> Any: + """Run a call that cannot be recorded between the current graph and the next one.""" + self.end() + with wp.ScopedStream(self.stream, sync_enter=False): + result = fn(*args, **kwargs) + self.steps.append((fn, args, kwargs)) + self.begin() + return result + + +@contextlib.contextmanager +def _paused_gc(): + """Keep collection-driven frees out of a recording, as ``NewtonQueries.capture_graph`` does. + + Objects allocated during the recording stay in the youngest generation, so collecting that generation afterwards + frees the recording's garbage without the full collection of the whole heap. + """ + was_enabled = gc.isenabled() + gc.disable() + try: + yield + finally: + if was_enabled: + gc.enable() + gc.collect(0) + + +def _argument_key(args: tuple, kwargs: dict[str, Any]) -> tuple: + """Key a call by the pointer, shape, strides, dtype and device of its arrays and the values of its scalars.""" + return tuple(_value_key(value) for value in args) + tuple( + (name, _value_key(value)) for name, value in kwargs.items() + ) + + +def _value_key(value: Any) -> Any: + # views of one allocation share a pointer, so the layout tells them apart + if isinstance(value, wp.array): + return value.ptr, value.shape, value.strides, value.dtype, str(value.device) + if isinstance(value, torch.Tensor): + return value.data_ptr(), value.shape, value.stride(), value.dtype, value.device + if value is None or isinstance(value, (bool, int, float, str)): + return value + if isinstance(value, (list, tuple)): + return tuple(_value_key(item) for item in value) + return id(value) diff --git a/source/isaaclab/isaaclab/visualizers/image_view.py b/source/isaaclab/isaaclab/visualizers/image_view.py index af9d05c73d49..befc55b2bc24 100644 --- a/source/isaaclab/isaaclab/visualizers/image_view.py +++ b/source/isaaclab/isaaclab/visualizers/image_view.py @@ -57,7 +57,7 @@ def __init__(self, cfg: ImageViewCfg, *, camera: Camera | BaseRayCasterCamera | self.camera = camera self.render: Callable[[wp.array | None], wp.array] | None = None self.aspect = 1.0 - self.frame = TimestampedBuffer() + self.frame = TimestampedBuffer(update_in_graph=False) self._host_frame: np.ndarray | None = None self._env_ids: wp.array | None = None self._depth_colors: wp.array | None = None diff --git a/source/isaaclab/test/assets/contract/test_articulation_contract.py b/source/isaaclab/test/assets/contract/test_articulation_contract.py index f6e7d6682a5d..805c19959a5e 100644 --- a/source/isaaclab/test/assets/contract/test_articulation_contract.py +++ b/source/isaaclab/test/assets/contract/test_articulation_contract.py @@ -25,8 +25,11 @@ import warp as wp from isaaclab.assets.articulation.base_articulation_data import BaseArticulationData +from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils import replace +from isaaclab.utils.buffers import reset_timestamps from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.capture import GraphedCallable from .articulation_factory import get_articulation from .backends import backends, read_backend_joint_state, requires @@ -410,6 +413,86 @@ def test_set_coms_invalidates_same_timestamp_dependents(monkeypatch, backend, bo _assert_buffers_stale(art.data, buffers) +# named apart from ``device``, whose Newton CUDA cases the conftest deselects: graph recording needs CUDA +_CUDA_DEVICES = pytest.mark.parametrize("cuda_device", test_devices(DeviceScope.DEFAULT_CUDA)) + + +def _recordable_articulation(backend: str, cuda_device: str, monkeypatch: pytest.MonkeyPatch): + art, view = _articulation(backend, cuda_device, monkeypatch) + if backend == "physx": + # the TensorAPI returns its own stable buffer, where the fixture view returns a copy allocated per call + monkeypatch.setattr( + view, "get_root_transforms", lambda: view._as_structured(view._root_transforms, wp.transformf, (N,)) + ) + return art + + +def _identity_yaw(pose: torch.Tensor) -> torch.Tensor: + pose = pose.clone() + pose[..., 3:] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=pose.device) + return pose + + +@_CUDA_DEVICES +def test_lazy_properties_update_on_every_graph_replay(monkeypatch, backend, cuda_device): + """A lazy property read while a GraphedCallable records updates on each replay, though current at recording. + + The joint acceleration finite difference advances only in :meth:`update`, so the recording leaves it alone. + """ + monkeypatch.setattr(GraphedCallable, "enabled", True) + art = _recordable_articulation(backend, cuda_device, monkeypatch) + art.data.update(dt=0.01) + _ = art.data.heading_w # current when the read is recorded + joint_acc = art.data.joint_acc + joint_acc_before = joint_acc.torch.clone() + + def read(): + _ = art.data.joint_acc + return art.data.heading_w + + graphed = GraphedCallable(read, cuda_device) + heading = graphed() + recorded = heading.torch.clone() + + art.write_root_link_pose_to_sim_index(root_pose=_payload((N,), 7, wp.transformf, cuda_device)) + graphed() + replayed = heading.torch.clone() + torch.testing.assert_close(joint_acc.torch, joint_acc_before) + art.data.update(dt=0.01) + torch.testing.assert_close(replayed, art.data.heading_w.torch) + assert not torch.allclose(replayed, recorded) + + +@_CUDA_DEVICES +def test_invalidation_inside_a_recording_records_the_update_again(monkeypatch, backend, cuda_device): + """A property invalidated between two reads of one recording updates again for the second read. + + The recording writes the root pose in place and invalidates the heading as the root pose writers do. + """ + monkeypatch.setattr(GraphedCallable, "enabled", True) + art = _recordable_articulation(backend, cuda_device, monkeypatch) + rotated = _payload((N,), 7, wp.transformf, cuda_device) + art.write_root_link_pose_to_sim_index(root_pose=_identity_yaw(rotated)) + art.data.update(dt=0.01) + unrotated = art.data.heading_w.torch.clone() + rotated_wp = wp.from_torch(rotated, dtype=wp.transformf) + + def rotate_and_read(): + _ = art.data.heading_w + wp.copy(art.data.root_link_pose_w.warp, rotated_wp) + reset_timestamps([art.data._heading_w]) + return art.data.heading_w + + graphed = GraphedCallable(rotate_and_read, cuda_device) + heading = graphed() # the recording is the first run + graphed() + replayed = heading.torch.clone() + art.write_root_link_pose_to_sim_index(root_pose=rotated) + art.data.update(dt=0.01) + torch.testing.assert_close(replayed, art.data.heading_w.torch) + assert not torch.allclose(replayed, unrotated) + + @requires("physx") def test_physx_com_cache_survives_com_and_joint_writes(monkeypatch): """A COM write refreshes the PhysX COM cache directly, and a joint write leaves it valid.""" diff --git a/source/isaaclab/test/sensors/test_sensor_update_schedule.py b/source/isaaclab/test/sensors/test_sensor_update_schedule.py index 07c404d7e79f..4d6b253698b7 100644 --- a/source/isaaclab/test/sensors/test_sensor_update_schedule.py +++ b/source/isaaclab/test/sensors/test_sensor_update_schedule.py @@ -20,6 +20,7 @@ from isaaclab.paths import ISAACLAB_ROOT from isaaclab.sensors import SensorBase, SensorBaseCfg from isaaclab.test.utils import DeviceScope, test_devices +from isaaclab.utils.warp.capture import GraphedCallable pytestmark = pytest.mark.unit @@ -175,3 +176,65 @@ def test_reset_cache_refreshes_on_positive_update_or_explicit_invalidation(devic sensor._invalidate_buffers() sensor.update(0.0, force_recompute=True) assert sensor.refreshes == [[1], [1]] + + +@wp.kernel +def _count_refresh(env_mask: wp.array(dtype=wp.bool), refreshes: wp.array(dtype=wp.int32)): + env = wp.tid() + if env_mask[env]: + refreshes[env] += 1 + + +class _DeviceRefreshSensor(_RefreshLogSensor): + """Sensor that counts the buffer refreshes of each environment on the device, as a CUDA graph replays them.""" + + def __init__(self, device: str): + super().__init__(update_period=0.0, device=device) + self.device_refreshes = wp.zeros(self._num_envs, dtype=wp.int32, device=device) + + def _update_buffers_impl(self, env_mask: wp.array): + wp.launch(_count_refresh, dim=self._num_envs, inputs=[env_mask, self.device_refreshes], device=self._device) + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_recorded_read_refreshes_on_every_replay(device, monkeypatch): + """A read recorded while the sensor is not dirty, as after a reset, still refreshes the sensor on each replay.""" + monkeypatch.setattr(GraphedCallable, "enabled", True) + sensor = _DeviceRefreshSensor(device) + sensor.update(0.005) + _ = sensor.data # the sensor is clean when the read is recorded + read = GraphedCallable(lambda: sensor.data, device) + read() # records the refresh of the outdated environments, none yet + for _ in range(3): + sensor.update(0.005) + read() + # one eager refresh, then one per replay + assert sensor.device_refreshes.numpy().tolist() == [4, 4] + + +class _Reader: + """Two recorded parts that read the same sensor, as the post-physics and observation parts of a step do.""" + + def __init__(self, sensor: _DeviceRefreshSensor): + self.sensor = sensor + self.first = GraphedCallable(self._read, sensor._device) + self.second = GraphedCallable(self._read, sensor._device) + + def _read(self): + _ = self.sensor.data + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_recorded_parts_reading_a_sensor_refresh_it_each_step(device, monkeypatch): + """The data of a sensor that recorded parts read refreshes once per step, also when a step skips the part that + refreshed it first: each recording holds the refresh of the environments still outdated.""" + monkeypatch.setattr(GraphedCallable, "enabled", True) + sensor = _DeviceRefreshSensor(device) + reader = _Reader(sensor) + for _ in range(4): # the first step records both parts, the others replay them + sensor.update(0.005) + reader.first() + reader.second() + sensor.update(0.005) + reader.second() + assert sensor.device_refreshes.numpy().tolist() == [5, 5] diff --git a/source/isaaclab/test/sim/test_newton_manager_visualization_state.py b/source/isaaclab/test/sim/test_newton_manager_visualization_state.py index 1873bd43e318..8c6e332db79a 100644 --- a/source/isaaclab/test/sim/test_newton_manager_visualization_state.py +++ b/source/isaaclab/test/sim/test_newton_manager_visualization_state.py @@ -146,6 +146,7 @@ def test_native_publication_reuses_clean_fk_and_refreshes_writes_and_swaps(monke state_version=0, kinematics_dirty=False, transforms_may_change_on_graph_replay=False, + fk_on_every_step=False, device=wp.get_device("cpu"), ) monkeypatch.setattr(owner, "backend", newton_backend) diff --git a/source/isaaclab/test/utils/test_timestamped_buffer.py b/source/isaaclab/test/utils/test_timestamped_buffer.py new file mode 100644 index 000000000000..a4bca98c248e --- /dev/null +++ b/source/isaaclab/test/utils/test_timestamped_buffer.py @@ -0,0 +1,124 @@ +# 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 + +"""When a :class:`TimestampedBuffer` owner updates its data, eagerly and while a CUDA graph records.""" + +from __future__ import annotations + +import pytest +import warp as wp + +from isaaclab.test.utils import DeviceScope, test_devices +from isaaclab.utils.buffers import TimestampedBuffer, reset_timestamps +from isaaclab.utils.warp.capture import GraphedCallable + +pytestmark = pytest.mark.unit + + +@wp.kernel +def _count_update(updates: wp.array(dtype=wp.int32)): + updates[0] += 1 + + +class _LazyValue: + """A lazily updated value counting its updates on the device.""" + + def __init__(self, device: str, update_in_graph: bool = True): + self.device = device + self.timestamp = 0.0 + self.updates = wp.zeros(1, dtype=wp.int32, device=device) + self._value = TimestampedBuffer(self.updates, update_in_graph=update_in_graph) + + def read(self) -> None: + if self._value.timestamp < self.timestamp: + wp.launch(_count_update, dim=1, inputs=[self.updates], device=self.device) + self._value.timestamp = self.timestamp + + @property + def num_updates(self) -> int: + return int(self.updates.numpy()[0]) + + +def test_eager_reads_update_once_per_timestamp(): + value = _LazyValue("cpu") + for _ in range(2): + value.timestamp += 0.01 + value.read() + value.read() + reset_timestamps([value._value]) + value.read() + assert value.num_updates == 3 + + +@pytest.fixture +def enabled(monkeypatch): + monkeypatch.setattr(GraphedCallable, "enabled", True) + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_recorded_read_updates_on_every_replay(device, enabled): + """A read recorded while the data is current still updates it on each replay, once per recording.""" + value = _LazyValue(device) + value.read() # the data is current when the read is recorded + + def read_twice(): + value.read() + value.read() + + graphed = GraphedCallable(read_twice, device) + graphed() # records the update and runs it once + for _ in range(3): + value.timestamp += 0.01 + graphed() + # one eager update, one when recording, then one per replay + assert value.num_updates == 5 + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_each_recording_holds_its_own_update(device, enabled): + """An invalidation inside a recording records the update again, and a later recording records its own.""" + value = _LazyValue(device) + value.read() + + def read_invalidate_read(): + value.read() + reset_timestamps([value._value]) + value.read() + + invalidated = GraphedCallable(read_invalidate_read, device) + later = GraphedCallable(value.read, device) + invalidated() + later() + value.read() # an eager read after the recordings keeps the eager rule + assert value.num_updates == 4 + invalidated() + later() + assert value.num_updates == 7 + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_an_opted_out_buffer_keeps_the_timestamp_rule_while_recording(device, enabled): + """A buffer opting out records its update only when it is stale by timestamp, as outside a recording.""" + value = _LazyValue(device, update_in_graph=False) + value.read() + graphed = GraphedCallable(value.read, device) + graphed() + assert value._value.timestamp == value.timestamp + graphed() + assert value.num_updates == 1 + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_a_raw_capture_keeps_the_timestamp_rule(device): + """A graph captured without :class:`GraphedCallable` holds the update only when the data is stale by timestamp.""" + value = _LazyValue(device) + value.read() + with wp.ScopedCapture(device=device) as capture: + value.read() + assert value._value.timestamp == value.timestamp + for _ in range(2): + value.timestamp += 0.01 + wp.capture_launch(capture.graph) + assert value.num_updates == 1 diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py new file mode 100644 index 000000000000..522c2efda6b1 --- /dev/null +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -0,0 +1,261 @@ +# 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 + +"""Tests for the CUDA graph recording of the Warp frontend's step parts.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import warp as wp + +from isaaclab.utils.warp.capture import GraphedCallable, eager, eager_method + +wp.init() +pytestmark = [pytest.mark.kitless, pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA device required")] + +DEVICE = "cuda:0" + + +@wp.kernel +def _affine(values: wp.array(dtype=wp.int32), scale: wp.int32, shift: wp.int32): + values[wp.tid()] = values[wp.tid()] * scale + shift + + +def _num_graphs(graphed: GraphedCallable) -> int: + """Number of graphs recorded for a callable.""" + return sum(isinstance(step, wp.Graph) for steps, _ in graphed._recordings.values() for step in steps) + + +class _Affine: + """Callable that applies ``x * scale + shift`` on the device and counts its Python invocations. + + A ``shift`` passed to the call replaces the configured one for that call. + """ + + def __init__(self, scale: int = 1, shift: int = 1): + self.scale, self.shift, self.calls = scale, shift, 0 + + def __call__(self, values: wp.array, shift: int | None = None) -> wp.array: + self.calls += 1 + shift = self.shift if shift is None else shift + wp.launch(_affine, dim=values.shape[0], inputs=[values, self.scale, shift], device=values.device) + return values + + +def _read(values: wp.array) -> list[int]: + wp.synchronize_device(values.device) + return values.numpy().tolist() + + +@pytest.fixture(autouse=True) +def enabled(monkeypatch): + monkeypatch.setattr(GraphedCallable, "enabled", True) + + +def test_first_call_records_and_runs_the_callable_once(): + """Recording has no eager warm-up: a stateful callable advances once per call, including the first.""" + fn = _Affine() + graphed = GraphedCallable(fn, DEVICE) + values = wp.zeros(2, dtype=wp.int32, device=DEVICE) + + assert graphed(values) is values + assert _read(values) == [1, 1] + assert graphed(values) is values + assert _read(values) == [2, 2] + assert (fn.calls, _num_graphs(graphed)) == (1, 1), "the second call must replay the recorded graph" + + +def test_changed_argument_records_the_callable_again(): + """A graph replays its recorded pointers and scalars, so a new array or scalar records a new graph.""" + fn = _Affine() + graphed = GraphedCallable(fn, DEVICE) + old, new = wp.zeros(1, dtype=wp.int32, device=DEVICE), wp.zeros(1, dtype=wp.int32, device=DEVICE) + + graphed(old) + graphed(new) + graphed(new) + graphed(new, 5) + graphed(new, 5) + # replays of the shift-5 recording add 5 each: 0 -> 1 -> 2 -> 7 -> 12 + assert (_read(old), _read(new), fn.calls, _num_graphs(graphed)) == ([1], [12], 3, 3) + + +def test_views_of_one_array_record_their_own_graphs(): + """Views that share an address but differ in length record their own graphs, each replaying over its length.""" + fn = _Affine() + graphed = GraphedCallable(fn, DEVICE) + values = wp.zeros(4, dtype=wp.int32, device=DEVICE) + + graphed(values[:2]) + graphed(values[:4]) + graphed(values[:4]) + assert (_read(values), fn.calls, _num_graphs(graphed)) == ([3, 3, 2, 2], 2, 2) + + +def test_physics_rebind_records_the_callable_again(): + fn = _Affine() + graphed = GraphedCallable(fn, DEVICE) + values = wp.zeros(1, dtype=wp.int32, device=DEVICE) + graphed(values) + + GraphedCallable.invalidate() + graphed(values) + graphed(values) + assert (fn.calls, _read(values), _num_graphs(graphed)) == (2, [3], 1) + + +def test_callable_runs_eagerly_when_disabled_or_on_cpu(monkeypatch): + on_cpu = _Affine() + cpu_graphed = GraphedCallable(on_cpu, "cpu") + cpu_values = wp.zeros(1, dtype=wp.int32, device="cpu") + cpu_graphed(cpu_values) + cpu_graphed(cpu_values) + + monkeypatch.setattr(GraphedCallable, "enabled", False) + disabled = _Affine() + graphed = GraphedCallable(disabled, DEVICE) + values = wp.zeros(1, dtype=wp.int32, device=DEVICE) + graphed(values) + graphed(values) + + assert (on_cpu.calls, _read(cpu_values), _num_graphs(cpu_graphed)) == (2, [2], 0) + assert (disabled.calls, _read(values), _num_graphs(graphed)) == (2, [2], 0) + + +def test_eager_call_runs_between_its_graphs_on_every_call(): + """The recording runs the graph before an eager call first, and every replay keeps that order.""" + before, between, after = _Affine(2, 0), _Affine(1, 10), _Affine(3, 0) + + def body(values: wp.array) -> wp.array: + before(values) + eager(between, values) + return after(values) + + graphed = GraphedCallable(body, DEVICE) + values = wp.ones(1, dtype=wp.int32, device=DEVICE) + + graphed(values) + # the non-commuting steps only give these values in order: 1 * 2 + 10 = 12 -> 36, then 36 * 2 + 10 = 82 -> 246 + assert _read(values) == [36] + graphed(values) + assert (_read(values), between.calls, before.calls, after.calls, _num_graphs(graphed)) == ([246], 2, 1, 1, 2) + + +def test_eager_call_first_runs_before_the_recorded_work(): + """A callable making its eager call first runs it before its recorded work, also when it replays the recording.""" + eager_fn, first, second = _Affine(1, 10), _Affine(2, 0), _Affine(3, 0) + + def body(values: wp.array) -> wp.array: + eager(eager_fn, values) + first(values) + return second(values) + + graphed = GraphedCallable(body, DEVICE) + values = wp.ones(1, dtype=wp.int32, device=DEVICE) + graphed(values) + graphed(values) + + assert _read(values) == [((1 + 10) * 6 + 10) * 6] + + +def test_eager_call_of_a_nested_callable_splits_the_enclosing_recording(): + eager_fn, inner_fn, outer_fn = _Affine(1, 10), _Affine(2, 0), _Affine(3, 0) + nested = GraphedCallable(lambda values: (eager(eager_fn, values), inner_fn(values)), DEVICE) + outer = GraphedCallable(lambda values: (outer_fn(values), nested(values)), DEVICE) + values = wp.ones(1, dtype=wp.int32, device=DEVICE) + + outer(values) + outer(values) + # 1 * 3 + 10 = 13 -> 26, then 26 * 3 + 10 = 88 -> 176: the nested eager call runs between the outer graphs + assert (_read(values), eager_fn.calls, inner_fn.calls, outer_fn.calls) == ([176], 2, 1, 1) + assert (_num_graphs(outer), _num_graphs(nested)) == (2, 0) + + +def test_eager_call_raises_inside_a_capture_no_callable_started(): + """A call that cannot be recorded must not be captured silently into a foreign graph.""" + fn = _Affine() + values = wp.zeros(1, dtype=wp.int32, device=DEVICE) + + with pytest.raises(RuntimeError, match="no GraphedCallable started"): + with wp.ScopedDevice(DEVICE), wp.ScopedCapture(): + eager(fn, values) + assert fn.calls == 0 + + +def test_callable_raising_while_recording_ends_the_capture(): + """A failed recording must not leave the device capturing; the next call records again.""" + recorded, eager_fn = _Affine(2, 0), _Affine(1, 10) + + def body(values: wp.array) -> wp.array: + recorded(values) + eager(eager_fn, values) + if recorded.calls == 1: + raise ValueError("first recording fails") + return values + + graphed = GraphedCallable(body, DEVICE) + values = wp.ones(1, dtype=wp.int32, device=DEVICE) + + with pytest.raises(ValueError, match="first recording fails"): + graphed(values) + assert not wp.get_device(DEVICE).is_capturing + graphed(values) + # the failed recording ran its first graph and the eager call: 1 * 2 + 10 = 12, then 12 * 2 + 10 = 34 + assert (_read(values), _num_graphs(graphed)) == ([34], 2) + + +class _ChangeRegistry: + """Host-side registry, like a solver's queue of model changes, that a recording cannot hold.""" + + def __init__(self): + self.changes = [] + + @eager_method + def add(self, change: int): + self.changes.append(change) + + +def test_eager_method_repeats_host_work_on_every_replay(): + """A recorded writer's host registration runs on the recording and on each replay, after the recorded kernel.""" + registry = _ChangeRegistry() + values = wp.zeros(1, dtype=wp.int32, device=DEVICE) + fn = _Affine() + + def writer(): + fn(values) + registry.add(7) + + graphed = GraphedCallable(writer, DEVICE) + for _ in range(3): + graphed() + assert (registry.changes, _read(values), fn.calls) == ([7, 7, 7], [3], 1) + + +def test_recording_settles_the_watched_backend_first(): + """Work the physics backend queued before a recording runs once, before it, not on every replay.""" + values = wp.zeros(1, dtype=wp.int32, device=DEVICE) + + class Backend: + pending = True + + def register_callback(self, fn, event): + return SimpleNamespace(deregister=lambda: None) + + def forward(self): + if self.pending: + wp.launch(_affine, dim=1, inputs=[values, 1, 1], device=DEVICE) + self.pending = False + + backend = Backend() + GraphedCallable.watch(backend) + try: + graphed = GraphedCallable(backend.forward, DEVICE) + for _ in range(3): + graphed() + finally: + GraphedCallable.unwatch() + assert _read(values) == [1] diff --git a/source/isaaclab_experimental/changelog.d/jichuanh-warp-recording-utils.skip b/source/isaaclab_experimental/changelog.d/jichuanh-warp-recording-utils.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py index f2e947fa9a06..ce6e434199d7 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py @@ -96,11 +96,9 @@ def base_pos_z(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEntit # Inline Tier 1 access: these observations derive body-frame quantities directly from -# root_link_pose_w (transformf) and root_com_vel_w (spatial_vectorf), avoiding the lazy -# TimestampedWarpBuffer properties which are not CUDA-graph-capturable. -# See GRAPH_CAPTURE_MIGRATION.md in isaaclab_newton for background. -# If ArticulationData Tier 2 lazy update is made graph-safe in the future, these can -# revert to reading the pre-computed .data buffers (simpler, avoids redundant rotations). +# root_link_pose_w (transformf) and root_com_vel_w (spatial_vectorf). +# Lazy asset data is recorded into CUDA graphs as well (a recording recomputes it on every replay), +# so these can read the pre-computed .data buffers (simpler, avoids redundant rotations). @wp.kernel diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py index 74f5fe60d24a..83d2adabc7a5 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py @@ -128,11 +128,9 @@ def __call__( # Inline Tier 1 access: these rewards derive body-frame quantities directly from -# root_link_pose_w (transformf) and root_com_vel_w (spatial_vectorf), avoiding the lazy -# TimestampedWarpBuffer properties which are not CUDA-graph-capturable. -# See GRAPH_CAPTURE_MIGRATION.md in isaaclab_newton for background. -# If ArticulationData Tier 2 lazy update is made graph-safe in the future, these can -# revert to reading the pre-computed .data buffers (simpler, avoids redundant rotations). +# root_link_pose_w (transformf) and root_com_vel_w (spatial_vectorf). +# Lazy asset data is recorded into CUDA graphs as well (a recording recomputes it on every replay), +# so these can read the pre-computed .data buffers (simpler, avoids redundant rotations). @wp.kernel diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst new file mode 100644 index 000000000000..b37a04119804 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -0,0 +1,4 @@ +* Changed Newton to reset the solver and evaluate forward kinematics once after a state write recorded in a Warp + stage, inside that stage's CUDA graph, instead of before every physics step once any write was recorded. State + written inside a raw CUDA graph capture still evaluates them before every physics step + (:attr:`~isaaclab_newton.physics.NewtonBackend.fk_on_every_step`). diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst new file mode 100644 index 000000000000..87d74a4fbd57 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -0,0 +1,9 @@ +* Fixed model changes registered with :meth:`~isaaclab_newton.physics.NewtonManager.add_model_change` inside a CUDA + graph recording, such as fixed tendon property writes, reaching the solver only when the graph was recorded: a part + of the step recorded with :class:`~isaaclab.utils.warp.capture.GraphedCallable` registers the change again on each + replay, and any other capture records the solver's refresh. +* Fixed lazily computed asset data properties, such as + :attr:`~isaaclab_newton.assets.ArticulationData.projected_gravity_b`, inside a CUDA graph recorded by + :class:`~isaaclab.utils.warp.capture.GraphedCallable`: 15 of them raised while a graph recorded, and the others + replayed the value of the recording step when they were current at recording. A recording now holds their + update, so every replay recomputes them. diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py index 083068dc311f..5c645d94f7a1 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation.py @@ -34,6 +34,7 @@ from isaaclab.utils.version import get_isaac_sim_version, has_kit from isaaclab.utils.warp import ProxyArray, memory from isaaclab.utils.warp import math as warp_math +from isaaclab.utils.warp.capture import eager_method from isaaclab.utils.warp.memory import resolve_1d_mask, resolve_ids, write_2d_with_mask from isaaclab.utils.wrench_composer import WrenchComposer @@ -2371,6 +2372,7 @@ def set_coms_index( # tell the physics engine that some of the body properties have been updated self._backend_manager.add_model_change(ModelFlags.BODY_INERTIAL_PROPERTIES) + @eager_method # converts CoM poses with torch and notifies the solver on the host def set_coms_mask( self, *, diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py index 0cb51991a716..7d91449edadd 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py @@ -158,10 +158,39 @@ def update(self, dt: float) -> None: self._sim_timestamp += dt # Replaying an outer capture of the step skips the backend's version increments, so invalidate here. self._backend_manager.backend.state_version += 1 - # Trigger an update of the joint and body com acceleration buffers at a higher frequency - # since we do finite differencing. - self.joint_acc - self.body_com_acc_w + # finite differences advance once per physics step: computed here over the step, then read as they are; + # a zero step (the update at initialization) has no difference to take, so they keep their values + if dt == 0.0: + return + wp.launch( + articulation_kernels.get_joint_acc_from_joint_vel, + dim=(self._num_instances, self._num_joints), + inputs=[ + self.joint_vel.warp, + self._previous_joint_vel, + dt, + ], + outputs=[ + self._joint_acc.data, + ], + device=self.device, + ) + self._joint_acc.timestamp = self._sim_timestamp + body_ordering = self.body_ordering + wp.launch( + articulation_kernels.get_body_com_acc_from_body_com_vel_ordered, + dim=(self._num_instances, self._num_bodies), + device=self.device, + inputs=[ + self._sim_bind_body_com_vel_w, + self._previous_body_com_vel, + body_ordering.user_to_backend if body_ordering is not None else None, + body_ordering is not None, + dt, + ], + outputs=[self._body_com_acc_w.data], + ) + self._body_com_acc_w.timestamp = self._sim_timestamp def _update_body_state(self) -> None: """Resolve shared FK, then refresh this view's reordered body state after a manual write.""" @@ -845,24 +874,6 @@ def body_com_acc_w(self) -> ProxyArray: All values are relative to the world. """ - if self._body_com_acc_w.timestamp < self._sim_timestamp: - # Finite-difference over the elapsed time, which spans the decimation when Newton owns it. - time_elapsed = self._sim_timestamp - self._body_com_acc_w.timestamp - body_ordering = self.body_ordering - wp.launch( - articulation_kernels.get_body_com_acc_from_body_com_vel_ordered, - dim=(self._num_instances, self._num_bodies), - device=self.device, - inputs=[ - self._sim_bind_body_com_vel_w, - self._previous_body_com_vel, - body_ordering.user_to_backend if body_ordering is not None else None, - body_ordering is not None, - time_elapsed, - ], - outputs=[self._body_com_acc_w.data], - ) - self._body_com_acc_w.timestamp = self._sim_timestamp return self._body_com_acc_w_ta @property @@ -1116,23 +1127,6 @@ def joint_acc(self) -> ProxyArray: Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ - if self._joint_acc.timestamp < self._sim_timestamp: - # note: we use finite differencing to compute acceleration - time_elapsed = self._sim_timestamp - self._joint_acc.timestamp - wp.launch( - articulation_kernels.get_joint_acc_from_joint_vel, - dim=(self._num_instances, self._num_joints), - inputs=[ - self.joint_vel.warp, - self._previous_joint_vel, - time_elapsed, - ], - outputs=[ - self._joint_acc.data, - ], - device=self.device, - ) - self._joint_acc.timestamp = self._sim_timestamp return self._joint_acc_ta """ @@ -1964,7 +1958,8 @@ def _configure_joint_ordering_buffers(self) -> None: self._previous_joint_vel.assign(self._sim_bind_joint_vel) self._actuator_stiffness.assign(self._sim_bind_joint_stiffness_sim) self._actuator_damping.assign(self._sim_bind_joint_damping_sim) - reset_timestamps([self._joint_acc, self._joint_pos_limits]) + self._joint_acc.data.zero_() + reset_timestamps([self._joint_pos_limits]) def _configure_body_ordering_buffers(self) -> None: """Allocate or release buffers owned only by nonidentity body ordering.""" @@ -1988,12 +1983,12 @@ def _configure_body_ordering_buffers(self) -> None: self._body_inertia_user = None self._body_com_pos_b_user = None + self._body_com_acc_w.data.zero_() reset_timestamps( [ self._body_link_vel_w, self._body_com_pose_b, self._body_com_pose_w, - self._body_com_acc_w, self._body_state_w, self._body_link_state_w, self._body_com_state_w, 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 31fc39dcd2d7..f130c4ca24da 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 @@ -21,6 +21,7 @@ from isaaclab.assets.rigid_object.base_rigid_object import BaseRigidObject from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source from isaaclab.utils.warp import ProxyArray, memory +from isaaclab.utils.warp.capture import eager_method from isaaclab.utils.warp.memory import resolve_ids from isaaclab.utils.wrench_composer import WrenchComposer @@ -842,6 +843,7 @@ def set_coms_index( # tell the physics engine that some of the body properties have been updated self._backend_manager.add_model_change(ModelFlags.BODY_INERTIAL_PROPERTIES) + @eager_method # converts CoM poses with torch and notifies the solver on the host def set_coms_mask( self, *, diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py index 688a4f109a8a..6485d2e63f10 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py @@ -128,9 +128,24 @@ def update(self, dt: float) -> None: self._sim_timestamp += dt # Replaying an outer capture of the step skips the backend's version increments, so invalidate here. self._backend_manager.backend.state_version += 1 - # Trigger an update of the body com acceleration buffer at a higher frequency - # since we do finite differencing. - self.body_com_acc_w + # finite differences advance once per physics step: computed here over the step, then read as they are; + # a zero step (the update at initialization) has no difference to take, so they keep their values + if dt == 0.0: + return + wp.launch( + shared_kernels.derive_body_acceleration_from_body_com_velocities, + dim=(self._num_instances, 1), + device=self.device, + inputs=[ + self._sim_bind_body_com_vel_w, + dt, + self._previous_body_com_vel, + ], + outputs=[ + self._body_com_acc_w.data, + ], + ) + self._body_com_acc_w.timestamp = self._sim_timestamp def _reset_pose(self) -> None: """Invalidate pose-dependent caches after an authoritative state write.""" @@ -396,25 +411,6 @@ def body_com_acc_w(self) -> ProxyArray: Shape is (num_instances, 1), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 1, 6). This quantity is the acceleration of the rigid bodies' center of mass frame relative to the world. """ - if self._body_com_acc_w.timestamp < self._sim_timestamp: - # Finite-difference over the elapsed time, which spans the decimation when Newton owns it. - time_elapsed = self._sim_timestamp - self._body_com_acc_w.timestamp - wp.launch( - shared_kernels.derive_body_acceleration_from_body_com_velocities, - dim=(self._num_instances, 1), - device=self.device, - inputs=[ - self._sim_bind_body_com_vel_w, - time_elapsed, - self._previous_body_com_vel, - ], - outputs=[ - self._body_com_acc_w.data, - ], - ) - # set the buffer data and timestamp - self._body_com_acc_w.timestamp = self._sim_timestamp - # update the previous velocity return self._body_com_acc_w_ta @property 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 67d5788377b0..aff140844eeb 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 @@ -22,6 +22,7 @@ from isaaclab.assets.rigid_object_collection.base_rigid_object_collection import BaseRigidObjectCollection from isaaclab.utils import clone, validate from isaaclab.utils.warp import ProxyArray, memory +from isaaclab.utils.warp.capture import eager_method from isaaclab.utils.warp.memory import resolve_ids from isaaclab.utils.wrench_composer import WrenchComposer @@ -957,6 +958,7 @@ def set_coms_index( # Tell the physics engine that some of the body properties have been updated self._backend_manager.add_model_change(ModelFlags.BODY_INERTIAL_PROPERTIES) + @eager_method # converts CoM poses with torch and notifies the solver on the host def set_coms_mask( self, *, diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py index ca273624e43e..eb8a66d4b914 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py @@ -132,9 +132,24 @@ def update(self, dt: float) -> None: self._sim_timestamp += dt # Replaying an outer capture of the step skips the backend's version increments, so invalidate here. self._backend_manager.backend.state_version += 1 - # Trigger an update of the body com acceleration buffer at a higher frequency - # since we do finite differencing. - self.body_com_acc_w + # finite differences advance once per physics step: computed here over the step, then read as they are; + # a zero step (the update at initialization) has no difference to take, so they keep their values + if dt == 0.0: + return + wp.launch( + shared_kernels.derive_body_acceleration_from_body_com_velocities, + dim=(self.num_instances, self.num_bodies), + device=self.device, + inputs=[ + self.body_com_vel_w.warp, + dt, + self._previous_body_com_vel, + ], + outputs=[ + self._body_com_acc_w.data, + ], + ) + self._body_com_acc_w.timestamp = self._sim_timestamp def _reset_pose(self) -> None: """Invalidate pose-dependent caches after an authoritative state write.""" @@ -338,23 +353,6 @@ def body_com_acc_w(self) -> ProxyArray: (num_instances, num_bodies, 6). This quantity is the acceleration of the rigid bodies' center of mass frame relative to the world. """ - if self._body_com_acc_w.timestamp < self._sim_timestamp: - # Finite-difference over the elapsed time, which spans the decimation when Newton owns it. - time_elapsed = self._sim_timestamp - self._body_com_acc_w.timestamp - wp.launch( - shared_kernels.derive_body_acceleration_from_body_com_velocities, - dim=(self.num_instances, self.num_bodies), - device=self.device, - inputs=[ - self.body_com_vel_w.warp, - time_elapsed, - self._previous_body_com_vel, - ], - outputs=[ - self._body_com_acc_w.data, - ], - ) - self._body_com_acc_w.timestamp = self._sim_timestamp return self._body_com_acc_w_ta @property diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index c82797432abe..cbf7e59ef1c4 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -156,7 +156,7 @@ def __init__(self, cfg: NewtonBackendCfg, builder: ModelBuilder | None = None, * {} if simulation else {path: bounds[0] for path, bounds in self.deformable_ranges.items()} ) """First particle index per deformable label on a render-only backend; empty on a simulation backend.""" - self.bvh_refit = TimestampedBuffer() + self.bvh_refit = TimestampedBuffer(update_in_graph=False) """Timestamp of the last BVH refit, shared by ray casters and cameras.""" self.cfg: NewtonCfg | None = physics_cfg if simulation else None """Newton physics settings, or ``None`` for a render-only backend.""" @@ -197,7 +197,10 @@ def __init__(self, cfg: NewtonBackendCfg, builder: ModelBuilder | None = None, * self.kinematics_dirty = False """Whether joint coordinates changed since the last forward kinematics.""" self.transforms_may_change_on_graph_replay = False - """Whether state was written inside an outer graph capture; :meth:`forward` then always runs.""" + """Whether state was written inside an outer graph capture, so reads refresh derived state.""" + self.fk_on_every_step = False + """Whether a raw graph capture replays state writes without their forward kinematics; :meth:`forward` + then always runs.""" self.model_changes: set[int] = set() """Model-property categories to notify the solver of at the next step.""" self.warned_model_changes: set[int] = set() @@ -237,7 +240,7 @@ def close(self) -> None: """Drop native handles after consumers release their bindings.""" self.model = self.state_0 = self.state_1 = self.control = None self.particle_ranges, self.deformable_ranges, self.geometry_offsets = {}, {}, {} - self.bvh_refit = TimestampedBuffer() + self.bvh_refit = TimestampedBuffer(update_in_graph=False) if self.cfg is not None: self.solver = self.solver_ops = self.collision_pipeline = self.contacts = self.contact_observables = None self.actuators = None @@ -346,7 +349,7 @@ def invalidate_body_state(self, env_mask: wp.array | None = None, *, consume_mas def forward(self) -> None: """Reset solver internals and evaluate FK for the flagged worlds and articulations, then clear the flags.""" self.notify_model_changes() - if not (self.kinematics_dirty or self.transforms_may_change_on_graph_replay): + if not (self.kinematics_dirty or self.fk_on_every_step): return ops, state = self.solver_ops, self.state_0 if ops is None: diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index 94f33e96f54c..3cca7e6ecd81 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -27,6 +27,7 @@ from isaaclab.utils.string import resolve_matching_names from isaaclab.utils.timer import Timer from isaaclab.utils.version import has_kit +from isaaclab.utils.warp.capture import record_at_end from isaaclab_newton.physics.newton_backend_cfg import NewtonBackendCfg from isaaclab_newton.physics.newton_builder_cfg import NewtonBuilderCfg @@ -185,9 +186,17 @@ def _mark_particles_dirty(self) -> None: self._flag_outer_capture() def _flag_outer_capture(self) -> None: - """Flag writes recorded into an outer graph capture.""" - if self.backend.device.is_capturing: - self.backend.transforms_may_change_on_graph_replay = True + """Flag writes recorded into an outer graph capture. + + A :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording the write also records :meth:`forward` at + its end, so each replay resets the solver and evaluates FK once after the write; a raw capture cannot, so FK + then runs before every physics step. + """ + backend = self.backend + if backend.device.is_capturing: + backend.transforms_may_change_on_graph_replay = True + if not record_at_end(backend.forward): + backend.fk_on_every_step = True def step(self) -> None: """Advance physics by one environment step, or one physics step when the environment runs decimation.""" diff --git a/source/isaaclab_newton/isaaclab_newton/test/fixtures/mock_newton.py b/source/isaaclab_newton/isaaclab_newton/test/fixtures/mock_newton.py index 6bd24fe2cbc7..efd33cafa840 100644 --- a/source/isaaclab_newton/isaaclab_newton/test/fixtures/mock_newton.py +++ b/source/isaaclab_newton/isaaclab_newton/test/fixtures/mock_newton.py @@ -83,6 +83,7 @@ def create_mock_newton_manager( state_version=0, device=wp.get_device("cpu"), transforms_may_change_on_graph_replay=False, + fk_on_every_step=False, ) return manager diff --git a/source/isaaclab_newton/test/assets/test_articulation.py b/source/isaaclab_newton/test/assets/test_articulation.py index cdac5ca0216f..f73cf0c2eef3 100644 --- a/source/isaaclab_newton/test/assets/test_articulation.py +++ b/source/isaaclab_newton/test/assets/test_articulation.py @@ -438,6 +438,7 @@ def test_task_space_allocation_and_capture(device, first_property): state_version=0, device=model.device, transforms_may_change_on_graph_replay=False, + fk_on_every_step=False, ) view = ArticulationView(model, "Robot", exclude_joint_types=[JointType.FIXED]) eager = ArticulationData(view, device, backend_manager=backend_manager) @@ -492,6 +493,7 @@ def test_world_hinged_root_has_no_base_dofs(device): state_version=0, device=model.device, transforms_may_change_on_graph_replay=False, + fk_on_every_step=False, ) root_view = ArticulationView(model, "Robot") data = ArticulationData(root_view, device, backend_manager=backend_manager) @@ -931,6 +933,22 @@ def scene(composite_scene: _Scene) -> _Scene: return composite_scene +def test_zero_step_update_keeps_the_accelerations(scene: _Scene) -> None: + """``update(0.0)``, which an articulation runs at initialization, takes no finite difference (a division by zero). + + The joint and body accelerations keep their values, as main's lazy finite difference gives no NaN before the first + step either. + """ + articulation = scene.articulations["floating"] + scene.step("floating") + joint_acc = articulation.data.joint_acc.torch.clone() + body_com_acc_w = articulation.data.body_com_acc_w.torch.clone() + + articulation.update(0.0) + torch.testing.assert_close(articulation.data.joint_acc.torch, joint_acc) + torch.testing.assert_close(articulation.data.body_com_acc_w.torch, body_com_acc_w) + + def _model_attribute(articulation: Articulation, name: str) -> torch.Tensor: """Read one live Newton model attribute through the articulation's view, in backend order.""" return wp.to_torch(articulation.root_view.get_attribute(name, articulation._backend_manager.backend.model))[:, 0] diff --git a/source/isaaclab_newton/test/assets/test_joint_coordinates.py b/source/isaaclab_newton/test/assets/test_joint_coordinates.py index 2d9fb46de182..17d5c7e96552 100644 --- a/source/isaaclab_newton/test/assets/test_joint_coordinates.py +++ b/source/isaaclab_newton/test/assets/test_joint_coordinates.py @@ -111,6 +111,7 @@ def test_joint_commands_preserve_coordinate_layout(ball_joint): state_version=0, device=model.device, transforms_may_change_on_graph_replay=False, + fk_on_every_step=False, ) view = ArticulationView(model, "Robot", exclude_joint_types=[newton.JointType.FREE]) data = ArticulationData(view, "cpu", backend_manager=backend_manager) diff --git a/source/isaaclab_newton/test/assets/test_rigid_object.py b/source/isaaclab_newton/test/assets/test_rigid_object.py index 7257c28f8a0f..08a3a7ccd69d 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object.py @@ -380,6 +380,19 @@ def scene(shared_scene: _Scene) -> _Scene: return shared_scene +def test_zero_step_update_keeps_the_accelerations(scene: _Scene) -> None: + """``update(0.0)``, which the assets run at initialization, takes no finite difference (a division by zero). + + The body accelerations keep their values, as main's lazy finite difference gives no NaN before the first step + either. + """ + scene.step() + for asset in (scene.cube, scene.collection): + body_com_acc_w = asset.data.body_com_acc_w.torch.clone() + asset.update(0.0) + torch.testing.assert_close(asset.data.body_com_acc_w.torch, body_com_acc_w) + + @pytest.mark.isaacsim_ci def test_external_force_on_single_body(scene: _Scene) -> None: """A permanent wrench reaches the solver in the local and the global frame, and a reset clears it. diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index 3ccd63d0c9bc..2ced8754840d 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -143,6 +143,7 @@ def on_physics_ready(_): assert isinstance(sim.backend_manager.backend.solver, SolverMuJoCo) # as a write during graph capture does sim.backend_manager.backend.transforms_may_change_on_graph_replay = True + sim.backend_manager.backend.fk_on_every_step = True sim.reset() assert events == ["ready", "prepare"] * 2 @@ -324,6 +325,7 @@ def check_step(self, captured, debug): fk_mask=wp.zeros(1, dtype=wp.bool, device=device), kinematics_dirty=False, transforms_may_change_on_graph_replay=False, + fk_on_every_step=False, state_version=0, model_changes=set(), warned_model_changes=set(), @@ -633,6 +635,7 @@ def eval_fk(self, state, worlds, articulations): fk_mask=fk_mask, kinematics_dirty=True, transforms_may_change_on_graph_replay=False, + fk_on_every_step=False, model_changes=set(), state_version=0, ) @@ -661,6 +664,7 @@ def test_manager_flags_the_masked_worlds_and_articulations(articulation_mask): fk_mask=wp.zeros(6, dtype=wp.bool, device="cpu"), kinematics_dirty=False, transforms_may_change_on_graph_replay=False, + fk_on_every_step=False, ) articulation_ids = wp.array([[0, 1], [2, 3], [4, 5]], dtype=wp.int32, device="cpu") env_mask = wp.array([True, False, True], dtype=wp.bool, device="cpu") diff --git a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py index 5b4bf1e14eb1..e6f621cd0970 100644 --- a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py +++ b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py @@ -17,6 +17,7 @@ import warp as wp from isaaclab_newton.assets import Articulation from isaaclab_newton.physics import MJWarpSolverCfg, NewtonBackend, NewtonCfg +from isaaclab_newton.physics.newton_solver import NewtonSolver from isaaclab_physx.sim.schemas import PhysxJointCfg from newton.solvers import SolverMuJoCo @@ -27,6 +28,7 @@ from isaaclab.sim import SimulationCfg, build_simulation_context from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.warp.capture import GraphedCallable def _generate_single_joint_articulations(num_articulations: int, device: str) -> Articulation: @@ -136,3 +138,51 @@ def test_env_reset_clears_selected_mjwarp_solver_internals(device): torch.testing.assert_close(wp.to_torch(state.joint_qd), joint_qd_before) assert torch.count_nonzero(warm_start[0]).item() == 0 torch.testing.assert_close(warm_start[1], torch.full_like(warm_start[1], 29.0)) + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_recorded_env_reset_evaluates_fk_once_per_replay(device): + """A recorded part of the step that resets an env clears the reset world's solver history inside its replay, and + the physics steps after it evaluate no further forward kinematics.""" + sim_cfg = SimulationCfg( + dt=1 / 120, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg(njmax=20, nconmax=20, integrator="implicitfast"), + num_substeps=1, + use_cuda_graph=False, + ), + ) + with build_simulation_context(sim_cfg=sim_cfg, device=device) as sim: + sim._app_control_on_stop_handle = None + articulation = _generate_single_joint_articulations(num_articulations=2, device=device) + sim.reset() + backend = sim.backend_manager.backend + warm_start = wp.to_torch(backend.solver.mjw_data.qacc_warmstart) + env_mask = wp.array([True, False], dtype=wp.bool, device=device) + joint_pos = wp.from_torch(articulation.data.default_joint_pos.torch.clone() + 0.25) + + def reset_env_0(): + articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) + + reset = GraphedCallable(reset_env_0, device) + enabled, GraphedCallable.enabled = GraphedCallable.enabled, True + try: + reset() # records + warm_start[0].fill_(13.0) + warm_start[1].fill_(17.0) + reset() # replays + wp.synchronize_device(device) + assert torch.count_nonzero(warm_start[0]).item() == 0 + torch.testing.assert_close(warm_start[1], torch.full_like(warm_start[1], 17.0)) + + with ( + patch.object(NewtonSolver, "eval_fk", side_effect=NewtonSolver.eval_fk) as fk, + patch.object(NewtonBackend, "_simulate", lambda self, steps: None), + ): + backend.invalidate_graph() + for _ in range(2): + sim.step(render=False) + assert fk.call_count == 0 + finally: + GraphedCallable.enabled = enabled + reset.reset() diff --git a/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst new file mode 100644 index 000000000000..19a61e0de8b2 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -0,0 +1,3 @@ +* Fixed lazily computed asset data properties replaying the value of the recording step from a CUDA + graph that :class:`~isaaclab.utils.warp.capture.GraphedCallable` recorded while they were current. A recording + now holds their update, so every replay recomputes them. diff --git a/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation_data.py b/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation_data.py index fccaabba97dd..7b12856e4ae7 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation_data.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/articulation/articulation_data.py @@ -1709,7 +1709,9 @@ def _create_buffers(self) -> None: # noqa: C901 self._body_link_pose_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.transformf, device=device)) self._body_link_pose_w_backend: TimestampedBuffer | None = None self._body_link_vel_w = TimestampedBuffer(wp.empty(body_shape, dtype=wp.spatial_vectorf, device=device)) - self._body_com_pose_b = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.transformf, device=device)) + self._body_com_pose_b = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.transformf, device=device), update_in_graph=False + ) self._body_com_pose_b_backend: TimestampedBuffer | None = None self._body_com_pose_w = TimestampedBuffer(wp.empty(body_shape, dtype=wp.transformf, device=device)) self._body_com_vel_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device)) @@ -1721,7 +1723,9 @@ def _create_buffers(self) -> None: # noqa: C901 self._joint_pos_backend: TimestampedBuffer | None = None self._joint_vel_buf = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) self._joint_vel_backend: TimestampedBuffer | None = None - self._joint_acc = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) + self._joint_acc = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) self._previous_joint_vel = wp.zeros(joint_shape, dtype=wp.float32, device=device) # -- Dynamics quantities for task-space controllers @@ -1736,12 +1740,24 @@ def _create_buffers(self) -> None: # noqa: C901 self._gravity_compensation_forces_backend: wp.array | None = None # -- Joint properties (CPU-only; timestamped so they can be re-read after writes) - self._joint_stiffness = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) - self._joint_damping = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) - self._joint_armature = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) - self._joint_pos_limits = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.vec2f, device=device)) - self._joint_vel_limits = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) - self._joint_effort_limits = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) + self._joint_stiffness = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) + self._joint_damping = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) + self._joint_armature = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) + self._joint_pos_limits = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.vec2f, device=device), update_in_graph=False + ) + self._joint_vel_limits = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) + self._joint_effort_limits = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) self._joint_stiffness_backend: TimestampedBuffer | None = None self._joint_damping_backend: TimestampedBuffer | None = None self._joint_armature_backend: TimestampedBuffer | None = None @@ -1749,7 +1765,9 @@ def _create_buffers(self) -> None: # noqa: C901 self._joint_vel_limits_backend: TimestampedBuffer | None = None self._joint_effort_limits_backend: TimestampedBuffer | None = None # Friction: one buffer with three coefficients per joint; component views are created lazily. - self._joint_friction_props_buf = TimestampedBuffer(wp.zeros((*joint_shape, 3), dtype=wp.float32, device=device)) + self._joint_friction_props_buf = TimestampedBuffer( + wp.zeros((*joint_shape, 3), dtype=wp.float32, device=device), update_in_graph=False + ) self._joint_friction_props_backend: TimestampedBuffer | None = None # Strided views into _joint_friction_props_buf.data, initialized below after # the initial property reads populate the combined buffer. @@ -1758,9 +1776,13 @@ def _create_buffers(self) -> None: # noqa: C901 self._joint_viscous_friction_coeff: wp.array | None = None # -- Body properties (CPU-only; read once at init, re-read via _read_scalar_binding) - self._body_mass = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.float32, device=device)) + self._body_mass = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.float32, device=device), update_in_graph=False + ) self._body_mass_backend: TimestampedBuffer | None = None - self._body_inertia = TimestampedBuffer(wp.zeros((*body_shape, 9), dtype=wp.float32, device=device)) + self._body_inertia = TimestampedBuffer( + wp.zeros((*body_shape, 9), dtype=wp.float32, device=device), update_in_graph=False + ) self._body_inertia_backend: TimestampedBuffer | None = None # -- Soft limits / custom joint properties @@ -2229,7 +2251,9 @@ def _configure_ordering_buffers(self) -> None: ) user_buffer.timestamp = backend_buffer.timestamp - self._joint_friction_props_backend = TimestampedBuffer(wp.zeros((*joint_shape, 3), wp.float32, device)) + self._joint_friction_props_backend = TimestampedBuffer( + wp.zeros((*joint_shape, 3), wp.float32, device), update_in_graph=False + ) self._joint_friction_props_backend.data.assign(self._joint_friction_props_buf.data) self._joint_friction_props_backend.timestamp = self._joint_friction_props_buf.timestamp wp.launch( @@ -2263,17 +2287,23 @@ def _configure_ordering_buffers(self) -> None: if self.has_body_ordering: body_shape = (self.num_instances, self.num_bodies) self._body_link_pose_w_backend = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.transformf, device=device)) - self._body_com_pose_b_backend = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.transformf, device=device)) + self._body_com_pose_b_backend = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.transformf, device=device), update_in_graph=False + ) self._body_com_vel_w_backend = TimestampedBuffer(wp.zeros(body_shape, wp.spatial_vectorf, device)) self._body_com_acc_w_backend = TimestampedBuffer(wp.zeros(body_shape, wp.spatial_vectorf, device)) # Invariant: from seeding onward, each backend staging must stay the backend-order # image of its public buffer. Partial body-property setters scatter only the # selected cells into both buffers and push full backend rows to the simulation, # so a stale or divergent staging silently corrupts the unselected cells. - self._body_mass_backend = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.float32, device=device)) + self._body_mass_backend = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.float32, device=device), update_in_graph=False + ) self._body_mass_backend.data.assign(self._body_mass.data) self._body_mass_backend.timestamp = self._body_mass.timestamp - self._body_inertia_backend = TimestampedBuffer(wp.zeros((*body_shape, 9), dtype=wp.float32, device=device)) + self._body_inertia_backend = TimestampedBuffer( + wp.zeros((*body_shape, 9), dtype=wp.float32, device=device), update_in_graph=False + ) self._body_inertia_backend.data.assign(self._body_inertia.data) self._body_inertia_backend.timestamp = self._body_inertia.timestamp wp.launch( diff --git a/source/isaaclab_ov/isaaclab_ov/assets/rigid_object/rigid_object_data.py b/source/isaaclab_ov/isaaclab_ov/assets/rigid_object/rigid_object_data.py index 5cd1da9eba28..4cb7491fc272 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/rigid_object/rigid_object_data.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/rigid_object/rigid_object_data.py @@ -894,7 +894,9 @@ def _create_buffers(self) -> None: # -- com frame w.r.t. world frame self._root_com_pose_w = TimestampedBuffer(wp.empty(num_instances, dtype=wp.transformf, device=device)) self._root_com_vel_w = TimestampedBuffer(wp.zeros(num_instances, dtype=wp.spatial_vectorf, device=device)) - self._body_com_acc_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device)) + self._body_com_acc_w = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device), update_in_graph=False + ) # -- combined state (these are cached as they concatenate) self._root_state_w = TimestampedBuffer(wp.empty(num_instances, dtype=vec13f, device=device)) self._root_link_state_w = TimestampedBuffer(wp.empty(num_instances, dtype=vec13f, device=device)) diff --git a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py index 32492a18da9d..613d6682eba7 100644 --- a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py +++ b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py @@ -128,10 +128,10 @@ def __init__(self, manager): self._manager = manager self.backend: OvPhysxBackend | None = None """Native resource borrowed from the context registry after warmup.""" - self._transforms = TimestampedBuffer(SceneDataFormat.Transform()) + self._transforms = TimestampedBuffer(SceneDataFormat.Transform(), update_in_graph=False) self.transforms_timestamp = 0 self.geometry_timestamp = 0 - self._geometry = TimestampedBuffer() + self._geometry = TimestampedBuffer(update_in_graph=False) self._deformable_bindings: list[tuple[OvPhysxView, Any, wp.array]] = [] self._pending_setup: tuple[OvPhysxBackend, str, Sequence[DeformableStageEntry] | None] | None = None @@ -143,7 +143,7 @@ def _defer_setup( self._transforms.data.transforms = None self.transforms_timestamp += 1 self._deformable_bindings = [] - self._geometry = TimestampedBuffer() + self._geometry = TimestampedBuffer(update_in_graph=False) self.geometry_timestamp += 1 self._pending_setup = (backend, device, entries) @@ -204,7 +204,7 @@ def setup( self.transforms_timestamp += 1 self._deformable_bindings = [] self.geometry_timestamp += 1 - self._geometry = TimestampedBuffer() + self._geometry = TimestampedBuffer(update_in_graph=False) if backend.rigid_body_view is not None and backend.rigid_body_view.count: self._transforms.data.transforms = wp.empty( diff --git a/source/isaaclab_ov/test/assets/test_articulation.py b/source/isaaclab_ov/test/assets/test_articulation.py index 1c18f8f81023..48ab1049ab76 100644 --- a/source/isaaclab_ov/test/assets/test_articulation.py +++ b/source/isaaclab_ov/test/assets/test_articulation.py @@ -68,6 +68,7 @@ BRANCHING_PHYSX_JOINT_NAMES, ) from isaaclab.utils import replace # noqa: E402 +from isaaclab.utils.buffers import TimestampedBuffer # noqa: E402 from isaaclab.utils.warp.launch_cache import _WarpLaunchCache # noqa: E402 from isaaclab_assets import FRANKA_PANDA_CFG # noqa: E402 @@ -407,10 +408,8 @@ def test_static_property_reads_are_not_invalidated_by_simulation_steps(): native actuator telemetry sync) host-bound. State buffers must still refresh every step. """ - class Buffer: - def __init__(self, shape): - self.data = wp.zeros(shape, dtype=wp.float32, device="cpu") - self.timestamp = -1.0 + def Buffer(shape): + return TimestampedBuffer(wp.zeros(shape, dtype=wp.float32, device="cpu")) data = ArticulationData.__new__(ArticulationData) data.device = "cpu" diff --git a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst new file mode 100644 index 000000000000..19a61e0de8b2 --- /dev/null +++ b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -0,0 +1,3 @@ +* Fixed lazily computed asset data properties replaying the value of the recording step from a CUDA + graph that :class:`~isaaclab.utils.warp.capture.GraphedCallable` recorded while they were current. A recording + now holds their update, so every replay recomputes them. diff --git a/source/isaaclab_physx/isaaclab_physx/renderers/fabric.py b/source/isaaclab_physx/isaaclab_physx/renderers/fabric.py index f61339c6ab15..45adae582217 100644 --- a/source/isaaclab_physx/isaaclab_physx/renderers/fabric.py +++ b/source/isaaclab_physx/isaaclab_physx/renderers/fabric.py @@ -189,7 +189,13 @@ def _bind_geometries(self, provider: SceneDataProvider, paths: tuple[str, ...]) ) offsets = dict.fromkeys(group_paths, 0) self._geometry_bindings.append( - ((selection, write_selection), frequency, TimestampedBuffer(), offsets, -frequency) + ( + (selection, write_selection), + frequency, + TimestampedBuffer(), + offsets, + -frequency, + ) ) def close(self) -> None: diff --git a/source/isaaclab_tasks_experimental/changelog.d/jichuanh-warp-recording-utils.skip b/source/isaaclab_tasks_experimental/changelog.d/jichuanh-warp-recording-utils.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py index bf05de7435cd..cdd47a6b473d 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py @@ -57,9 +57,9 @@ def base_yaw_roll(env: ManagerBasedEnv, out, asset_cfg: SceneEntityCfg = SceneEn ) -# Inline Tier 1 access: derives projected gravity directly from root_link_pose_w, -# avoiding the lazy TimestampedWarpBuffer which is not CUDA-graph-capturable. -# See GRAPH_CAPTURE_MIGRATION.md in isaaclab_newton for background. +# Inline Tier 1 access: derives projected gravity directly from root_link_pose_w. +# Lazy asset data is recorded into CUDA graphs as well (a recording recomputes it on every replay), +# so this can read asset.data.projected_gravity_b directly. @wp.kernel diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py index 649c50928985..5d9ee72cbdda 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py @@ -33,11 +33,9 @@ # --------------------------------------------------------------------------- -# Inline Tier 1 access: derives projected gravity directly from root_link_pose_w, -# avoiding the lazy TimestampedWarpBuffer which is not CUDA-graph-capturable. -# See GRAPH_CAPTURE_MIGRATION.md in isaaclab_newton for background. -# If ArticulationData Tier 2 lazy update is made graph-safe, this can revert to -# reading asset.data.projected_gravity_b directly. +# Inline Tier 1 access: derives projected gravity directly from root_link_pose_w. +# Lazy asset data is recorded into CUDA graphs as well (a recording recomputes it on every replay), +# so this can read asset.data.projected_gravity_b directly. @wp.kernel From d495a1edced9ec41645cb31d9817f22edfcc993d Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Fri, 13 Nov 2026 17:11:11 -0800 Subject: [PATCH 02/30] Register model changes again on each replay of a GraphedCallable recording --- .../jichuanh-warp-recording-utils.changed.rst | 3 +++ .../jichuanh-warp-recording-utils.fixed.rst | 4 ---- .../isaaclab_newton/physics/newton_manager.py | 11 ++++++----- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst index b37a04119804..e6073d418a3e 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -2,3 +2,6 @@ stage, inside that stage's CUDA graph, instead of before every physics step once any write was recorded. State written inside a raw CUDA graph capture still evaluates them before every physics step (:attr:`~isaaclab_newton.physics.NewtonBackend.fk_on_every_step`). +* Changed :meth:`~isaaclab_newton.physics.NewtonManager.add_model_change` inside a recording of + :class:`~isaaclab.utils.warp.capture.GraphedCallable` to register the change again on each replay, so the next step + refreshes the solver once for all changes; any other capture still records the refresh of that change. diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst index 87d74a4fbd57..a0fe72ea2ffd 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,7 +1,3 @@ -* Fixed model changes registered with :meth:`~isaaclab_newton.physics.NewtonManager.add_model_change` inside a CUDA - graph recording, such as fixed tendon property writes, reaching the solver only when the graph was recorded: a part - of the step recorded with :class:`~isaaclab.utils.warp.capture.GraphedCallable` registers the change again on each - replay, and any other capture records the solver's refresh. * Fixed lazily computed asset data properties, such as :attr:`~isaaclab_newton.assets.ArticulationData.projected_gravity_b`, inside a CUDA graph recorded by :class:`~isaaclab.utils.warp.capture.GraphedCallable`: 15 of them raised while a graph recorded, and the others diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index 3cca7e6ecd81..57494afeb30d 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -27,7 +27,7 @@ from isaaclab.utils.string import resolve_matching_names from isaaclab.utils.timer import Timer from isaaclab.utils.version import has_kit -from isaaclab.utils.warp.capture import record_at_end +from isaaclab.utils.warp.capture import capturing, eager, is_recording, record_at_end from isaaclab_newton.physics.newton_backend_cfg import NewtonBackendCfg from isaaclab_newton.physics.newton_builder_cfg import NewtonBuilderCfg @@ -359,18 +359,19 @@ def request_extended_contact_attribute(self, attr: str) -> None: def add_model_change(self, change: ModelFlags) -> None: """Register a model change to notify the solver at the next step. - Inside a graph capture, the refresh of this change alone is recorded instead, so every replay applies it; - changes queued before the capture stay queued for the next step. + The registration is host work: a recorded part of the step that writes registers it again on each replay. A + capture that no :class:`~isaaclab.utils.warp.capture.GraphedCallable` records cannot repeat host work, so it + records the refresh of this change alone instead; changes queued before the capture stay queued. """ backend = self.backend - if wp.get_device(backend.device).is_capturing: + if capturing(backend.device) and not is_recording(): queued, backend.model_changes = backend.model_changes, {change} try: backend.notify_model_changes() finally: backend.model_changes = queued else: - backend.model_changes.add(change) + eager(backend.model_changes.add, change) def invalidate_fk( self, From 5a65f9416587ffe1aeebfeae5778bd39396c63f9 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Fri, 13 Nov 2026 17:11:56 -0800 Subject: [PATCH 03/30] Reset the delayed PD actuators and torch-driven Newton actuator states eagerly in a recording --- .../isaaclab/actuators/actuator_pd.py | 2 ++ .../isaaclab/actuators/newton/adapter.py | 20 +++++++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/source/isaaclab/isaaclab/actuators/actuator_pd.py b/source/isaaclab/isaaclab/actuators/actuator_pd.py index d7019a5e8bc2..f7aee013573c 100644 --- a/source/isaaclab/isaaclab/actuators/actuator_pd.py +++ b/source/isaaclab/isaaclab/actuators/actuator_pd.py @@ -15,6 +15,7 @@ from ..utils import DelayBuffer, LinearInterpolation from ..utils.types import ArticulationActions +from ..utils.warp.capture import eager_method from .actuator_base import ActuatorBase, resolve_joint_parameter if TYPE_CHECKING: @@ -436,6 +437,7 @@ def __init__(self, cfg: DelayedPDActuatorCfg, *args, **kwargs): self.efforts_delay_buffer = DelayBuffer(cfg.max_delay, self._num_envs, device=self._device) self._delay_buffers = (self.positions_delay_buffer, self.velocities_delay_buffer, self.efforts_delay_buffer) + @eager_method # samples new delays and resets the delay buffers with torch def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array | None = None) -> None: super().reset(env_ids, env_mask) if env_mask is not None: diff --git a/source/isaaclab/isaaclab/actuators/newton/adapter.py b/source/isaaclab/isaaclab/actuators/newton/adapter.py index 4904d4c7780c..fdc25b98d595 100644 --- a/source/isaaclab/isaaclab/actuators/newton/adapter.py +++ b/source/isaaclab/isaaclab/actuators/newton/adapter.py @@ -32,6 +32,7 @@ from newton.selection import ArticulationView from ...utils import index_fill_ +from ...utils.warp.capture import eager from .kernels import ( build_implicit_dof_mask, build_per_dof_env_mask_kernel, @@ -201,11 +202,9 @@ def reset( self._reset_states(env_mask) return if env_ids is None or env_ids == slice(None): - for sa, sb in zip(self._states_a, self._states_b): + for act, sa, sb in zip(self.actuators, self._states_a, self._states_b): if sa is not None: - sa.reset(None) - if sb is not None: - sb.reset(None) + self._reset_state_pair(act, sa, sb, None) return num_envs = len(range(self._num_envs)[env_ids]) if isinstance(env_ids, slice) else len(env_ids) @@ -329,8 +328,17 @@ def _reset_states(self, env_mask: wp.array) -> None: inputs=[act.indices, env_mask, self._dof_offset, self.num_joints, per_dof_mask], device=self._device, ) - sa.reset(per_dof_mask) - sb.reset(per_dof_mask) + self._reset_state_pair(act, sa, sb, per_dof_mask) + + @staticmethod + def _reset_state_pair(act: Actuator, sa: Any, sb: Any, per_dof_mask: wp.array | None) -> None: + """Reset both state buffers of an actuator; a torch state, such as a neural network drive's, cannot be + recorded, so a recording repeats its reset eagerly.""" + for state in (sa, sb): + if act.is_graphable(): + state.reset(per_dof_mask) + else: + eager(state.reset, per_dof_mask) # --------------------------------------------------------------------------- From 275e7c2e91d91acf96fd5e9d14372c55fa46a457 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Fri, 13 Nov 2026 17:12:29 -0800 Subject: [PATCH 04/30] Count Warp's CPU capture as a capture in capturing() --- source/isaaclab/isaaclab/utils/warp/capture.py | 11 +++++++---- source/isaaclab/test/utils/warp/test_capture.py | 15 ++++++++++++++- .../jichuanh-warp-recording-utils.changed.rst | 2 +- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index 492fd4db689b..b1228c68aaaa 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -26,13 +26,16 @@ def capturing(device: wp.Device | str | None = None) -> bool: - """Whether a CUDA graph is being recorded on ``device`` (the current device by default). + """Whether a graph is being recorded on ``device`` (the current device by default), a CUDA graph or Warp's CPU one. - It reads Warp's table of the recordings in progress first, which costs ~20x less than ``Device.is_capturing``, so - outside a recording the check spares the CUDA query; every recording in Isaac Lab starts through Warp. + It reads Warp's records of the captures in progress first, which costs ~20x less than ``Device.is_capturing``, so + outside a recording the check spares the CUDA query; every recording in Isaac Lab starts through Warp. Warp's CPU + capture is not in its CUDA capture table and is read from the runtime's private ``_apic_capture``. """ runtime = _warp_context.runtime - return runtime is not None and bool(runtime.captures) and wp.get_device(device).is_capturing + if runtime is None or not (runtime.captures or runtime._apic_capture is not None): + return False + return wp.get_device(device).is_capturing def is_recording() -> bool: diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py index 522c2efda6b1..ff1adb85a5f7 100644 --- a/source/isaaclab/test/utils/warp/test_capture.py +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -12,7 +12,7 @@ import pytest import warp as wp -from isaaclab.utils.warp.capture import GraphedCallable, eager, eager_method +from isaaclab.utils.warp.capture import GraphedCallable, capturing, eager, eager_method wp.init() pytestmark = [pytest.mark.kitless, pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA device required")] @@ -186,6 +186,19 @@ def test_eager_call_raises_inside_a_capture_no_callable_started(): assert fn.calls == 0 +def test_capturing_sees_a_cpu_capture(): + """Warp's CPU capture counts as a capture, so a call that cannot be recorded raises inside it as on CUDA.""" + fn = _Affine() + values = wp.zeros(1, dtype=wp.int32, device="cpu") + + with wp.ScopedDevice("cpu"), wp.ScopedCapture(): + assert capturing("cpu") + with pytest.raises(RuntimeError, match="no GraphedCallable started"): + eager(fn, values) + assert not capturing("cpu") + assert fn.calls == 0 + + def test_callable_raising_while_recording_ends_the_capture(): """A failed recording must not leave the device capturing; the next call records again.""" recorded, eager_fn = _Affine(2, 0), _Affine(1, 10) diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst index e6073d418a3e..f4f7e6e0fe1f 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,6 +1,6 @@ * Changed Newton to reset the solver and evaluate forward kinematics once after a state write recorded in a Warp stage, inside that stage's CUDA graph, instead of before every physics step once any write was recorded. State - written inside a raw CUDA graph capture still evaluates them before every physics step + written inside a raw graph capture still evaluates them before every physics step (:attr:`~isaaclab_newton.physics.NewtonBackend.fk_on_every_step`). * Changed :meth:`~isaaclab_newton.physics.NewtonManager.add_model_change` inside a recording of :class:`~isaaclab.utils.warp.capture.GraphedCallable` to register the change again on each replay, so the next step From 19df241e1fff0f2b253ddf288fe1fa526443f88e Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sat, 14 Nov 2026 23:18:26 -0800 Subject: [PATCH 05/30] Read the finite-difference accelerations as they are in a recording --- .../test/assets/contract/test_articulation_contract.py | 4 ++++ .../changelog.d/jichuanh-warp-recording-utils.fixed.rst | 3 ++- .../rigid_object_collection/rigid_object_collection_data.py | 5 ++++- .../changelog.d/jichuanh-warp-recording-utils.fixed.rst | 3 ++- .../isaaclab_physx/assets/articulation/articulation_data.py | 5 ++++- 5 files changed, 16 insertions(+), 4 deletions(-) diff --git a/source/isaaclab/test/assets/contract/test_articulation_contract.py b/source/isaaclab/test/assets/contract/test_articulation_contract.py index 805c19959a5e..a8fc39ef0871 100644 --- a/source/isaaclab/test/assets/contract/test_articulation_contract.py +++ b/source/isaaclab/test/assets/contract/test_articulation_contract.py @@ -441,10 +441,14 @@ def test_lazy_properties_update_on_every_graph_replay(monkeypatch, backend, cuda """ monkeypatch.setattr(GraphedCallable, "enabled", True) art = _recordable_articulation(backend, cuda_device, monkeypatch) + # a previous velocity apart from the current one gives the step a nonzero acceleration, which a recorded + # finite difference would overwrite + art.data._previous_joint_vel.fill_(-1.0) art.data.update(dt=0.01) _ = art.data.heading_w # current when the read is recorded joint_acc = art.data.joint_acc joint_acc_before = joint_acc.torch.clone() + assert torch.count_nonzero(joint_acc_before) > 0 def read(): _ = art.data.joint_acc diff --git a/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst index 19a61e0de8b2..fc3dfc7727f8 100644 --- a/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,3 +1,4 @@ * Fixed lazily computed asset data properties replaying the value of the recording step from a CUDA graph that :class:`~isaaclab.utils.warp.capture.GraphedCallable` recorded while they were current. A recording - now holds their update, so every replay recomputes them. + now holds their update, so every replay recomputes them. The accelerations taken by finite differencing, which + ``update`` advances once per physics step, are read as they are. diff --git a/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection_data.py b/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection_data.py index cc123cb7bc3f..c81b86e5287d 100644 --- a/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection_data.py +++ b/source/isaaclab_ov/isaaclab_ov/assets/rigid_object_collection/rigid_object_collection_data.py @@ -861,7 +861,10 @@ def _create_buffers(self) -> None: self._body_com_lin_vel_b = TimestampedBuffer(wp.empty(body_shape, dtype=wp.vec3f, device=device)) self._body_com_ang_vel_b = TimestampedBuffer(wp.empty(body_shape, dtype=wp.vec3f, device=device)) # -- derived properties (acceleration via finite differencing) - self._body_com_acc_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device)) + # update() advances the finite difference once per physics step, so a recording reads it as it is + self._body_com_acc_w = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device), update_in_graph=False + ) # Holds the previous-step COM velocity for FD; initialised lazily on first access. self._previous_body_com_vel: wp.array | None = None # -- derived properties (projected gravity and heading) diff --git a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst index 19a61e0de8b2..63ee2fd617ab 100644 --- a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,3 +1,4 @@ * Fixed lazily computed asset data properties replaying the value of the recording step from a CUDA graph that :class:`~isaaclab.utils.warp.capture.GraphedCallable` recorded while they were current. A recording - now holds their update, so every replay recomputes them. + now holds their update, so every replay recomputes them. The joint acceleration, which + :meth:`~isaaclab_physx.assets.ArticulationData.update` advances once per physics step, is read as it is. diff --git a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py index 5eafbba2378e..027f3c74661e 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py @@ -1691,7 +1691,10 @@ def _create_buffers(self) -> None: self._joint_vel = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) self._joint_pos_backend: TimestampedBuffer | None = None self._joint_vel_backend: TimestampedBuffer | None = None - self._joint_acc = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) + # update() advances the finite difference once per physics step, so a recording reads it as it is + self._joint_acc = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) # -- derived properties (these are cached to avoid repeated memory allocations) self._projected_gravity_b = TimestampedBuffer(wp.empty(num_instances, dtype=wp.vec3f, device=device)) self._heading_w = TimestampedBuffer(wp.empty(num_instances, dtype=wp.float32, device=device)) From 64f42d4769277649899453270b0305770bcd627c Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sat, 14 Nov 2026 23:18:37 -0800 Subject: [PATCH 06/30] Refresh cameras eagerly on each replay of a recording --- .../changelog.d/jichuanh-warp-recording-utils.fixed.rst | 2 +- source/isaaclab/isaaclab/sensors/camera/camera.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst index 6cdc982ed6d0..dc2931b2ce8a 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,4 +1,4 @@ * Fixed sensors read inside a recorded CUDA graph after a reset keeping their data from before the recording: :class:`~isaaclab.sensors.SensorBase` now records the buffer refresh whenever a :class:`~isaaclab.utils.warp.capture.GraphedCallable` records, so each replay refreshes the environments whose - data is outdated. + data is outdated. :class:`~isaaclab.sensors.Camera` renders eagerly at that place on each replay. diff --git a/source/isaaclab/isaaclab/sensors/camera/camera.py b/source/isaaclab/isaaclab/sensors/camera/camera.py index 159d5426587b..f16fa002e0c1 100644 --- a/source/isaaclab/isaaclab/sensors/camera/camera.py +++ b/source/isaaclab/isaaclab/sensors/camera/camera.py @@ -26,6 +26,7 @@ quat_from_matrix, ) from ...utils.warp import ProxyArray +from ...utils.warp.capture import eager_method from ...utils.warp.memory import resolve_1d_indices, resolve_ids from ..sensor_base import SensorBase from .camera_data import CameraData, RenderBufferKind @@ -728,6 +729,7 @@ def _prepare_camera(self, env_mask: wp.array) -> None: self._update_camera_state(env_mask=env_mask, frame_op=1) self._renderer.prepare_capture(self._render_data, self._data, self._frame) + @eager_method # reads the outdated mask on the host and renders def _update_buffers_impl(self, env_mask: wp.array): if not self._env_mask_has_any(env_mask): return From 65c28a6eee9904a25ee295500e8997e00da208e8 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sat, 14 Nov 2026 23:18:38 -0800 Subject: [PATCH 07/30] Key recordings by argument position and scalar type --- .../isaaclab/isaaclab/utils/warp/capture.py | 12 +++++++---- .../isaaclab/test/utils/warp/test_capture.py | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index b1228c68aaaa..430f287f12e3 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -317,8 +317,11 @@ def _paused_gc(): def _argument_key(args: tuple, kwargs: dict[str, Any]) -> tuple: - """Key a call by the pointer, shape, strides, dtype and device of its arrays and the values of its scalars.""" - return tuple(_value_key(value) for value in args) + tuple( + """Key a call by the pointer, shape, strides, dtype and device of its arrays and the type and value of its scalars. + + Positional and keyword arguments key apart. + """ + return tuple(_value_key(value) for value in args), tuple( (name, _value_key(value)) for name, value in kwargs.items() ) @@ -329,8 +332,9 @@ def _value_key(value: Any) -> Any: return value.ptr, value.shape, value.strides, value.dtype, str(value.device) if isinstance(value, torch.Tensor): return value.data_ptr(), value.shape, value.stride(), value.dtype, value.device + # True, 1 and 1.0 compare equal, so the type tells them apart if value is None or isinstance(value, (bool, int, float, str)): - return value + return type(value), value if isinstance(value, (list, tuple)): - return tuple(_value_key(item) for item in value) + return type(value), tuple(_value_key(item) for item in value) return id(value) diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py index ff1adb85a5f7..50830210ce4d 100644 --- a/source/isaaclab/test/utils/warp/test_capture.py +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -84,6 +84,26 @@ def test_changed_argument_records_the_callable_again(): assert (_read(old), _read(new), fn.calls, _num_graphs(graphed)) == ([1], [12], 3, 3) +def test_equal_arguments_of_another_layout_or_type_record_their_own_graphs(): + """Arguments that compare equal but differ in position, keyword or scalar type each record a graph.""" + values = wp.zeros(1, dtype=wp.int32, device=DEVICE) + calls = [] + + def fn(*args, **kwargs): + calls.append((args, kwargs)) + wp.launch(_affine, dim=1, inputs=[values, 1, 1], device=DEVICE) + + graphed = GraphedCallable(fn, DEVICE) + graphed(("shift", 1)) + graphed(shift=1) + graphed(1) + graphed(True) + graphed(1.0) + graphed([1]) + graphed((1,)) + assert len(calls) == 7, "an equal-comparing call replayed another call's graph" + + def test_views_of_one_array_record_their_own_graphs(): """Views that share an address but differ in length record their own graphs, each replaying over its length.""" fn = _Affine() From 86e7a63cc9c29732468dc1533278dc92dbbc53bb Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 01:55:17 -0800 Subject: [PATCH 08/30] Refresh host-bound sensors eagerly and read CPU-view body properties as they are in a recording --- .../jichuanh-warp-recording-utils.changed.rst | 2 ++ .../tacsl_sensor/visuotactile_sensor.py | 2 ++ .../jichuanh-warp-recording-utils.fixed.rst | 3 +- .../sensors/contact_sensor/contact_sensor.py | 2 ++ .../frame_transformer/frame_transformer.py | 2 ++ .../isaaclab_ov/sensors/imu/imu.py | 2 ++ .../joint_wrench/joint_wrench_sensor.py | 2 ++ .../isaaclab_ov/sensors/pva/pva.py | 2 ++ .../jichuanh-warp-recording-utils.fixed.rst | 5 ++- .../assets/articulation/articulation_data.py | 18 +++++++--- .../assets/rigid_object/rigid_object_data.py | 5 ++- .../rigid_object_collection_data.py | 5 ++- .../sensors/contact_sensor/contact_sensor.py | 2 ++ .../frame_transformer/frame_transformer.py | 2 ++ .../isaaclab_physx/sensors/imu/imu.py | 2 ++ .../joint_wrench/joint_wrench_sensor.py | 2 ++ .../isaaclab_physx/sensors/pva/pva.py | 2 ++ .../sensors/ray_caster/ray_caster.py | 2 ++ .../test/sensors/test_contact_sensor.py | 36 ++++++++++++++++++- .../test/sensors/test_ray_caster_graph.py | 2 +- 20 files changed, 90 insertions(+), 10 deletions(-) create mode 100644 source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst diff --git a/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst new file mode 100644 index 000000000000..a65c9610ee13 --- /dev/null +++ b/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -0,0 +1,2 @@ +* Changed :class:`~isaaclab_contrib.sensors.VisuoTactileSensor` to refresh eagerly at its place on every replay of a + :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording, since its refresh renders on the host. diff --git a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py index e66b53f78a3d..f363ed84f0eb 100644 --- a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py +++ b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py @@ -23,6 +23,7 @@ from isaaclab.sensors.camera import Camera from isaaclab.sensors.sensor_base import SensorBase from isaaclab.utils.math import quat_apply, quat_inv +from isaaclab.utils.warp.capture import eager_method from .visuotactile_render import GelsightRender from .visuotactile_sensor_data import VisuoTactileSensorData @@ -489,6 +490,7 @@ def _initialize_visualization(self): if self.cfg.visualizer_cfg: self._visualizer = VisualizationMarkers(self.cfg.visualizer_cfg) + @eager_method # refreshes its camera and renders the tactile image on the host, so it cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data. diff --git a/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst index fc3dfc7727f8..535f93b7b261 100644 --- a/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,4 +1,5 @@ * Fixed lazily computed asset data properties replaying the value of the recording step from a CUDA graph that :class:`~isaaclab.utils.warp.capture.GraphedCallable` recorded while they were current. A recording now holds their update, so every replay recomputes them. The accelerations taken by finite differencing, which - ``update`` advances once per physics step, are read as they are. + ``update`` advances once per physics step, are read as they are. The OVPhysX sensors read through host calls, so + each sensor refresh runs eagerly at its place on every replay. diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py index 612c2d72b928..769248e46e8d 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py @@ -22,6 +22,7 @@ from isaaclab.sensors.contact_sensor import BaseContactSensor from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source, split_path_expr from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov._clone import ordered_clone_paths @@ -386,6 +387,7 @@ def _fetch_ovphysx_buffers(self, include_pose: bool = True) -> None: assert self._poses_flat_buf is not None self._root_view.read_into(TT.RIGID_BODY_POSE, self._poses_flat_buf) + @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None) -> None: """Read contact data from ovphysx and update sensor buffers.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py b/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py index 7437f7b88c3a..0c2d4a04522e 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py @@ -19,6 +19,7 @@ from isaaclab.sensors.frame_transformer.kernels import frame_transformer_update_kernel from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source from isaaclab.utils.math import is_identity_pose, normalize, quat_from_angle_axis +from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView @@ -382,6 +383,7 @@ def _initialize_impl(self) -> None: device=self._device, ) + @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None) -> None: """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/imu/imu.py b/source/isaaclab_ov/isaaclab_ov/sensors/imu/imu.py index 6ca08d779ba7..ee5c31af6e5b 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/imu/imu.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/imu/imu.py @@ -16,6 +16,7 @@ from isaaclab.sensors.imu.kernels import imu_update_kernel from isaaclab.sim.utils.queries import path_expr_to_glob from isaaclab.utils.warp import memory as memory_kernels +from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView @@ -184,6 +185,7 @@ def _refresh_gravity_bias(self): self._gravity_w = gravity self._gravity_bias_w = wp.vec3f(-gravity[0], -gravity[1], -gravity[2]) + @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py b/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py index d0e115da9e6a..087689262ae1 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py @@ -19,6 +19,7 @@ from isaaclab.sensors.joint_wrench import BaseJointWrenchSensor from isaaclab.sim.utils.queries import find_first_matching_prim, get_all_matching_child_prims, path_expr_to_glob from isaaclab.utils.warp import memory as memory_kernels +from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView @@ -180,6 +181,7 @@ def _resolve_articulation_root_prim_path(self) -> str: root_prim_path_relative_to_prim_path = first_env_root_prim_path[len(first_env_matching_prim_path) :] return self.cfg.prim_path + root_prim_path_relative_to_prim_path + @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array) -> None: """Read OVPhysX incoming joint wrenches and split them into force / torque buffers. diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/pva/pva.py b/source/isaaclab_ov/isaaclab_ov/sensors/pva/pva.py index b268d0427f05..668330fb5fe2 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/pva/pva.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/pva/pva.py @@ -15,6 +15,7 @@ from isaaclab.sensors.pva import BasePva from isaaclab.sensors.pva.kernels import make_pva_update from isaaclab.sim.utils.queries import path_expr_to_glob +from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView @@ -162,6 +163,7 @@ def _refresh_gravity_vec(self): scale = 1.0 / max(math.sqrt(gravity[0] ** 2 + gravity[1] ** 2 + gravity[2] ** 2), 1.0e-9) self._gravity_vec_w = wp.vec3f(gravity[0] * scale, gravity[1] * scale, gravity[2] * scale) + @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst index 63ee2fd617ab..fbf537f48f12 100644 --- a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,4 +1,7 @@ * Fixed lazily computed asset data properties replaying the value of the recording step from a CUDA graph that :class:`~isaaclab.utils.warp.capture.GraphedCallable` recorded while they were current. A recording now holds their update, so every replay recomputes them. The joint acceleration, which - :meth:`~isaaclab_physx.assets.ArticulationData.update` advances once per physics step, is read as it is. + :meth:`~isaaclab_physx.assets.ArticulationData.update` advances once per physics step, and the body COM poses, + masses and inertias, which PhysX serves from CPU-only views, are read as they are. +* Fixed the PhysX sensors raising inside a :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording: their + PhysX tensor reads cannot be recorded, so each sensor refresh runs eagerly at its place on every replay. diff --git a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py index 027f3c74661e..87cea6687c0e 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py @@ -1671,7 +1671,10 @@ def _create_buffers(self) -> None: self._body_link_pose_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.transformf, device=device)) self._body_link_vel_w = TimestampedBuffer(wp.empty(body_shape, dtype=wp.spatial_vectorf, device=device)) # -- com frame w.r.t. link frame - self._body_com_pose_b = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.transformf, device=device)) + # refreshed from a CPU-only tensor view, which a recording cannot repeat, so a recording reads it as it is + self._body_com_pose_b = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.transformf, device=device), update_in_graph=False + ) self._body_com_pose_b_backend: TimestampedBuffer | None = None # -- com frame w.r.t. world frame self._root_com_pose_w = TimestampedBuffer(wp.empty(num_instances, dtype=wp.transformf, device=device)) @@ -1803,9 +1806,14 @@ def _create_buffers(self) -> None: # host-to-device on GPU pipelines. Under body ordering the backend-order staging buffers # below are gathered into these public-order buffers on read. _masses = self._root_view.get_masses() - self._body_mass = TimestampedBuffer(wp.zeros(_masses.shape, dtype=_masses.dtype, device=device)) + # refreshed from a CPU-only tensor view, which a recording cannot repeat, so a recording reads it as it is + self._body_mass = TimestampedBuffer( + wp.zeros(_masses.shape, dtype=_masses.dtype, device=device), update_in_graph=False + ) _inertias = self._root_view.get_inertias() - self._body_inertia = TimestampedBuffer(wp.zeros(_inertias.shape, dtype=_inertias.dtype, device=device)) + self._body_inertia = TimestampedBuffer( + wp.zeros(_inertias.shape, dtype=_inertias.dtype, device=device), update_in_graph=False + ) self._body_mass_backend: wp.array | None = None self._body_inertia_backend: wp.array | None = None self._default_root_state = None @@ -1887,7 +1895,9 @@ def _configure_ordering_buffers(self) -> None: # selected cells into both buffers and push full backend rows to the simulation, # so a stale or divergent staging silently corrupts the unselected cells. if self._body_com_pose_b_backend is None: - self._body_com_pose_b_backend = TimestampedBuffer(wp.zeros(body_shape, wp.transformf, device)) + self._body_com_pose_b_backend = TimestampedBuffer( + wp.zeros(body_shape, wp.transformf, device), update_in_graph=False + ) if self._body_mass_backend is None: self._body_mass_backend = wp.clone(self._body_mass.data, device=device) if self._body_inertia_backend is None: diff --git a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object_data.py b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object_data.py index 7a33127b288d..83633b5a9530 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object_data.py @@ -861,7 +861,10 @@ def _create_buffers(self) -> None: self._root_link_pose_w = TimestampedBuffer(wp.zeros(num_instances, dtype=wp.transformf, device=device)) self._root_link_vel_w = TimestampedBuffer(wp.empty(num_instances, dtype=wp.spatial_vectorf, device=device)) # -- com frame w.r.t. link frame - self._body_com_pose_b = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.transformf, device=device)) + # refreshed from a CPU-only tensor view, which a recording cannot repeat, so a recording reads it as it is + self._body_com_pose_b = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.transformf, device=device), update_in_graph=False + ) # -- com frame w.r.t. world frame self._root_com_pose_w = TimestampedBuffer(wp.empty(num_instances, dtype=wp.transformf, device=device)) self._root_com_vel_w = TimestampedBuffer(wp.zeros(num_instances, dtype=wp.spatial_vectorf, device=device)) diff --git a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection_data.py b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection_data.py index 9ba6e7da0a15..e27fdba3996a 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection_data.py @@ -746,7 +746,10 @@ def _create_buffers(self) -> None: self._body_link_pose_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.transformf, device=device)) self._body_link_vel_w = TimestampedBuffer(wp.empty(body_shape, dtype=wp.spatial_vectorf, device=device)) # -- com frame w.r.t. link frame - self._body_com_pose_b = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.transformf, device=device)) + # refreshed from a CPU-only tensor view, which a recording cannot repeat, so a recording reads it as it is + self._body_com_pose_b = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.transformf, device=device), update_in_graph=False + ) # -- com frame w.r.t. world frame self._body_com_pose_w = TimestampedBuffer(wp.empty(body_shape, dtype=wp.transformf, device=device)) self._body_com_vel_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device)) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py index edbf2e8c5524..0b0494d353cb 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py @@ -24,6 +24,7 @@ from isaaclab.sensors.contact_sensor.contact_force_marker import ContactForceVisualizer from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source, split_path_expr from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.capture import eager_method from .contact_sensor_data import ContactSensorData from .kernels import ( @@ -445,6 +446,7 @@ def _create_buffers(self) -> None: device=self._device, ) + @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data. diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer.py b/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer.py index 223f40763f26..b5814d9de390 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer.py @@ -21,6 +21,7 @@ from isaaclab.sensors.frame_transformer.kernels import frame_transformer_update_kernel from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source from isaaclab.utils.math import is_identity_pose, normalize, quat_from_angle_axis +from isaaclab.utils.warp.capture import eager_method from .frame_transformer_data import FrameTransformerData @@ -373,6 +374,7 @@ def _initialize_impl(self): ) self._use_recorded_launch = wp.get_device(self._device).is_cuda + @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" # Resolve mask diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py b/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py index e4691ff4b165..3d9966dbc31c 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py @@ -17,6 +17,7 @@ from isaaclab.sensors.imu.kernels import imu_update_kernel from isaaclab.sim.utils.queries import path_expr_to_glob from isaaclab.utils.warp import memory as memory_kernels +from isaaclab.utils.warp.capture import eager_method from .imu_data import ImuData @@ -172,6 +173,7 @@ def _refresh_gravity_bias(self): self._gravity_w = gravity self._gravity_bias_w = wp.vec3f(-gravity[0], -gravity[1], -gravity[2]) + @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py index 1ef7a7412e8e..5e16954d8fb1 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py @@ -18,6 +18,7 @@ from isaaclab.sensors.joint_wrench import BaseJointWrenchSensor from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source from isaaclab.utils.warp import memory as memory_kernels +from isaaclab.utils.warp.capture import eager_method from .joint_wrench_sensor_data import JointWrenchSensorData @@ -144,6 +145,7 @@ def has_articulation_root_api(prim) -> bool: logger.info(f"Joint wrench sensor initialized: {self._num_envs} envs, {self._num_bodies} bodies") + @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array) -> None: """Read PhysX incoming joint wrenches and split them into force / torque buffers. diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py b/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py index 17969394518b..ffd90cef09b9 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py @@ -16,6 +16,7 @@ from isaaclab.sensors.pva import BasePva from isaaclab.sensors.pva.kernels import make_pva_update from isaaclab.sim.utils.queries import path_expr_to_glob +from isaaclab.utils.warp.capture import eager_method from .pva_data import PvaData @@ -175,6 +176,7 @@ def _refresh_gravity_vec(self): scale = 1.0 / max(math.sqrt(gravity[0] ** 2 + gravity[1] ** 2 + gravity[2] ** 2), 1.0e-9) self._gravity_vec_w = wp.vec3f(gravity[0] * scale, gravity[1] * scale, gravity[2] * scale) + @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/ray_caster/ray_caster.py b/source/isaaclab_physx/isaaclab_physx/sensors/ray_caster/ray_caster.py index d592e128fe2a..42ea7a42fc87 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/ray_caster/ray_caster.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/ray_caster/ray_caster.py @@ -17,6 +17,7 @@ import isaaclab.sim as sim_utils from isaaclab.sensors.ray_caster.base_ray_caster import BaseRayCaster from isaaclab.sensors.ray_caster.ray_caster_cfg import RayCasterCfg +from isaaclab.utils.warp.capture import eager_method logger = logging.getLogger(__name__) @@ -145,6 +146,7 @@ def _get_view_transforms_wp(self) -> wp.array: self._raw_transforms = wp.from_torch(transforms.contiguous()).view(wp.transformf) return self._raw_transforms + @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array) -> None: """Refresh PhysX transforms and update ray data eagerly or through a CUDA graph. diff --git a/source/isaaclab_physx/test/sensors/test_contact_sensor.py b/source/isaaclab_physx/test/sensors/test_contact_sensor.py index 0108e0f0452b..64bf873caf24 100644 --- a/source/isaaclab_physx/test/sensors/test_contact_sensor.py +++ b/source/isaaclab_physx/test/sensors/test_contact_sensor.py @@ -35,6 +35,7 @@ from isaaclab.sim.utils.stage import get_current_stage from isaaclab.terrains import HfRandomUniformTerrainCfg, TerrainGeneratorCfg, TerrainImporterCfg from isaaclab.utils import configclass, replace +from isaaclab.utils.warp.capture import GraphedCallable ## # Custom helper classes. @@ -269,7 +270,7 @@ def fetch() -> None: sensor._fetch_physx_buffers = fetch with wp.ScopedCapture(device=wp.get_device(device)): - with pytest.raises(RuntimeError, match="CUDA graph capture"): + with pytest.raises(RuntimeError, match="graph capture"): sensor._update_buffers_impl(env_mask) # record something so the outer capture does not end empty wp.copy(destination, source) @@ -278,6 +279,39 @@ def fetch() -> None: assert fetch_call_count == 0 +def test_contact_sensor_update_repeats_eagerly_on_every_replay_of_a_recording(monkeypatch): + """A GraphedCallable recording that updates the sensor runs the PhysX reads and the update on every replay.""" + monkeypatch.setattr(GraphedCallable, "enabled", True) + device = "cuda:0" + env_mask = wp.ones(1, dtype=wp.bool, device=device) + source = wp.ones(1, dtype=wp.int32, device=device) + destination = wp.zeros(1, dtype=wp.int32, device=device) + before = wp.zeros(1, dtype=wp.int32, device=device) + sensor = _make_graph_test_sensor() + + fetch_call_count = 0 + + def fetch() -> None: + nonlocal fetch_call_count + fetch_call_count += 1 + + sensor._fetch_physx_buffers = fetch + sensor._compute = lambda: wp.copy(destination, source) + + def step() -> None: + wp.copy(before, source) # recorded work around the eager update + sensor._update_buffers_impl(env_mask) + + graphed = GraphedCallable(step, device) + graphed() # the recording is the first run; without the eager boundary the sensor raises here + source.fill_(2) + graphed() + wp.synchronize_device(device) + + assert fetch_call_count == 2 + assert destination.numpy().tolist() == [2] + + def test_contact_sensor_falls_back_when_graph_capture_fails(monkeypatch): """A capture failure should disable graphs and still produce data eagerly.""" device = "cuda:0" diff --git a/source/isaaclab_physx/test/sensors/test_ray_caster_graph.py b/source/isaaclab_physx/test/sensors/test_ray_caster_graph.py index 0acab87f7dc9..e986f1b9b5e1 100644 --- a/source/isaaclab_physx/test/sensors/test_ray_caster_graph.py +++ b/source/isaaclab_physx/test/sensors/test_ray_caster_graph.py @@ -138,7 +138,7 @@ def test_ray_caster_refuses_update_inside_outer_graph_capture(monkeypatch): zeros = wp.zeros_like(sensor._test_output) with wp.ScopedCapture(device=device): - with pytest.raises(RuntimeError, match="CUDA graph capture"): + with pytest.raises(RuntimeError, match="graph capture"): sensor._update_buffers_impl(env_mask) # record something so the outer capture does not end empty wp.copy(sensor._test_output, zeros) From 883dc257096e9aef4b1462b496f074f9b8df2c5f Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 16:40:21 -0800 Subject: [PATCH 09/30] Repeat forward kinematics before an eager call that consumed them while recording A state write recorded by GraphedCallable sets the host flag kinematics_dirty and records forward() at the end of the recording. An eager call of the same recording that read body state ran forward() eagerly and cleared the flag, so the end-of-recording forward() recorded nothing and replays, whose write sets no host flag, never evaluated FK for the replayed write. NewtonManager.forward() now adds a forced FK step right before such an eager call through the new capture helper repeat_before_eager_call; the device masks the replayed write set still select the worlds. --- .../jichuanh-warp-recording-utils.added.rst | 2 + .../isaaclab/isaaclab/utils/warp/capture.py | 18 +++++++ .../isaaclab/test/utils/warp/test_capture.py | 35 +++++++++++++- .../jichuanh-warp-recording-utils.fixed.rst | 3 ++ .../isaaclab_newton/physics/newton_backend.py | 11 +++-- .../isaaclab_newton/physics/newton_manager.py | 20 ++++++-- .../test/physics/test_newton_solver_reset.py | 47 ++++++++++++++++++- 7 files changed, 128 insertions(+), 8 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst index ad043f683a79..db55bd3dfaa3 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst @@ -11,3 +11,5 @@ :attr:`~isaaclab.utils.buffers.TimestampedBuffer.timestamp` now reads as stale until the buffer is updated in that recording, so a lazily cached value read in a recording is recomputed on every replay; ``update_in_graph=False`` keeps the plain timestamp rule, as does any other CUDA graph capture. +* Added :func:`~isaaclab.utils.warp.capture.repeat_before_eager_call`, with which an + :func:`~isaaclab.utils.warp.capture.eager` call of a recording adds a call that every replay runs right before it. diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index 430f287f12e3..ec294589a728 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -58,6 +58,24 @@ def record_at_end(fn: Callable[[], None]) -> bool: return True +def repeat_before_eager_call(fn: Callable[[], None]) -> bool: + """From inside an :func:`eager` call of a :class:`GraphedCallable` recording, run ``fn`` on every replay right + before that call. + + An eager call repeats on each replay with only its own arguments; work it does conditionally on host state that a + replay does not restore, such as a flag a recorded write set, must be added to the replays this way. + + Returns: + Whether an eager call of a recording is running; otherwise nothing is added. + """ + recording = GraphedCallable._recording + if recording is None or recording.capturing: + return False + # the eager call is added to the recording after it returns, so this step comes before it + recording.steps.append((fn, (), {})) + return True + + def eager(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: """Call a function that cannot be recorded from inside a :class:`GraphedCallable`. diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py index 50830210ce4d..b90cd730647e 100644 --- a/source/isaaclab/test/utils/warp/test_capture.py +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -12,7 +12,13 @@ import pytest import warp as wp -from isaaclab.utils.warp.capture import GraphedCallable, capturing, eager, eager_method +from isaaclab.utils.warp.capture import ( + GraphedCallable, + capturing, + eager, + eager_method, + repeat_before_eager_call, +) wp.init() pytestmark = [pytest.mark.kitless, pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA device required")] @@ -165,6 +171,33 @@ def body(values: wp.array) -> wp.array: assert (_read(values), between.calls, before.calls, after.calls, _num_graphs(graphed)) == ([246], 2, 1, 1, 2) +def test_an_eager_call_adds_a_call_that_every_replay_runs_right_before_it(): + """Work an eager call does only while recording, such as consuming a flag a recorded write set on the host, repeats + on every replay right before the eager call.""" + before, added, after = _Affine(2, 0), _Affine(1, 10), _Affine(3, 0) + added_outside_a_recording = [] + + def eager_call(values: wp.array): + # on replays no recording runs, so the call is not added again + if not repeat_before_eager_call(lambda: added(values)): + added_outside_a_recording.append(True) + after(values) + + def body(values: wp.array): + before(values) + eager(eager_call, values) + + graphed = GraphedCallable(body, DEVICE) + values = wp.ones(1, dtype=wp.int32, device=DEVICE) + graphed(values) + # the recording ran only the eager call: 1 * 2 = 2 -> 6 + assert _read(values) == [6] + graphed(values) + # the replay adds 10 between the recorded scale and the eager call: (6 * 2 + 10) * 3 = 66 + assert (_read(values), added.calls, len(added_outside_a_recording)) == ([66], 1, 1) + assert not repeat_before_eager_call(lambda: None), "outside a recording nothing is added" + + def test_eager_call_first_runs_before_the_recorded_work(): """A callable making its eager call first runs it before its recorded work, also when it replays the recording.""" eager_fn, first, second = _Affine(1, 10), _Affine(2, 0), _Affine(3, 0) diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst index a0fe72ea2ffd..3b73e656d306 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -3,3 +3,6 @@ :class:`~isaaclab.utils.warp.capture.GraphedCallable`: 15 of them raised while a graph recorded, and the others replayed the value of the recording step when they were current at recording. A recording now holds their update, so every replay recomputes them. +* Fixed forward kinematics after a state write recorded by :class:`~isaaclab.utils.warp.capture.GraphedCallable` + being skipped on replays when an :func:`~isaaclab.utils.warp.capture.eager` call of the same recording read body + state after the write: every replay now evaluates them right before that call. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index cbf7e59ef1c4..eb353579dec5 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -346,10 +346,15 @@ def invalidate_body_state(self, env_mask: wp.array | None = None, *, consume_mas device=self.device, ) - def forward(self) -> None: - """Reset solver internals and evaluate FK for the flagged worlds and articulations, then clear the flags.""" + def forward(self, force: bool = False) -> None: + """Reset solver internals and evaluate FK for the flagged worlds and articulations, then clear the flags. + + Args: + force: Whether to evaluate even when the host flags report no pending work, for a replay whose recorded + writes flagged worlds on the device only. Defaults to False. + """ self.notify_model_changes() - if not (self.kinematics_dirty or self.fk_on_every_step): + if not (force or self.kinematics_dirty or self.fk_on_every_step): return ops, state = self.solver_ops, self.state_0 if ops is None: diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index 57494afeb30d..d2f4fcefaaa3 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -27,7 +27,7 @@ from isaaclab.utils.string import resolve_matching_names from isaaclab.utils.timer import Timer from isaaclab.utils.version import has_kit -from isaaclab.utils.warp.capture import capturing, eager, is_recording, record_at_end +from isaaclab.utils.warp.capture import capturing, eager, is_recording, record_at_end, repeat_before_eager_call from isaaclab_newton.physics.newton_backend_cfg import NewtonBackendCfg from isaaclab_newton.physics.newton_builder_cfg import NewtonBuilderCfg @@ -166,9 +166,23 @@ def _close_backend(self, *, dispatch_stop: bool = True) -> None: SimulationContext.instance().close_backend(backend) def forward(self) -> None: - """Update articulation kinematics without stepping physics; see :meth:`NewtonBackend.forward`.""" + """Update articulation kinematics without stepping physics; see :meth:`NewtonBackend.forward`. + + An :func:`~isaaclab.utils.warp.capture.eager` call of a recording that consumes pending FK here clears the host + flag the recorded write set, so the FK the recording would add at its end is not recorded and a replay, whose + write sets no host flag, would skip it: every replay then evaluates FK right before that eager call. + """ + backend = self.backend + if backend is None: + return + if backend.kinematics_dirty and not backend.device.is_capturing: + repeat_before_eager_call(self._forward_on_replay) + backend.forward() + + def _forward_on_replay(self) -> None: + """Evaluate FK for the worlds the replayed writes flagged on the device.""" if self.backend is not None: - self.backend.forward() + self.backend.forward(force=True) def video_capture_backend(self) -> str: """Newton GL headless perspective video capture.""" diff --git a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py index e6f621cd0970..6f2aad476372 100644 --- a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py +++ b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py @@ -28,7 +28,7 @@ from isaaclab.sim import SimulationCfg, build_simulation_context from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR -from isaaclab.utils.warp.capture import GraphedCallable +from isaaclab.utils.warp.capture import GraphedCallable, eager def _generate_single_joint_articulations(num_articulations: int, device: str) -> Articulation: @@ -186,3 +186,48 @@ def reset_env_0(): finally: GraphedCallable.enabled = enabled reset.reset() + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_an_eager_read_after_a_recorded_write_sees_its_forward_kinematics_on_every_replay(device): + """An eager call that reads body poses after a recorded joint write consumes the write's pending FK while + recording; every replay still evaluates FK for the replayed write before that call, so it reads the new poses.""" + sim_cfg = SimulationCfg( + dt=1 / 120, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg(njmax=20, nconmax=20, integrator="implicitfast"), + num_substeps=1, + use_cuda_graph=False, + ), + ) + with build_simulation_context(sim_cfg=sim_cfg, device=device) as sim: + sim._app_control_on_stop_handle = None + articulation = _generate_single_joint_articulations(num_articulations=2, device=device) + sim.reset() + env_mask = wp.array([True, False], dtype=wp.bool, device=device) + default_joint_pos = articulation.data.default_joint_pos.torch.clone() + joint_pos = wp.from_torch(default_joint_pos.clone()) + reads: list[torch.Tensor] = [] + + def read_body_poses(): + reads.append(articulation.data.body_link_pose_w.torch.clone()) + + def reset_env_0(): + articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) + eager(read_body_poses) + + reset = GraphedCallable(reset_env_0, device) + enabled, GraphedCallable.enabled = GraphedCallable.enabled, True + try: + for offset in (0.25, 0.5, 1.0): # the first call records, the others replay + wp.to_torch(joint_pos).copy_(default_joint_pos + offset) + reset() + wp.synchronize_device(device) + # the same write and read without a recording + articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) + expected = articulation.data.body_link_pose_w.torch.clone() + torch.testing.assert_close(reads[-1], expected, msg=f"offset {offset}") + assert not torch.allclose(reads[0][0], reads[-1][0]), "the joint write must move env 0's bodies" + finally: + GraphedCallable.enabled = enabled + reset.reset() From bcf4edfd34346883a75265ac572f7f371ee9cf45 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 01:09:32 -0800 Subject: [PATCH 10/30] Read lazy data as stale inside any graph capture TimestampedBuffer reads -1 and commits no fresh timestamp inside any Warp capture, so every capture that reads lazy data holds its update and an abandoned capture leaves the data stale. Sensors refresh in every capture that reads them and clear the dirty flag only outside captures. Removes the recording token and the sensors' _refreshed buffer. (cherry picked from commit cf0721e72680178051516cc9fcc8da078ffbed21) --- .../jichuanh-warp-recording-utils.added.rst | 9 +- .../jichuanh-warp-recording-utils.fixed.rst | 5 +- .../isaaclab/isaaclab/sensors/sensor_base.py | 18 ++- .../utils/buffers/timestamped_buffer.py | 32 ++--- .../isaaclab/isaaclab/utils/warp/capture.py | 11 +- .../sensors/test_sensor_update_schedule.py | 33 +++-- .../test/utils/test_timestamped_buffer.py | 122 +++++++++--------- 7 files changed, 120 insertions(+), 110 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst index db55bd3dfaa3..f3cf8b0a2d81 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst @@ -6,10 +6,9 @@ repeats the call at the same place with the same arguments. * Added :func:`~isaaclab.utils.warp.capture.record_at_end` to record a call once at the end of the :class:`~isaaclab.utils.warp.capture.GraphedCallable` being recorded. -* Added the ``update_in_graph`` argument to :class:`~isaaclab.utils.buffers.TimestampedBuffer`. While a - :class:`~isaaclab.utils.warp.capture.GraphedCallable` records, a buffer's - :attr:`~isaaclab.utils.buffers.TimestampedBuffer.timestamp` now reads as stale until the buffer is updated in that - recording, so a lazily cached value read in a recording is recomputed on every replay; ``update_in_graph=False`` - keeps the plain timestamp rule, as does any other CUDA graph capture. +* Added the ``update_in_graph`` argument to :class:`~isaaclab.utils.buffers.TimestampedBuffer`. Inside any CUDA + graph capture a buffer's :attr:`~isaaclab.utils.buffers.TimestampedBuffer.timestamp` now reads as stale and an + update does not mark it fresh, so a lazily cached value read in a capture is recomputed on every replay, and the + first read after an abandoned capture recomputes it; ``update_in_graph=False`` keeps the plain timestamp rule. * Added :func:`~isaaclab.utils.warp.capture.repeat_before_eager_call`, with which an :func:`~isaaclab.utils.warp.capture.eager` call of a recording adds a call that every replay runs right before it. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst index dc2931b2ce8a..b72f2dd1b3b9 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,4 +1,3 @@ * Fixed sensors read inside a recorded CUDA graph after a reset keeping their data from before the recording: - :class:`~isaaclab.sensors.SensorBase` now records the buffer refresh whenever a - :class:`~isaaclab.utils.warp.capture.GraphedCallable` records, so each replay refreshes the environments whose - data is outdated. :class:`~isaaclab.sensors.Camera` renders eagerly at that place on each replay. + :class:`~isaaclab.sensors.SensorBase` now records the buffer refresh in every CUDA graph capture that reads the + data, so each replay refreshes the environments whose data is outdated. :class:`~isaaclab.sensors.Camera` renders eagerly at that place on each replay. diff --git a/source/isaaclab/isaaclab/sensors/sensor_base.py b/source/isaaclab/isaaclab/sensors/sensor_base.py index 91fcef79b9bc..006e9f7a2fad 100644 --- a/source/isaaclab/isaaclab/sensors/sensor_base.py +++ b/source/isaaclab/isaaclab/sensors/sensor_base.py @@ -30,7 +30,7 @@ from ..physics import PhysicsEvent, PhysicsManager from ..sim.utils.queries import get_first_matching_ancestor_prim from ..sim.utils.transforms import resolve_prim_pose -from ..utils.buffers import TimestampedBuffer +from ..utils.warp.capture import capturing from ..utils.warp.memory import resolve_1d_mask from .kernels import invalidate_buffers_kernel, reset_envs_kernel, update_outdated_envs_kernel, update_timestamp_kernel @@ -218,7 +218,7 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None ], device=self._device, ) - if env_mask is self._ALL_ENV_MASK: + if env_mask is self._ALL_ENV_MASK and not capturing(self._device): self._data_dirty = False def update(self, dt: float, force_recompute: bool = False): @@ -466,8 +466,6 @@ def _create_timing_buffers(self) -> None: # A negative timestamp means no backend sample has been read since initialization/reset. self._timestamp_last_update = wp.full(self._num_envs, -1.0, dtype=wp.float32, device=self._device) self._elapsed_since_update = wp.zeros(self._num_envs, dtype=wp.float64, device=self._device) - # the time of the last refresh, which reads stale in each new graph recording - self._refreshed = TimestampedBuffer(timestamp=0.0) def _invalidate_buffers(self, env_mask: wp.array | None = None) -> None: """Invalidate selected results without advancing sampling clocks; None selects all environments.""" @@ -481,10 +479,9 @@ def _invalidate_buffers(self, env_mask: wp.array | None = None) -> None: def _update_outdated_buffers(self) -> None: """Fills the sensor data for the outdated sensors.""" - # a CUDA graph replays without this check, so the refresh timestamp reads stale in each new GraphedCallable - # recording, which then holds the refresh (see TimestampedBuffer); the outdated mask selects the environments - # each replay updates - if not self._data_dirty and self._refreshed.timestamp >= 0.0: + # a graph replays without this check, so every capture that reads the data holds the refresh; the outdated + # mask selects the environments each replay updates + if not self._data_dirty and not capturing(self._device): return self._update_buffers_impl(self._is_outdated) self._mark_buffers_updated() @@ -498,8 +495,9 @@ def _mark_buffers_updated(self) -> None: inputs=[self._is_outdated, self._timestamp, self._timestamp_last_update, self._elapsed_since_update], device=self._device, ) - self._data_dirty = False - self._refreshed.timestamp = 0.0 + if not capturing(self._device): + # the refresh is recorded, not run: only the replays fill the buffers + self._data_dirty = False @staticmethod def _process_batch(sensors: Sequence[SensorBase]) -> None: diff --git a/source/isaaclab/isaaclab/utils/buffers/timestamped_buffer.py b/source/isaaclab/isaaclab/utils/buffers/timestamped_buffer.py index bc0b790e6a21..3dbe6fb06207 100644 --- a/source/isaaclab/isaaclab/utils/buffers/timestamped_buffer.py +++ b/source/isaaclab/isaaclab/utils/buffers/timestamped_buffer.py @@ -6,7 +6,7 @@ from collections.abc import Iterable from typing import Any -from ..warp.capture import GraphedCallable +from ..warp.capture import capture_in_progress def reset_timestamps(buffers: Iterable["TimestampedBuffer | None"]) -> None: @@ -26,14 +26,14 @@ class TimestampedBuffer: The owner supplies storage and updates the timestamp after computing the value. Array caches accept Torch or Warp arrays directly; no conversion is performed. - While a :class:`~isaaclab.utils.warp.capture.GraphedCallable` records, :attr:`timestamp` reads -1 (stale) until - the data is updated in that recording: a graph replays without the owner's timestamp check, so a recording that - reads the data must hold its update for every replay to recompute it. Data whose update a recording must not hold, - such as a value its owner fetches through a host call or a cache that records its own graph, opts out with - ``update_in_graph=False``. Any other CUDA graph capture keeps the plain timestamp rule. + Inside any graph capture, on any device, :attr:`timestamp` reads -1 (stale) and a fresh timestamp is not + committed: a graph replays without the owner's timestamp check, so a capture that reads the data must hold its + update for every replay to recompute it, and the update of a capture that is abandoned never runs. Data whose + update a capture must not hold, such as a value its owner fetches through a host call or a cache that records its + own graph, opts out with ``update_in_graph=False``. """ - __slots__ = ("data", "update_in_graph", "_timestamp", "_recording") + __slots__ = ("data", "update_in_graph", "_timestamp") def __init__(self, data: Any = None, timestamp: float = -1.0, *, update_in_graph: bool = True): """Initialize the buffer. @@ -41,28 +41,22 @@ def __init__(self, data: Any = None, timestamp: float = -1.0, *, update_in_graph Args: data: Cached array, native-format struct, or grouped data. Defaults to None, before allocation. timestamp: Source timestamp represented by the data. Defaults to -1, which marks it stale. - update_in_graph: Whether a :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording that reads the - data updates it. Defaults to True. + update_in_graph: Whether a graph capture that reads the data updates it. Defaults to True. """ self.data = data self.update_in_graph = update_in_graph self._timestamp = timestamp - self._recording: object = None @property def timestamp(self) -> float: """Source timestamp represented by the data; -1 marks it stale.""" - # is_recording(), inlined: every lazy data read checks it - recording = GraphedCallable._recording - if recording is not None and recording.capturing and self.update_in_graph: - if self._recording is not recording.token: - return -1.0 + if self.update_in_graph and capture_in_progress(): + return -1.0 return self._timestamp @timestamp.setter def timestamp(self, value: float) -> None: + if value >= 0.0 and self.update_in_graph and capture_in_progress(): + # the update is recorded, not run: only the replays make the data fresh + return self._timestamp = value - recording = GraphedCallable._recording - if recording is not None and recording.capturing: - # the recording in progress now holds the update; invalidating clears it, so a later read records it again - self._recording = recording.token if value >= 0 else None diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index ec294589a728..bb1924960e6d 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -32,12 +32,17 @@ def capturing(device: wp.Device | str | None = None) -> bool: outside a recording the check spares the CUDA query; every recording in Isaac Lab starts through Warp. Warp's CPU capture is not in its CUDA capture table and is read from the runtime's private ``_apic_capture``. """ - runtime = _warp_context.runtime - if runtime is None or not (runtime.captures or runtime._apic_capture is not None): + if not capture_in_progress(): return False return wp.get_device(device).is_capturing +def capture_in_progress() -> bool: + """Whether Warp records a graph on any device, a CUDA graph or its CPU one.""" + runtime = _warp_context.runtime + return runtime is not None and bool(runtime.captures or runtime._apic_capture is not None) + + def is_recording() -> bool: """Whether a :class:`GraphedCallable` records, so that an :func:`eager` call repeats on each of its replays.""" recording = GraphedCallable._recording @@ -285,8 +290,6 @@ def __init__(self, device: wp.Device): # calls recorded after the recorded function (see record_at_end) self.end_calls: list = [] self.capturing = False - # identifies the recording to the buffers it refreshes, without keeping its graphs alive - self.token = object() def begin(self) -> None: """Start the next graph.""" diff --git a/source/isaaclab/test/sensors/test_sensor_update_schedule.py b/source/isaaclab/test/sensors/test_sensor_update_schedule.py index 4d6b253698b7..fab70e551633 100644 --- a/source/isaaclab/test/sensors/test_sensor_update_schedule.py +++ b/source/isaaclab/test/sensors/test_sensor_update_schedule.py @@ -12,6 +12,7 @@ from __future__ import annotations import ast +import contextlib import numpy as np import pytest @@ -196,22 +197,38 @@ def _update_buffers_impl(self, env_mask: wp.array): wp.launch(_count_refresh, dim=self._num_envs, inputs=[env_mask, self.device_refreshes], device=self._device) -@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_recorded_read_refreshes_on_every_replay(device, monkeypatch): - """A read recorded while the sensor is not dirty, as after a reset, still refreshes the sensor on each replay.""" - monkeypatch.setattr(GraphedCallable, "enabled", True) +def _capture(device: str, fn) -> wp.Graph: + with wp.ScopedDevice(device), wp.ScopedCapture() as capture: + fn() + return capture.graph + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) +def test_captured_read_refreshes_on_every_replay(device): + """A read captured while the sensor is not dirty, as after a reset, still refreshes the sensor on each replay.""" sensor = _DeviceRefreshSensor(device) sensor.update(0.005) - _ = sensor.data # the sensor is clean when the read is recorded - read = GraphedCallable(lambda: sensor.data, device) - read() # records the refresh of the outdated environments, none yet + _ = sensor.data # the sensor is clean when the read is captured + graph = _capture(device, lambda: sensor.data) for _ in range(3): sensor.update(0.005) - read() + wp.capture_launch(graph) # one eager refresh, then one per replay assert sensor.device_refreshes.numpy().tolist() == [4, 4] +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) +def test_an_abandoned_capture_leaves_the_sensor_due_for_the_next_read(device): + """A capture that reads the sensor and is abandoned launches no refresh, so the next plain read refreshes.""" + sensor = _DeviceRefreshSensor(device) + sensor.update(0.005) + with contextlib.suppress(RuntimeError), wp.ScopedDevice(device), wp.ScopedCapture(): + _ = sensor.data + raise RuntimeError("abandon the capture") + _ = sensor.data + assert sensor.device_refreshes.numpy().tolist() == [1, 1] + + class _Reader: """Two recorded parts that read the same sensor, as the post-physics and observation parts of a step do.""" diff --git a/source/isaaclab/test/utils/test_timestamped_buffer.py b/source/isaaclab/test/utils/test_timestamped_buffer.py index a4bca98c248e..6023ba9a8e48 100644 --- a/source/isaaclab/test/utils/test_timestamped_buffer.py +++ b/source/isaaclab/test/utils/test_timestamped_buffer.py @@ -3,10 +3,12 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""When a :class:`TimestampedBuffer` owner updates its data, eagerly and while a CUDA graph records.""" +"""When a :class:`TimestampedBuffer` owner updates its data, eagerly and inside graph captures.""" from __future__ import annotations +import contextlib + import pytest import warp as wp @@ -18,29 +20,43 @@ @wp.kernel -def _count_update(updates: wp.array(dtype=wp.int32)): +def _double(source: wp.array(dtype=wp.float32), value: wp.array(dtype=wp.float32), updates: wp.array(dtype=wp.int32)): + value[0] = 2.0 * source[0] updates[0] += 1 class _LazyValue: - """A lazily updated value counting its updates on the device.""" + """Twice a source value, updated lazily; the updates are counted on the device.""" def __init__(self, device: str, update_in_graph: bool = True): self.device = device self.timestamp = 0.0 + self.source = wp.ones(1, dtype=wp.float32, device=device) + self.value = wp.zeros(1, dtype=wp.float32, device=device) self.updates = wp.zeros(1, dtype=wp.int32, device=device) - self._value = TimestampedBuffer(self.updates, update_in_graph=update_in_graph) + self._value = TimestampedBuffer(self.value, update_in_graph=update_in_graph) + + def set_source(self, source: float) -> None: + self.source.fill_(source) + self.timestamp += 0.01 - def read(self) -> None: + def read(self) -> wp.array: if self._value.timestamp < self.timestamp: - wp.launch(_count_update, dim=1, inputs=[self.updates], device=self.device) + wp.launch(_double, dim=1, inputs=[self.source, self.value, self.updates], device=self.device) self._value.timestamp = self.timestamp + return self.value @property def num_updates(self) -> int: return int(self.updates.numpy()[0]) +def _capture(device: str, fn) -> wp.Graph: + with wp.ScopedDevice(device), wp.ScopedCapture() as capture: + fn() + return capture.graph + + def test_eager_reads_update_once_per_timestamp(): value = _LazyValue("cpu") for _ in range(2): @@ -52,73 +68,57 @@ def test_eager_reads_update_once_per_timestamp(): assert value.num_updates == 3 -@pytest.fixture -def enabled(monkeypatch): - monkeypatch.setattr(GraphedCallable, "enabled", True) - - -@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_recorded_read_updates_on_every_replay(device, enabled): - """A read recorded while the data is current still updates it on each replay, once per recording.""" +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) +def test_a_capture_holds_the_update_of_every_read(device): + """A read captured while the data is current still updates it on each replay.""" value = _LazyValue(device) - value.read() # the data is current when the read is recorded - - def read_twice(): - value.read() + value.read() # the data is current when the read is captured + graph = _capture(device, value.read) + for source in (2.0, 3.0): + value.set_source(source) + wp.capture_launch(graph) + assert (value.value.numpy()[0], value.num_updates) == (6.0, 3) + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) +def test_a_capture_commits_no_freshness(device): + """An update captured, not run, leaves the data stale for the next eager read, whether the graph is launched or + abandoned.""" + value = _LazyValue(device) + value.set_source(2.0) + _capture(device, value.read) # never launched + assert value.read().numpy()[0] == 4.0 + value.set_source(3.0) + with contextlib.suppress(RuntimeError), wp.ScopedDevice(device), wp.ScopedCapture(): value.read() - - graphed = GraphedCallable(read_twice, device) - graphed() # records the update and runs it once - for _ in range(3): - value.timestamp += 0.01 - graphed() - # one eager update, one when recording, then one per replay - assert value.num_updates == 5 + raise RuntimeError("abandon the capture") + assert value.read().numpy()[0] == 6.0 @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_each_recording_holds_its_own_update(device, enabled): - """An invalidation inside a recording records the update again, and a later recording records its own.""" +def test_an_abandoned_recording_leaves_the_next_plain_read_correct(device, monkeypatch): + """A :class:`GraphedCallable` that reads the data and raises while recording launches nothing, so the next plain + read updates the data.""" + monkeypatch.setattr(GraphedCallable, "enabled", True) value = _LazyValue(device) value.read() - def read_invalidate_read(): - value.read() - reset_timestamps([value._value]) + def read_then_raise(): value.read() + raise RuntimeError("abandon the recording") - invalidated = GraphedCallable(read_invalidate_read, device) - later = GraphedCallable(value.read, device) - invalidated() - later() - value.read() # an eager read after the recordings keeps the eager rule - assert value.num_updates == 4 - invalidated() - later() - assert value.num_updates == 7 + value.set_source(5.0) + with pytest.raises(RuntimeError, match="abandon the recording"): + GraphedCallable(read_then_raise, device)() + assert value.read().numpy()[0] == 10.0 -@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_an_opted_out_buffer_keeps_the_timestamp_rule_while_recording(device, enabled): - """A buffer opting out records its update only when it is stale by timestamp, as outside a recording.""" +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) +def test_an_opted_out_buffer_keeps_the_timestamp_rule_inside_a_capture(device): + """A buffer opting out holds its update in a capture only when it is stale by timestamp, as outside one.""" value = _LazyValue(device, update_in_graph=False) value.read() - graphed = GraphedCallable(value.read, device) - graphed() - assert value._value.timestamp == value.timestamp - graphed() - assert value.num_updates == 1 - - -@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_a_raw_capture_keeps_the_timestamp_rule(device): - """A graph captured without :class:`GraphedCallable` holds the update only when the data is stale by timestamp.""" - value = _LazyValue(device) - value.read() - with wp.ScopedCapture(device=device) as capture: - value.read() - assert value._value.timestamp == value.timestamp - for _ in range(2): - value.timestamp += 0.01 - wp.capture_launch(capture.graph) + graph = _capture(device, value.read) + value.timestamp += 0.01 + wp.capture_launch(graph) assert value.num_updates == 1 From c88845c5d41b3132596b183ef2cfcf7f512824cb Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 01:27:40 -0800 Subject: [PATCH 11/30] Resolve flagged state writes at the start of the Newton step graph The physics step resets the solver and evaluates FK for the worlds and articulations flagged on the device at its start, inside its CUDA graph, so a replayed state write is resolved by the next step. Removes record_at_end and fk_on_every_step; a write recorded in an outer capture flags reads as on main, and add_model_change records the solver refresh in any capture as on main. Forward inside a capture leaves the host flag pending. (cherry picked from commit fb4fbd65e23405e7bfaddf0d6bebfe7120515ef6) --- .../jichuanh-warp-recording-utils.added.rst | 2 - .../isaaclab/isaaclab/utils/warp/capture.py | 18 --- ...test_newton_manager_visualization_state.py | 1 - .../jichuanh-warp-recording-utils.changed.rst | 10 +- .../isaaclab_newton/physics/newton_backend.py | 34 ++++-- .../isaaclab_newton/physics/newton_manager.py | 29 ++--- .../test/fixtures/mock_newton.py | 1 - .../test/assets/test_articulation.py | 2 - .../test/assets/test_joint_coordinates.py | 1 - .../test/physics/test_newton_manager.py | 53 ++++++++- .../test/physics/test_newton_solver_reset.py | 108 +++++++++++++----- 11 files changed, 165 insertions(+), 94 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst index f3cf8b0a2d81..5ceac2c17129 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst @@ -4,8 +4,6 @@ * Added :func:`~isaaclab.utils.warp.capture.eager` for calls that cannot be recorded inside a recorded part. While the part records, the call ends the current CUDA graph and runs eagerly before the next graph starts. Every replay repeats the call at the same place with the same arguments. -* Added :func:`~isaaclab.utils.warp.capture.record_at_end` to record a call once at the end of the - :class:`~isaaclab.utils.warp.capture.GraphedCallable` being recorded. * Added the ``update_in_graph`` argument to :class:`~isaaclab.utils.buffers.TimestampedBuffer`. Inside any CUDA graph capture a buffer's :attr:`~isaaclab.utils.buffers.TimestampedBuffer.timestamp` now reads as stale and an update does not mark it fresh, so a lazily cached value read in a capture is recomputed on every replay, and the diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index bb1924960e6d..166b7ee7e74b 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -49,20 +49,6 @@ def is_recording() -> bool: return recording is not None and recording.capturing -def record_at_end(fn: Callable[[], None]) -> bool: - """Record ``fn`` at the end of the :class:`GraphedCallable` being recorded, once however often it is requested. - - Returns: - Whether a :class:`GraphedCallable` records; without one, the caller handles the replays itself. - """ - recording = GraphedCallable._recording - if recording is None: - return False - if fn not in recording.end_calls: - recording.end_calls.append(fn) - return True - - def repeat_before_eager_call(fn: Callable[[], None]) -> bool: """From inside an :func:`eager` call of a :class:`GraphedCallable` recording, run ``fn`` on every replay right before that call. @@ -254,8 +240,6 @@ def _record_calls(device: wp.Device): recording.begin() try: yield recording - for fn in recording.end_calls: - fn() except BaseException: recording.abort() raise @@ -287,8 +271,6 @@ def __init__(self, device: wp.Device): self.capture_stream = wp.stream_from_torch(torch.cuda.Stream(device=device.alias)) self.mode = wp.CaptureMode.RELAXED self.steps: list = [] - # calls recorded after the recorded function (see record_at_end) - self.end_calls: list = [] self.capturing = False def begin(self) -> None: diff --git a/source/isaaclab/test/sim/test_newton_manager_visualization_state.py b/source/isaaclab/test/sim/test_newton_manager_visualization_state.py index 8c6e332db79a..1873bd43e318 100644 --- a/source/isaaclab/test/sim/test_newton_manager_visualization_state.py +++ b/source/isaaclab/test/sim/test_newton_manager_visualization_state.py @@ -146,7 +146,6 @@ def test_native_publication_reuses_clean_fk_and_refreshes_writes_and_swaps(monke state_version=0, kinematics_dirty=False, transforms_may_change_on_graph_replay=False, - fk_on_every_step=False, device=wp.get_device("cpu"), ) monkeypatch.setattr(owner, "backend", newton_backend) diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst index f4f7e6e0fe1f..22d1225b7d5a 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,7 +1,3 @@ -* Changed Newton to reset the solver and evaluate forward kinematics once after a state write recorded in a Warp - stage, inside that stage's CUDA graph, instead of before every physics step once any write was recorded. State - written inside a raw graph capture still evaluates them before every physics step - (:attr:`~isaaclab_newton.physics.NewtonBackend.fk_on_every_step`). -* Changed :meth:`~isaaclab_newton.physics.NewtonManager.add_model_change` inside a recording of - :class:`~isaaclab.utils.warp.capture.GraphedCallable` to register the change again on each replay, so the next step - refreshes the solver once for all changes; any other capture still records the refresh of that change. +* Changed Newton to reset the solver and evaluate forward kinematics for the worlds flagged by state writes at the + start of each physics step, inside the step's CUDA graph, instead of eagerly before every step once a write was + recorded in a graph. Without flagged worlds the masked kernels do no work. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index eb353579dec5..fee4ab5efcf1 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -197,10 +197,7 @@ def __init__(self, cfg: NewtonBackendCfg, builder: ModelBuilder | None = None, * self.kinematics_dirty = False """Whether joint coordinates changed since the last forward kinematics.""" self.transforms_may_change_on_graph_replay = False - """Whether state was written inside an outer graph capture, so reads refresh derived state.""" - self.fk_on_every_step = False - """Whether a raw graph capture replays state writes without their forward kinematics; :meth:`forward` - then always runs.""" + """Whether state was written inside an outer graph capture; :meth:`forward` then always runs.""" self.model_changes: set[int] = set() """Model-property categories to notify the solver of at the next step.""" self.warned_model_changes: set[int] = set() @@ -354,16 +351,23 @@ def forward(self, force: bool = False) -> None: writes flagged worlds on the device only. Defaults to False. """ self.notify_model_changes() - if not (force or self.kinematics_dirty or self.fk_on_every_step): + if not (force or self.kinematics_dirty or self.transforms_may_change_on_graph_replay): return - ops, state = self.solver_ops, self.state_0 - if ops is None: + if self.solver_ops is None: raise RuntimeError("Newton state was authored before the solver was initialized (init_solver).") + self._resolve_flagged() + if not self.device.is_capturing: + # a capture records the work without running it + self.kinematics_dirty = False + + def _resolve_flagged(self) -> None: + """Reset solver internals and evaluate FK for the worlds and articulations flagged on the device, then clear + the device flags.""" + ops, state = self.solver_ops, self.state_0 ops.reset(state, self.world_mask) ops.eval_fk(state, self.world_mask, self.fk_mask) self.fk_mask.zero_() self.world_mask.zero_() - self.kinematics_dirty = False self.state_version += 1 def notify_model_changes(self) -> None: @@ -501,12 +505,15 @@ def step(self) -> bool: steps = self.decimation if self.handles_decimation() else 1 actuators = self.actuators with wp.ScopedDevice(self.device): - self.forward() if actuators is None or actuators.is_all_graphable: + self.notify_model_changes() self._launch(("simulate", steps), partial(self._simulate, steps)) + if not self.device.is_capturing: + self.kinematics_dirty = False else: if self.device.is_capturing: raise RuntimeError("Newton actuators that cannot be captured prevent recording the step.") + self.forward() self._stage_body_forces() for i in range(steps): self._launch("before_actuators", self._before_actuators) @@ -617,7 +624,14 @@ def _launch(self, key: str | tuple[str, int], fn: Callable[[], None]) -> None: self.graphs[key] = self.capture(fn) def _simulate(self, steps: int) -> None: - """Run ``steps`` physics steps with the Newton actuators, then finish the step.""" + """Resolve the flagged state writes, run ``steps`` physics steps with the Newton actuators, then finish the + step. + + A captured step resolves the flags on every replay, since replayed writes flag worlds on the device only; with + nothing flagged the masked kernels do no work. + """ + if self.device.is_capturing or self.kinematics_dirty or self.transforms_may_change_on_graph_replay: + self._resolve_flagged() actuators = self.actuators self._stage_body_forces() for i in range(steps): diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index d2f4fcefaaa3..0aca54352e4e 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -27,7 +27,7 @@ from isaaclab.utils.string import resolve_matching_names from isaaclab.utils.timer import Timer from isaaclab.utils.version import has_kit -from isaaclab.utils.warp.capture import capturing, eager, is_recording, record_at_end, repeat_before_eager_call +from isaaclab.utils.warp.capture import repeat_before_eager_call from isaaclab_newton.physics.newton_backend_cfg import NewtonBackendCfg from isaaclab_newton.physics.newton_builder_cfg import NewtonBuilderCfg @@ -169,8 +169,8 @@ def forward(self) -> None: """Update articulation kinematics without stepping physics; see :meth:`NewtonBackend.forward`. An :func:`~isaaclab.utils.warp.capture.eager` call of a recording that consumes pending FK here clears the host - flag the recorded write set, so the FK the recording would add at its end is not recorded and a replay, whose - write sets no host flag, would skip it: every replay then evaluates FK right before that eager call. + flag the recorded write set, and a replay, whose write sets no host flag, would skip it: every replay then + evaluates FK right before that eager call. """ backend = self.backend if backend is None: @@ -200,17 +200,9 @@ def _mark_particles_dirty(self) -> None: self._flag_outer_capture() def _flag_outer_capture(self) -> None: - """Flag writes recorded into an outer graph capture. - - A :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording the write also records :meth:`forward` at - its end, so each replay resets the solver and evaluates FK once after the write; a raw capture cannot, so FK - then runs before every physics step. - """ - backend = self.backend - if backend.device.is_capturing: - backend.transforms_may_change_on_graph_replay = True - if not record_at_end(backend.forward): - backend.fk_on_every_step = True + """Flag writes recorded into an outer graph capture.""" + if self.backend.device.is_capturing: + self.backend.transforms_may_change_on_graph_replay = True def step(self) -> None: """Advance physics by one environment step, or one physics step when the environment runs decimation.""" @@ -373,19 +365,18 @@ def request_extended_contact_attribute(self, attr: str) -> None: def add_model_change(self, change: ModelFlags) -> None: """Register a model change to notify the solver at the next step. - The registration is host work: a recorded part of the step that writes registers it again on each replay. A - capture that no :class:`~isaaclab.utils.warp.capture.GraphedCallable` records cannot repeat host work, so it - records the refresh of this change alone instead; changes queued before the capture stay queued. + Inside a graph capture, the refresh of this change alone is recorded instead, so every replay applies it; + changes queued before the capture stay queued for the next step. """ backend = self.backend - if capturing(backend.device) and not is_recording(): + if wp.get_device(backend.device).is_capturing: queued, backend.model_changes = backend.model_changes, {change} try: backend.notify_model_changes() finally: backend.model_changes = queued else: - eager(backend.model_changes.add, change) + backend.model_changes.add(change) def invalidate_fk( self, diff --git a/source/isaaclab_newton/isaaclab_newton/test/fixtures/mock_newton.py b/source/isaaclab_newton/isaaclab_newton/test/fixtures/mock_newton.py index efd33cafa840..6bd24fe2cbc7 100644 --- a/source/isaaclab_newton/isaaclab_newton/test/fixtures/mock_newton.py +++ b/source/isaaclab_newton/isaaclab_newton/test/fixtures/mock_newton.py @@ -83,7 +83,6 @@ def create_mock_newton_manager( state_version=0, device=wp.get_device("cpu"), transforms_may_change_on_graph_replay=False, - fk_on_every_step=False, ) return manager diff --git a/source/isaaclab_newton/test/assets/test_articulation.py b/source/isaaclab_newton/test/assets/test_articulation.py index f73cf0c2eef3..03881312fe32 100644 --- a/source/isaaclab_newton/test/assets/test_articulation.py +++ b/source/isaaclab_newton/test/assets/test_articulation.py @@ -438,7 +438,6 @@ def test_task_space_allocation_and_capture(device, first_property): state_version=0, device=model.device, transforms_may_change_on_graph_replay=False, - fk_on_every_step=False, ) view = ArticulationView(model, "Robot", exclude_joint_types=[JointType.FIXED]) eager = ArticulationData(view, device, backend_manager=backend_manager) @@ -493,7 +492,6 @@ def test_world_hinged_root_has_no_base_dofs(device): state_version=0, device=model.device, transforms_may_change_on_graph_replay=False, - fk_on_every_step=False, ) root_view = ArticulationView(model, "Robot") data = ArticulationData(root_view, device, backend_manager=backend_manager) diff --git a/source/isaaclab_newton/test/assets/test_joint_coordinates.py b/source/isaaclab_newton/test/assets/test_joint_coordinates.py index 17d5c7e96552..2d9fb46de182 100644 --- a/source/isaaclab_newton/test/assets/test_joint_coordinates.py +++ b/source/isaaclab_newton/test/assets/test_joint_coordinates.py @@ -111,7 +111,6 @@ def test_joint_commands_preserve_coordinate_layout(ball_joint): state_version=0, device=model.device, transforms_may_change_on_graph_replay=False, - fk_on_every_step=False, ) view = ArticulationView(model, "Robot", exclude_joint_types=[newton.JointType.FREE]) data = ArticulationData(view, "cpu", backend_manager=backend_manager) diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index 2ced8754840d..6b457098a1fe 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -143,7 +143,6 @@ def on_physics_ready(_): assert isinstance(sim.backend_manager.backend.solver, SolverMuJoCo) # as a write during graph capture does sim.backend_manager.backend.transforms_may_change_on_graph_replay = True - sim.backend_manager.backend.fk_on_every_step = True sim.reset() assert events == ["ready", "prepare"] * 2 @@ -325,7 +324,6 @@ def check_step(self, captured, debug): fk_mask=wp.zeros(1, dtype=wp.bool, device=device), kinematics_dirty=False, transforms_may_change_on_graph_replay=False, - fk_on_every_step=False, state_version=0, model_changes=set(), warned_model_changes=set(), @@ -607,6 +605,55 @@ def test_step_runs_eagerly_once_then_replays_a_graph_only_when_the_solver_suppor # ----- Reset masks ------------------------------------------------------------------------- +@wp.kernel +def _count_flagged(flags: wp.array(dtype=wp.bool), counts: wp.array(dtype=wp.int32)): + i = wp.tid() + if flags[i]: + counts[i] += 1 + + +def test_a_captured_step_resolves_the_worlds_a_replayed_write_flagged(): + """A replayed state write flags worlds on the device only; each replay of the captured step resets the solver and + evaluates FK for exactly those worlds and articulations, then clears the flags.""" + backend = _recording_backend([], captures=True) + resets = wp.zeros(2, dtype=wp.int32, device="cpu") + fks = wp.zeros(1, dtype=wp.int32, device="cpu") + ops = backend.solver_ops + ops.reset = lambda state, worlds: wp.launch(_count_flagged, 2, inputs=[worlds, resets], device="cpu") + ops.eval_fk = lambda state, worlds, articulations: wp.launch( + _count_flagged, 1, inputs=[articulations, fks], device="cpu" + ) + + backend.step() # runs eagerly with nothing flagged, then captures the step + assert backend.graphs + for _ in range(2): + # as a replayed write flags them, with no host flag + backend.world_mask.assign(wp.array([True, False], dtype=wp.bool, device="cpu")) + backend.fk_mask.fill_(True) + backend.step() + + assert (resets.numpy().tolist(), fks.numpy().tolist()) == ([2, 0], [2]) + assert not backend.world_mask.numpy().any() and not backend.fk_mask.numpy().any() + + +def test_forward_recorded_in_an_abandoned_capture_leaves_the_flags_pending(): + """FK recorded in a capture runs only when the graph is launched, so a capture that is abandoned leaves the host + flag and the device flags pending for the next eager forward.""" + backend = _recording_backend([]) + resets = wp.zeros(2, dtype=wp.int32, device="cpu") + backend.solver_ops.reset = lambda state, worlds: wp.launch(_count_flagged, 2, inputs=[worlds, resets], device="cpu") + backend.world_mask.assign(wp.array([True, False], dtype=wp.bool, device="cpu")) + backend.kinematics_dirty = True + + with wp.ScopedDevice("cpu"), wp.ScopedCapture(): # never launched + backend.forward() + assert backend.kinematics_dirty + backend.forward() + + assert resets.numpy().tolist() == [1, 0] + assert not backend.kinematics_dirty and not backend.world_mask.numpy().any() + + def test_forward_resolves_flagged_worlds_once_and_not_while_an_outer_graph_records_the_read(): """Reading published state resolves pending FK once; a raw read during capture leaves it pending.""" resets, fks = [], [] @@ -635,7 +682,6 @@ def eval_fk(self, state, worlds, articulations): fk_mask=fk_mask, kinematics_dirty=True, transforms_may_change_on_graph_replay=False, - fk_on_every_step=False, model_changes=set(), state_version=0, ) @@ -664,7 +710,6 @@ def test_manager_flags_the_masked_worlds_and_articulations(articulation_mask): fk_mask=wp.zeros(6, dtype=wp.bool, device="cpu"), kinematics_dirty=False, transforms_may_change_on_graph_replay=False, - fk_on_every_step=False, ) articulation_ids = wp.array([[0, 1], [2, 3], [4, 5]], dtype=wp.int32, device="cpu") env_mask = wp.array([True, False, True], dtype=wp.bool, device="cpu") diff --git a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py index 6f2aad476372..58c699cfc0d7 100644 --- a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py +++ b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py @@ -17,7 +17,6 @@ import warp as wp from isaaclab_newton.assets import Articulation from isaaclab_newton.physics import MJWarpSolverCfg, NewtonBackend, NewtonCfg -from isaaclab_newton.physics.newton_solver import NewtonSolver from isaaclab_physx.sim.schemas import PhysxJointCfg from newton.solvers import SolverMuJoCo @@ -60,6 +59,21 @@ def _generate_single_joint_articulations(num_articulations: int, device: str) -> return articulation +def _no_substeps(self, contacts, *, observables): + """Stand-in for :meth:`NewtonBackend._run_solver_substeps` that leaves the state and solver history as they are.""" + + +def _sim_cfg(use_cuda_graph: bool) -> SimulationCfg: + return SimulationCfg( + dt=1 / 120, + physics=NewtonCfg( + solver_cfg=MJWarpSolverCfg(njmax=20, nconmax=20, integrator="implicitfast"), + num_substeps=1, + use_cuda_graph=use_cuda_graph, + ), + ) + + @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) def test_env_reset_clears_selected_mjwarp_solver_internals(device): """An env reset clears the flagged world's MuJoCo warm-start history and keeps the others. @@ -129,7 +143,7 @@ def test_env_reset_clears_selected_mjwarp_solver_internals(device): backend = sim.backend_manager.backend backend.invalidate_graph() - with patch.object(NewtonBackend, "_simulate", lambda self, steps: None): + with patch.object(NewtonBackend, "_run_solver_substeps", _no_substeps): sim.step(render=False) backend.invalidate_graph() wp.synchronize_device(device) @@ -140,26 +154,21 @@ def test_env_reset_clears_selected_mjwarp_solver_internals(device): torch.testing.assert_close(warm_start[1], torch.full_like(warm_start[1], 29.0)) +@pytest.mark.parametrize("use_cuda_graph", [False, True], ids=["eager_step", "captured_step"]) @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_recorded_env_reset_evaluates_fk_once_per_replay(device): - """A recorded part of the step that resets an env clears the reset world's solver history inside its replay, and - the physics steps after it evaluate no further forward kinematics.""" - sim_cfg = SimulationCfg( - dt=1 / 120, - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg(njmax=20, nconmax=20, integrator="implicitfast"), - num_substeps=1, - use_cuda_graph=False, - ), - ) - with build_simulation_context(sim_cfg=sim_cfg, device=device) as sim: +def test_the_step_after_a_replayed_state_write_resolves_it_as_after_an_eager_write(device, use_cuda_graph): + """A joint write recorded by a :class:`GraphedCallable` flags its world on the device only. On every replay, the + next physics step, eager or replayed from its own graph, resets that world's solver history, keeps the other + worlds' history and evaluates its forward kinematics, as after the same write made eagerly.""" + with build_simulation_context(sim_cfg=_sim_cfg(use_cuda_graph), device=device) as sim: sim._app_control_on_stop_handle = None articulation = _generate_single_joint_articulations(num_articulations=2, device=device) sim.reset() backend = sim.backend_manager.backend warm_start = wp.to_torch(backend.solver.mjw_data.qacc_warmstart) env_mask = wp.array([True, False], dtype=wp.bool, device=device) - joint_pos = wp.from_torch(articulation.data.default_joint_pos.torch.clone() + 0.25) + default_joint_pos = articulation.data.default_joint_pos.torch.clone() + joint_pos = wp.from_torch(default_joint_pos.clone()) def reset_env_0(): articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) @@ -167,25 +176,66 @@ def reset_env_0(): reset = GraphedCallable(reset_env_0, device) enabled, GraphedCallable.enabled = GraphedCallable.enabled, True try: - reset() # records - warm_start[0].fill_(13.0) - warm_start[1].fill_(17.0) - reset() # replays - wp.synchronize_device(device) - assert torch.count_nonzero(warm_start[0]).item() == 0 - torch.testing.assert_close(warm_start[1], torch.full_like(warm_start[1], 17.0)) - - with ( - patch.object(NewtonSolver, "eval_fk", side_effect=NewtonSolver.eval_fk) as fk, - patch.object(NewtonBackend, "_simulate", lambda self, steps: None), - ): + with patch.object(NewtonBackend, "_run_solver_substeps", _no_substeps): backend.invalidate_graph() - for _ in range(2): + for offset in (0.25, 0.5, 1.0): # the first write and step record, the others replay + wp.to_torch(joint_pos).copy_(default_joint_pos + offset) + warm_start[0].fill_(13.0) + warm_start[1].fill_(17.0) + reset() sim.step(render=False) - assert fk.call_count == 0 + wp.synchronize_device(device) + assert torch.count_nonzero(warm_start[0]).item() == 0, f"offset {offset}" + torch.testing.assert_close(warm_start[1], torch.full_like(warm_start[1], 17.0)) + body_q = wp.to_torch(backend.state_0.body_q).clone() + # the same write made eagerly, resolved by the forward boundary + articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) + backend.forward(force=True) + wp.synchronize_device(device) + torch.testing.assert_close(body_q, wp.to_torch(backend.state_0.body_q), msg=f"offset {offset}") + assert bool(backend.graphs) == use_cuda_graph + finally: + GraphedCallable.enabled = enabled + reset.reset() + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_a_recorded_read_after_a_recorded_write_sees_its_forward_kinematics_on_every_replay(device): + """A read recorded after an eager read consumed the pending FK of a recorded write still evaluates FK on every + replay, so it reads the body poses of each replayed write.""" + with build_simulation_context(sim_cfg=_sim_cfg(use_cuda_graph=False), device=device) as sim: + sim._app_control_on_stop_handle = None + articulation = _generate_single_joint_articulations(num_articulations=2, device=device) + sim.reset() + env_mask = wp.array([True, False], dtype=wp.bool, device=device) + default_joint_pos = articulation.data.default_joint_pos.torch.clone() + joint_pos = wp.from_torch(default_joint_pos.clone()) + poses = wp.zeros_like(articulation.data.body_link_pose_w.warp) + + def reset_env_0(): + articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) + + def read_body_poses(): + wp.copy(poses, articulation.data.body_link_pose_w.warp) + + reset, read = GraphedCallable(reset_env_0, device), GraphedCallable(read_body_poses, device) + enabled, GraphedCallable.enabled = GraphedCallable.enabled, True + try: + for offset in (0.25, 0.5, 1.0): # the first calls record, the others replay + wp.to_torch(joint_pos).copy_(default_joint_pos + offset) + reset() + if offset == 0.25: + _ = articulation.data.body_link_pose_w # an eager read consumes the pending FK + read() + wp.synchronize_device(device) + # the same write and read without a recording + articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) + expected = articulation.data.body_link_pose_w.torch + torch.testing.assert_close(wp.to_torch(poses), expected, msg=f"offset {offset}") finally: GraphedCallable.enabled = enabled reset.reset() + read.reset() @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) From 5f6671c0c1982304e26593fdcc131248131e73f0 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 01:44:05 -0800 Subject: [PATCH 12/30] Run a recorded call that makes an eager call without a graph A GraphedCallable that meets an eager() call while recording abandons the recording, which launches nothing, and runs plainly from then on, starting with that call; an invalidation lets it record again. A recording is one graph: _Recording.split and repeat_before_eager_call are removed, and Newton's forward is main's again. --- .../jichuanh-warp-recording-utils.added.rst | 9 +- .../jichuanh-warp-recording-utils.fixed.rst | 3 +- .../isaaclab/isaaclab/utils/warp/capture.py | 145 ++++++++---------- .../isaaclab/test/utils/warp/test_capture.py | 97 ++++++------ .../jichuanh-warp-recording-utils.changed.rst | 5 +- .../jichuanh-warp-recording-utils.fixed.rst | 3 - .../isaaclab_newton/physics/newton_backend.py | 11 +- .../isaaclab_newton/physics/newton_manager.py | 19 +-- .../test/physics/test_newton_solver_reset.py | 49 +----- .../jichuanh-warp-recording-utils.fixed.rst | 2 +- .../jichuanh-warp-recording-utils.fixed.rst | 2 +- 11 files changed, 131 insertions(+), 214 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst index 5ceac2c17129..8b34d1ed7e42 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst @@ -1,12 +1,11 @@ * Added :mod:`isaaclab.utils.warp.capture`. :class:`~isaaclab.utils.warp.capture.GraphedCallable` records a call as a CUDA graph on its first run with a given argument layout and replays it after; it records again for another layout or when the physics backend rebinds its buffers. -* Added :func:`~isaaclab.utils.warp.capture.eager` for calls that cannot be recorded inside a recorded part. While - the part records, the call ends the current CUDA graph and runs eagerly before the next graph starts. Every replay - repeats the call at the same place with the same arguments. +* Added :func:`~isaaclab.utils.warp.capture.eager` and :func:`~isaaclab.utils.warp.capture.eager_method` for calls + that cannot be recorded. A :class:`~isaaclab.utils.warp.capture.GraphedCallable` that makes one while it records + abandons the recording without launching it and runs without a CUDA graph from then on, logging a warning that + names both calls. * Added the ``update_in_graph`` argument to :class:`~isaaclab.utils.buffers.TimestampedBuffer`. Inside any CUDA graph capture a buffer's :attr:`~isaaclab.utils.buffers.TimestampedBuffer.timestamp` now reads as stale and an update does not mark it fresh, so a lazily cached value read in a capture is recomputed on every replay, and the first read after an abandoned capture recomputes it; ``update_in_graph=False`` keeps the plain timestamp rule. -* Added :func:`~isaaclab.utils.warp.capture.repeat_before_eager_call`, with which an - :func:`~isaaclab.utils.warp.capture.eager` call of a recording adds a call that every replay runs right before it. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst index b72f2dd1b3b9..e391d32a16c4 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,3 +1,4 @@ * Fixed sensors read inside a recorded CUDA graph after a reset keeping their data from before the recording: :class:`~isaaclab.sensors.SensorBase` now records the buffer refresh in every CUDA graph capture that reads the - data, so each replay refreshes the environments whose data is outdated. :class:`~isaaclab.sensors.Camera` renders eagerly at that place on each replay. + data, so each replay refreshes the environments whose data is outdated. :class:`~isaaclab.sensors.Camera` renders + on the host, so a recorded call that reads it runs without a CUDA graph. diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index 166b7ee7e74b..e2aacc1a8f90 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -3,8 +3,8 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""CUDA graph recording of the Warp frontend: :class:`GraphedCallable` records a call as CUDA graphs and replays it, -and :func:`eager` runs a call that cannot be recorded at its place in the recording. +"""CUDA graph recording of the Warp frontend: :class:`GraphedCallable` records a call as a CUDA graph and replays it. +A call that cannot be recorded goes through :func:`eager`; a recorded call that makes one runs plainly instead. """ from __future__ import annotations @@ -12,6 +12,7 @@ import contextlib import functools import gc +import logging from collections.abc import Callable from typing import TYPE_CHECKING, Any, ClassVar @@ -24,6 +25,8 @@ if TYPE_CHECKING: from ...physics import PhysicsManager +logger = logging.getLogger(__name__) + def capturing(device: wp.Device | str | None = None) -> bool: """Whether a graph is being recorded on ``device`` (the current device by default), a CUDA graph or Warp's CPU one. @@ -43,36 +46,11 @@ def capture_in_progress() -> bool: return runtime is not None and bool(runtime.captures or runtime._apic_capture is not None) -def is_recording() -> bool: - """Whether a :class:`GraphedCallable` records, so that an :func:`eager` call repeats on each of its replays.""" - recording = GraphedCallable._recording - return recording is not None and recording.capturing - - -def repeat_before_eager_call(fn: Callable[[], None]) -> bool: - """From inside an :func:`eager` call of a :class:`GraphedCallable` recording, run ``fn`` on every replay right - before that call. - - An eager call repeats on each replay with only its own arguments; work it does conditionally on host state that a - replay does not restore, such as a flag a recorded write set, must be added to the replays this way. - - Returns: - Whether an eager call of a recording is running; otherwise nothing is added. - """ - recording = GraphedCallable._recording - if recording is None or recording.capturing: - return False - # the eager call is added to the recording after it returns, so this step comes before it - recording.steps.append((fn, (), {})) - return True - - def eager(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: - """Call a function that cannot be recorded from inside a :class:`GraphedCallable`. + """Call a function that cannot be recorded. - Outside a recording this is a plain call. While a :class:`GraphedCallable` records, the call ends the current - graph, runs eagerly and starts the next graph, and every replay repeats it at the same place with the same - arguments, so the arguments must stay valid across calls like the arrays a graph reads. Replays discard its result. + Outside a recording this is a plain call. A :class:`GraphedCallable` that meets it while recording abandons the + recording, which launches nothing, and runs plainly from then on, this call included. Args: fn: The function to call. @@ -87,20 +65,33 @@ def eager(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: """ recording = GraphedCallable._recording if recording is not None and recording.capturing: - return recording.split(fn, args, kwargs) + raise _EagerCall(fn) if capturing(): - name = getattr(fn, "__qualname__", type(fn).__name__) raise RuntimeError( - f"'{name}' cannot be recorded, so it cannot run inside a graph capture that no GraphedCallable started." + f"'{_name(fn)}' cannot be recorded, so it cannot run inside a graph capture that no GraphedCallable" + " started." ) return fn(*args, **kwargs) +class _EagerCall(BaseException): + """Raised by :func:`eager` inside a recording, which the :class:`GraphedCallable` abandons. + + It derives from :class:`BaseException`, so the ``except Exception`` handlers of the recorded code let it through. + """ + + def __init__(self, fn: Callable[..., Any]): + super().__init__(_name(fn)) + + +def _name(fn: Callable[..., Any]) -> str: + return getattr(fn, "__qualname__", type(fn).__name__) + + def eager_method(method: Callable[..., Any]) -> Callable[..., Any]: """Run a method that cannot be recorded through :func:`eager`. - A :class:`GraphedCallable` recording a call to the method replays it eagerly with the same arguments. An override - in a subclass is decorated again. + A :class:`GraphedCallable` that calls the method runs plainly. An override in a subclass is decorated again. Args: method: The method to wrap. @@ -117,14 +108,14 @@ def wrapper(self, *args: Any, **kwargs: Any) -> Any: class GraphedCallable: - """A callable recorded as CUDA graphs on its first call with a given argument layout and replayed after. + """A callable recorded as a CUDA graph on its first call with a given argument layout and replayed after. * The first call with a given argument layout records without an eager warm-up: the recording is its first execution. Later calls with the same array pointers and scalar values replay that recording and return the result of the recording call, so the callable returns buffers its owner keeps. - * Calls that cannot be recorded go through :func:`eager`. A recording ends its graph at each of them, runs the - call and starts the next graph; a replay launches the graphs and repeats the calls with their recorded - arguments, in the recorded order. + * Calls that cannot be recorded go through :func:`eager`. A recording that meets one is abandoned without + launching anything, and the callable runs plainly from then on, starting with this call; it records again after + :meth:`reset`. * :attr:`enabled` turns recording off process-wide, to run every part eagerly; it is on by default. A callable on a CPU device always runs eagerly. * :attr:`generation` advances when the terms change or the physics backend rebinds its buffers or stops (see @@ -145,18 +136,20 @@ class GraphedCallable: """The watched physics backend's forward, run before each recording (see :meth:`watch`).""" _recording: ClassVar[_Recording | None] = None - """The recording in progress, which :func:`eager` calls split.""" + """The recording in progress, which an :func:`eager` call abandons.""" def __init__(self, fn: Callable[..., Any], device: wp.DeviceLike): """Initialize the callable. Args: - fn: Callable to record. Its GPU work must be capturable, except for :func:`eager` calls. + fn: Callable to record. Its GPU work must be capturable; a call that is not goes through :func:`eager`. device: Warp device that runs the callable. """ self._fn = fn self._device = wp.get_device(device) - self._recordings: dict[tuple, tuple[list, Any]] = {} + self._recordings: dict[tuple, tuple[wp.Graph, Any]] = {} + self._plain = False + """Whether the callable met an :func:`eager` call while recording, so it runs plainly.""" self._generation = GraphedCallable.generation def __call__(self, *args: Any, **kwargs: Any) -> Any: @@ -168,17 +161,27 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any: if self._generation != GraphedCallable.generation: self.reset() self._generation = GraphedCallable.generation + if self._plain: + return self._fn(*args, **kwargs) key = _argument_key(args, kwargs) recorded = self._recordings.get(key) if recorded is None: - self._recordings[key] = recorded = self._record(args, kwargs) + try: + self._recordings[key] = recorded = self._record(args, kwargs) + except _EagerCall as call: + self._plain = True + logger.warning( + "'%s' calls '%s', which cannot be recorded, so it runs without a CUDA graph.", _name(self._fn), call + ) + return self._fn(*args, **kwargs) return recorded[1] - steps, result = recorded - _replay(steps) + graph, result = recorded + wp.capture_launch(graph) return result def reset(self) -> None: - """Drop the recordings; the callable records again on its next call.""" + """Drop the recordings; the callable records again on its next call, also after it ran plainly.""" + self._plain = False if self._recordings: # graphs may still be executing; drain the device before releasing them wp.synchronize_device(self._device) @@ -216,19 +219,23 @@ def invalidate(cls, payload: Any = None) -> None: """Record every callable again on its next call.""" cls.generation += 1 - def _record(self, args: tuple, kwargs: dict[str, Any]) -> tuple[list, Any]: - """Record the callable as its first run and return the recorded steps and the result.""" + def _record(self, args: tuple, kwargs: dict[str, Any]) -> tuple[wp.Graph, Any]: + """Record the callable as its first run and return the graph and the result. + + Raises: + _EagerCall: If the callable makes an :func:`eager` call; the recording launched nothing. + """ with _record_calls(self._device) as recording: result = self._fn(*args, **kwargs) - return recording.steps, result + return recording.graph, result @contextlib.contextmanager def _record_calls(device: wp.Device): - """Record the calls made inside as CUDA graphs split around :func:`eager` calls; the recording is their first run. + """Record the calls made inside as a CUDA graph; the recording is their first run. Yields: - The recording, whose steps replay the calls (see :func:`_replay`). + The recording, whose graph replays the calls. """ if GraphedCallable._settle is not None: # physics work queued before the recording runs now, once, instead of on every replay @@ -248,21 +255,11 @@ def _record_calls(device: wp.Device): GraphedCallable._recording = enclosing -def _replay(steps: list) -> None: - """Launch the graphs of a recording and repeat its eager calls, in the recorded order.""" - for step in steps: - if isinstance(step, wp.Graph): - wp.capture_launch(step) - else: - fn, args, kwargs = step - fn(*args, **kwargs) - - class _Recording: - """The steps of one recording: CUDA graphs split around :func:`eager` calls, launched as they end.""" + """One recording: a CUDA graph, launched when it ends since the recording is the first run of the callable.""" def __init__(self, device: wp.Device): - # graphs are captured on the capture stream and launched on the stream the callable runs on + # the graph is captured on the capture stream and launched on the stream the callable runs on self.stream = wp.get_stream(device) self.capture_stream = self.stream self.mode = wp.CaptureMode.THREAD_LOCAL @@ -270,37 +267,27 @@ def __init__(self, device: wp.Device): # RTX uses the legacy CUDA stream. A nonblocking stream avoids implicit synchronization. self.capture_stream = wp.stream_from_torch(torch.cuda.Stream(device=device.alias)) self.mode = wp.CaptureMode.RELAXED - self.steps: list = [] + self.graph: wp.Graph | None = None self.capturing = False def begin(self) -> None: - """Start the next graph.""" + """Start the graph.""" wp.capture_begin(stream=self.capture_stream, capture_mode=self.mode) self.capturing = True def end(self) -> None: - """End the current graph and launch it, since the recording is the first run of the callable.""" + """End the graph and launch it.""" self.capturing = False - graph = wp.capture_end(stream=self.capture_stream) - wp.capture_launch(graph, stream=self.stream) - self.steps.append(graph) + self.graph = wp.capture_end(stream=self.capture_stream) + wp.capture_launch(self.graph, stream=self.stream) def abort(self) -> None: - """End the current graph without launching it, after the callable raised.""" + """End the graph without launching it, after the callable raised or made an :func:`eager` call.""" if self.capturing: self.capturing = False with contextlib.suppress(Exception): wp.capture_end(stream=self.capture_stream) - def split(self, fn: Callable[..., Any], args: tuple, kwargs: dict[str, Any]) -> Any: - """Run a call that cannot be recorded between the current graph and the next one.""" - self.end() - with wp.ScopedStream(self.stream, sync_enter=False): - result = fn(*args, **kwargs) - self.steps.append((fn, args, kwargs)) - self.begin() - return result - @contextlib.contextmanager def _paused_gc(): diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py index b90cd730647e..7cd032196237 100644 --- a/source/isaaclab/test/utils/warp/test_capture.py +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -7,6 +7,7 @@ from __future__ import annotations +import logging from types import SimpleNamespace import pytest @@ -17,7 +18,6 @@ capturing, eager, eager_method, - repeat_before_eager_call, ) wp.init() @@ -33,7 +33,7 @@ def _affine(values: wp.array(dtype=wp.int32), scale: wp.int32, shift: wp.int32): def _num_graphs(graphed: GraphedCallable) -> int: """Number of graphs recorded for a callable.""" - return sum(isinstance(step, wp.Graph) for steps, _ in graphed._recordings.values() for step in steps) + return len(graphed._recordings) class _Affine: @@ -152,8 +152,8 @@ def test_callable_runs_eagerly_when_disabled_or_on_cpu(monkeypatch): assert (disabled.calls, _read(values), _num_graphs(graphed)) == (2, [2], 0) -def test_eager_call_runs_between_its_graphs_on_every_call(): - """The recording runs the graph before an eager call first, and every replay keeps that order.""" +def test_an_eager_call_abandons_the_recording_and_the_callable_runs_plainly(caplog): + """A recording that meets an eager call launches nothing; the call then runs plainly, now and on later calls.""" before, between, after = _Affine(2, 0), _Affine(1, 10), _Affine(3, 0) def body(values: wp.array) -> wp.array: @@ -164,58 +164,56 @@ def body(values: wp.array) -> wp.array: graphed = GraphedCallable(body, DEVICE) values = wp.ones(1, dtype=wp.int32, device=DEVICE) - graphed(values) - # the non-commuting steps only give these values in order: 1 * 2 + 10 = 12 -> 36, then 36 * 2 + 10 = 82 -> 246 + with caplog.at_level(logging.WARNING, logger="isaaclab.utils.warp.capture"): + graphed(values) + # only the plain run reached the device: 1 * 2 + 10 = 12 -> 36 assert _read(values) == [36] graphed(values) - assert (_read(values), between.calls, before.calls, after.calls, _num_graphs(graphed)) == ([246], 2, 1, 1, 2) + # 36 * 2 + 10 = 82 -> 246; the abandoned recording ran the Python of `before` once more + assert (_read(values), before.calls, between.calls, after.calls, _num_graphs(graphed)) == ([246], 3, 2, 2, 0) + assert [record.getMessage() for record in caplog.records] == [ + "'test_an_eager_call_abandons_the_recording_and_the_callable_runs_plainly..body' calls" + " '_Affine', which cannot be recorded, so it runs without a CUDA graph." + ] -def test_an_eager_call_adds_a_call_that_every_replay_runs_right_before_it(): - """Work an eager call does only while recording, such as consuming a flag a recorded write set on the host, repeats - on every replay right before the eager call.""" - before, added, after = _Affine(2, 0), _Affine(1, 10), _Affine(3, 0) - added_outside_a_recording = [] - - def eager_call(values: wp.array): - # on replays no recording runs, so the call is not added again - if not repeat_before_eager_call(lambda: added(values)): - added_outside_a_recording.append(True) - after(values) +def test_an_eager_call_abandons_the_recording_through_an_exception_handler(): + """The code a recording calls cannot catch the abandonment by mistake.""" + fn = _Affine(1, 10) def body(values: wp.array): - before(values) - eager(eager_call, values) + try: + eager(fn, values) + except Exception: # noqa: BLE001 + pytest.fail("the abandonment must pass an `except Exception` handler") graphed = GraphedCallable(body, DEVICE) - values = wp.ones(1, dtype=wp.int32, device=DEVICE) - graphed(values) - # the recording ran only the eager call: 1 * 2 = 2 -> 6 - assert _read(values) == [6] + values = wp.zeros(1, dtype=wp.int32, device=DEVICE) graphed(values) - # the replay adds 10 between the recorded scale and the eager call: (6 * 2 + 10) * 3 = 66 - assert (_read(values), added.calls, len(added_outside_a_recording)) == ([66], 1, 1) - assert not repeat_before_eager_call(lambda: None), "outside a recording nothing is added" + assert (_read(values), fn.calls, _num_graphs(graphed)) == ([10], 1, 0) -def test_eager_call_first_runs_before_the_recorded_work(): - """A callable making its eager call first runs it before its recorded work, also when it replays the recording.""" - eager_fn, first, second = _Affine(1, 10), _Affine(2, 0), _Affine(3, 0) +def test_a_callable_that_ran_plainly_records_again_after_an_invalidation(): + """A term change can remove the eager call, so an invalidation lets the callable record again.""" + fn, eager_fn = _Affine(2, 0), _Affine(1, 10) + uses_eager = [True] - def body(values: wp.array) -> wp.array: - eager(eager_fn, values) - first(values) - return second(values) + def body(values: wp.array): + fn(values) + if uses_eager[0]: + eager(eager_fn, values) graphed = GraphedCallable(body, DEVICE) values = wp.ones(1, dtype=wp.int32, device=DEVICE) - graphed(values) - graphed(values) - - assert _read(values) == [((1 + 10) * 6 + 10) * 6] + graphed(values) # abandoned, then plain: 1 * 2 + 10 = 12 + uses_eager[0] = False + GraphedCallable.invalidate() + graphed(values) # records: 24 + graphed(values) # replays: 48 + assert (_read(values), fn.calls, _num_graphs(graphed)) == ([48], 3, 1) -def test_eager_call_of_a_nested_callable_splits_the_enclosing_recording(): +def test_an_eager_call_of_a_nested_callable_makes_both_run_plainly(): eager_fn, inner_fn, outer_fn = _Affine(1, 10), _Affine(2, 0), _Affine(3, 0) nested = GraphedCallable(lambda values: (eager(eager_fn, values), inner_fn(values)), DEVICE) outer = GraphedCallable(lambda values: (outer_fn(values), nested(values)), DEVICE) @@ -223,9 +221,9 @@ def test_eager_call_of_a_nested_callable_splits_the_enclosing_recording(): outer(values) outer(values) - # 1 * 3 + 10 = 13 -> 26, then 26 * 3 + 10 = 88 -> 176: the nested eager call runs between the outer graphs - assert (_read(values), eager_fn.calls, inner_fn.calls, outer_fn.calls) == ([176], 2, 1, 1) - assert (_num_graphs(outer), _num_graphs(nested)) == (2, 0) + # 1 * 3 + 10 = 13 -> 26, then 26 * 3 + 10 = 88 -> 176 + assert (_read(values), eager_fn.calls, inner_fn.calls) == ([176], 2, 2) + assert (_num_graphs(outer), _num_graphs(nested), outer._plain, nested._plain) == (0, 0, True, True) def test_eager_call_raises_inside_a_capture_no_callable_started(): @@ -253,12 +251,11 @@ def test_capturing_sees_a_cpu_capture(): def test_callable_raising_while_recording_ends_the_capture(): - """A failed recording must not leave the device capturing; the next call records again.""" - recorded, eager_fn = _Affine(2, 0), _Affine(1, 10) + """A failed recording launches nothing and must not leave the device capturing; the next call records again.""" + recorded = _Affine(2, 0) def body(values: wp.array) -> wp.array: recorded(values) - eager(eager_fn, values) if recorded.calls == 1: raise ValueError("first recording fails") return values @@ -269,9 +266,9 @@ def body(values: wp.array) -> wp.array: with pytest.raises(ValueError, match="first recording fails"): graphed(values) assert not wp.get_device(DEVICE).is_capturing + assert _read(values) == [1] graphed(values) - # the failed recording ran its first graph and the eager call: 1 * 2 + 10 = 12, then 12 * 2 + 10 = 34 - assert (_read(values), _num_graphs(graphed)) == ([34], 2) + assert (_read(values), _num_graphs(graphed)) == ([2], 1) class _ChangeRegistry: @@ -285,8 +282,8 @@ def add(self, change: int): self.changes.append(change) -def test_eager_method_repeats_host_work_on_every_replay(): - """A recorded writer's host registration runs on the recording and on each replay, after the recorded kernel.""" +def test_an_eager_method_makes_its_recorded_caller_run_plainly(): + """A writer whose host registration cannot be recorded runs plainly, so the registration happens on every call.""" registry = _ChangeRegistry() values = wp.zeros(1, dtype=wp.int32, device=DEVICE) fn = _Affine() @@ -298,7 +295,7 @@ def writer(): graphed = GraphedCallable(writer, DEVICE) for _ in range(3): graphed() - assert (registry.changes, _read(values), fn.calls) == ([7, 7, 7], [3], 1) + assert (registry.changes, _read(values), _num_graphs(graphed)) == ([7, 7, 7], [3], 0) def test_recording_settles_the_watched_backend_first(): diff --git a/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst index a65c9610ee13..4af5cad1c8ee 100644 --- a/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,2 +1,3 @@ -* Changed :class:`~isaaclab_contrib.sensors.VisuoTactileSensor` to refresh eagerly at its place on every replay of a - :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording, since its refresh renders on the host. +* Changed :class:`~isaaclab_contrib.sensors.VisuoTactileSensor` to refresh through + :func:`~isaaclab.utils.warp.capture.eager`, since its refresh renders on the host: a + :class:`~isaaclab.utils.warp.capture.GraphedCallable` that refreshes it runs without a CUDA graph. diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst index 3b73e656d306..a0fe72ea2ffd 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -3,6 +3,3 @@ :class:`~isaaclab.utils.warp.capture.GraphedCallable`: 15 of them raised while a graph recorded, and the others replayed the value of the recording step when they were current at recording. A recording now holds their update, so every replay recomputes them. -* Fixed forward kinematics after a state write recorded by :class:`~isaaclab.utils.warp.capture.GraphedCallable` - being skipped on replays when an :func:`~isaaclab.utils.warp.capture.eager` call of the same recording read body - state after the write: every replay now evaluates them right before that call. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index fee4ab5efcf1..8b6c70096876 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -343,15 +343,10 @@ def invalidate_body_state(self, env_mask: wp.array | None = None, *, consume_mas device=self.device, ) - def forward(self, force: bool = False) -> None: - """Reset solver internals and evaluate FK for the flagged worlds and articulations, then clear the flags. - - Args: - force: Whether to evaluate even when the host flags report no pending work, for a replay whose recorded - writes flagged worlds on the device only. Defaults to False. - """ + def forward(self) -> None: + """Reset solver internals and evaluate FK for the flagged worlds and articulations, then clear the flags.""" self.notify_model_changes() - if not (force or self.kinematics_dirty or self.transforms_may_change_on_graph_replay): + if not (self.kinematics_dirty or self.transforms_may_change_on_graph_replay): return if self.solver_ops is None: raise RuntimeError("Newton state was authored before the solver was initialized (init_solver).") diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index 0aca54352e4e..94f33e96f54c 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -27,7 +27,6 @@ from isaaclab.utils.string import resolve_matching_names from isaaclab.utils.timer import Timer from isaaclab.utils.version import has_kit -from isaaclab.utils.warp.capture import repeat_before_eager_call from isaaclab_newton.physics.newton_backend_cfg import NewtonBackendCfg from isaaclab_newton.physics.newton_builder_cfg import NewtonBuilderCfg @@ -166,23 +165,9 @@ def _close_backend(self, *, dispatch_stop: bool = True) -> None: SimulationContext.instance().close_backend(backend) def forward(self) -> None: - """Update articulation kinematics without stepping physics; see :meth:`NewtonBackend.forward`. - - An :func:`~isaaclab.utils.warp.capture.eager` call of a recording that consumes pending FK here clears the host - flag the recorded write set, and a replay, whose write sets no host flag, would skip it: every replay then - evaluates FK right before that eager call. - """ - backend = self.backend - if backend is None: - return - if backend.kinematics_dirty and not backend.device.is_capturing: - repeat_before_eager_call(self._forward_on_replay) - backend.forward() - - def _forward_on_replay(self) -> None: - """Evaluate FK for the worlds the replayed writes flagged on the device.""" + """Update articulation kinematics without stepping physics; see :meth:`NewtonBackend.forward`.""" if self.backend is not None: - self.backend.forward(force=True) + self.backend.forward() def video_capture_backend(self) -> str: """Newton GL headless perspective video capture.""" diff --git a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py index 58c699cfc0d7..7c69f037aa3c 100644 --- a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py +++ b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py @@ -27,7 +27,7 @@ from isaaclab.sim import SimulationCfg, build_simulation_context from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR -from isaaclab.utils.warp.capture import GraphedCallable, eager +from isaaclab.utils.warp.capture import GraphedCallable def _generate_single_joint_articulations(num_articulations: int, device: str) -> Articulation: @@ -190,7 +190,7 @@ def reset_env_0(): body_q = wp.to_torch(backend.state_0.body_q).clone() # the same write made eagerly, resolved by the forward boundary articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) - backend.forward(force=True) + backend.forward() wp.synchronize_device(device) torch.testing.assert_close(body_q, wp.to_torch(backend.state_0.body_q), msg=f"offset {offset}") assert bool(backend.graphs) == use_cuda_graph @@ -236,48 +236,3 @@ def read_body_poses(): GraphedCallable.enabled = enabled reset.reset() read.reset() - - -@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_an_eager_read_after_a_recorded_write_sees_its_forward_kinematics_on_every_replay(device): - """An eager call that reads body poses after a recorded joint write consumes the write's pending FK while - recording; every replay still evaluates FK for the replayed write before that call, so it reads the new poses.""" - sim_cfg = SimulationCfg( - dt=1 / 120, - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg(njmax=20, nconmax=20, integrator="implicitfast"), - num_substeps=1, - use_cuda_graph=False, - ), - ) - with build_simulation_context(sim_cfg=sim_cfg, device=device) as sim: - sim._app_control_on_stop_handle = None - articulation = _generate_single_joint_articulations(num_articulations=2, device=device) - sim.reset() - env_mask = wp.array([True, False], dtype=wp.bool, device=device) - default_joint_pos = articulation.data.default_joint_pos.torch.clone() - joint_pos = wp.from_torch(default_joint_pos.clone()) - reads: list[torch.Tensor] = [] - - def read_body_poses(): - reads.append(articulation.data.body_link_pose_w.torch.clone()) - - def reset_env_0(): - articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) - eager(read_body_poses) - - reset = GraphedCallable(reset_env_0, device) - enabled, GraphedCallable.enabled = GraphedCallable.enabled, True - try: - for offset in (0.25, 0.5, 1.0): # the first call records, the others replay - wp.to_torch(joint_pos).copy_(default_joint_pos + offset) - reset() - wp.synchronize_device(device) - # the same write and read without a recording - articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) - expected = articulation.data.body_link_pose_w.torch.clone() - torch.testing.assert_close(reads[-1], expected, msg=f"offset {offset}") - assert not torch.allclose(reads[0][0], reads[-1][0]), "the joint write must move env 0's bodies" - finally: - GraphedCallable.enabled = enabled - reset.reset() diff --git a/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst index 535f93b7b261..f2976f8d4988 100644 --- a/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -2,4 +2,4 @@ graph that :class:`~isaaclab.utils.warp.capture.GraphedCallable` recorded while they were current. A recording now holds their update, so every replay recomputes them. The accelerations taken by finite differencing, which ``update`` advances once per physics step, are read as they are. The OVPhysX sensors read through host calls, so - each sensor refresh runs eagerly at its place on every replay. + a recorded call that refreshes one runs without a CUDA graph. diff --git a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst index fbf537f48f12..024cbcd7c84d 100644 --- a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -4,4 +4,4 @@ :meth:`~isaaclab_physx.assets.ArticulationData.update` advances once per physics step, and the body COM poses, masses and inertias, which PhysX serves from CPU-only views, are read as they are. * Fixed the PhysX sensors raising inside a :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording: their - PhysX tensor reads cannot be recorded, so each sensor refresh runs eagerly at its place on every replay. + PhysX tensor reads cannot be recorded, so a recorded call that refreshes one runs without a CUDA graph. From cf463a5f4dfd69430036b07b2642f238b48a2a4e Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 01:45:14 -0800 Subject: [PATCH 13/30] Raise on torch work and host synchronizations while a graph records While a GraphedCallable recording captures its graph, a torch dispatch guard raises on every torch operation on the recording's device that is not a view, and torch runs in sync debug mode error. GraphedCallable names the call for these errors and for CUDA's capture errors. The guard and the sync debug mode are restored when the graph ends, also when the recording raises or is abandoned. Ported from the recording guard of jichuanh/warp-capture-detection (decision 62a). --- .../jichuanh-warp-recording-utils.added.rst | 4 + .../isaaclab/isaaclab/utils/warp/capture.py | 95 ++++++++++++++++++- .../isaaclab/test/utils/warp/test_capture.py | 63 ++++++++++++ .../test/utils/warp/test_capture_guard.py | 56 +++++++++++ .../test/utils/warp/test_capture_kit.py | 32 +++++++ 5 files changed, 247 insertions(+), 3 deletions(-) create mode 100644 source/isaaclab/test/utils/warp/test_capture_guard.py create mode 100644 source/isaaclab/test/utils/warp/test_capture_kit.py diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst index 8b34d1ed7e42..846a9bf618bd 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst @@ -9,3 +9,7 @@ graph capture a buffer's :attr:`~isaaclab.utils.buffers.TimestampedBuffer.timestamp` now reads as stale and an update does not mark it fresh, so a lazily cached value read in a capture is recomputed on every replay, and the first read after an abandoned capture recomputes it; ``update_in_graph=False`` keeps the plain timestamp rule. +* Added checks to :class:`~isaaclab.utils.warp.capture.GraphedCallable` recordings, with and without Kit: a torch + operation on the recording's device that is not a view, or a host synchronization, while the graph records raises a + :class:`RuntimeError` naming the recorded call and the operation, since a replay would skip it or keep the value it + read. The checks end with the graph, also when the recording raises or is abandoned. diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index e2aacc1a8f90..6b59bd89a411 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -17,8 +17,10 @@ from typing import TYPE_CHECKING, Any, ClassVar import torch +import torch.utils._pytree as _pytree import warp as wp import warp._src.context as _warp_context +from torch.utils._python_dispatch import TorchDispatchMode from ..version import has_kit @@ -224,9 +226,19 @@ def _record(self, args: tuple, kwargs: dict[str, Any]) -> tuple[wp.Graph, Any]: Raises: _EagerCall: If the callable makes an :func:`eager` call; the recording launched nothing. + RuntimeError: If the callable runs work the graph cannot hold while it records (see :class:`_Recording`). """ - with _record_calls(self._device) as recording: - result = self._fn(*args, **kwargs) + try: + with _record_calls(self._device) as recording: + result = self._fn(*args, **kwargs) + except RuntimeError as exc: + if not any(text in str(exc) for text in _UNRECORDABLE_ERRORS): + raise + raise RuntimeError( + f"'{_name(self._fn)}' synchronizes the host with the device or runs a torch CUDA operation outside the" + " graph while it records, so a replay would keep the value it read or skip the operation. Run the" + f" function through eager() or mark it with @eager_method. ({exc})" + ) from exc return recording.graph, result @@ -255,8 +267,65 @@ def _record_calls(device: wp.Device): GraphedCallable._recording = enclosing +_UNRECORDABLE_ERRORS = ( + # torch, in sync debug mode "error", on a host synchronization + "called a synchronizing CUDA operation", + # CUDA, on work for the legacy default stream, torch's current stream, while a blocking Warp stream captures + "operation would make the legacy stream depend on a capturing blocking stream", + # CUDA, on a synchronization of the capturing stream + "operation not permitted when stream is capturing", + # the torch operation guard of a recording (see _TorchOpGuard) + "runs outside the graph a recording captures", +) +"""Texts of the errors a call raises for work a graph cannot hold while it records.""" + + +class _TorchOpGuard(TorchDispatchMode): + """Raise on a torch operation on a device while a graph records there. + + Torch runs on its own stream, so the operation would run once at recording time and never in a replay. Views and + other operations whose outputs alias their inputs launch no work and pass (``OpOverload.is_view``): wrapping Warp + memory with :func:`warp.to_torch` (``aten.lift_fresh``), slicing, reshaping. + """ + + def __init__(self, device: torch.device): + super().__init__() + self._device = device + + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + kwargs = kwargs or {} + if not func.is_view and self._touches_device(args, kwargs): + raise RuntimeError( + f"The torch operation {func} runs outside the graph a recording captures, once at recording time." + ) + return func(*args, **kwargs) + + def _touches_device(self, args: tuple, kwargs: dict) -> bool: + for leaf in _pytree.tree_leaves((args, kwargs)): + device = leaf.device if isinstance(leaf, torch.Tensor) else leaf if isinstance(leaf, torch.device) else None + # a device without an index, such as torch.device("cuda"), is the current one of its type + if device is not None and device.type == self._device.type and device.index in (None, self._device.index): + return True + return False + + class _Recording: - """One recording: a CUDA graph, launched when it ends since the recording is the first run of the callable.""" + """One recording: a CUDA graph, launched when it ends since the recording is the first run of the callable. + + Work the graph cannot hold raises while it records, and :meth:`GraphedCallable._record` names the call: + + * Torch runs on its current stream, which the recording does not change, so a torch operation on the recording's + device would run once at recording time and never in a replay. While the graph records, a torch dispatch guard + raises on every such operation that is not a view (see :class:`_TorchOpGuard`), with and without Kit. Without + Kit, CUDA would reject it anyway (``cudaErrorStreamCaptureImplicit``: Warp captures a blocking stream, torch runs + on the legacy one); with Kit, Warp captures a nonblocking stream in relaxed mode, which CUDA lets torch work + bypass silently. + * Torch runs in sync debug mode ``"error"`` (:func:`torch.cuda.set_sync_debug_mode`), so a host synchronization + on any stream raises. + * Warp raises on its own synchronizations during a capture. + + The guard and the previous sync debug mode are restored when the graph ends, also when the recording is abandoned. + """ def __init__(self, device: wp.Device): # the graph is captured on the capture stream and launched on the stream the callable runs on @@ -269,15 +338,21 @@ def __init__(self, device: wp.Device): self.mode = wp.CaptureMode.RELAXED self.graph: wp.Graph | None = None self.capturing = False + # the sync debug mode outside the graph + self._sync_debug_mode = torch.cuda.get_sync_debug_mode() + self._torch_device = torch.device(wp.device_to_torch(device)) + self._guard: _TorchOpGuard | None = None def begin(self) -> None: """Start the graph.""" wp.capture_begin(stream=self.capture_stream, capture_mode=self.mode) self.capturing = True + self._enter_guards() def end(self) -> None: """End the graph and launch it.""" self.capturing = False + self._release() self.graph = wp.capture_end(stream=self.capture_stream) wp.capture_launch(self.graph, stream=self.stream) @@ -285,9 +360,23 @@ def abort(self) -> None: """End the graph without launching it, after the callable raised or made an :func:`eager` call.""" if self.capturing: self.capturing = False + self._release() with contextlib.suppress(Exception): wp.capture_end(stream=self.capture_stream) + def _enter_guards(self) -> None: + """Raise on torch work and host synchronizations while the graph records.""" + torch.cuda.set_sync_debug_mode("error") + self._guard = _TorchOpGuard(self._torch_device) + self._guard.__enter__() + + def _release(self) -> None: + """Leave the torch guards of the graph that ends.""" + if self._guard is not None: + guard, self._guard = self._guard, None + guard.__exit__(None, None, None) + torch.cuda.set_sync_debug_mode(self._sync_debug_mode) + @contextlib.contextmanager def _paused_gc(): diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py index 7cd032196237..92408ce838fa 100644 --- a/source/isaaclab/test/utils/warp/test_capture.py +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -11,6 +11,7 @@ from types import SimpleNamespace import pytest +import torch import warp as wp from isaaclab.utils.warp.capture import ( @@ -322,3 +323,65 @@ def forward(self): finally: GraphedCallable.unwatch() assert _read(values) == [1] + + +def _synchronizing_call(values: torch.Tensor) -> float: + """A torch host synchronization, whose value a replay would keep.""" + return values.sum().item() + + +def test_a_host_synchronization_while_recording_raises_naming_the_call(): + """A torch operation that synchronizes the host inside a recorded graph raises instead of baking its value.""" + values = torch.ones(4, device=DEVICE) + previous = torch.cuda.get_sync_debug_mode() + graphed = GraphedCallable(lambda: _synchronizing_call(values), DEVICE) + with pytest.raises(RuntimeError, match="' synchronizes the host with the device or runs a torch CUDA"): + graphed() + assert torch.cuda.get_sync_debug_mode() == previous, "the sync debug mode must be restored after a raise" + + +def test_a_host_synchronization_in_an_eager_call_runs_plainly_in_the_previous_mode(): + values = torch.ones(4, device=DEVICE) + previous = torch.cuda.get_sync_debug_mode() + modes = [] + + def body(): + modes.append(torch.cuda.get_sync_debug_mode()) + return eager(_synchronizing_call, values) + + graphed = GraphedCallable(body, DEVICE) + assert graphed() == 4.0 + assert graphed() == 4.0 + # the abandoned recording ran in mode "error" (2), the plain runs in the previous mode + assert modes == [2, previous, previous] + assert torch.cuda.get_sync_debug_mode() == previous + + +def test_the_sync_debug_mode_is_restored_when_the_recording_raises(): + previous = torch.cuda.get_sync_debug_mode() + + def body(): + raise ValueError("term failed") + + with pytest.raises(ValueError, match="term failed"): + GraphedCallable(body, DEVICE)() + assert torch.cuda.get_sync_debug_mode() == previous + + +def test_a_torch_operation_while_recording_raises_naming_the_call_and_the_operation(): + """A torch operation on the recording's device would run once at recording time; the guard raises, with and + without Kit, before CUDA would.""" + values = torch.ones(4, device=DEVICE) + graphed = GraphedCallable(lambda: values.add_(1), DEVICE) + with pytest.raises(RuntimeError, match=r"(?s)' .*while it records.*aten\.add_"): + graphed() + # the operation did not run, and the guard is released after the raise + assert values.add(1).sum().item() == 8.0 + + +def test_a_torch_operation_in_an_eager_call_runs(): + values = torch.ones(4, device=DEVICE) + graphed = GraphedCallable(lambda: eager(values.add_, 1), DEVICE) + graphed() + graphed() + assert values.sum().item() == 12.0 diff --git a/source/isaaclab/test/utils/warp/test_capture_guard.py b/source/isaaclab/test/utils/warp/test_capture_guard.py new file mode 100644 index 000000000000..329fc7111037 --- /dev/null +++ b/source/isaaclab/test/utils/warp/test_capture_guard.py @@ -0,0 +1,56 @@ +# 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 + +# pyright: reportPrivateUsage=none + +"""The torch operation guard a recording holds while a graph records (see :class:`_TorchOpGuard`).""" + +import pytest +import torch +import warp as wp + +from isaaclab.utils.warp import ProxyArray +from isaaclab.utils.warp.capture import _TorchOpGuard + +pytestmark = pytest.mark.unit + +CPU = torch.device("cpu") + + +@pytest.mark.parametrize( + "operation", + [ + lambda t: t + 1, + lambda t: t.sum(), + lambda t: t[0].item(), + lambda t: t.zero_(), + lambda t: torch.zeros(3, device="cpu"), + lambda t: t.clone(), + ], + ids=["add", "sum", "item", "zero_", "zeros", "clone"], +) +def test_the_guard_raises_on_work_on_its_device(operation): + t = torch.ones(4) + with pytest.raises(RuntimeError, match="runs outside the graph a recording captures"), _TorchOpGuard(CPU): + operation(t) + + +def test_the_guard_passes_views_and_warp_memory(): + """Views launch no work; wrapping Warp memory is a view of it (``aten.lift_fresh``).""" + t = torch.ones(4, 2) + array = wp.zeros(4, dtype=wp.float32, device="cpu") + proxy = ProxyArray(wp.zeros(4, dtype=wp.vec3f, device="cpu")) + with _TorchOpGuard(CPU): + t.view(8) + t[1:] + t.reshape(2, 4) + t.t() + wp.to_torch(array) + proxy.torch[0:2] + + +def test_the_guard_passes_work_on_another_device(): + with _TorchOpGuard(torch.device("cuda", 0)): + torch.ones(4).sum() diff --git a/source/isaaclab/test/utils/warp/test_capture_kit.py b/source/isaaclab/test/utils/warp/test_capture_kit.py new file mode 100644 index 000000000000..573f4af51d8f --- /dev/null +++ b/source/isaaclab/test/utils/warp/test_capture_kit.py @@ -0,0 +1,32 @@ +# 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 + +"""Under Kit, a recording captures a nonblocking stream in relaxed mode, where CUDA lets torch work on the legacy stream +run once at recording time; the recording's torch guard must still raise.""" + +from isaaclab.test.utils import launch_test_simulation + +launch_test_simulation() + +import pytest # noqa: E402 +import torch # noqa: E402 +import warp as wp # noqa: E402 + +from isaaclab.utils.version import has_kit # noqa: E402 +from isaaclab.utils.warp.capture import GraphedCallable # noqa: E402 + +pytestmark = pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA device required") + +DEVICE = "cuda:0" + + +def test_a_torch_operation_while_recording_under_kit_raises(monkeypatch): + monkeypatch.setattr(GraphedCallable, "enabled", True) + assert has_kit(), "this test checks the relaxed capture Kit uses" + values = torch.ones(4, device=DEVICE) + graphed = GraphedCallable(lambda: values.add_(1), DEVICE) + with pytest.raises(RuntimeError, match=r"while it records.*aten\.add_"): + graphed() + assert values.sum().item() == 4.0, "the operation must not have run" From 8e44a498090ebcee4d919ba0917fac2ded8160cf Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 01:50:23 -0800 Subject: [PATCH 14/30] Keep one recorded Warp launch per call site outside the graphs _WarpLaunchCache keys a recorded launch by its call site: a changed kernel argument or launch dimension is set on the cached wp.Launch in place, a changed kernel, launch option, or array/scalar argument of another operation records it again, and every cache is cleared when the physics backend rebinds or stops. The per-physics-step updates of Newton asset data and of the sensor clocks, which run outside the recorded parts of the step, launch through it (decision 70a, 01:16 spec). --- .../jichuanh-warp-recording-utils.changed.rst | 4 + .../isaaclab/isaaclab/sensors/sensor_base.py | 10 +- .../isaaclab/isaaclab/utils/warp/capture.py | 11 +- .../isaaclab/utils/warp/launch_cache.py | 103 ++++++++++++++++-- .../test/utils/warp/test_launch_cache.py | 98 +++++++++++++++++ .../jichuanh-warp-recording-utils.changed.rst | 2 + .../assets/articulation/articulation_data.py | 11 +- .../assets/rigid_object/rigid_object_data.py | 6 +- .../rigid_object_collection_data.py | 6 +- 9 files changed, 226 insertions(+), 25 deletions(-) create mode 100644 source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst new file mode 100644 index 000000000000..122b3ddc1cd8 --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -0,0 +1,4 @@ +* Changed the cached Warp launches of asset data, sensors and managers to keep one recorded launch per call site: an + argument or launch dimension that changes is set on that launch in place instead of recording a new one, and the + Warp frontend clears every recorded launch when the physics backend rebinds its buffers or stops. The sensor clock + update of each physics step replays a recorded launch. diff --git a/source/isaaclab/isaaclab/sensors/sensor_base.py b/source/isaaclab/isaaclab/sensors/sensor_base.py index 006e9f7a2fad..e966272f0bfb 100644 --- a/source/isaaclab/isaaclab/sensors/sensor_base.py +++ b/source/isaaclab/isaaclab/sensors/sensor_base.py @@ -31,6 +31,7 @@ from ..sim.utils.queries import get_first_matching_ancestor_prim from ..sim.utils.transforms import resolve_prim_pose from ..utils.warp.capture import capturing +from ..utils.warp.launch_cache import _WarpLaunchCache from ..utils.warp.memory import resolve_1d_mask from .kernels import invalidate_buffers_kernel, reset_envs_kernel, update_outdated_envs_kernel, update_timestamp_kernel @@ -227,8 +228,11 @@ def update(self, dt: float, force_recompute: bool = False): if not self._is_initialized: return self._data_dirty |= dt > 0.0 - # Update the timestamp for the sensors - wp.launch( + # Update the timestamp for the sensors, through a recorded launch: the update runs once per physics step + # outside the recorded parts of the step + self._launch_cache.launch( + "update_timestamp", + wp.launch, update_timestamp_kernel, dim=self._num_envs, inputs=[ @@ -239,7 +243,6 @@ def update(self, dt: float, force_recompute: bool = False): dt, self.cfg.update_period - 1e-6, ], - device=self._device, ) # Update the buffers; debug visualization refreshes lazily from its callback. if force_recompute: @@ -466,6 +469,7 @@ def _create_timing_buffers(self) -> None: # A negative timestamp means no backend sample has been read since initialization/reset. self._timestamp_last_update = wp.full(self._num_envs, -1.0, dtype=wp.float32, device=self._device) self._elapsed_since_update = wp.zeros(self._num_envs, dtype=wp.float64, device=self._device) + self._launch_cache = _WarpLaunchCache(self._device) def _invalidate_buffers(self, env_mask: wp.array | None = None) -> None: """Invalidate selected results without advancing sampling clocks; None selects all environments.""" diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index 6b59bd89a411..fa5e1c088a0e 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -23,6 +23,7 @@ from torch.utils._python_dispatch import TorchDispatchMode from ..version import has_kit +from .launch_cache import _WarpLaunchCache if TYPE_CHECKING: from ...physics import PhysicsManager @@ -191,9 +192,9 @@ def reset(self) -> None: @classmethod def watch(cls, backend_manager: PhysicsManager) -> None: - """Record every callable again after the physics backend rebinds its buffers or stops, and settle the backend - before each recording: work it queued before (model changes, kinematics) runs then, once, so a recording holds - only the work of its own calls. + """Record every callable and every cached launch again after the physics backend rebinds its buffers or stops, + and settle the backend before each recording: work it queued before (model changes, kinematics) runs then, + once, so a recording holds only the work of its own calls. Args: backend_manager: Physics manager that dispatches the lifecycle events. @@ -204,8 +205,10 @@ def watch(cls, backend_manager: PhysicsManager) -> None: cls.unwatch() cls._settle = backend_manager.forward cls._callback_handles = [ - backend_manager.register_callback(cls.invalidate, event) + backend_manager.register_callback(callback, event) for event in (PhysicsEvent.PHYSICS_READY, PhysicsEvent.STOP) + # the recorded launches of the code outside the graphs read the same buffers + for callback in (cls.invalidate, _WarpLaunchCache.clear_all) ] @classmethod diff --git a/source/isaaclab/isaaclab/utils/warp/launch_cache.py b/source/isaaclab/isaaclab/utils/warp/launch_cache.py index 785fb683979c..62fb7c178316 100644 --- a/source/isaaclab/isaaclab/utils/warp/launch_cache.py +++ b/source/isaaclab/isaaclab/utils/warp/launch_cache.py @@ -3,33 +3,85 @@ # # SPDX-License-Identifier: BSD-3-Clause +import weakref from collections.abc import Callable +from typing import Any, ClassVar import warp as wp +_LAUNCH_ARGUMENTS = ("kernel", "dim", "inputs", "outputs") +"""The arguments of ``wp.launch`` a cached launch compares one by one; any other argument is a launch option.""" + +_UNKNOWN = object() +"""Key of an argument whose value cannot be compared, such as a Warp struct: it is set on every launch.""" + class _WarpLaunchCache: - """Cache stable eager-CUDA commands returned by a Warp launch operation. + """Recorded Warp launches of code that runs outside a CUDA graph, one per call site. + + Each call site names itself with ``key``, so the cache holds at most one :class:`warp.Launch` per call site. A + launch compares its arguments with those of the call site's cached launch: + + * Through ``wp.launch``, a changed kernel argument is set on the cached launch in place, and so is a changed launch + dimension. A kernel argument that cannot be compared, such as a Warp struct, is set on every launch. A changed + kernel or launch option records the call site's launch again. + * Through any other operation, which must accept ``device`` and ``record_cmd`` like ``wp.launch``, a changed array + or scalar argument records the call site's launch again; other arguments must stay valid until the key is + cleared. - The operation must accept ``device`` and ``record_cmd`` like ``wp.launch``. - Its arguments and array storage must remain stable until the key is cleared. - CPU execution and graph capture invoke the operation directly. + CPU execution and graph capture invoke the operation directly. :meth:`clear_all` empties every cache, which the + recording of the environment step does when the physics backend rebinds its buffers or stops (see + :meth:`~isaaclab.utils.warp.capture.GraphedCallable.watch`). """ + _instances: ClassVar[weakref.WeakSet] = weakref.WeakSet() + def __init__(self, device: str): self._device = wp.get_device(device) - self._commands: dict[object, wp.Launch] = {} + self._commands: dict[object, tuple[wp.Launch, tuple]] = {} + _WarpLaunchCache._instances.add(self) def launch(self, key: object, operation: Callable, *args, **kwargs) -> None: + """Launch through the call site's cached launch, recording it on the first call. + + Args: + key: Name of the call site. + operation: ``wp.launch``, or an operation that accepts ``device`` and ``record_cmd`` like it. + *args: Positional arguments of the operation. + **kwargs: Keyword arguments of the operation, without ``device``. + """ if not self._device.is_cuda or self._device.is_capturing: operation(*args, **kwargs, device=self._device) return - command = self._commands.get(key) - if command is None: - command = operation(*args, **kwargs, device=self._device, record_cmd=True) - if command is None: + cached = self._commands.get(key) + if operation is wp.launch and len(args) <= len(_LAUNCH_ARGUMENTS): + launch = dict(zip(_LAUNCH_ARGUMENTS, args), **kwargs) + kernel, dim = launch.pop("kernel"), launch.pop("dim") + params = [*launch.pop("inputs", ()), *launch.pop("outputs", ())] + keys = [_key(value) for value in params] + # the launch options left, such as block_dim, compared as a whole + options = tuple(sorted((name, _key(value)) for name, value in launch.items())) + if cached is not None: + command, (cached_kernel, cached_dim, cached_keys, cached_options) = cached + if cached_kernel is kernel and cached_options == options and len(cached_keys) == len(keys): + for index, (new, old) in enumerate(zip(keys, cached_keys)): + if new is _UNKNOWN or new != old: + command.set_param_at_index(index, params[index]) + if dim != cached_dim: + command.set_dim(dim) + self._commands[key] = command, (kernel, dim, keys, options) + command.launch() + return + signature = (kernel, dim, keys, options) + else: + signature = _key((args, kwargs), unknown=None) + if cached is not None and cached[1] == signature: + cached[0].launch() return - self._commands[key] = command + command = operation(*args, **kwargs, device=self._device, record_cmd=True) + if command is None: + return + self._commands[key] = command, signature command.launch() def clear(self, key: object | None = None) -> None: @@ -38,3 +90,34 @@ def clear(self, key: object | None = None) -> None: self._commands.clear() else: self._commands.pop(key, None) + + @classmethod + def clear_all(cls, payload: Any = None) -> None: + """Remove the recorded launches of every cache, so they record again on their next launch. + + Args: + payload: Event payload of a physics callback, unused. + """ + for cache in list(cls._instances): + cache.clear() + + +def _key(value: Any, unknown: Any = _UNKNOWN) -> Any: + """Key an argument by what a launch reads of it: an array by its pointer and layout, a scalar by its type and value. + + A :class:`~isaaclab.utils.warp.ProxyArray` keys as the Warp array it wraps. Lists and tuples key item by item. Any + other value keys as ``unknown``. + """ + if isinstance(value, wp.array): + return value.ptr, value.shape, value.strides, value.dtype + # True, 1 and 1.0 compare equal, so the type tells them apart + if value is None or isinstance(value, (bool, int, float, str)): + return type(value), value + if isinstance(value, (list, tuple)): + return type(value), tuple(_key(item, unknown) for item in value) + if isinstance(value, dict): + return tuple((name, _key(item, unknown)) for name, item in value.items()) + array = getattr(value, "warp", None) + if isinstance(array, wp.array): + return _key(array) + return unknown diff --git a/source/isaaclab/test/utils/warp/test_launch_cache.py b/source/isaaclab/test/utils/warp/test_launch_cache.py index a5d90d6c7cac..bbee1299dbe5 100644 --- a/source/isaaclab/test/utils/warp/test_launch_cache.py +++ b/source/isaaclab/test/utils/warp/test_launch_cache.py @@ -3,7 +3,14 @@ # # SPDX-License-Identifier: BSD-3-Clause +from types import SimpleNamespace + +import pytest +import warp as wp + import isaaclab.utils.warp.launch_cache as launch_cache +from isaaclab.test.utils import DeviceScope, test_devices +from isaaclab.utils.warp.capture import GraphedCallable from isaaclab.utils.warp.launch_cache import _WarpLaunchCache @@ -61,3 +68,94 @@ def launch(*args, **kwargs): cache.launch("empty", launch, kernel, dim=0, inputs=[], outputs=[]) cache.launch("empty", launch, kernel, dim=0, inputs=[], outputs=[]) assert len(calls) == 8 + + +def test_another_operation_records_again_when_an_array_or_scalar_argument_changes(monkeypatch): + """An operation other than ``wp.launch`` cannot take an argument in place, so the call site records it again.""" + + class Device: + is_cuda = True + is_capturing = False + + calls = [] + + def operation(values, scale, device, record_cmd=False): + calls.append((values, scale)) + return SimpleNamespace(launch=lambda: None) + + monkeypatch.setattr(launch_cache.wp, "get_device", lambda _: Device()) + cache = _WarpLaunchCache("cuda:0") + first, second = wp.zeros(2, dtype=wp.float32, device="cpu"), wp.zeros(2, dtype=wp.float32, device="cpu") + for values, scale in ((first, 1.0), (first, 1.0), (second, 1.0), (second, 2.0), (second, 2.0)): + cache.launch("site", operation, values, scale) + assert calls == [(first, 1.0), (second, 1.0), (second, 2.0)] + assert len(cache._commands) == 1 + + +def test_a_physics_rebind_or_stop_clears_every_cache(monkeypatch): + """The recording of the environment step clears the recorded launches with its own recordings.""" + + class Device: + is_cuda = True + is_capturing = False + + class BackendManager: + def __init__(self): + self.callbacks = [] + + def register_callback(self, fn, event): + self.callbacks.append(fn) + return SimpleNamespace(deregister=lambda: None) + + def forward(self): + pass + + monkeypatch.setattr(launch_cache.wp, "get_device", lambda _: Device()) + caches = [_WarpLaunchCache("cuda:0") for _ in range(2)] + for cache in caches: + cache.launch("site", lambda device, record_cmd=False: SimpleNamespace(launch=lambda: None)) + manager = BackendManager() + GraphedCallable.watch(manager) + try: + assert _WarpLaunchCache.clear_all in manager.callbacks + for callback in manager.callbacks: + callback(None) + finally: + GraphedCallable.unwatch() + assert [len(cache._commands) for cache in caches] == [0, 0] + + +@wp.kernel +def _scale_into(values: wp.array(dtype=wp.float32), scale: wp.float32, out: wp.array(dtype=wp.float32)): + i = wp.tid() + out[i] = values[i] * scale + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +def test_a_cached_launch_takes_changed_arguments_in_place(device, monkeypatch): + """A call site keeps one recorded launch: a reallocated array, a changed scalar and a changed dimension are set on + it in place, without recording a new launch.""" + recorded = [] + launch = wp.launch + + def counting_launch(*args, **kwargs): + if kwargs.get("record_cmd"): + recorded.append(True) + return launch(*args, **kwargs) + + monkeypatch.setattr(launch_cache.wp, "launch", counting_launch) + cache = _WarpLaunchCache(device) + out = wp.zeros(4, dtype=wp.float32, device=device) + + def scale(values: wp.array, factor: float, dim: int = 4): + cache.launch("scale", counting_launch, _scale_into, dim=dim, inputs=[values, factor], outputs=[out]) + return out.numpy().tolist() + + assert scale(wp.full(4, 1.0, dtype=wp.float32, device=device), 2.0) == [2.0] * 4 + reallocated = wp.full(4, 3.0, dtype=wp.float32, device=device) + assert scale(reallocated, 5.0) == [15.0] * 4 + assert scale(reallocated, 1.0, dim=2) == [3.0, 3.0, 15.0, 15.0] + assert (len(recorded), len(cache._commands)) == (1, 1) + _WarpLaunchCache.clear_all() + assert scale(reallocated, 2.0) == [6.0] * 4 + assert len(recorded) == 2 diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst index 22d1225b7d5a..6196c9862b4a 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,3 +1,5 @@ * Changed Newton to reset the solver and evaluate forward kinematics for the worlds flagged by state writes at the start of each physics step, inside the step's CUDA graph, instead of eagerly before every step once a write was recorded in a graph. Without flagged worlds the masked kernels do no work. +* Changed the per-physics-step update of the Newton articulation, rigid object and rigid object collection data to + replay recorded Warp launches, which costs less host time than a new launch. diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py index 7d91449edadd..507778f9fec2 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py @@ -162,7 +162,10 @@ def update(self, dt: float) -> None: # a zero step (the update at initialization) has no difference to take, so they keep their values if dt == 0.0: return - wp.launch( + # recorded launches: the update runs once per physics step outside the recorded parts of the step + self._read_launch_cache.launch( + "joint_acc", + wp.launch, articulation_kernels.get_joint_acc_from_joint_vel, dim=(self._num_instances, self._num_joints), inputs=[ @@ -173,14 +176,14 @@ def update(self, dt: float) -> None: outputs=[ self._joint_acc.data, ], - device=self.device, ) self._joint_acc.timestamp = self._sim_timestamp body_ordering = self.body_ordering - wp.launch( + self._read_launch_cache.launch( + "body_com_acc_w", + wp.launch, articulation_kernels.get_body_com_acc_from_body_com_vel_ordered, dim=(self._num_instances, self._num_bodies), - device=self.device, inputs=[ self._sim_bind_body_com_vel_w, self._previous_body_com_vel, diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py index 6485d2e63f10..bc0ef5149816 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py @@ -132,10 +132,12 @@ def update(self, dt: float) -> None: # a zero step (the update at initialization) has no difference to take, so they keep their values if dt == 0.0: return - wp.launch( + # a recorded launch: the update runs once per physics step outside the recorded parts of the step + self._read_launch_cache.launch( + "body_com_acc_w", + wp.launch, shared_kernels.derive_body_acceleration_from_body_com_velocities, dim=(self._num_instances, 1), - device=self.device, inputs=[ self._sim_bind_body_com_vel_w, dt, diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py index eb8a66d4b914..5e4c8746c622 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py @@ -136,10 +136,12 @@ def update(self, dt: float) -> None: # a zero step (the update at initialization) has no difference to take, so they keep their values if dt == 0.0: return - wp.launch( + # a recorded launch: the update runs once per physics step outside the recorded parts of the step + self._read_launch_cache.launch( + "body_com_acc_w", + wp.launch, shared_kernels.derive_body_acceleration_from_body_com_velocities, dim=(self.num_instances, self.num_bodies), - device=self.device, inputs=[ self.body_com_vel_w.warp, dt, From 08b7b713618f6049d64d2761299a5b67f3ad7ce6 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 02:07:53 -0800 Subject: [PATCH 15/30] Document the host work an abandoned recording repeats --- source/isaaclab/isaaclab/utils/warp/capture.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index fa5e1c088a0e..aecf1e9782df 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -118,7 +118,9 @@ class GraphedCallable: result of the recording call, so the callable returns buffers its owner keeps. * Calls that cannot be recorded go through :func:`eager`. A recording that meets one is abandoned without launching anything, and the callable runs plainly from then on, starting with this call; it records again after - :meth:`reset`. + :meth:`reset`. Known limitation: the host work the callable did before the :func:`eager` call, such as a Python + counter it advanced, ran once in the abandoned recording and runs again in the plain call, on that first call + only; its device work ran only in the plain call. * :attr:`enabled` turns recording off process-wide, to run every part eagerly; it is on by default. A callable on a CPU device always runs eagerly. * :attr:`generation` advances when the terms change or the physics backend rebinds its buffers or stops (see From 133c3506c318adc3bfb9e81700f45eaaf16379c6 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 14:02:03 -0800 Subject: [PATCH 16/30] Test that repeated sensor reads in a capture refresh the data once per replay Inside a capture every read records the sensor refresh, since no read can know what a replay will find outdated. The first refresh a replay runs clears the outdated environments, so the later ones update none. The Kit test now asserts this contract instead of one recorded refresh. --- source/isaaclab/test/sensors/test_sensor_base.py | 7 +++++-- .../test/sensors/test_sensor_update_schedule.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/source/isaaclab/test/sensors/test_sensor_base.py b/source/isaaclab/test/sensors/test_sensor_base.py index 8e5553fc18d9..197fa18046d0 100644 --- a/source/isaaclab/test/sensors/test_sensor_base.py +++ b/source/isaaclab/test/sensors/test_sensor_base.py @@ -312,7 +312,8 @@ def test_reset_keeps_cleared_cache_and_pending_peer_updates(create_dummy_sensor, @pytest.mark.parametrize("device", ("cuda",)) def test_repeated_data_reads_are_graph_safe(create_dummy_sensor, device): - """Test that CUDA graph capture records one backend refresh for repeated reads.""" + """Test that each read in a CUDA graph capture records a backend refresh, and that a replay refreshes the data + once: the first refresh clears the outdated environments the later ones would update.""" sensor_cfg, sim, dt = create_dummy_sensor sensor = DummySensor(cfg=sensor_cfg) sim.step() @@ -328,8 +329,10 @@ def test_repeated_data_reads_are_graph_safe(create_dummy_sensor, device): _ = sensor.data _ = sensor.data - assert sensor.backend_update_count == backend_update_count + 1 + assert sensor.backend_update_count == backend_update_count + 2 + count = sensor._data.count.clone() wp.capture_launch(capture.graph) + assert torch.equal(sensor._data.count, count + 1) @pytest.mark.parametrize("device", ("cpu",)) diff --git a/source/isaaclab/test/sensors/test_sensor_update_schedule.py b/source/isaaclab/test/sensors/test_sensor_update_schedule.py index fab70e551633..a2b21eeee5d9 100644 --- a/source/isaaclab/test/sensors/test_sensor_update_schedule.py +++ b/source/isaaclab/test/sensors/test_sensor_update_schedule.py @@ -217,6 +217,21 @@ def test_captured_read_refreshes_on_every_replay(device): assert sensor.device_refreshes.numpy().tolist() == [4, 4] +@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) +def test_repeated_reads_in_a_capture_refresh_the_data_once_per_replay(device): + """Each read in a capture records the refresh, since no read can know what a replay finds outdated; the first + refresh a replay runs clears the outdated environments, so the later ones update none.""" + sensor = _DeviceRefreshSensor(device) + sensor.update(0.005) + _ = sensor.data + graph = _capture(device, lambda: (sensor.data, sensor.data)) + for _ in range(3): + sensor.update(0.005) + wp.capture_launch(graph) + # one eager refresh, then one per replay + assert sensor.device_refreshes.numpy().tolist() == [4, 4] + + @pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) def test_an_abandoned_capture_leaves_the_sensor_due_for_the_next_read(device): """A capture that reads the sensor and is abandoned launches no refresh, so the next plain read refreshes.""" From 03d29aacd756f472db9f9dd807d371e499dd5c81 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 15:36:29 -0800 Subject: [PATCH 17/30] Mark work that cannot be recorded only with eager_method The inline eager() call is removed: a method that cannot be recorded is marked with @eager_method, whose wrapper abandons a GraphedCallable recording, raises inside a capture no GraphedCallable started, and runs plainly otherwise. The Newton actuator adapter, which decides at run time whether an actuator state can be recorded, resets an unrecordable state through a method marked with it. --- .../jichuanh-warp-recording-utils.added.rst | 7 +- .../isaaclab/actuators/newton/adapter.py | 12 ++- .../isaaclab/isaaclab/utils/warp/capture.py | 75 ++++++++----------- .../isaaclab/test/utils/warp/test_capture.py | 49 ++++++++---- .../jichuanh-warp-recording-utils.changed.rst | 4 +- 5 files changed, 79 insertions(+), 68 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst index 846a9bf618bd..48457cc55409 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst @@ -1,10 +1,9 @@ * Added :mod:`isaaclab.utils.warp.capture`. :class:`~isaaclab.utils.warp.capture.GraphedCallable` records a call as a CUDA graph on its first run with a given argument layout and replays it after; it records again for another layout or when the physics backend rebinds its buffers. -* Added :func:`~isaaclab.utils.warp.capture.eager` and :func:`~isaaclab.utils.warp.capture.eager_method` for calls - that cannot be recorded. A :class:`~isaaclab.utils.warp.capture.GraphedCallable` that makes one while it records - abandons the recording without launching it and runs without a CUDA graph from then on, logging a warning that - names both calls. +* Added :func:`~isaaclab.utils.warp.capture.eager_method` to mark methods that cannot be recorded. A + :class:`~isaaclab.utils.warp.capture.GraphedCallable` that calls one while it records abandons the recording + without launching it and runs without a CUDA graph from then on, logging a warning that names both calls. * Added the ``update_in_graph`` argument to :class:`~isaaclab.utils.buffers.TimestampedBuffer`. Inside any CUDA graph capture a buffer's :attr:`~isaaclab.utils.buffers.TimestampedBuffer.timestamp` now reads as stale and an update does not mark it fresh, so a lazily cached value read in a capture is recomputed on every replay, and the diff --git a/source/isaaclab/isaaclab/actuators/newton/adapter.py b/source/isaaclab/isaaclab/actuators/newton/adapter.py index fdc25b98d595..58c3d7389b40 100644 --- a/source/isaaclab/isaaclab/actuators/newton/adapter.py +++ b/source/isaaclab/isaaclab/actuators/newton/adapter.py @@ -32,7 +32,7 @@ from newton.selection import ArticulationView from ...utils import index_fill_ -from ...utils.warp.capture import eager +from ...utils.warp.capture import eager_method from .kernels import ( build_implicit_dof_mask, build_per_dof_env_mask_kernel, @@ -333,12 +333,18 @@ def _reset_states(self, env_mask: wp.array) -> None: @staticmethod def _reset_state_pair(act: Actuator, sa: Any, sb: Any, per_dof_mask: wp.array | None) -> None: """Reset both state buffers of an actuator; a torch state, such as a neural network drive's, cannot be - recorded, so a recording repeats its reset eagerly.""" + recorded, so its reset goes through :meth:`_reset_unrecordable_state`.""" for state in (sa, sb): if act.is_graphable(): state.reset(per_dof_mask) else: - eager(state.reset, per_dof_mask) + NewtonActuatorAdapter._reset_unrecordable_state(state, per_dof_mask) + + @staticmethod + @eager_method + def _reset_unrecordable_state(state: Any, per_dof_mask: wp.array | None) -> None: + """Reset an actuator state that cannot be recorded, so a recorded call that resets it runs without a graph.""" + state.reset(per_dof_mask) # --------------------------------------------------------------------------- diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index aecf1e9782df..7e003293b5fa 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -4,7 +4,8 @@ # SPDX-License-Identifier: BSD-3-Clause """CUDA graph recording of the Warp frontend: :class:`GraphedCallable` records a call as a CUDA graph and replays it. -A call that cannot be recorded goes through :func:`eager`; a recorded call that makes one runs plainly instead. +A method that cannot be recorded is marked with :func:`eager_method`; a recorded call that calls one runs plainly +instead. """ from __future__ import annotations @@ -49,36 +50,9 @@ def capture_in_progress() -> bool: return runtime is not None and bool(runtime.captures or runtime._apic_capture is not None) -def eager(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: - """Call a function that cannot be recorded. - - Outside a recording this is a plain call. A :class:`GraphedCallable` that meets it while recording abandons the - recording, which launches nothing, and runs plainly from then on, this call included. - - Args: - fn: The function to call. - *args: Positional arguments of the call. - **kwargs: Keyword arguments of the call. - - Returns: - The result of the call. - - Raises: - RuntimeError: If the current device is capturing a graph that no :class:`GraphedCallable` records. - """ - recording = GraphedCallable._recording - if recording is not None and recording.capturing: - raise _EagerCall(fn) - if capturing(): - raise RuntimeError( - f"'{_name(fn)}' cannot be recorded, so it cannot run inside a graph capture that no GraphedCallable" - " started." - ) - return fn(*args, **kwargs) - - class _EagerCall(BaseException): - """Raised by :func:`eager` inside a recording, which the :class:`GraphedCallable` abandons. + """Raised by an :func:`eager_method` method called inside a recording, which the :class:`GraphedCallable` + abandons. It derives from :class:`BaseException`, so the ``except Exception`` handlers of the recorded code let it through. """ @@ -92,20 +66,34 @@ def _name(fn: Callable[..., Any]) -> str: def eager_method(method: Callable[..., Any]) -> Callable[..., Any]: - """Run a method that cannot be recorded through :func:`eager`. + """Mark a method that cannot be recorded, such as one that reads device data on the host or runs torch work. - A :class:`GraphedCallable` that calls the method runs plainly. An override in a subclass is decorated again. + Outside a recording the method runs as a plain call. A :class:`GraphedCallable` that calls it while recording + abandons the recording, which launches nothing, and runs plainly from then on, this call included. An override in a + subclass is decorated again. Args: - method: The method to wrap. + method: The method to mark. Returns: The wrapped method. + + Raises: + RuntimeError: If the method is called while the current device captures a graph that no + :class:`GraphedCallable` records. """ @functools.wraps(method) def wrapper(self, *args: Any, **kwargs: Any) -> Any: - return eager(method, self, *args, **kwargs) + recording = GraphedCallable._recording + if recording is not None and recording.capturing: + raise _EagerCall(method) + if capturing(): + raise RuntimeError( + f"'{_name(method)}' cannot be recorded, so it cannot run inside a graph capture that no" + " GraphedCallable started." + ) + return method(self, *args, **kwargs) return wrapper @@ -116,9 +104,9 @@ class GraphedCallable: * The first call with a given argument layout records without an eager warm-up: the recording is its first execution. Later calls with the same array pointers and scalar values replay that recording and return the result of the recording call, so the callable returns buffers its owner keeps. - * Calls that cannot be recorded go through :func:`eager`. A recording that meets one is abandoned without - launching anything, and the callable runs plainly from then on, starting with this call; it records again after - :meth:`reset`. Known limitation: the host work the callable did before the :func:`eager` call, such as a Python + * Methods that cannot be recorded are marked with :func:`eager_method`. A recording that calls one is abandoned + without launching anything, and the callable runs plainly from then on, starting with this call; it records + again after :meth:`reset`. Known limitation: the host work the callable did before that call, such as a Python counter it advanced, ran once in the abandoned recording and runs again in the plain call, on that first call only; its device work ran only in the plain call. * :attr:`enabled` turns recording off process-wide, to run every part eagerly; it is on by default. A callable on @@ -141,20 +129,21 @@ class GraphedCallable: """The watched physics backend's forward, run before each recording (see :meth:`watch`).""" _recording: ClassVar[_Recording | None] = None - """The recording in progress, which an :func:`eager` call abandons.""" + """The recording in progress, which a call of an :func:`eager_method` method abandons.""" def __init__(self, fn: Callable[..., Any], device: wp.DeviceLike): """Initialize the callable. Args: - fn: Callable to record. Its GPU work must be capturable; a call that is not goes through :func:`eager`. + fn: Callable to record. Its GPU work must be capturable; a method that is not is marked with + :func:`eager_method`. device: Warp device that runs the callable. """ self._fn = fn self._device = wp.get_device(device) self._recordings: dict[tuple, tuple[wp.Graph, Any]] = {} self._plain = False - """Whether the callable met an :func:`eager` call while recording, so it runs plainly.""" + """Whether the callable called an :func:`eager_method` method while recording, so it runs plainly.""" self._generation = GraphedCallable.generation def __call__(self, *args: Any, **kwargs: Any) -> Any: @@ -230,7 +219,7 @@ def _record(self, args: tuple, kwargs: dict[str, Any]) -> tuple[wp.Graph, Any]: """Record the callable as its first run and return the graph and the result. Raises: - _EagerCall: If the callable makes an :func:`eager` call; the recording launched nothing. + _EagerCall: If the callable calls an :func:`eager_method` method; the recording launched nothing. RuntimeError: If the callable runs work the graph cannot hold while it records (see :class:`_Recording`). """ try: @@ -242,7 +231,7 @@ def _record(self, args: tuple, kwargs: dict[str, Any]) -> tuple[wp.Graph, Any]: raise RuntimeError( f"'{_name(self._fn)}' synchronizes the host with the device or runs a torch CUDA operation outside the" " graph while it records, so a replay would keep the value it read or skip the operation. Run the" - f" function through eager() or mark it with @eager_method. ({exc})" + f" work in a method marked with @eager_method. ({exc})" ) from exc return recording.graph, result @@ -362,7 +351,7 @@ def end(self) -> None: wp.capture_launch(self.graph, stream=self.stream) def abort(self) -> None: - """End the graph without launching it, after the callable raised or made an :func:`eager` call.""" + """End the graph without launching it, after the callable raised or called an :func:`eager_method` method.""" if self.capturing: self.capturing = False self._release() diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py index 92408ce838fa..ee99b79ce2ad 100644 --- a/source/isaaclab/test/utils/warp/test_capture.py +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -17,7 +17,6 @@ from isaaclab.utils.warp.capture import ( GraphedCallable, capturing, - eager, eager_method, ) @@ -53,6 +52,24 @@ def __call__(self, values: wp.array, shift: int | None = None) -> wp.array: return values +class _EagerAffine(_Affine): + """An :class:`_Affine` whose call cannot be recorded: a method marked with :func:`eager_method`.""" + + __call__ = eager_method(_Affine.__call__) + + +class _HostWork: + """Work that cannot be recorded, in methods marked with :func:`eager_method`.""" + + @eager_method + def total(self, values: torch.Tensor) -> float: + return _synchronizing_call(values) + + @eager_method + def add(self, values: torch.Tensor, amount: int) -> None: + values.add_(amount) + + def _read(values: wp.array) -> list[int]: wp.synchronize_device(values.device) return values.numpy().tolist() @@ -155,11 +172,11 @@ def test_callable_runs_eagerly_when_disabled_or_on_cpu(monkeypatch): def test_an_eager_call_abandons_the_recording_and_the_callable_runs_plainly(caplog): """A recording that meets an eager call launches nothing; the call then runs plainly, now and on later calls.""" - before, between, after = _Affine(2, 0), _Affine(1, 10), _Affine(3, 0) + before, between, after = _Affine(2, 0), _EagerAffine(1, 10), _Affine(3, 0) def body(values: wp.array) -> wp.array: before(values) - eager(between, values) + between(values) return after(values) graphed = GraphedCallable(body, DEVICE) @@ -174,17 +191,17 @@ def body(values: wp.array) -> wp.array: assert (_read(values), before.calls, between.calls, after.calls, _num_graphs(graphed)) == ([246], 3, 2, 2, 0) assert [record.getMessage() for record in caplog.records] == [ "'test_an_eager_call_abandons_the_recording_and_the_callable_runs_plainly..body' calls" - " '_Affine', which cannot be recorded, so it runs without a CUDA graph." + " '_Affine.__call__', which cannot be recorded, so it runs without a CUDA graph." ] def test_an_eager_call_abandons_the_recording_through_an_exception_handler(): """The code a recording calls cannot catch the abandonment by mistake.""" - fn = _Affine(1, 10) + fn = _EagerAffine(1, 10) def body(values: wp.array): try: - eager(fn, values) + fn(values) except Exception: # noqa: BLE001 pytest.fail("the abandonment must pass an `except Exception` handler") @@ -196,13 +213,13 @@ def body(values: wp.array): def test_a_callable_that_ran_plainly_records_again_after_an_invalidation(): """A term change can remove the eager call, so an invalidation lets the callable record again.""" - fn, eager_fn = _Affine(2, 0), _Affine(1, 10) + fn, eager_fn = _Affine(2, 0), _EagerAffine(1, 10) uses_eager = [True] def body(values: wp.array): fn(values) if uses_eager[0]: - eager(eager_fn, values) + eager_fn(values) graphed = GraphedCallable(body, DEVICE) values = wp.ones(1, dtype=wp.int32, device=DEVICE) @@ -215,8 +232,8 @@ def body(values: wp.array): def test_an_eager_call_of_a_nested_callable_makes_both_run_plainly(): - eager_fn, inner_fn, outer_fn = _Affine(1, 10), _Affine(2, 0), _Affine(3, 0) - nested = GraphedCallable(lambda values: (eager(eager_fn, values), inner_fn(values)), DEVICE) + eager_fn, inner_fn, outer_fn = _EagerAffine(1, 10), _Affine(2, 0), _Affine(3, 0) + nested = GraphedCallable(lambda values: (eager_fn(values), inner_fn(values)), DEVICE) outer = GraphedCallable(lambda values: (outer_fn(values), nested(values)), DEVICE) values = wp.ones(1, dtype=wp.int32, device=DEVICE) @@ -229,24 +246,24 @@ def test_an_eager_call_of_a_nested_callable_makes_both_run_plainly(): def test_eager_call_raises_inside_a_capture_no_callable_started(): """A call that cannot be recorded must not be captured silently into a foreign graph.""" - fn = _Affine() + fn = _EagerAffine() values = wp.zeros(1, dtype=wp.int32, device=DEVICE) with pytest.raises(RuntimeError, match="no GraphedCallable started"): with wp.ScopedDevice(DEVICE), wp.ScopedCapture(): - eager(fn, values) + fn(values) assert fn.calls == 0 def test_capturing_sees_a_cpu_capture(): """Warp's CPU capture counts as a capture, so a call that cannot be recorded raises inside it as on CUDA.""" - fn = _Affine() + fn = _EagerAffine() values = wp.zeros(1, dtype=wp.int32, device="cpu") with wp.ScopedDevice("cpu"), wp.ScopedCapture(): assert capturing("cpu") with pytest.raises(RuntimeError, match="no GraphedCallable started"): - eager(fn, values) + fn(values) assert not capturing("cpu") assert fn.calls == 0 @@ -347,7 +364,7 @@ def test_a_host_synchronization_in_an_eager_call_runs_plainly_in_the_previous_mo def body(): modes.append(torch.cuda.get_sync_debug_mode()) - return eager(_synchronizing_call, values) + return _HostWork().total(values) graphed = GraphedCallable(body, DEVICE) assert graphed() == 4.0 @@ -381,7 +398,7 @@ def test_a_torch_operation_while_recording_raises_naming_the_call_and_the_operat def test_a_torch_operation_in_an_eager_call_runs(): values = torch.ones(4, device=DEVICE) - graphed = GraphedCallable(lambda: eager(values.add_, 1), DEVICE) + graphed = GraphedCallable(lambda: _HostWork().add(values, 1), DEVICE) graphed() graphed() assert values.sum().item() == 12.0 diff --git a/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst index 4af5cad1c8ee..9116ea69d7e9 100644 --- a/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,3 +1,3 @@ -* Changed :class:`~isaaclab_contrib.sensors.VisuoTactileSensor` to refresh through - :func:`~isaaclab.utils.warp.capture.eager`, since its refresh renders on the host: a +* Changed :class:`~isaaclab_contrib.sensors.VisuoTactileSensor` to mark its refresh with + :func:`~isaaclab.utils.warp.capture.eager_method`, since it renders on the host: a :class:`~isaaclab.utils.warp.capture.GraphedCallable` that refreshes it runs without a CUDA graph. From 3d4a2b77bb97d51e2feb3d65f036d358cd3f047c Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 15:44:37 -0800 Subject: [PATCH 18/30] Record without pausing the garbage collector GraphedCallable paused Python's garbage collector while it recorded, to keep collection-driven frees out of the graph (#6456). Warp 1.17.0, the locked version, fixes that, so recordings no longer pause it. --- .../isaaclab/isaaclab/utils/warp/capture.py | 20 +------------------ 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index 7e003293b5fa..4a59c87e3861 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -12,7 +12,6 @@ import contextlib import functools -import gc import logging from collections.abc import Callable from typing import TYPE_CHECKING, Any, ClassVar @@ -249,7 +248,7 @@ def _record_calls(device: wp.Device): recording = _Recording(device) enclosing, GraphedCallable._recording = GraphedCallable._recording, recording try: - with _paused_gc(), wp.ScopedStream(recording.capture_stream): + with wp.ScopedStream(recording.capture_stream): recording.begin() try: yield recording @@ -372,23 +371,6 @@ def _release(self) -> None: torch.cuda.set_sync_debug_mode(self._sync_debug_mode) -@contextlib.contextmanager -def _paused_gc(): - """Keep collection-driven frees out of a recording, as ``NewtonQueries.capture_graph`` does. - - Objects allocated during the recording stay in the youngest generation, so collecting that generation afterwards - frees the recording's garbage without the full collection of the whole heap. - """ - was_enabled = gc.isenabled() - gc.disable() - try: - yield - finally: - if was_enabled: - gc.enable() - gc.collect(0) - - def _argument_key(args: tuple, kwargs: dict[str, Any]) -> tuple: """Key a call by the pointer, shape, strides, dtype and device of its arrays and the type and value of its scalars. From fd1e9f997f36c0e6dfcec1d1bbc164c05f180a17 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 15:45:34 -0800 Subject: [PATCH 19/30] Remove the process-wide switch that turned recording off GraphedCallable.enabled had no setter outside tests, which only set it to its default. A GraphedCallable records on a CUDA device and runs eagerly on a CPU device. --- source/isaaclab/isaaclab/utils/warp/capture.py | 8 ++------ .../assets/contract/test_articulation_contract.py | 2 -- .../test/sensors/test_sensor_update_schedule.py | 3 +-- .../test/utils/test_timestamped_buffer.py | 3 +-- source/isaaclab/test/utils/warp/test_capture.py | 15 +-------------- .../isaaclab/test/utils/warp/test_capture_kit.py | 3 +-- .../test/physics/test_newton_solver_reset.py | 4 ---- .../test/sensors/test_contact_sensor.py | 3 +-- 8 files changed, 7 insertions(+), 34 deletions(-) diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index 4a59c87e3861..ab0baefdfde8 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -108,17 +108,13 @@ class GraphedCallable: again after :meth:`reset`. Known limitation: the host work the callable did before that call, such as a Python counter it advanced, ran once in the abandoned recording and runs again in the plain call, on that first call only; its device work ran only in the plain call. - * :attr:`enabled` turns recording off process-wide, to run every part eagerly; it is on by default. A callable on - a CPU device always runs eagerly. + * A callable on a CPU device always runs eagerly. * :attr:`generation` advances when the terms change or the physics backend rebinds its buffers or stops (see :meth:`watch`), and every callable records again on its next call. * Called inside a graph capture that something else started, it runs inline, so its kernels become part of that capture. """ - enabled: ClassVar[bool] = True - """Whether callables record CUDA graphs. Turn it off to run every recorded part eagerly.""" - generation: ClassVar[int] = 0 """Counter of term changes, physics rebinds and stops; a callable recorded under an older value records again.""" @@ -149,7 +145,7 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any: """Run the callable and return its result.""" if capturing(self._device): return self._fn(*args, **kwargs) - if not (GraphedCallable.enabled and self._device.is_cuda): + if not self._device.is_cuda: return self._fn(*args, **kwargs) if self._generation != GraphedCallable.generation: self.reset() diff --git a/source/isaaclab/test/assets/contract/test_articulation_contract.py b/source/isaaclab/test/assets/contract/test_articulation_contract.py index a8fc39ef0871..b88be91006eb 100644 --- a/source/isaaclab/test/assets/contract/test_articulation_contract.py +++ b/source/isaaclab/test/assets/contract/test_articulation_contract.py @@ -439,7 +439,6 @@ def test_lazy_properties_update_on_every_graph_replay(monkeypatch, backend, cuda The joint acceleration finite difference advances only in :meth:`update`, so the recording leaves it alone. """ - monkeypatch.setattr(GraphedCallable, "enabled", True) art = _recordable_articulation(backend, cuda_device, monkeypatch) # a previous velocity apart from the current one gives the step a nonzero acceleration, which a recorded # finite difference would overwrite @@ -473,7 +472,6 @@ def test_invalidation_inside_a_recording_records_the_update_again(monkeypatch, b The recording writes the root pose in place and invalidates the heading as the root pose writers do. """ - monkeypatch.setattr(GraphedCallable, "enabled", True) art = _recordable_articulation(backend, cuda_device, monkeypatch) rotated = _payload((N,), 7, wp.transformf, cuda_device) art.write_root_link_pose_to_sim_index(root_pose=_identity_yaw(rotated)) diff --git a/source/isaaclab/test/sensors/test_sensor_update_schedule.py b/source/isaaclab/test/sensors/test_sensor_update_schedule.py index a2b21eeee5d9..6b760006f929 100644 --- a/source/isaaclab/test/sensors/test_sensor_update_schedule.py +++ b/source/isaaclab/test/sensors/test_sensor_update_schedule.py @@ -257,10 +257,9 @@ def _read(self): @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_recorded_parts_reading_a_sensor_refresh_it_each_step(device, monkeypatch): +def test_recorded_parts_reading_a_sensor_refresh_it_each_step(device): """The data of a sensor that recorded parts read refreshes once per step, also when a step skips the part that refreshed it first: each recording holds the refresh of the environments still outdated.""" - monkeypatch.setattr(GraphedCallable, "enabled", True) sensor = _DeviceRefreshSensor(device) reader = _Reader(sensor) for _ in range(4): # the first step records both parts, the others replay them diff --git a/source/isaaclab/test/utils/test_timestamped_buffer.py b/source/isaaclab/test/utils/test_timestamped_buffer.py index 6023ba9a8e48..01a12c8aaf1f 100644 --- a/source/isaaclab/test/utils/test_timestamped_buffer.py +++ b/source/isaaclab/test/utils/test_timestamped_buffer.py @@ -96,10 +96,9 @@ def test_a_capture_commits_no_freshness(device): @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) -def test_an_abandoned_recording_leaves_the_next_plain_read_correct(device, monkeypatch): +def test_an_abandoned_recording_leaves_the_next_plain_read_correct(device): """A :class:`GraphedCallable` that reads the data and raises while recording launches nothing, so the next plain read updates the data.""" - monkeypatch.setattr(GraphedCallable, "enabled", True) value = _LazyValue(device) value.read() diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py index ee99b79ce2ad..798cff13e7f0 100644 --- a/source/isaaclab/test/utils/warp/test_capture.py +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -75,11 +75,6 @@ def _read(values: wp.array) -> list[int]: return values.numpy().tolist() -@pytest.fixture(autouse=True) -def enabled(monkeypatch): - monkeypatch.setattr(GraphedCallable, "enabled", True) - - def test_first_call_records_and_runs_the_callable_once(): """Recording has no eager warm-up: a stateful callable advances once per call, including the first.""" fn = _Affine() @@ -152,22 +147,14 @@ def test_physics_rebind_records_the_callable_again(): assert (fn.calls, _read(values), _num_graphs(graphed)) == (2, [3], 1) -def test_callable_runs_eagerly_when_disabled_or_on_cpu(monkeypatch): +def test_callable_runs_eagerly_on_cpu(): on_cpu = _Affine() cpu_graphed = GraphedCallable(on_cpu, "cpu") cpu_values = wp.zeros(1, dtype=wp.int32, device="cpu") cpu_graphed(cpu_values) cpu_graphed(cpu_values) - monkeypatch.setattr(GraphedCallable, "enabled", False) - disabled = _Affine() - graphed = GraphedCallable(disabled, DEVICE) - values = wp.zeros(1, dtype=wp.int32, device=DEVICE) - graphed(values) - graphed(values) - assert (on_cpu.calls, _read(cpu_values), _num_graphs(cpu_graphed)) == (2, [2], 0) - assert (disabled.calls, _read(values), _num_graphs(graphed)) == (2, [2], 0) def test_an_eager_call_abandons_the_recording_and_the_callable_runs_plainly(caplog): diff --git a/source/isaaclab/test/utils/warp/test_capture_kit.py b/source/isaaclab/test/utils/warp/test_capture_kit.py index 573f4af51d8f..9bfa4cd3c42a 100644 --- a/source/isaaclab/test/utils/warp/test_capture_kit.py +++ b/source/isaaclab/test/utils/warp/test_capture_kit.py @@ -22,8 +22,7 @@ DEVICE = "cuda:0" -def test_a_torch_operation_while_recording_under_kit_raises(monkeypatch): - monkeypatch.setattr(GraphedCallable, "enabled", True) +def test_a_torch_operation_while_recording_under_kit_raises(): assert has_kit(), "this test checks the relaxed capture Kit uses" values = torch.ones(4, device=DEVICE) graphed = GraphedCallable(lambda: values.add_(1), DEVICE) diff --git a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py index 7c69f037aa3c..91a3b81a0246 100644 --- a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py +++ b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py @@ -174,7 +174,6 @@ def reset_env_0(): articulation.write_joint_position_to_sim_mask(position=joint_pos, env_mask=env_mask) reset = GraphedCallable(reset_env_0, device) - enabled, GraphedCallable.enabled = GraphedCallable.enabled, True try: with patch.object(NewtonBackend, "_run_solver_substeps", _no_substeps): backend.invalidate_graph() @@ -195,7 +194,6 @@ def reset_env_0(): torch.testing.assert_close(body_q, wp.to_torch(backend.state_0.body_q), msg=f"offset {offset}") assert bool(backend.graphs) == use_cuda_graph finally: - GraphedCallable.enabled = enabled reset.reset() @@ -219,7 +217,6 @@ def read_body_poses(): wp.copy(poses, articulation.data.body_link_pose_w.warp) reset, read = GraphedCallable(reset_env_0, device), GraphedCallable(read_body_poses, device) - enabled, GraphedCallable.enabled = GraphedCallable.enabled, True try: for offset in (0.25, 0.5, 1.0): # the first calls record, the others replay wp.to_torch(joint_pos).copy_(default_joint_pos + offset) @@ -233,6 +230,5 @@ def read_body_poses(): expected = articulation.data.body_link_pose_w.torch torch.testing.assert_close(wp.to_torch(poses), expected, msg=f"offset {offset}") finally: - GraphedCallable.enabled = enabled reset.reset() read.reset() diff --git a/source/isaaclab_physx/test/sensors/test_contact_sensor.py b/source/isaaclab_physx/test/sensors/test_contact_sensor.py index 64bf873caf24..9f0213e5ac67 100644 --- a/source/isaaclab_physx/test/sensors/test_contact_sensor.py +++ b/source/isaaclab_physx/test/sensors/test_contact_sensor.py @@ -279,9 +279,8 @@ def fetch() -> None: assert fetch_call_count == 0 -def test_contact_sensor_update_repeats_eagerly_on_every_replay_of_a_recording(monkeypatch): +def test_contact_sensor_update_repeats_eagerly_on_every_replay_of_a_recording(): """A GraphedCallable recording that updates the sensor runs the PhysX reads and the update on every replay.""" - monkeypatch.setattr(GraphedCallable, "enabled", True) device = "cuda:0" env_mask = wp.ones(1, dtype=wp.bool, device=device) source = wp.ones(1, dtype=wp.int32, device=device) From 84565e79736a0e90be03f88aee37ddd76fa56dd2 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:12:54 -0800 Subject: [PATCH 20/30] Read the PhysX joint state as it is inside a graph capture The host actuator runtime captures its graphs with wp.ScopedCapture and reads the joint positions and velocities inside. Since a capture holds the update of lazy data, those reads refreshed from PhysX tensor views, which no graph can hold, so the capture failed and the runtime fell back to eager execution. The joint state buffers now opt out of the in-capture update, as the other PhysX-served data does. --- .../jichuanh-warp-recording-utils.fixed.rst | 5 +++-- .../assets/articulation/articulation_data.py | 10 ++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst index 024cbcd7c84d..58d700f9f8c3 100644 --- a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,7 +1,8 @@ * Fixed lazily computed asset data properties replaying the value of the recording step from a CUDA graph that :class:`~isaaclab.utils.warp.capture.GraphedCallable` recorded while they were current. A recording now holds their update, so every replay recomputes them. The joint acceleration, which - :meth:`~isaaclab_physx.assets.ArticulationData.update` advances once per physics step, and the body COM poses, - masses and inertias, which PhysX serves from CPU-only views, are read as they are. + :meth:`~isaaclab_physx.assets.ArticulationData.update` advances once per physics step, the body COM poses, + masses and inertias, which PhysX serves from CPU-only views, and the joint positions and velocities, which a + graph cannot refresh from PhysX, are read as they are, so the host actuator runtime still captures its graphs. * Fixed the PhysX sensors raising inside a :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording: their PhysX tensor reads cannot be recorded, so a recorded call that refreshes one runs without a CUDA graph. diff --git a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py index 87cea6687c0e..70a5e4d88add 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py @@ -1690,8 +1690,14 @@ def _create_buffers(self) -> None: self._body_link_state_w = TimestampedBuffer(wp.empty(body_shape, dtype=vec13f, device=device)) self._body_com_state_w = TimestampedBuffer(wp.empty(body_shape, dtype=vec13f, device=device)) # -- joint state - self._joint_pos = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) - self._joint_vel = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) + # refreshed by PhysX tensor reads, which no graph can hold: a capture reads them as they are, as the host + # actuator runtime's captured graphs do + self._joint_pos = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) + self._joint_vel = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) self._joint_pos_backend: TimestampedBuffer | None = None self._joint_vel_backend: TimestampedBuffer | None = None # update() advances the finite difference once per physics step, so a recording reads it as it is From 0e71e2c87354dcadcc46a383b5ce03e9bd74b176 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:14:28 -0800 Subject: [PATCH 21/30] Skip the in-place root pose test for OVPhysX, whose reads copy the binding again --- .../test/assets/contract/test_articulation_contract.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/source/isaaclab/test/assets/contract/test_articulation_contract.py b/source/isaaclab/test/assets/contract/test_articulation_contract.py index b88be91006eb..362df1ce3785 100644 --- a/source/isaaclab/test/assets/contract/test_articulation_contract.py +++ b/source/isaaclab/test/assets/contract/test_articulation_contract.py @@ -472,6 +472,11 @@ def test_invalidation_inside_a_recording_records_the_update_again(monkeypatch, b The recording writes the root pose in place and invalidates the heading as the root pose writers do. """ + if backend == "ovphysx": + pytest.skip( + "the test writes the root pose data buffer directly, while OVPhysX's writers write the binding, which each" + " read inside a capture copies into the buffer again" + ) art = _recordable_articulation(backend, cuda_device, monkeypatch) rotated = _payload((N,), 7, wp.transformf, cuda_device) art.write_root_link_pose_to_sim_index(root_pose=_identity_yaw(rotated)) From 1dd3e6a96565678c8a9dfe32e9c2dc826e8a304c Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:39:15 -0800 Subject: [PATCH 22/30] Stop labelling the other backends' sensors as unrecordable The PhysX, OVPhysX and visuo-tactile sensors no longer mark their refresh with eager_method: a step is recorded only with Newton physics, so these sensors never refresh inside a recording. --- .../jichuanh-warp-recording-utils.changed.rst | 3 -- .../tacsl_sensor/visuotactile_sensor.py | 2 -- .../jichuanh-warp-recording-utils.fixed.rst | 3 +- .../sensors/contact_sensor/contact_sensor.py | 2 -- .../frame_transformer/frame_transformer.py | 2 -- .../isaaclab_ov/sensors/imu/imu.py | 2 -- .../joint_wrench/joint_wrench_sensor.py | 2 -- .../isaaclab_ov/sensors/pva/pva.py | 2 -- .../jichuanh-warp-recording-utils.fixed.rst | 2 -- .../sensors/contact_sensor/contact_sensor.py | 2 -- .../frame_transformer/frame_transformer.py | 2 -- .../isaaclab_physx/sensors/imu/imu.py | 2 -- .../joint_wrench/joint_wrench_sensor.py | 2 -- .../isaaclab_physx/sensors/pva/pva.py | 2 -- .../sensors/ray_caster/ray_caster.py | 2 -- .../test/sensors/test_contact_sensor.py | 35 +------------------ 16 files changed, 2 insertions(+), 65 deletions(-) delete mode 100644 source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst diff --git a/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst deleted file mode 100644 index 9116ea69d7e9..000000000000 --- a/source/isaaclab_contrib/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ /dev/null @@ -1,3 +0,0 @@ -* Changed :class:`~isaaclab_contrib.sensors.VisuoTactileSensor` to mark its refresh with - :func:`~isaaclab.utils.warp.capture.eager_method`, since it renders on the host: a - :class:`~isaaclab.utils.warp.capture.GraphedCallable` that refreshes it runs without a CUDA graph. diff --git a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py index f363ed84f0eb..e66b53f78a3d 100644 --- a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py +++ b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_sensor.py @@ -23,7 +23,6 @@ from isaaclab.sensors.camera import Camera from isaaclab.sensors.sensor_base import SensorBase from isaaclab.utils.math import quat_apply, quat_inv -from isaaclab.utils.warp.capture import eager_method from .visuotactile_render import GelsightRender from .visuotactile_sensor_data import VisuoTactileSensorData @@ -490,7 +489,6 @@ def _initialize_visualization(self): if self.cfg.visualizer_cfg: self._visualizer = VisualizationMarkers(self.cfg.visualizer_cfg) - @eager_method # refreshes its camera and renders the tactile image on the host, so it cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data. diff --git a/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst index f2976f8d4988..fc3dfc7727f8 100644 --- a/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -1,5 +1,4 @@ * Fixed lazily computed asset data properties replaying the value of the recording step from a CUDA graph that :class:`~isaaclab.utils.warp.capture.GraphedCallable` recorded while they were current. A recording now holds their update, so every replay recomputes them. The accelerations taken by finite differencing, which - ``update`` advances once per physics step, are read as they are. The OVPhysX sensors read through host calls, so - a recorded call that refreshes one runs without a CUDA graph. + ``update`` advances once per physics step, are read as they are. diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py index 769248e46e8d..612c2d72b928 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py @@ -22,7 +22,6 @@ from isaaclab.sensors.contact_sensor import BaseContactSensor from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source, split_path_expr from isaaclab.utils.warp import ProxyArray -from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov._clone import ordered_clone_paths @@ -387,7 +386,6 @@ def _fetch_ovphysx_buffers(self, include_pose: bool = True) -> None: assert self._poses_flat_buf is not None self._root_view.read_into(TT.RIGID_BODY_POSE, self._poses_flat_buf) - @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None) -> None: """Read contact data from ovphysx and update sensor buffers.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py b/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py index 0c2d4a04522e..7437f7b88c3a 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/frame_transformer/frame_transformer.py @@ -19,7 +19,6 @@ from isaaclab.sensors.frame_transformer.kernels import frame_transformer_update_kernel from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source from isaaclab.utils.math import is_identity_pose, normalize, quat_from_angle_axis -from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView @@ -383,7 +382,6 @@ def _initialize_impl(self) -> None: device=self._device, ) - @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None) -> None: """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/imu/imu.py b/source/isaaclab_ov/isaaclab_ov/sensors/imu/imu.py index ee5c31af6e5b..6ca08d779ba7 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/imu/imu.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/imu/imu.py @@ -16,7 +16,6 @@ from isaaclab.sensors.imu.kernels import imu_update_kernel from isaaclab.sim.utils.queries import path_expr_to_glob from isaaclab.utils.warp import memory as memory_kernels -from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView @@ -185,7 +184,6 @@ def _refresh_gravity_bias(self): self._gravity_w = gravity self._gravity_bias_w = wp.vec3f(-gravity[0], -gravity[1], -gravity[2]) - @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py b/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py index 087689262ae1..d0e115da9e6a 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/joint_wrench/joint_wrench_sensor.py @@ -19,7 +19,6 @@ from isaaclab.sensors.joint_wrench import BaseJointWrenchSensor from isaaclab.sim.utils.queries import find_first_matching_prim, get_all_matching_child_prims, path_expr_to_glob from isaaclab.utils.warp import memory as memory_kernels -from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView @@ -181,7 +180,6 @@ def _resolve_articulation_root_prim_path(self) -> str: root_prim_path_relative_to_prim_path = first_env_root_prim_path[len(first_env_matching_prim_path) :] return self.cfg.prim_path + root_prim_path_relative_to_prim_path - @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array) -> None: """Read OVPhysX incoming joint wrenches and split them into force / torque buffers. diff --git a/source/isaaclab_ov/isaaclab_ov/sensors/pva/pva.py b/source/isaaclab_ov/isaaclab_ov/sensors/pva/pva.py index 668330fb5fe2..b268d0427f05 100644 --- a/source/isaaclab_ov/isaaclab_ov/sensors/pva/pva.py +++ b/source/isaaclab_ov/isaaclab_ov/sensors/pva/pva.py @@ -15,7 +15,6 @@ from isaaclab.sensors.pva import BasePva from isaaclab.sensors.pva.kernels import make_pva_update from isaaclab.sim.utils.queries import path_expr_to_glob -from isaaclab.utils.warp.capture import eager_method import isaaclab_ov.tensor_types as TT from isaaclab_ov.sim.views.ovphysx_view import OvPhysxView @@ -163,7 +162,6 @@ def _refresh_gravity_vec(self): scale = 1.0 / max(math.sqrt(gravity[0] ** 2 + gravity[1] ** 2 + gravity[2] ** 2), 1.0e-9) self._gravity_vec_w = wp.vec3f(gravity[0] * scale, gravity[1] * scale, gravity[2] * scale) - @eager_method # OVPhysX binding reads are host calls, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst index 58d700f9f8c3..11835bef5c2b 100644 --- a/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -4,5 +4,3 @@ :meth:`~isaaclab_physx.assets.ArticulationData.update` advances once per physics step, the body COM poses, masses and inertias, which PhysX serves from CPU-only views, and the joint positions and velocities, which a graph cannot refresh from PhysX, are read as they are, so the host actuator runtime still captures its graphs. -* Fixed the PhysX sensors raising inside a :class:`~isaaclab.utils.warp.capture.GraphedCallable` recording: their - PhysX tensor reads cannot be recorded, so a recorded call that refreshes one runs without a CUDA graph. diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py index 0b0494d353cb..edbf2e8c5524 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py @@ -24,7 +24,6 @@ from isaaclab.sensors.contact_sensor.contact_force_marker import ContactForceVisualizer from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source, split_path_expr from isaaclab.utils.warp import ProxyArray -from isaaclab.utils.warp.capture import eager_method from .contact_sensor_data import ContactSensorData from .kernels import ( @@ -446,7 +445,6 @@ def _create_buffers(self) -> None: device=self._device, ) - @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data. diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer.py b/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer.py index b5814d9de390..223f40763f26 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/frame_transformer/frame_transformer.py @@ -21,7 +21,6 @@ from isaaclab.sensors.frame_transformer.kernels import frame_transformer_update_kernel from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source from isaaclab.utils.math import is_identity_pose, normalize, quat_from_angle_axis -from isaaclab.utils.warp.capture import eager_method from .frame_transformer_data import FrameTransformerData @@ -374,7 +373,6 @@ def _initialize_impl(self): ) self._use_recorded_launch = wp.get_device(self._device).is_cuda - @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" # Resolve mask diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py b/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py index 3d9966dbc31c..e4691ff4b165 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/imu/imu.py @@ -17,7 +17,6 @@ from isaaclab.sensors.imu.kernels import imu_update_kernel from isaaclab.sim.utils.queries import path_expr_to_glob from isaaclab.utils.warp import memory as memory_kernels -from isaaclab.utils.warp.capture import eager_method from .imu_data import ImuData @@ -173,7 +172,6 @@ def _refresh_gravity_bias(self): self._gravity_w = gravity self._gravity_bias_w = wp.vec3f(-gravity[0], -gravity[1], -gravity[2]) - @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py index 5e16954d8fb1..1ef7a7412e8e 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/joint_wrench/joint_wrench_sensor.py @@ -18,7 +18,6 @@ from isaaclab.sensors.joint_wrench import BaseJointWrenchSensor from isaaclab.sim.utils.queries import path_expr_to_glob, resolve_matching_prims_from_source from isaaclab.utils.warp import memory as memory_kernels -from isaaclab.utils.warp.capture import eager_method from .joint_wrench_sensor_data import JointWrenchSensorData @@ -145,7 +144,6 @@ def has_articulation_root_api(prim) -> bool: logger.info(f"Joint wrench sensor initialized: {self._num_envs} envs, {self._num_bodies} bodies") - @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array) -> None: """Read PhysX incoming joint wrenches and split them into force / torque buffers. diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py b/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py index ffd90cef09b9..17969394518b 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/pva/pva.py @@ -16,7 +16,6 @@ from isaaclab.sensors.pva import BasePva from isaaclab.sensors.pva.kernels import make_pva_update from isaaclab.sim.utils.queries import path_expr_to_glob -from isaaclab.utils.warp.capture import eager_method from .pva_data import PvaData @@ -176,7 +175,6 @@ def _refresh_gravity_vec(self): scale = 1.0 / max(math.sqrt(gravity[0] ** 2 + gravity[1] ** 2 + gravity[2] ** 2), 1.0e-9) self._gravity_vec_w = wp.vec3f(gravity[0] * scale, gravity[1] * scale, gravity[2] * scale) - @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array | None = None): """Fills the buffers of the sensor data.""" env_mask = self._resolve_indices_and_mask(None, env_mask) diff --git a/source/isaaclab_physx/isaaclab_physx/sensors/ray_caster/ray_caster.py b/source/isaaclab_physx/isaaclab_physx/sensors/ray_caster/ray_caster.py index 42ea7a42fc87..d592e128fe2a 100644 --- a/source/isaaclab_physx/isaaclab_physx/sensors/ray_caster/ray_caster.py +++ b/source/isaaclab_physx/isaaclab_physx/sensors/ray_caster/ray_caster.py @@ -17,7 +17,6 @@ import isaaclab.sim as sim_utils from isaaclab.sensors.ray_caster.base_ray_caster import BaseRayCaster from isaaclab.sensors.ray_caster.ray_caster_cfg import RayCasterCfg -from isaaclab.utils.warp.capture import eager_method logger = logging.getLogger(__name__) @@ -146,7 +145,6 @@ def _get_view_transforms_wp(self) -> wp.array: self._raw_transforms = wp.from_torch(transforms.contiguous()).view(wp.transformf) return self._raw_transforms - @eager_method # PhysX tensor reads run on the legacy CUDA stream, so they cannot be recorded def _update_buffers_impl(self, env_mask: wp.array) -> None: """Refresh PhysX transforms and update ray data eagerly or through a CUDA graph. diff --git a/source/isaaclab_physx/test/sensors/test_contact_sensor.py b/source/isaaclab_physx/test/sensors/test_contact_sensor.py index 9f0213e5ac67..0108e0f0452b 100644 --- a/source/isaaclab_physx/test/sensors/test_contact_sensor.py +++ b/source/isaaclab_physx/test/sensors/test_contact_sensor.py @@ -35,7 +35,6 @@ from isaaclab.sim.utils.stage import get_current_stage from isaaclab.terrains import HfRandomUniformTerrainCfg, TerrainGeneratorCfg, TerrainImporterCfg from isaaclab.utils import configclass, replace -from isaaclab.utils.warp.capture import GraphedCallable ## # Custom helper classes. @@ -270,7 +269,7 @@ def fetch() -> None: sensor._fetch_physx_buffers = fetch with wp.ScopedCapture(device=wp.get_device(device)): - with pytest.raises(RuntimeError, match="graph capture"): + with pytest.raises(RuntimeError, match="CUDA graph capture"): sensor._update_buffers_impl(env_mask) # record something so the outer capture does not end empty wp.copy(destination, source) @@ -279,38 +278,6 @@ def fetch() -> None: assert fetch_call_count == 0 -def test_contact_sensor_update_repeats_eagerly_on_every_replay_of_a_recording(): - """A GraphedCallable recording that updates the sensor runs the PhysX reads and the update on every replay.""" - device = "cuda:0" - env_mask = wp.ones(1, dtype=wp.bool, device=device) - source = wp.ones(1, dtype=wp.int32, device=device) - destination = wp.zeros(1, dtype=wp.int32, device=device) - before = wp.zeros(1, dtype=wp.int32, device=device) - sensor = _make_graph_test_sensor() - - fetch_call_count = 0 - - def fetch() -> None: - nonlocal fetch_call_count - fetch_call_count += 1 - - sensor._fetch_physx_buffers = fetch - sensor._compute = lambda: wp.copy(destination, source) - - def step() -> None: - wp.copy(before, source) # recorded work around the eager update - sensor._update_buffers_impl(env_mask) - - graphed = GraphedCallable(step, device) - graphed() # the recording is the first run; without the eager boundary the sensor raises here - source.fill_(2) - graphed() - wp.synchronize_device(device) - - assert fetch_call_count == 2 - assert destination.numpy().tolist() == [2] - - def test_contact_sensor_falls_back_when_graph_capture_fails(monkeypatch): """A capture failure should disable graphs and still produce data eagerly.""" device = "cuda:0" From 638e59570715f5df5de4ff624258a58b44563ecd Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:34:48 -0800 Subject: [PATCH 23/30] Prune recording tests that stronger tests already cover The eager timestamp test and the single-read sensor capture test fail only when the articulation contract tests and the repeated-read sensor test fail too. The in-recording invalidation test passes without the recording rule. The CPU capture check joins the foreign-capture test as its CPU case, and the PhysX ray caster test matches the sensor's own error again. --- .../contract/test_articulation_contract.py | 41 ------------------- .../sensors/test_sensor_update_schedule.py | 14 ------- .../test/utils/test_timestamped_buffer.py | 13 +----- .../isaaclab/test/utils/warp/test_capture.py | 25 ++++------- .../test/sensors/test_ray_caster_graph.py | 2 +- 5 files changed, 10 insertions(+), 85 deletions(-) diff --git a/source/isaaclab/test/assets/contract/test_articulation_contract.py b/source/isaaclab/test/assets/contract/test_articulation_contract.py index 362df1ce3785..dda8ce0f2432 100644 --- a/source/isaaclab/test/assets/contract/test_articulation_contract.py +++ b/source/isaaclab/test/assets/contract/test_articulation_contract.py @@ -27,7 +27,6 @@ from isaaclab.assets.articulation.base_articulation_data import BaseArticulationData from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils import replace -from isaaclab.utils.buffers import reset_timestamps from isaaclab.utils.warp import ProxyArray from isaaclab.utils.warp.capture import GraphedCallable @@ -427,12 +426,6 @@ def _recordable_articulation(backend: str, cuda_device: str, monkeypatch: pytest return art -def _identity_yaw(pose: torch.Tensor) -> torch.Tensor: - pose = pose.clone() - pose[..., 3:] = torch.tensor([0.0, 0.0, 0.0, 1.0], device=pose.device) - return pose - - @_CUDA_DEVICES def test_lazy_properties_update_on_every_graph_replay(monkeypatch, backend, cuda_device): """A lazy property read while a GraphedCallable records updates on each replay, though current at recording. @@ -466,40 +459,6 @@ def read(): assert not torch.allclose(replayed, recorded) -@_CUDA_DEVICES -def test_invalidation_inside_a_recording_records_the_update_again(monkeypatch, backend, cuda_device): - """A property invalidated between two reads of one recording updates again for the second read. - - The recording writes the root pose in place and invalidates the heading as the root pose writers do. - """ - if backend == "ovphysx": - pytest.skip( - "the test writes the root pose data buffer directly, while OVPhysX's writers write the binding, which each" - " read inside a capture copies into the buffer again" - ) - art = _recordable_articulation(backend, cuda_device, monkeypatch) - rotated = _payload((N,), 7, wp.transformf, cuda_device) - art.write_root_link_pose_to_sim_index(root_pose=_identity_yaw(rotated)) - art.data.update(dt=0.01) - unrotated = art.data.heading_w.torch.clone() - rotated_wp = wp.from_torch(rotated, dtype=wp.transformf) - - def rotate_and_read(): - _ = art.data.heading_w - wp.copy(art.data.root_link_pose_w.warp, rotated_wp) - reset_timestamps([art.data._heading_w]) - return art.data.heading_w - - graphed = GraphedCallable(rotate_and_read, cuda_device) - heading = graphed() # the recording is the first run - graphed() - replayed = heading.torch.clone() - art.write_root_link_pose_to_sim_index(root_pose=rotated) - art.data.update(dt=0.01) - torch.testing.assert_close(replayed, art.data.heading_w.torch) - assert not torch.allclose(replayed, unrotated) - - @requires("physx") def test_physx_com_cache_survives_com_and_joint_writes(monkeypatch): """A COM write refreshes the PhysX COM cache directly, and a joint write leaves it valid.""" diff --git a/source/isaaclab/test/sensors/test_sensor_update_schedule.py b/source/isaaclab/test/sensors/test_sensor_update_schedule.py index 6b760006f929..73b2ff9c4517 100644 --- a/source/isaaclab/test/sensors/test_sensor_update_schedule.py +++ b/source/isaaclab/test/sensors/test_sensor_update_schedule.py @@ -203,20 +203,6 @@ def _capture(device: str, fn) -> wp.Graph: return capture.graph -@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) -def test_captured_read_refreshes_on_every_replay(device): - """A read captured while the sensor is not dirty, as after a reset, still refreshes the sensor on each replay.""" - sensor = _DeviceRefreshSensor(device) - sensor.update(0.005) - _ = sensor.data # the sensor is clean when the read is captured - graph = _capture(device, lambda: sensor.data) - for _ in range(3): - sensor.update(0.005) - wp.capture_launch(graph) - # one eager refresh, then one per replay - assert sensor.device_refreshes.numpy().tolist() == [4, 4] - - @pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) def test_repeated_reads_in_a_capture_refresh_the_data_once_per_replay(device): """Each read in a capture records the refresh, since no read can know what a replay finds outdated; the first diff --git a/source/isaaclab/test/utils/test_timestamped_buffer.py b/source/isaaclab/test/utils/test_timestamped_buffer.py index 01a12c8aaf1f..ec9194e65a75 100644 --- a/source/isaaclab/test/utils/test_timestamped_buffer.py +++ b/source/isaaclab/test/utils/test_timestamped_buffer.py @@ -13,7 +13,7 @@ import warp as wp from isaaclab.test.utils import DeviceScope, test_devices -from isaaclab.utils.buffers import TimestampedBuffer, reset_timestamps +from isaaclab.utils.buffers import TimestampedBuffer from isaaclab.utils.warp.capture import GraphedCallable pytestmark = pytest.mark.unit @@ -57,17 +57,6 @@ def _capture(device: str, fn) -> wp.Graph: return capture.graph -def test_eager_reads_update_once_per_timestamp(): - value = _LazyValue("cpu") - for _ in range(2): - value.timestamp += 0.01 - value.read() - value.read() - reset_timestamps([value._value]) - value.read() - assert value.num_updates == 3 - - @pytest.mark.parametrize("device", test_devices(DeviceScope.CPU_AND_DEFAULT_CUDA)) def test_a_capture_holds_the_update_of_every_read(device): """A read captured while the data is current still updates it on each replay.""" diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py index 798cff13e7f0..0ef7e4c67c2c 100644 --- a/source/isaaclab/test/utils/warp/test_capture.py +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -231,27 +231,18 @@ def test_an_eager_call_of_a_nested_callable_makes_both_run_plainly(): assert (_num_graphs(outer), _num_graphs(nested), outer._plain, nested._plain) == (0, 0, True, True) -def test_eager_call_raises_inside_a_capture_no_callable_started(): - """A call that cannot be recorded must not be captured silently into a foreign graph.""" +@pytest.mark.parametrize("device", [DEVICE, "cpu"]) +def test_eager_call_raises_inside_a_capture_no_callable_started(device): + """A call that cannot be recorded must not be captured silently into a foreign graph; Warp's CPU capture counts + as a capture too.""" fn = _EagerAffine() - values = wp.zeros(1, dtype=wp.int32, device=DEVICE) - - with pytest.raises(RuntimeError, match="no GraphedCallable started"): - with wp.ScopedDevice(DEVICE), wp.ScopedCapture(): - fn(values) - assert fn.calls == 0 - - -def test_capturing_sees_a_cpu_capture(): - """Warp's CPU capture counts as a capture, so a call that cannot be recorded raises inside it as on CUDA.""" - fn = _EagerAffine() - values = wp.zeros(1, dtype=wp.int32, device="cpu") + values = wp.zeros(1, dtype=wp.int32, device=device) - with wp.ScopedDevice("cpu"), wp.ScopedCapture(): - assert capturing("cpu") + with wp.ScopedDevice(device), wp.ScopedCapture(): + assert capturing(device) with pytest.raises(RuntimeError, match="no GraphedCallable started"): fn(values) - assert not capturing("cpu") + assert not capturing(device) assert fn.calls == 0 diff --git a/source/isaaclab_physx/test/sensors/test_ray_caster_graph.py b/source/isaaclab_physx/test/sensors/test_ray_caster_graph.py index e986f1b9b5e1..0acab87f7dc9 100644 --- a/source/isaaclab_physx/test/sensors/test_ray_caster_graph.py +++ b/source/isaaclab_physx/test/sensors/test_ray_caster_graph.py @@ -138,7 +138,7 @@ def test_ray_caster_refuses_update_inside_outer_graph_capture(monkeypatch): zeros = wp.zeros_like(sensor._test_output) with wp.ScopedCapture(device=device): - with pytest.raises(RuntimeError, match="graph capture"): + with pytest.raises(RuntimeError, match="CUDA graph capture"): sensor._update_buffers_impl(env_mask) # record something so the outer capture does not end empty wp.copy(sensor._test_output, zeros) From 7c0784c04d1ab90dc08380ead8bbeae331d0a38e Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 16:37:25 -0800 Subject: [PATCH 24/30] Leave resetting recordings to their owners GraphedCallable no longer follows the physics backend through a class-level subscription (watch, unwatch, generation, invalidate), and cached Warp launches no longer have a global clear_all. Nothing in this part records a step, so the owner that does resets its own callables and clears its own caches, as main's physics backend and asset data do. --- .../jichuanh-warp-recording-utils.added.rst | 2 +- .../jichuanh-warp-recording-utils.changed.rst | 5 +- .../isaaclab/isaaclab/utils/warp/capture.py | 59 +------------------ .../isaaclab/utils/warp/launch_cache.py | 20 +------ .../isaaclab/test/utils/warp/test_capture.py | 38 ++---------- .../test/utils/warp/test_launch_cache.py | 36 +---------- 6 files changed, 15 insertions(+), 145 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst index 48457cc55409..7dc218f9f3fd 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst @@ -1,6 +1,6 @@ * Added :mod:`isaaclab.utils.warp.capture`. :class:`~isaaclab.utils.warp.capture.GraphedCallable` records a call as a CUDA graph on its first run with a given argument layout and replays it after; it records again for another - layout or when the physics backend rebinds its buffers. + layout, or after its owner calls :meth:`~isaaclab.utils.warp.capture.GraphedCallable.reset`. * Added :func:`~isaaclab.utils.warp.capture.eager_method` to mark methods that cannot be recorded. A :class:`~isaaclab.utils.warp.capture.GraphedCallable` that calls one while it records abandons the recording without launching it and runs without a CUDA graph from then on, logging a warning that names both calls. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst index 122b3ddc1cd8..4507d30089b5 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,4 +1,3 @@ * Changed the cached Warp launches of asset data, sensors and managers to keep one recorded launch per call site: an - argument or launch dimension that changes is set on that launch in place instead of recording a new one, and the - Warp frontend clears every recorded launch when the physics backend rebinds its buffers or stops. The sensor clock - update of each physics step replays a recorded launch. + argument or launch dimension that changes is set on that launch in place instead of recording a new one. The + sensor clock update of each physics step replays a recorded launch. diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index ab0baefdfde8..d1671f5d9bc1 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -14,7 +14,7 @@ import functools import logging from collections.abc import Callable -from typing import TYPE_CHECKING, Any, ClassVar +from typing import Any, ClassVar import torch import torch.utils._pytree as _pytree @@ -23,10 +23,6 @@ from torch.utils._python_dispatch import TorchDispatchMode from ..version import has_kit -from .launch_cache import _WarpLaunchCache - -if TYPE_CHECKING: - from ...physics import PhysicsManager logger = logging.getLogger(__name__) @@ -109,20 +105,12 @@ class GraphedCallable: counter it advanced, ran once in the abandoned recording and runs again in the plain call, on that first call only; its device work ran only in the plain call. * A callable on a CPU device always runs eagerly. - * :attr:`generation` advances when the terms change or the physics backend rebinds its buffers or stops (see - :meth:`watch`), and every callable records again on its next call. + * Its owner calls :meth:`reset` when what a recording holds changes, such as the physics buffers after a rebind, + and the callable records again on its next call. * Called inside a graph capture that something else started, it runs inline, so its kernels become part of that capture. """ - generation: ClassVar[int] = 0 - """Counter of term changes, physics rebinds and stops; a callable recorded under an older value records again.""" - - _callback_handles: ClassVar[list] = [] - - _settle: ClassVar[Callable[[], None] | None] = None - """The watched physics backend's forward, run before each recording (see :meth:`watch`).""" - _recording: ClassVar[_Recording | None] = None """The recording in progress, which a call of an :func:`eager_method` method abandons.""" @@ -139,7 +127,6 @@ def __init__(self, fn: Callable[..., Any], device: wp.DeviceLike): self._recordings: dict[tuple, tuple[wp.Graph, Any]] = {} self._plain = False """Whether the callable called an :func:`eager_method` method while recording, so it runs plainly.""" - self._generation = GraphedCallable.generation def __call__(self, *args: Any, **kwargs: Any) -> Any: """Run the callable and return its result.""" @@ -147,9 +134,6 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any: return self._fn(*args, **kwargs) if not self._device.is_cuda: return self._fn(*args, **kwargs) - if self._generation != GraphedCallable.generation: - self.reset() - self._generation = GraphedCallable.generation if self._plain: return self._fn(*args, **kwargs) key = _argument_key(args, kwargs) @@ -176,40 +160,6 @@ def reset(self) -> None: wp.synchronize_device(self._device) self._recordings.clear() - @classmethod - def watch(cls, backend_manager: PhysicsManager) -> None: - """Record every callable and every cached launch again after the physics backend rebinds its buffers or stops, - and settle the backend before each recording: work it queued before (model changes, kinematics) runs then, - once, so a recording holds only the work of its own calls. - - Args: - backend_manager: Physics manager that dispatches the lifecycle events. - """ - # imported here so that the utilities do not load the physics package - from ...physics import PhysicsEvent - - cls.unwatch() - cls._settle = backend_manager.forward - cls._callback_handles = [ - backend_manager.register_callback(callback, event) - for event in (PhysicsEvent.PHYSICS_READY, PhysicsEvent.STOP) - # the recorded launches of the code outside the graphs read the same buffers - for callback in (cls.invalidate, _WarpLaunchCache.clear_all) - ] - - @classmethod - def unwatch(cls) -> None: - """Stop following the physics backend.""" - for handle in cls._callback_handles: - handle.deregister() - cls._callback_handles = [] - cls._settle = None - - @classmethod - def invalidate(cls, payload: Any = None) -> None: - """Record every callable again on its next call.""" - cls.generation += 1 - def _record(self, args: tuple, kwargs: dict[str, Any]) -> tuple[wp.Graph, Any]: """Record the callable as its first run and return the graph and the result. @@ -238,9 +188,6 @@ def _record_calls(device: wp.Device): Yields: The recording, whose graph replays the calls. """ - if GraphedCallable._settle is not None: - # physics work queued before the recording runs now, once, instead of on every replay - GraphedCallable._settle() recording = _Recording(device) enclosing, GraphedCallable._recording = GraphedCallable._recording, recording try: diff --git a/source/isaaclab/isaaclab/utils/warp/launch_cache.py b/source/isaaclab/isaaclab/utils/warp/launch_cache.py index 62fb7c178316..88def8df99b2 100644 --- a/source/isaaclab/isaaclab/utils/warp/launch_cache.py +++ b/source/isaaclab/isaaclab/utils/warp/launch_cache.py @@ -3,9 +3,8 @@ # # SPDX-License-Identifier: BSD-3-Clause -import weakref from collections.abc import Callable -from typing import Any, ClassVar +from typing import Any import warp as wp @@ -29,17 +28,12 @@ class _WarpLaunchCache: or scalar argument records the call site's launch again; other arguments must stay valid until the key is cleared. - CPU execution and graph capture invoke the operation directly. :meth:`clear_all` empties every cache, which the - recording of the environment step does when the physics backend rebinds its buffers or stops (see - :meth:`~isaaclab.utils.warp.capture.GraphedCallable.watch`). + CPU execution and graph capture invoke the operation directly. """ - _instances: ClassVar[weakref.WeakSet] = weakref.WeakSet() - def __init__(self, device: str): self._device = wp.get_device(device) self._commands: dict[object, tuple[wp.Launch, tuple]] = {} - _WarpLaunchCache._instances.add(self) def launch(self, key: object, operation: Callable, *args, **kwargs) -> None: """Launch through the call site's cached launch, recording it on the first call. @@ -91,16 +85,6 @@ def clear(self, key: object | None = None) -> None: else: self._commands.pop(key, None) - @classmethod - def clear_all(cls, payload: Any = None) -> None: - """Remove the recorded launches of every cache, so they record again on their next launch. - - Args: - payload: Event payload of a physics callback, unused. - """ - for cache in list(cls._instances): - cache.clear() - def _key(value: Any, unknown: Any = _UNKNOWN) -> Any: """Key an argument by what a launch reads of it: an array by its pointer and layout, a scalar by its type and value. diff --git a/source/isaaclab/test/utils/warp/test_capture.py b/source/isaaclab/test/utils/warp/test_capture.py index 0ef7e4c67c2c..341c637d8227 100644 --- a/source/isaaclab/test/utils/warp/test_capture.py +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -8,7 +8,6 @@ from __future__ import annotations import logging -from types import SimpleNamespace import pytest import torch @@ -135,13 +134,14 @@ def test_views_of_one_array_record_their_own_graphs(): assert (_read(values), fn.calls, _num_graphs(graphed)) == ([3, 3, 2, 2], 2, 2) -def test_physics_rebind_records_the_callable_again(): +def test_reset_records_the_callable_again(): + """The owner resets a callable when what its recordings hold changes, such as the physics buffers.""" fn = _Affine() graphed = GraphedCallable(fn, DEVICE) values = wp.zeros(1, dtype=wp.int32, device=DEVICE) graphed(values) - GraphedCallable.invalidate() + graphed.reset() graphed(values) graphed(values) assert (fn.calls, _read(values), _num_graphs(graphed)) == (2, [3], 1) @@ -198,8 +198,8 @@ def body(values: wp.array): assert (_read(values), fn.calls, _num_graphs(graphed)) == ([10], 1, 0) -def test_a_callable_that_ran_plainly_records_again_after_an_invalidation(): - """A term change can remove the eager call, so an invalidation lets the callable record again.""" +def test_a_callable_that_ran_plainly_records_again_after_a_reset(): + """A term change can remove the eager call, so a reset lets the callable record again.""" fn, eager_fn = _Affine(2, 0), _EagerAffine(1, 10) uses_eager = [True] @@ -212,7 +212,7 @@ def body(values: wp.array): values = wp.ones(1, dtype=wp.int32, device=DEVICE) graphed(values) # abandoned, then plain: 1 * 2 + 10 = 12 uses_eager[0] = False - GraphedCallable.invalidate() + graphed.reset() graphed(values) # records: 24 graphed(values) # replays: 48 assert (_read(values), fn.calls, _num_graphs(graphed)) == ([48], 3, 1) @@ -294,32 +294,6 @@ def writer(): assert (registry.changes, _read(values), _num_graphs(graphed)) == ([7, 7, 7], [3], 0) -def test_recording_settles_the_watched_backend_first(): - """Work the physics backend queued before a recording runs once, before it, not on every replay.""" - values = wp.zeros(1, dtype=wp.int32, device=DEVICE) - - class Backend: - pending = True - - def register_callback(self, fn, event): - return SimpleNamespace(deregister=lambda: None) - - def forward(self): - if self.pending: - wp.launch(_affine, dim=1, inputs=[values, 1, 1], device=DEVICE) - self.pending = False - - backend = Backend() - GraphedCallable.watch(backend) - try: - graphed = GraphedCallable(backend.forward, DEVICE) - for _ in range(3): - graphed() - finally: - GraphedCallable.unwatch() - assert _read(values) == [1] - - def _synchronizing_call(values: torch.Tensor) -> float: """A torch host synchronization, whose value a replay would keep.""" return values.sum().item() diff --git a/source/isaaclab/test/utils/warp/test_launch_cache.py b/source/isaaclab/test/utils/warp/test_launch_cache.py index bbee1299dbe5..a9cc066cb3ca 100644 --- a/source/isaaclab/test/utils/warp/test_launch_cache.py +++ b/source/isaaclab/test/utils/warp/test_launch_cache.py @@ -10,7 +10,6 @@ import isaaclab.utils.warp.launch_cache as launch_cache from isaaclab.test.utils import DeviceScope, test_devices -from isaaclab.utils.warp.capture import GraphedCallable from isaaclab.utils.warp.launch_cache import _WarpLaunchCache @@ -92,39 +91,6 @@ def operation(values, scale, device, record_cmd=False): assert len(cache._commands) == 1 -def test_a_physics_rebind_or_stop_clears_every_cache(monkeypatch): - """The recording of the environment step clears the recorded launches with its own recordings.""" - - class Device: - is_cuda = True - is_capturing = False - - class BackendManager: - def __init__(self): - self.callbacks = [] - - def register_callback(self, fn, event): - self.callbacks.append(fn) - return SimpleNamespace(deregister=lambda: None) - - def forward(self): - pass - - monkeypatch.setattr(launch_cache.wp, "get_device", lambda _: Device()) - caches = [_WarpLaunchCache("cuda:0") for _ in range(2)] - for cache in caches: - cache.launch("site", lambda device, record_cmd=False: SimpleNamespace(launch=lambda: None)) - manager = BackendManager() - GraphedCallable.watch(manager) - try: - assert _WarpLaunchCache.clear_all in manager.callbacks - for callback in manager.callbacks: - callback(None) - finally: - GraphedCallable.unwatch() - assert [len(cache._commands) for cache in caches] == [0, 0] - - @wp.kernel def _scale_into(values: wp.array(dtype=wp.float32), scale: wp.float32, out: wp.array(dtype=wp.float32)): i = wp.tid() @@ -156,6 +122,6 @@ def scale(values: wp.array, factor: float, dim: int = 4): assert scale(reallocated, 5.0) == [15.0] * 4 assert scale(reallocated, 1.0, dim=2) == [3.0, 3.0, 15.0, 15.0] assert (len(recorded), len(cache._commands)) == (1, 1) - _WarpLaunchCache.clear_all() + cache.clear() assert scale(reallocated, 2.0) == [6.0] * 4 assert len(recorded) == 2 From 908ff157c3cea07fc5e85a065c21c318e7649910 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Mon, 16 Nov 2026 23:41:47 -0800 Subject: [PATCH 25/30] Resolve flagged writes in the step graph only after writes were recorded in a graph --- .../jichuanh-warp-recording-utils.changed.rst | 6 +++--- .../isaaclab_newton/physics/newton_backend.py | 20 ++++++++++++------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst index 6196c9862b4a..9c8ee4cb58e7 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,5 +1,5 @@ -* Changed Newton to reset the solver and evaluate forward kinematics for the worlds flagged by state writes at the - start of each physics step, inside the step's CUDA graph, instead of eagerly before every step once a write was - recorded in a graph. Without flagged worlds the masked kernels do no work. +* Changed Newton, once a state write was recorded in a graph, to reset the solver and evaluate forward kinematics + for the worlds flagged by state writes at the start of each physics step, inside the step's CUDA graph, instead of + eagerly before every step. Without flagged worlds the masked kernels do no work. * Changed the per-physics-step update of the Newton articulation, rigid object and rigid object collection data to replay recorded Warp launches, which costs less host time than a new launch. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index 8b6c70096876..ef0e2c0e8f3e 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -501,8 +501,14 @@ def step(self) -> bool: actuators = self.actuators with wp.ScopedDevice(self.device): if actuators is None or actuators.is_all_graphable: - self.notify_model_changes() - self._launch(("simulate", steps), partial(self._simulate, steps)) + # A solver reset may read the world mask on the host, so it stays outside the step graph until writes + # were recorded into a graph; their replays flag worlds on the device only. + replay_writes = self.transforms_may_change_on_graph_replay + if replay_writes: + self.notify_model_changes() + else: + self.forward() + self._launch(("simulate", steps, replay_writes), partial(self._simulate, steps)) if not self.device.is_capturing: self.kinematics_dirty = False else: @@ -619,13 +625,13 @@ def _launch(self, key: str | tuple[str, int], fn: Callable[[], None]) -> None: self.graphs[key] = self.capture(fn) def _simulate(self, steps: int) -> None: - """Resolve the flagged state writes, run ``steps`` physics steps with the Newton actuators, then finish the - step. + """Resolve the flagged state writes once writes were recorded into a graph, run ``steps`` physics steps with + the Newton actuators, then finish the step. - A captured step resolves the flags on every replay, since replayed writes flag worlds on the device only; with - nothing flagged the masked kernels do no work. + A captured step then resolves the flags on every replay, since replayed writes flag worlds on the device only; + with nothing flagged the masked kernels do no work. """ - if self.device.is_capturing or self.kinematics_dirty or self.transforms_may_change_on_graph_replay: + if self.transforms_may_change_on_graph_replay: self._resolve_flagged() actuators = self.actuators self._stage_body_forces() From 90bbae9c71f2cac52cfd1b283ee63dec7b098406 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 17 Nov 2026 00:46:01 -0800 Subject: [PATCH 26/30] Set the recorded-write flag in the captured-step reset test --- source/isaaclab_newton/test/physics/test_newton_manager.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index 6b457098a1fe..1c496e09aa3e 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -613,9 +613,11 @@ def _count_flagged(flags: wp.array(dtype=wp.bool), counts: wp.array(dtype=wp.int def test_a_captured_step_resolves_the_worlds_a_replayed_write_flagged(): - """A replayed state write flags worlds on the device only; each replay of the captured step resets the solver and - evaluates FK for exactly those worlds and articulations, then clears the flags.""" + """Once a state write was recorded into a graph, its replays flag worlds on the device only; each replay of the + captured step resets the solver and evaluates FK for exactly those worlds and articulations, then clears the + flags.""" backend = _recording_backend([], captures=True) + backend.transforms_may_change_on_graph_replay = True # as recording a state write sets it resets = wp.zeros(2, dtype=wp.int32, device="cpu") fks = wp.zeros(1, dtype=wp.int32, device="cpu") ops = backend.solver_ops From 02fb34cf577ddf11446282fa1d507977d277753f Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 17 Nov 2026 11:32:52 -0800 Subject: [PATCH 27/30] Merge the plain-call cases of GraphedCallable and comment its recording steps --- source/isaaclab/isaaclab/utils/warp/capture.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index d1671f5d9bc1..2422369fc8f6 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -130,18 +130,19 @@ def __init__(self, fn: Callable[..., Any], device: wp.DeviceLike): def __call__(self, *args: Any, **kwargs: Any) -> Any: """Run the callable and return its result.""" - if capturing(self._device): - return self._fn(*args, **kwargs) - if not self._device.is_cuda: - return self._fn(*args, **kwargs) - if self._plain: + # inside another capture (its kernels join it), on a CPU device, or after an abandoned recording: run plainly + if capturing(self._device) or not self._device.is_cuda or self._plain: return self._fn(*args, **kwargs) + # one recording per argument layout: array pointers and scalar values key = _argument_key(args, kwargs) recorded = self._recordings.get(key) if recorded is None: try: + # the recording is the first run, so there is no eager warm-up whose work would run twice self._recordings[key] = recorded = self._record(args, kwargs) except _EagerCall as call: + # the recording launched nothing; the callable cannot be recorded, so it runs plainly from now on, + # starting with this call, until reset() lets it record again self._plain = True logger.warning( "'%s' calls '%s', which cannot be recorded, so it runs without a CUDA graph.", _name(self._fn), call @@ -149,6 +150,7 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any: return self._fn(*args, **kwargs) return recorded[1] graph, result = recorded + # a replay writes into the buffers the recording call returned, so it returns that same result wp.capture_launch(graph) return result @@ -168,11 +170,13 @@ def _record(self, args: tuple, kwargs: dict[str, Any]) -> tuple[wp.Graph, Any]: RuntimeError: If the callable runs work the graph cannot hold while it records (see :class:`_Recording`). """ try: + # the calls run once while they are recorded; their result is what every replay returns with _record_calls(self._device) as recording: result = self._fn(*args, **kwargs) except RuntimeError as exc: if not any(text in str(exc) for text in _UNRECORDABLE_ERRORS): raise + # a host sync or an eager torch CUDA op inside the recording: name the fix instead of torch's message raise RuntimeError( f"'{_name(self._fn)}' synchronizes the host with the device or runs a torch CUDA operation outside the" " graph while it records, so a replay would keep the value it read or skip the operation. Run the" From c0c292a9cdb517fa783160a867de26506f0ee218 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 17 Nov 2026 11:39:13 -0800 Subject: [PATCH 28/30] Say "cached launch" for the launch cache, keeping "record" for GraphedCallable --- .../jichuanh-warp-recording-utils.changed.rst | 6 +++--- source/isaaclab/isaaclab/sensors/sensor_base.py | 2 +- source/isaaclab/isaaclab/utils/warp/capture.py | 3 +++ source/isaaclab/isaaclab/utils/warp/launch_cache.py | 10 +++++----- source/isaaclab/test/utils/warp/test_launch_cache.py | 4 ++-- 5 files changed, 14 insertions(+), 11 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst index 4507d30089b5..a4e113a4dce3 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,3 +1,3 @@ -* Changed the cached Warp launches of asset data, sensors and managers to keep one recorded launch per call site: an - argument or launch dimension that changes is set on that launch in place instead of recording a new one. The - sensor clock update of each physics step replays a recorded launch. +* Changed the cached Warp launches of asset data, sensors and managers to keep one cached launch per call site: an + argument or launch dimension that changes is set on that launch in place instead of building a new one. The + sensor clock update of each physics step reuses a cached launch. diff --git a/source/isaaclab/isaaclab/sensors/sensor_base.py b/source/isaaclab/isaaclab/sensors/sensor_base.py index e966272f0bfb..4dd3ad333ad9 100644 --- a/source/isaaclab/isaaclab/sensors/sensor_base.py +++ b/source/isaaclab/isaaclab/sensors/sensor_base.py @@ -228,7 +228,7 @@ def update(self, dt: float, force_recompute: bool = False): if not self._is_initialized: return self._data_dirty |= dt > 0.0 - # Update the timestamp for the sensors, through a recorded launch: the update runs once per physics step + # Update the timestamp for the sensors, through a cached launch: the update runs once per physics step # outside the recorded parts of the step self._launch_cache.launch( "update_timestamp", diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py index 2422369fc8f6..b0f2f5d970e6 100644 --- a/source/isaaclab/isaaclab/utils/warp/capture.py +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -109,6 +109,9 @@ class GraphedCallable: and the callable records again on its next call. * Called inside a graph capture that something else started, it runs inline, so its kernels become part of that capture. + + Recording here means this callable's own CUDA graph; :func:`capturing` tells whether any graph capture is in + progress on the device, also one something else started. """ _recording: ClassVar[_Recording | None] = None diff --git a/source/isaaclab/isaaclab/utils/warp/launch_cache.py b/source/isaaclab/isaaclab/utils/warp/launch_cache.py index 88def8df99b2..f10385ce5fc6 100644 --- a/source/isaaclab/isaaclab/utils/warp/launch_cache.py +++ b/source/isaaclab/isaaclab/utils/warp/launch_cache.py @@ -16,16 +16,16 @@ class _WarpLaunchCache: - """Recorded Warp launches of code that runs outside a CUDA graph, one per call site. + """Cached Warp launches of code that runs outside a CUDA graph, one per call site. Each call site names itself with ``key``, so the cache holds at most one :class:`warp.Launch` per call site. A launch compares its arguments with those of the call site's cached launch: * Through ``wp.launch``, a changed kernel argument is set on the cached launch in place, and so is a changed launch dimension. A kernel argument that cannot be compared, such as a Warp struct, is set on every launch. A changed - kernel or launch option records the call site's launch again. + kernel or launch option builds the call site's launch again. * Through any other operation, which must accept ``device`` and ``record_cmd`` like ``wp.launch``, a changed array - or scalar argument records the call site's launch again; other arguments must stay valid until the key is + or scalar argument builds the call site's launch again; other arguments must stay valid until the key is cleared. CPU execution and graph capture invoke the operation directly. @@ -36,7 +36,7 @@ def __init__(self, device: str): self._commands: dict[object, tuple[wp.Launch, tuple]] = {} def launch(self, key: object, operation: Callable, *args, **kwargs) -> None: - """Launch through the call site's cached launch, recording it on the first call. + """Launch through the call site's cached launch, building it on the first call. Args: key: Name of the call site. @@ -79,7 +79,7 @@ def launch(self, key: object, operation: Callable, *args, **kwargs) -> None: command.launch() def clear(self, key: object | None = None) -> None: - """Remove one recorded launch or every recorded launch.""" + """Remove one cached launch or every cached launch.""" if key is None: self._commands.clear() else: diff --git a/source/isaaclab/test/utils/warp/test_launch_cache.py b/source/isaaclab/test/utils/warp/test_launch_cache.py index a9cc066cb3ca..339c6382d380 100644 --- a/source/isaaclab/test/utils/warp/test_launch_cache.py +++ b/source/isaaclab/test/utils/warp/test_launch_cache.py @@ -99,8 +99,8 @@ def _scale_into(values: wp.array(dtype=wp.float32), scale: wp.float32, out: wp.a @pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) def test_a_cached_launch_takes_changed_arguments_in_place(device, monkeypatch): - """A call site keeps one recorded launch: a reallocated array, a changed scalar and a changed dimension are set on - it in place, without recording a new launch.""" + """A call site keeps one cached launch: a reallocated array, a changed scalar and a changed dimension are set on + it in place, without building a new launch.""" recorded = [] launch = wp.launch From 3c65f77950cc8491c529a4f7e01622c7d4962272 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 17 Nov 2026 11:41:59 -0800 Subject: [PATCH 29/30] Restore the lazy finite differences of the Newton asset data, keeping only the ordering fix --- .../jichuanh-warp-recording-utils.changed.rst | 2 - .../jichuanh-warp-recording-utils.fixed.rst | 2 + .../assets/articulation/articulation_data.py | 87 +++++++++++-------- .../assets/rigid_object/rigid_object_data.py | 47 +++++----- .../rigid_object_collection_data.py | 45 +++++----- .../test/assets/test_articulation.py | 16 ---- .../test/assets/test_rigid_object.py | 13 --- 7 files changed, 101 insertions(+), 111 deletions(-) diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst index 9c8ee4cb58e7..9d94a3693d77 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,5 +1,3 @@ * Changed Newton, once a state write was recorded in a graph, to reset the solver and evaluate forward kinematics for the worlds flagged by state writes at the start of each physics step, inside the step's CUDA graph, instead of eagerly before every step. Without flagged worlds the masked kernels do no work. -* Changed the per-physics-step update of the Newton articulation, rigid object and rigid object collection data to - replay recorded Warp launches, which costs less host time than a new launch. diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst index a0fe72ea2ffd..aa3bc353ea96 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -3,3 +3,5 @@ :class:`~isaaclab.utils.warp.capture.GraphedCallable`: 15 of them raised while a graph recorded, and the others replayed the value of the recording step when they were current at recording. A recording now holds their update, so every replay recomputes them. +* Fixed the first joint and body accelerations of a Newton articulation after its joint or body ordering is set up: + they were a finite difference over the time since the simulation start instead of since the last update. diff --git a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py index 507778f9fec2..ff611ce49b60 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py @@ -158,42 +158,10 @@ def update(self, dt: float) -> None: self._sim_timestamp += dt # Replaying an outer capture of the step skips the backend's version increments, so invalidate here. self._backend_manager.backend.state_version += 1 - # finite differences advance once per physics step: computed here over the step, then read as they are; - # a zero step (the update at initialization) has no difference to take, so they keep their values - if dt == 0.0: - return - # recorded launches: the update runs once per physics step outside the recorded parts of the step - self._read_launch_cache.launch( - "joint_acc", - wp.launch, - articulation_kernels.get_joint_acc_from_joint_vel, - dim=(self._num_instances, self._num_joints), - inputs=[ - self.joint_vel.warp, - self._previous_joint_vel, - dt, - ], - outputs=[ - self._joint_acc.data, - ], - ) - self._joint_acc.timestamp = self._sim_timestamp - body_ordering = self.body_ordering - self._read_launch_cache.launch( - "body_com_acc_w", - wp.launch, - articulation_kernels.get_body_com_acc_from_body_com_vel_ordered, - dim=(self._num_instances, self._num_bodies), - inputs=[ - self._sim_bind_body_com_vel_w, - self._previous_body_com_vel, - body_ordering.user_to_backend if body_ordering is not None else None, - body_ordering is not None, - dt, - ], - outputs=[self._body_com_acc_w.data], - ) - self._body_com_acc_w.timestamp = self._sim_timestamp + # Trigger an update of the joint and body com acceleration buffers at a higher frequency + # since we do finite differencing. + self.joint_acc + self.body_com_acc_w def _update_body_state(self) -> None: """Resolve shared FK, then refresh this view's reordered body state after a manual write.""" @@ -877,6 +845,24 @@ def body_com_acc_w(self) -> ProxyArray: All values are relative to the world. """ + if self._body_com_acc_w.timestamp < self._sim_timestamp: + # Finite-difference over the elapsed time, which spans the decimation when Newton owns it. + time_elapsed = self._sim_timestamp - self._body_com_acc_w.timestamp + body_ordering = self.body_ordering + wp.launch( + articulation_kernels.get_body_com_acc_from_body_com_vel_ordered, + dim=(self._num_instances, self._num_bodies), + device=self.device, + inputs=[ + self._sim_bind_body_com_vel_w, + self._previous_body_com_vel, + body_ordering.user_to_backend if body_ordering is not None else None, + body_ordering is not None, + time_elapsed, + ], + outputs=[self._body_com_acc_w.data], + ) + self._body_com_acc_w.timestamp = self._sim_timestamp return self._body_com_acc_w_ta @property @@ -1130,6 +1116,23 @@ def joint_acc(self) -> ProxyArray: Shape is (num_instances, num_joints), dtype = wp.float32. In torch this resolves to (num_instances, num_joints). """ + if self._joint_acc.timestamp < self._sim_timestamp: + # note: we use finite differencing to compute acceleration + time_elapsed = self._sim_timestamp - self._joint_acc.timestamp + wp.launch( + articulation_kernels.get_joint_acc_from_joint_vel, + dim=(self._num_instances, self._num_joints), + inputs=[ + self.joint_vel.warp, + self._previous_joint_vel, + time_elapsed, + ], + outputs=[ + self._joint_acc.data, + ], + device=self.device, + ) + self._joint_acc.timestamp = self._sim_timestamp return self._joint_acc_ta """ @@ -1777,12 +1780,18 @@ def _create_buffers(self) -> None: # -- com frame w.r.t. world frame self._root_com_pose_w = TimestampedBuffer() self._body_com_pose_w = TimestampedBuffer() - self._body_com_acc_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device)) + # a finite difference, which update() takes every physics step: a recording that reads it must not hold it + self._body_com_acc_w = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device), update_in_graph=False + ) # -- derived properties (these are cached to avoid repeated memory allocations) self._projected_gravity_b = TimestampedBuffer() self._heading_w = TimestampedBuffer() # -- joint state - self._joint_acc = TimestampedBuffer(wp.zeros(joint_shape, dtype=wp.float32, device=device)) + # a finite difference, which update() takes every physics step: a recording that reads it must not hold it + self._joint_acc = TimestampedBuffer( + wp.zeros(joint_shape, dtype=wp.float32, device=device), update_in_graph=False + ) self._joint_pos_user: wp.array | None = None self._joint_vel_user: wp.array | None = None self._joint_stiffness_user: wp.array | None = None @@ -1961,6 +1970,8 @@ def _configure_joint_ordering_buffers(self) -> None: self._previous_joint_vel.assign(self._sim_bind_joint_vel) self._actuator_stiffness.assign(self._sim_bind_joint_stiffness_sim) self._actuator_damping.assign(self._sim_bind_joint_damping_sim) + # the ordering does not make the finite difference stale: keeping its timestamp, the next read differences + # over the time since the last one, not since the simulation started self._joint_acc.data.zero_() reset_timestamps([self._joint_pos_limits]) diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py index bc0ef5149816..5cb765f18f21 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object/rigid_object_data.py @@ -128,26 +128,9 @@ def update(self, dt: float) -> None: self._sim_timestamp += dt # Replaying an outer capture of the step skips the backend's version increments, so invalidate here. self._backend_manager.backend.state_version += 1 - # finite differences advance once per physics step: computed here over the step, then read as they are; - # a zero step (the update at initialization) has no difference to take, so they keep their values - if dt == 0.0: - return - # a recorded launch: the update runs once per physics step outside the recorded parts of the step - self._read_launch_cache.launch( - "body_com_acc_w", - wp.launch, - shared_kernels.derive_body_acceleration_from_body_com_velocities, - dim=(self._num_instances, 1), - inputs=[ - self._sim_bind_body_com_vel_w, - dt, - self._previous_body_com_vel, - ], - outputs=[ - self._body_com_acc_w.data, - ], - ) - self._body_com_acc_w.timestamp = self._sim_timestamp + # Trigger an update of the body com acceleration buffer at a higher frequency + # since we do finite differencing. + self.body_com_acc_w def _reset_pose(self) -> None: """Invalidate pose-dependent caches after an authoritative state write.""" @@ -413,6 +396,25 @@ def body_com_acc_w(self) -> ProxyArray: Shape is (num_instances, 1), dtype = wp.spatial_vectorf. In torch this resolves to (num_instances, 1, 6). This quantity is the acceleration of the rigid bodies' center of mass frame relative to the world. """ + if self._body_com_acc_w.timestamp < self._sim_timestamp: + # Finite-difference over the elapsed time, which spans the decimation when Newton owns it. + time_elapsed = self._sim_timestamp - self._body_com_acc_w.timestamp + wp.launch( + shared_kernels.derive_body_acceleration_from_body_com_velocities, + dim=(self._num_instances, 1), + device=self.device, + inputs=[ + self._sim_bind_body_com_vel_w, + time_elapsed, + self._previous_body_com_vel, + ], + outputs=[ + self._body_com_acc_w.data, + ], + ) + # set the buffer data and timestamp + self._body_com_acc_w.timestamp = self._sim_timestamp + # update the previous velocity return self._body_com_acc_w_ta @property @@ -906,7 +908,10 @@ def _create_buffers(self) -> None: self._heading_w = TimestampedBuffer() # -- com frame w.r.t. world frame self._root_com_pose_w = TimestampedBuffer() - self._body_com_acc_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device)) + # a finite difference, which update() takes every physics step: a recording that reads it must not hold it + self._body_com_acc_w = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device), update_in_graph=False + ) self._body_com_pose_b = TimestampedBuffer() # Empty memory pre-allocations self._root_state_w = None diff --git a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py index 5e4c8746c622..f5ef391164f0 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py @@ -132,26 +132,9 @@ def update(self, dt: float) -> None: self._sim_timestamp += dt # Replaying an outer capture of the step skips the backend's version increments, so invalidate here. self._backend_manager.backend.state_version += 1 - # finite differences advance once per physics step: computed here over the step, then read as they are; - # a zero step (the update at initialization) has no difference to take, so they keep their values - if dt == 0.0: - return - # a recorded launch: the update runs once per physics step outside the recorded parts of the step - self._read_launch_cache.launch( - "body_com_acc_w", - wp.launch, - shared_kernels.derive_body_acceleration_from_body_com_velocities, - dim=(self.num_instances, self.num_bodies), - inputs=[ - self.body_com_vel_w.warp, - dt, - self._previous_body_com_vel, - ], - outputs=[ - self._body_com_acc_w.data, - ], - ) - self._body_com_acc_w.timestamp = self._sim_timestamp + # Trigger an update of the body com acceleration buffer at a higher frequency + # since we do finite differencing. + self.body_com_acc_w def _reset_pose(self) -> None: """Invalidate pose-dependent caches after an authoritative state write.""" @@ -355,6 +338,23 @@ def body_com_acc_w(self) -> ProxyArray: (num_instances, num_bodies, 6). This quantity is the acceleration of the rigid bodies' center of mass frame relative to the world. """ + if self._body_com_acc_w.timestamp < self._sim_timestamp: + # Finite-difference over the elapsed time, which spans the decimation when Newton owns it. + time_elapsed = self._sim_timestamp - self._body_com_acc_w.timestamp + wp.launch( + shared_kernels.derive_body_acceleration_from_body_com_velocities, + dim=(self.num_instances, self.num_bodies), + device=self.device, + inputs=[ + self.body_com_vel_w.warp, + time_elapsed, + self._previous_body_com_vel, + ], + outputs=[ + self._body_com_acc_w.data, + ], + ) + self._body_com_acc_w.timestamp = self._sim_timestamp return self._body_com_acc_w_ta @property @@ -734,7 +734,10 @@ def _create_buffers(self) -> None: self._body_com_pose_b = TimestampedBuffer(wp.empty(body_shape, dtype=wp.transformf, device=device)) # -- com frame w.r.t. world frame self._body_com_pose_w = TimestampedBuffer(wp.empty(body_shape, dtype=wp.transformf, device=device)) - self._body_com_acc_w = TimestampedBuffer(wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device)) + # a finite difference, which update() takes every physics step: a recording that reads it must not hold it + self._body_com_acc_w = TimestampedBuffer( + wp.zeros(body_shape, dtype=wp.spatial_vectorf, device=device), update_in_graph=False + ) # -- combined state (these are cached as they concatenate) self._body_state_w = TimestampedBuffer(wp.empty(body_shape, dtype=vec13f, device=device)) self._body_link_state_w = TimestampedBuffer(wp.empty(body_shape, dtype=vec13f, device=device)) diff --git a/source/isaaclab_newton/test/assets/test_articulation.py b/source/isaaclab_newton/test/assets/test_articulation.py index 03881312fe32..cdac5ca0216f 100644 --- a/source/isaaclab_newton/test/assets/test_articulation.py +++ b/source/isaaclab_newton/test/assets/test_articulation.py @@ -931,22 +931,6 @@ def scene(composite_scene: _Scene) -> _Scene: return composite_scene -def test_zero_step_update_keeps_the_accelerations(scene: _Scene) -> None: - """``update(0.0)``, which an articulation runs at initialization, takes no finite difference (a division by zero). - - The joint and body accelerations keep their values, as main's lazy finite difference gives no NaN before the first - step either. - """ - articulation = scene.articulations["floating"] - scene.step("floating") - joint_acc = articulation.data.joint_acc.torch.clone() - body_com_acc_w = articulation.data.body_com_acc_w.torch.clone() - - articulation.update(0.0) - torch.testing.assert_close(articulation.data.joint_acc.torch, joint_acc) - torch.testing.assert_close(articulation.data.body_com_acc_w.torch, body_com_acc_w) - - def _model_attribute(articulation: Articulation, name: str) -> torch.Tensor: """Read one live Newton model attribute through the articulation's view, in backend order.""" return wp.to_torch(articulation.root_view.get_attribute(name, articulation._backend_manager.backend.model))[:, 0] diff --git a/source/isaaclab_newton/test/assets/test_rigid_object.py b/source/isaaclab_newton/test/assets/test_rigid_object.py index 08a3a7ccd69d..7257c28f8a0f 100644 --- a/source/isaaclab_newton/test/assets/test_rigid_object.py +++ b/source/isaaclab_newton/test/assets/test_rigid_object.py @@ -380,19 +380,6 @@ def scene(shared_scene: _Scene) -> _Scene: return shared_scene -def test_zero_step_update_keeps_the_accelerations(scene: _Scene) -> None: - """``update(0.0)``, which the assets run at initialization, takes no finite difference (a division by zero). - - The body accelerations keep their values, as main's lazy finite difference gives no NaN before the first step - either. - """ - scene.step() - for asset in (scene.cube, scene.collection): - body_com_acc_w = asset.data.body_com_acc_w.torch.clone() - asset.update(0.0) - torch.testing.assert_close(asset.data.body_com_acc_w.torch, body_com_acc_w) - - @pytest.mark.isaacsim_ci def test_external_force_on_single_body(scene: _Scene) -> None: """A permanent wrench reaches the solver in the local and the global frame, and a reset clears it. From 741e29de8c6bdb48e14048855af02e982ce8d4e1 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 17 Nov 2026 12:25:22 -0800 Subject: [PATCH 30/30] Keep a solver reset that reads the host before the step graph, also after recorded state writes --- .../jichuanh-warp-recording-utils.changed.rst | 3 ++- .../physics/coupling/coupler.py | 13 +++++++++-- .../isaaclab_newton/physics/newton_backend.py | 12 +++++++--- .../isaaclab_newton/physics/newton_solver.py | 6 +++++ .../test/physics/test_newton_manager.py | 22 +++++++++++++++++++ 5 files changed, 50 insertions(+), 6 deletions(-) diff --git a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst index 9d94a3693d77..b0da6d4d15c7 100644 --- a/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -1,3 +1,4 @@ * Changed Newton, once a state write was recorded in a graph, to reset the solver and evaluate forward kinematics for the worlds flagged by state writes at the start of each physics step, inside the step's CUDA graph, instead of - eagerly before every step. Without flagged worlds the masked kernels do no work. + eagerly before every step. Without flagged worlds the masked kernels do no work. A solver whose reset reads the + world mask on the host, such as an MPM coupler with one world, still resets before every step. diff --git a/source/isaaclab_newton/isaaclab_newton/physics/coupling/coupler.py b/source/isaaclab_newton/isaaclab_newton/physics/coupling/coupler.py index a5132eb7005a..f78a932e8530 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/coupling/coupler.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/coupling/coupler.py @@ -356,11 +356,15 @@ def create_collision_pipeline(self, **kwargs) -> CollisionPipeline: kwargs["shape_pairs_filtered"] = self.native.view(self.cfg.outer_contact_entry).shape_contact_pairs return super().create_collision_pipeline(**kwargs) + @property + def reset_is_capturable(self) -> bool: + """False for a single world with an MPM entry, whose :meth:`reset` reads the world mask on the host.""" + return not self._resets_single_mpm_world() + def reset(self, state: State, world_mask: wp.array) -> None: """Reset every entry for masked worlds, promoting a selected single MPM world to the full-reset path.""" solver = self.native - has_mpm_entry = any(isinstance(entry.solver_cfg, MPMSolverCfg) for entry in self.cfg.entries) - if solver.model.world_count == 1 and has_mpm_entry: + if self._resets_single_mpm_world(): selected = world_mask.numpy() if not selected.any(): return @@ -369,6 +373,11 @@ def reset(self, state: State, world_mask: wp.array) -> None: return solver.reset(state, world_mask=world_mask, flags=0) + def _resets_single_mpm_world(self) -> bool: + """Whether the model has one world and an MPM entry, whose reset reads the world mask on the host.""" + has_mpm_entry = any(isinstance(entry.solver_cfg, MPMSolverCfg) for entry in self.cfg.entries) + return self.native.model.world_count == 1 and has_mpm_entry + def check_step(self, captured: bool, debug: bool) -> None: """Raise asynchronous failures, and log diagnostics, of every entry's solver.""" for entry in self.entries.values(): diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py index ef0e2c0e8f3e..cf3662b81999 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py @@ -355,6 +355,11 @@ def forward(self) -> None: # a capture records the work without running it self.kinematics_dirty = False + def _resolves_in_step_graph(self) -> bool: + """Whether the step graph resolves the flagged worlds: once state writes were recorded into a graph, unless + the solver's reset reads the host, which then resolves before the step (see :meth:`forward`).""" + return self.transforms_may_change_on_graph_replay and self.solver_ops.reset_is_capturable + def _resolve_flagged(self) -> None: """Reset solver internals and evaluate FK for the worlds and articulations flagged on the device, then clear the device flags.""" @@ -502,8 +507,9 @@ def step(self) -> bool: with wp.ScopedDevice(self.device): if actuators is None or actuators.is_all_graphable: # A solver reset may read the world mask on the host, so it stays outside the step graph until writes - # were recorded into a graph; their replays flag worlds on the device only. - replay_writes = self.transforms_may_change_on_graph_replay + # were recorded into a graph; their replays flag worlds on the device only. A reset that reads the + # host (reset_is_capturable False) always stays outside, as before. + replay_writes = self._resolves_in_step_graph() if replay_writes: self.notify_model_changes() else: @@ -631,7 +637,7 @@ def _simulate(self, steps: int) -> None: A captured step then resolves the flags on every replay, since replayed writes flag worlds on the device only; with nothing flagged the masked kernels do no work. """ - if self.transforms_may_change_on_graph_replay: + if self._resolves_in_step_graph(): self._resolve_flagged() actuators = self.actuators self._stage_body_forces() diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_solver.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_solver.py index b6061c4f241b..823c1a24a81a 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_solver.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_solver.py @@ -173,6 +173,12 @@ def step( def post_step(self, state: State) -> None: """Publish derived state once per physics step, after the substeps.""" + @property + def reset_is_capturable(self) -> bool: + """Whether :meth:`reset` reads no host data, so a recorded step graph can hold it. A reset that reads the + world mask on the host runs before the step graph instead, as without recorded state writes.""" + return True + def reset(self, state: State, world_mask: wp.array) -> None: """Clear solver-owned history for the worlds of a ``(world_count + 1,)`` mask, keeping authored joint state.""" self.native.reset(state, world_mask=world_mask, flags=0) diff --git a/source/isaaclab_newton/test/physics/test_newton_manager.py b/source/isaaclab_newton/test/physics/test_newton_manager.py index 1c496e09aa3e..1c7237de12f7 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -638,6 +638,28 @@ def test_a_captured_step_resolves_the_worlds_a_replayed_write_flagged(): assert not backend.world_mask.numpy().any() and not backend.fk_mask.numpy().any() +def test_a_reset_that_reads_the_host_resolves_before_the_captured_step(): + """A solver reset that reads the world mask on the host, such as an MPM coupler with one world, runs before the + step graph on every step, also once state writes were recorded; the step graph never holds it.""" + backend = _recording_backend([], captures=True) + backend.transforms_may_change_on_graph_replay = True # as recording a state write sets it + ops = backend.solver_ops + type(ops).reset_is_capturable = property(lambda self: False) + resets = [] + ops.reset = lambda state, worlds: resets.append(worlds.numpy().tolist()) # a host read + ops.eval_fk = lambda state, worlds, articulations: None + + backend.step() # resolves eagerly with nothing flagged, then captures the step without the reset + assert backend.graphs + for _ in range(2): + backend.world_mask.assign(wp.array([True, False], dtype=wp.bool, device="cpu")) + backend.step() + + # one eager reset per step, each reading the flags of that step + assert resets == [[False, False], [True, False], [True, False]] + assert not backend.world_mask.numpy().any() + + def test_forward_recorded_in_an_abandoned_capture_leaves_the_flags_pending(): """FK recorded in a capture runs only when the graph is launched, so a capture that is abandoned leaves the host flag and the device flags pending for the next eager forward."""