Repository navigation
[Newton] Redesign Newton Manager [2c/N] - #8735
Conversation
571c9f0 to
ab68d86
Compare
# Description Part of the Newton manager redesign (overview with API examples: #8218 (comment)). [1/N] #8711 (merged) made physics managers instances owned by the simulation as `sim.backend_manager`. The former [2/N] #8712 is split into five stacked PRs: | PR | Stage | |---|---| | [2a/N] **#8733 (this PR)** | Move Newton simulation data onto NewtonBackend | | [2b/N] #8734 | Describe Newton solvers with solver specifications | | [2c/N] #8735 | Move Newton manager logic into backend functions | | [2d/N] #8736 | Capture Newton model changes and Torch work in the step | | [2e/N] #8737 | Run each Newton step as one step graph | This PR is the bottom of the stack and targets `main` directly. ## What this PR does Newton's `Model` stays the immutable description (like `mjModel`). **`NewtonBackend`** becomes the mutable data bound to one finalized model (like `mjData`): state, control, solver, collision pipeline, contacts, sensors, Newton actuators and reset masks. The manager reads and writes `backend.*` instead of private fields, and a hard reset closes the backend and finalizes a new one. - The simulation registry still owns the builder and backend: consumers call `sim.get_or_create_backend(NewtonBuilderCfg(...))` / `sim.get_or_create_backend(NewtonBackendCfg(...))` as before. `NewtonBackendCfg.class_type` is `NewtonBackend`, constructed through `instantiate`. - Replication outputs (`NewtonCloneRecord`, site index map, world transforms, source builders) are read through manager accessors instead of private fields; site and extended-attribute requests persist on the builder across hard resets, so sensors no longer re-register them. - `add_contact_sensor` / `add_imu_sensor` return the Newton sensor. - `NewtonBuilderCfg` and `NewtonBackendCfg` move into their own `newton_builder_cfg.py` / `newton_backend_cfg.py`. - The per-solver manager subclasses and their hooks are unchanged apart from operating on the backend. ## Type of change - Breaking change. No deprecation shims: removed APIs are listed below with their replacements. ## Migration | Before | Now | |---|---| | `manager.get_model()`, `get_state_0()`, `get_state_1()`, `get_control()`, `get_contacts()` | `manager.backend.model`, `.state_0`, `.state_1`, `.control`, `.contacts` | | `manager._solver`, `_contacts`, `_collision_pipeline`, `_adapter`, `_world_reset_mask`, `_fk_reset_mask`, `kinematics_dirty` | `backend.solver`, `.contacts`, `.collision_pipeline`, `.actuators`, `.world_mask`, `.fk_mask`, `.kinematics_dirty` | | `get_num_envs()`, `get_dt()`, `get_solver_dt()` | `backend.model.world_count`, `backend.dt`, `backend.solver_dt` | | `cl_register_site(...)` | `register_site(...)` | | `add_frame_transform_sensor(...)` | construct `newton.sensors.SensorFrameTransform` on `backend.model` | | `add_contact_sensor` / `add_imu_sensor` returning a key or index | both return the Newton sensor | | private replication fields (`_cl_site_index_map`, `_world_xforms`, `_cl_protos`, ...) | `get_site_index_map()`, `get_world_xforms()`, `get_clone_source_builders()`, `get_clone_record()` | | `from isaaclab_newton.physics.newton_manager_cfg import NewtonBuilderCfg, NewtonBackendCfg` | `from isaaclab_newton.physics import NewtonBuilderCfg, NewtonBackendCfg` | | sensors re-registering sites / `body_qdd` on `STOP` | not needed; requests persist on the builder | ## Testing Every test file in its own process without Isaac Sim (Kit), compared with `main`: no file has more failures or fewer passes, apart from two tests removed with the deprecated accessors. Remaining failures also fail on `main` or need missing extras (Kit launcher tests, rl_games/sb3, `rerun`). Not run: Kit-only tests and the GB300, Rizon coffee and teapot examples. ## 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 changelog fragments --------- Co-authored-by: Maximilian Krause <[email protected]>
ab68d86 to
836cb62
Compare
[Medium impact] The changes affect Newton simulation stepping and query workflows. Restore the viewer’s picking callback after hard resets before merging. Findings
SummaryMoves Newton solver setup, stepping, sensors, and queries into functions that take a
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart LR
M[NewtonManager] -->|lifecycle and step calls| F[Backend functions]
F --> B[NewtonBackend]
B --> S[Solver and contacts]
B --> C[Callbacks and captured step]
Q[Renderers and sensors] -->|queries| F
Reviews (1) · Last reviewed commit: "Move Newton manager logic into backend f..." · Reviewed by Greptile |
| """Run before the actuators of every physics step.""" | ||
| self.post_actuator_callbacks: list[Callable[[], None]] = [] | ||
| """Run after the actuators of every physics step.""" | ||
| self.state_force_callbacks: list[Callable[[State], None]] = [] |
There was a problem hiding this comment.
Moving state_force_callbacks onto each backend drops the Newton viewer’s picking callback after a hard reset. NewtonVisualizer.initialize() registers it only once. On later resets, NewtonVisualizer.reset() binds the viewer to the new model but never registers the callback again. Object dragging therefore stops applying forces after sim.reset().
Re-register the picking callback on the new backend before capturing its first step.
Knowledge Base Used: Newton backend
There was a problem hiding this comment.
Fixed in f1e58ca: NewtonVisualizer.reset() registers picking with the new backend; covered in test_newton_visualizer_hard_reset_rebinds_viewer_model.
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Scope and over-engineering (1), API (1), Compatibility and deprecation (2), Implementation (1), Style consistency (1), Test quality (1). Other reviewed categories look good.
- PR description: The title and body match the 27-file diff, but qualify “code motion” and document pre-finalization callback behavior; no measurable performance claim requires evidence.
- Design and architecture: Architecture looks good.
- Scope and over-engineering: Minimal implementation: keep existing
newton_backend.pyas the model-bound owner andNewtonManageras the builder/site/clone-record lifecycle owner; no source modules were added, and deletegraph_capture_pendingbecause graph and capture state derive it. Scope is cohesive; no split recommended. - API: The documented backend API exposes four internal helpers without external production callers; make them private and document only consumer-facing operations.
- Compatibility and deprecation: Breaking changes: removing public
NewtonQuerieslacks a functional warning shim, migration coverage, and removal window; callback registrars must also preserve pre-finalization registration until backend creation. - Implementation: Relaxed CUDA capture is fixed during solver initialization, so render activation before actual capture is ignored; resolve capture mode when recording the graph.
- Style consistency: Private stepping and capture helpers are interleaved with public functions, contrary to the repository file-order rule; move them below the public API.
- Test quality: The side-by-side backend test protects a distinct contract, but hard-coded
cuda:0breaks CPU-only and masked multi-GPU runs; parameterize it with the repository device utilities.
Significant concerns. Posted 7 inline findings.
Automated review; human maintainers own approval decisions.
| ----------------- | ||
|
|
||
| .. automodule:: isaaclab_newton.physics.newton_backend | ||
| :members: resolve_deterministic_mode, init_solver, allocate_contacts, invalidate_fk, invalidate_body_state, forward, |
There was a problem hiding this comment.
🟡 Warning · Api — Internal helpers promoted to public API
allocate_contacts, notify_model_changes, resolve_deterministic_mode and compile_label_pattern have no caller outside newton_backend.py; publishing them adds compatibility obligations. Keep them private and drop them from the documented member list.
There was a problem hiding this comment.
Fixed: these are now private backend methods/helpers; the docs list only capture_graph besides NewtonBackend.
| "NewtonCloneRecord", | ||
| "NewtonCollisionPipelineCfg", | ||
| "NewtonManager", | ||
| "NewtonQueries", |
There was a problem hiding this comment.
🟡 Warning · Compatibility — NewtonQueries removed without deprecation bridge
NewtonQueries was a public package export; deleting it breaks existing imports immediately. Keep a forwarding shim that emits a deprecation warning and delegates to the newton_backend functions for the prescribed window.
There was a problem hiding this comment.
Intentional: no shims in this series. The removal is marked Breaking with its replacement.
| """Records the step as a CUDA graph, or ``None`` when the step runs eagerly; set by :func:`init_solver`.""" | ||
| self.graph: wp.Graph | None = None | ||
| """Captured step.""" | ||
| self.graph_capture_pending = False |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — graph_capture_pending duplicates derivable state
At the only check the flag equals capture is not None, because step returns early whenever graph exists. Delete the field and test backend.capture, removing four synchronization sites.
There was a problem hiding this comment.
Removed; capture is not None decides capture.
| return backend.graph is not None | ||
|
|
||
|
|
||
| def _simulate_full(backend: NewtonBackend) -> None: |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Private helpers interleaved with public functions
The guide orders a file public functions, public classes, then private ones; _simulate_full, _run_solver_substeps and _paused_gc sit between public functions. Move the private helpers below the public API.
There was a problem hiding this comment.
Fixed: public methods and functions first, private ones last.
| self._initialize_contacts() | ||
| state_0 = backend.state_0 | ||
| self._staged_body_f = wp.zeros_like(state_0.body_f) if state_0.body_count else None | ||
| relaxed = sim is not None and has_kit() and (sim.has_gui or sim.has_offscreen_render) |
There was a problem hiding this comment.
🟡 Warning · Implementation — Relaxed capture frozen at solver init
relaxed is resolved at init instead of at capture time, so a renderer enabled afterwards records THREAD_LOCAL; the mjwarp_rtx case sets _has_offscreen_render after reset and no longer covers relaxed capture.
There was a problem hiding this comment.
Fixed: relaxed mode is resolved when the step is captured.
| Hard resets discard these hooks; register them again when the new model is ready. | ||
| """ | ||
| self._pre_actuator_callbacks.append(callback) | ||
| self.backend.pre_actuator_callbacks.append(callback) |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Callback registration requires a live backend
These registrars dereference self.backend unguarded, so registering before start_simulation now raises AttributeError where the manager-owned lists accepted it; unregister_post_step_callback and set_decimation still guard. Guard consistently.
There was a problem hiding this comment.
Intentional: every registrar runs after the backend exists (they read the model); registration before the first reset isn't supported.
|
|
||
| from isaaclab.sim import SimulationContext | ||
|
|
||
| DEVICE = "cuda:0" |
There was a problem hiding this comment.
🟡 Warning · Test Quality — New test hard-codes CUDA device
Module-level DEVICE = "cuda:0" errors on CPU-only runners and ignores the multi-GPU runtime mask. Parametrize with test_devices(DeviceScope.CUDA) and thread the device through the helpers, as sibling Newton tests do.
There was a problem hiding this comment.
Fixed: parametrized with test_devices(DeviceScope.CUDA).
maxkra15
left a comment
There was a problem hiding this comment.
The ownership split looks good to me. Left two comments on particle-only queries and the standalone MPM path that I'd like us to fix before merging.
| self._refit_bvh() | ||
| return | ||
| state = self.state_0 | ||
| pointers = state.body_q.ptr, 0 if state.particle_q is None else state.particle_q.ptr |
There was a problem hiding this comment.
Can we keep the None check for body_q here? Newton leaves it as None for a particle-only model, so this now raises AttributeError with CUDA graphs enabled. The old helper used 0 for a missing array. Same thing in the renderer and ray caster, so those need updating too. A small case without rigid bodies would catch this.
There was a problem hiding this comment.
Fixed in c63c908: NewtonBackend.state_pointers() uses 0 for a missing array, shared by the refit, renderer and ray caster; covered by test_bvh_refit_captures_a_model_without_rigid_bodies.
| simulate = self._simulate_physics_only | ||
| if self.graph is not None: | ||
| wp.capture_launch(self.graph) | ||
| return True |
There was a problem hiding this comment.
Should check_step move into the backend too? It only runs from NewtonManager.step() at the moment, so calling backend.step() directly skips the sparse MPM error check after graph replay. I checked with an injected overflow status: the step returns fine, then the normal checker raises. I'd put the check here and remove it from the manager so we don't sync twice.
There was a problem hiding this comment.
Fixed in c63c908: backend.step() runs check_step after the launch and the manager no longer calls it.
|
run-ci |
| # ----- Reset-mask kernels ---------------------------------------------------------------- | ||
|
|
||
|
|
||
| @wp.kernel(enable_backward=False) | ||
| def _flag_worlds_and_articulations_masked( | ||
| env_mask: wp.array(dtype=wp.bool), | ||
| articulation_ids: wp.array2d(dtype=wp.int32), | ||
| world_mask: wp.array(dtype=wp.bool), | ||
| fk_mask: wp.array(dtype=wp.bool), | ||
| ): | ||
| """Flag each masked world for a solver reset and its articulations for FK.""" | ||
| world, articulation = wp.tid() | ||
| if env_mask[world]: | ||
| world_mask[world] = True | ||
| fk_mask[articulation_ids[world, articulation]] = True | ||
|
|
||
|
|
||
| @wp.kernel(enable_backward=False) | ||
| def _flag_worlds_and_articulations_indexed( | ||
| env_ids: wp.array(dtype=Any), | ||
| articulation_ids: wp.array2d(dtype=wp.int32), | ||
| world_mask: wp.array(dtype=wp.bool), | ||
| fk_mask: wp.array(dtype=wp.bool), | ||
| ): | ||
| """Flag each selected world for a solver reset and its articulations for FK.""" | ||
| i, articulation = wp.tid() | ||
| world = wp.int32(env_ids[i]) | ||
| world_mask[world] = True | ||
| fk_mask[articulation_ids[world, articulation]] = True | ||
|
|
||
|
|
||
| @wp.kernel(enable_backward=False) | ||
| def _flag_worlds_masked(env_mask: wp.array(dtype=wp.bool), world_mask: wp.array(dtype=wp.bool)): | ||
| """Flag each masked world for a solver reset.""" | ||
| world = wp.tid() | ||
| if env_mask[world]: | ||
| world_mask[world] = True | ||
|
|
||
|
|
||
| @wp.kernel(enable_backward=False) | ||
| def _flag_worlds_indexed(env_ids: wp.array(dtype=Any), world_mask: wp.array(dtype=wp.bool)): | ||
| """Flag each selected world for a solver reset.""" | ||
| world_mask[wp.int32(env_ids[wp.tid()])] = True |
There was a problem hiding this comment.
Should we consider moving those to a utility file?
c63c908 to
c30f8ae
Compare
|
run-ci |
# Description Part 2c-ii of the Newton manager redesign ([overview](#8218 (comment))). Follows [2c/N] #8735 (merged). The test overhaul is [2c-iii/N] #8884. ## Reset and FK flags are mask-only `NewtonBackend.invalidate_fk(env_mask, articulation_ids, *, articulation_mask, consume_mask)` and `invalidate_body_state(env_mask, *, consume_mask)` select worlds and articulations with boolean masks only. The flag kernels run one thread per world and take no index selectors, so their launch shape is fixed and any write made through a `_mask` writer can be recorded into a CUDA graph. Resets still call the `_index` writers until mask-based environment resets land. The FK flag kernel is specialized per view with `wp.static` on its articulation count and on whether an articulation mask is given, so it handles no optional arrays at run time. The id-indexed kernels and their dtype dispatch are removed. - **Breaking:** `NewtonManager.invalidate_fk` and `invalidate_body_state` (and the backend methods) no longer take `env_ids`. Pass a boolean `env_mask`, and `articulation_mask` to select view-local articulations. ## Index writes convert ids at the asset boundary Asset `*_index` writes (articulation root and joint state, rigid object root state, rigid object collection body state, cable segments) flag their ids into a per-asset scratch mask with one small kernel and pass that mask on. The backend clears each entry as it reads it (`consume_mask=True`), so the mask starts empty for the next write without a memset. Writes over all environments pass the asset's all-true mask. Collections also flag `body_ids` into a scratch object mask, zeroed after the call when a subset of objects was written. The assets share one `mask_from_ids` helper. ## Asset state writes - Rigid object collection writes use separate index and mask kernels. The mask kernels take only masks and full data, so the index path can later be removed without touching them. - Asset writers flag the backend once per write. The data classes' `_reset_pose` / `_reset_velocity` invalidate only derived caches. - Obtaining write destinations no longer refreshes derived state. ## Deprecated joint-state index writer `Articulation.write_joint_state_to_sim_index` (Newton, PhysX, OVPhysX) emits a `DeprecationWarning`. Use `write_joint_state_to_sim_mask`, or `write_joint_position_to_sim_index` and `write_joint_velocity_to_sim_index`. The lift, locomotion, Franka pour, Rizon coffee and UR10 particle-push resets move to the position and velocity writers. ## Performance RTX PRO 6000 Blackwell, Warp 1.17.0, `main` at `c498443e0`. Environment throughput from `isaaclab benchmark runtime --task <task> --num_envs 4096 --num_steps 1000 --warmup_steps 100 --visualizer none physics=newton_mjwarp`, two alternating sequential rounds after a warm-up run (steps/s): | Task | `main` | this PR | change | |---|---|---|---| | Cartpole (reset-heavy) | 2.67M | 2.63M | −1.4% | | Flat ANYmal-D | 254.3k | 254.7k | +0.2% | Per-call cost of articulation writes, 4096 envs, CUDA, three alternating rounds (host-bound; µs): | Write | `main` | this PR | |---|---|---| | `write_joint_state_to_sim_index` | 61.6 | 57.9 | | `write_joint_position_to_sim_index` | 59.1 | 55.0 | | `write_root_link_pose_to_sim_index` | 71.3 | 78.8 | | `write_root_link_pose_to_sim_mask` | 52.5 | 52.8 | | `write_joint_state_to_sim_mask` | 42.6 | 33.6 | The ids→mask launch adds about 5.5 µs to each `_index` write; root pose index writes are about 7.5 µs slower than on `main`, and reset-heavy Cartpole, which makes four `_index` writes per reset, is 1.4% slower. Mask-based environment resets (a later stage) move resets onto the `_mask` writers. ## Testing Targeted tests pass, run file by file: Newton manager abstraction, two backends, visualization state, articulation and rigid object contracts (all backends), articulation, rigid object and collections, cable, joint coordinates, Newton actuators, MDP events, lift environment config and Warp event capture safety. ## 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 changelog fragments
Description
Part 2c of the Newton manager redesign (overview).
Builds on [2a/N] #8733 and [2b/N] #8734 (both merged).
Summary
NewtonManager's step, reset and contact logic moves ontoNewtonBackend. A backend now holds everything onemodel's step needs and the methods that run it, so backends with different solvers can be built and stepped side by
side without a manager or simulation context:
Why:
outer-capture flag and the captured graph live on the backend, so they are discarded with the model instead of
being cleared by hand in the manager.
test_two_backends.py: MJWarp andFeatherstone stepped side by side, eager and captured, with reset masks isolated per backend).
The manager keeps what outlives a model (builder, sites, clone record, decimation) and scene-data timestamps. Solver
behavior goes through
solver_cfg.class_typeas in 2b. Behavior is unchanged, including the solver-init callback andinitial-FK order.
NewtonQueries.run_querycombined a shared BVH refit with each consumer's query capture. It is split: the shared partis
backend.refit_bvh(timestamp), and the renderer and ray caster capture their own query, as the frame transformeralready did.
The Newton viewer now registers its picking forces with each new backend on a hard reset, since state-force callbacks
belong to the backend.
Breaking changes
NewtonQueries.run_querybackend.refit_bvh(timestamp), then capture the query withnewton_backend.capture_graphNewtonQueries.capture_graph,._refit_bvhnewton_backend.capture_graph,backend.refit_bvhNewtonManager.transforms_may_change_on_graph_replayNewtonBackend.transforms_may_change_on_graph_replay_simulate_full,_graph,_post_step_callbacks, ...)backend.step(),backend.graph,backend.post_step_callbacks, ...Performance
isaaclab benchmark runtime, 4096 envs,physics=newton_mjwarp, 1000 steps, warm kernel cache, run sequentially:Testing
Targeted tests pass, run file by file: manager abstraction (106), two backends (3), Newton visualizer adapter, VBD core, MJWarp tendon control,
MPM reset masks and object, coupler, coupler runtime, custom coupling, visualization state, articulation (incl.
contract
-k newton), joint coordinates, Newton actuators, BAM actuator, contact sensor, frame transformer, raycaster, IMU, cloner. Tests that need Isaac Sim (renderers, deformable object,
test_newton_solver_reset) were not runlocally.
Checklist
pre-commitchecks with./isaaclab.sh --format