Skip to content

Add frame stacking support for explicit temporal info - #5574

Merged
kellyguo11 merged 5 commits into
isaac-sim:developfrom
jmart-nv:jmart/frame-stacking
May 16, 2026
Merged

kellyguo11 merged 5 commits into
isaac-sim:developfrom
jmart-nv:jmart/frame-stacking

Conversation

@jmart-nv

@jmart-nv jmart-nv commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

This enables frame stacking for newton+warp by default in the cartpole camera presets task.

Newton Frame Stacking: Provides explicit temporal data to newton.

RTX uses DLSS anti-aliasing by default, which provides implicit temporal data. The newton_renderer does not provide temporal data. However, newton's energy-conserving physics solver requires temporal velocity data in order to compensate for the lack of damping, which causes convergence problems when paired with newton_renderer.

This commit provides explicit temporal information via 2-frame stacking by default for cartpole-camera when using newton+newton_renderer. This allows newton to provide the damping it needs to converge at the same rate as physx. This adds 36% GPU memory overhead, but the wall clock overhead is negligible.

The default for all other physics/renderer backends is still stack size = 1 (disabled) since physx has implicit damping built-in via its TGS solver, and RTX provides temporal data implicitly.

Implementation:

For manager-based envs, a new stacked_image term is added to the MDP observations - tasks can opt into frame stacking by adding the stacked_image term to their observation cfg and setting frame_stack to a value > 1.

The cartpole camera presets direct env now implements frame stacking using CircularBuffer from isaaclab.utils.buffers directly in _get_observations.

Added new unit tests for the MDP term (mocked + ObservationManager E2E) and cartpole integration, and updated the documentation with a note about newton's dependency on temporal data.

Note: This is a task-local re-implementation of the closed PR #5232

Type of change

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

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

- Added `FrameStackBuffer` helper class which implements a ring buffer over the last N rendered frames.
- Hooked up frame stacking in cartpole camera cfg which defaults to 2 for newton+warp and 1 for all other combos, with cli override.
- Updated renderer docs to mention newton dependency on temporal information.
- Added new unit tests for the buffer and cartpole integration.
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels May 11, 2026
@greptile-apps

greptile-apps Bot commented May 11, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces a FrameStackBuffer ring buffer and a CartpoleCameraPresetsEnv subclass to provide explicit temporal observations for the Newton + Newton-Warp backend combination, where neither the physics solver nor the renderer supplies implicit temporal data.

  • FrameStackBuffer maintains a (frame_stack, num_envs, H, W, C) history tensor and reconstructs the stacked output in-place via narrow + copy_, avoiding per-frame allocations; the init-on-reset path correctly fills all history slots with the first post-reset frame so the policy never sees zero-padded warm-up data.
  • CartpoleCameraPresetsEnv wraps CartpoleCameraEnv, auto-detects the Newton+Warp combo via lazy isinstance checks, bumps observation_space before calling super().__init__(), and correctly clones the buffer's shared return value in _get_observations.
  • The frame_stack=0 sentinel in the config (meaning "auto-detect") is documented in comments but not enforced by validation, making it easy to misinterpret 0 as "disabled" when setting via CLI overrides.

Confidence Score: 4/5

Safe to merge with minor follow-up; the core ring-buffer logic is correct and well-tested, and the env wiring works for the current usage pattern.

The ring-buffer arithmetic, init-on-reset behavior, and env integration are all verified by a thorough test suite. The main concerns are design-level: cfg.observation_space[-1] is mutated in-place before the parent constructor runs (safe only if configclass always deep-copies), update() returns shared internal storage that callers must clone (current code does so correctly), and the frame_stack=0 sentinel could be misread by users as disabled rather than auto-detect. None of these affect correctness in the current code paths, but they introduce fragility for future callers and config overrides.

cartpole_camera_presets_env.py and cartpole_camera_presets_env_cfg.py deserve a second look — the in-place cfg mutation and the sentinel value design are the most likely sources of hard-to-diagnose bugs if the config machinery or user overrides change.

Important Files Changed

Filename Overview
source/isaaclab/isaaclab/envs/utils/frame_stack.py New FrameStackBuffer ring buffer class; ring arithmetic and init-on-reset logic are correct and well-tested, but update() returns shared mutable internal storage that callers must clone.
source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env.py New CartpoleCameraPresetsEnv subclass wiring FrameStackBuffer; correctly clones the stacked output, but mutates cfg.observation_space in-place before super().init() and passes Sequence[int] where torch.Tensor is declared.
source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py Adds frame_stack: int = 0 sentinel to BaseCartpoleCameraEnvCfg; sentinel semantics (0 = auto, 1 = disabled) are unintuitive and not enforced by validation.
source/isaaclab/test/envs/test_frame_stack.py Comprehensive pure-tensor unit tests covering ring ordering, partial env reset, dtype preservation, CUDA device, and long-run stability; no issues found.
source/isaaclab_tasks/test/test_cartpole_camera_presets_frame_stack.py Integration tests covering the full physics×renderer truth table, obs-space arithmetic for all data-type presets, and end-to-end env construction; good coverage of the sentinel resolution logic.
source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/init.py Redirects Isaac-Cartpole-Camera-Presets-Direct-v0 entry point to the new CartpoleCameraPresetsEnv; change is minimal and correct.
source/isaaclab/isaaclab/envs/utils/init.py Exports FrameStackBuffer from the utils package; no issues.
docs/source/overview/core-concepts/renderers.rst Adds a documentation note explaining Newton Warp renderer's lack of temporal anti-aliasing and recommending task-local frame stacking; clear and accurate.

Sequence Diagram

sequenceDiagram
    participant Env as CartpoleCameraPresetsEnv
    participant Base as CartpoleCameraEnv
    participant Buf as FrameStackBuffer

    Note over Env: __init__
    Env->>Env: resolve_cfg_presets(cfg)
    Env->>Env: _resolve_frame_stack_default() → 1 or 2
    Env->>Env: "bump cfg.observation_space[-1] *= frame_stack"
    Env->>Base: super().__init__(cfg)
    Env->>Buf: FrameStackBuffer(single_shape, frame_stack, device)

    Note over Env: per-step loop
    Env->>Base: super()._get_observations()
    Base-->>Env: obs[policy] shape (N,H,W,C)
    Env->>Buf: update(obs[policy])
    Buf->>Buf: fill history slots for reset envs (init path)
    Buf->>Buf: copy current frame into _history[frame_idx]
    Buf->>Buf: rebuild _stacked via narrow+copy_
    Buf-->>Env: "_stacked (N,H,W,C*K) shared ref"
    Env->>Env: .clone() → obs[policy]

    Note over Env: on episode reset
    Env->>Base: super()._reset_idx(env_ids)
    Env->>Buf: reset(env_ids) marks envs for init
    Note over Buf: next update() fills all history slots with first post-reset frame
Loading

Reviews (1): Last reviewed commit: "OMPE-88188: Add frame stacking support f..." | Re-trigger Greptile

- Update reset API to accept sequence of ints or torch tensor.
- Changed frame_stack default sentinel to `-1` to better communicate intent; `0` is now treated as "no stacking" (synonym for `1`.)
- Cleaned up observation space logic to avoid in-place mutation.
- Updated tests.

@isaaclab-review-bot isaaclab-review-bot Bot left a comment

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.

Code Review: Frame Stacking for Temporal Observations

This PR adds a well-designed FrameStackBuffer utility and integrates it into the cartpole camera presets task. The implementation addresses a real need—providing explicit temporal information for Newton+Warp where implicit temporal data isn't available. Overall structure is clean, but I found a few issues worth addressing.

Summary

Strengths:

  • Ring buffer design avoids per-frame allocations
  • Auto-detection of Newton+Warp combo is convenient
  • Comprehensive unit tests for the buffer itself
  • Good documentation of the temporal info requirement

Areas for improvement: See inline comments below.

- Added assertion for contiguity of frame stack buffer.
- Added new test for ring buffer shifting behavior.
- Replaced `FrameStackBuffer` helper class with the existing `CircularBuffer` from `isaaclab.utils.buffers`.
- Added `stacked_image(ManagerTermBase)` to `observations.py` so manager-based envs can opt into frame stacking via cfg.
- Refactored cartpole direct env to use `CircularBuffer` directly.
- Replaced buffer-level unit tests with 9 MDP-term tests + 3 `ObservationManager` E2E tests; cartpole task tests unchanged.
@jmart-nv
jmart-nv requested a review from ooctipus as a code owner May 12, 2026 15:58
@kellyguo11 kellyguo11 changed the title OMPE-88188: Add frame stacking support for explicit temporal info Add frame stacking support for explicit temporal info May 15, 2026
@kellyguo11 kellyguo11 moved this to Ready to merge in Isaac Lab May 15, 2026
@kellyguo11

Copy link
Copy Markdown
Contributor

@hujc7 fyi, changes to cartpole environments

@kellyguo11
kellyguo11 merged commit cafc911 into isaac-sim:develop May 16, 2026
52 of 56 checks passed
@github-project-automation github-project-automation Bot moved this from Ready to merge to Done in Isaac Lab May 16, 2026
@isaaclab-review-bot isaaclab-review-bot Bot mentioned this pull request May 16, 2026
7 tasks
jmart-nv added a commit to jmart-nv/IsaacLab that referenced this pull request Jun 4, 2026
…isaac-sim#5574.

- circular_buffer.py: replace torch.roll with O(1) write-index append; add CPU mirror of max_len and CPU bool gate to skip GPU sync on the steady-state path; rotate on read via the `buffer` property.
- observations.py (stacked_image): drop trailing `.clone()` from the permute().reshape() chain (reshape on non-contig already allocates).
- cartpole_camera_presets_env.py: same `.clone()` drop in the direct env.
- delay_buffer.py: same `.clone()` drop on the DelayBuffer.compute return.
pbarejko pushed a commit that referenced this pull request Jun 5, 2026
# Description

