Skip to content

Remove per-step host synchronizations from the environment hot path - #7495

Closed
StafaH wants to merge 1 commit into
isaac-sim:developfrom
StafaH:perf/remove-hot-path-host-syncs
Closed

StafaH wants to merge 1 commit into
isaac-sim:developfrom
StafaH:perf/remove-hot-path-host-syncs

Conversation

@StafaH

@StafaH StafaH commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

Description

Profiling Isaac-Lift-KukaAllegro-Camera on Newton/MJWarp (4096 envs, Newton Warp tiled camera, RTX PRO 6000) showed that the env step is bound by a CPU-only tail (rewards, reset, commands, observation terms) that runs while the GPU idles, and that ~40 host-device synchronizations per step keep host work from overlapping device work. This PR removes the synchronizations that are pure integration overhead and keeps behavior unchanged:

  • isaaclab: scalar index assignments (x[ids] = scalar, a host scalar upload + stream sync each) in CircularBuffer.reset, RewardManager.reset, EventManager.apply (reset mode), JointAction.reset, SensorBase._resolve_indices_and_mask, and the episode-length reset now use index_fill_; TerminationManager.compute updates last-episode bookkeeping with a masked torch.where instead of nonzero; VisualizationMarkers.visualize skips the synchronizing environment-index validation when no visualizer backend consumes marker state; Camera skips the device->host outdated-mask readback when update_period == 0 (the generation check already dedupes fetches); zero-range uniform noise returns its input.
  • isaaclab_newton: NewtonManager._update_sensor_tasks only uploads the sensor-graph flags when they change (the pageable host->device assign synchronized the stream on every render).
  • isaaclab_tasks (lift task): the progress rewards use torch.where(..., out=) instead of boolean-mask writes (4 syncs per step, right after physics), object_ee_distance indexes with a cached device tensor instead of a Python list, and the camera observation converts/normalizes in one fused pass without a NaN scrub on uint8 images.

Measured with uv run isaaclab benchmark runtime --task Isaac-Lift-KukaAllegro-Camera --num_envs 4096 --num_steps 500 --warmup_steps 50 --visualizer none (sequential runs):

build 4096 envs 8192 envs
develop @ 4f15463 148.6k FPS 178.3k FPS
this PR 155.1k FPS (+4.4%) 199.1k FPS (+11.7%)
this PR + sim.use_newton_actuators=True 156.2k FPS (+5.1%)

The reward-term change accounts for most of the 4096-env gain; the others are individually within measurement noise but remove ~25 stream synchronizations per step and are prerequisites for a fully asynchronous (mask-based reset) step, which a non-mergeable prototype measured at +19-22% (177k-181k FPS). A full breakdown (physics graph 12.2 ms wall / 8.0 ms kernels, render 7.3 ms, CPU tail ~7 ms) is available on request.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

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 the pre-commit checks with ./isaaclab.sh --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package (do not edit CHANGELOG.rst or bump extension.toml — CI handles that)
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

Existing tests run locally: test_circular_buffer.py, test_noise.py, test_termination_manager.py, test_reward_manager.py, test_event_manager.py, test_visualization_markers.py all pass.

🤖 Generated with Claude Code

Profiling Isaac-Lift-KukaAllegro-Camera on Newton/MJWarp showed ~40 host-device synchronizations per env step (boolean-mask writes in reward terms, Python-list indexing, scalar index assignments in reset paths, a nonzero in termination bookkeeping, a device->host camera mask readback, a pageable sensor-graph flag upload, and marker index validation with no visualizer). Each one drains the CUDA stream and prevents host work from overlapping device work. This change replaces them with device-side equivalents (torch.where, index_fill_, cached index tensors, change-detected flag uploads) and skips redundant image passes (NaN scrub on uint8, zero-range noise). Measured +4-5% throughput at 4096 envs on the camera lift task; it is also a prerequisite for a fully asynchronous (mask-based reset) step, which a prototype measured at +19-22%.
@github-actions github-actions Bot added the isaac-lab Related to Isaac Lab team label Sep 2, 2026
@kellyguo11 kellyguo11 moved this to In progress in Isaac Lab Sep 2, 2026
asset: RigidObject = env.scene[asset_cfg.name]
obj: RigidObject = env.scene[object_cfg.name]
asset_pos = asset.data.body_pos_w.torch[:, asset_cfg.body_ids]
# index with a cached device tensor: indexing with a Python list uploads it every call (a stream sync)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the code looks a bit weird, maybe something funcky happended in SceneEntityCfg and we should fix that?

StafaH added a commit to StafaH/IsaacLab that referenced this pull request Sep 25, 2026
Ports the changes of isaac-sim#7495 onto this branch: device-side index fills in
reset paths, a change-detected Newton sensor flag upload, and an identity
shortcut for zero-width uniform noise. The termination, lift reward, and
marker changes overlap with the previous commit and are reconciled here.
ooctipus added a commit that referenced this pull request Sep 28, 2026
# Description

Part 4 of the camera performance series. Based on the latest `develop`,
including #8084 and #8087. Supersedes #7495.

Profiling the camera and direct tasks found host-device synchronizations
in every step: the CPU blocked on the GPU, then ran Python code while
the GPU sat idle. This PR removes them from termination tracking, the
Lift rewards and success monitoring, marker validation, camera updates,
and the Cartpole and Pendulum direct tasks. It also incorporates the
hot-path fixes from #6492 (by @kellyguo11) that still apply to current
`develop`.

- `torch.where` replaces `nonzero` in the termination manager and
replaces boolean-mask writes in the Lift progress rewards.
- `SuccessMonitor` updates no longer synchronize. They rank outcomes
with fixed-size scatters instead of `unique_consecutive`,
`repeat_interleave`, and boolean masks. Masked or overflowing outcomes
go to an internal scratch row. A new `valid` argument lets the Lift
reset hook pass a mask instead of filtering.
- `SuccessMonitor.get_mean_success_rate()` returns a 0-d tensor, so
logging it does not synchronize. The Cartpole direct and Pendulum MARL
success rates are logged as tensors for the same reason. Call `.item()`
where a Python float is needed.
- Cartpole direct and Pendulum MARL store their joint indices as device
tensors. Observations, rewards, terminations, resets, and effort writes
no longer upload host lists each step.
- Marker index validation runs only when a backend consumes the IDs, and
once per ID tensor.
- Cameras with `update_period == 0` skip the outdated-mask readback.
- Zero-width uniform `add` noise returns its input.
- `object_point_cloud_b` defaults to `visualize=False`. Drawing 262k
markers every step cost a sync, and with RTX the markers appeared in
camera images. The Kuka rendering test already disabled them for that
reason.
- `ActionManager` caches its term dimensions, which are fixed after
construction but were recomputed on every action step (from #6492).
- The Cartpole and Reorient direct tasks drop redundant action copies
(from #6492).

With #8087, managers finalize scene-entity selections to device tensors.
`object_ee_distance` therefore indexes with `asset_cfg.body_ids`
directly, and this PR's earlier cached device-ID helper was removed.
After #8087 it would have iterated the finalized tensor to build its
cache key, reading indices back from the device.

### Changes from #6492

Each #6492 change was checked against current `develop`:

| #6492 change | Decision |
| --- | --- |
| Skip observation-term clones | Not taken: `develop` already provides
this through #8038. |
| Cabinet direct `actions.clone()` | Not taken: the line no longer
exists. |
| `ActionManager` caches term dimensions | **Taken.** |
| Cartpole direct index cleanup | **Taken and extended.** #6492 fixed 1
of the 9 synchronizations caused by host-list joint indexing. Storing
the joint indices as device tensors removes all 9. |
| Drop `actions.clone()` in the Cartpole and Reorient direct tasks |
**Taken.** Neither task modifies the stored actions in place. |
| Drop `actions.clone()` in the Locomotion direct task | **Not taken.**
Its reset zeroes `self.actions` in place, which would zero the policy's
own action tensor, e.g. the one held in RL rollout storage. |

### Investigated and dropped: Newton sensor-graph flag cache

An earlier revision cached the Newton sensor graph's task flags and
skipped the upload when they were unchanged, on the premise that each
upload synchronized the stream. That premise does not hold for the
current Warp (1.17), so the change was reverted and `develop`'s per-call
upload is kept:

- Warp uploads the flags with a single `cudaMemcpyAsync` from pageable
memory, which CUDA stages on the host without waiting for the stream.
- Behind about 455 ms of Warp kernels queued on the same stream, ten
uploads return in 0.07–0.13 ms.
- An Nsight Systems trace of the Kuka camera task shows each flag
upload's `cudaMemcpyAsync` returning in 5.9 µs on average, 35.6 µs at
most.
- End to end (Kuka camera task, 256 environments), `develop`'s upload,
the cache, and device-side flag writes measured 12.53, 12.50, and 12.47
ms per step. That spread is within run-to-run noise (12.45–12.58 ms).

## Series

1. #8036: Read camera outputs through `ProxyArray.torch` (bug fix)
(base: develop)
2. #8037: Fused normalization for strided camera images (base: #8036)
3. #8038: Skip redundant observation copies (base: #8037)
4. #8039: Remove per-step host synchronizations (base: develop)
5. #8040: Newton `render_batch` in one sensor-graph launch (base:
develop)
6. #8041: RSL-RL cuDNN benchmark, mixed precision and compile settings
(base: develop)
7. #8042: Kuka Allegro camera tasks on the shared image observation
(base: #8038)

The series is split from #7440, which remains the combined reference
branch.

## Type of change

- Bug fix (non-breaking change which fixes an issue)
- Changes to `SuccessMonitor`: `get_mean_success_rate()` returns a 0-d
tensor instead of a float, and `success_update()` gains a `valid`
argument. The changelog includes migration guidance.

## Performance

RTX PRO 6000 Blackwell Workstation Edition (driver 595.91.07); PyTorch
2.12.0+cu130; Warp 1.17.0; Newton 1.6.0; GPU otherwise idle. `develop`
at `10fdf81d9` compared with this PR (`b2727a0f2`; later commits only
trim comments and revert the Newton change above), with the same
`uv.lock`. Runtime benchmark (`isaaclab benchmark runtime`),
Newton/MJWarp, seed 42, no visualizer. Three fresh processes per
revision, run in alternating order. Figures are the mean step time
across processes.

| Workload | `develop` | This PR | Change |
| --- | ---: | ---: | ---: |
| `Isaac-Lift-KukaAllegro-Camera`, 256 envs,
`presets=duo_camera,rgb128`, Newton renderer (500 steps) | 14.44 ms |
12.62 ms | **−12.6%** (+14.4% throughput) |
| `Isaac-Cartpole-Direct`, 4096 envs (2,000 steps) | 1.674 ms | 1.441 ms
| **−13.9%** (+16.2% throughput) |
| `Isaac-Pendulum-MARL-Direct`, 4096 envs (2,000 steps) | 2.144 ms |
1.862 ms | **−13.2%** (+15.2% throughput) |

Per-process step times (`develop` → PR):
- Camera: `14.44, 14.48, 14.40` → `12.67, 12.63, 12.57` ms.
- Cartpole: `1.680, 1.685, 1.657` → `1.446, 1.438, 1.439` ms.
- Pendulum: `2.137, 2.158, 2.137` → `1.827, 1.863, 1.895` ms.

Host synchronizations per `env.step()`, attributed to call sites with
PyTorch sync-debug mode over 170 steps (4096 envs):

| Task | `develop` | This PR | Remaining |
| --- | ---: | ---: | --- |
| `Isaac-Lift-KukaAllegro-Camera` (`presets=cube`, Newton renderer) |
21.3 | 4.2 | step reset and command-resample `nonzero`; curriculum,
command-metric, and termination logging reads |
| `Isaac-Cartpole-Direct` | 10.3 | 1.0 | step reset `nonzero` |
| `Isaac-Pendulum-MARL-Direct` | 10.0 | 1.0 | step reset `nonzero` |

PyTorch labels sync-debug mode a prototype that does not detect every
synchronization, and it does not see synchronizations issued by Warp, so
these counts are lower bounds.

Reproduce with:

```bash
uv run --frozen isaaclab benchmark runtime \
  --task Isaac-Lift-KukaAllegro-Camera --num_envs 256 --num_steps 500 \
  --warmup_steps 100 --seed 42 --device cuda:0 --visualizer none \
  --output_path /tmp/pr8039 physics=newton_mjwarp renderer=newton_renderer presets=duo_camera,rgb128
```

### Not addressed

- **Step reset and command resampling:** both still call `nonzero` once
per step. Both convert a mask into variable-length environment IDs, and
the reset and command pipelines consume those IDs throughout. Removing
these synchronizations means moving those pipelines to masks or padded
IDs, which is out of scope here.
- **Warp-side synchronizations:** the Nsight trace above also records
many `cudaStreamSynchronize` calls outside the flag uploads, which
PyTorch's sync-debug mode cannot attribute. Their sources are not yet
identified.

## Validation

- Cartpole direct produces bit-identical observation and reward
checksums to `develop` after 150 seeded steps, including resets.
- Pendulum MARL is not run-to-run deterministic on MJWarp. Its
observations and rewards were instead compared on identical state
against `develop`'s host-index formulas for 150 steps, with a maximum
difference of 0.0. Reorient direct is also non-deterministic; its change
only removes a copy of an action tensor that is never modified in place.
- `test_circular_buffer.py`, `test_noise.py`, `test_curriculum.py`, the
manager tests (including `test_event_manager.py`,
`test_reward_manager.py`, `test_termination_manager.py`, and
`test_scene_entity_cfg.py`), `test_lift_env_cfg.py`,
`test_sensor_base.py`, `test_visualization_markers.py`, and
`test_kit_visualizer_scene_partitioning.py` pass.
- `test_rendering_lift_kuka_homo_kitless.py` passes for the Newton
renderer and legacy OVRTX cases. The two `ovstage` OVRTX cases fail
identically on `develop`.
- `uv run --frozen isaaclab -f` passes, including changelog checks.

## Release backport

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

---------

Co-authored-by: Octi Zhang <[email protected]>
isaaclab-bot Bot pushed a commit that referenced this pull request Sep 28, 2026
# Description

Part 4 of the camera performance series. Based on the latest `develop`,
including #8084 and #8087. Supersedes #7495.

Profiling the camera and direct tasks found host-device synchronizations
in every step: the CPU blocked on the GPU, then ran Python code while
the GPU sat idle. This PR removes them from termination tracking, the
Lift rewards and success monitoring, marker validation, camera updates,
and the Cartpole and Pendulum direct tasks. It also incorporates the
hot-path fixes from #6492 (by @kellyguo11) that still apply to current
`develop`.

- `torch.where` replaces `nonzero` in the termination manager and
replaces boolean-mask writes in the Lift progress rewards.
- `SuccessMonitor` updates no longer synchronize. They rank outcomes
with fixed-size scatters instead of `unique_consecutive`,
`repeat_interleave`, and boolean masks. Masked or overflowing outcomes
go to an internal scratch row. A new `valid` argument lets the Lift
reset hook pass a mask instead of filtering.
- `SuccessMonitor.get_mean_success_rate()` returns a 0-d tensor, so
logging it does not synchronize. The Cartpole direct and Pendulum MARL
success rates are logged as tensors for the same reason. Call `.item()`
where a Python float is needed.
- Cartpole direct and Pendulum MARL store their joint indices as device
tensors. Observations, rewards, terminations, resets, and effort writes
no longer upload host lists each step.
- Marker index validation runs only when a backend consumes the IDs, and
once per ID tensor.
- Cameras with `update_period == 0` skip the outdated-mask readback.
- Zero-width uniform `add` noise returns its input.
- `object_point_cloud_b` defaults to `visualize=False`. Drawing 262k
markers every step cost a sync, and with RTX the markers appeared in
camera images. The Kuka rendering test already disabled them for that
reason.
- `ActionManager` caches its term dimensions, which are fixed after
construction but were recomputed on every action step (from #6492).
- The Cartpole and Reorient direct tasks drop redundant action copies
(from #6492).

With #8087, managers finalize scene-entity selections to device tensors.
`object_ee_distance` therefore indexes with `asset_cfg.body_ids`
directly, and this PR's earlier cached device-ID helper was removed.
After #8087 it would have iterated the finalized tensor to build its
cache key, reading indices back from the device.

### Changes from #6492

Each #6492 change was checked against current `develop`:

| #6492 change | Decision |
| --- | --- |
| Skip observation-term clones | Not taken: `develop` already provides
this through #8038. |
| Cabinet direct `actions.clone()` | Not taken: the line no longer
exists. |
| `ActionManager` caches term dimensions | **Taken.** |
| Cartpole direct index cleanup | **Taken and extended.** #6492 fixed 1
of the 9 synchronizations caused by host-list joint indexing. Storing
the joint indices as device tensors removes all 9. |
| Drop `actions.clone()` in the Cartpole and Reorient direct tasks |
**Taken.** Neither task modifies the stored actions in place. |
| Drop `actions.clone()` in the Locomotion direct task | **Not taken.**
Its reset zeroes `self.actions` in place, which would zero the policy's
own action tensor, e.g. the one held in RL rollout storage. |

### Investigated and dropped: Newton sensor-graph flag cache

An earlier revision cached the Newton sensor graph's task flags and
skipped the upload when they were unchanged, on the premise that each
upload synchronized the stream. That premise does not hold for the
current Warp (1.17), so the change was reverted and `develop`'s per-call
upload is kept:

- Warp uploads the flags with a single `cudaMemcpyAsync` from pageable
memory, which CUDA stages on the host without waiting for the stream.
- Behind about 455 ms of Warp kernels queued on the same stream, ten
uploads return in 0.07–0.13 ms.
- An Nsight Systems trace of the Kuka camera task shows each flag
upload's `cudaMemcpyAsync` returning in 5.9 µs on average, 35.6 µs at
most.
- End to end (Kuka camera task, 256 environments), `develop`'s upload,
the cache, and device-side flag writes measured 12.53, 12.50, and 12.47
ms per step. That spread is within run-to-run noise (12.45–12.58 ms).

## Series

1. #8036: Read camera outputs through `ProxyArray.torch` (bug fix)
(base: develop)
2. #8037: Fused normalization for strided camera images (base: #8036)
3. #8038: Skip redundant observation copies (base: #8037)
4. #8039: Remove per-step host synchronizations (base: develop)
5. #8040: Newton `render_batch` in one sensor-graph launch (base:
develop)
6. #8041: RSL-RL cuDNN benchmark, mixed precision and compile settings
(base: develop)
7. #8042: Kuka Allegro camera tasks on the shared image observation
(base: #8038)

The series is split from #7440, which remains the combined reference
branch.

## Type of change

- Bug fix (non-breaking change which fixes an issue)
- Changes to `SuccessMonitor`: `get_mean_success_rate()` returns a 0-d
tensor instead of a float, and `success_update()` gains a `valid`
argument. The changelog includes migration guidance.

## Performance

RTX PRO 6000 Blackwell Workstation Edition (driver 595.91.07); PyTorch
2.12.0+cu130; Warp 1.17.0; Newton 1.6.0; GPU otherwise idle. `develop`
at `10fdf81d9` compared with this PR (`b2727a0f2`; later commits only
trim comments and revert the Newton change above), with the same
`uv.lock`. Runtime benchmark (`isaaclab benchmark runtime`),
Newton/MJWarp, seed 42, no visualizer. Three fresh processes per
revision, run in alternating order. Figures are the mean step time
across processes.

| Workload | `develop` | This PR | Change |
| --- | ---: | ---: | ---: |
| `Isaac-Lift-KukaAllegro-Camera`, 256 envs,
`presets=duo_camera,rgb128`, Newton renderer (500 steps) | 14.44 ms |
12.62 ms | **−12.6%** (+14.4% throughput) |
| `Isaac-Cartpole-Direct`, 4096 envs (2,000 steps) | 1.674 ms | 1.441 ms
| **−13.9%** (+16.2% throughput) |
| `Isaac-Pendulum-MARL-Direct`, 4096 envs (2,000 steps) | 2.144 ms |
1.862 ms | **−13.2%** (+15.2% throughput) |

Per-process step times (`develop` → PR):
- Camera: `14.44, 14.48, 14.40` → `12.67, 12.63, 12.57` ms.
- Cartpole: `1.680, 1.685, 1.657` → `1.446, 1.438, 1.439` ms.
- Pendulum: `2.137, 2.158, 2.137` → `1.827, 1.863, 1.895` ms.

Host synchronizations per `env.step()`, attributed to call sites with
PyTorch sync-debug mode over 170 steps (4096 envs):

| Task | `develop` | This PR | Remaining |
| --- | ---: | ---: | --- |
| `Isaac-Lift-KukaAllegro-Camera` (`presets=cube`, Newton renderer) |
21.3 | 4.2 | step reset and command-resample `nonzero`; curriculum,
command-metric, and termination logging reads |
| `Isaac-Cartpole-Direct` | 10.3 | 1.0 | step reset `nonzero` |
| `Isaac-Pendulum-MARL-Direct` | 10.0 | 1.0 | step reset `nonzero` |

PyTorch labels sync-debug mode a prototype that does not detect every
synchronization, and it does not see synchronizations issued by Warp, so
these counts are lower bounds.

Reproduce with:

```bash
uv run --frozen isaaclab benchmark runtime \
  --task Isaac-Lift-KukaAllegro-Camera --num_envs 256 --num_steps 500 \
  --warmup_steps 100 --seed 42 --device cuda:0 --visualizer none \
  --output_path /tmp/pr8039 physics=newton_mjwarp renderer=newton_renderer presets=duo_camera,rgb128
```

### Not addressed

- **Step reset and command resampling:** both still call `nonzero` once
per step. Both convert a mask into variable-length environment IDs, and
the reset and command pipelines consume those IDs throughout. Removing
these synchronizations means moving those pipelines to masks or padded
IDs, which is out of scope here.
- **Warp-side synchronizations:** the Nsight trace above also records
many `cudaStreamSynchronize` calls outside the flag uploads, which
PyTorch's sync-debug mode cannot attribute. Their sources are not yet
identified.

## Validation

- Cartpole direct produces bit-identical observation and reward
checksums to `develop` after 150 seeded steps, including resets.
- Pendulum MARL is not run-to-run deterministic on MJWarp. Its
observations and rewards were instead compared on identical state
against `develop`'s host-index formulas for 150 steps, with a maximum
difference of 0.0. Reorient direct is also non-deterministic; its change
only removes a copy of an action tensor that is never modified in place.
- `test_circular_buffer.py`, `test_noise.py`, `test_curriculum.py`, the
manager tests (including `test_event_manager.py`,
`test_reward_manager.py`, `test_termination_manager.py`, and
`test_scene_entity_cfg.py`), `test_lift_env_cfg.py`,
`test_sensor_base.py`, `test_visualization_markers.py`, and
`test_kit_visualizer_scene_partitioning.py` pass.
- `test_rendering_lift_kuka_homo_kitless.py` passes for the Newton
renderer and legacy OVRTX cases. The two `ovstage` OVRTX cases fail
identically on `develop`.
- `uv run --frozen isaaclab -f` passes, including changelog checks.

## Release backport

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

---------

Co-authored-by: Octi Zhang <[email protected]>

(cherry picked from commit 60bc09f)
@StafaH StafaH closed this Sep 28, 2026
@StafaH
StafaH deleted the perf/remove-hot-path-host-syncs branch October 10, 2026 19:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

isaac-lab Related to Isaac Lab team

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants