Skip to content

[OvPhysX] Halve GPU state read and write cost with captured ovphysx sessions - #9220

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

hujc7 wants to merge 68 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, OvPhysxView state reads and most writes replay ovphysx 0.8 session reads and writes captured into CUDA graphs instead of blocking tensor-binding calls; values match the binding.
Per call, reads take 43-56% less time than main and writes 59-74% less; Isaac-Ant-Direct at 4096 envs steps 3.5% faster.

Description

Path (CUDA) Now
State reads: poses, velocities, accelerations, joint state, Jacobians, mass matrices, deformable nodes Captured session read, no host wait
Writes from a Warp array, whole or by mask: joint targets, actuation forces, rigid-body poses and velocities, wrenches (whole only) Captured session write; the next step waits for it
Articulation root and joint state, masked wrenches, writes by indices or from host data, properties, CPU simulation Unchanged: TensorBinding
OvPhysxManager.update_kinematics One held query instead of a new query and a wait per call
RigidObjectCollection masked writers One masked write without host mask-to-ids; fixes collections of seven bodies

Breaking for direct OvPhysxView and RigidObjectCollection callers (no Lab caller affected): masks must be Warp bool arrays on the simulation device, session calls stay on one stream, a view's prims stay in one physics scene, and collection masks must cover every environment and body.

Validation (L40)

Gate Result
Per-call A/B vs main Session reads −43 to −56% (fd3eef142cc); session writes −59 to −74% (bbaa2b4f473); calls left on the binding −8 to +6%
Env step, 4096 envs, session reads only (fd3eef142cc) Cartpole +3.8%, Ant +3.5%, Humanoid +3.3%, G1 +1.6%, Lift +1.5%, AnymalD −0.2%, Reach −1.5%
OvPhysX tests of the 7 touched files at 8ce4d1dd065 253 passed, 2 xfailed

Type of change

  • New feature (non-breaking change which adds functionality)
  • Breaking change (existing functionality will not work without user modification)

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: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge; no new blocking issue was established.

Summary

The PR moves CUDA state reads and selected writes to captured OvPhysX sessions.

  • CUDA state reads and writes replay captured OvPhysX sessions.
  • Collection mask writes update selected bodies without host mask conversion.
  • OvPhysX stage export passes USD stages directly to its callers.

No new actionable issues were established. Runtime tests were not run during this review.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[OvPhysxView call] --> B{Eligible CUDA state call?}
  B -->|No| C[TensorBinding]
  B -->|Yes| D{Buffer already captured?}
  D -->|No| E[Hold query and capture graph]
  D -->|Yes| F[Replay on caller stream]
  E --> F
  F --> G[Manager waits before next step]
Loading

Reviews (2) · 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.
Group the session-read members with inline comments and keep the
capture stream as its wp.Stream only; say what the placement scales
are for and why each replay records an event. In the joint mapping,
keep one table of slot and scale per joint axis, name the DOF count
dofs, and fail directly when the session reads none of the joints.
The padding test compared zero joint positions only: its initial
joint positions are never written. Write a distinct position to every
DOF through the view, and add a robot with a two-axis ball joint and
a prismatic joint, so a swapped axis or a scaled linear axis fails.
ArticulationData refreshes the articulation kinematics before reading a Jacobian or mass matrix, as it does for link
poses, instead of the session reads calling back into the manager. Session reads take the loaded stage text and parse
the deformable sim-mesh frames themselves, so the manager wires no hooks into them and view writes no longer report to
them.
The session reads' own stream becomes _capture_stream and the caller's current stream caller_stream. READS states
that Lab keeps the table and where ovphysx documents its attributes, and the warm read cites ovphysx's public device
guide instead of an internal ADR.
Inside the caller's capture, a read made once before records its graph into the caller's graph as a child node, so a
frontend can capture a whole step around warmed-up reads. A capture cannot launch a graph, and ovphysx lets one query
hold a single captured read, so the plan's own graph is inserted rather than read again. The event after it is an
external event node, which every replay of the caller's graph records, and wait() keeps it until invalidate(), so the
next step still waits for those replays.
@hujc7
hujc7 marked this pull request as draft November 30, 2026 16:34
hujc7 added 26 commits December 2, 2026 11:06
…one stream

A DirectGPU session commit of articulation root or joint state writes every articulation of the scene back, so the next kinematic refresh zeroes their link accelerations and incoming joint forces; these writes keep the TensorBinding. Session replays run on one stream and raise on another. The backend parses the loaded stage once for the sessions and the tendon lookup.
Both backends' collection link-pose mask writes launch isaaclab.utils.warp.memory.make_masked_copy instead of an equal per-backend kernel; the OvPhysX collection's view write helpers are named for the view write they make.
A native fused binding has one row per (body, environment), so its second dimension, the lane count, equals the body count of a seven-body pose or six-body velocity collection: the mock check misread those as the mock layout.
…k lengths

The fused pose binding is (N * B, 7) and the test mock's (N, B, 7), so the rank tells them apart for any body count; the collection and its data share is_fused_layout at all five layout sites, where a seven-body collection read as the mock sized its data for 14 environments. The collection's mask resolvers refuse a mask that is not one entry per environment or body, which left stale view-mask rows.
The stage serializer returns the stage it opened, which the backend populates from and keeps as usd_stage for the tendon names and deformable mesh frames, instead of keeping the USDA text and parsing it again. The captured sessions' replay and capture helpers are ordered as they are called.
Isaac Lab never runs on Warp's null stream, so the test guarded no Lab path; the one-line stream conversion stays.
Both reads guard one contract, the asset's kinematic refresh before a session read; one scene checks each after its own joint write.
The fused-binding layout check it guards is device-independent Python; the CUDA run also covers the session write.
test_session_writes_match_bindings already compares pose and velocity session writes with the binding's row by row; the wrench, which cannot be read back, needs the steps.
Neither the tensor type nor the articulation or body changes them: the articulation test ran them 48 times and the rigid test 8 times, each order check behind a busy kernel.
The session-read equivalence assertions already fail when ovphysx changes the unit of angular joint quantities or the frame of deformable points; their messages now name the likely cause. The canaries only added a message, through six private symbols.
No Isaac Lab code makes a structural edit through the native PhysX handle, and every asset writes a centre of mass through set_attribute, which already releases the captured wrench writes; the backend's close still releases every capture. The guide now says to make such edits on the USD stage before reset.
…ked write

The collection creates its pose and velocity bindings at initialization and raises when it cannot, so the guard never ran; had it run, it would have dropped the write without an error.
…ssion-read

# Conflicts:
#	source/isaaclab_ov/test/assets/test_deformable_object.py
@hujc7 hujc7 changed the title [OvPhysX] Halve GPU state-read cost with captured ovphysx session reads [OvPhysX] Halve GPU state read and write cost with captured ovphysx sessions Dec 2, 2026
@hujc7
hujc7 marked this pull request as ready for review December 2, 2026 23:35
@hujc7

hujc7 commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

@greptileai review

@hujc7

hujc7 commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

@isaaclab-review-bot review

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