Skip to content

Optimizes the performance of circular buffer - #4275

Closed
iansseijelly wants to merge 8 commits into
isaac-sim:developfrom
ucb-bar:delayed_actuator_perf_fix
Closed

iansseijelly wants to merge 8 commits into
isaac-sim:developfrom
ucb-bar:delayed_actuator_perf_fix

Conversation

@iansseijelly

@iansseijelly iansseijelly commented Dec 23, 2025 •

Copy link
Copy Markdown

Description

This PR addresses issue #4274.

Type of change

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

Screenshots

Training throughput before and after the patch running training on task [Isaac-Velocity-Flat-Spot-v0].

delayed_buffer_perf_fix ## 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 updated the changelog and the corresponding version in the extension's config/extension.toml file
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

@github-actions github-actions Bot added bug Something isn't working isaac-lab Related to Isaac Lab team labels Dec 23, 2025
@greptile-apps

greptile-apps Bot commented Dec 24, 2025

Copy link
Copy Markdown
Contributor

Greptile Summary

Optimized circular buffer performance by eliminating GPU-CPU synchronization in the hot path, addressing the performance issue identified in #4274.

Key optimizations:

  • Cached max_length as an integer to avoid repeated .item() calls that trigger GPU sync
  • Added _all_initialized flag to skip first-push checks after warmup, avoiding torch.any().item() calls
  • Removed unnecessary .clone() in DelayBuffer.compute() return path
  • Changed to in-place assignment ([:]) in DelayedPDActuator to avoid tensor reallocation

Performance impact:
According to the PR description, profiling showed excessive time spent in aten::item (89% CPU time) and torch.any checks. These optimizations eliminate both bottlenecks in steady-state operation after warmup.

Code correctness:

  • The in-place assignment pattern is safe because CircularBuffer.__getitem__ returns indexed views
  • The _all_initialized flag is correctly reset on buffer reset
  • Initialization logic still handles first-push correctly before setting the flag

Confidence Score: 4/5

  • This PR is safe to merge with minimal risk - well-targeted performance optimizations
  • The changes are focused performance optimizations that eliminate GPU-CPU synchronization overhead without altering logic. The coordinated changes across three files (caching max_length, skipping checks after warmup, removing clone, using in-place assignment) work together correctly. Minor deduction because there are no new tests to verify the optimizations don't break edge cases, though the logic appears sound.
  • No files require special attention

Important Files Changed

Filename Overview
source/isaaclab/isaaclab/utils/buffers/circular_buffer.py Optimized to avoid GPU-CPU synchronization in hot path by caching max_length as integer and tracking initialization state
source/isaaclab/isaaclab/utils/buffers/delay_buffer.py Removed unnecessary .clone() call since consumer now uses in-place assignment
source/isaaclab/isaaclab/actuators/actuator_pd.py Changed to in-place assignment to avoid unnecessary tensor allocation and copying

Sequence Diagram

sequenceDiagram
    participant Actuator as DelayedPDActuator
    participant DelayBuf as DelayBuffer
    participant CircBuf as CircularBuffer
    
    Note over Actuator,CircBuf: Hot Path (called every physics step)
    
    Actuator->>DelayBuf: compute(control_action.joint_positions)
    DelayBuf->>CircBuf: append(data)
    
    alt First time after reset
        CircBuf->>CircBuf: Check _all_initialized flag (false)
        CircBuf->>CircBuf: Check is_first_push = (_num_pushes == 0)
        CircBuf->>CircBuf: Call .any().item() (GPU sync)
        CircBuf->>CircBuf: Initialize buffer if needed
        CircBuf->>CircBuf: Set _all_initialized = true
    else All batches initialized (optimized path)
        CircBuf->>CircBuf: Skip initialization check
        Note over CircBuf: No GPU-CPU sync needed!
    end
    
    CircBuf->>CircBuf: Increment _num_pushes
    DelayBuf->>CircBuf: __getitem__(time_lags)
    CircBuf-->>DelayBuf: Return delayed data (view)
    DelayBuf-->>Actuator: Return delayed data (no clone)
    Actuator->>Actuator: In-place assign with [:]
    
    Note over Actuator,CircBuf: Optimizations Applied:<br/>1. Cached max_length as int (avoid .item())<br/>2. Skip initialization check after warmup<br/>3. Removed unnecessary .clone()<br/>4. In-place assignment in actuator
Loading

@greptile-apps

greptile-apps Bot commented Dec 24, 2025

Copy link
Copy Markdown
Contributor

Greptile found no issues!

From now on, if a review finishes and we haven't found any issues, we will not post anything, but you can confirm that we reviewed your changes in the status check section.

This feature can be toggled off in your Code Review Settings by deselecting "Create a status check for each PR".

@garylvov

Copy link
Copy Markdown
Collaborator

Hi, this is a cool optimization, I'm excited to try it, thank you!

Two quick qs:

  • Does this only affect configurations that use the delayed PD actuator, or does it apply to all actuator configurations?
  • I see in your charts that the FPS is improved. How much of a difference does this make in cumulative training time? Like, does it go from 2 hours to train to 1.5 hours to train? I'd love to see the reward with and without the optimization over time

control_action.joint_positions = self.positions_delay_buffer.compute(control_action.joint_positions)
control_action.joint_velocities = self.velocities_delay_buffer.compute(control_action.joint_velocities)
control_action.joint_efforts = self.efforts_delay_buffer.compute(control_action.joint_efforts)
control_action.joint_positions[:] = self.positions_delay_buffer.compute(control_action.joint_positions)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is the assignment operation here needed? 🤔

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This uses slice assignment to keep the original tensor storage (control_action.joint_positions etc.) and overwrite its contents in place. Without this, compute() may return a new tensor, causing buffer replacement and additional allocation or copy overhead.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The delay buffer anyway returns a copied tensor since the time-lags indexed the torch tensor internally. The operation here will do another copy of that tensor which I don't think is needed. Also it will override the initial command set into the environment (after action processing). This may affect the next decimation consequently.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@iansseijelly and @T-K-233 : Let me know your thoughts on the above. Thanks again!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pinging again. @iansseijelly @T-K-233

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Sorry, I missed this comment earlier.
The intention of line this was just to replace the .clone called from the original compute here to save the cost of one allocation. Indeed, the time-lag index should create a copied tensor, so if the original clone is unuseful, then so is this one.
Regarding the decimation comment, I do not fully get it. But the decimation semantics should remain unchanged before and after this PR.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I agree it'd be better removing the [:] in these lines if they are not necessary.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks, I have removed them accordingly.

@Mayankm96 Mayankm96 changed the title perf: optimize the performance of circular buffer Optimize the performance of circular buffer Dec 27, 2025
@T-K-233

T-K-233 commented Dec 27, 2025

Copy link
Copy Markdown
Contributor

Hi, this is a cool optimization, I'm excited to try it, thank you!

Two quick qs:

  • Does this only affect configurations that use the delayed PD actuator, or does it apply to all actuator configurations?

It only affect the delayed PD actuator. Only the DelayedPDActuator utilizes the DelayBuffer object.

  • I see in your charts that the FPS is improved. How much of a difference does this make in cumulative training time? Like, does it go from 2 hours to train to 1.5 hours to train? I'd love to see the reward with and without the optimization over time

For the Isaac-Velocity-Flat-Spot-v0 task, the cumulative training time reduces from 45.76 minutes to 42.35 minutes. This is with 2000 iters, and the difference will become bigger for longer training runs.

The reward and metric of this task with and without this change is identical.

image

The full tensorboard log is also attached for reference:

spot_training_logs.zip

@garylvov

garylvov commented Dec 27, 2025 •

Copy link
Copy Markdown
Collaborator

Awesome, thank you for answering my questions, I really appreciate it!

@Mayankm96 Mayankm96 moved this to In review in Isaac Lab Jan 12, 2026

@AntoineRichard AntoineRichard left a comment

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 policies are training well on this branch and they do transfer to main, so it's likely the implementation is correct.

Code-wise it also looks good. I've suggested some modification to further improve the performance, but it's not as substantial as removing the cloning step. If we are in a rush we can get this in as is. These will likely get reworked to support warp anyway.

