Skip to content

Optimize PhysX global external wrench submission - #7431

Closed
NeoZng wants to merge 1 commit into
isaac-sim:developfrom
NeoZng:fix/physx-wrench-global-at-com
Closed

NeoZng wants to merge 1 commit into
isaac-sim:developfrom
NeoZng:fix/physx-wrench-global-at-com

Conversation

@NeoZng

@NeoZng NeoZng commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR avoids unnecessary body-transform reads when PhysX can submit an external wrench directly in the global frame at the body's center of mass.

WrenchComposer.all_wrenches_global_at_com tracks a conservative aggregate invariant across all add_*, set_*, and add_raw_buffers_from inputs. The three PhysX writers use the raw global-at-CoM force and global torque buffers only while that invariant holds. Any local-frame or explicitly positioned force contribution, including one from another instantaneous or permanent composer, retains the existing body-frame composition path. Partial resets also retain the conservative fallback state.

This keeps the optimization independent of individual MDP terms and covers multiple external-wrench contributors without changing their existing add/set semantics. It is scoped to PhysX Articulation, RigidObject, and RigidObjectCollection; other backends and assist-force MDP code are unchanged. No new dependencies are required.

Related context: #7398 addressed cached COM-property access. This PR does not reopen that issue; it optimizes the remaining body-pose composition path for eligible external wrenches.

Validation

  • uv run isaaclab -f and ./isaaclab.sh --format: all pre-commit hooks passed.
  • WrenchComposer CPU/CUDA suite: 374 passed.
  • PhysX writer regression using the existing kitless runtime fixtures: 18 passed on CPU/CUDA. It covers direct global-at-CoM submission and the local-frame/positioned-force fallbacks for all three affected asset types.
  • Focused cross-backend interface/body-ordering suite: 6 passed, 18 skipped because the corresponding optional backends were unavailable, and 2293 deselected.
  • The direct-submission regression fails on the unpatched develop writer and passes with this change because the baseline reads body poses before submission.

PhysX performance profile

The workload was a custom articulated-robot recovery setup. A reset event installed a persistent world-frame upward assist force at a body CoM, and an interval event refreshed it every control step through:

asset.permanent_wrench_composer.set_forces_and_torques_index(
    forces=forces,
    body_ids=[body_id],
    env_ids=env_ids,
    is_global=True,
)

The composer submitted the buffered force on every physics step. The same assist-force event code was used for the develop baseline and the patch.

A same-process A/B used 4096 environments, a 27-body articulation, 100 warmup steps, and 2000 alternating paired samples per path:

Scope Develop Patch Change
External-wrench writer mean 0.313958 ms 0.188137 ms -0.125821 ms (-40.08%)
Full physics-cycle mean 10.971542 ms 10.856342 ms -0.115200 ms (-1.05%)

The reported 20-iteration PhysX training profiles used the same seed and configuration. The task had no Eval or policy export. RSL-RL measures collect_time around the rollout and logs both collection and learning time before saving a checkpoint, so checkpoint writing, startup, shutdown, and process wall time are excluded. The means below discard iterations 0-4 and use the remaining 15 samples per run. Positive improvements indicate that the patch was faster.

Collection time:

Environments Develop Patch Improvement Paired saving (95% interval)
4096 1.752667 s 1.728533 s +1.38% 24.13 ms [13.85, 34.42]
16384 3.170067 s 3.131667 s +1.21% 38.40 ms [24.85, 51.95]

Iteration time:

Environments Develop Patch Improvement
4096 1.770000 s 1.745333 s +1.39%
16384 3.198667 s 3.160667 s +1.19%

All reported runs completed 20/20 iterations and show a small collection-time benefit. The targeted 2000-pair writer A/B remains the direct evidence for the optimized path, rather than a claim of a universal training speedup.

Type of change

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

Release backport

  • Backport this pull request to the active release branch after it merges into develop

Screenshots

Not applicable; this change has no visual output.

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with ./isaaclab.sh --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my feature works
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package (do not edit CHANGELOG.rst or bump extension.toml — CI handles that)
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

Track whether every buffered external-wrench contribution can be submitted in the global frame at the body CoM, and let the PhysX writers use that representation directly.

Conservatively retain the existing composition path for local-frame or positioned forces, including mixed instantaneous and permanent sources.

Validated with a persistent world-frame assist force written through permanent_wrench_composer.set_forces_and_torques_index(..., is_global=True).

Signed-off-by: NeoZng <[email protected]>
@NeoZng
NeoZng requested a review from a team August 29, 2026 11:21
@github-actions github-actions Bot added bug Something isn't working isaac-lab Related to Isaac Lab team labels Aug 29, 2026
@greptile-apps

greptile-apps Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR tracks whether composed external wrenches can be submitted directly to PhysX in the global frame at each body’s center of mass, avoiding unnecessary transform reads.

  • Adds a conservative aggregate eligibility invariant to WrenchComposer.
  • Uses direct global submission for eligible articulation, rigid-object, and rigid-object-collection wrenches.
  • Retains body-frame composition for local-frame and explicitly positioned forces.
  • Adds CPU/CUDA, backend-interface, ordering, and PhysX regression coverage.

Confidence Score: 5/5

The PR appears safe to merge; no actionable correctness, security, or contract failures were identified.

The eligibility state is conservative across mutation and reset paths, while direct PhysX submission preserves frame semantics, center-of-mass application, body ordering, and collection layout with focused regression coverage.

Important Files Changed

Filename Overview
source/isaaclab/isaaclab/utils/wrench_composer.py Adds a conservative global-at-CoM invariant across all public contribution, merge, and reset paths.
source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation.py Selects direct global submission when eligible while preserving backend body reordering and the composed fallback.
source/isaaclab_physx/isaaclab_physx/assets/rigid_object/rigid_object.py Bypasses body-frame composition for eligible global-at-CoM rigid-object wrenches.
source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection.py Adds direct global submission while preserving the collection view’s body-major reshape and index mapping.
source/isaaclab/test/utils/test_wrench_composer.py Covers invariant transitions, contributor merging, positioned and local forces, and conservative partial resets.
source/isaaclab/test/assets/test_articulation_iface.py Verifies eligible articulation wrenches avoid pose reads and reach PhysX in the global frame.
source/isaaclab/test/assets/test_rigid_object_iface.py Verifies direct global rigid-object submission and buffer contents.
source/isaaclab/test/assets/test_rigid_object_collection_iface.py Verifies direct global collection submission and body-major output ordering.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Buffered external wrenches] --> B{All global and at CoM?}
    B -->|Yes| C[Use raw global force and torque buffers]
    B -->|No| D[Compose wrench into body frame]
    C --> E[Apply with is_global true]
    D --> F[Apply with is_global false]
    E --> G[PhysX body views]
    F --> G
Loading

Reviews (1): Last reviewed commit: "Optimize PhysX global external wrench su..." | Re-trigger Greptile

@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

Reviewed the new conservative global-at-CoM eligibility invariant and its use by all three PhysX external-wrench writers. The direct-submission path preserves the existing fallback for local-frame or positioned contributions while avoiding body-transform reads for eligible wrenches.

  • Design and architecture: The eligibility decision is appropriately centralized in WrenchComposer and propagated across add, set, merge, and reset operations. Partial resets intentionally retain a conservative false state, which can forgo the optimization but does not change wrench behavior.
  • API: The added all_wrenches_global_at_com property is additive, read-only, and documents its conservative reset semantics. Existing wrench buffer shapes and PhysX submission contracts remain unchanged, and both affected packages include changelog fragments.
  • Implementation: The producer and consumer paths support direct submission: a true invariant excludes local and positioned-force contributions, while articulation body reordering and rigid-object-collection reshaping continue to operate on identically shaped buffers. The inline flattened Warp views in the rigid-object fast path are not shown to create a material cost or correctness issue warranting a pre-merge change. The fast path leaves lazy body-frame outputs dirty, preserving later composition behavior.

No blocking issues. No inline issue met the actionable-evidence threshold; the assessment above records the review feedback.

Automated review; human maintainers own approval decisions.

@AntoineRichard

Copy link
Copy Markdown
Collaborator

@NeoZng Thanks for the PR, I don't think this is the right form. I had pushed something addressing the other side of the problem here: #7362, but I think I can do both at the same time while keeping everything in the composer. The assets should not do weird things with the composer outputs, the composer should infer the most efficient path on its own, it has everything it needs.

@NeoZng

NeoZng commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor Author

ur right. maintaining a state machine inside wrenchcomposer is much better than having the asset side do it separately and repeatedly (also, creating unnecessary cross-layer coupling). maybe we need an "aggregate mode" enum to tackle different fast paths. looking forward to your patch.
pr closed.

@NeoZng NeoZng closed this Sep 2, 2026
@github-project-automation github-project-automation Bot moved this from In review to Done in Isaac Lab Sep 2, 2026
ooctipus added a commit that referenced this pull request Sep 24, 2026
# Description

`WrenchComposer.compose_to_body_frame()` was called unconditionally by
every backend writer on every physics step. It reads `body_com_pos_w`
and `body_link_quat_w`, which on PhysX chains to `_ensure_fk_fresh()` →
`update_articulations_kinematic()` (a scene-global articulation FK pass)
plus `root_view.get_link_transforms()`, then launches the composition
kernel.

That work is unnecessary whenever the buffered wrench is already in a
frame the consumer accepts. This PR moves the frame decision into the
composer, which hands each writer the cheapest valid representation:

- **all-local content** → the local buffers, untouched. An all-local
wrench composes to exactly itself, because the pose data is multiplied
by zero.
- **all-global-at-CoM content** → the global buffers, untouched,
submitted in the world frame by backends that accept one.
- **anything else** → composed as before.

Writers declare what they can consume once at construction
(`supports_world_at_com`) and call `get_forces_and_torques()` per step.
All frame logic stays inside the composer; no writer touches a raw
buffer or knows a frame rule.

## New public API

```python
class WrenchComposer:
    def __init__(self, asset, *, supports_world_at_com: bool = False) -> None: ...
    def get_forces_and_torques(self) -> tuple[wp.array, wp.array, bool]: ...

forces, torques, is_global = composer.get_forces_and_torques()
```

Additive only. `compose_to_body_frame()`, `out_force_b`, and
`out_torque_b` remain public and behaviorally unchanged, so no
deprecation cycle is needed. `supports_world_at_com` defaults to
`False`, which is exactly the previous behavior.

The composer tracks local contributions, global contributions, and
positioned global forces with plain booleans. These flags stay
conservative across partial resets and clear on a full `reset()`;
checking whether a partial reset removed every contribution would
require scanning the buffers. The returned `is_global` boolean follows
the existing asset API and is passed directly to the backend. No frame
enum, content bitmask, or classification helper is needed.

## Equivalence

All three branches are exact, from `compose_wrench_to_body_frame`:

- **local only**: the three global buffers are zero, so both
`quat_rotate_inv` terms vanish and the output is identically
`(local_force_b, local_torque_b)`. Note a *positioned* local force also
qualifies — the kernel folds `cross(P_b, F_b)` straight into
`local_torque_b`.
- **global-at-CoM only**: `global_force_w` and the local buffers are
zero, so `corrected_torque_w == global_torque_w`. Submitting the world
buffers is the same wrench, provided the consumer applies force at the
CoM — verified against the vendored `omni.physics.tensors` API, where
`position_data=None` means "at the link transform" for **both**
`is_global` values, so the flag only reinterprets the vectors' frame and
never moves the application point.
- **anything else**: unchanged.

## Backend coverage

| backend | `supports_world_at_com` | change |
|---|---|---|
| PhysX | `True` | writer passes the returned `is_global` directly |
| OvPhysX | `True` | writer passes `is_global` to the packing kernel to
skip the inline rotate |
| Newton | `False` (default) | writer swaps to
`get_forces_and_torques()`; no constructor change |

OvPhysX is the largest win. Its wrench binding wants a world-frame
wrench, so a global wrench previously round-tripped: the composer
rotated world→body, then the packing kernel rotated body→world. Measured
on this branch with a body rotated 90° about +z, a local force `(1,0,0)`
emits `(0,1,0)` while a global force `(1,0,0)` emits `(1,0,0)` — an
exact round trip, so skipping both rotations is output-preserving. The
packed `[6:9]` link position is still written unconditionally on both
paths.

Newton keeps the body frame because it binds a body-frame array to the
solver. Worth noting for a follow-up: its writer kernel already performs
the same body→world rotation OvPhysX's does, so Newton could plausibly
take the same flag and win the global-at-CoM path too. That is
deliberately out of scope here.

## Validation

The existing composer rotation, positioned-force, merge, reset, and
overwrite tests now exercise `get_forces_and_torques()` directly.
Existing frame/position cases cover the four add/set index/mask APIs.
The existing articulation body-ordering test checks local/world
forwarding, composition avoidance, and packed link positions. One shared
rigid-object writer check replaces the separate backend/equivalence
suites and their duplicate rotation kernel.

Local results:

- `test_wrench_composer.py`: **375 passed** on CPU/CUDA.
- Articulation ordering and rigid-object wrench writer checks: **24
passed** across PhysX, Newton, and OvPhysX.
- `uv run isaaclab -f`: all pre-commit checks passed.
- Structural audit: no new test classes or kernels; no production
changes in the test consolidation. The composer architecture regression
still rejects frame/content enums, the classification layer, and the old
submission alias.

Regression sensitivity was checked by temporarily restoring
unconditional composition and stale-pose caching: the updated existing
tests fail on unnecessary pose reads and on a second read after the body
rotates, respectively.

The previously recorded paired Python dispatch microbenchmark changed
local buffer selection from about 99 ns to 46 ns per call, and
global-at-CoM selection from 127 ns to 60 ns. This measures buffer
selection only, not end-to-end simulation; production code is unchanged
by the test consolidation.

## Performance

The end-to-end measurements below were recorded for the original
optimization; they were not rerun for the boolean/API simplification.

Real PhysX, RTX 5090, ANYMAL-C (17 bodies) × 4096 envs = 69,632 links.
Same-process paired A/B with the arm order alternated per iteration,
400–500 pairs, 95% CI on paired differences. Baseline is
`compose_to_body_frame()` — what the writers previously called
unconditionally.

| scope | content | baseline | patched | paired delta | 95% CI |
|---|---|---:|---:|---:|---|
| composition path only | global-at-CoM | 0.2194 ms | 0.0191 ms |
**−0.2003 ms** (−91.3%) | [0.1915, 0.2091] |
| composition path only | local | 0.1926 ms | 0.0159 ms | **−0.1767 ms**
(−91.8%) | [0.1712, 0.1822] |
| full `write_data_to_sim` | global-at-CoM | 1.0799 ms | 0.9897 ms |
**−0.0902 ms** (−8.4%) | [0.0797, 0.1007] |
| full `write_data_to_sim` | local | 1.0072 ms | 0.9305 ms | **−0.0767
ms** (−7.6%) | [0.0719, 0.0815] |

Read the end-to-end row as the honest headline: **~0.08 ms per asset per
physics step**. Roughly half the isolated saving does not reach the
caller, because other work in `write_data_to_sim` touches body poses
anyway and pays part of that cost regardless. A cuboid rigid-object
scene at the same env count saved only ~6.5 µs, as expected — there is
no articulation FK pass to skip.

Scope caveat: no in-tree task sets `is_global=True` today (both shipped
`apply_external_force_torque` events use the local default), so the
local path is what delivers value now, and it is the one that reaches
every backend.

## Supersedes

This replaces two open PRs, both of which found one half of this
problem:

- **#7431** (@NeoZng) identified the global-at-CoM case and the cost of
the pose read. Its mechanism is correct and its writer-level measurement
is corroborated here. It is superseded on placement rather than
substance: it put the frame decision in three PhysX writers behind a
public eligibility flag, leaving Newton and OvPhysX unserved. The credit
for the world-at-CoM half of this mechanism is theirs.
- **#7362** cached composition for unchanged local wrenches. Superseded
because not composing at all is strictly stronger — the cache does
nothing when the wrench is rewritten every step, which is the common
case for a per-step randomized push.

## Type of change

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

## Checklist

- [x] I have read and understood the [contribution
guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html)
- [x] I have run the `pre-commit` checks with `./isaaclab.sh --format`
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have added a changelog fragment under
`source/<pkg>/changelog.d/` for every touched package
- [x] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Octi Zhang <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working isaac-lab Related to Isaac Lab team

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants