Skip to content

Fix O(N)/O(N^2) camera-pose resolution stall under PhysX + Newton ren… - #6554

Closed
yts-nv wants to merge 6 commits into
isaac-sim:developfrom
yts-nv:fix/physx-newton-camera-pose-scaling
Closed

yts-nv wants to merge 6 commits into
isaac-sim:developfrom
yts-nv:fix/physx-newton-camera-pose-scaling

Conversation

@yts-nv

@yts-nv yts-nv commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Description

At high environment counts (e.g. Isaac-Lift-KukaAllegro-Camera at 8192 envs) with
presets=physx,newton_renderer, the PhysX-backed camera-sensor pose update stalls for
minutes per training iteration, causing benchmarks to time out with no results.

Root cause: two per-prim Python hotspots on the PhysX -> Newton-renderer camera path,
both scaling with the whole-scene prim/body count rather than the handful of managed cameras:

  1. FabricFrameView._compute_fabric_indices_for rebuilt a {str(Sdf.Path): index} map over
    every prim in the Fabric selection (~1.14M prims for an 8192-env scene) on every env
    reset
    , only to resolve the managed camera prims.
    -> Cache the map per selection; rebuild only when the selection size changes.

  2. SceneDataProvider.create_mapping used an O(N^2) list.index() lookup per input transform
    (~200k rigid bodies).
    -> Replace with an O(N) dict lookup.

Results

Measured on Isaac-Lift-KukaAllegro-Camera, presets=physx,newton_renderer,single_camera,rgb64,
num_envs=8192 (RTX PRO 6000 Blackwell):

before after
per-iteration ~220 s ~53 s
outcome timeout, no results completes, KPIs written

Training rewards are unchanged (verified at num_envs=256; per-iteration mean reward identical).

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Performance improvement

Checklist

  • I have run the pre-commit checks with ./isaaclab.sh --format
  • I have updated the changelog and the corresponding version in the extension's config/extension.toml
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

@github-actions github-actions Bot added bug Something isn't working isaac-lab Related to Isaac Lab team labels Jul 16, 2026
@greptile-apps

greptile-apps Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes two separate per-prim Python hotspots on the PhysX → Newton-renderer camera path that caused per-iteration stalls of ~220 s at 8192 environments, reducing it to ~53 s.

  • FabricFrameView._compute_fabric_indices_for: caches the str(Sdf.Path) → fabric-index dict per selection object (keyed by id(selection) + size), avoiding a full rebuild over all ~1.1 M prims in the scene on every environment reset.
  • SceneDataProvider.create_mapping: replaces an O(N²) list.index() inner loop (~200k rigid bodies) with a single O(N) dict build followed by O(1) lookups per input path, preserving first-occurrence and missing-path (-1) semantics exactly.

Confidence Score: 4/5

Safe to merge for the described production use case; the one concern is a code-pattern fragility in the caching strategy that is unlikely to trigger in the steady-state training loop.

Both hotfixes are correct and well-scoped. The scene_data_provider.py change is a clean algorithmic substitution with identical semantics. The fabric_frame_view.py cache uses id(selection) as its key, which can theoretically serve a stale dict if a selection object is GC'd and a new one lands at the same address with the same prim count — a silent correctness hazard. In the current training loop, selections are long-lived view attributes so the risk is low, but it is a structural fragility worth noting.

The cache implementation in fabric_frame_view.py around the id(selection) keying deserves a second look; scene_data_provider.py is straightforward and needs no special attention.

Important Files Changed

Filename Overview
source/isaaclab_physx/isaaclab_physx/sim/views/fabric_frame_view.py Caches the expensive path→Fabric-index dict keyed by id(selection); addresses the O(N) str conversion over all 1.1M scene prims on every reset, with one minor robustness concern around Python id-reuse.
source/isaaclab/isaaclab/scene_data/scene_data_provider.py Replaces O(N²) list.index() per input path with a single O(N) dict build + O(1) lookups; semantics match the original (first-occurrence wins, missing paths → -1, None output slots skipped).

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Camera pose update triggered] --> B[FabricFrameView._compute_fabric_indices_for]
    B --> C{Cache hit for selection?}
    C -- Yes, same id + same size --> D[Reuse cached path-to-idx dict]
    C -- No --> E[Build str path dict over all selection prims]
    E --> F[Store entry in _fab_pathmap_cache]
    F --> D
    D --> G[Lookup managed camera paths]
    G --> H[Return wp.array of fabric indices]
    I[SceneDataProvider.create_mapping] --> J[Build path-to-out_idx dict over output paths O-N]
    J --> K[Resolve each input_path via dict.get O-1 each]
    K --> L{mapping == identity?}
    L -- Yes --> M[Return None]
    L -- No --> N[Return wp.int32 remapping array]
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A[Camera pose update triggered] --> B[FabricFrameView._compute_fabric_indices_for]
    B --> C{Cache hit for selection?}
    C -- Yes, same id + same size --> D[Reuse cached path-to-idx dict]
    C -- No --> E[Build str path dict over all selection prims]
    E --> F[Store entry in _fab_pathmap_cache]
    F --> D
    D --> G[Lookup managed camera paths]
    G --> H[Return wp.array of fabric indices]
    I[SceneDataProvider.create_mapping] --> J[Build path-to-out_idx dict over output paths O-N]
    J --> K[Resolve each input_path via dict.get O-1 each]
    K --> L{mapping == identity?}
    L -- Yes --> M[Return None]
    L -- No --> N[Return wp.int32 remapping array]
Loading

Reviews (1): Last reviewed commit: "Fix O(N)/O(N^2) camera-pose resolution s..." | Re-trigger Greptile

Comment on lines +740 to +745
entry = cache.get(id(selection))
if entry is not None and entry[0] == n:
path_to_idx = entry[1]
else:
path_to_idx = {str(p): i for i, p in enumerate(all_paths)}
cache[id(selection)] = (n, path_to_idx)

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 id() reuse can silently serve a stale index map

Python reuses memory addresses: if a selection object is garbage-collected and a new object is later allocated at the same address, id(new_selection) == id(old_selection) and the cache would return the old path→index dict. The size check (entry[0] == n) only guards against a different-sized selection landing at that address; a same-sized new selection would pass it and get wrong fabric indices — silently, with no error.

In the current steady-state training loop the selection objects are long-lived view attributes, so this is unlikely to fire. A structurally sound alternative is weakref.WeakKeyDictionary (requires the selection type to support weak-referencing), which auto-evicts entries on GC and uses actual object identity rather than potentially reused addresses. If the selection is not weakly-referenceable, caching the map as an instance attribute keyed by selection itself (if hashable) avoids the id-reuse hazard too.

@yts-nv
yts-nv force-pushed the fix/physx-newton-camera-pose-scaling branch 2 times, most recently from 3417f85 to ab9e44b Compare July 16, 2026 05:01
…derer

At high environment counts (e.g. Isaac-Lift-KukaAllegro-Camera at 8192 envs),
the PhysX-backed camera sensor pose update stalls for minutes per training
iteration, causing benchmarks to time out with no results.

Two per-prim Python hotspots on the PhysX -> Newton-renderer camera path:

1. FabricFrameView._compute_fabric_indices_for rebuilt a
   {str(Sdf.Path): index} map over EVERY prim in the Fabric selection
   (~1.14M prims for an 8192-env scene) on every env reset, only to resolve
   the managed camera prims. Cache the map per selection and rebuild it only
   when the selection size changes.

2. SceneDataProvider.create_mapping used an O(N^2) list.index() lookup per
   input transform (~200k rigid bodies). Replace it with an O(N) dict lookup.

Measured on Isaac-Lift-KukaAllegro-Camera,
presets=physx,newton_renderer,single_camera,rgb64, num_envs=8192
(RTX PRO 6000 Blackwell): per-iteration time drops from ~220 s to ~53 s and
the run completes and writes benchmark KPIs instead of timing out. Training
rewards are unchanged (verified at num_envs=256).
@yts-nv
yts-nv force-pushed the fix/physx-newton-camera-pose-scaling branch from ab9e44b to 051dec8 Compare July 16, 2026 05:18
@yts-nv
yts-nv requested a review from a team July 22, 2026 02:13
@yts-nv
yts-nv requested a review from StafaH as a code owner July 28, 2026 08:38
@pv-nvidia pv-nvidia self-assigned this Jul 30, 2026
See :meth:`_rebuild_ro_arrays`: the resolved index arrays are recomputed
only when the selection size changes; the wrappers are always rebuilt.
"""
n = len(self._sel_rw.GetPaths())

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.

Caching on just the length feels fragile. But better caching like computing a hash might make this slow again...

changes; the indexed-fabric-array wrappers below are always rebuilt since
the underlying buckets may have moved.
"""
n = len(self._sel_ro.GetPaths())

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.

Caching on just the length feels fragile. But better caching like computing a hash might make this slow again...

self._ro_child_idx_host = self._compute_fabric_indices(self._sel_ro).numpy()
self._ro_parent_idx_host = self._compute_parent_fabric_indices(self._sel_ro).numpy()
self._ro_cached_n = n
# Fresh device arrays each rebuild (do not alias one cached wp.array across

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.

I don't understand this comment

if getattr(self, "_ro_cached_n", None) != n:
# Cache only the tiny resolved indices on the host (a few KB), NOT the
# giant per-selection path->index dict.
self._ro_child_idx_host = self._compute_fabric_indices(self._sel_ro).numpy()

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.

Why .numpy() here?

"""
n = len(self._sel_rw.GetPaths())
if getattr(self, "_rw_cached_n", None) != n:
self._rw_child_idx_host = self._compute_fabric_indices(self._sel_rw).numpy()

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.

Why numpy() here?

self._rw_child_idx_host = self._compute_fabric_indices(self._sel_rw).numpy()
self._rw_parent_idx_host = self._compute_parent_fabric_indices(self._sel_rw).numpy()
self._rw_cached_n = n
self._rw_fabric_indices = wp.array(self._rw_child_idx_host, dtype=wp.int32, device=self._device)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Wny do we create new indices here? Can't we use the cached ones directly?

# the churning per-reset wrappers).
self._ro_fabric_indices = wp.array(self._ro_child_idx_host, dtype=wp.int32, device=self._device)
self._ro_parent_fabric_indices = wp.array(self._ro_parent_idx_host, dtype=wp.int32, device=self._device)
self._world_ifa_ro = self._build_indexed_array(self._sel_ro, self._WORLD_MATRIX_NAME, self._ro_fabric_indices)

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.

Wny do we create new indices here? Can't we use the cached ones directly?

@AntoineRichard

AntoineRichard commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closing this PR in favor of #6805 to avoid accidental merging. If you feel different feel free to re-open it.

@pv-nvidia pv-nvidia mentioned this pull request Aug 4, 2026
7 tasks done
pbarejko pushed a commit that referenced this pull request Aug 7, 2026
)

# Description

Camera world-pose resolution stalled at high environment counts on the
PhysX backend, badly enough to time out benchmarks. There are two
independent bottlenecks; the PR also adds a lifecycle hook that came out
of review.

### 1. `FabricFrameView` resolved prim paths on the host, against the
whole stage

Cameras read their poses from Fabric. To do that the frame view needs to
know where each camera's data sits in Fabric memory, so it builds a
lookup table from "camera number" to "Fabric slot".

Building that table was very slow. The view selected prims by requiring
the Fabric world and local matrix attributes — but every xformable in
the stage carries those, so the selection matched the **entire stage**
(~1.1M prims at 8192 environments), not the view's handful of cameras.
Finding its own prims in that list then meant building a Python
dictionary over all of it, on the host:

```python
path_to_idx = {str(p): i for i, p in enumerate(selection.GetPaths())}
```

That ran twice per rebuild (once for the children, once for their
parents), and rebuilt whenever `PrepareForReuse()` reported a bucket
change — in practice on every environment reset.

The cost of that dictionary scales with the size of the whole scene, not
with the number of cameras: it converts every path in the stage to a
Python string and inserts it. Measured directly, one full rebuild takes
10 ms on a bare stage but **556 ms once 100k unrelated prims are
present** (table below), and it grows linearly from there — seconds of
host work per reset at the ~1.1M prims of an 8192-environment scene.

**Fix:** author a private per-view `uint` index attribute on each
managed prim (and on each unique parent), holding that prim's view
index. Every selection requires the matching index attribute, so
**selections resolve to exactly the view's prims**. The view-to-Fabric
slot mapping is then rebuilt by inverting that attribute in a single
Warp kernel launch:

```python
fabric_slots[view_indices[fabric_slot]] = fabric_slot
```

That is `O(view)` device work with no host-side path resolution and no
Python objects created per frame.

There is also **no cache**, so there is nothing to invalidate. The table
is rebuilt from live Fabric data on every access, which means a bucket
reorder can never leave a stale mapping behind. Selections are still
checked with `GetCount()`, which is exact here: the index attribute
belongs to one view, so the count can only change if one of that view's
prims actually disappeared — and then the view raises a clear error
instead of silently reading the wrong prim.

Attribute names embed a process-wide monotonic uid, so a dead view's
leftover attributes can never satisfy a live view's selection — and
since review, they are removed outright when the view is released
(section 3). Parent reads get their own read-only selection, keeping the
child RO/RW flip semantics from #5677 intact.

### 2. `SceneDataProvider.create_mapping` did a linear scan per item

```python
for i, path in enumerate(input_paths):
    mapping[i] = paths.index(path)   # O(N) scan, per path
```

**Fix:** build the reverse dict once (first occurrence wins, matching
`list.index` semantics), then resolve each path in `O(1)`. Measured over
200k paths, preserving first-occurrence semantics costs nothing versus
an unguarded dict comprehension, so the fix carries no behaviour change.

### 3. Index attributes are removed when a view is released (from
review)

The per-view index attributes from fix 1 were initially never removed,
so views recreated over the same prims on a long-lived stage accumulated
attribute pairs, widening those prims' Fabric buckets. Measured over 8
successive views on one stage (512 prims), attributes on a single prim
went 1 → 8 and first-access rose monotonically from 120 ms to 173 ms.

**Fix:** `FabricFrameView.close()` removes the view's tags (measured at
4.7 µs per prim, ~77 ms for an 8192-env view) and is safe to call more
than once. `BaseFrameView` gains a no-op `close()` so callers can close
any backend uniformly. Every in-repo callsite now closes its view:
`Camera` when invalidated **and when dropped** (`__del__`),
`prim_world_positions` after each per-env view it creates in a loop, and
`SceneAsset` before replacing its cached view. Views dropped without
`close()` are cleaned up best-effort from `__del__`, following the
shutdown-safe idiom the env classes already use (`sys` bound as a
default argument; nothing runs during interpreter finalization, where
Fabric dies with the process anyway), and a warning names the view so
the missing `close()` call can be fixed.

## How the problem was found

The stall was invisible in Tracy. Comparing captures before and after
the commit that introduced it, Kit's own per-frame work is unchanged —
`App Update` totals 65.1 s before and 62.3 s after, over ~120 frames.
All the lost time sits in the gaps *between* frames, where the main
thread is blocked in Python and Kit records nothing.

A `py-spy` capture found the cause: `_compute_fabric_indices_for`
accounted for **11.86% of samples (23.2 s of a 195 s run)**, reached
through `camera.reset()` → `get_world_poses()` → the selection rebuild.
Every frame on that chain carries essentially the same share, so the
whole cost is that one function.

Fixes nvbug 6535498.

## Type of change

- Bug fix (non-breaking change which fixes an issue)
- New feature (non-breaking change which adds functionality) —
`FrameView.close()`

## Benchmarks

### End-to-end symptom

Task `Isaac-Lift-KukaAllegro-Camera`, 8192 environments,
`presets=physx,isaacsim_rtx_renderer,duo_camera`. Commit `69888c34e471`
(which introduced the problem) against its parent `e5f99d320338`:

| | Parent | With the problem |
| --- | ---: | ---: |
| Mean environment step | 699 ms | 7193 ms |
| Slow steps (over 3 s) | 1 of 100 | 28 of 100, averaging 18.9 s |
| GPU utilization | 23.4% | 4.7% |

GPU and CPU utilization both drop during the slow steps, which is what a
stall looks like — the pipeline is waiting, not doing extra work.

With this PR, the same task at 8192 environments steps at **mean 1.554
s, peak 1.663 s** — peak within 7% of mean, i.e. the stalls are gone.
(Measured on an RTX A6000, so the absolute step time is not comparable
to the table above, which was captured on different hardware; the stall
signature is the comparison that matters.)

### Selection size — the actual fix

L40, `cuda:0`, 1024-prim view (1024 children + 1024 parents). "Filler"
is xformable prims **not** in the view but carrying Fabric matrices —
i.e. the rest of a real scene.

| filler prims | `develop` selection | this PR |
| ---: | ---: | ---: |
| 0 | 2,048 | 1,024 |
| 10,000 | 12,048 | 1,024 |
| 100,000 | 102,048 | **1,024** |

`develop` scales with the stage; this PR is pinned to the view.

### Slot-mapping rebuild (mean ms, the path hit on every reset)

| filler prims | `develop` child | `develop` parent | `develop` full RO
rebuild | PR child | PR parent |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 0 | 4.67 | 5.40 | 10.24 | 0.137 | 0.191 |
| 10,000 | 24.05 | 24.69 | 62.47 | 0.139 | 0.193 |
| 100,000 | 274.21 | 270.47 | **556.41** | **0.137** | **0.190** |

`develop` grows linearly with stage size — **556 ms per rebuild** at
100k filler prims. This PR is flat at **~0.14 ms**, a **~2000×**
reduction, and unchanged from 0 to 100k filler prims. First access at
100k filler: 1824 ms → 383 ms.

### `create_mapping` (pure Python, reversed path order)

| N | `develop` | this PR | speedup |
| ---: | ---: | ---: | ---: |
| 1,000 | 0.0038 s | 0.0001 s | 27× |
| 5,000 | 0.0862 s | 0.0007 s | 120× |
| 20,000 | 1.3241 s | 0.0030 s | 434× |
| 50,000 | 8.5507 s | 0.0092 s | **929×** |
| 200,000 | (not run) | 0.0467 s | — |

Outputs verified identical at every N. At the ~200k rigid bodies of an
8192-environment scene the old path takes minutes.

## Tests

| Suite | Result |
| --- | --- |
| `isaaclab_physx/test/sim/test_views_xform_prim_fabric.py` | 79 passed,
4 skipped (`cpu` + `cuda:0` on an L40) |
| `isaaclab/test/sim/test_views_xform_prim.py` (USD contract) | 63
passed |
| `isaaclab_newton/test/sim/test_views_xform_prim_newton.py` | 58 passed
|
| `isaaclab/test/sensors/test_camera.py` (main consumer, incl. the new
`close()` call) | 35 passed, 0 missing-`close()` warnings |
| `isaaclab/test/utils/warp/test_proxy_array.py` | 81 passed |

New tests:

- `test_selections_match_only_the_view_prims` asserts each selection
matches exactly the prims the view manages. Verified to fail without the
fix — with the selections unscoped it reports `matched 8 prims, expected
4`, because the child selections pick up the parents too.
- `test_close_removes_index_attributes` asserts the tag-scoped selection
drops to zero after `close()` and that a second `close()` is a no-op.
- `test_garbage_collection_removes_index_attributes_and_warns` asserts a
view dropped without `close()` still removes its tags on collection and
logs the warning.

`test_fabric_rebuild_after_topology_change` was updated to drive the new
refresh paths instead of the removed `_rebuild_{ro,rw}_arrays`.

The 4 skips are environmental: empty device parameter sets, and Fabric
hierarchy bindings that are unavailable in a headless experience.

**Coverage gap:** `test_physx_scene_data_backend.py` and
`test_ovphysx_scene_data_backend.py` both skip at collection on the
machine used here, so the `create_mapping` change is exercised only by
the standalone benchmark above, not by the test suite. Worth a look in
CI, where those backends are available.

## Screenshots

Not applicable — no visual change. The benchmarks above cover the
behaviour change.

## Notes for reviewers

**Review feedback addressed so far:** the index-attribute accumulation
is fixed by `close()` (section 3); the opposite-space recompute no
longer refreshes the same selection twice on writer-scope exit;
`create_mapping` keeps `list.index`'s first-occurrence semantics for
duplicate paths (measured free at 200k paths); and docstrings/changelogs
were trimmed to the observable contract.

**The `isaaclab`/`isaaclab_physx` changelog fragments are still named
`fix-physx-newton-camera-pose-scaling.rst`**, inherited from #6554 —
nothing here touches Newton or scaling. The new `isaaclab_mimic`
fragment uses the branch slug. Happy to rename if reviewers prefer.

**A handful of tests still drop views without `close()`** and now log
the new warning during runs; harmless, cleanup to follow.

EDIT: fixed — the only remaining warning is the one
`test_garbage_collection_removes_index_attributes_and_warns` asserts on.
`Camera` previously closed its view only on invalidation, so a dropped
camera still went through `__del__`; it now closes in `Camera.__del__`
too. `test_camera.py` went from 3 warnings to 0.

## Relationship to #6554

#6554 found the same two slow paths. This PR takes its
`SceneDataProvider` fix unchanged (credited with a `Co-authored-by`
line) and replaces its Fabric frame view fix.

#6554 kept the whole-stage selection and the Python dictionary, and
cached the result, reusing it while the number of selected prims stayed
the same. Two problems with that. The cache key is unsafe: an equal prim
count does not mean the prims or their order stayed the same, so after a
bucket reorder or a same-count membership change the cached indices
point at the wrong prims and cameras silently read another prim's
transform. And it treats the symptom — the underlying operation is still
proportional to the size of the whole scene, just performed less often.

Making the selection small removes the need for a cache at all, so both
problems go away.

## 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](https://pre-commit.com/) 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 (do **not** edit
`CHANGELOG.rst` or bump `extension.toml` — CI handles that)
- [x] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there

---------

Co-authored-by: pv-nvidia <197907000+pv-nvidia@users.noreply.github.com>
Co-authored-by: yts-nv <yts-nv@users.noreply.github.com>
Co-authored-by: Kelly Guo <kellyg@nvidia.com>
pv-nvidia added a commit to pv-nvidia/pv-isaac-lab that referenced this pull request Aug 27, 2026
…aac-sim#6805)

Camera world-pose resolution stalled at high environment counts on the
PhysX backend, badly enough to time out benchmarks. There are two
independent bottlenecks; the PR also adds a lifecycle hook that came out
of review.

whole stage

Cameras read their poses from Fabric. To do that the frame view needs to
know where each camera's data sits in Fabric memory, so it builds a
lookup table from "camera number" to "Fabric slot".

Building that table was very slow. The view selected prims by requiring
the Fabric world and local matrix attributes — but every xformable in
the stage carries those, so the selection matched the **entire stage**
(~1.1M prims at 8192 environments), not the view's handful of cameras.
Finding its own prims in that list then meant building a Python
dictionary over all of it, on the host:

```python
path_to_idx = {str(p): i for i, p in enumerate(selection.GetPaths())}
```

That ran twice per rebuild (once for the children, once for their
parents), and rebuilt whenever `PrepareForReuse()` reported a bucket
change — in practice on every environment reset.

The cost of that dictionary scales with the size of the whole scene, not
with the number of cameras: it converts every path in the stage to a
Python string and inserts it. Measured directly, one full rebuild takes
10 ms on a bare stage but **556 ms once 100k unrelated prims are
present** (table below), and it grows linearly from there — seconds of
host work per reset at the ~1.1M prims of an 8192-environment scene.

**Fix:** author a private per-view `uint` index attribute on each
managed prim (and on each unique parent), holding that prim's view
index. Every selection requires the matching index attribute, so
**selections resolve to exactly the view's prims**. The view-to-Fabric
slot mapping is then rebuilt by inverting that attribute in a single
Warp kernel launch:

```python
fabric_slots[view_indices[fabric_slot]] = fabric_slot
```

That is `O(view)` device work with no host-side path resolution and no
Python objects created per frame.

There is also **no cache**, so there is nothing to invalidate. The table
is rebuilt from live Fabric data on every access, which means a bucket
reorder can never leave a stale mapping behind. Selections are still
checked with `GetCount()`, which is exact here: the index attribute
belongs to one view, so the count can only change if one of that view's
prims actually disappeared — and then the view raises a clear error
instead of silently reading the wrong prim.

Attribute names embed a process-wide monotonic uid, so a dead view's
leftover attributes can never satisfy a live view's selection — and
since review, they are removed outright when the view is released
(section 3). Parent reads get their own read-only selection, keeping the
child RO/RW flip semantics from isaac-sim#5677 intact.

```python
for i, path in enumerate(input_paths):
    mapping[i] = paths.index(path)   # O(N) scan, per path
```

**Fix:** build the reverse dict once (first occurrence wins, matching
`list.index` semantics), then resolve each path in `O(1)`. Measured over
200k paths, preserving first-occurrence semantics costs nothing versus
an unguarded dict comprehension, so the fix carries no behaviour change.

review)

The per-view index attributes from fix 1 were initially never removed,
so views recreated over the same prims on a long-lived stage accumulated
attribute pairs, widening those prims' Fabric buckets. Measured over 8
successive views on one stage (512 prims), attributes on a single prim
went 1 → 8 and first-access rose monotonically from 120 ms to 173 ms.

**Fix:** `FabricFrameView.close()` removes the view's tags (measured at
4.7 µs per prim, ~77 ms for an 8192-env view) and is safe to call more
than once. `BaseFrameView` gains a no-op `close()` so callers can close
any backend uniformly. Every in-repo callsite now closes its view:
`Camera` when invalidated **and when dropped** (`__del__`),
`prim_world_positions` after each per-env view it creates in a loop, and
`SceneAsset` before replacing its cached view. Views dropped without
`close()` are cleaned up best-effort from `__del__`, following the
shutdown-safe idiom the env classes already use (`sys` bound as a
default argument; nothing runs during interpreter finalization, where
Fabric dies with the process anyway), and a warning names the view so
the missing `close()` call can be fixed.

The stall was invisible in Tracy. Comparing captures before and after
the commit that introduced it, Kit's own per-frame work is unchanged —
`App Update` totals 65.1 s before and 62.3 s after, over ~120 frames.
All the lost time sits in the gaps *between* frames, where the main
thread is blocked in Python and Kit records nothing.

A `py-spy` capture found the cause: `_compute_fabric_indices_for`
accounted for **11.86% of samples (23.2 s of a 195 s run)**, reached
through `camera.reset()` → `get_world_poses()` → the selection rebuild.
Every frame on that chain carries essentially the same share, so the
whole cost is that one function.

Fixes nvbug 6535498.

- Bug fix (non-breaking change which fixes an issue)
- New feature (non-breaking change which adds functionality) —
`FrameView.close()`

Task `Isaac-Lift-KukaAllegro-Camera`, 8192 environments,
`presets=physx,isaacsim_rtx_renderer,duo_camera`. Commit `69888c34e471`
(which introduced the problem) against its parent `e5f99d320338`:

| | Parent | With the problem |
| --- | ---: | ---: |
| Mean environment step | 699 ms | 7193 ms |
| Slow steps (over 3 s) | 1 of 100 | 28 of 100, averaging 18.9 s |
| GPU utilization | 23.4% | 4.7% |

GPU and CPU utilization both drop during the slow steps, which is what a
stall looks like — the pipeline is waiting, not doing extra work.

With this PR, the same task at 8192 environments steps at **mean 1.554
s, peak 1.663 s** — peak within 7% of mean, i.e. the stalls are gone.
(Measured on an RTX A6000, so the absolute step time is not comparable
to the table above, which was captured on different hardware; the stall
signature is the comparison that matters.)

L40, `cuda:0`, 1024-prim view (1024 children + 1024 parents). "Filler"
is xformable prims **not** in the view but carrying Fabric matrices —
i.e. the rest of a real scene.

| filler prims | `develop` selection | this PR |
| ---: | ---: | ---: |
| 0 | 2,048 | 1,024 |
| 10,000 | 12,048 | 1,024 |
| 100,000 | 102,048 | **1,024** |

`develop` scales with the stage; this PR is pinned to the view.

| filler prims | `develop` child | `develop` parent | `develop` full RO
rebuild | PR child | PR parent |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 0 | 4.67 | 5.40 | 10.24 | 0.137 | 0.191 |
| 10,000 | 24.05 | 24.69 | 62.47 | 0.139 | 0.193 |
| 100,000 | 274.21 | 270.47 | **556.41** | **0.137** | **0.190** |

`develop` grows linearly with stage size — **556 ms per rebuild** at
100k filler prims. This PR is flat at **~0.14 ms**, a **~2000×**
reduction, and unchanged from 0 to 100k filler prims. First access at
100k filler: 1824 ms → 383 ms.

| N | `develop` | this PR | speedup |
| ---: | ---: | ---: | ---: |
| 1,000 | 0.0038 s | 0.0001 s | 27× |
| 5,000 | 0.0862 s | 0.0007 s | 120× |
| 20,000 | 1.3241 s | 0.0030 s | 434× |
| 50,000 | 8.5507 s | 0.0092 s | **929×** |
| 200,000 | (not run) | 0.0467 s | — |

Outputs verified identical at every N. At the ~200k rigid bodies of an
8192-environment scene the old path takes minutes.

| Suite | Result |
| --- | --- |
| `isaaclab_physx/test/sim/test_views_xform_prim_fabric.py` | 79 passed,
4 skipped (`cpu` + `cuda:0` on an L40) |
| `isaaclab/test/sim/test_views_xform_prim.py` (USD contract) | 63
passed |
| `isaaclab_newton/test/sim/test_views_xform_prim_newton.py` | 58 passed
|
| `isaaclab/test/sensors/test_camera.py` (main consumer, incl. the new
`close()` call) | 35 passed, 0 missing-`close()` warnings |
| `isaaclab/test/utils/warp/test_proxy_array.py` | 81 passed |

New tests:

- `test_selections_match_only_the_view_prims` asserts each selection
matches exactly the prims the view manages. Verified to fail without the
fix — with the selections unscoped it reports `matched 8 prims, expected
4`, because the child selections pick up the parents too.
- `test_close_removes_index_attributes` asserts the tag-scoped selection
drops to zero after `close()` and that a second `close()` is a no-op.
- `test_garbage_collection_removes_index_attributes_and_warns` asserts a
view dropped without `close()` still removes its tags on collection and
logs the warning.

`test_fabric_rebuild_after_topology_change` was updated to drive the new
refresh paths instead of the removed `_rebuild_{ro,rw}_arrays`.

The 4 skips are environmental: empty device parameter sets, and Fabric
hierarchy bindings that are unavailable in a headless experience.

**Coverage gap:** `test_physx_scene_data_backend.py` and
`test_ovphysx_scene_data_backend.py` both skip at collection on the
machine used here, so the `create_mapping` change is exercised only by
the standalone benchmark above, not by the test suite. Worth a look in
CI, where those backends are available.

Not applicable — no visual change. The benchmarks above cover the
behaviour change.

**Review feedback addressed so far:** the index-attribute accumulation
is fixed by `close()` (section 3); the opposite-space recompute no
longer refreshes the same selection twice on writer-scope exit;
`create_mapping` keeps `list.index`'s first-occurrence semantics for
duplicate paths (measured free at 200k paths); and docstrings/changelogs
were trimmed to the observable contract.

**The `isaaclab`/`isaaclab_physx` changelog fragments are still named
`fix-physx-newton-camera-pose-scaling.rst`**, inherited from isaac-sim#6554 —
nothing here touches Newton or scaling. The new `isaaclab_mimic`
fragment uses the branch slug. Happy to rename if reviewers prefer.

**A handful of tests still drop views without `close()`** and now log
the new warning during runs; harmless, cleanup to follow.

EDIT: fixed — the only remaining warning is the one
`test_garbage_collection_removes_index_attributes_and_warns` asserts on.
`Camera` previously closed its view only on invalidation, so a dropped
camera still went through `__del__`; it now closes in `Camera.__del__`
too. `test_camera.py` went from 3 warnings to 0.

`SceneDataProvider` fix unchanged (credited with a `Co-authored-by`
line) and replaces its Fabric frame view fix.

cached the result, reusing it while the number of selected prims stayed
the same. Two problems with that. The cache key is unsafe: an equal prim
count does not mean the prims or their order stayed the same, so after a
bucket reorder or a same-count membership change the cached indices
point at the wrong prims and cameras silently read another prim's
transform. And it treats the symptom — the underlying operation is still
proportional to the size of the whole scene, just performed less often.

Making the selection small removes the need for a cache at all, so both
problems go away.

- [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](https://pre-commit.com/) 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 (do **not** edit
`CHANGELOG.rst` or bump `extension.toml` — CI handles that)
- [x] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there

---------

Co-authored-by: pv-nvidia <197907000+pv-nvidia@users.noreply.github.com>
Co-authored-by: yts-nv <yts-nv@users.noreply.github.com>
Co-authored-by: Kelly Guo <kellyg@nvidia.com>
(cherry picked from commit 480370c)
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

None yet

Development

Successfully merging this pull request may close these issues.

7 participants