Comment on lines +170 to +172
if self._need_reset:
if self._buffer is None or (self._num_pushes == 0).any().item():
raise RuntimeError("Attempting to retrieve data on an empty circular buffer. Please append data first.")

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.

Mostly a NIT but I'm not sure, about these lines.
If you need a reset, do we need to perform that extra check to raise the exception?
Also what happens if the self._need_reset flag is True, but none of the other checks are True. Should we still return the buffer?

It looks to me that if _need_reset is False, then append should have made sure none of the other conditions could be True.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

In practice, this is never raised. I wanted to match the semantics of the original code, but guard the check with a scalar value to make it cheaper, so hence the change. The assumption here is that when _need_reset is True, the conditions in here better be true, because _need_reset is a shadow boolean state in cpu.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

could we simplify this to check only for self._need_reset then if that's the only value needed?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yeah, sounds good. I have made teh changes accordingly. This should also be safe, since overall we are expected to only call getitem after at least one append.

@@ -100,6 +104,8 @@ def reset(self, batch_ids: Sequence[int] | None = None):
batch_ids = slice(None)
# reset the number of pushes for the specified batch indices
self._num_pushes[batch_ids] = 0
# reset is needed on next update to fill entire buffer with initial data
self._need_reset = True
if self._buffer is not None:
# set buffer at batch_id reset indices to 0.0 so that the buffer() getter returns the cleared circular buffer after reset.
self._buffer[:, batch_ids, :] = 0.0

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.

Consider replacing with:
self._buffer[:, batch_ids].zero_()

Benchmarking with BATCH_SIZE=4096, NUM_JOINTS=12, HISTORY_LENGTH=6
====================================================================================================
Scenario                  | Method 1 (= 0.0)          | Method 2 (.zero_())       | Best         
----------------------------------------------------------------------------------------------------
1 reset (single index)    | 20.33 ± 1.51 µs           | 19.52 ± 1.70 µs           | Method 2 (1.04x)
10 resets                 | 21.42 ± 1.55 µs           | 21.20 ± 1.67 µs           | Method 2 (1.01x)
100 resets                | 22.24 ± 1.60 µs           | 21.64 ± 1.20 µs           | Method 2 (1.03x)
500 resets                | 21.91 ± 1.03 µs           | 21.57 ± 1.10 µs           | Method 2 (1.02x)
1000 resets               | 22.03 ± 1.30 µs           | 21.79 ± 1.16 µs           | Method 2 (1.01x)
2048 resets (half)        | 22.61 ± 2.16 µs           | 22.31 ± 1.34 µs           | Method 2 (1.01x)
All resets (N)            | 23.23 ± 1.37 µs           | 23.18 ± 0.51 µs           | Method 2 (1.00x)
====================================================================================================

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I agree with this. Thanks for the detailed microbenchmark.

Comment on lines +140 to +142
is_first_push = self._num_pushes == 0
if is_first_push.any().item():
self._buffer[:, is_first_push] = data[is_first_push]

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.

I would also consider doing:

is_first_push = self._num_pushes == 0
expanded_mask = is_first_push[None, :, None].expand_as(self._buffer)
expanded_data = data[None].expand_as(self._buffer)
torch.where(expanded_mask, expanded_data, self._buffer,  out=self._buffer)

This should be about 3 times faster than:

is_first_push = self._num_pushes == 0
self._buffer[:, is_first_push] = data[is_first_push]

And then it saves you the:

if is_first_push.any().item():

which on its own costs about 0.6x the time of:

is_first_push = self._num_pushes == 0
expanded_mask = is_first_push[None, :, None].expand_as(self._buffer)
expanded_data = data[None].expand_as(circular_buffer)
torch.where(expanded_mask, expanded_data, self._buffer, self._buffer)

TLDR; replace:

is_first_push = self._num_pushes == 0
            if is_first_push.any().item():
                self._buffer[:, is_first_push] = data[is_first_push]

with:

is_first_push = self._num_pushes == 0
if is_first_push.any().item():
    expanded_mask = is_first_push[None, :, None].expand_as(self._buffer)
    expanded_data = data[None].expand_as(self._buffer)
    torch.where(expanded_mask, expanded_data, self._buffer, out=self._buffer)
[INFO] Using python from: /home/antoiner/Documents/IsaacLab-Internal/_isaac_sim/python.sh                                                                                              
Benchmarking with BATCH_SIZE=4096, NUM_JOINTS=12, HISTORY_LENGTH=6
============================================================================================================================================
Scenario             | direct_mask        | where_mask         | Best
--------------------------------------------------------------------------------------------------------------------------------------------
1 reset              |  94.4± 3.6µs |  25.0± 1.1µs | where_mask
10 resets            |  96.8± 4.2µs |  25.3± 0.8µs | where_mask
100 resets           |  99.3± 4.2µs |  25.3± 1.7µs | where_mask
500 resets           |  99.7± 4.5µs |  25.5± 1.5µs | where_mask
1000 resets          |  98.9± 3.4µs |  25.3± 1.0µs | where_mask
2048 resets (half)   |  99.8± 3.4µs |  26.0± 1.4µs | where_mask
All resets (N)       | 100.3± 3.7µs |  26.0± 1.7µs | where_mask
============================================================================================================================================

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I also agree with this. Looks like it saves a lot of time.
Probably need a little more comment/documentation on what's happening here since mask programming is less interpretable.

@Mayankm96
Mayankm96 force-pushed the main branch 2 times, most recently from 2ef7fc8 to f3061a4 Compare January 28, 2026 16:16
@iansseijelly

Copy link
Copy Markdown
Author

Hi, we have just addressed the suggestions that @AntoineRichard provided.
Thanks for the help, everyone :)

@kellyguo11
kellyguo11 changed the base branch from main to develop February 7, 2026 04:45
@kellyguo11 kellyguo11 changed the title Optimize the performance of circular buffer Optimizes the performance of circular buffer Feb 7, 2026
@kellyguo11

Copy link
Copy Markdown
Contributor

@iansseijelly Thanks for the improvements and addressing the comments! As we've shifted our development to the new develop branch, could you do a rebase to resolve the conflicts on top of develop?

@T-K-233
T-K-233 force-pushed the delayed_actuator_perf_fix branch from 2a30454 to d8658a8 Compare February 9, 2026 17:24
@iansseijelly

Copy link
Copy Markdown
Author

@iansseijelly Thanks for the improvements and addressing the comments! As we've shifted our development to the new develop branch, could you do a rebase to resolve the conflicts on top of develop?

We just rebased atop develop. Thanks.

@kellyguo11

Copy link
Copy Markdown
Contributor

hmm github is not giving me the option to update the branch. could you grab the latest changes from tot develop so that the CI tests can run? we added a fix recently that was preventing the installation from working.

…n the hot path, avoiding unnecessary kernel and synchronization
@T-K-233
T-K-233 force-pushed the delayed_actuator_perf_fix branch from d03d7bf to 20b53cf Compare February 13, 2026 00:27
@iansseijelly

Copy link
Copy Markdown
Author

Hi, I just rebased again atop develop. Can you try again? Thanks for the help.

@kellyguo11

Copy link
Copy Markdown
Contributor

Thanks a lot! seeing a test failure in test_observation_manager.py

source/isaaclab/test/managers/test_observation_manager.py ......F....... [ 93%]
.                                                                        [100%]

=================================== FAILURES ===================================
_________________________ test_compute_with_2d_history _________________________
source/isaaclab/test/managers/test_observation_manager.py:462: in test_compute_with_2d_history
    observations = obs_man.compute()
                   ^^^^^^^^^^^^^^^^^
source/isaaclab/isaaclab/managers/observation_manager.py:337: in compute
    obs_buffer[group_name] = self.compute_group(group_name, update_history=update_history)
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
source/isaaclab/isaaclab/managers/observation_manager.py:421: in compute_group
    circular_buffer.append(obs)
source/isaaclab/isaaclab/utils/buffers/circular_buffer.py:145: in append
    expanded_mask = is_first_push[None, :, None].expand_as(self._buffer)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E   RuntimeError: The expanded size of the tensor (256) must match the existing size (20) at non-singleton dimension 3.  Target sizes: [5, 20, 128, 256, 1].  Tensor sizes: [1, 20, 1]

