Skip to content

Adds Newton + Isaac RTX Rendering Performance Optimizations - #5017

Merged
ncournia-nv merged 12 commits into
isaac-sim:developfrom
ncournia-nv:dev/ncournia/perf-test
Apr 1, 2026
Merged

ncournia-nv merged 12 commits into
isaac-sim:developfrom
ncournia-nv:dev/ncournia/perf-test

Conversation

@ncournia-nv

Copy link
Copy Markdown
Collaborator

Newton + Isaac RTX Rendering Performance Optimizations

This document describes four performance optimizations applied to the Newton physics simulator when used with the Isaac Sim RTX renderer inside Isaac Lab. Together they reduce per-frame time from ~323 ms to ~60 ms (a 5.4x speedup), making Newton's rendering path slightly faster than PhysX's equivalent (~65 ms).

All live primarily in two files:

  • source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py
  • source/isaaclab_newton/isaaclab_newton/physics/_cubric.py (new)

with small additions to PhysicsManager and SimulationContext in the core isaaclab package.


Baseline: ~323 ms per frame

The starting point is the unoptimized Newton + RTX rendering loop. A Nsight Systems trace reveals the structure:

  • Two physics steps execute per frame (typical for 2× physics substeps per render frame).
  • After each physics step, Newton writes updated body transforms to Fabric (Omniverse's GPU scene-graph cache) and then triggers a full CPU hierarchy update via update_world_xforms(). This hierarchy walk recomputes every world-space transform in the scene from parent-child relationships — even though Newton already computed the correct world transforms and wrote them directly.
  • The Kit renderer also runs its own, lighter, internal hierarchy update.

The per-step Fabric sync and hierarchy update dominates the frame. Because it runs after every physics step (not just before rendering), the cost is multiplied by the number of substeps.

newton-rtx-baseline

Optimization 1 — Dirty-Flag Deferred Sync: ~244 ms per frame

Problem

Every physics substep was calling sync_transforms_to_usd(), which writes Newton body poses to Fabric and then invokes update_world_xforms(). The hierarchy update is expensive and only needs to happen once before the renderer reads the scene — not after every substep.

Solution

A dirty-flag pattern decouples physics stepping from Fabric synchronization:

  1. _mark_transforms_dirty() — called at the end of each _simulate() call, sets _transforms_dirty = True. This is cheap (a boolean assignment).
  2. sync_transforms_to_usd() — now checks _transforms_dirty at the top and returns immediately if transforms haven't changed. When dirty, it writes transforms and calls the hierarchy update, then clears the flag.
  3. pre_render() — a new method added to PhysicsManager (base class) and overridden by NewtonManager. It calls sync_transforms_to_usd(). The SimulationContext.render() method calls physics_manager.pre_render() before updating visualizers and cameras, ensuring transforms are flushed exactly once per render frame.

The key insight is that the renderer only reads scene transforms during render(), not during step(). By deferring the Fabric write and hierarchy update to render time, we eliminate redundant work when multiple physics substeps run per render frame. For 2 substeps per frame, this cuts the hierarchy update count in half.

Key code paths

  • _simulate() → _mark_transforms_dirty() (just sets a flag)
  • SimulationContext.render() → PhysicsManager.pre_render() → NewtonManager.sync_transforms_to_usd() (runs once, clears the flag)
newton-rtx-dirty

Optimization 2 — CUDA Graph Capture (Relaxed Mode): ~144 ms per frame

Problem

Looking at the physics steps in the trace, the GPU is underutilized. Each Warp kernel launch (collision detection, constraint solve, integration, FK evaluation) incurs a round-trip to the CPU via Python — launch overhead, GIL acquisition, and driver calls. For a simulation with many small kernels per substep, this CPU-side overhead becomes the bottleneck while the GPU sits idle between dispatches.

Newton already supported CUDA graphs (pre-recording a sequence of kernel launches and replaying them with a single driver call), but CUDA graph capture was disabled when RTX rendering was active. The original code had:

use_cuda_graph = cfg.use_cuda_graph and (cls._usdrt_stage is None)

This was necessary because RTX's background threads use CUDA's legacy stream (stream 0) for async operations like cudaImportExternalMemory. Warp's standard ScopedCapture() uses cudaStreamCaptureModeThreadLocal on a blocking stream, which implicitly synchronizes with legacy stream 0. If RTX ops happen during capture, the CUDA runtime raises error 906 (cudaErrorStreamCaptureImplicit).

Solution

A deferred, relaxed-mode CUDA graph capture strategy that is compatible with RTX:

Deferral: Graph capture is postponed from initialize_solver() to the first step() call. By that time, RTX has finished its initialization (all cudaImportExternalMemory calls are done) and is idle between render frames, providing a clean capture window.

# In initialize_solver():
cls._graph = None
cls._graph_capture_pending = True

# In step():
if cls._graph_capture_pending:
    cls._graph = cls._capture_relaxed_graph(device)

Relaxed-mode capture (_capture_relaxed_graph): This method works around two conflicting requirements:

  1. RTX compatibility: RTX threads use legacy stream 0. A blocking stream (Warp's default) implicitly syncs with it, causing capture failures. Solution: create a non-blocking stream (cudaStreamNonBlocking = 0x01) that has no implicit synchronization with stream 0.

  2. Warp compatibility: mujoco_warp internally calls wp.capture_while, which checks Warp's device.captures registry to decide whether to insert a conditional graph node or synchronize eagerly. Without a registered capture, it calls wp.synchronize_stream on the capturing stream — which is illegal inside graph capture. Solution: call wp.capture_begin(external=True, stream=fresh_stream) to register the capture in Warp's tracking without calling cudaStreamBeginCapture again (already done externally).

The capture sequence:

  1. Warmup run — execute _simulate_physics_only() eagerly to pre-allocate all MuJoCo-Warp scratch buffers (allocations are forbidden inside graph capture).
  2. Create a non-blocking CUDA stream via cudaStreamCreateWithFlags(..., NonBlocking).
  3. Begin capture with cudaStreamBeginCapture(..., cudaStreamCaptureModeRelaxed) — relaxed mode allows other streams to operate freely during capture.
  4. Register with Warp via wp.capture_begin(external=True, stream=...).
  5. Record physics kernels — _simulate_physics_only() inside wp.ScopedStream(fresh_stream).
  6. Finalize — wp.capture_end() then cudaStreamEndCapture() to obtain the graph.

Physics-only capture: _simulate_physics_only() was factored out of _simulate() to exclude Fabric sync operations (wp.synchronize_device, wp.fabricarray) that are incompatible with graph capture. After graph replay, step() marks transforms dirty, and pre_render() handles the Fabric sync eagerly.

The ctypes binding to libcudart.so is used directly because Warp's ScopedCapture doesn't expose control over capture mode or stream type.

newton-rtx-cuda-graph

Optimization 3 — GPU Transform Hierarchy via cubric: ~60 ms per frame

Problem

Even with the dirty-flag pattern reducing hierarchy updates to once per render frame, the update_world_xforms() call is still a CPU-side tree walk over the entire Fabric scene graph. For scenes with thousands of prims (typical in multi-environment RL), this CPU hierarchy propagation is a significant bottleneck.

The PhysX backend avoids this problem by using cubric — a GPU-accelerated transform hierarchy library. cubric runs the parent-child transform propagation entirely on the GPU via IAdapter::compute(), which is dramatically faster than the CPU walk. However, cubric has no Python bindings.

Solution

Pure-Python ctypes bindings to cubric's Carbonite interface (_cubric.py), allowing Newton to use the same GPU hierarchy propagation that PhysX uses.

cubric is implemented as a Carbonite plugin and exposes its API through the omni::cubric::IAdapter interface. The bindings work by:

  1. Acquiring the Carbonite Framework — libcarb.so's acquireFramework() returns the singleton Framework*.
  2. Acquiring the IAdapter interface — calling tryAcquireInterfaceWithClient() with the interface descriptor omni::cubric::IAdapter version 0.1.
  3. Wrapping function pointers — the IAdapter struct is a C++ vtable-like struct with function pointers at known offsets.

Each function pointer is read from the struct at its byte offset and wrapped with ctypes.CFUNCTYPE to make it callable from Python.

Integration in sync_transforms_to_usd():

The sync method now mirrors PhysX's ScopedUSDRT pattern:

  1. Pause Fabric change tracking — track_world_xform_changes(False) and track_local_xform_changes(False). This is critical: SelectPrims with ReadWrite access internally calls getAttributeArrayGpu, which marks Fabric buffers dirty. If tracking is still active, the hierarchy records the change and Kit's updateWorldXforms will do an expensive connectivity rebuild every frame.
  2. Write transforms — the existing Warp kernel writes Newton body poses to Fabric's omni:fabric:worldMatrix.
  3. Resume tracking — re-enable change tracking (in a finally block for safety).
  4. Run cubric compute — IAdapter::compute() with eRigidBody | eForceUpdate options and eAll dirty mode. The eRigidBody flag tells cubric to use inverse propagation on prims tagged with PhysicsRigidBodyAPI (preserve the world matrix that Newton wrote, derive the local transform) and forward propagation on everything else (propagate parent transforms to children). eForceUpdate bypasses cubric's change-listener dirty check since we know transforms have changed.

The adapter is lazily created on the first sync_transforms_to_usd() call rather than during initialize_solver(), to avoid startup-ordering issues with the cubric plugin.

When cubric is unavailable (e.g., plugin not loaded, CPU-only), the code falls back gracefully to the CPU update_world_xforms() path.

sync_transforms_to_usd():
    ┌─────────────────────────────────┐
    │  Pause Fabric change tracking   │
    ├─────────────────────────────────┤
    │  SelectPrims (ReadWrite)        │
    │  wp.launch(_set_fabric_transforms) │  ← GPU: write Newton poses to Fabric
    │  wp.synchronize_device()        │
    ├─────────────────────────────────┤
    │  cubric IAdapter::compute()     │  ← GPU: propagate hierarchy
    ├─────────────────────────────────┤
    │  Resume Fabric change tracking  │
    └─────────────────────────────────┘

A future Kit release is expected to ship official Python bindings for cubric, at which point the ctypes approach can be replaced.

The result is a frame time of ~60 ms — slightly faster than PhysX's ~65 ms on the same scene.

newton-rtx-cubric

Summary

Optimization Frame Time Speedup vs. Baseline Key Technique
Baseline ~323 ms — Sync + hierarchy after every substep
Dirty-flag deferred sync ~244 ms 1.3× Sync once per render frame, not per substep
CUDA graph (relaxed mode) ~144 ms 2.2× Eliminate per-kernel CPU launch overhead
cubric GPU hierarchy ~60 ms 5.4× GPU hierarchy propagation via ctypes bindings

All four optimizations are complementary and stack on top of each other. The final result matches or slightly beats the PhysX rendering path (~65 ms) while using Newton as the physics backend.

Co-developed with Toby Jones (NVIDIA).

@github-actions github-actions Bot added the isaac-lab Related to Isaac Lab team label Mar 14, 2026
@greptile-apps

greptile-apps Bot commented Mar 14, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR implements four complementary performance optimizations for Newton + Isaac RTX rendering, reducing per-frame time from ~323 ms to ~60 ms (5.4×). The changes are well-reasoned and the engineering is sophisticated, but several fragile patterns warrant attention before merging.

What changed:

  • Dirty-flag deferred sync (_mark_transforms_dirty / pre_render): decouples physics stepping from Fabric writes so the expensive hierarchy update runs once per render frame instead of after every substep. Clean, safe change.
  • Deferred relaxed CUDA graph capture (_capture_relaxed_graph): works around RTX's incompatibility with standard ScopedCapture by using a non-blocking stream and cudaStreamCaptureModeRelaxed. The implementation is careful and well-documented.
  • GPU transform hierarchy via cubric ctypes bindings (_cubric.py): mirrors PhysX's internal GPU hierarchy path. Pure-Python ctypes bindings over undocumented C++ struct layouts; acknowledged as a stopgap until official Python bindings ship.
  • _simulate_physics_only factoring: cleanly separates GPU-capturable physics work from Fabric-sync operations.

Key concerns:

  • In sync_transforms_to_usd(), the early return when SelectPrims finds zero prims does not clear _transforms_dirty, causing repeated execution of the full setup code on every render frame in that edge case.
  • _capture_relaxed_graph mutates private attributes of a wp.Graph object (graph.graph and graph.graph_exec) that are undocumented Warp internals; a Warp version bump could silently break graph replay.
  • IAdapter::bindToStage is called on every render frame. If this call is not cheap or idempotent, it may reduce the expected speedup from the cubric optimization.
  • The byte offsets in _cubric.py (_FW_OFF_TRY_ACQUIRE, _IA_OFF_*) are hardcoded from a specific Carbonite SDK build; there is no version guard to detect when the struct layout has changed, which would produce silent incorrect behavior or crashes.

Confidence Score: 3/5

  • Merging is risky without addressing the fragile Warp internal API mutation and the missing dirty-flag clear on empty selection; the cubric byte-offset bindings could silently break on a Kit/Isaac Sim version bump.
  • The performance optimizations are well-designed and complementary. The core logic (dirty flag, deferred capture, cubric integration) is sound and the fallback paths are properly handled. However, three fragile patterns reduce confidence: (1) the graph.graph = raw_graph mutation of Warp private internals with no version guard, (2) the missing _transforms_dirty clear on empty-selection early return which could cause per-frame overhead in edge cases, and (3) the hardcoded Carbonite struct byte offsets in _cubric.py with no defensive version check. None of these are runtime crashes under the tested configuration, but they create maintenance landmines for future Warp or Kit version updates.
  • source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py (dirty-flag clear, Warp graph internals, bind_to_stage frequency) and source/isaaclab_newton/isaaclab_newton/physics/_cubric.py (hardcoded struct offsets).

Important Files Changed

Filename Overview
source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py Core file with all four optimizations: dirty-flag deferred sync, deferred relaxed CUDA graph capture, cubric GPU hierarchy integration, and _simulate_physics_only factoring. Contains fragile Warp internals mutation (graph.graph = raw_graph), a _transforms_dirty flag that isn't cleared on empty-selection early return, and bind_to_stage called every render frame.
source/isaaclab_newton/isaaclab_newton/physics/_cubric.py New file providing pure-Python ctypes bindings for the cubric IAdapter GPU transform hierarchy. Relies on hardcoded byte offsets into Carbonite Framework and IAdapter struct layouts that are undocumented and version-sensitive. Fallback to CPU update_world_xforms() is well-handled.
source/isaaclab/isaaclab/sim/simulation_context.py One-line addition of physics_manager.pre_render() at the start of render(). Safe change: all non-Newton backends inherit a no-op implementation from PhysicsManager.
source/isaaclab/isaaclab/physics/physics_manager.py Adds a no-op pre_render() classmethod to the PhysicsManager ABC. Clean, backward-compatible addition that all existing subclasses (PhysxManager) inherit safely without change.

Sequence Diagram

sequenceDiagram
    participant SC as SimulationContext
    participant PM as NewtonManager
    participant GPU as GPU (CUDA)
    participant FB as Fabric (USD)
    participant CB as cubric IAdapter
    participant RTX as RTX Renderer

    Note over SC,RTX: Per-frame loop
    SC->>PM: step()
    activate PM
    alt CUDA graph captured
        PM->>GPU: capture_launch(_graph)
        GPU-->>PM: (physics kernels replay)
        PM->>PM: _mark_transforms_dirty()
    else eager execution
        PM->>GPU: _simulate_physics_only()
        GPU-->>PM: (physics step complete)
        PM->>PM: _mark_transforms_dirty()
    end
    deactivate PM

    SC->>SC: render()
    SC->>PM: pre_render()
    activate PM
    PM->>PM: sync_transforms_to_usd()
    alt _transforms_dirty == True
        PM->>FB: track_world_xform_changes(False)
        PM->>FB: track_local_xform_changes(False)
        PM->>GPU: wp.launch(_set_fabric_transforms)
        GPU-->>FB: write body poses to worldMatrix
        PM->>GPU: wp.synchronize_device()
        PM->>PM: _transforms_dirty = False
        alt cubric available
            PM->>CB: bind_to_stage(adapter_id, fabric_id)
            PM->>CB: compute(adapter_id, eRigidBody|eForceUpdate, eAll)
            CB->>GPU: GPU hierarchy propagation
        else fallback
            PM->>FB: update_world_xforms() (CPU)
        end
        PM->>FB: track_world_xform_changes(True)
        PM->>FB: track_local_xform_changes(True)
    end
    deactivate PM
    SC->>RTX: update_visualizers() / Kit render
    RTX->>FB: read worldMatrix (already updated)
Loading

Last reviewed commit: a0248bc

Comment on lines +70 to +94
_OPT_DEFAULT = _OPT_RIGID_BODY | _OPT_FORCE_UPDATE

# AdapterDirtyMode
_DIRTY_ALL = 0 # eAll — dirty all prims in the stage
_DIRTY_COARSE = 1 # eCoarse — dirty all prims in visited buckets


# ---------------------------------------------------------------------------
# ctypes struct mirrors
# ---------------------------------------------------------------------------
class _Version(ctypes.Structure):
_fields_ = [("major", ctypes.c_uint32), ("minor", ctypes.c_uint32)]


class _InterfaceDesc(ctypes.Structure):
"""``carb::InterfaceDesc`` — {const char* name, Version version}."""
_fields_ = [
("name", ctypes.c_char_p),
("version", _Version),
]


def _read_u64(addr: int) -> int:
return ctypes.c_uint64.from_address(addr).value

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.

Hardcoded byte offsets into native C++ struct layouts

The constants _FW_OFF_TRY_ACQUIRE = 24, _IA_OFF_CREATE = 8, _IA_OFF_RELEASE = 32, _IA_OFF_BIND = 40, and _IA_OFF_COMPUTE = 56 are hardcoded byte offsets into Carbonite's Framework vtable and IAdapter's function-pointer table, derived from a specific build of the Carbonite SDK.

If NVIDIA inserts or reorders fields in either struct in a future Kit/Isaac Sim release, every call through these pointers will silently dispatch to the wrong function. Because the pointer reads via _read_u64 bypass all type safety, the failure mode is either silent mis-computation or an immediate segfault — both hard to diagnose.

A few mitigations worth considering:

  • Add a version assertion on the carb framework (acquireFramework returns a version) to bail out early when the framework version changes.
  • Add a smoke-test after acquiring the pointers: e.g., call IAdapter::getAttribute (offset 0) and verify the returned version matches the expected IAdapter 0.1 version before using the other slots.
  • Document the exact Kit/Isaac Sim version these offsets were verified against in a comment next to each constant.

@fatimaanes
fatimaanes self-requested a review March 15, 2026 15:56
@kellyguo11

Copy link
Copy Markdown
Contributor

@ncournia-nv could you run the formatter ./isaaclab.sh -f?

also seeing some failures in test_rendering_correctness.py - https://github.com/isaac-sim/IsaacLab/actions/runs/23513986493/job/68449749241?pr=5017

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

Detailed Code Review — Newton + RTX Rendering Performance Optimizations

Excellent PR. The 5.4× speedup from three stacked optimizations (dirty-flag deferred sync, relaxed-mode CUDA graph capture, cubric GPU hierarchy) is well-motivated by Nsight traces and the implementation shows deep understanding of the CUDA capture + RTX interaction constraints. The PR description is production-quality documentation.

NOTE: This review's inline comments were posted against the wrong commit due to a tooling error. Please see the subsequent review for the actual inline code comments.

CI Status: pre-commit fails (ruff try-except-pass lint). Other failures (isaaclab core, newton, physx) appear to be pre-existing flaky tests unrelated to this PR.

Overall verdict: Approve with minor fixes. The architecture is sound.

Comment thread scripts/benchmarks/benchmark_startup.py Outdated
# Override config with CLI args
env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs
env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device
env_cfg.seed = args_cli.seed

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.

Bug: unconditional seed override clobbers config default.

env_cfg.seed = args_cli.seed

When --seed is not passed, args_cli.seed is None. This unconditionally overwrites whatever env_cfg.seed was — either the task config's default or the conditional assignment at module-level line 166.

Line 166 already does the right thing:

env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed

This line should match that pattern, or just be removed since the module-level assignment already ran:

# Either:
env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed
# Or just delete this line — line 166 already handled it.

Comment thread scripts/benchmarks/benchmark_startup.py Outdated

# -- Create the benchmark instance ------------------------------------------

env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed

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.

Nit: module-level seed assignment is redundant with main(). This line correctly does the conditional assignment, but then main() line 206 unconditionally overwrites it (see other comment). If you fix line 206 to be conditional too, consider removing one of the two assignments to avoid confusion about which one "wins".

Since env_cfg is passed into main() and main() also sets num_envs and device there, it'd be cleaner to do all config overrides in one place — inside main() — and remove this line.

Comment thread scripts/benchmarks/benchmark_startup.py Outdated

# Finalize benchmark output
benchmark.update_manual_recorders()
benchmark._finalize_impl()

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.

Minor: calling private _finalize_impl() directly.

I know other benchmark scripts (benchmark_non_rl.py) do this too, so this is a pre-existing pattern rather than a problem you introduced. Still worth noting: if BaseIsaacLabBenchmark ever gains a public finalize() wrapper (which it should), this should switch to it.

Comment thread scripts/benchmarks/benchmark_startup.py Outdated

imports_profile.disable()

if torch.cuda.is_available() and torch.cuda.is_initialized():

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.

Design note: cuda.is_initialized() check may miss lazy CUDA init.

At this point in the script, CUDA may not yet be initialized (torch was just imported but no tensor ops have run). If CUDA isn't initialized, is_initialized() returns False and the synchronize is skipped — which is correct, since there's nothing to sync. But it means the wall-clock imports_time_end doesn't account for any deferred GPU init that gets triggered later.

This is fine for a profiling script (you're measuring import time, not GPU init time), but worth a comment explaining the intent — especially since the same pattern at lines 225 and 245 does catch active GPU work.

Comment thread scripts/benchmarks/utils.py Outdated
for func_key, (_, _, tottime, cumtime, callers) in stats.stats.items():
filename, _, funcname = func_key
if _is_isaaclab(filename):
label = _make_label(filename, funcname)

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.

Observation (not a bug): external functions can appear with abbreviated labels. When an external function (e.g., torch.nn.modules.linear:forward) is directly called by an IsaacLab function, _make_label truncates the path to site-packages-relative or last-3-components. This is fine for readability but means the label isn't a valid Python import path — it's a display-only string. Worth a brief docstring note on _make_label that labels are for display, not programmatic use.

Comment thread scripts/benchmarks/benchmark_startup.py Outdated

# Sample random actions
actions = (
torch.rand(env.unwrapped.num_envs, env.unwrapped.single_action_space.shape[0], device=env.unwrapped.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.

Nit: single_action_space may not exist for all env types.

For DirectMARLEnv, the action space structure is different — single_action_space exists but might be a Dict space, not a Box, so .shape[0] would fail. The type signature of main() accepts DirectMARLEnvCfg, but this line assumes a flat action space.

Since this is a benchmarking script (not a general-purpose tool), this is acceptable if the docs/help text clarify it's for single-agent RL envs. But if MARL envs are intended to be supported, this needs a check.

if isinstance(measurement, StatisticalMeasurement):
unit_str = f" {measurement.unit.strip()}" if (measurement.unit and measurement.unit.strip()) else ""
value = f"{self._format_scalar(measurement.mean)}{unit_str}"
elif isinstance(measurement, SingleMeasurement):

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.

Good addition. The catch-all rendering for unknown phases is clean and doesn't break existing behavior. One minor style nit: the unit_str construction is duplicated between the frametime_phase block above and this new block. Could extract a helper like _format_measurement_value(measurement) to DRY it up, but that's cosmetic.

@kellyguo11

Copy link
Copy Markdown
Contributor

Detailed Code Review — Newton + RTX Rendering Performance Optimizations

Excellent PR. The 5.4× speedup from three stacked optimizations (dirty-flag deferred sync, relaxed-mode CUDA graph capture, cubric GPU hierarchy) is well-motivated by Nsight traces and the implementation shows deep understanding of the CUDA capture + RTX interaction constraints. The PR description is production-quality documentation.

Below are the issues I found, ordered roughly by severity. Inline comments are posted as review comments on the relevant lines.

CI Status: pre-commit fails (ruff try-except-pass lint on line 718-720 of newton_manager.py). Other failures (isaaclab core, newton, physx) appear to be pre-existing flaky tests unrelated to this PR.

Overall verdict: Approve with minor fixes. The architecture is sound; the issues are correctness edge cases and cleanup items, not design flaws.


1. CUDA Graph Handle Management (_capture_relaxed_graph, line ~737)

After wp.capture_end() returns a wp.Graph, you overwrite its .graph member with a ctypes.c_void_p and set .graph_exec = None. Potential issues:

  • Type mismatch: raw_graph is a ctypes.c_void_p struct, not its integer .value. When wp.capture_launch passes this to cudaGraphInstantiate, the wrong type may cause issues. Use raw_graph.value if you need the integer handle.
  • Double capture end: If wp.capture_end() in external mode still calls cudaStreamEndCapture internally, your subsequent manual cudaStreamEndCapture may return NULL or double-free the graph.
  • graph_exec = None: Forces wp.capture_launch to re-instantiate on every launch, which may add overhead. Consider instantiating once.

Suggestion: Verify exactly what wp.capture_end(stream=fresh_stream) returns in external mode. If it already contains the correct graph, the manual cudaStreamEndCapture may be redundant.

2. bind_to_stage Called Every Frame (line 249)

The Fabric stage ID doesn't change between frames. Calling bindToStage every sync is at minimum unnecessary overhead and potentially triggers internal state reconstruction in cubric. PhysX's DirectGpuHelper binds once.

Consider caching:

if cls._cubric_bound_fabric_id != fabric_id:
    cls._cubric.bind_to_stage(cls._cubric_adapter, fabric_id)
    cls._cubric_bound_fabric_id = fabric_id

3. Warmup Run During First step() Advances Physics State (line ~673)

The warmup call in _capture_relaxed_graph() runs _simulate_physics_only() eagerly, advancing _state_0/_state_1 at the first step() call after reset. This means the first frame has an extra physics advancement compared to the non-RTX path (where warmup happens during initialize_solver()).

Suggestion: Save and restore state around the warmup, or document the first-frame side effect.

4. _transforms_dirty Not Cleared on Empty Selection (line 233)

When GetCount() == 0, the method returns without clearing _transforms_dirty. Every subsequent frame will re-enter the full sync path (pause/resume tracking, SelectPrims) for nothing. Add cls._transforms_dirty = False before the early return.

5. Hard-Coded Struct Offsets in _cubric.py (lines 37-56)

The vtable offsets are derived from specific Kit/cubric header versions. If a future Kit version reorders fields, these will silently read wrong function pointers, causing segfaults (not Python exceptions). Consider:

  • Document the exact Kit/cubric version these offsets were verified against
  • Add a smoke-test (create + release) during initialize() to validate function pointers
  • Track the migration plan to official Python bindings

6. tryAcquireInterfaceWithClient ABI (_cubric.py line ~159)

The ctypes signature passes _InterfaceDesc by value. This is correct for the Carbonite C ABI on x86_64 (struct ≤16 bytes → registers), but verify the C++ side doesn't expect const InterfaceDesc& (by-reference), which would be an ABI mismatch.

7. Pre-commit Lint Fix Needed (line ~718)

try-except-pass → use contextlib.suppress(Exception) or add # noqa: SIM105.

8. release_adapter Shutdown Safety (line 340)

If cubric plugin is already torn down during Kit shutdown, the function pointer call in release_adapter could segfault. Wrap in try/except.

9. Double sync_transforms_to_usd() Call Path

pre_render() → sync_transforms_to_usd() runs first, then update_visualizers() → NewtonSceneDataProvider.update() → sync_transforms_to_usd() runs second. The dirty flag makes the second call a cheap no-op, but consider removing the scene data provider call since pre_render() now handles it.

This reverts commit 46830e6a6e3150da5f0fb378528ab78253e0dea0.
- Apply ruff formatting to _cubric.py (comment alignment, trailing commas)
- Replace bare try/except/pass with contextlib.suppress(Exception) in
  _capture_relaxed_graph (SIM105)
- Clear _transforms_dirty on empty SelectPrims result to avoid
  redundant setup overhead on subsequent render frames (greptile)
- Cache cubric fabric_id to avoid calling bind_to_stage every frame;
  only rebind when the Fabric stage ID actually changes (greptile)
- Add explanatory comment for Warp Graph internal patching (greptile)
@kellyguo11 kellyguo11 changed the title Newton + Isaac RTX Rendering Performance Optimizations Adds Newton + Isaac RTX Rendering Performance Optimizations Mar 29, 2026
@ncournia-nv
ncournia-nv force-pushed the dev/ncournia/perf-test branch from 1f256db to 808c90c Compare March 30, 2026 17:16
Regenerate the shadow_hand newton-isaacsim_rtx_renderer-rgba golden
image to match the deferred sync rendering output. The previous
golden image differed by 5.15% (just over the 5% threshold) due to
minor rendering differences from the dirty-flag deferred sync
optimization.
@ncournia-nv

Copy link
Copy Markdown
Collaborator Author

CI Failure Analysis

All 6 failing jobs in the latest CI run are pre-existing failures unrelated to this PR. The same tests fail across unrelated branches with identical errors.

Failure Breakdown

Job Failing Test(s) Pre-existing? Evidence
isaaclab (core) [1/3] test_first_frame_textured_rendering (delta 18.7 > 15.0 threshold), test_tiled_camera semantic segmentation (negative mean assertion) ✅ Yes Fails on test_ci_issues, my-ci-fix-3, reb/multitask_demo_migrate
isaaclab (core) [2/3] test_ideal_pd_actuator (test report missing — timeout/crash) ✅ Yes Fails on my-ci-fix-3, reb/multitask_demo_migrate
isaaclab (core) [3/3] test_manager_based_rl_env_obs_spaces (clip_constraint), test_device_constructors, test_spawn_from_files, test_utils_transforms (all timeout/crash — -1/0 results) ✅ Yes Fails on test_ci_issues, my-ci-fix-3, reb/multitask_demo_migrate
isaaclab_tasks [3/3] test_rendering_correctness (42 golden image mismatches at 5-32% diff — CI GPU vs golden image GPU mismatch) ✅ Yes Fails on all checked branches
isaaclab_contrib test_thruster, test_multirotor (timeout — no test report generated) ✅ Yes test_multirotor crashes on my-ci-fix-3, fails on reb/multitask_demo_migrate. Flaky — passed on our previous run
environments_training test_train_environments[skrl-task_spec19] (1 of 568 tests) ✅ Yes Fails on all checked branches

Cross-Branch Verification

Checked recent CI runs on unrelated branches to confirm these are not introduced by our changes:

  • test_ci_issues (Mar 31) — same core [1/3], core [3/3], tasks [3/3], environments_training failures
  • my-ci-fix-3 (Mar 31) — same core [1/3], [2/3], [3/3], tasks [3/3], contrib, environments_training failures
  • reb/multitask_demo_migrate (Mar 31) — even more failures (10 jobs failing)

What Passes

All jobs directly related to our changes pass cleanly: pre-commit, isaaclab_newton, isaaclab_rl, isaaclab_physx, docs build, license-check.

@ncournia-nv
ncournia-nv merged commit e7f34eb into isaac-sim:develop Apr 1, 2026
23 of 29 checks passed
es-rl pushed a commit to es-rl/IsaacLab-Newton that referenced this pull request Apr 4, 2026
…m#5017)

# Newton + Isaac RTX Rendering Performance Optimizations

This document describes four performance optimizations applied to the
Newton physics simulator when used with the Isaac Sim RTX renderer
inside Isaac Lab. Together they reduce per-frame time from **~323 ms to
~60 ms** (a **5.4x speedup**), making Newton's rendering path slightly
faster than PhysX's equivalent (~65 ms).

All live primarily in two files:

- `source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py`
- `source/isaaclab_newton/isaaclab_newton/physics/_cubric.py` (new)

with small additions to `PhysicsManager` and `SimulationContext` in the
core `isaaclab` package.

---

## Baseline: ~323 ms per frame

The starting point is the unoptimized Newton + RTX rendering loop. A
Nsight Systems trace reveals the structure:

- **Two physics steps** execute per frame (typical for 2× physics
substeps per render frame).
- **After each physics step**, Newton writes updated body transforms to
Fabric (Omniverse's GPU scene-graph cache) and then triggers a full CPU
hierarchy update via `update_world_xforms()`. This hierarchy walk
recomputes every world-space transform in the scene from parent-child
relationships — even though Newton already computed the correct world
transforms and wrote them directly.
- The Kit renderer also runs its own, lighter, internal hierarchy
update.

The per-step Fabric sync and hierarchy update dominates the frame.
Because it runs after *every* physics step (not just before rendering),
the cost is multiplied by the number of substeps.

<img width="2169" height="750" alt="newton-rtx-baseline"
src="https://github.com/user-attachments/assets/f7fc0079-9cca-43d2-9ade-9069e29718d4"
/>

---

## Optimization 1 — Dirty-Flag Deferred Sync: ~244 ms per frame

### Problem

Every physics substep was calling `sync_transforms_to_usd()`, which
writes Newton body poses to Fabric and then invokes
`update_world_xforms()`. The hierarchy update is expensive and only
needs to happen once before the renderer reads the scene — not after
every substep.

### Solution

A **dirty-flag pattern** decouples physics stepping from Fabric
synchronization:

1. **`_mark_transforms_dirty()`** — called at the end of each
`_simulate()` call, sets `_transforms_dirty = True`. This is cheap (a
boolean assignment).
2. **`sync_transforms_to_usd()`** — now checks `_transforms_dirty` at
the top and returns immediately if transforms haven't changed. When
dirty, it writes transforms and calls the hierarchy update, then clears
the flag.
3. **`pre_render()`** — a new method added to `PhysicsManager` (base
class) and overridden by `NewtonManager`. It calls
`sync_transforms_to_usd()`. The `SimulationContext.render()` method
calls `physics_manager.pre_render()` before updating visualizers and
cameras, ensuring transforms are flushed exactly once per render frame.

The key insight is that the renderer only reads scene transforms during
`render()`, not during `step()`. By deferring the Fabric write and
hierarchy update to render time, we eliminate redundant work when
multiple physics substeps run per render frame. For 2 substeps per
frame, this cuts the hierarchy update count in half.

### Key code paths

- `_simulate()` → `_mark_transforms_dirty()` (just sets a flag)
- `SimulationContext.render()` → `PhysicsManager.pre_render()` →
`NewtonManager.sync_transforms_to_usd()` (runs once, clears the flag)

<img width="2174" height="765" alt="newton-rtx-dirty"
src="https://github.com/user-attachments/assets/eae6dbd9-7936-492e-a922-4fff5c0d7861"
/>

---

## Optimization 2 — CUDA Graph Capture (Relaxed Mode): ~144 ms per frame

### Problem

Looking at the physics steps in the trace, the GPU is underutilized.
Each Warp kernel launch (collision detection, constraint solve,
integration, FK evaluation) incurs a round-trip to the CPU via Python —
launch overhead, GIL acquisition, and driver calls. For a simulation
with many small kernels per substep, this CPU-side overhead becomes the
bottleneck while the GPU sits idle between dispatches.

Newton already supported CUDA graphs (pre-recording a sequence of kernel
launches and replaying them with a single driver call), but CUDA graph
capture was **disabled when RTX rendering was active**. The original
code had:

```python
use_cuda_graph = cfg.use_cuda_graph and (cls._usdrt_stage is None)
```

This was necessary because RTX's background threads use CUDA's legacy
stream (stream 0) for async operations like `cudaImportExternalMemory`.
Warp's standard `ScopedCapture()` uses
`cudaStreamCaptureModeThreadLocal` on a blocking stream, which
implicitly synchronizes with legacy stream 0. If RTX ops happen during
capture, the CUDA runtime raises error 906
(`cudaErrorStreamCaptureImplicit`).

### Solution

A **deferred, relaxed-mode CUDA graph capture** strategy that is
compatible with RTX:

**Deferral:** Graph capture is postponed from `initialize_solver()` to
the first `step()` call. By that time, RTX has finished its
initialization (all `cudaImportExternalMemory` calls are done) and is
idle between render frames, providing a clean capture window.

```python
# In initialize_solver():
cls._graph = None
cls._graph_capture_pending = True

# In step():
if cls._graph_capture_pending:
    cls._graph = cls._capture_relaxed_graph(device)
```

**Relaxed-mode capture** (`_capture_relaxed_graph`): This method works
around two conflicting requirements:

1. **RTX compatibility**: RTX threads use legacy stream 0. A blocking
stream (Warp's default) implicitly syncs with it, causing capture
failures. Solution: create a **non-blocking stream**
(`cudaStreamNonBlocking = 0x01`) that has no implicit synchronization
with stream 0.

2. **Warp compatibility**: `mujoco_warp` internally calls
`wp.capture_while`, which checks Warp's `device.captures` registry to
decide whether to insert a conditional graph node or synchronize
eagerly. Without a registered capture, it calls `wp.synchronize_stream`
on the capturing stream — which is illegal inside graph capture.
Solution: call `wp.capture_begin(external=True, stream=fresh_stream)` to
register the capture in Warp's tracking without calling
`cudaStreamBeginCapture` again (already done externally).

The capture sequence:

1. **Warmup run** — execute `_simulate_physics_only()` eagerly to
pre-allocate all MuJoCo-Warp scratch buffers (allocations are forbidden
inside graph capture).
2. **Create a non-blocking CUDA stream** via
`cudaStreamCreateWithFlags(..., NonBlocking)`.
3. **Begin capture** with `cudaStreamBeginCapture(...,
cudaStreamCaptureModeRelaxed)` — relaxed mode allows other streams to
operate freely during capture.
4. **Register with Warp** via `wp.capture_begin(external=True,
stream=...)`.
5. **Record physics kernels** — `_simulate_physics_only()` inside
`wp.ScopedStream(fresh_stream)`.
6. **Finalize** — `wp.capture_end()` then `cudaStreamEndCapture()` to
obtain the graph.

**Physics-only capture:** `_simulate_physics_only()` was factored out of
`_simulate()` to exclude Fabric sync operations
(`wp.synchronize_device`, `wp.fabricarray`) that are incompatible with
graph capture. After graph replay, `step()` marks transforms dirty, and
`pre_render()` handles the Fabric sync eagerly.

The ctypes binding to `libcudart.so` is used directly because Warp's
`ScopedCapture` doesn't expose control over capture mode or stream type.

<img width="2168" height="745" alt="newton-rtx-cuda-graph"
src="https://github.com/user-attachments/assets/eecfde04-41f4-488e-97e4-4d87cf617830"
/>

---

## Optimization 3 — GPU Transform Hierarchy via cubric: ~60 ms per frame

### Problem

Even with the dirty-flag pattern reducing hierarchy updates to once per
render frame, the `update_world_xforms()` call is still a **CPU-side
tree walk** over the entire Fabric scene graph. For scenes with
thousands of prims (typical in multi-environment RL), this CPU hierarchy
propagation is a significant bottleneck.

The PhysX backend avoids this problem by using **cubric** — a
GPU-accelerated transform hierarchy library. cubric runs the
parent-child transform propagation entirely on the GPU via
`IAdapter::compute()`, which is dramatically faster than the CPU walk.
However, cubric has no Python bindings.

### Solution

**Pure-Python ctypes bindings to cubric's Carbonite interface**
(`_cubric.py`), allowing Newton to use the same GPU hierarchy
propagation that PhysX uses.

cubric is implemented as a Carbonite plugin and exposes its API through
the `omni::cubric::IAdapter` interface. The bindings work by:

1. **Acquiring the Carbonite Framework** — `libcarb.so`'s
`acquireFramework()` returns the singleton `Framework*`.
2. **Acquiring the IAdapter interface** — calling
`tryAcquireInterfaceWithClient()` with the interface descriptor
`omni::cubric::IAdapter` version `0.1`.
3. **Wrapping function pointers** — the `IAdapter` struct is a C++
vtable-like struct with function pointers at known offsets.

Each function pointer is read from the struct at its byte offset and
wrapped with `ctypes.CFUNCTYPE` to make it callable from Python.

**Integration in `sync_transforms_to_usd()`:**

The sync method now mirrors PhysX's `ScopedUSDRT` pattern:

1. **Pause Fabric change tracking** — `track_world_xform_changes(False)`
and `track_local_xform_changes(False)`. This is critical: `SelectPrims`
with `ReadWrite` access internally calls `getAttributeArrayGpu`, which
marks Fabric buffers dirty. If tracking is still active, the hierarchy
records the change and Kit's `updateWorldXforms` will do an expensive
connectivity rebuild every frame.
2. **Write transforms** — the existing Warp kernel writes Newton body
poses to Fabric's `omni:fabric:worldMatrix`.
3. **Resume tracking** — re-enable change tracking (in a `finally` block
for safety).
4. **Run cubric compute** — `IAdapter::compute()` with `eRigidBody |
eForceUpdate` options and `eAll` dirty mode. The `eRigidBody` flag tells
cubric to use **inverse propagation** on prims tagged with
`PhysicsRigidBodyAPI` (preserve the world matrix that Newton wrote,
derive the local transform) and **forward propagation** on everything
else (propagate parent transforms to children). `eForceUpdate` bypasses
cubric's change-listener dirty check since we know transforms have
changed.

The adapter is lazily created on the first `sync_transforms_to_usd()`
call rather than during `initialize_solver()`, to avoid startup-ordering
issues with the cubric plugin.

When cubric is unavailable (e.g., plugin not loaded, CPU-only), the code
falls back gracefully to the CPU `update_world_xforms()` path.

```
sync_transforms_to_usd():
    ┌─────────────────────────────────┐
    │  Pause Fabric change tracking   │
    ├─────────────────────────────────┤
    │  SelectPrims (ReadWrite)        │
    │  wp.launch(_set_fabric_transforms) │  ← GPU: write Newton poses to Fabric
    │  wp.synchronize_device()        │
    ├─────────────────────────────────┤
    │  cubric IAdapter::compute()     │  ← GPU: propagate hierarchy
    ├─────────────────────────────────┤
    │  Resume Fabric change tracking  │
    └─────────────────────────────────┘
```

A future Kit release is expected to ship official Python bindings for
cubric, at which point the ctypes approach can be replaced.

The result is a frame time of **~60 ms** — slightly faster than PhysX's
**~65 ms** on the same scene.

<img width="2169" height="896" alt="newton-rtx-cubric"
src="https://github.com/user-attachments/assets/1474b806-fe82-44be-add3-324971ec37a0"
/>

---

## Summary

| Optimization | Frame Time | Speedup vs. Baseline | Key Technique |
|---|---|---|---|
| Baseline | ~323 ms | — | Sync + hierarchy after every substep |
| Dirty-flag deferred sync | ~244 ms | 1.3× | Sync once per render
frame, not per substep |
| CUDA graph (relaxed mode) | ~144 ms | 2.2× | Eliminate per-kernel CPU
launch overhead |
| cubric GPU hierarchy | ~60 ms | 5.4× | GPU hierarchy propagation via
ctypes bindings |

All four optimizations are complementary and stack on top of each other.
The final result matches or slightly beats the PhysX rendering path (~65
ms) while using Newton as the physics backend.

*Co-developed with Toby Jones (NVIDIA).*
ooctipus added a commit that referenced this pull request Sep 19, 2026
Newton's relaxed graph capture could silently fall back to eager
execution with CUDA 13 PyTorch wheels: its loader searched only for
`libcudart.so.12` and the unversioned `libcudart.so`, although PyTorch
had already loaded `libcudart.so.13`. This changed the simulation path
used by the Newton AnymalD tiled OpenGL golden test. Loading the runtime
major reported by `torch.version.cuda` restores relaxed physics and
sensor graph capture and prevents accidentally choosing an available
CUDA 12 runtime in a mixed-runtime process.

The hardcoded CUDA 12 loader originated in
[#5017](#5017), commit
[e7f34eb](e7f34eb).
Our CUDA 13 wheel switch in
[#7674](#7674), commit
[2e6b425](2e6b425),
exposed the assumption on x86; develop's ARM configuration already
selects CUDA 13 wheels. A controlled comparison reproduced the exact CI
drift (1.42% pixel difference, SSIM 0.9804) on all three attempts by
setting only the manager's runtime handle to `None`; the same test
passed when the runtime was available.

The loader remains inline and uses the existing PyTorch dependency.
Missing runtimes and CPU-only PyTorch retain an unavailable runtime
handle. No dependency, graph algorithm, golden image, or comparison
threshold changes are included.

Validation:

- Regression red/green: CUDA 13 selection, unavailable matching runtime,
and CPU-only cases failed with the old loader. All six focused
runtime/capture tests passed with the fix, including an actual
`cudaRuntimeGetVersion` check on CUDA 12.8.
- An isolated import with both the shared CUDA 12 runtime and system
CUDA 13.1 present selected `libcudart.so.13` and reported runtime
version 13010.
- The existing `test_visualizer_golden[newton-anymal_d-newton-tiled]`
passed on its first actual run with the exact PyTorch 2.12.0+cu130
stack: 1 passed, 11 deselected in 86.60 seconds. The log confirms
`libcudart.so.13`, runtime version 13000, and successful relaxed graph
capture. All 22 CUDA/PyTorch/Triton package versions matched #7674's
lock.
- GPU validation used an isolated environment on an RTX 5090, reusing
Newton 1.6rc1, Warp 1.17.0, and Isaac Sim 6.0.1 from the existing local
environment; it does not replace full CI validation with the remaining
locked dependencies.
- `uv run isaaclab -f` passed.
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

None yet

Development

Successfully merging this pull request may close these issues.

2 participants