Frame-stacking was added to cartpole-camera by #5574 to make the task
solvable on the Newton+Warp backend. Single-frame RGB observations don't
carry pole velocity, so a single-image policy can only recover ~100/300
mean episode reward. On PhysX+RTX, implicit damping in the dynamics plus
temporal antialiasing in the renderer leak enough adjacent-frame
correlation that a single-frame policy still hits ~296. Newton+Warp has
neither, so explicit frame stacking is required for the task to be
solvable on this backend.

The implementation regressed throughput by 42% (54.6 → 31.7 FPS) and
inflated peak VRAM 2.7× (3.13 → 8.37 GB) at R256, 1024 envs. PR #5574
added a `CircularBuffer` ring + a `stacked_image` MDP term that:

1. Stored frames as **float32** even when the camera output was uint8 →
4× ring memory and 4× shift bandwidth.
2. Ran the per-frame normalize (`x/255 - mean(x)`) **before** the
buffer, forcing the buffer to be float32.
3. Re-rolled the buffer with `torch.roll` on every append → ring-sized
temporary per env.step.
4. Built the channel-stacked policy obs via `permute + reshape + clone`
→ fresh `(B, H, W, K*C)` float32 tensor per env.step.
5. Inlined the normalize math at 5 call sites across DirectRLEnv and
ManagerBasedEnv paths.

This PR rewrites the frame-stacking hot path; the result runs **24%
faster than the pre-framestack baseline** with identical PPO
convergence.

| Change | Why |
|---|---|
| **uint8 ring buffer.** Defer the `x/255 − mean` normalize past the
frame-stack buffer for RGB-like data types. | Ring is 4× smaller; shift
bandwidth per env.step drops 4×. |
| **Free contiguous stacked output.** New `CircularBuffer.stack_dim` arg
+ `.stacked` property arrange storage so the channel-stacked output is a
contiguous view of internal storage. | Eliminates one `(B, H, W,
K*C)`-sized allocation and a permute kernel per env.step. |
| **Drop `torch.roll` on append.** Replace with a front-to-back memmove.
| One fewer ring-sized allocation and one fewer kernel launch per
env.step. |
| **Fused Warp normalize kernel** (`normalize_image_uint8`). One kernel:
`(uint8 / 255) − per-(batch, channel) mean → float32`. | Replaces upcast
+ reduce + subtract (three PyTorch passes) with one fused launch over
the K-stacked input. |
| **Tiled int32 partial-sum reduction kernel**
(`spatial_sum_uint8_tiled`). Warp kernel writes `(B, NUM_TILES, C)`
int32 partials along H; PyTorch collapses the partial dim. | int32
accumulator is safe up to H·W·255 (128× headroom at R256) and ~3× faster
than int64 / float32 on PyTorch's auto-tuned reduce path. C-innermost
launch shape gives stride-1 reads on src's contiguous trailing dim. |
| **Shared `isaaclab.utils.images.normalize_camera_image` dispatch.**
One helper used by both `image()` (DirectRLEnv) and
`stacked_image.__call__` (ManagerBasedEnv); routes uint8 contiguous
inputs through the Warp fast path and falls back to PyTorch otherwise. |
Removes inline normalize math duplicated across 5 sites; the fast path
picks itself up automatically. |
| **`image(clone=False)` opt-out.** Callers that immediately copy into
their own storage skip the defensive clone. | Saves one obs-sized
allocation per env.step at the consumer site (frame-stack buffer). |
| **Allocator-managed obs lifetime.** `_get_observations` allocates the
normalize output fresh each call (no persistent `out=` buffer). | The RL
trainer holds a reference to the previous-iteration observation until
`record_transition` returns; reusing one buffer across env.step
boundaries aliases the trainer's prior obs. Fresh allocation lets
PyTorch's caching allocator hand out a different block while the prior
is still referenced. |

## Type of change

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

## Results

R256 (256×256), 1024 envs, PPO via skrl 2.1.0, seed 42, on NVIDIA L40.
Perf via non_rl measured over n=3 warm trials:

| Stage | FPS | step_ms | Peak VRAM | Mean reward |
|---|---|---|---|---|
| Pre-framestack baseline | 54.62 | 18.67 | 3.13 GB | ~102 (unsolvable —
no temporal info) |
| Frame stacking from #5574 | 31.72 | 32.07 | 8.37 GB | 297.68 |
| This PR (pre-rebase) | 67.87 | 15.32 | 4.41 GB | 297.60 |
| **This PR (post-rebase)** | **69.50** | **14.94** | **4.57 GB** |
**293.43** |

## Screenshots

<img width="1432" height="989" alt="pr_figure_v2"
src="https://github.com/user-attachments/assets/39791fc5-64ea-456d-83f5-d1faf2358ac9"
/>

## Environment

NVIDIA L40 (48 GB), driver 570.158.01. Newton+Warp backend
(`presets=newton_mjwarp,newton_renderer`). skrl 2.1.0 trainer.

## Checklist

- [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
`./isaaclab.sh --format`
- [ ] I have made corresponding changes to the documentation *(N/A -
frame stacking already documented, these changes are implementation
details)*
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have updated the changelog and the corresponding version in the
extension's `config/extension.toml` file
- [x] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there
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

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

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants