Skip to content

[OvPhysX] Halve GPU state-read cost with captured ovphysx session reads - #9220

Open
hujc7 wants to merge 6 commits into
isaac-sim:mainfrom
hujc7:jichuanh/ovphysx-session-read
Open

hujc7 wants to merge 6 commits into
isaac-sim:mainfrom
hujc7:jichuanh/ovphysx-session-read

Conversation

@hujc7

@hujc7 hujc7 commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

On a CUDA simulation, OvPhysX state reads take 43-56% less time per call than main; Isaac-Ant-Direct at 4096 envs steps 3.5% faster.
OvPhysxView.read_into replays an ovphysx 0.8 session read captured into a CUDA graph instead of a blocking tensor-binding read; values match the binding.

Description

Area Now
OvPhysxView.read_into / get_attribute(out=...) of CUDA state (root, link and rigid-body poses, velocities, accelerations; joint state; Jacobians; mass matrices; deformable nodes) Replays a captured session read on the caller's current Warp stream, without a host wait.
Each destination buffer captures its own graph on its first read.
Values Same layout, row order and units as the binding.
Joint quantities may differ in the last bit (the session reports degrees); deformable points carry float32 rounding from the simulation-mesh frame.
Still read through the binding Properties, contacts, gravity compensation forces, every CPU-simulation read.
OvPhysxManager.invalidate_session_reads() New. Call it before a structural edit made through the native handle, which ovphysx does not report.
SceneDataProvider poses Filled on the stream of the call that refreshed them; a reader on another non-blocking stream waits for that stream first (ovphysx.rst).

No new dependency: ovphysx 0.8 is already pinned on main.

Validation (L40, branch fd3eef142cc vs main 158bfc02608)

Gate Result
Per-call read A/B, 3 interleaved reps, device-synced CUDA session reads (15): −43 to −56% vs main, e.g. root velocity 57.3 -> 25.2 us, Jacobian 49.5 -> 26.0 us
CUDA binding reads (13): +1 to +6%, per-rep ranges overlapping main's (−4 to +4% in the previous run); CPU reads (22): −2 to +3%
source/isaaclab_ov/test (before the test audit) Branch 463 passed (main 432); the same 3 failures and 1 collection error on both
source/isaaclab_ov/test at head db56f66037e, one process per file The PR's 5 test files: 179 passed, 26 skipped, 2 xfailed
Every other file passes except the 3 failures and 1 collection error main also has

Environment throughput (L40, 4096 envs, physics=ovphysx, main and PR runs interleaved)

Task Workload main steps/s PR steps/s Δ vs main Reps
Isaac-Cartpole-Direct env step 907,951 942,435 +3.8% 3
Isaac-Ant-Direct env step 736,849 762,849 +3.5% 3
Isaac-Humanoid-Direct env step 394,845 408,022 +3.3% 5
Isaac-Velocity-Flat-G1 env step 121,117 123,065 +1.6% 3
Isaac-Lift-Franka env step 126,666 128,549 +1.5% 3
Isaac-Velocity-Flat-AnymalD env step 184,548 184,270 −0.2% 3
Isaac-Reach-Franka env step 392,548 386,781 −1.5% 3
Isaac-Ant-Direct rsl_rl training, 100 iterations 360,134 371,137 +3.1% 3
Isaac-Velocity-Flat-AnymalD rsl_rl training, 100 iterations 151,728 154,067 +1.5% 3

Env step = isaaclab benchmark runtime, 1000 steps; training = isaaclab benchmark training, total fps. Means over the reps.
Isaac-Reach-Franka: one PR rep held a single 0.26 s iteration; the other two reps are within 0.6% of main.
Isaac-Humanoid-Direct ran alone on its GPU: run beside three other jobs it read −8.2%, and under a fixed load on the other GPUs both arms lost about the same (PR +1.3%).

Known limits (no Lab caller today):

  • A SceneDataProvider cache-hit reader on a different non-blocking stream must wait for the refreshing stream itself (documented above).
  • A deformable body replaced at the same prim path through native OVStage edits keeps the frame captured at load.

Type of change

  • New feature (non-breaking change which adds functionality)

Screenshots

Not applicable.

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with uv run isaaclab --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have validated the changed behavior with focused coverage and applied the test-audit criteria to any test changes
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package (do not edit CHANGELOG.rst or bump package versions — CI handles that)
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

On a CUDA simulation, OvPhysxView.read_into of simulation state (poses,
velocities, accelerations, joint state, Jacobians, mass matrices and
deformable nodes) replays an OvPhysX 0.8 session read captured into a CUDA
graph for each destination buffer, instead of a synchronous tensor-binding
read. Placement kernels write the binding's layout and units, so the values
match the binding. The replay runs on the caller's current Warp stream.

Add OvPhysxManager.invalidate_session_reads() for structural edits made
through the native handle, which OvPhysX does not report.
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Nov 25, 2026
The kinematic-refresh test builds its own scene: on the shared module scene
it passed with the refresh removed once other tests had run. The gravity force
test now changes gravity and compares the read with the binding, the
invalidation test disables a body through the native handle, and the
equivalence checks share one binding reference and one replay-only guard.
@hujc7

hujc7 commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

run-ci

@isaaclab-bot isaaclab-bot Bot added ci:run-docker Trigger the on-demand Docker and GPU CI workflow and removed ci:run-docker Trigger the on-demand Docker and GPU CI workflow labels Nov 25, 2026
@hujc7
hujc7 marked this pull request as ready for review November 25, 2026 22:18
@hujc7
hujc7 requested a review from a team November 25, 2026 22:18

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Isaac Lab Review Bot

Needs attention: Scope and over-engineering (3), Compatibility and deprecation (2), Implementation (5), Style consistency (8), Test quality (4). Other reviewed categories look good.

  • PR description: Historical L40 comparisons support speed claims; correct non-breaking, get_attribute, and first-read wording, and supply head-versus-baseline revisions, commands/workloads, hardware, backend, environment count, warmup, and metrics while preserving template sections.
  • Design and architecture: Architecture looks good.
  • Scope and over-engineering: Minimal implementation: Extend OvPhysxView dispatch and OvPhysxBackend/OvPhysxManager lifecycle; keep ovphysx_session_reads.py for graph, read, and query lifetimes, and fixtures/views/session_reads.py for shared replay enforcement. Remove duplicate eligibility checks, repeated output validation, and the custom zeroing kernel. Retain mapping, capture, replay, synchronization, and cleanup; trim duplicate test captures. Scope is cohesive; no split recommended.
  • API: API changes look good.
  • Compatibility and deprecation: Breaking changes: read_into and get_attribute(out=...) lose blocking completion and exact binding values without a deprecation bridge; retain binding behavior by default and expose captured reads through explicit opt-in.
  • Implementation: Session reads can return stale kinematics because direct view and raw-binding joint writes do not mark manager state dirty; preserve automatic kinematic refresh at the read boundary.
  • Style consistency: Read documentation conflates captured and binding paths and implies automatic cross-stream waiting; separate the contracts, qualify get_attribute(out=...), and explicitly assign synchronization responsibility to callers.
  • Test quality: The native-edit test passes with no-op invalidation, so it does not protect recapture; replace it with a case requiring recapture or remove it.

Needs rework. Posted 22 inline findings.

Automated review; human maintainers own approval decisions.

ValueError: If a prim is not on the loaded stage.
"""
# 1. Parse the stage ovphysx loaded, once per load.
if self._loaded_stage is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Critical · Implementation — Refresh frames after native replacement

invalidate_session_reads recaptures graphs but _loaded_stage still supplies the original frame. A same-path deformable replacement with a changed frame returns wrong world points; refresh the frame source.

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.

Known limit, listed in the PR description: the frames come from the stage ovphysx loaded, and no Lab caller replaces a deformable at the same path through native OVStage edits, so this stays out of scope.

plan = self._plans[key]
# 3. Replay it on the caller's stream, after the kinematic refresh it depends on.
stream = self.stream
if tensor_type in _KINEMATIC_READS and self.refresh_kinematics is not None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔴 Critical · Implementation — Refresh kinematics after direct writes

A joint write through set_attribute or a raw binding does not set manager.kinematics_dirty. Session Jacobian and mass-matrix reads can therefore return stale values; retain the binding read’s automatic refresh.

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.

Fixed in f4f6672: a DOF_POSITION or ROOT_POSE write through OvPhysxView.set_attribute marks the manager's kinematics dirty, so the next Jacobian or mass-matrix replay refreshes them; test_session_kinematic_reads_follow_joint_writes now covers that view write path. A raw binding write outside the view is not tracked.

# 2. Node i of body b lands on binding row b * nodes + i.
body_of = {prim: body for body, prim in enumerate(prims)}
bodies = np.repeat([body_of[prim] for prim in session_rows], counts)
dst_rows = bodies * nodes + np.concatenate([np.arange(count) for count in counts])

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.

🔴 Critical · Implementation — Clear padded deformable nodes

Node placement writes only reported nodes, but _node_sources never marks shorter bodies as padded. Replays retain old destination values in unused slots; mark and clear padded layouts on every replay.

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.

Fixed in f4f6672: _node_sources marks the plan padded when a body has fewer nodes than the binding row, so the graph zeroes the destination first; test_session_deformable_reads_pad_shorter_bodies reads a 5-node and a 4-node body through a generic view.

handles = [paths.intern_path(p) for p in roots]
with self._physx.read_sync(SimObjectType.ARTICULATION, list(names), prim_paths=handles) as result:
groups = _read_groups(result)
row_of = {path: row for row, path in enumerate(_row_paths(result, groups))}

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.

🔴 Critical · Implementation — Handle split articulation groups

The articulation table maps roots using only the first session group. A view spanning differently structured articulations can reject valid binding rows; combine the groups or fall back to the binding.

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.

Measured at 3349f3a with one view over a floating-base and a fixed-base articulation: the metadata columns come back as one group per attribute holding all 4 rows, and the root-pose, DOF-position and link-pose replays equal the binding exactly. Jacobian and mass-matrix bindings refuse a heterogeneous view at creation, so no session read is planned for them.

key = self._key_aliases.get(tt, tt)
if key in READS:
reads = OvPhysxSessionReads.for_physx(self._physx)
if reads is not None and reads.read_into(self, key, binding, view):

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.

🔴 Critical · Compatibility — Preserve blocking reads by default

Existing read_into and get_attribute(out=...) calls now return with CUDA writes pending; cross-stream callers can consume stale buffers. Keep the blocking contract and expose replay through an opt-in API.

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.

Intended: the replay runs asynchronously on the caller's current Warp stream, which is where the 43-56% per-call saving comes from. Every Lab caller consumes on that stream, and the contract for work on other non-blocking streams is documented in ovphysx.rst and the changelog, so no opt-in is added.

expected = {}
for name, articulation in scene.islands.items():
view = articulation.root_view
# The plan built above, right after the writes, serves the read.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Warning · Style Consistency — Correct capture timing

The comment says the plan was built after the writes, but it was captured before the steps and writes. Say this call replays the earlier capture.

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.

Fixed in f4f6672: the comment says this read replays the plan captured above.

from isaaclab_ov.test.fixtures.views.session_reads import binding_values, replays_only

spawn, tensor_types = _SESSION_DEFORMABLE_CASES[kind]
with _ovphysx_sim_context(device="cuda:0", gravity_enabled=True) as sim:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Warning · Test Quality — Honor selected CUDA devices

The new deformable cases force cuda:0 despite the runtime test-device mask. Parameterize them with test_devices(DeviceScope.CUDA).

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.

Every deformable test in this file runs through _ovphysx_sim_context(device="cuda:0"); the new cases follow that. Moving the file to test_devices(DeviceScope.CUDA) is a separate change.

try:
replayed = wp.zeros_like(binding_values(view, TT.RIGID_BODY_POSE))
view.read_into(TT.RIGID_BODY_POSE, replayed) # captures the plan
sim.backend_manager.invalidate_session_reads()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Warning · Test Quality — Invalidation case proves no need

The edit affects a body outside the view, and the test says the old capture still reads correctly. A no-op invalidation passes; use a case requiring recapture or remove it.

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.

Fixed in db56f66: the read after invalidate_session_reads must capture again (captures_again), so an invalidation that keeps the plans fails the test.

scene.sim.step()
# A collection reads LINK_* through its RIGID_BODY_* binding; the cuboid pairs read the rigid-body types.
served = {TT.LINK_POSE: TT.RIGID_BODY_POSE, TT.LINK_VELOCITY: TT.RIGID_BODY_VELOCITY}.get(tensor_type)
owners = (scene.fused, scene.stepped) if served else (scene.dynamic, scene.kinematic, scene.spinning)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Warning · Test Quality — Remove duplicate collection captures

Fused and Stepped have the same collection layout and alias path here. Capturing both adds no distinct read contract; retain one representative.

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.

Fixed in db56f66: the link-type cases read one collection.

stream = wp.get_device(device).null_stream if null_stream else wp.Stream(device)
with wp.ScopedStream(stream), patch.object(wp, "capture_launch", wraps=wp.capture_launch) as launch:
view.read_into(TT.RIGID_BODY_POSE, replayed)
assert launch.call_args.kwargs["stream"] is stream

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Warning · Test Quality — Test stream ordering through data

Inspecting capture_launch arguments tests call shape; device synchronization masks ordering faults. Queue a dependent read on the selected stream and verify its result after synchronizing that stream.

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.

Fixed in db56f66: the test queues a copy after the replay on the selected stream, synchronizes only that stream and compares the copy with the binding; the capture_launch patch is gone.

@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5 · The PR appears safe to merge, with a non-blocking padding issue for generic views over differently sized deformables.RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect state reads across CUDA simulations using the OvPhysX backend.

The PR appears safe to merge, with a non-blocking padding issue for generic views over differently sized deformables.

Findings

  1. P2 Padded nodes keep old values ▶

Summary

CUDA state reads through read_into now capture and replay OvPhysX session reads on the caller's Warp stream.

  • Reusable CUDA state reads replay captured OvPhysX session reads.
  • The physics manager coordinates captured reads with steps and native edits.

Acknowledged limits from hujc7: a cached SceneDataProvider reader on another non-blocking stream must wait for the refreshing stream; native replacement of a deformable at the same path keeps its load-time frame. Both were explicitly listed as known limits with no current Lab caller.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[View read_into] --> B{CUDA state read?}
    B -- No --> C[TensorBinding read]
    B -- Yes --> D{Destination plan exists?}
    D -- No --> E[Query rows and capture read graph]
    E --> F[Replay on caller stream]
    D -- Yes --> F
    F --> G[Record completion event]
    G --> H[Wait before step or release]
Loading

Reviews (1) · Last reviewed commit: "Merge remote-tracking branch 'upstream/m..." · Reviewed by Greptile

Comment on lines +438 to +441
# 2. Node i of body b lands on binding row b * nodes + i.
body_of = {prim: body for body, prim in enumerate(prims)}
bodies = np.repeat([body_of[prim] for prim in session_rows], counts)
dst_rows = bodies * nodes + np.concatenate([np.arange(count) for count in counts])

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.

P2 Padded nodes keep old values

For a generic OvPhysxView over deformables with different node counts, _node_sources writes only the real nodes but never sets plan.padded. The graph therefore skips _clear. With counts [5, 4] and a destination filled with -1, the second body's fifth node stays -1 instead of matching the binding's padded output.

Set plan.padded when any count is below nodes, and add a mixed-count test through the generic view. The asset subclass's uniform-count check does not protect this path.

Suggested change
# 2. Node i of body b lands on binding row b * nodes + i.
body_of = {prim: body for body, prim in enumerate(prims)}
bodies = np.repeat([body_of[prim] for prim in session_rows], counts)
dst_rows = bodies * nodes + np.concatenate([np.arange(count) for count in counts])
# 2. Node i of body b lands on binding row b * nodes + i.
plan.padded = plan.padded or any(count < nodes for count in counts)
body_of = {prim: body for body, prim in enumerate(prims)}
bodies = np.repeat([body_of[prim] for prim in session_rows], counts)
dst_rows = bodies * nodes + np.concatenate([np.arange(count) for count in counts])

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.

Fixed in f4f6672 with that line; test_session_deformable_reads_pad_shorter_bodies reads a 5-node and a 4-node body through a generic OvPhysxView, and fails with the line removed.

- Clear padded node rows when a view's deformables have different node counts.
- Mark the kinematics stale after a joint-position or root-pose write through a
  view, so Jacobian and mass-matrix replays refresh them as binding reads did.
- Release an empty source's query even when closing its warm read fails.
- Zero padded destinations with Warp's memset, route through one READS check,
  validate get_attribute(out=...) once, order members and annotations per the
  guide, and state the two read contracts and the caller's cross-stream wait.
- The native-edit test asserts the read after invalidation captures again.
- The stream test queues a copy after the replay and syncs only that stream.
- Read the collection link types through one collection; both share a layout.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant