Skip to content

Keep Newton CUDA graph captures free of graph memory - #8528

Closed
egolubev-nvda wants to merge 1 commit into
isaac-sim:developfrom
egolubev-nvda:egolubev/fix-newton-capture-graph-memory
Closed

egolubev-nvda wants to merge 1 commit into
isaac-sim:developfrom
egolubev-nvda:egolubev/fix-newton-capture-graph-memory

Conversation

@egolubev-nvda

Copy link
Copy Markdown
Contributor

Description

On Windows, Newton's first CUDA graph capture can stall for many minutes when it runs after the OVRTX renderer's first frame. This PR keeps Newton captures free of graph memory, which removes the trigger.

Fixes #8342.

Root cause

Measured on Windows 11, RTX 6000 Ada, driver 596.72, with Isaac-Lift-KukaAllegro-Camera (presets=newton_mjwarp,ovrtx,single_camera,simple_shading_full_mdl64):

  • MuJoCo-Warp allocates temporary arrays on every step (make_constraint, _create_solver_context, implicit, ...). Inside NewtonQueries.capture_graph these become graph memory nodes (60 allocations per physics graph).
  • The first graph-memory allocation makes the driver reserve a 96 GiB virtual-address range, placed directly above a 52 GiB managed-memory window. The renderer creates that window: OVRTX loads Cubric even with ISAAC_LAB_OVRTX_USE_OVSTAGE=0, and Cubric allocates managed memory.
  • When the renderer's first frame has already taken GPU addresses just above that window (about 2.25 GiB in our runs), the driver retries placement 2 MiB higher each time. Each attempt costs about 0.8 s of kernel CPU while the GPU is idle, so getting past the blocked range takes about 15 minutes.
  • We observed this directly: the reservation's base address climbed 2 MiB per ~0.8 s, the capturing thread spent 1.00 s/s in kernel mode inside cuMemAllocAsync, and in runs that completed the reservation was placed on the first attempt.
  • Capture Newton CUDA graphs without advancing simulation #8058 moved Newton's first capture from solver setup to the first physics step, after the first frame. Fix Windows hangs by warming up Newton before CUDA graph capture #8316's eager first step does not help, because eager allocations use the ordinary pool, so the first graph-memory allocation still happens during capture.

Change

  • NewtonQueries.capture_graph installs _GraphLifetimeAllocator for the capture. It serves Python array allocations made during capture from ordinary device memory, with the thread's capture mode exchanged to relaxed around cudaMalloc, as Warp's native sort does for its capture-time allocations. The captured graph has no memory nodes, so the driver never reserves graph memory.
  • A block freed during the top-level recording is reused by a later same-size allocation in that recording, as graph memory is. Blocks freed inside conditional bodies (capture_while / capture_if) or after recording may still be read by replays, so they are held and freed when the graph is released (weakref.finalize).
  • This covers physics, sensor and run_query graphs. Behavior is the same on all platforms.

Measurements

Before (1d5a8fc) After
Camera task, 1024 envs, stalls (8 s capture watchdog) 7 / 10 0 / 10
Graph memory after first replay, 8192 envs 224 MiB 0
Physics step, 8192 envs, synchronized, median of 3 23.967 ms 24.041 ms (+0.3%)
Peak GPU memory, 8192 envs 3.19 GB 3.26 GB
Capture time ~0.44 s 0.44–0.48 s

Measured on the commit above with the change applied; this branch is the same change rebased onto current develop.

Limits

  • Warp's native scratch allocations (array_scan, array_sum, radix sort, run-length encode) bypass Python allocators and still create graph memory. Captures that reach them (for example Newton mesh-plane contacts with reduce_contacts, SAP broad phase, deterministic contact sorting) are not covered. The Kuka tasks do not reach them (graph memory measured 0).
  • Uses private Warp entry points: wp_cuda_thread_exchange_capture_mode and wp_cuda_stream_get_capture_id.
  • wp.ScopedAllocator is device-wide during capture, so another thread allocating on the same device during capture would get memory held until that graph is released.

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 uv run isaaclab --format (ruff check and format on the changed files)
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have validated the changed behavior with focused coverage and applied the test-audit criteria to any test changes
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

