Skip to content

Prototype native Torch scene selectors (alternative C) - #8089

Closed
StafaH wants to merge 1 commit into
isaac-sim:developfrom
StafaH:perf/scene-indices-native
Closed

StafaH wants to merge 1 commit into
isaac-sim:developfrom
StafaH:perf/scene-indices-native

Conversation

@StafaH

@StafaH StafaH commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Alternative C: prototype native Torch selectors in SceneEntityCfg, with no retained Python-index copy and no second Torch-selector field.

Compare with #8087 (automatic wrapper) and #8088 (separate tensor accessor). All three independently start from develop e140fa930cecc84f4fe1599569c8c998c24148bb, so their changes can be compared directly. Related: #8039. These are alternatives; choose one design rather than merging them together.

Implementation

  • Resolve names and validate selections on the host, then replace each non-slice joint_ids, body_ids, fixed_tendon_ids, and object_collection_ids with a one-dimensional torch.long tensor on the scene device. Slices remain slices.
  • Existing Torch consumers use those fields directly, without a wrapper or accessor dispatch. Existing Lift/termination caches naturally retain the already-resolved tensor.
  • Replace scalar CUDA-index expressions in pose rewards, cabinet terms, and manipulation consumers with one-element tensor selections, preserving the output shape without scalar readback.
  • Build experimental Warp selection arrays/masks from device tensors, and change reach kernels to read their first selected body from the device array.
  • Keep genuine host conversion at setup/inspection boundaries: name metadata, collision metadata, and material-shape setup in Newton, PhysX, and OVPhysX. Use bulk tolist() rather than reading individual device scalars.
  • Serialize selectors back to host lists, including nested manager configs, using a small dataclass field serializer hook. Tensor fields without that metadata keep the existing serialization behavior.
  • Add migration docs and changelog fragments for all seven touched packages.

Migration and ownership

This is a breaking prototype: after resolution, *_ids are tensors or slices, not Python lists. Existing list configurations still work. There is one authoritative device selector and no retained host index cache.

# Normal indexing uses the resolved tensor directly.
positions = asset.data.body_pos_w.torch[:, cfg.body_ids]

# Keep the index on CUDA when selecting one body.
first_position = asset.data.body_pos_w.torch[:, cfg.body_ids[:1]].squeeze(1)

# Host-only setup/export: this copies and synchronizes when IDs are on CUDA.
host_ids = cfg.body_ids.tolist()

ids[0] is a zero-dimensional tensor; using it as a scalar array index or Python integer can synchronize CUDA. len(ids) and ids.shape only inspect metadata. Treat selectors as read-only and replace/re-resolve after configuration edits. Copies own copies of their tensor storage. Re-resolution and serialization both read back device indices and belong outside stepping code. This design has neither the stale-host/device-cache risk of two mutable representations nor the cheap host-value access supplied by the other two alternatives.

Performance comparison

Same machine: RTX PRO 6000 Blackwell, PyTorch 2.12.0+cu130. Fresh processes in forward/reverse order (base, wrapper, separate, native, then reversed), 200 warmup calls, five blocks of 2,000 calls, CUDA synchronization at each block boundary. Each cell shows the median block time from both process runs, in µs/call.

  • Joint observation: real joint_pos, (4096, 32) input, eight shuffled selected joints.
  • Single-body reward: real position_command_error, 4,096 environments. The first two alternatives preserve host scalar indexing; this prototype uses the migrated device selection.
  • Host conversion: materialize the eight joint IDs as a Python list.
Design Joint observation Single-body reward Python-list conversion
develop (lists) 14.00 / 13.14 77.53 / 47.63 0.15 / 0.13
#8087: automatic wrapper 8.40 / 7.63 50.96 / 48.17 0.24 / 0.24
#8088: separate tensor 5.21 / 5.11 51.59 / 48.29 0.14 / 0.14
This PR: native tensor 4.96 / 5.09 60.09 / 61.13 7.78 / 7.78

Native tensors are effectively tied with the separate accessor for ordinary indexing; the small difference does not establish a meaningful winner. The automatic wrapper has additional dispatch overhead.

The tradeoff is visible in the other consumers: native single-body selection performs a gather/allocation where a host integer allowed a tensor view, and tolist() introduces a device-to-host copy plus synchronization. The pose-reward timings also show run-to-run variation (particularly the baseline), so use these as measured cases rather than a universal throughput prediction.

Profiler, 50 calls per case:

  • Joint observation: baseline has 50 H→D copies and 50 stream synchronizations. All three candidates have zero.
  • Migrated single-body reward: native has zero copies and zero stream synchronizations, as do the two alternatives retaining host scalar indices.
  • Python-list conversion: native has 50 D→H copies and 50 stream synchronizations. The other designs have zero.
  • The profiler's final device synchronization is excluded from the per-call stream synchronization counts.

Full task comparison

Isaac-Lift-KukaAllegro, Newton MJWarp, 64 environments, seed 42, no renderer, 200 warmup steps and 1,000 measured steps. Fresh processes in separate/native/native/separate order. Values are mean ms/iteration:

Design Two runs
#8088: separate tensor 8.776 / 8.765
This PR: native tensor 9.663 / 8.819

All runs completed. These are host-return measurements including resets; a documentation build was active on the CPU. They do not establish an end-to-end advantage for native selectors. This prototype primarily simplifies representation and automatically accelerates existing tensor-indexing consumers, with an API migration and potentially more expensive scalar/host consumers.

uv run --frozen isaaclab benchmark runtime \
  --task Isaac-Lift-KukaAllegro --num_envs 64 --num_steps 1000 \
  --warmup_steps 200 --seed 42 --device cuda:0 --visualizer none \
  --output_path /tmp/native-selector-comparison physics=newton_mjwarp
Focused benchmark reproduction (run in each branch)

Save this script outside the repository and execute it with uv run --frozen python /tmp/benchmark.py:

import gc
import json
import statistics
import time
from functools import partial
from types import SimpleNamespace

import torch
from isaaclab.managers import SceneEntityCfg
from isaaclab.envs.mdp.observations import joint_pos
from isaaclab.envs.mdp.rewards import position_command_error
from isaaclab.utils.string import resolve_matching_names

class Scene(dict):
    device = 'cuda:0'

names = [f'part_{i}' for i in range(32)]
find = partial(resolve_matching_names, list_of_strings=names)
root = torch.zeros(4096, 3, device='cuda:0')
quat = torch.tensor([[0.,0.,0.,1.]], device='cuda:0').repeat(4096, 1)
scene = Scene(robot=SimpleNamespace(
    joint_names=names, num_joints=32, body_names=names, num_bodies=32,
    find_joints=find, find_bodies=find,
    data=SimpleNamespace(
        joint_pos=SimpleNamespace(torch=torch.randn(4096,32,device='cuda:0')),
        root_pos_w=SimpleNamespace(torch=root), root_quat_w=SimpleNamespace(torch=quat),
        body_pos_w=SimpleNamespace(torch=torch.randn(4096,32,3,device='cuda:0')))))
cfg=SceneEntityCfg('robot',joint_ids=[15,2,29,5,22,11,30,0],body_ids=[15,2])
cfg.resolve(scene)
env=SimpleNamespace(scene=scene,command_manager=SimpleNamespace(get_command=lambda _: root))

def host_list():
    ids=cfg.joint_ids
    return ids.tolist() if isinstance(ids,torch.Tensor) else list(ids)

result={'torch':torch.__version__,'gpu':torch.cuda.get_device_name()}
gc.disable()
for name,fn in [('joint_pos',lambda:joint_pos(env,cfg)), ('single_body_reward',lambda:position_command_error(env,'pose',cfg)),('host_list',host_list)]:
    for _ in range(200): fn()
    torch.cuda.synchronize()
    timings=[]
    for _ in range(5):
        start=time.perf_counter()
        for _ in range(2000): fn()
        torch.cuda.synchronize()
        timings.append((time.perf_counter()-start)*1e6/2000)
    with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU,torch.profiler.ProfilerActivity.CUDA]) as profile:
        for _ in range(50): fn()
    counts={item.key:item.count for item in profile.key_averages() if 'Memcpy' in item.key or 'Synchronize' in item.key}
    result[name]={'median_us':statistics.median(timings),'blocks_us':timings,'profile_50_calls':counts}
