Skip to content

Commit 3e5ceeb

Browse files
authored
[Warp] Part 1a/8: Resolve id and mask selections through shared helpers (#8821)
## Review Map - A number is one feature and its letters are that feature's PRs, in merge order; an arrow points from a PR to the PRs that build on it. - A stacked PR's page shows the cumulative diff of its dependency chain; the "Exact changes" link opens that PR's Files changed page on its own changes (parent head to PR head). #6646's head merges `main` for one conflict, so its link also shows `main`'s #8928. - #8783 and #6607 are no longer part of the series. | PR | Status | Depends on | Exact changes | |---|---|---|---| | 📌 #8821 Part 1a/8: shared id and mask helpers, mask writers without host sync | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/8821?label=) | — | — | | #8824 Part 1b/8: PhysX tendon mask setters through the masks | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/8824?label=) | 1a | [link](https://github.com/isaac-sim/IsaacLab/pull/8824/changes/84470f4c0c5dfe1905dd1b5d822f6faf50832d4d..2fbbcc5a98a91f34c129f1ce65b227201ec50f60) | | #6646 Part 2a/8: reset only the masked environments | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/6646?label=) | 1a | [link](https://github.com/isaac-sim/IsaacLab/pull/6646/changes/84470f4c0c5dfe1905dd1b5d822f6faf50832d4d..41ed0c0775175ad2f76db6bb9c31202d80e1519b) | | #8997 Part 2b/8: actuator networks reset by mask | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/8997?label=) | 2a | [link](https://github.com/isaac-sim/IsaacLab/pull/8997/changes/41ed0c0775175ad2f76db6bb9c31202d80e1519b..cb14223b1d957f7fd8ac232ea50605618ce53de3) | | #8856 Part 3a/8: env origins as a ProxyArray, `SceneEntityCfg` Warp selections | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/8856?label=) | 2a | [link](https://github.com/isaac-sim/IsaacLab/pull/8856/changes/41ed0c0775175ad2f76db6bb9c31202d80e1519b..f8944ad680d2bb4b09b13d2adb4b740eafe7b363) | | #8228 Part 3b/8: ray caster camera frames as a ProxyArray, Rough velocity tasks (re-cut not pushed yet) | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/8228?label=) | 3a | — | | #8998 Part 4a/8: recording utilities, lazy buffers correct under recording | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/8998?label=) | 2b, 3a | [link](https://github.com/isaac-sim/IsaacLab/pull/8998/changes/9d74ad2de08a152312833dbe3ad9260b02f683b0..0e2a77d842051fb3946feb988f2e14d010aac3fb) | | Parts 4b-4h/8: the Warp frontend on the stable managers (not opened) | — | 4a | — | | Part 5/8: OVPhysX on the Warp frontend (not opened) | — | 4h | — | | Part 6/8: Warp noise model with an additive bias (not opened) | — | 4h | — | | #7012 Part 7/8: `--video` on the Warp frontend (re-cut not pushed yet) | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/7012?label=) | 4h | — | | Part 8a/8: Direct Warp environment step (not opened) | — | 5, 7 | — | | #6582 Part 8b/8: Shadow Hand Warp twin, Allegro twin fix (re-cut not pushed yet) | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/6582?label=) | 8a | — | | #8861 [DO-NOT-MERGE] all parts combined for review | ![](https://img.shields.io/github/pulls/detail/state/isaac-sim/IsaacLab/8861?label=) | ALL | — | ```mermaid --- config: look: neo flowchart: curve: basis --- flowchart TD A1("📌 <b>#8821</b> · 1a<br/>id/mask helpers") B1("<b>#8824</b> · 1b<br/>PhysX tendon masks") A2("<b>#6646</b> · 2a<br/>masked resets") B2("<b>#8997</b> · 2b<br/>actuator net reset") A3("<b>#8856</b> · 3a<br/>env origins, Warp selections") B3("<b>#8228</b> · 3b<br/>Rough velocity") A4("<b>#8998</b> · 4a<br/>recording utilities") P4("4b-4h<br/>Warp frontend on the stable managers") P5("5<br/>OVPhysX") P6("6<br/>noise model") P7("<b>#7012</b> · 7<br/>--video") A8("8a<br/>Direct env step") B8("<b>#6582</b> · 8b<br/>Shadow twin") A1 --> B1 A1 --> A2 A2 --> B2 A2 --> A3 A3 --> B3 B2 --> A4 A3 --> A4 A4 --> P4 P4 --> P5 P4 --> P6 P4 --> P7 P5 --> A8 P7 --> A8 A8 --> B8 style A1 stroke-width:3px ``` ## Summary Id and mask selections in the Newton, OVPhysX and PhysX assets, the camera and the wrench composer resolve through main's `resolve_1d_mask` and a new `resolve_ids`, both in `isaaclab.utils.warp.memory`, instead of hand-written copies (−907 / +410 source lines). Newton mask writers that converted masks to ids now write through the mask: the fixed-tendon setters are 2.7-5.4x faster. # Description **Update (2026-11-12):** a Newton model-property write recorded into a graph capture now refreshes the solver on every replay, not only the first (`NewtonManager.add_model_change` records the refresh inside a capture); merged main `616f517707d`. **Update (2026-11-10):** a mask longer than its destination raises instead of being written past the end (the Newton fixed-tendon writer launches over the mask), and the PhysX and rigid-object selection docstrings say ids come first, as `resolve_ids` does. The `all_ids=slice(None)` form of `resolve_ids` leaves this PR for the part that first uses it. ## 1. Changes 1. **Helpers** (`isaaclab/utils/warp/memory.py`, next to main's `resolve_1d_mask`): new `resolve_ids` (ids or a boolean mask → ids on the device of the caller's all-ids array; callers that need contiguous int32 ids pass the result through main's `resolve_1d_indices`, as main's indexed writers do). `resolve_1d_mask` takes `scratch_mask` as optional again: a mask passed without one is used as given when it is not longer than the destination, so a shorter mask writes only the rows it covers, as main's Newton mask writers do; a longer mask raises with or without a scratch mask. New `write_2d_with_mask` writes a scalar or a 2-D array into a buffer where an env mask and an item mask are both true, launching main's masked copy and fill kernels over the mask lengths on the output's device (torch vector data with strided components goes through scalar views, without a copy); the Newton articulation and collection mask writers use it. 2. **All assets, `Camera` and `WrenchComposer` use them**, so every selection accepts the same inputs: integer sequences, negative-step slices, ids on another device. A `ProxyArray` raises `TypeError`. 3. **Newton writes without a host sync:** the fixed-tendon mask setters write through the masks; joint-coordinate writes reuse a scratch mask. The `RigidObjectCollection` mask writers (main's, since #8870) launch over the mask lengths like the other Newton mask writers, so a mask shorter than the asset dimension writes only the rows it covers. 4. **Fixes:** the deformable `write_nodal_*_to_sim_mask` writers raised whenever `env_mask` was given (OVPhysX, PhysX); the Newton fixed-tendon mask setters accepted data of the wrong shape; a Newton model-property write recorded into a graph capture (such as the fixed-tendon mask writer, now capturable) left the solver on the first replay's values, because `NewtonManager.add_model_change` only queued the refresh on the host. ## 2. Performance (MEASURED) 8gpu L40, Newton contract mocks, 4096 envs, host µs per call including the GPU wait, main `299af193136` against this PR at `b75b5a81585` (same source as the head but for main's #8971), 3 alternated runs per arm. | Write | main | this PR | | |---|---|---|---| | Fixed-tendon stiffness mask, half envs, 2 tendons | 455 | 84 | 5.4x | | Fixed-tendon position limit mask, all | 216 | 80 | 2.7x | | Fixed-tendon position limit mask, half envs, 2 tendons | 393 | 84 | 4.7x | | `write_fixed_tendon_properties_to_sim_mask`, all | 373 | 124 | 3.0x | | `write_fixed_tendon_properties_to_sim_mask`, half envs, 2 tendons | 573 | 127 | 4.5x | | Joint position index write, half envs | 290 | 249 | 1.17x | | Joint state index write, half envs | 321 | 281 | 1.14x | | Joint position mask write; collection pose and velocity mask writes | | | within ±1% | ## Type of change - Bug fix (non-breaking change which fixes an issue) - New feature (non-breaking change which adds functionality) ## Screenshots Not applicable. ## Checklist Docker and GPU tests run on demand. Push the commits you want tested, then comment `run-ci` on the pull request. - [x] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `uv run isaaclab --format` - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have validated the changed behavior with focused coverage and applied the [test-audit criteria](https://github.com/isaac-sim/IsaacLab/blob/HEAD/skills/developer/test-audit/SKILL.md) to any test changes - [x] I have added a changelog fragment under `source/<pkg>/changelog.d/` for every touched package (do **not** edit `CHANGELOG.rst` or bump package versions — CI handles that) - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there
1 parent 5d410ae commit 3e5ceeb

40 files changed

Lines changed: 772 additions & 954 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
* Added :func:`~isaaclab.utils.warp.memory.resolve_ids`, which resolves an index selection given as ids or as a
2+
boolean mask to ids on a device, as :func:`~isaaclab.utils.warp.memory.resolve_1d_mask` does to a mask.
3+
* Added :func:`~isaaclab.utils.warp.memory.write_2d_with_mask`, which writes 2-D data or one scalar into a Warp array
4+
where a row mask and a column mask are both true, launching over the mask lengths.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
* Changed the env selection helpers of :class:`~isaaclab.utils.wrench_composer.WrenchComposer` and
2+
:class:`~isaaclab.sensors.Camera` to resolve ``env_ids`` and ``env_mask`` through
3+
:func:`~isaaclab.utils.warp.memory.resolve_ids` and :func:`~isaaclab.utils.warp.memory.resolve_1d_mask`.
4+
Any integer sequence and slices with a negative step are accepted, ids on another device are moved to the owner's
5+
device, and a :class:`~isaaclab.utils.warp.ProxyArray` is rejected with a :class:`TypeError`. The
6+
:class:`~isaaclab.sensors.Camera` now rejects floating-point ``env_ids`` with a :class:`TypeError` and
7+
multi-dimensional ``env_ids`` with a :class:`ValueError` instead of casting and flattening them.
8+
* Changed :class:`~isaaclab.utils.wrench_composer.WrenchComposer` to resolve ``body_ids`` through
9+
:func:`~isaaclab.utils.warp.memory.resolve_ids` as well, so slices other than ``slice(None)`` are accepted.
10+
* Changed :func:`~isaaclab.utils.warp.memory.resolve_1d_mask` to make ``scratch_mask`` optional for callers that never
11+
pass ids. Their masks are returned as given. Ids without a ``scratch_mask`` raise a :class:`ValueError`, and so
12+
does a mask longer than ``all_mask``.
13+
* Changed :func:`~isaaclab.utils.warp.memory.resolve_ids` to use given ids over a mask: the mask is converted to ids
14+
only when no ids (or ``slice(None)``) are given. When both ``env_ids`` and ``env_mask`` are given, PhysX assets now
15+
use the ids, which their views take without a host synchronization; mask-native consumers still use the mask.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
* Fixed the ``write_nodal_*_to_sim_mask`` methods of :class:`~isaaclab.assets.BaseDeformableObject`, which the
2+
OVPhysX deformable object inherits, raising a :class:`RuntimeError` whenever ``env_mask`` was given.
3+
* Fixed :meth:`~isaaclab.sensors.Camera.reset` with an ``env_mask`` on another device than the camera: the camera
4+
poses are now updated through the mask resolved on the camera's device, like the timestamps and buffers.

‎source/isaaclab/changelog.d/jichuanh-id-mask.minor‎

Whitespace-only changes.

‎source/isaaclab/isaaclab/assets/deformable_object/base_deformable_object.py‎

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
from ...utils import math as math_utils
1717
from ...utils.warp import ProxyArray
18+
from ...utils.warp.memory import resolve_ids
1819
from ..asset_base import AssetBase
1920

2021
if TYPE_CHECKING:
@@ -200,6 +201,9 @@ def write_nodal_kinematic_target_to_sim_index(
200201

201202
"""
202203
Operations - Write to simulation (mask variants).
204+
205+
These convert the mask to ids, which waits for the device, and call the index variants.
206+
Backends with a mask write path override them.
203207
"""
204208

205209
def write_nodal_state_to_sim_mask(
@@ -214,10 +218,7 @@ def write_nodal_state_to_sim_mask(
214218
Shape is (num_instances, max_sim_vertices_per_body, 6).
215219
env_mask: Environment mask. If None, then all indices are used.
216220
"""
217-
if env_mask is not None:
218-
env_ids = wp.nonzero(env_mask)
219-
else:
220-
env_ids = self._ALL_INDICES
221+
env_ids = resolve_ids(mask=env_mask, all_ids=self._ALL_INDICES)
221222
self.write_nodal_state_to_sim_index(nodal_state, env_ids=env_ids, full_data=True)
222223

223224
def write_nodal_pos_to_sim_mask(
@@ -232,10 +233,7 @@ def write_nodal_pos_to_sim_mask(
232233
Shape is (num_instances, max_sim_vertices_per_body, 3).
233234
env_mask: Environment mask. If None, then all indices are used.
234235
"""
235-
if env_mask is not None:
236-
env_ids = wp.nonzero(env_mask)
237-
else:
238-
env_ids = self._ALL_INDICES
236+
env_ids = resolve_ids(mask=env_mask, all_ids=self._ALL_INDICES)
239237
self.write_nodal_pos_to_sim_index(nodal_pos, env_ids=env_ids, full_data=True)
240238

241239
def write_nodal_velocity_to_sim_mask(
@@ -250,10 +248,7 @@ def write_nodal_velocity_to_sim_mask(
250248
Shape is (num_instances, max_sim_vertices_per_body, 3).
251249
env_mask: Environment mask. If None, then all indices are used.
252250
"""
253-
if env_mask is not None:
254-
env_ids = wp.nonzero(env_mask)
255-
else:
256-
env_ids = self._ALL_INDICES
251+
env_ids = resolve_ids(mask=env_mask, all_ids=self._ALL_INDICES)
257252
self.write_nodal_velocity_to_sim_index(nodal_vel, env_ids=env_ids, full_data=True)
258253

259254
def write_nodal_kinematic_target_to_sim_mask(
@@ -268,10 +263,7 @@ def write_nodal_kinematic_target_to_sim_mask(
268263
Shape is (num_instances, max_sim_vertices_per_body, 4).
269264
env_mask: Environment mask. If None, then all indices are used.
270265
"""
271-
if env_mask is not None:
272-
env_ids = wp.nonzero(env_mask)
273-
else:
274-
env_ids = self._ALL_INDICES
266+
env_ids = resolve_ids(mask=env_mask, all_ids=self._ALL_INDICES)
275267
self.write_nodal_kinematic_target_to_sim_index(targets, env_ids=env_ids, full_data=True)
276268

277269
"""

‎source/isaaclab/isaaclab/sensors/camera/camera.py‎

Lines changed: 3 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
quat_from_matrix,
2727
)
2828
from ...utils.warp import ProxyArray
29+
from ...utils.warp.memory import resolve_1d_indices, resolve_ids
2930
from ..sensor_base import SensorBase
3031
from .camera_data import CameraData, RenderBufferKind
3132

@@ -641,7 +642,7 @@ def reset(self, env_ids: Sequence[int] | slice | None = None, env_mask: wp.array
641642
# reset the data
642643
# note: this recomputation is useful if one performs events such as randomizations on the camera poses.
643644
if env_mask is not None:
644-
self._update_poses(env_mask=env_mask, frame_op=2)
645+
self._update_poses(env_mask=reset_mask, frame_op=2)
645646
elif env_ids is None:
646647
self._update_poses(frame_op=2)
647648
else:
@@ -1002,27 +1003,7 @@ def _resolve_env_ids_wp(self, env_ids: Sequence[int] | torch.Tensor | wp.array |
10021003
"""Resolve camera indices to a Warp ``int32`` array."""
10031004
if env_ids is None:
10041005
return None
1005-
if isinstance(env_ids, wp.array):
1006-
if env_ids.dtype != wp.int32:
1007-
raise TypeError(f"Unsupported wp.array dtype for env_ids: {env_ids.dtype}. Expected wp.int32.")
1008-
if env_ids.ndim != 1:
1009-
raise ValueError("Warp camera indices must be a one-dimensional array.")
1010-
if str(env_ids.device) == str(self._device):
1011-
return env_ids
1012-
return env_ids.to(self._device)
1013-
elif isinstance(env_ids, torch.Tensor):
1014-
env_ids = env_ids.to(device=self._device, dtype=torch.int32).reshape(-1)
1015-
if not env_ids.is_contiguous():
1016-
env_ids = env_ids.contiguous()
1017-
return wp.from_torch(env_ids, dtype=wp.int32)
1018-
elif isinstance(env_ids, slice) and (env_ids.step or 1) > 0:
1019-
return wp.from_torch(wp.to_torch(self._ALL_INDICES)[env_ids])
1020-
elif isinstance(env_ids, slice):
1021-
# Torch cannot slice with a negative step.
1022-
env_ids = np.arange(self._view.count, dtype=np.int32)[env_ids]
1023-
else:
1024-
env_ids = np.asarray(env_ids, dtype=np.int32).reshape(-1)
1025-
return wp.array(env_ids, dtype=wp.int32, device=self._device)
1006+
return resolve_1d_indices(resolve_ids(ids=env_ids, all_ids=self._ALL_INDICES))
10261007

10271008
def _env_mask_has_any(self, env_mask: wp.array) -> bool:
10281009
"""Return whether the mask selects any camera."""

‎source/isaaclab/isaaclab/utils/warp/memory.py‎

Lines changed: 112 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import warp as wp
2121

2222
from .index_kernel import selector_dtype
23+
from .proxy_array import ProxyArray
2324

2425
_CONCAT_TILE_SIZE = 32
2526

@@ -290,6 +291,37 @@ def fill(
290291
return fill
291292

292293

294+
def write_2d_with_mask(
295+
data: "float | torch.Tensor | wp.array",
296+
row_mask: wp.array,
297+
column_mask: wp.array,
298+
out: wp.array,
299+
) -> None:
300+
"""Write ``data`` into ``out`` where both masks are true, launching over the mask lengths.
301+
302+
A mask shorter than ``out`` writes only the rows or columns it covers. Callers resolve the masks and check the
303+
data shape.
304+
305+
Args:
306+
data: Values of shape ``(row_mask.shape[0], column_mask.shape[0])`` in the dtype of ``out``, as a ``wp.array``
307+
or a ``torch.Tensor`` with the dtype's trailing dimensions, or one scalar for every selected entry.
308+
row_mask: Boolean mask over the first dimension of ``out``.
309+
column_mask: Boolean mask over the second dimension of ``out``.
310+
out: Output array. The launch runs on its device.
311+
"""
312+
dim = (row_mask.shape[0], column_mask.shape[0])
313+
if isinstance(data, (int, float)):
314+
kernel = make_masked_fill(out.dtype, 2)
315+
elif isinstance(data, torch.Tensor) and data.ndim > 2 and data.stride(-1) != 1:
316+
# a vector-typed argument needs packed components; copy strided ones through scalar views instead
317+
scalar = out.dtype._wp_scalar_type_
318+
kernel, dim = make_masked_copy(scalar, 3), (*dim, data.shape[-1])
319+
data, out = wp.from_torch(data, dtype=scalar), out.view(scalar)
320+
else:
321+
kernel = make_masked_copy(out.dtype, 2)
322+
wp.launch(kernel, dim=dim, inputs=[data, row_mask, column_mask], outputs=[out], device=out.device)
323+
324+
293325
@cache
294326
def _make_populate_mask(dtype) -> wp.Kernel:
295327
@wp.kernel(module="unique")
@@ -316,11 +348,11 @@ def resolve_1d_mask(
316348
ids: "Sequence[int] | slice | torch.Tensor | wp.array | None" = None,
317349
mask: "wp.array | torch.Tensor | None" = None,
318350
all_mask: wp.array,
319-
scratch_mask: wp.array,
351+
scratch_mask: wp.array | None = None,
320352
) -> wp.array:
321353
"""Resolve a selection using caller-owned boolean storage on its device.
322354
323-
An explicit boolean mask takes precedence. ``None`` and ``slice(None)`` return
355+
A given boolean mask is used as given, so a mask consumer converts no ids. ``None`` and ``slice(None)`` return
324356
the identical ``all_mask`` object. Boolean selectors are masks; signed int32/int64
325357
selectors are indices, supporting negatives and duplicates. Index values must be
326358
in ``[-size, size)``; invalid device indices are ignored without a host sync.
@@ -329,21 +361,32 @@ def resolve_1d_mask(
329361
storage. Host sequences and device transfers are eager-only and may allocate.
330362
Temporary CUDA index uploads synchronize their stream before releasing storage;
331363
preallocated device selectors avoid this synchronization.
332-
Integer widths and strides are preserved. Masks must have the destination shape
333-
and boolean dtype. The returned scratch storage is reused, so this is not reentrant.
364+
Integer widths and strides are preserved. Masks use the boolean dtype and are never
365+
longer than ``all_mask``; with a ``scratch_mask`` they have its exact shape. The returned
366+
scratch storage is reused, so this is not reentrant.
367+
Callers that never select by ids may omit ``scratch_mask``; their masks, which may be
368+
shorter than ``all_mask``, are then returned as given, and the callers launch over the
369+
mask lengths, so a short mask writes only the rows it covers.
370+
371+
Raises:
372+
ValueError: If ids or a slice select a subset of elements and no ``scratch_mask`` is given,
373+
or a boolean mask is longer than ``all_mask`` or differs from a given ``scratch_mask`` shape.
334374
"""
335-
device = scratch_mask.device
336-
if scratch_mask.ndim != 1 or scratch_mask.dtype != wp.bool:
337-
raise ValueError("scratch_mask must be a rank-1 boolean Warp array")
338-
if all_mask.shape != scratch_mask.shape or all_mask.dtype != wp.bool or all_mask.device != device:
339-
raise ValueError("all_mask must match scratch_mask shape, dtype and device")
375+
device = all_mask.device
376+
if scratch_mask is not None:
377+
if scratch_mask.ndim != 1 or scratch_mask.dtype != wp.bool:
378+
raise ValueError("scratch_mask must be a rank-1 boolean Warp array")
379+
if all_mask.shape != scratch_mask.shape or all_mask.dtype != wp.bool or all_mask.device != scratch_mask.device:
380+
raise ValueError("all_mask must match scratch_mask shape, dtype and device")
340381

341382
temporary_input = False
342383
selection = mask if mask is not None else ids
343384
if selection is None or (isinstance(selection, slice) and selection == slice(None)):
344385
return all_mask
345386
if isinstance(selection, slice):
346-
start, stop, step = selection.indices(scratch_mask.shape[0])
387+
start, stop, step = selection.indices(all_mask.shape[0])
388+
if scratch_mask is None:
389+
raise ValueError("resolve_1d_mask needs a scratch_mask to write ids into.")
347390
scratch_mask.zero_()
348391
count = len(range(start, stop, step))
349392
if count:
@@ -381,11 +424,15 @@ def resolve_1d_mask(
381424
if selection.ndim != 1:
382425
raise ValueError("Selectors must be rank-1 arrays")
383426
if mask is not None or selection.dtype == wp.bool:
384-
if selection.dtype != wp.bool or selection.shape != scratch_mask.shape:
385-
raise ValueError("Boolean masks must match the destination shape and dtype")
427+
size = all_mask.shape[0] # the scratch_mask length when one is given
428+
fits = selection.shape[0] == size if scratch_mask is not None else selection.shape[0] <= size
429+
if selection.dtype != wp.bool or not fits:
430+
raise ValueError("Boolean masks must fit the destination shape and use the boolean dtype")
386431
return selection
387432
if selection.dtype not in (wp.int32, wp.int64):
388433
raise TypeError("Index arrays must use signed int32 or int64 values")
434+
if scratch_mask is None:
435+
raise ValueError("resolve_1d_mask needs a scratch_mask to write ids into.")
389436
scratch_mask.zero_()
390437
if selection.size:
391438
wp.launch(
@@ -395,3 +442,56 @@ def resolve_1d_mask(
395442
# Eager uploads must outlive scatter even on imported nonblocking CUDA streams.
396443
wp.synchronize_stream(wp.get_stream(device))
397444
return scratch_mask
445+
446+
447+
def resolve_ids(
448+
*,
449+
ids: "Sequence[int] | slice | torch.Tensor | wp.array | None" = None,
450+
mask: "wp.array | torch.Tensor | None" = None,
451+
all_ids: wp.array,
452+
) -> "wp.array | torch.Tensor":
453+
"""Resolve ids/mask into ids on the device of ``all_ids``. Given ids are used as given: a consumer of ids takes
454+
them without converting the mask, which happens only when no ids (or ``slice(None)``) are given.
455+
456+
Pass the result to :func:`resolve_1d_indices` where contiguous int32 ids are needed.
457+
458+
Args:
459+
ids: Index ids. Accepts ``Sequence[int]``, ``slice``, ``torch.Tensor``, ``wp.array``,
460+
or ``None`` (all elements). Tensors and warp arrays keep their integer dtype.
461+
mask: Boolean mask. Its ids are found with :func:`torch.nonzero`, which waits for
462+
the device.
463+
all_ids: Pre-allocated ids of every element, returned as-is when *ids* and *mask*
464+
select every element.
465+
466+
Returns:
467+
``all_ids``, a ``torch.Tensor`` or a ``wp.array`` of ids on the device of ``all_ids``.
468+
A mask resolves to an int64 ``torch.Tensor``; lists and slices resolve to ``wp.int32``.
469+
470+
Raises:
471+
TypeError: If *ids* is a :class:`ProxyArray`, which is output-only, or *mask* is
472+
neither a ``wp.array`` nor a ``torch.Tensor``.
473+
"""
474+
device = all_ids.device
475+
if mask is not None and (ids is None or (isinstance(ids, slice) and ids == slice(None))):
476+
if isinstance(mask, wp.array):
477+
mask = wp.to_torch(mask)
478+
elif not isinstance(mask, torch.Tensor):
479+
raise TypeError(f"Unsupported mask type: {type(mask)}")
480+
return torch.nonzero(mask.to(wp.device_to_torch(device))).squeeze(-1)
481+
if isinstance(ids, torch.Tensor):
482+
return ids if str(ids.device) == str(device) else ids.to(wp.device_to_torch(device))
483+
if ids is None:
484+
return all_ids
485+
if isinstance(ids, wp.array):
486+
return ids if ids.device == device else ids.to(device)
487+
if isinstance(ids, ProxyArray):
488+
raise TypeError("ProxyArray is output-only; pass .warp or .torch explicitly.")
489+
if isinstance(ids, slice):
490+
if ids == slice(None):
491+
return all_ids
492+
start, stop, step = ids.indices(all_ids.shape[0])
493+
if step > 0:
494+
# a strided view of the caller's all-ids, no copy
495+
return wp.from_torch(wp.to_torch(all_ids)[start:stop:step])
496+
return wp.array(list(range(start, stop, step)), dtype=wp.int32, device=device)
497+
return wp.array(list(ids), dtype=wp.int32, device=device)

‎source/isaaclab/isaaclab/utils/wrench_composer.py‎

Lines changed: 6 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
from .warp import ProxyArray
1717
from .warp.index_kernel import selector_dtype
18+
from .warp.memory import resolve_ids
1819
from .warp.wrench import (
1920
add_raw_wrench_buffers,
2021
compose_wrench_to_body_frame,
@@ -573,7 +574,7 @@ def reset(
573574
flags. Other ``env_ids`` or ``env_mask`` values perform a partial reset on the specified environments using
574575
the reset kernels. An inactive composer already holds zero buffers, so any reset of it is a no-op.
575576
576-
.. caution:: If both ``env_ids`` and ``env_mask`` are provided, ``env_mask`` takes precedence.
577+
.. caution:: If both ``env_ids`` and ``env_mask`` are provided, the mask is used: the kernels take it.
577578
578579
Args:
579580
env_ids: Environment indices. Defaults to None (all environments).
@@ -700,24 +701,9 @@ def _resolve_env_ids(self, env_ids: wp.array | torch.Tensor | list | slice | Non
700701
Environment indices.
701702
702703
Raises:
703-
TypeError: If ``env_ids`` is an unsupported type.
704+
TypeError: If ``env_ids`` is a :class:`~isaaclab.utils.warp.ProxyArray`.
704705
"""
705-
if env_ids is None:
706-
return self._ALL_ENV_INDICES
707-
# Check tensor types before slice comparison (tensor == slice crashes)
708-
if isinstance(env_ids, torch.Tensor):
709-
return env_ids
710-
if isinstance(env_ids, wp.array):
711-
return env_ids
712-
if env_ids == slice(None):
713-
return self._ALL_ENV_INDICES
714-
if isinstance(env_ids, slice):
715-
return wp.from_torch(wp.to_torch(self._ALL_ENV_INDICES)[env_ids])
716-
if isinstance(env_ids, list):
717-
return wp.array(env_ids, dtype=wp.int32, device=self.device)
718-
raise TypeError(
719-
f"env_ids must be None, slice(None), list, torch.Tensor, or wp.array, got {type(env_ids).__name__}"
720-
)
706+
return resolve_ids(ids=env_ids, all_ids=self._ALL_ENV_INDICES)
721707

722708
def _resolve_body_ids(
723709
self, body_ids: Sequence[int] | torch.Tensor | wp.array | slice | None
@@ -731,23 +717,9 @@ def _resolve_body_ids(
731717
Body indices.
732718
733719
Raises:
734-
TypeError: If ``body_ids`` is an unsupported type.
720+
TypeError: If ``body_ids`` is a :class:`~isaaclab.utils.warp.ProxyArray`.
735721
"""
736-
if body_ids is None:
737-
return self._ALL_BODY_INDICES
738-
if isinstance(body_ids, ProxyArray):
739-
raise TypeError("ProxyArray is output-only; pass .warp or .torch explicitly.")
740-
if isinstance(body_ids, torch.Tensor):
741-
return body_ids
742-
if isinstance(body_ids, wp.array):
743-
return body_ids
744-
if body_ids == slice(None):
745-
return self._ALL_BODY_INDICES
746-
if isinstance(body_ids, Sequence):
747-
return wp.array(body_ids, dtype=wp.int32, device=self.device)
748-
raise TypeError(
749-
f"body_ids must be None, slice(None), a sequence, torch.Tensor, or wp.array, got {type(body_ids).__name__}"
750-
)
722+
return resolve_ids(ids=body_ids, all_ids=self._ALL_BODY_INDICES)
751723

752724
def _ensure_composed(self):
753725
"""Compose input buffers into output buffers if dirty."""

0 commit comments

Comments
 (0)