Repository navigation
Clear MJWarp solver internals on env reset - #5730
Conversation
There was a problem hiding this comment.
Review Summary
This PR correctly addresses a critical NaN propagation bug in MJWarp solver state. The implementation is well-structured and follows Isaac Lab's existing patterns.
✅ What Looks Good
-
Clean Hook Pattern: The
_reset_solver_internalshook allows each solver subclass to clear its internal state without modifying the base class behavior. Default no-op is appropriate. -
Correct Execution Order: Placing the reset at the top of
step()before model changes and FK evaluation matches Kamino's existing "reset-first" contract. The mask is properly consumed then cleared. -
Dtype Change Rationale: Switching
_world_reset_maskfromwp.int32towp.boolis justified since MJWarp'sreset_datarequires bool, and Kamino's int32 requirement is handled via a dedicated mirror buffer. -
Thorough Documentation: The changelog entry and docstrings clearly explain the problem, solution, and upstream tracking issues.
-
Kamino Compatibility: The
_convert_bool_mask_to_int32kernel properly handles the dtype mismatch with good comments explaining why view casting doesn't work.
💬 Suggestions (Non-blocking)
-
Test Coverage: The PR description mentions not adding a NaN-injection regression test. While the Cartpole smoke tests provide behavioral validation, a targeted test that:
- Injects a NaN into one world's solver state
- Triggers env reset
- Verifies the world recovers on the next step
Would be valuable for preventing future regressions, especially given this is a subtle state-leakage bug. Consider adding this in a follow-up if not in this PR.
-
Minor - Import Organization: In
mjwarp_manager.py, the newmujoco_warpimport could be grouped with other external imports for consistency (currently it appears to be alphabetically placed, which is fine). -
Future Cleanup Note: The PR description mentions potentially migrating Kamino's inline
solver.reset(world_mask=...)to use the new hook. This would unify the reset contract across all solvers. Consider adding a TODO comment or tracking issue for this.
Questions
-
CUDA Graph Compatibility: The new
_reset_solver_internalscall happens before graph capture check. Ismujoco_warp.reset_dataCUDA-graph-compatible, or does the conditional mask create graph-capture issues? The existing Kamino reset has similar structure, so this is likely fine, but worth confirming. -
First Step After
start_simulation: On the very firststep()after simulation starts, the mask is all-zeros. Thereset_datacall would be a no-op (no worlds flagged), correct? Just confirming the semantics are as intended.
Verdict: The fix is correct and addresses a real NaN-recovery gap. The implementation is clean and well-documented. Approve with optional test coverage enhancement.
Update (9a68923): ✅ Good improvements in this push:
-
Noneguard added to_reset_solver_internals— Defensive check prevents accidental full-reset whenworld_maskisNone. The docstring clearly explains themujoco_warp.reset_databehavior that makes this necessary. -
Docstring update in
newton_manager.py— Now correctly lists_reset_solver_internalsas an overridable hook.
No new concerns. Previous review stands.
Update (10f46062): ✅ Excellent refinements:
-
Deferred
mujoco_warpimport — Moved inside_reset_solver_internalsso docs builds (which don't install mujoco_warp) can still autodoc the module. Good defensive pattern. -
Cross-device mask bridging — New
_mjwarp_reset_maskclass attribute handles the edge case where_world_reset_maskis on CPU butmjw_datalives oncuda:0(typical for CPU-pinned sims sincemujoco_warp.put_dataalways lands on Warp's default device). The lazy allocation and device check logic is correct. -
_solver_specific_clearimplementation — Properly releases the mirror buffer, preventing memory leaks across simulation restarts.
This resolves my earlier import organization suggestion (now moot with deferred import). No new concerns. LGTM!
Update (e967a159): This commit is a merge from develop — no changes to the actual MJWarp/Newton physics code since last review. Previous LGTM stands.
Update (dd183fe6): Merge commit from develop branch. The diff contains extensive changes to unrelated areas (pyproject.toml modernization, visualizer tests, sensor stale-data fixes, etc.), but no modifications to the MJWarp solver reset logic that this PR introduces. Previous approval stands.
Re-review triggered 2026-05-28: Verified head commit dd183fe6 against develop merge. No new changes to the PR's core MJWarp reset logic. Review remains current.
Update (33517a0e): Good refinements in this commit:
-
wp.ScopedDevicewrapper — Thereset_datacall is now wrapped inwith wp.ScopedDevice(target_device)ensuring the kernel launches on the correct device regardless of Warp's current default. More robust than relying on implicit device selection. -
Device detection via
xfrc_applied— Changed fromqpos.devicetoxfrc_applied.devicefor determining the target device. This aligns with the field thatreset_dataactually zeroes. -
Docstring/comment cleanup — Updated documentation to accurately describe the new
ScopedDevice-based approach.
No new concerns. LGTM!---
Update (cca3053): New commits are a large merge from main (50+ PRs) plus removal of ls_parallel from MJWarp solver documentation. The mjwarp_manager.py file containing the reset logic was not modified in these commits. No new issues introduced in the PR-specific changes. Previous approval stands.
Greptile SummaryThis PR wires
Confidence Score: 4/5Safe to merge. The change is well-scoped and correctly addresses the NaN-recovery gap in MJWarp; the qpos/qvel overwrite by reset_data is immediately overwritten by the solver's own sync, so reset poses are unaffected. The core fix is straightforward and the logic is sound. The only notable gap is that Pay closest attention to Important Files Changed
Sequence DiagramsequenceDiagram
participant Env as ManagerBasedEnv
participant NM as NewtonManager.step()
participant MJW as NewtonMJWarpManager._reset_solver_internals()
participant MW as mujoco_warp.reset_data()
participant Solver as SolverMuJoCo.step()
Env->>NM: "invalidate_fk(env_ids) sets _world_reset_mask[i]=True"
Env->>NM: step()
NM->>MJW: _reset_solver_internals(_world_reset_mask)
MJW->>MW: "reset_data(mjw_model, mjw_data, reset=mask)"
MW-->>MJW: clears qacc_warmstart, qfrc_applied, xfrc_applied, qacc, contacts
MJW-->>NM: return
NM->>NM: eval_fk (masked FK for reset worlds)
NM->>NM: _world_reset_mask.zero_()
NM->>Solver: solver.step() x num_substeps
Solver-->>NM: re-syncs qpos/qvel from state.joint_q/joint_qd
|
| world_mask: Per-world bool mask of shape ``(world_count,)``; | ||
| ``True`` for worlds that need their MJWarp internals cleared. | ||
| """ | ||
| mujoco_warp.reset_data(cls._solver.mjw_model, cls._solver.mjw_data, reset=world_mask) |
There was a problem hiding this comment.
Missing
None guard before forwarding world_mask to mujoco_warp.reset_data. The parallel _forward_kamino in kamino_manager.py explicitly handles world_mask is None by passing solver_mask = None to the solver. Here, if world_mask is None (possible before start_simulation completes or in test contexts), mujoco_warp.reset_data(reset=None) could silently reset every world in the model rather than nothing — an incorrect, hard-to-diagnose mass state wipe.
| mujoco_warp.reset_data(cls._solver.mjw_model, cls._solver.mjw_data, reset=world_mask) | |
| if world_mask is None: | |
| return | |
| mujoco_warp.reset_data(cls._solver.mjw_model, cls._solver.mjw_data, reset=world_mask) |
|
cc @mmichelis @jumyungc — would love your input on a VBD-side follow-up. While reviewing this PR (bot pinged the asymmetry between solvers), I audited Buffers in
There's also a smoking-gun comment at L636 that hints the authors already considered this:
… but that's a user-facing note — there's no public method on For comparison, this PR fixes the same flavor of bug on the MJWarp side by calling Questions for you:
Not blocking this PR — happy to keep it scoped to MJWarp and follow up with whatever you recommend. |
| # ``reset_data`` kernels launch on ``cuda:0``; this mirror bridges that | ||
| # gap. Lazily allocated in :meth:`_reset_solver_internals` and released | ||
| # via :meth:`_solver_specific_clear`. | ||
| _mjwarp_reset_mask: wp.array | None = None |
There was a problem hiding this comment.
Is this expected behavior from mujoco_warp.put_data? Since a fix there could remove this need to mirror cpu-cuda device world masks.
| # call mujoco_warp.reset_data so NaNs cannot leak through env reset (see newton#1266). | ||
| # Fires at the top of step() to match NewtonKaminoManager.step()'s ordering — keeping | ||
| # the contract uniform "solver-specific reset is the first thing every step does." | ||
| cls._reset_solver_internals(cls._world_reset_mask) |
There was a problem hiding this comment.
Is this the correct location to call the internal reset? From the comment of Miguel on the newton issue, it seems the mjwarp reset data is called during the sim reset in mjlab. In RL environments we have the reset_idx call scene resets, could we potentially also call a sim.reset which does the specific solver resets.
Thanks for the in-depth check! Personally, I think a SolverVBD reset makes the most sense, given the amount of solver-specific parameters that need to be properly reset. I think |
Ok, so the current form of the PR is correct, and that's something you'll be able to leverage? @mmichelis |
33517a0 to
cca3053
Compare
@AntoineRichard I would say the form is correct and usable for the resets that I want to do, but I'm still questioning if it wouldn't make more sense that this is done on the newton side, since these are solver specific clears, and ideally maintained by whoever is implementing the newton solvers. |
cca3053 to
9cab5c8
Compare
MJWarp's per-world warm-start (qacc_warmstart), accumulated forces (qfrc_applied, xfrc_applied), qacc, contact arrays, energy, and solver counters were retained across IsaacLab env reset. A NaN that surfaced in one solve warm-started the next iteration, so any world that went NaN stayed dead. NewtonMJWarpManager now calls mujoco_warp.reset_data() at the top of step() with the accumulated per-world reset mask via a new NewtonManager._reset_solver_internals hook. The mask is switched from wp.int32 to wp.bool so it can feed mujoco_warp.reset_data (which strictly requires wp.array[bool]) zero conversion. NewtonKaminoManager mirrors it into a Kamino-side int32 buffer each step because the upstream Kamino kernels are declared wp.array[int32] despite SolverKamino.reset's docstring advertising wp.int8 | wp.bool — tracked at newton-physics/newton#2932. The mirror can be removed once that lands. See newton-physics/newton#1266 for the upstream NaN-recovery discussion; this is the workaround until SolverMuJoCo.reset lands in newton#2657.
mujoco_warp.reset_data(reset=None) short-circuits its per-world wp.static(reset is not None) guard and resets every world to model defaults. The mask is non-None in the normal lifecycle, but an unusual call sequence (e.g. invocation between NewtonManager.clear and the next start_simulation) would silently nuke all sims. Defensive early-return matches the asymmetry greptile flagged with the Kamino path, which already handles the None case explicitly. Also list _reset_solver_internals in NewtonManager's class docstring alongside the other subclass-extendable hooks so future solver implementers can discover it.
isaaclab_newton CI failed every CPU-parameterized contact-sensor test with "trying to launch on device='cuda:0', but input array for argument 'reset_in' is on device=cpu". Cause: NewtonManager._world_reset_mask is allocated on PhysicsManager._device (e.g. cpu in tests pinned to cpu), but mujoco_warp.put_data always lands on Warp's default device (cuda:0 on hosts with CUDA available) regardless of the Newton model's device. The reset_data kernels then launch on cuda:0 and reject the cpu mask. NewtonMJWarpManager now keeps a persistent _mjwarp_reset_mask co-located with mjw_data, populated via wp.copy from the base mask only when the two arrays live on different devices. _solver_specific_clear releases it on teardown. Also defer the `import mujoco_warp` to inside _reset_solver_internals so the Sphinx docs build, which does not install mujoco_warp, can still autodoc NewtonMJWarpManager. Without the deferral, the module-level import raised ModuleNotFoundError during doc builds and Build Latest Docs failed with "autodoc: failed to import class 'NewtonMJWarpManager'".
Scope mujoco_warp.reset_data to the MJWarp data device so CPU-pinned Newton tests do not inherit Warp's default CUDA launch device. Keep the reset mask mirror for cases where the mask and solver data live on different devices.
Update the Newton dependency pins to the latest upstream commit and drop the obsolete Kamino reset-mask int32 mirror now that latest Newton accepts the shared bool mask.
Newton's SolverBase.reset API (newton#2657) landed in the commit develop already pins, so replace the direct mujoco_warp.reset_data workaround with solver.reset(state, world_mask, flags=0). flags=0 clears only the solver-owned buffers (qacc_warmstart, qfrc_applied, xfrc_applied, ctrl, act) and preserves the joint state IsaacLab authored during the reset. Upstream launches on the model device and validates the mask, so the on-device mask mirror and ScopedDevice handling are no longer needed. Also invoke the hook from forward(): it consumes (zeroes) the same masks step() reads, so a data-read-triggered forward() between an env reset and the next step would otherwise discard the reset selection before the solver internals were ever cleared. Gate the CPU-MuJoCo path on a non-empty mask: its reset branch owns a single global MjData and is not mask-aware, and the hook fires on every boundary with a usually-empty mask.
Two-env MJWarp test poisons qacc_warmstart, authors a joint write for one env, and verifies both public boundaries (sim.forward and sim.step) clear the flagged world's history while preserving the other world's history and the authored joint state. Fails when the _reset_solver_internals override is disabled.
Move the SolverBase.reset(flags=0) call into the base _reset_solver_internals hook so any solver that implements the upstream reset API (currently MuJoCo; VBD or others if they add one) is covered automatically. SolverBase.reset is a documented no-op, so solvers without an override are unaffected. MJWarp's override shrinks to the CPU-MuJoCo gating and delegates to the base; Kamino opts out since its FK delegate already performs the masked SolverKamino.reset with an explicit ResetConfig. Also move the regression test from test_articulation.py to test/physics/test_newton_solver_reset.py: the articulation suite is solver-agnostic and the test is MJWarp-specific.
0744b24 to
ac10be7
Compare
Re-sync onto latest develop (adds isaac-sim#6431 rendering-test timeout bump, isaac-sim#5730, isaac-sim#6363, OVPhysX test enablement). Keep device_scope test_devices() migration in test_rigid_object.py over develop's cpu/cuda:0 list.
# Description Clears per-world solver-internal buffers on env reset via Newton's solver-reset API — closing the NaN-recovery gap discussed in [newton-physics/newton#1266](newton-physics/newton#1266). Without this, a world that produces a NaN in one solve warm-starts the next iteration from that NaN (MJWarp leaves `mj_checkPos` / `mj_checkVel` / `mj_checkAcc` as TODOs, so nothing in the solver cleans it up). IsaacLab's standard reset rewrites `joint_q` / `joint_qd` / `body_q` but never touches MJWarp-internal `qacc_warmstart`, applied forces, or activations — the world is permanently dead. ## What changed * New `NewtonManager._reset_solver_internals(world_mask)` hook, invoked at **both** boundaries that consume the accumulated reset masks, immediately before the masks are zeroed: the top of `step()` and `forward()`. The `forward()` call site matters because data reads may trigger `forward()` between an env reset and the next `step()`, which would otherwise consume the mask before the solver internals were ever cleared. * The **base implementation is solver-agnostic**: it forwards to `SolverBase.reset(state, world_mask=..., flags=0)` — the upstream API from [newton-physics/newton#2657](newton-physics/newton#2657), available at the Newton commit `develop` already pins. `flags=0` clears only solver-owned buffers and preserves the joint state IsaacLab authored during the reset. `SolverBase.reset` is a documented no-op, so solvers that do not implement it (VBD, XPBD, Featherstone, MPM today) are unaffected — and any solver that adds a `reset()` upstream is covered automatically with no IsaacLab change. * `NewtonMJWarpManager` specializes the hook only to gate the CPU-MuJoCo path (`use_mujoco_cpu=True`): its reset branch owns a single global `MjData` and is not mask-aware, and the hook fires on every boundary with a usually-all-`False` mask. For MJWarp, `SolverMuJoCo.reset(flags=0)` zeroes `qacc_warmstart`, `qfrc_applied`, `xfrc_applied`, `ctrl`, `act` per masked world. * `NewtonKaminoManager` opts out with a documented no-op override — its FK delegate already performs the masked `SolverKamino.reset` with an explicit `ResetConfig` at the same boundaries, so the generic call would be a redundant second reset. ## Type of change * Bug fix (non-breaking change which fixes an issue) ## Screenshots N/A — physics behavior fix, no UI. ## 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 updated the changelog and the corresponding version in the extension's `config/extension.toml` file - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there ## Test plan * New regression test `source/isaaclab_newton/test/physics/test_newton_solver_reset.py` (2 envs, CUDA): poisons `qacc_warmstart`, authors a joint write for one env, and verifies both public boundaries (`sim.forward()` and `sim.step()`) clear the flagged world's history while preserving the other world's history and the authored joint state. Verified to fail with the reset disabled. * `source/isaaclab_newton/test/physics/test_newton_manager_abstraction.py` passes (74 tests). * Canonical training probes run to completion with no tracebacks: * `./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-Direct --num_envs 16 presets=newton_mjwarp --max_iterations 5` * `./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-Direct --num_envs 16 presets=newton_kamino --max_iterations 5`
Description
Clears per-world solver-internal buffers on env reset via Newton's solver-reset API — closing the NaN-recovery gap discussed in newton-physics/newton#1266.
Without this, a world that produces a NaN in one solve warm-starts the next iteration from that NaN (MJWarp leaves
mj_checkPos/mj_checkVel/mj_checkAccas TODOs, so nothing in the solver cleans it up). IsaacLab's standard reset rewritesjoint_q/joint_qd/body_qbut never touches MJWarp-internalqacc_warmstart, applied forces, or activations — the world is permanently dead.What changed
NewtonManager._reset_solver_internals(world_mask)hook, invoked at both boundaries that consume the accumulated reset masks, immediately before the masks are zeroed: the top ofstep()andforward(). Theforward()call site matters because data reads may triggerforward()between an env reset and the nextstep(), which would otherwise consume the mask before the solver internals were ever cleared.SolverBase.reset(state, world_mask=..., flags=0)— the upstream API from newton-physics/newton#2657, available at the Newton commitdevelopalready pins.flags=0clears only solver-owned buffers and preserves the joint state IsaacLab authored during the reset.SolverBase.resetis a documented no-op, so solvers that do not implement it (VBD, XPBD, Featherstone, MPM today) are unaffected — and any solver that adds areset()upstream is covered automatically with no IsaacLab change.NewtonMJWarpManagerspecializes the hook only to gate the CPU-MuJoCo path (use_mujoco_cpu=True): its reset branch owns a single globalMjDataand is not mask-aware, and the hook fires on every boundary with a usually-all-Falsemask. For MJWarp,SolverMuJoCo.reset(flags=0)zeroesqacc_warmstart,qfrc_applied,xfrc_applied,ctrl,actper masked world.NewtonKaminoManageropts out with a documented no-op override — its FK delegate already performs the maskedSolverKamino.resetwith an explicitResetConfigat the same boundaries, so the generic call would be a redundant second reset.Type of change
Screenshots
N/A — physics behavior fix, no UI.
Checklist
pre-commitchecks with./isaaclab.sh --formatconfig/extension.tomlfileCONTRIBUTORS.mdor my name already exists thereTest plan
source/isaaclab_newton/test/physics/test_newton_solver_reset.py(2 envs, CUDA): poisonsqacc_warmstart, authors a joint write for one env, and verifies both public boundaries (sim.forward()andsim.step()) clear the flagged world's history while preserving the other world's history and the authored joint state. Verified to fail with the reset disabled.source/isaaclab_newton/test/physics/test_newton_manager_abstraction.pypasses (74 tests)../isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-Direct --num_envs 16 presets=newton_mjwarp --max_iterations 5./isaaclab.sh train --rl_library rsl_rl --task Isaac-Cartpole-Direct --num_envs 16 presets=newton_kamino --max_iterations 5