Skip to content

Fix Newton deferred graph warmup - #5983

Closed
AntoineRichard wants to merge 9 commits into
isaac-sim:developfrom
AntoineRichard:antoine/fix-newton-deferred-wrench
Closed

AntoineRichard wants to merge 9 commits into
isaac-sim:developfrom
AntoineRichard:antoine/fix-newton-deferred-wrench

Conversation

@AntoineRichard

@AntoineRichard AntoineRichard commented Jun 5, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Fixes #5961.

When Kit/RTX is active, CUDA graph capture is deferred until the first NewtonManager.step() because initialization may overlap RTX background-stream work. Before capture, _capture_relaxed_graph() performs an eager warmup simulation to allocate Newton solver buffers.

The warmup is not a user-visible IsaacLab step, but it was mutating the live state: it can advance positions and velocities, clear a staged state.body_f wrench, and swap the manager’s double-buffered states. The first graph replay could therefore begin from the warmup state rather than the caller-prepared state.

This PR snapshots both state buffers before warmup and restores their references and contents in a finally block before capture begins. Restoring both buffers is required because a solver may ping-pong them during warmup; synchronizing after restoration ensures capture sees the restored data.

The regression test forces deferred relaxed capture, stages a wrench that cancels gravity, and checks that the first visible replay has zero vertical velocity. The test uses native Warp arrays and adds no dependencies.

Dependencies: none.

Type of change

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

Screenshots

N/A — backend-only physics change.

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with ./isaaclab.sh -f
  • I have made corresponding changes to the documentation (not applicable; no user-facing documentation changed)
  • 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

Test Plan

  • ./isaaclab.sh -f
  • git diff --check
  • The focused CUDA regression needs an IsaacLab Python environment with Warp and a CUDA runtime. The local wrapper resolved to an environment without Warp, so CI/GPU validation must run it.

@github-actions github-actions Bot added bug Something isn't working isaac-lab Related to Isaac Lab team labels Jun 5, 2026

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

Review Summary

This PR fixes #5961 where the CUDA graph warmup run was inadvertently modifying state that would leak into the first user-visible physics step.

Root Cause & Fix

The warmup step in _capture_relaxed_graph() advances Newton outside normal IsaacLab step bookkeeping, purely to trigger lazy solver allocations before graph capture. The fix snapshots _state_0 and _state_1 before warmup, runs the warmup, then restores both object references and tensor data in a finally block — ensuring the internal warmup's state changes do not leak into the first real graph replay.


Incremental Review (e632b39)

The new commit addresses feedback from @pbarejko's review:

Changes Made

  1. Changelog clarified: The entry now accurately describes the fix as preventing "the internal warmup step" from leaking state, rather than the previous wording about preserving external wrenches. This better communicates what the code actually does.

  2. Docstring improved: The explanation of the warmup purpose is now clearer — emphasizes that warmup triggers lazy solver allocations and that state is restored so the internal advance doesn't become the initial state for real replays.

  3. Removed redundant wp.synchronize_stream:

    • Before: Two syncs — one after simulate(), one after .assign() in finally
    • After: One sync — only after the .assign() calls complete

    This addresses @pbarejko's question about why two syncs were needed. The warmup simulate() doesn't need a sync afterward because we're immediately restoring state anyway — we only need to ensure the restoration completes before graph capture begins.

Assessment

✅ The changelog now accurately describes the fix
✅ Double sync removed as @pbarejko questioned
✅ Comments/docstrings are clearer about the warmup's purpose
✅ pre-commit passed, CI still running


Previous Findings (from initial review)

1. Mixed cls vs NewtonManager in finally block — Minor (Style)

finally:
    NewtonManager._state_0 = state_0   # explicit class name
    NewtonManager._state_1 = state_1
    cls._state_0.assign(state_0_snapshot)  # cls

Still present. The inconsistency remains (functionally correct, stylistically inconsistent). Non-blocking.

2. Test Coverage — Positive

The regression test properly validates the fix by:

  • Forcing the deferred capture path
  • Staging a wrench that cancels gravity
  • Verifying first-step velocity remains ~0

Verdict

The incremental changes appropriately address reviewer feedback. The changelog is now accurate, and the double-sync question has been resolved by removing the unnecessary first sync. The fix remains correct.

No blocking issues. CI is still in progress at time of review.

Reviewed at e632b39 🤖

@greptile-apps

greptile-apps Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a bug in the Newton deferred CUDA graph warmup path where external wrenches (and other user-staged writes to _state_0) were silently consumed during the warmup step and thus lost on the first real physics step. The fix snapshots both physics state buffers before the warmup run and restores them (data and references) in a finally block, so the user-staged writes are intact for the graph capture and subsequent replay.

  • Adds cls._model.state() snapshot allocation and assign copy/restore around the warmup simulate() call, guarded by try/finally with a stream sync to ensure GPU operations complete.
  • Introduces a changelog entry describing the fix for the deferred CUDA graph wrench preservation.

Confidence Score: 4/5

Safe to merge; the change is narrowly scoped to the deferred RTX warmup path, and the snapshot/restore logic correctly handles both single-state and double-buffered substep configurations.

The snapshot-and-restore approach is sound: state references are saved before warmup, GPU memory is snapshotted via assign, a try/finally guarantees the restore runs even on exception, and a stream sync at the end of the finally block ensures all GPU ops complete before graph capture begins. The only caveat is that if simulate() throws inside a bad CUDA context the subsequent assign calls in the finally block may also fail, but that is an inherent GPU error-handling constraint and not introduced by this PR.

No files require special attention; the change is confined to a single method in newton_manager.py.

Important Files Changed

Filename Overview
source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py Core fix: wraps the warmup simulate() in a try/finally that snapshots and restores _state_0/_state_1 data and references so first-step wrenches survive into graph capture and replay. Logic and stream synchronisation are correct for all double-buffer and single-state configurations.
source/isaaclab_newton/changelog.d/yizew-deferred-cuda-wrench.rst New changelog fragment describing the deferred CUDA graph wrench fix; content is accurate and follows project conventions.

Sequence Diagram

sequenceDiagram
    participant step as step()
    participant crg as _capture_relaxed_graph()
    participant sim as simulate()
    participant stream as CUDA stream

    step->>crg: first call (RTX active, _graph_capture_pending)
    Note over crg: Save state_0/state_1 refs
    crg->>stream: state_0_snapshot.assign(state_0)
    crg->>stream: state_1_snapshot.assign(state_1)
    Note over crg: [try]
    crg->>sim: simulate() — warmup (pre-allocs solver buffers, consumes wrenches)
    sim-->>crg: done
    crg->>stream: wp.synchronize_stream (drain warmup)
    Note over crg: [finally — restore]
    crg->>crg: "_state_0 = state_0 (restore ref)"
    crg->>crg: "_state_1 = state_1 (restore ref)"
    crg->>stream: _state_0.assign(state_0_snapshot) (restore data + wrenches)
    crg->>stream: _state_1.assign(state_1_snapshot) (restore data)
    crg->>stream: wp.synchronize_stream (drain restore)
    Note over crg: Create non-blocking stream, begin relaxed capture
    crg->>sim: simulate() — graph capture (sees restored wrenches)
    sim-->>crg: done
    crg->>crg: wp.capture_end → wp.Graph
    crg-->>step: graph
    step->>stream: wp.capture_launch(graph)
Loading

Reviews (1): Last reviewed commit: "Fix Newton deferred graph warmup" | Re-trigger Greptile

@AntoineRichard
AntoineRichard force-pushed the antoine/fix-newton-deferred-wrench branch from e53e8f5 to 3f47b17 Compare June 5, 2026 09:43
@AntoineRichard
AntoineRichard requested a review from pbarejko June 5, 2026 13:27
@YizeWang YizeWang mentioned this pull request Jun 5, 2026
5 of 7 tasks
Fixed
^^^^^

* Fixed deferred Newton CUDA graph capture with Kit/RTX so first-step external wrenches are preserved.

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.

What I really find ambiguous. The changes are related to newton manager, however the comment explains CUDA graph capture with Kit/RTX.

Also, I have been wondering what does this really fix? You create snapshots, you stash them, and after sim you recover them.

Why do we need to call wp.synchronize_stream twice?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yeah, we were seeing an issue with defered capture.

The warmup steps the simulation without calling lab internals so on the very first step we can get incorrect behaviors. So we snapshot the state before warm-up and restore them after the warmup that's it.

We may not need the wp.sync twice.

@AntoineRichard

Copy link
Copy Markdown
Collaborator Author

@YizeWang is this still needed?

Restore Newton states after relaxed CUDA graph warmup so first-step staged external wrenches are consumed by the captured physics step instead of the warmup step.
@AntoineRichard
AntoineRichard force-pushed the antoine/fix-newton-deferred-wrench branch from e632b39 to 5142b7f Compare July 9, 2026 08:13
@AntoineRichard
AntoineRichard requested a review from pbarejko July 9, 2026 08:14
@AntoineRichard

AntoineRichard commented Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Confirmed with @YizeWang that this is needed, @pbarejko @ooctipus for review.

@AntoineRichard
AntoineRichard requested a review from ooctipus July 9, 2026 08:15
Clone arrays from the live state instead of constructing snapshots from the model. This preserves warmup rollback when solver-owned state buffers have been lazily resized.
Refresh the rendering baselines with outputs from the official CI runner. The corrected deferred warmup rollback removes a hidden Newton step and intentionally shifts the cloth trajectory.
wp.synchronize_device("cuda:0")

joint_qd = NewtonManager._state_0.joint_qd.numpy()
assert np.isclose(joint_qd[2], 0.0, atol=1e-3, rtol=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.

You observe here effect of gravity, why not additionally observe initial conditions from joint_q? They should be all initial values?

@AntoineRichard
AntoineRichard requested a review from a team August 27, 2026 07:57
@kellyguo11

Copy link
Copy Markdown
Contributor

run-ci

@isaaclab-bot isaaclab-bot Bot added the ci:run-docker Trigger the on-demand Docker and GPU CI workflow label Sep 5, 2026
@isaaclab-bot isaaclab-bot Bot removed the ci:run-docker Trigger the on-demand Docker and GPU CI workflow label Sep 5, 2026
@kellyguo11

Copy link
Copy Markdown
Contributor

this probably needs a rebase, but I don't seem to have access to do that

@StafaH

StafaH commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

@AntoineRichard I merged the latest develop into this branch, but I can't push here because "Allow edits by maintainers" is off, so I opened AntoineRichard#20 against antoine/fix-newton-deferred-wrench. Could you merge that PR so we can get this one merged?

Besides resolving conflicts, the merge adapts the fix to develop:

  • develop moved state to NewtonManager.backend.state_0 / state_1, so the old _state_0 / _state_1 references no longer existed.
  • The snapshot is skipped for sensor-graph captures, which can run on a sensor-only backend without state_1.
  • The regression test now forces the relaxed capture path; on develop it had stopped exercising the fix. It fails without the restore and passes with it.
  • The isaaclab_tasks .skip fragment is removed: develop regenerated the Franka cloth goldens, and they pass with this fix.

I also benchmarked it against develop (Newton + RTX, and kitless Newton + Newton renderer) and found no regression. The full numbers are in AntoineRichard#20.

@StafaH

StafaH commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator

Closing as this is now fixed by #8058 using native warp graph capture in RELAXED mode. More elegant fix and we can remove all the custom code.

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.

[Bug Report] Kit Visualizer + Newton MJWarp Drops First-Step External Wrench

4 participants