On Windows, the first graph-memory allocation recorded after the renderer's
first frame can stall the CUDA driver for minutes. Serve Python array
allocations made during Newton captures from ordinary device memory held until
the graph is released, reusing blocks freed in the top-level recording.

Fixes isaac-sim#8342.
@egolubev-nvda
egolubev-nvda requested a review from a team October 13, 2026 17:53
@github-actions github-actions Bot added bug Something isn't working isaac-lab Related to Isaac Lab team labels Oct 13, 2026
@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High impact] The PR appears safe to merge; no actionable issue was found.

Summary

Newton captures now use ordinary device memory for Python array allocations. Freed blocks stay alive until the graph is released, except when later top-level allocations can reuse them.

  • Newton graph captures keep Python arrays out of graph memory.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Start capture] --> B[Install temporary allocator]
    B --> C[Allocate ordinary device memory]
    C --> D{Array freed during top-level recording?}
    D -->|Yes| E[Allow later same-size reuse]
    D -->|No| F[Hold freed block]
    E --> G[Finish capture]
    F --> G
    G --> H[Replay graph]
    H --> I[Graph released]
    I --> J[Free held blocks]
Loading

Reviews (1) · Last reviewed commit: "Keep Newton CUDA graph captures free of ..." · Reviewed by Greptile

@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.

Isaac Lab Review Bot

Needs attention: Implementation (1), Style consistency (2), Test quality (1). Other reviewed categories look good.

  • PR description: The description matches the diff and supplies revisions, hardware, workload, and metrics; add exact benchmark commands, warmup details, and the focused regression-test command.
  • Design and architecture: Architecture looks good.
  • Scope and over-engineering: No over-engineering issues.
  • API: API changes look good.
  • Compatibility and deprecation: No breaking changes identified.
  • Implementation: Capture-block reuse ignores the calling thread, allowing another thread using the device-wide scoped allocator to take graph-referenced memory; restrict reuse to the capturing thread.
  • Style consistency: The new private allocator violates the prescribed module layout by preceding public classes; move it after the module’s public classes.
  • Test quality: The allocator regression covers graph memory, replay, capture modes, and release, but its final post-release assertion is vacuous; assert the underlying deallocation or remove it.

Minor fixes needed. Posted 4 inline findings.

Automated review; human maintainers own approval decisions.

self.bvh_refit = TimestampedBuffer()


class _GraphLifetimeAllocator:

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.

🟡 Warning · Style Consistency — Private class precedes public classes

The documented file structure places private classes after public ones. Move _GraphLifetimeAllocator below NewtonQueries and the other public classes in this module.

be read by replays, so they are freed when the graph is released.
"""

memory_kind = wp.MemoryKind.CUDA_DEVICE

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.

🟡 Warning · Style Consistency — Class variable missing ClassVar hint

Class variables must carry a ClassVar[type] hint; ClassVar is already imported here. Annotate as memory_kind: ClassVar[wp.MemoryKind] = wp.MemoryKind.CUDA_DEVICE.


def allocate(self, size_in_bytes: int) -> int:
self.allocation_count += 1
reusable = self._reusable_blocks.get(size_in_bytes) if self._in_top_level_recording() else None

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.

🟡 Warning · Implementation — Capture-time reuse ignores calling thread

_in_top_level_recording queries the capture stream, not the caller, and ScopedAllocator is device-wide. A concurrent thread allocating during capture can receive a block the graph still writes on replay. Record and compare the capturing thread id.

# After release, frees go straight to the device.
survivor_ptr = survivors.pop().ptr
gc.collect()
assert all(ptr != survivor_ptr for ptr, _ in allocator._held_blocks)

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.

🟡 Warning · Test Quality — Vacuous post-release assertion

_held_blocks was just asserted empty and _graph_released prevents further appends, so this check passes regardless of behavior. Assert the device allocator receives the free, or drop these three lines.

@egolubev-nvda

Copy link
Copy Markdown
Contributor Author

Superseded by #8539, which applies @shi-eric's early graph-memory reservation from #8342. It is smaller, uses only public Warp API, also covers Warp's native scratch allocations, and fixes the same stall under Kit with Newton physics (measured 0/8 there, 7/8 on develop).

kellyguo11 pushed a commit that referenced this pull request Oct 14, 2026
# Description

On Windows, the first CUDA graph capture after the renderer's first
frame can stall for many minutes. This PR applies the workaround from
@shi-eric's analysis in #8342: record one tiny allocation in a CUDA
graph when `SimulationContext` is created, so the CUDA driver reserves
graph memory before anything can block its placement.

Fixes #8342. Supersedes #8528.

## Root cause (summary of #8342)

- The first allocation recorded in a CUDA graph makes the driver reserve
a large virtual-address range for graph memory (96 GiB on our machine).
- Cubric allocates managed memory, which creates a 52 GiB managed-memory
window. The driver places the graph-memory range directly above that
window.
- When a rendered frame already occupies those addresses, the driver
retries placement 2 MiB higher each time, at about 0.8 s of kernel CPU
per attempt. The GPU stays idle; getting past the blocked range takes
about 15 minutes.
- #8058 moved Newton's first capture to the first physics step, after
the first frame. MuJoCo-Warp allocates temporaries on every step, so the
capture contains allocations.

## Change

- `isaaclab.utils.device.reserve_cuda_graph_memory(device)`: records one
`wp.empty(1)` inside `wp.ScopedCapture`, once per CUDA device. It skips
non-CUDA devices, devices with the Warp memory pool disabled, and
devices that are already capturing. A failure is logged as a warning and
never blocks startup.
- `SimulationContext.__init__` calls it right after selecting the
device, before physics backends and renderers are created. Every entry
point (environments, benchmarks, tests) goes through this path.
- Runs on all platforms; on platforms without the driver issue the extra
capture is harmless.

## Measurements

Windows 11, RTX 6000 Ada, driver 596.72,
`Isaac-Lift-KukaAllegro-Camera`, 1024 envs, `newton_mjwarp`, capture
watchdog 8–15 s:

| Setup | `develop` | This PR |
|---|---|---|
| OVRTX (kitless),
`presets=newton_mjwarp,ovrtx,single_camera,simple_shading_full_mdl64` |
about 70% of runs stalled | 0 / 10 |
| Kit with Isaac Sim RTX,
`presets=newton_mjwarp,isaacsim_rtx,single_camera` | 7 / 8 stalled | 0 /
8 |

The Kit result means this stall is not limited to OVRTX: Kit with Newton
physics hits it too.

Other checks with the same workaround (applied at `gym.make`,
physics-only task, 8192 envs):

- A graph-memory trim right before Newton's capture does not release the
early reservation (0 / 8 stalls).
- Physics step, full environment step and peak GPU memory are within
noise of `develop`.

## Limits

- Under Kit, Kit's renderer starts before `SimulationContext`, so the
reservation cannot precede it. It still precedes Cubric's managed memory
and the next rendered frame, which was enough in the measurements above.
- OvPhysX imports `ovstage` in `_prepare_stage_creation`, before this
call. OvPhysX with OVRTX was not measured.
- Linux, L40, and long training runs were not tested here.
- Kit with PhysX physics was not tested.

## Type of change

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

## 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](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html)
- [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with
`uv run isaaclab --format` (ruff check and format on the changed files)
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have validated the changed behavior with focused coverage and
applied the [test-audit
criteria](https://github.com/isaac-sim/IsaacLab/blob/develop/skills/developer/test-audit/SKILL.md)
to any test changes
- [x] I have added a changelog fragment under
`source/<pkg>/changelog.d/` for every touched package
- [ ] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there
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

None yet

Development

Successfully merging this pull request may close these issues.

[Bug Report] Windows: Newton CUDA graph capture hangs in a Warp allocation (regression from #8058, not fixed by #8316)

1 participant