Dexsuite task in test_environments.py also failing with similar error:

________ test_environments[Isaac-Dexsuite-Kuka-Allegro-Lift-v0-32-cuda] ________
source/isaaclab_tasks/test/test_environments.py:38: in test_environments
    _run_environments(task_name, device, num_envs, create_stage_in_memory=False)
source/isaaclab_tasks/test/env_test_utils.py:158: in _run_environments
    _check_random_actions(
source/isaaclab_tasks/test/env_test_utils.py:230: in _check_random_actions
    obs, _ = env.reset()
             ^^^^^^^^^^^
/isaac-sim/kit/python/lib/python3.12/site-packages/gymnasium/wrappers/common.py:400: in reset
    return super().reset(seed=seed, options=options)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/isaac-sim/kit/python/lib/python3.12/site-packages/gymnasium/core.py:333: in reset
    return self.env.reset(seed=seed, options=options)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
source/isaaclab/isaaclab/envs/manager_based_env.py:384: in reset
    self.obs_buf = self.observation_manager.compute(update_history=True)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
source/isaaclab/isaaclab/managers/observation_manager.py:337: in compute
    obs_buffer[group_name] = self.compute_group(group_name, update_history=update_history)
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
source/isaaclab/isaaclab/managers/observation_manager.py:412: in compute_group
    circular_buffer.append(obs)
source/isaaclab/isaaclab/utils/buffers/circular_buffer.py:145: in append
    expanded_mask = is_first_push[None, :, None].expand_as(self._buffer)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E   RuntimeError: The expanded size of the tensor (4) must match the existing size (32) at non-singleton dimension 2.  Target sizes: [5, 32, 4, 3].  Tensor sizes: [1, 32, 1]

@T-K-233

T-K-233 commented Mar 5, 2026

Copy link
Copy Markdown
Contributor

Thanks. We have fixed the logic.

I think @AntoineRichard 's solution only applies to the actuator's case. However, Isaac Lab test catches a case where input tensor can be higher dimensional (dim=5 in the failing case).

Additionally, we realized that the suggested line

torch.where(expanded_mask, expanded_data, self._buffer,  out=self._buffer)

does not apply any effect.

We are reverting to our initial solution.

@StafaH

StafaH commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

Hi @iansseijelly, sorry for the delay in getting back to you here. We are still interested in getting this merged in, are you able to update the MR and resolve the conflicts? If you can also post up-to-date benchmark results in the perf difference that would be appreciated!

@ooctipus

ooctipus commented Jul 12, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks @iansseijelly (and apologies for the long open time) — the ideas here have since landed on develop via the frame-stacking refactor (#5574, #5849): _max_len_int avoids the .item() sync in max_length, and the CPU-side _need_reset gate skips the steady-state torch.any probe. The final piece this PR targeted — the torch.any + masked backfill inside append — is removed in #6471 with benchmarks. Closing as superseded; the analysis here was correct and is now fully covered on develop.

@ooctipus ooctipus closed this Jul 12, 2026
@github-project-automation github-project-automation Bot moved this from In review to Done in Isaac Lab Jul 12, 2026
ooctipus added a commit that referenced this pull request Jul 13, 2026
## Description

`CircularBuffer.append` backfills all history slots on the first push
after a reset. The current implementation gates the backfill on
`torch.any(is_first_push)` (device-scalar to Python bool) and applies it
with boolean-mask indexing (host-synchronizing `nonzero`). With per-env
resets, both fire on nearly every append at scale: with 8
history-enabled observation buffers this costs ~24 stream syncs per env
step at 8192 envs.

This change applies the backfill branchlessly with `torch.where(...,
out=self._buffer)`: in-place, no allocation, no host synchronization,
identical results.

## Benchmark

Standalone A/B on this file only (RTX 5090, torch CUDA):
`batch_size=8192`, `max_len=5`, feature dim 32, 2000 steps, each step
resetting a random 2% of batch ids (typical episode-termination rate)
followed by one append. Warmup excluded, `torch.cuda.synchronize()`
outside the timed loop.

| layout | develop | this PR | speedup |
|---|---|---|---|
| legacy (`stack_dim=None`) | 143.3 µs/append | 78.6 µs/append |
**1.82×** |
| stacked (`stack_dim=1`) | 152.0 µs/append | 85.9 µs/append | **1.77×**
|
| no pending resets (both layouts' shared path) | 30.1 µs/append | 30.0
µs/append | 1.00× |

Equivalence: after the 2000 mixed reset/append steps,
`torch.equal(buffer_old, buffer_new)` is `True` in both layouts.

In a full dexsuite training loop (Isaac-Lift-Franka, Newton/mjwarp, 8192
envs) this was part of a sweep that removed ~56 of ~133
`cudaStreamSynchronize` calls per env step, worth ~+20% collection FPS
overall.

## Related work

#5395 and #4275 attacked the same sync class earlier; most of their
content has since landed via the frame-stacking refactor (#5574/#5849):
the CPU-side `_need_reset` gate, `_max_len_int` (no `.item()` in the
`max_length` property), the sync-free `__getitem__`, and the
`DelayBuffer` clone removal are all in `develop` today. The masked
first-push backfill inside the `_need_reset` branch is the one remaining
per-step sync from that series — this PR completes it.

## Type of change

- Bug fix / performance (non-breaking)

## Checklist

- [x] I have run the `pre-commit` checks with `./isaaclab.sh --format`
- [x] I have added my changelog fragment under `changelog.d`
matthewtrepte pushed a commit to matthewtrepte/IsaacLab that referenced this pull request Aug 4, 2026
## Description

`CircularBuffer.append` backfills all history slots on the first push
after a reset. The current implementation gates the backfill on
`torch.any(is_first_push)` (device-scalar to Python bool) and applies it
with boolean-mask indexing (host-synchronizing `nonzero`). With per-env
resets, both fire on nearly every append at scale: with 8
history-enabled observation buffers this costs ~24 stream syncs per env
step at 8192 envs.

This change applies the backfill branchlessly with `torch.where(...,
out=self._buffer)`: in-place, no allocation, no host synchronization,
identical results.

## Benchmark

Standalone A/B on this file only (RTX 5090, torch CUDA):
`batch_size=8192`, `max_len=5`, feature dim 32, 2000 steps, each step
resetting a random 2% of batch ids (typical episode-termination rate)
followed by one append. Warmup excluded, `torch.cuda.synchronize()`
outside the timed loop.

| layout | develop | this PR | speedup |
|---|---|---|---|
| legacy (`stack_dim=None`) | 143.3 µs/append | 78.6 µs/append |
**1.82×** |
| stacked (`stack_dim=1`) | 152.0 µs/append | 85.9 µs/append | **1.77×**
|
| no pending resets (both layouts' shared path) | 30.1 µs/append | 30.0
µs/append | 1.00× |

Equivalence: after the 2000 mixed reset/append steps,
`torch.equal(buffer_old, buffer_new)` is `True` in both layouts.

In a full dexsuite training loop (Isaac-Lift-Franka, Newton/mjwarp, 8192
envs) this was part of a sweep that removed ~56 of ~133
`cudaStreamSynchronize` calls per env step, worth ~+20% collection FPS
overall.

## Related work

isaac-sim#5395 and isaac-sim#4275 attacked the same sync class earlier; most of their
content has since landed via the frame-stacking refactor (isaac-sim#5574/isaac-sim#5849):
the CPU-side `_need_reset` gate, `_max_len_int` (no `.item()` in the
`max_length` property), the sync-free `__getitem__`, and the
`DelayBuffer` clone removal are all in `develop` today. The masked
first-push backfill inside the `_need_reset` branch is the one remaining
per-step sync from that series — this PR completes it.

## Type of change

- Bug fix / performance (non-breaking)

## Checklist

- [x] I have run the `pre-commit` checks with `./isaaclab.sh --format`
- [x] I have added my changelog fragment under `changelog.d`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working isaac-lab Related to Isaac Lab team

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

8 participants