Repository navigation
Adds Newton + Isaac RTX Rendering Performance Optimizations - #5017
Conversation
Greptile SummaryThis 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:
Key concerns:
Confidence Score: 3/5
Important Files Changed
Sequence DiagramsequenceDiagram
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)
Last reviewed commit: a0248bc |
| _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 | ||
|
|
There was a problem hiding this comment.
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 (
acquireFrameworkreturns 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 expectedIAdapter0.1version before using the other slots. - Document the exact Kit/Isaac Sim version these offsets were verified against in a comment next to each constant.
|
@ncournia-nv could you run the formatter also seeing some failures in test_rendering_correctness.py - https://github.com/isaac-sim/IsaacLab/actions/runs/23513986493/job/68449749241?pr=5017 |
There was a problem hiding this comment.
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.
| # 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 |
There was a problem hiding this comment.
Bug: unconditional seed override clobbers config default.
env_cfg.seed = args_cli.seedWhen --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.seedThis 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.|
|
||
| # -- Create the benchmark instance ------------------------------------------ | ||
|
|
||
| env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed |
There was a problem hiding this comment.
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.
|
|
||
| # Finalize benchmark output | ||
| benchmark.update_manual_recorders() | ||
| benchmark._finalize_impl() |
There was a problem hiding this comment.
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.
|
|
||
| imports_profile.disable() | ||
|
|
||
| if torch.cuda.is_available() and torch.cuda.is_initialized(): |
There was a problem hiding this comment.
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.
| for func_key, (_, _, tottime, cumtime, callers) in stats.stats.items(): | ||
| filename, _, funcname = func_key | ||
| if _is_isaaclab(filename): | ||
| label = _make_label(filename, funcname) |
There was a problem hiding this comment.
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.
|
|
||
| # Sample random actions | ||
| actions = ( | ||
| torch.rand(env.unwrapped.num_envs, env.unwrapped.single_action_space.shape[0], device=env.unwrapped.device) |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
Detailed Code Review — Newton + RTX Rendering Performance OptimizationsExcellent 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 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 (
|
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)
1f256db to
808c90c
Compare
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.
This reverts commit 9f9e5ba.
CI Failure AnalysisAll 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
Cross-Branch VerificationChecked recent CI runs on unrelated branches to confirm these are not introduced by our changes:
What PassesAll jobs directly related to our changes pass cleanly: pre-commit, isaaclab_newton, isaaclab_rl, isaaclab_physx, docs build, license-check. |
…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).*
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.
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.pysource/isaaclab_newton/isaaclab_newton/physics/_cubric.py(new)with small additions to
PhysicsManagerandSimulationContextin the coreisaaclabpackage.Baseline: ~323 ms per frame
The starting point is the unoptimized Newton + RTX rendering loop. A Nsight Systems trace reveals the structure:
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 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.
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 invokesupdate_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:
_mark_transforms_dirty()— called at the end of each_simulate()call, sets_transforms_dirty = True. This is cheap (a boolean assignment).sync_transforms_to_usd()— now checks_transforms_dirtyat the top and returns immediately if transforms haven't changed. When dirty, it writes transforms and calls the hierarchy update, then clears the flag.pre_render()— a new method added toPhysicsManager(base class) and overridden byNewtonManager. It callssync_transforms_to_usd(). TheSimulationContext.render()method callsphysics_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 duringstep(). 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)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:
This was necessary because RTX's background threads use CUDA's legacy stream (stream 0) for async operations like
cudaImportExternalMemory. Warp's standardScopedCapture()usescudaStreamCaptureModeThreadLocalon 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 firststep()call. By that time, RTX has finished its initialization (allcudaImportExternalMemorycalls are done) and is idle between render frames, providing a clean capture window.Relaxed-mode capture (
_capture_relaxed_graph): This method works around two conflicting requirements: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.Warp compatibility:
mujoco_warpinternally callswp.capture_while, which checks Warp'sdevice.capturesregistry to decide whether to insert a conditional graph node or synchronize eagerly. Without a registered capture, it callswp.synchronize_streamon the capturing stream — which is illegal inside graph capture. Solution: callwp.capture_begin(external=True, stream=fresh_stream)to register the capture in Warp's tracking without callingcudaStreamBeginCaptureagain (already done externally).The capture sequence:
_simulate_physics_only()eagerly to pre-allocate all MuJoCo-Warp scratch buffers (allocations are forbidden inside graph capture).cudaStreamCreateWithFlags(..., NonBlocking).cudaStreamBeginCapture(..., cudaStreamCaptureModeRelaxed)— relaxed mode allows other streams to operate freely during capture.wp.capture_begin(external=True, stream=...)._simulate_physics_only()insidewp.ScopedStream(fresh_stream).wp.capture_end()thencudaStreamEndCapture()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, andpre_render()handles the Fabric sync eagerly.The ctypes binding to
libcudart.sois used directly because Warp'sScopedCapturedoesn't expose control over capture mode or stream type.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::IAdapterinterface. The bindings work by:libcarb.so'sacquireFramework()returns the singletonFramework*.tryAcquireInterfaceWithClient()with the interface descriptoromni::cubric::IAdapterversion0.1.IAdapterstruct 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.CFUNCTYPEto make it callable from Python.Integration in
sync_transforms_to_usd():The sync method now mirrors PhysX's
ScopedUSDRTpattern:track_world_xform_changes(False)andtrack_local_xform_changes(False). This is critical:SelectPrimswithReadWriteaccess internally callsgetAttributeArrayGpu, which marks Fabric buffers dirty. If tracking is still active, the hierarchy records the change and Kit'supdateWorldXformswill do an expensive connectivity rebuild every frame.omni:fabric:worldMatrix.finallyblock for safety).IAdapter::compute()witheRigidBody | eForceUpdateoptions andeAlldirty mode. TheeRigidBodyflag tells cubric to use inverse propagation on prims tagged withPhysicsRigidBodyAPI(preserve the world matrix that Newton wrote, derive the local transform) and forward propagation on everything else (propagate parent transforms to children).eForceUpdatebypasses 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 duringinitialize_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.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.
Summary
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).