print(json.dumps(result))

Validation

  • 244 focused tests passed, one skipped: selector behavior/CUDA/host metadata/Warp integration (6), manager base (5), dict serialization (9), configclass (37), array conversions (145), Lift configs (9), experimental frontend config conversion (8), reward parity (19), event parity (5), and live Newton material-body selection (1).
  • The frontend registry completeness test conditionally skips because some registered task configs do not provide its requested newton_mjwarp preset; the reason was inspected.
  • CUDA regression fails on untouched develop at the real joint_pos consumer, then passes here.
  • A second negative control restores the old scalar body-index expression while retaining native tensors: the same CUDA test fails at position_command_error with a synchronizing operation. Restoring the migrated expression makes it pass.
  • Native Kuka smoke and the longer comparison runs completed.
  • uv run --frozen isaaclab -f passed, including changelog validation.
  • Full documentation build passed without warnings or errors (uv run --frozen --isolated --extra dev -- make -C docs current-docs 'SPHINXOPTS=-j 4').
  • Existing TorchScript/Newton deprecation warnings and PyTorch's sync-debug prototype warning remain. Full PhysX/OVPhysX runtime coverage and exhaustive task coverage are not claimed by these checks.

Type of change

  • Breaking API prototype
  • Performance improvement for existing tensor-indexing consumers
  • Documentation update

Release backport

  • Backport this pull request to the active release branch after it merges into develop

Checklist

  • I have read and understood the contribution guidelines.
  • I have run pre-commit checks with uv run --frozen isaaclab -f.
  • I have made corresponding changes to the documentation.
  • I have added meaningful tests and verified the CUDA regressions with negative controls.
  • I have added changelog fragments for every touched source package.
  • My name already exists in CONTRIBUTORS.md.

@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Sep 27, 2026
@StafaH StafaH closed this Sep 27, 2026
StafaH added a commit that referenced this pull request Sep 28, 2026
# Description

Finalize resolved scene-entity selections to device tensors, following
Newton's build-then-finalize model. Manager terms index with the
existing `*_ids` fields and no longer upload indices or synchronize CUDA
on every call. No second field or helper is needed.

Alternative A to #8088, which adds separate `*_ids_torch` fields.
Related: #8039, #8089.

## Design

- **Build:** `SceneEntityCfg.resolve(scene)` is unchanged. It fills
`joint_ids`, `body_ids`, `fixed_tendon_ids`, and `object_collection_ids`
with host lists. Class-based terms can read these lists in `__init__`.
- **Finalize:** once every term is constructed, `ManagerBase` calls the
new `SceneEntityCfg.finalize(device)` on the configurations it resolved.
Each list becomes a `torch.long` tensor on the simulation device, shared
by the terms that use it, and slices stay slices. Finalization is
one-way, and calling it again does nothing. Configurations resolved
outside managers, such as by action or command terms, are left
unchanged.
- **Consumers:** term calls use `data[:, cfg.joint_ids]` and pass
`cfg.joint_ids` to asset write methods as before. Tensors compare
unequal to `slice(None)`, so the existing `ids == slice(None)` checks
continue to work.
- **No per-step host reads:** a scalar selection such as `data[:,
cfg.body_ids[0]]` would read a CUDA tensor back to the host, so these
reads become device gathers: `data[:, cfg.body_ids][:, 0]`. Event terms
that previously rebuilt index tensors on each call now use the finalized
tensors directly; every backend accepts int64 index tensors.
- **Scope:** 13 files, all in `isaaclab` and `isaaclab_tasks`. Backend
asset APIs, `isaaclab_experimental` (whose managers are a separate
implementation), and serialization helpers are unchanged.

### Why tensors rather than `ProxyArray` or a wrapper

| Design | Call site | `joint_pos` (µs/call) | `joint_pos_limits`
(µs/call) | Syncs/call |
| --- | --- | ---: | ---: | ---: |
| develop (host lists) | `data[:, cfg.joint_ids]` | 383 † | 1470–1566 †
| 1 / 4 |
| Previous revision: `IndexSequence` wrapper | `data[:, cfg.joint_ids]`
| 8.45–8.50 | 64.4–65.7 | 0 |
| #8088: separate `*_ids_torch` | `data[:, cfg.joint_ids_torch]` |
5.34–5.99 | 47.95–48.83 | 0 |
| **This PR: finalized tensors** | `data[:, cfg.joint_ids]` |
**5.32–6.38** | **48.00–49.19** | 0 |

Finalized tensors match #8088 with a single field. A finalized
`ProxyArray` was also prototyped. Indexing with it directly cost about 2
µs more per index (7.7 µs vs. 5.3–6.1 µs), because it dispatches through
`ProxyArray`'s deprecated Torch bridge, and asset write methods reject
it. It would therefore need an explicit accessor at every call site. No
consumer used its Warp view.

Benchmark: RTX PRO 6000 Blackwell, PyTorch 2.12.0+cu130. Real
`joint_pos` observation and `joint_pos_limits` reward, `(4096, 32)` CUDA
data, joints `[15, 2, 29, 5, 22, 11, 30, 0]`. Each fresh process ran 200
warmup calls, then five blocks of 2,000 calls. Figures are median block
times from two or more processes per design, run in alternating order.
Synchronizations were counted with PyTorch's sync-debug mode.

† The GPU was fully utilized by unrelated processes during these runs,
which inflates develop's synchronizing path. On an idle GPU, the same
benchmark previously measured develop at 13.05–13.11 µs. The
synchronization-free designs are CPU-bound and are comparable with one
another.

## Type of change

- New feature
- Breaking change: term calls receive finalized `torch.long` tensors
instead of host lists. Migration:
- Replace per-step scalar reads such as `data[:, cfg.body_ids[0]]` with
`data[:, cfg.body_ids][:, 0]`, or read host values in the term's
`__init__`.
- Replace `torch.tensor(cfg.body_ids)` with `cfg.body_ids`; the
finalized selection is already a device tensor.
- Replace `isinstance(ids, list)` checks with `isinstance(ids, slice)`.
  - Class terms can still read host lists in `__init__`.
- Documentation update

## Validation

- 206 focused tests passed: managers (event, observation, reward,
termination, base, scene selection), dict, configclass, wrench composer,
gravity observations, and Lift configuration.
- New tests cover:
  - finalization of ordering, slices, empty selections, and copies;
- that class terms see host lists while term calls see device tensors,
whether the manager is created while the simulation is playing or
deferred until physics is ready;
- a real `joint_pos` consumer and a device gather under CUDA sync-debug
`error` mode;
  - external-force sizing for a finalized body subset.
- All six new tests fail when `finalize` is disabled.
- Newton/MJWarp runtime smoke tests passed with 64 environments, seed
42, 20 warmup and 100 measured steps, and no renderer, for
`Isaac-Lift-KukaAllegro`, `Isaac-Velocity-Flat-AnymalD`, and
`Isaac-Open-Drawer-Franka`. The last exercises the changed drawer-joint
gather. No implicit `ProxyArray` deprecation warnings were emitted.
- `uv run --frozen isaaclab -f` passed, including changelog checks.
- Not run: the full documentation build, PhysX/OVPhysX runtime, and
`test_recorder_manager_integration` (requires full Isaac Sim).

Reproduce the smoke test:

```bash
uv run --frozen isaaclab benchmark runtime \
  --task Isaac-Lift-KukaAllegro --num_envs 64 --num_steps 100 \
  --warmup_steps 20 --seed 42 --device cuda:0 --visualizer none \
  --output_path /tmp/scene-selector-smoke physics=newton_mjwarp
```

## Known limitations

- Serializing a finalized configuration emits tensors for its
selections, following the existing `class_to_dict` tensor handling. No
code in this repository serializes term configurations after
finalization.
- Finalized tensors are read-only by convention. Calling `resolve()`
after `finalize()` is unsupported.
- A few class terms copy selection fields in `__init__` and therefore
keep the host list or their own tensor. Two of these, NIST
`reset_end_effector_around_asset` and PhysX
`randomize_rigid_body_material`, keep host lists: the first can adopt
the finalized tensor in a follow-up, while the second iterates backend
body IDs on the CPU and should stay on the host.

## Release backport

- [x] <!-- backport-active-release --> Backport this pull request to the
active release branch after it merges into `develop`

## Checklist

- [x] I have read and understood the contribution guidelines.
- [x] I have run the pre-commit checks with `uv run --frozen isaaclab
-f`.
- [x] I have made corresponding changes to the documentation.
- [x] I have added tests that prove the behavior and checked them
against the change disabled.
- [x] I have added a changelog fragment for every touched source
package.
- [x] My name already exists in `CONTRIBUTORS.md`.
isaaclab-bot Bot pushed a commit that referenced this pull request Sep 28, 2026
# Description

Finalize resolved scene-entity selections to device tensors, following
Newton's build-then-finalize model. Manager terms index with the
existing `*_ids` fields and no longer upload indices or synchronize CUDA
on every call. No second field or helper is needed.

Alternative A to #8088, which adds separate `*_ids_torch` fields.
Related: #8039, #8089.

## Design

- **Build:** `SceneEntityCfg.resolve(scene)` is unchanged. It fills
`joint_ids`, `body_ids`, `fixed_tendon_ids`, and `object_collection_ids`
with host lists. Class-based terms can read these lists in `__init__`.
- **Finalize:** once every term is constructed, `ManagerBase` calls the
new `SceneEntityCfg.finalize(device)` on the configurations it resolved.
Each list becomes a `torch.long` tensor on the simulation device, shared
by the terms that use it, and slices stay slices. Finalization is
one-way, and calling it again does nothing. Configurations resolved
outside managers, such as by action or command terms, are left
unchanged.
- **Consumers:** term calls use `data[:, cfg.joint_ids]` and pass
`cfg.joint_ids` to asset write methods as before. Tensors compare
unequal to `slice(None)`, so the existing `ids == slice(None)` checks
continue to work.
- **No per-step host reads:** a scalar selection such as `data[:,
cfg.body_ids[0]]` would read a CUDA tensor back to the host, so these
reads become device gathers: `data[:, cfg.body_ids][:, 0]`. Event terms
that previously rebuilt index tensors on each call now use the finalized
tensors directly; every backend accepts int64 index tensors.
- **Scope:** 13 files, all in `isaaclab` and `isaaclab_tasks`. Backend
asset APIs, `isaaclab_experimental` (whose managers are a separate
implementation), and serialization helpers are unchanged.

### Why tensors rather than `ProxyArray` or a wrapper

| Design | Call site | `joint_pos` (µs/call) | `joint_pos_limits`
(µs/call) | Syncs/call |
| --- | --- | ---: | ---: | ---: |
| develop (host lists) | `data[:, cfg.joint_ids]` | 383 † | 1470–1566 †
| 1 / 4 |
| Previous revision: `IndexSequence` wrapper | `data[:, cfg.joint_ids]`
| 8.45–8.50 | 64.4–65.7 | 0 |
| #8088: separate `*_ids_torch` | `data[:, cfg.joint_ids_torch]` |
5.34–5.99 | 47.95–48.83 | 0 |
| **This PR: finalized tensors** | `data[:, cfg.joint_ids]` |
**5.32–6.38** | **48.00–49.19** | 0 |

Finalized tensors match #8088 with a single field. A finalized
`ProxyArray` was also prototyped. Indexing with it directly cost about 2
µs more per index (7.7 µs vs. 5.3–6.1 µs), because it dispatches through
`ProxyArray`'s deprecated Torch bridge, and asset write methods reject
it. It would therefore need an explicit accessor at every call site. No
consumer used its Warp view.

Benchmark: RTX PRO 6000 Blackwell, PyTorch 2.12.0+cu130. Real
`joint_pos` observation and `joint_pos_limits` reward, `(4096, 32)` CUDA
data, joints `[15, 2, 29, 5, 22, 11, 30, 0]`. Each fresh process ran 200
warmup calls, then five blocks of 2,000 calls. Figures are median block
times from two or more processes per design, run in alternating order.
Synchronizations were counted with PyTorch's sync-debug mode.

† The GPU was fully utilized by unrelated processes during these runs,
which inflates develop's synchronizing path. On an idle GPU, the same
benchmark previously measured develop at 13.05–13.11 µs. The
synchronization-free designs are CPU-bound and are comparable with one
another.

## Type of change

- New feature
- Breaking change: term calls receive finalized `torch.long` tensors
instead of host lists. Migration:
- Replace per-step scalar reads such as `data[:, cfg.body_ids[0]]` with
`data[:, cfg.body_ids][:, 0]`, or read host values in the term's
`__init__`.
- Replace `torch.tensor(cfg.body_ids)` with `cfg.body_ids`; the
finalized selection is already a device tensor.
- Replace `isinstance(ids, list)` checks with `isinstance(ids, slice)`.
  - Class terms can still read host lists in `__init__`.
- Documentation update

## Validation

- 206 focused tests passed: managers (event, observation, reward,
termination, base, scene selection), dict, configclass, wrench composer,
gravity observations, and Lift configuration.
- New tests cover:
  - finalization of ordering, slices, empty selections, and copies;
- that class terms see host lists while term calls see device tensors,
whether the manager is created while the simulation is playing or
deferred until physics is ready;
- a real `joint_pos` consumer and a device gather under CUDA sync-debug
`error` mode;
  - external-force sizing for a finalized body subset.
- All six new tests fail when `finalize` is disabled.
- Newton/MJWarp runtime smoke tests passed with 64 environments, seed
42, 20 warmup and 100 measured steps, and no renderer, for
`Isaac-Lift-KukaAllegro`, `Isaac-Velocity-Flat-AnymalD`, and
`Isaac-Open-Drawer-Franka`. The last exercises the changed drawer-joint
gather. No implicit `ProxyArray` deprecation warnings were emitted.
- `uv run --frozen isaaclab -f` passed, including changelog checks.
- Not run: the full documentation build, PhysX/OVPhysX runtime, and
`test_recorder_manager_integration` (requires full Isaac Sim).

Reproduce the smoke test:

```bash
uv run --frozen isaaclab benchmark runtime \
  --task Isaac-Lift-KukaAllegro --num_envs 64 --num_steps 100 \
  --warmup_steps 20 --seed 42 --device cuda:0 --visualizer none \
  --output_path /tmp/scene-selector-smoke physics=newton_mjwarp
```

## Known limitations

- Serializing a finalized configuration emits tensors for its
selections, following the existing `class_to_dict` tensor handling. No
code in this repository serializes term configurations after
finalization.
- Finalized tensors are read-only by convention. Calling `resolve()`
after `finalize()` is unsupported.
- A few class terms copy selection fields in `__init__` and therefore
keep the host list or their own tensor. Two of these, NIST
`reset_end_effector_around_asset` and PhysX
`randomize_rigid_body_material`, keep host lists: the first can adopt
the finalized tensor in a follow-up, while the second iterates backend
body IDs on the CPU and should stay on the host.

## Release backport

- [x] <!-- backport-active-release --> Backport this pull request to the
active release branch after it merges into `develop`

## Checklist

- [x] I have read and understood the contribution guidelines.
- [x] I have run the pre-commit checks with `uv run --frozen isaaclab
-f`.
- [x] I have made corresponding changes to the documentation.
- [x] I have added tests that prove the behavior and checked them
against the change disabled.
- [x] I have added a changelog fragment for every touched source
package.
- [x] My name already exists in `CONTRIBUTORS.md`.

(cherry picked from commit 10fdf81)
@StafaH
StafaH deleted the perf/scene-indices-native branch October 10, 2026 19:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant