Repository navigation
Centralize shared Warp mathematics and rank specialization - #8842
Conversation
[High impact] Shared math changes reach physics assets, experimental tasks, and ray casting. The PR appears safe to merge, with a non-blocking gap in tests for strided arrays and CUDA capture replay. Findings
SummaryMoves shared Warp math into
No tests were executed during this review. Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
F["kernel_factory.make_binary"] --> M["isaaclab.utils.warp.math"]
B["Newton, PhysX, and OV backend state reads"] --> M
R["Ray caster kernels"] --> M
T["Experimental observations, rewards, and terminations"] --> M
M --> W["Warp device functions and rank-specific kernels"]
Reviews (1) · Last reviewed commit: "Centralize shared Warp mathematics and r..." · Reviewed by Greptile |
| def test_heading_and_inverse_rotation_use_body_and_world_frames(): | ||
| with wp.ScopedDevice("cpu"): | ||
| s = 2.0**-0.5 | ||
| quat = wp.array([[0, 0, s, s], [0, 0, -s, s]], dtype=wp.quatf) | ||
| vector = wp.array([[1, 2, 3], [4, 5, 6]], dtype=wp.vec3f) | ||
| forward = wp.array([[1, 0, 0], [0, 1, 0]], dtype=wp.vec3f) | ||
| rotated = wp.empty(2, dtype=wp.vec3f) | ||
| heading = wp.empty(2, dtype=float) | ||
| for inverse, yaw, shape in [ | ||
| (math_kernels.quat_rotate_inv_kernel[1], math_kernels.heading_kernel[1], (2,)), | ||
| (math_kernels.quat_rotate_inv_kernel[2], math_kernels.heading_kernel[2], (1, 2)), | ||
| ]: | ||
| wp.launch(inverse, shape, [quat.reshape(shape), vector.reshape(shape), rotated.reshape(shape)]) | ||
| wp.launch(yaw, shape, [forward.reshape(shape), quat.reshape(shape), heading.reshape(shape)]) |
There was a problem hiding this comment.
Stride and replay tests missing
test_heading_and_inverse_rotation_use_body_and_world_frames only launches contiguous arrays on CPU. Backend state reads now use these generated kernels, but the tests do not protect their promised stride support or CUDA capture replay. Future changes could break either without failing these tests.
Add cases for both ranks with independently strided inputs and outputs. Also add a CUDA capture/replay case that changes input values before replay, skipping it when CUDA is unavailable.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Scope and over-engineering (2), Compatibility and deprecation (3), Style consistency (2), Test quality (1). Other reviewed categories look good.
- PR description: Replace the overstated architecture-gate claim with the specific retired names checked, and list each removed symbol’s replacement and the inverse-rotation argument-order change; no performance evidence is needed.
- Design and architecture: Architecture looks good.
- Scope and over-engineering: Minimal implementation: keep
isaaclab.utils.warp.mathas owner, remove its unused acceleration helper, mergekernel_factory.pyinto it, and retain backend/task substitutions plus compatibility aliases. Suggested PR breakdown: 1) shared math, migrated consumers, aliases, and numerical validation; 2) reorientationxyzwshortest-rotation fix with its regression coverage. - API: API changes look good.
- Compatibility and deprecation: Breaking changes:
state_kernels,quat_yaw_only, and backend heading, inverse-rotation, soft-limit, and Jacobian symbols lack functional warning aliases, migration guidance, and transition coverage. - Implementation: Implementation looks good.
- Style consistency: Rank-indexed kernel dictionaries use singular names, obscuring their collection contract; rename them plurally and update consumers.
- Test quality: Numerical contracts and yaw regressions are useful, but the ownership test relies on exact source, import, and retired-name greps; retain only behavioral and kernel-ownership assertions.
Significant concerns. Posted 8 inline findings.
Automated review; human maintainers own approval decisions.
| # | ||
| # SPDX-License-Identifier: BSD-3-Clause | ||
|
|
||
| """Warp helper functions for body-frame state computations. |
There was a problem hiding this comment.
🔴 Critical · Compatibility — Restore state_kernels module with deprecation
This public cross-package import path is deleted outright, breaking any external importer. Keep the module forwarding to isaaclab.utils.warp.math with a DeprecationWarning and a migration note for the prescribed removal window.
| CAMERA_RAYCAST_MAX_DIST: float = 1e6 | ||
|
|
||
|
|
||
| @wp.func |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Keep quat_yaw_only as deprecated alias
This public core @wp.func is removed without a bridge, so downstream kernels calling it break at compile time. Retain it forwarding to yaw_quat through the deprecation window.
| import warp as wp | ||
|
|
||
|
|
||
| def make_binary(operation, left_dtype, right_dtype, result_dtype, ndim: int, *, module: str) -> wp.Kernel: |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Inline make_binary into math module
make_binary has one consumer. Defining it in math.py deletes this file, the module keyword that exists only to bridge the split, and the ndim guard no call site can reach.
|
|
||
|
|
||
| @wp.func | ||
| def acceleration_at_offset(acceleration: wp.spatial_vectorf, angular_velocity: wp.vec3f, offset: wp.vec3f) -> wp.vec3f: |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Remove unused acceleration_at_offset helper
No production code calls acceleration_at_offset; its only caller is the new test's _transport kernel. Delete it and add it alongside the consumer that needs it.
|
|
||
|
|
||
| @wp.func | ||
| def heading_from_quat(forward_vec: wp.vec3f, quat: wp.quatf): |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Annotate and trim heading_from_quat
Unlike every neighbor in this module, heading_from_quat has no return annotation and carries a multi-section docstring narrating its two-line body. Add -> float and reduce it to a one-line contract.
| dst[env, body, 5, dof] = angular[2] | ||
|
|
||
|
|
||
| quat_rotate_inv_kernel = { |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Name rank-keyed kernel mappings plural
quat_rotate_inv_kernel and heading_kernel are dictionaries indexed by rank, so call sites read quat_rotate_inv_kernel[1]. The guide requires plural names for collections; rename both and their consumers.
| np.testing.assert_array_equal(result.numpy()[0, 0, 3:], [[0, 1], [0, 0], [2, 0]]) | ||
|
|
||
|
|
||
| def test_shared_math_ownership(source_checkout_root): |
There was a problem hiding this comment.
🟡 Warning · Test Quality — Replace source greps with behavior assertions
Most of this test parses ASTs for retired names, file paths, and factory placement, so a behavior-preserving rename fails it while a math regression passes. Keep only the kernel-module ownership assertion.
| """ | ||
|
|
||
|
|
||
| @wp.kernel |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Bridge removed backend kernel symbols
root_heading_w, body_heading_w, quat_apply_inverse_1D/2D_kernel and the articulation soft-limit and Jacobian helpers vanish across all three backends with no aliases, though these files retain a Deprecated kernels section. Add forwarding definitions.
| raise ValueError(f"Expected rank 1 or 2, got {ndim}") | ||
|
|
||
| @wp.kernel(module=module) | ||
| def apply( |
|
run-ci |
## Description Reuse Warp's native views, indexed arrays, copy and fill for ordinary memory movement. A single frequency-agnostic owner, `isaaclab.utils.warp.memory`, retains selection normalization, component views, boolean-masked updates, and measured fused operations. Physical equations, application frequencies, native gathering and simulator row-ID bookkeeping remain with their owners. `memory.concat(first, second, result)` now packs components through `tile_load`, `tile_empty`, `tile_assign` and `tile_store`. It owns validation, scalar views and the tiled grid. No array storage is allocated. Contiguous rank-1 and rank-2 arrays share the same cached specialization; strided arrays retain their layout. Specialization depends on scalar type and component widths, without body/joint/pose/velocity concepts. The cached kernel factory stays private to this operation. The existing launch cache records commands returned by a launch operation. Asset readers pass typed Warp arrays (`.warp` for public proxy properties) directly to `memory.concat`; other cached kernels pass `wp.launch`. This keeps layout preparation out of repeated eager reads and keeps operation-specific code out of the launch cache. CPU calls and CUDA graph capture invoke the operation directly. Callers must clear recorded commands when bound storage changes. Ordinary selected writes use `wp.indexedarray` with `wp.copy` or `.fill_()`. `resolve_1d_indices` returns contiguous int32 selectors: existing contiguous int32 storage is reused, while strided/int64 inputs require a copy/cast. Full-shaped sources select the same source and destination views. The general `make_copy`, `make_fill`, selector-width dispatch and `full_source` flags are removed. Small boolean-mask kernels retain dynamic device selection without compaction; custom factories construct only requested isolated kernels, without eager variant registries. **Migration:** import `resolve_1d_mask` from `isaaclab.utils.warp.memory`; the experimental re-export is removed. Warm execution paths before graph capture. Indexed conversion during capture requires Warp's memory pool. Concatenation inputs and output must not overlap; recorded commands require stable storage. Sensor callers and their buffer-lifetime handling are in #8820. ## Validation Regression validation on `366a86fdf`: **741 tests passed** — articulation contracts (487), rigid-object contracts (231), shared memory (13), mocked IMU/PVA recording (8), and mocked frame-transformer recording (2). The asset suites exercised PhysX, Newton, and OVPhysX with pinned optional OV dependencies; 16 unsupported cases skipped and 5 expected failures remain. The sensor unit cases ran with Kit bootstrap disabled, using their existing mocked views. Before the fix, the same suites reproduced all 37 failures covered by those local boundaries. Asset readers explicitly supply `.warp` views to the host concat operation. Tendon writers pass their already normalized int32 device selectors directly to the native binding, and sensor unit fixtures create the selector buffers normally owned by initialization. The contribution guide distinguishes host operations from `wp.launch` argument conversion. A file-by-file audit checked all 10 changed paths and all 36 concat calls in the six affected data classes. Full formatting, changelog validation and `git diff --check` passed. Earlier unchanged checks cover actuator collection (29), launch caching (1), and asset runtime boundaries (14), plus CPU/CUDA, float32/float64, gradients, tile tails, strides, and graph replay in the memory suite. The prior structural audit, negative controls and clean Sphinx build remain applicable. No kernel implementation changed in this correction. Checks used GPU 0 (RTX 5090), Python 3.12 and Warp 1.17 with verified checkout imports. All five previously failing jobs passed on this head in [Docker CI run 40635185447](https://github.com/isaac-sim/IsaacLab/actions/runs/40635185447): all three core shards, PhysX, and test-curobo. This verifies all 60 reported failures, including the 23 full-simulator concat cases unavailable locally. Other jobs in the wider CI matrix may still be running. Combined environment measurements are in #8820. ## Performance Measured on `3c98a7b08` against `ef3fbd818`, using three fresh processes. The subsequent caller/fixture correction leaves the measured kernels unchanged. CUDA-event measurements use eleven alternating trials of 200 captured operations; eager wall measurements use five alternating trials of 1,000 calls. Repeated operations reuse the same buffers, and all outputs are checked against NumPy. - 65,536 contiguous 7+6-component records: captured **7.76 → 3.02 µs** (2.57× faster); repeated recorded calls **8.40 → 4.03 µs**. - 4,099 contiguous records, including a partial tile: captured **3.01 → 1.50 µs**. - Strided 257×17 records: captured **3.41 → 1.67 µs**. - 65,536 3+4-component records: captured **2.71 → 2.23 µs**. Gains depend on the layout. - Initializing both rank-1 and rank-2 7+6 layouts: cold-cache median **429.66 → 362.93 ms**; warm-disk-cache median **4.67 → 2.78 ms**. These are first-operation setup/load/compile times, excluding process imports, context initialization and array allocation. One shared specialization avoids the second compilation; a single tiled specialization itself did not compile faster. **Tradeoff:** direct uncached eager calls rebuild views: **9.42 → 27.98 µs** for the large 7+6 case. Production asset readers reuse recorded commands; direct callers should do the same for stable hot-path buffers. These operation-level gains do not imply a corresponding environment FPS gain. The native-selector conversion tradeoff remains: per-call strided int64/int32 normalization measured 1.28 → 3.33 µs captured in the preceding follow-up. The tiled operation follows [Warp's concatenation example](https://nvidia.github.io/warp/stable/language_reference/_generated/warp.tile_empty.html), validated against the pinned Warp 1.17 runtime. ## Dependencies and review Part 2/4, independently based on `main`; #8842 is merged and this PR has no unmerged dependency. #8844 covers wrench composition. #8820 contains sensor integration and complete-series measurements. Working branches exist only in `ooctipus/IsaacLab`. ## Checklist - [x] Contribution and test-audit guidance applied - [x] Formatting, changelog, documentation and focused checks passed - [x] Structural gates and negative controls validated - [ ] GitHub checks for the updated head
## Description Wrench writes duplicated selector handling and global/local buffer routing across four set/add kernels. `isaaclab.utils.warp.wrench` now owns force, torque and moment-arm algebra; `WrenchComposer` owns native buffers, destination selection and state bookkeeping in one shared preparation method. Cached factories define and return concrete kernels in isolated Warp modules. Writers specialize only the requested selector types and set/add operation. Index and mask resets share one factory and one seven-buffer reset body. Full resets still use native `zero_()`. There are no eager variant tables or returned dispatchers. Frame and input-presence decisions use Python metadata without reading device values. They are fixed at graph capture; selector contents and force/torque values remain device inputs and can change during replay. Exclusive destinations retain ordinary read-add-write assignments. Kernel contracts document frames, launch shapes, null inputs and moment-arm semantics; buffer names spell out their meaning. **Deprecation until Isaac Lab 3.2:** all 11 old wrench entry points in `isaaclab.utils.warp.kernels` remain importable and emit `DeprecationWarning` with the removal release and migration path. Old kernel objects remain launchable with their original signatures, including generic index kernels, masks, Torch/Warp selector helpers and five-buffer frame routing. A lazily loaded compatibility module adapts those signatures to the shared wrench operations; the composer uses the new API directly. Use `WrenchComposer`, or `isaaclab.utils.warp.wrench` for direct launches. The new writer factory accepts the selected force/torque destinations rather than five buffers plus `is_global`. The release note records deprecation instead of an immediate breaking removal. ## Validation Head `028b0fd80`, based on `main` at `9860e2bd8` after #8843 merged. **38 WrenchComposer tests passed**, covering index/mask set/add, both selector widths, local/global frames, moment arms, partial/full reset, lazy composition and CUDA replay. Seven compatibility cases exercise all deprecated entry points and check warning text, original launch signatures, frame routing, null inputs and numerical results on CUDA. Those cases also passed on CPU during development and failed against the pre-fix imports for the intended missing-symbol errors. The structural audit verified file ownership, one-way compatibility dependencies, lazy loading and all 11 deprecated star imports. Full repository formatting, changelog validation and `git diff --check` passed; the private compatibility module also passed explicit Ruff checks. A clean Sphinx HTML build (`-E -a -W --keep-going`) passed with zero warnings. Focused CUDA-event measurements of the six current mask/index set/add/reset variants found no material latency change after extracting the shared device functions. Full simulator CI previously passed on `ce4676b33` in [Docker run 40656490099](https://github.com/isaac-sim/IsaacLab/actions/runs/40656490099). That result predates the deprecation change; [Docker CI for the new head](https://github.com/isaac-sim/IsaacLab/actions/runs/40860136394) was triggered with `run-ci` and is queued. Local validation used Python 3.12 and Warp 1.17 with verified checkout imports. Focused command: `CUDA_VISIBLE_DEVICES=0 uv run python -m pytest source/isaaclab/test/utils/test_wrench_composer.py -q`. ## Why retain a fused partial reset? On an RTX 5090 (driver 580.178.04), resetting seven `vec3f` buffers with shape 4,096×16 and half the environments selected took **2.98 µs** with the fused indexed reset versus **20.42 µs** for seven native indexed-view clears. The masked case took **2.00 µs** versus **8.70 µs** for seven shared masked fills. These are CUDA-event medians of nine alternating trials, each capturing 100 resets after warmup; indexed views were prebuilt. Shapes 4,096×1 and 65,536×16 were also checked for correctness and timing. This measures the value of retaining existing fusion, not a new throughput improvement. The previous fused implementation (`be26c2dcf`, identical wrench source in `64f723ba7`) and the refactored `3c2b3c107` had comparable repeated latency. Three fresh-process trials of the first masked reset measured cold kernel initialization **279.36 → 262.86 ms**, and warm disk-cache initialization **1.63 → 1.70 ms**. These timings predate the deprecation adapters and include factory/compilation/launch and synchronization, excluding imports, CUDA context setup and allocation; they are not environment-startup measurements. No environment FPS gain is claimed. ## Review and dependencies Independent PR against `main`, part 3/4 of the shared Warp refactor. #8842 and #8843 are merged; #8820 contains sensor integration and complete-series measurements. All working branches are in `ooctipus/IsaacLab`. ## Checklist - [x] Contribution and test-audit guidance applied - [x] Formatting, changelog and focused tests passed - [x] Structural audit and regression gates passed - [ ] GitHub checks for the updated head
## What changed PVA's standard output arrays, cached Warp/Torch views, and reset defaults now have one owner in core. Each backend keeps its public `PvaData` class and inherits that storage. The core `PvaData` factory and `BasePvaData` interface remain available. Direct use of the backend classes and base interface is documented as deprecated; imports do not warn, and no removal release is scheduled. `PvaCfg.data_types` selects pose (required), velocity, acceleration, and projected gravity. Disabled groups allocate no output buffer and raise `NotImplementedError` when read. Each backend declares its supported groups. The shared `BasePva` owns validation, reset, and acceleration visualization; backends own native acquisition, solver mappings, and measurement conversion. Kernels take the optional output arrays separately, and the shared writer receives resolved Boolean options. Newton's native gather kernel remains in its backend. IMU, PVA, and frame-transformer equations have shared core kernel owners. Contact and frame-transformer packed reads use the existing `memory.concat` operation with buffer-lifetime-aware capture. Redundant PhysX/OV PVA, IMU, and joint-wrench kernel files and the PhysX frame kernel file are removed; OV's frame kernel keeps its native operation. The contribution guide now records the ownership and test criteria used here. The PR changes 59 files, with 1,081 additions and 1,693 deletions against its merge base. ## Review boundary and migration Antoine requested a consistent data-container direction. This PR retains the PVA public hierarchy and imports while sharing their storage implementation. IMU, joint wrench, frame transformer, and contact retain their existing public data hierarchies; a broader hierarchy removal can be reviewed separately. Ray-caster and camera data are untouched. See the PVA migration notes and per-package changelog fragments for direct-data users. This is part 4/4. #8842, #8843, and #8844 are merged; their implementation commits are absent from this branch. All working branches are in `ooctipus/IsaacLab`. No upstream mirror branch is used. ## Validation Head: `9d0a4cf37`, based on upstream `main` at `e125fd749`. On this head, 11 shared sensor tests and 4 real Newton PVA tests pass locally. Formatting, changelog checks, `git diff --check`, and a file-by-file owner/forbidden-path audit pass. The public PVA imports and inherited factory path are exercised without import warnings. The earlier 782-test local run and broader benchmark series belong to older revisions, so they are not claimed as current-head proof. Full PhysX/OV simulation coverage requires CI; Docker CI for this head is pending. On the prior head, its only failing job was performance smoke: Isaac Sim aborted while creating shared memory on the runner, so no performance conclusion was possible. Historical paired environment timings were noisy and do not establish a general FPS improvement. The operation-level concatenation timings and full reproduction method are in merged #8843.
Description
Quaternion/frame equations, heading, interval scaling, and Jacobian shifts were independently implemented in backend and task packages. Give shared mathematics one core owner,
isaaclab.utils.warp.math, and migrate consumers to it. Device operations compose into fused caller kernels. Warp'swp.map(..., return_kernel=True)predeclares rank-1/rank-2 inverse rotation and heading, plus rank-2 interval scaling, using Warp's per-operation compilation modules. Zero-extent input and output descriptors avoid allocation and singleton-broadcast specialization; callers keep their existing launch cache. There is no project-specific elementwise mapping factory.Backends retain native solver access and policies. Quaternion
xyzw, spatial(linear, angular), frames, and existing non-unit-quaternion behavior are explicit contracts. The reorientation task also corrects its quaternion angular error to usexyzwcomponents and shortest-rotation math. Deleted duplicate definitions and the Newton state-math module have no forwarding aliases. Shared math entry points use operation names:quat_rotate_inv[rank],heading[rank],scale_intervals, andshift_jacobian_reference. The device operation remainsscale_interval; no_kernelcompatibility aliases remain.This is an ownership refactor; no general environment-FPS improvement is claimed.
Validation
62 tests passed across shared math (7), ray casting (16), and experimental observation/reward/termination parity (39). The shared math cases exercise both ranks with independently strided inputs and outputs, untouched padding, and CUDA graph replay after all inputs change. Interval scaling checks positive and negative runtime factors.
All six native asset/articulation kernel modules compiled on CUDA. An import probe forbidding allocation, launch, and compilation passed. The architecture gate rejects restored custom-factory files, retired helper names,
_kernelaliases, and forbidden backend dependencies; numerical tests separately protect the equations. Restoring the retired factory failed the intended gate. A centralized audit of all five review-change paths confirmed that the math equations are unchanged and the deleted factory has no callers.All GPU checks used
CUDA_VISIBLE_DEVICES=0, Python 3.12, Warp 1.17, and the dependencies locked by mainfa569a550. Each PR was tested in an isolated source checkout with verified import paths. Fullisaaclab --format, changelog validation,git diff --check, and the combined clean Sphinx build passed. The integration branch also passed shared math, shared sensor contracts, and real Newton PVA tests (17 checks). Existing dependency deprecation warnings remain; complete OV/PhysX simulator tests require CI runtimes unavailable locally.Review and dependencies
This is an independent PR against
main, part 1/4 of the shared Warp refactor. It has no unmerged code dependency. The complete series is #8842 (math), #8843 (memory), #8844 (wrench), and #8820 (sensor integration), where the final end-to-end results are reported. Working branches are hosted only inooctipus/IsaacLab.Checklist