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..7dc218f9f3fd --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.added.rst @@ -0,0 +1,14 @@ +* 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 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. +* 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 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/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..a4e113a4dce3 --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -0,0 +1,3 @@ +* 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/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..e391d32a16c4 --- /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 in every CUDA graph capture that reads the + 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/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/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..58c3d7389b40 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_method 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,23 @@ 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 its reset goes through :meth:`_reset_unrecordable_state`.""" + for state in (sa, sb): + if act.is_graphable(): + state.reset(per_dof_mask) + else: + 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/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/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 diff --git a/source/isaaclab/isaaclab/sensors/sensor_base.py b/source/isaaclab/isaaclab/sensors/sensor_base.py index 6f4d15db2768..4dd3ad333ad9 100644 --- a/source/isaaclab/isaaclab/sensors/sensor_base.py +++ b/source/isaaclab/isaaclab/sensors/sensor_base.py @@ -30,6 +30,8 @@ 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.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 @@ -217,7 +219,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): @@ -226,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 cached 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=[ @@ -238,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: @@ -465,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.""" @@ -478,7 +483,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.""" - if not self._data_dirty: + # 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() @@ -492,7 +499,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 + 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 04c360494b36..3dbe6fb06207 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 capture_in_progress + def reset_timestamps(buffers: Iterable["TimestampedBuffer | None"]) -> None: """Invalidate cached values, skipping unallocated or unaffected buffers. @@ -19,16 +20,43 @@ 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. - """ - data: Any = None - """Cached array, native-format struct, or grouped data; None before allocation.""" + 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``. + """ - timestamp: float = -1.0 - """Source timestamp represented by the data; -1 marks it stale.""" + __slots__ = ("data", "update_in_graph", "_timestamp") + + 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 graph capture that reads the data updates it. Defaults to True. + """ + self.data = data + self.update_in_graph = update_in_graph + self._timestamp = timestamp + + @property + def timestamp(self) -> float: + """Source timestamp represented by the data; -1 marks it stale.""" + 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 diff --git a/source/isaaclab/isaaclab/utils/warp/capture.py b/source/isaaclab/isaaclab/utils/warp/capture.py new file mode 100644 index 000000000000..b0f2f5d970e6 --- /dev/null +++ b/source/isaaclab/isaaclab/utils/warp/capture.py @@ -0,0 +1,345 @@ +# 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 a CUDA graph and replays it. +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 + +import contextlib +import functools +import logging +from collections.abc import Callable +from typing import 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 + +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. + + 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``. + """ + 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) + + +class _EagerCall(BaseException): + """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. + """ + + 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]: + """Mark a method that cannot be recorded, such as one that reads device data on the host or runs torch work. + + 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 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: + 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 + + +class GraphedCallable: + """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. + * 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. + * A callable on a CPU device always runs eagerly. + * 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. + + 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 + """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 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 called an :func:`eager_method` method while recording, so it runs plainly.""" + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + """Run the callable and return its result.""" + # 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 + ) + 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 + + def reset(self) -> None: + """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) + self._recordings.clear() + + 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 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: + # 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" + f" work in a method marked with @eager_method. ({exc})" + ) from exc + return recording.graph, result + + +@contextlib.contextmanager +def _record_calls(device: wp.Device): + """Record the calls made inside as a CUDA graph; the recording is their first run. + + Yields: + The recording, whose graph replays the calls. + """ + recording = _Recording(device) + enclosing, GraphedCallable._recording = GraphedCallable._recording, recording + try: + with wp.ScopedStream(recording.capture_stream): + recording.begin() + try: + yield recording + except BaseException: + recording.abort() + raise + recording.end() + finally: + 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. + + 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 + 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.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) + + def abort(self) -> None: + """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() + 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) + + +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. + + 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() + ) + + +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 + # 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(_value_key(item) for item in value) + return id(value) diff --git a/source/isaaclab/isaaclab/utils/warp/launch_cache.py b/source/isaaclab/isaaclab/utils/warp/launch_cache.py index 785fb683979c..f10385ce5fc6 100644 --- a/source/isaaclab/isaaclab/utils/warp/launch_cache.py +++ b/source/isaaclab/isaaclab/utils/warp/launch_cache.py @@ -4,37 +4,104 @@ # SPDX-License-Identifier: BSD-3-Clause from collections.abc import Callable +from typing import Any 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. + """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 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 builds 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. """ 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]] = {} def launch(self, key: object, operation: Callable, *args, **kwargs) -> None: + """Launch through the call site's cached launch, building 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: - """Remove one recorded launch or every recorded launch.""" + """Remove one cached launch or every cached launch.""" if key is None: self._commands.clear() else: self._commands.pop(key, None) + + +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/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..dda8ce0f2432 100644 --- a/source/isaaclab/test/assets/contract/test_articulation_contract.py +++ b/source/isaaclab/test/assets/contract/test_articulation_contract.py @@ -25,8 +25,10 @@ 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.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 +412,53 @@ 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 + + +@_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. + """ + 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 + 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) + + @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_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 07c404d7e79f..73b2ff9c4517 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 @@ -20,6 +21,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 +177,81 @@ 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) + + +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_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.""" + 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.""" + + 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): + """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.""" + 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/utils/test_timestamped_buffer.py b/source/isaaclab/test/utils/test_timestamped_buffer.py new file mode 100644 index 000000000000..ec9194e65a75 --- /dev/null +++ b/source/isaaclab/test/utils/test_timestamped_buffer.py @@ -0,0 +1,112 @@ +# 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 inside graph captures.""" + +from __future__ import annotations + +import contextlib + +import pytest +import warp as wp + +from isaaclab.test.utils import DeviceScope, test_devices +from isaaclab.utils.buffers import TimestampedBuffer +from isaaclab.utils.warp.capture import GraphedCallable + +pytestmark = pytest.mark.unit + + +@wp.kernel +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: + """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.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) -> wp.array: + if self._value.timestamp < self.timestamp: + 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 + + +@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 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() + raise RuntimeError("abandon the capture") + assert value.read().numpy()[0] == 6.0 + + +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +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.""" + value = _LazyValue(device) + value.read() + + def read_then_raise(): + value.read() + raise RuntimeError("abandon the recording") + + 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.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() + graph = _capture(device, value.read) + value.timestamp += 0.01 + wp.capture_launch(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..341c637d8227 --- /dev/null +++ b/source/isaaclab/test/utils/warp/test_capture.py @@ -0,0 +1,356 @@ +# 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 + +import logging + +import pytest +import torch +import warp as wp + +from isaaclab.utils.warp.capture import ( + GraphedCallable, + capturing, + 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 len(graphed._recordings) + + +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 + + +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() + + +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_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() + 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_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) + + graphed.reset() + graphed(values) + graphed(values) + assert (fn.calls, _read(values), _num_graphs(graphed)) == (2, [3], 1) + + +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) + + assert (on_cpu.calls, _read(cpu_values), _num_graphs(cpu_graphed)) == (2, [2], 0) + + +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), _EagerAffine(1, 10), _Affine(3, 0) + + def body(values: wp.array) -> wp.array: + before(values) + between(values) + return after(values) + + graphed = GraphedCallable(body, DEVICE) + values = wp.ones(1, dtype=wp.int32, device=DEVICE) + + 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) + # 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.__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 = _EagerAffine(1, 10) + + def body(values: wp.array): + try: + fn(values) + except Exception: # noqa: BLE001 + pytest.fail("the abandonment must pass an `except Exception` handler") + + graphed = GraphedCallable(body, DEVICE) + values = wp.zeros(1, dtype=wp.int32, device=DEVICE) + graphed(values) + assert (_read(values), fn.calls, _num_graphs(graphed)) == ([10], 1, 0) + + +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] + + def body(values: wp.array): + fn(values) + if uses_eager[0]: + eager_fn(values) + + graphed = GraphedCallable(body, DEVICE) + values = wp.ones(1, dtype=wp.int32, device=DEVICE) + graphed(values) # abandoned, then plain: 1 * 2 + 10 = 12 + uses_eager[0] = False + graphed.reset() + graphed(values) # records: 24 + graphed(values) # replays: 48 + assert (_read(values), fn.calls, _num_graphs(graphed)) == ([48], 3, 1) + + +def test_an_eager_call_of_a_nested_callable_makes_both_run_plainly(): + 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) + + outer(values) + outer(values) + # 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) + + +@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 wp.ScopedDevice(device), wp.ScopedCapture(): + assert capturing(device) + with pytest.raises(RuntimeError, match="no GraphedCallable started"): + fn(values) + assert not capturing(device) + assert fn.calls == 0 + + +def test_callable_raising_while_recording_ends_the_capture(): + """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) + 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 + assert _read(values) == [1] + graphed(values) + assert (_read(values), _num_graphs(graphed)) == ([2], 1) + + +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_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() + + def writer(): + fn(values) + registry.add(7) + + graphed = GraphedCallable(writer, DEVICE) + for _ in range(3): + graphed() + assert (registry.changes, _read(values), _num_graphs(graphed)) == ([7, 7, 7], [3], 0) + + +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 _HostWork().total(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: _HostWork().add(values, 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..9bfa4cd3c42a --- /dev/null +++ b/source/isaaclab/test/utils/warp/test_capture_kit.py @@ -0,0 +1,31 @@ +# 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(): + 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" diff --git a/source/isaaclab/test/utils/warp/test_launch_cache.py b/source/isaaclab/test/utils/warp/test_launch_cache.py index a5d90d6c7cac..339c6382d380 100644 --- a/source/isaaclab/test/utils/warp/test_launch_cache.py +++ b/source/isaaclab/test/utils/warp/test_launch_cache.py @@ -3,7 +3,13 @@ # # 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.launch_cache import _WarpLaunchCache @@ -61,3 +67,61 @@ 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 + + +@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 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 + + 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) + cache.clear() + assert scale(reallocated, 2.0) == [6.0] * 4 + assert len(recorded) == 2 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..b0da6d4d15c7 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.changed.rst @@ -0,0 +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. 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/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..aa3bc353ea96 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -0,0 +1,7 @@ +* 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. +* 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.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..ff611ce49b60 100644 --- a/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py +++ b/source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py @@ -1780,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 @@ -1964,7 +1970,10 @@ 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]) + # 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]) def _configure_body_ordering_buffers(self) -> None: """Allocate or release buffers owned only by nonidentity body ordering.""" @@ -1988,12 +1997,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..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 @@ -908,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.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..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 @@ -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/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 c82797432abe..cf3662b81999 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.""" @@ -237,7 +237,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 @@ -348,14 +348,26 @@ def forward(self) -> None: self.notify_model_changes() if not (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 _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.""" + 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: @@ -493,12 +505,22 @@ 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._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. 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: + self.forward() + self._launch(("simulate", steps, replay_writes), 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) @@ -609,7 +631,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 once writes were recorded into a graph, run ``steps`` physics steps with + the Newton actuators, then finish the step. + + 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._resolves_in_step_graph(): + 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_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 3ccd63d0c9bc..1c7237de12f7 100644 --- a/source/isaaclab_newton/test/physics/test_newton_manager.py +++ b/source/isaaclab_newton/test/physics/test_newton_manager.py @@ -605,6 +605,79 @@ 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(): + """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 + 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_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.""" + 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 = [], [] 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..91a3b81a0246 100644 --- a/source/isaaclab_newton/test/physics/test_newton_solver_reset.py +++ b/source/isaaclab_newton/test/physics/test_newton_solver_reset.py @@ -27,6 +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 def _generate_single_joint_articulations(num_articulations: int, device: str) -> Articulation: @@ -58,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. @@ -127,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) @@ -136,3 +152,83 @@ 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("use_cuda_graph", [False, True], ids=["eager_step", "captured_step"]) +@pytest.mark.parametrize("device", test_devices(DeviceScope.DEFAULT_CUDA)) +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) + 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) + + reset = GraphedCallable(reset_env_0, device) + try: + with patch.object(NewtonBackend, "_run_solver_substeps", _no_substeps): + backend.invalidate_graph() + 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) + 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() + 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: + 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) + 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: + reset.reset() + read.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..fc3dfc7727f8 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -0,0 +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. 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/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_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..11835bef5c2b --- /dev/null +++ b/source/isaaclab_physx/changelog.d/jichuanh-warp-recording-utils.fixed.rst @@ -0,0 +1,6 @@ +* 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, 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. 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..70a5e4d88add 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)) @@ -1687,11 +1690,20 @@ 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 - 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)) @@ -1800,9 +1812,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 @@ -1884,7 +1901,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/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