Skip to content

Clear MJWarp solver internals on env reset - #5730

Merged
AntoineRichard merged 9 commits into
isaac-sim:developfrom
AntoineRichard:antoiner/mjwarp-reset-data
Jul 8, 2026
Merged

AntoineRichard merged 9 commits into
isaac-sim:developfrom
AntoineRichard:antoiner/mjwarp-reset-data

Conversation

@AntoineRichard

@AntoineRichard AntoineRichard commented May 21, 2026 •

Copy link
Copy Markdown
Collaborator

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_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, 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

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with ./isaaclab.sh --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the changelog and the corresponding version in the extension's config/extension.toml file
  • 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

@github-actions github-actions Bot added the isaac-lab Related to Isaac Lab team label May 21, 2026

@isaaclab-review-bot isaaclab-review-bot Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

  1. Clean Hook Pattern: The _reset_solver_internals hook allows each solver subclass to clear its internal state without modifying the base class behavior. Default no-op is appropriate.

  2. 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.

  3. Dtype Change Rationale: Switching _world_reset_mask from wp.int32 to wp.bool is justified since MJWarp's reset_data requires bool, and Kamino's int32 requirement is handled via a dedicated mirror buffer.

  4. Thorough Documentation: The changelog entry and docstrings clearly explain the problem, solution, and upstream tracking issues.

  5. Kamino Compatibility: The _convert_bool_mask_to_int32 kernel properly handles the dtype mismatch with good comments explaining why view casting doesn't work.

💬 Suggestions (Non-blocking)

  1. 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.

  2. Minor - Import Organization: In mjwarp_manager.py, the new mujoco_warp import could be grouped with other external imports for consistency (currently it appears to be alphabetically placed, which is fine).

  3. 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

  1. CUDA Graph Compatibility: The new _reset_solver_internals call happens before graph capture check. Is mujoco_warp.reset_data CUDA-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.

  2. First Step After start_simulation: On the very first step() after simulation starts, the mask is all-zeros. The reset_data call 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:

  1. None guard added to _reset_solver_internals — Defensive check prevents accidental full-reset when world_mask is None. The docstring clearly explains the mujoco_warp.reset_data behavior that makes this necessary.

  2. Docstring update in newton_manager.py — Now correctly lists _reset_solver_internals as an overridable hook.

No new concerns. Previous review stands.


Update (10f46062): ✅ Excellent refinements:

  1. Deferred mujoco_warp import — Moved inside _reset_solver_internals so docs builds (which don't install mujoco_warp) can still autodoc the module. Good defensive pattern.

  2. Cross-device mask bridging — New _mjwarp_reset_mask class attribute handles the edge case where _world_reset_mask is on CPU but mjw_data lives on cuda:0 (typical for CPU-pinned sims since mujoco_warp.put_data always lands on Warp's default device). The lazy allocation and device check logic is correct.

  3. _solver_specific_clear implementation — 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:

  1. wp.ScopedDevice wrapper — The reset_data call is now wrapped in with 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.

  2. Device detection via xfrc_applied — Changed from qpos.device to xfrc_applied.device for determining the target device. This aligns with the field that reset_data actually zeroes.

  3. 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-apps

greptile-apps Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR wires mujoco_warp.reset_data into IsaacLab's MJWarp physics manager so that solver-internal scratch buffers (qacc_warmstart, qfrc_applied, xfrc_applied, contact arrays, etc.) are cleared for reset worlds at the start of every step(), preventing NaN values produced in one solve from poisoning the next.

  • Introduces a new NewtonManager._reset_solver_internals(world_mask) hook (no-op default) called unconditionally at the top of the base step(), keeping a uniform "reset-first" contract across solvers; NewtonMJWarpManager overrides it to call mujoco_warp.reset_data.
  • Changes _world_reset_mask dtype from wp.int32 to wp.bool (required by mujoco_warp.reset_data); adds a _convert_bool_mask_to_int32 Warp kernel and _world_reset_mask_int32 mirror in NewtonKaminoManager to satisfy Kamino's strict wp.array[int32] mask-consumer kernels.
  • Adds NewtonKaminoManager._solver_specific_clear to release the new int32 mirror buffer on teardown.

Confidence Score: 4/5

Safe 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 NewtonMJWarpManager._reset_solver_internals passes world_mask straight to mujoco_warp.reset_data without a None guard, while the analogous Kamino path explicitly handles None. Although the normal lifecycle makes world_mask reliably non-None by the time step() is called, the inconsistency could cause a silent full-world reset in unusual call sequences. The class docstring also omits the new hook from its list of overridable methods. Both findings are minor and non-blocking.

Pay closest attention to mjwarp_manager.py — specifically whether mujoco_warp.reset_data(reset=None) is truly a no-op or resets all worlds, which determines the impact of the missing guard.

Important Files Changed

Filename Overview
source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py Changed _world_reset_mask dtype from wp.int32 to wp.bool; added _reset_solver_internals hook called at top of every step(); mask write-sites updated accordingly. The hook is invoked unconditionally without a None guard before passing the mask to subclass implementations.
source/isaaclab_newton/isaaclab_newton/physics/mjwarp_manager.py New _reset_solver_internals override calls mujoco_warp.reset_data with the per-world bool mask each step; correctly clears warm-start / accumulated-force buffers for reset worlds. Lacks the None-mask guard that the parallel Kamino path has in _forward_kamino.
source/isaaclab_newton/isaaclab_newton/physics/kamino_manager.py Adds _convert_bool_mask_to_int32 Warp kernel and _world_reset_mask_int32 mirror buffer so the new wp.bool base mask can be forwarded to Kamino's strict wp.array[int32] APIs; adds _solver_specific_clear to release the mirror. Logic is consistent with existing patterns.
source/isaaclab_newton/changelog.d/antoiner-mjwarp-reset-data.rst New changelog fragment documenting the NaN-recovery fix and the dtype change; accurate and complete.

Sequence Diagram

sequenceDiagram
    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
Loading

Comments Outside Diff (1)

  1. source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py, line 179-181 (link)

    P2 The NewtonManager class docstring enumerates the hooks that subclasses may extend, but the newly added _reset_solver_internals is omitted, leaving it undiscoverable for future solver implementers. Anyone adding a third solver won't know to override this hook to clear their own warm-start buffers.

Reviews (1): Last reviewed commit: "Clear MJWarp solver internals on env res..." | Re-trigger Greptile

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)

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 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.

Suggested change
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)

@kellyguo11 kellyguo11 moved this to In review in Isaac Lab May 21, 2026
@AntoineRichard

Copy link
Copy Markdown
Collaborator Author

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 SolverVBD to see whether the new _reset_solver_internals hook should be plumbed there too. Findings: VBD carries a non-trivial pile of per-world / per-body / per-joint state that survives IsaacLab's standard env reset, because env reset only writes joint_q / joint_qd / body_q and never touches solver internals.

Buffers in solver_vbd.py that look like they'd benefit from a per-world clear on env.reset(env_ids):

Buffer Where Why stale data matters
body_q_prev L637 Friction tangential displacement reads this; post-teleport it points at the pre-reset pose so friction sees a "jump" worth of velocity
particle_q_prev L465 Same problem for cloth/deformable verts
pos_prev_collision_detection L535 Drives accumulated-displacement collision retrigger; stale = missed / duplicated collisions
joint_lambda_lin / joint_lambda_ang L698-699 Augmented-Lagrangian state (hard mode)
joint_C0_lin / joint_C0_ang L700-701 Hard-mode constraint snapshot
joint_sigma_prev / joint_kappa_prev / joint_dkappa_prev L704-706 Dahl friction state — the code comment explicitly notes "persistent across timesteps"
_prev_contact_lambda / _prev_contact_stick_flag / … L800-805 Contact-slot-indexed; self-decays as contacts vanish/reappear after reset, so likely fine to ignore

There's also a smoking-gun comment at L636 that hints the authors already considered this:

"Dynamic teleportation: also set body_q_prev and body_qd."

… but that's a user-facing note — there's no public method on SolverVBD that does the per-world clear, so callers can't actually act on it cleanly.

For comparison, this PR fixes the same flavor of bug on the MJWarp side by calling mujoco_warp.reset_data(reset=mask) from a new _reset_solver_internals hook. The hook is the right contract for VBD too — NewtonCoupledMJWarpVBDManager in particular is currently silently carrying the same MJWarp NaN-warmstart bug because its rigid sub-solver is an SolverMuJoCo instance that this PR's override doesn't currently reach.

Questions for you:

  1. Is the right path an upstream SolverVBD.reset(state, world_mask=...) (parallel to newton#2657 for MJWarp and the kernel-dtype work in newton#2932 for Kamino)? Happy to file that issue if so.
  2. Or do you prefer we ship a lab-side stopgap that reaches into solver.body_q_prev / solver.joint_sigma_prev / etc. with per-world masked clear kernels — same flavor of invasion as mujoco_warp.reset_data(solver.mjw_model, solver.mjw_data, …) already in this PR? I'd rather not, but it's an option if upstream timelines are tight.
  3. Anything in the buffer list above I've got wrong — e.g. buffers that recompute every step and don't actually need clearing, or buffers I missed?

Not blocking this PR — happy to keep it scoped to MJWarp and follow up with whatever you recommend.

@mmichelis mmichelis left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the NaN fix! It would indeed be quite nice if there was a regression test, to verify NaNs are reset correctly.

# ``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

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.

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)

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.

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.

@mmichelis

Copy link
Copy Markdown
Contributor

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 SolverVBD to see whether the new _reset_solver_internals hook should be plumbed there too. Findings: VBD carries a non-trivial pile of per-world / per-body / per-joint state that survives IsaacLab's standard env reset, because env reset only writes joint_q / joint_qd / body_q and never touches solver internals.

Buffers in solver_vbd.py that look like they'd benefit from a per-world clear on env.reset(env_ids):

Buffer Where Why stale data matters
body_q_prev L637 Friction tangential displacement reads this; post-teleport it points at the pre-reset pose so friction sees a "jump" worth of velocity
particle_q_prev L465 Same problem for cloth/deformable verts
pos_prev_collision_detection L535 Drives accumulated-displacement collision retrigger; stale = missed / duplicated collisions
joint_lambda_lin / joint_lambda_ang L698-699 Augmented-Lagrangian state (hard mode)
joint_C0_lin / joint_C0_ang L700-701 Hard-mode constraint snapshot
joint_sigma_prev / joint_kappa_prev / joint_dkappa_prev L704-706 Dahl friction state — the code comment explicitly notes "persistent across timesteps"
_prev_contact_lambda / _prev_contact_stick_flag / … L800-805 Contact-slot-indexed; self-decays as contacts vanish/reappear after reset, so likely fine to ignore
There's also a smoking-gun comment at L636 that hints the authors already considered this:

"Dynamic teleportation: also set body_q_prev and body_qd."

… but that's a user-facing note — there's no public method on SolverVBD that does the per-world clear, so callers can't actually act on it cleanly.

For comparison, this PR fixes the same flavor of bug on the MJWarp side by calling mujoco_warp.reset_data(reset=mask) from a new _reset_solver_internals hook. The hook is the right contract for VBD too — NewtonCoupledMJWarpVBDManager in particular is currently silently carrying the same MJWarp NaN-warmstart bug because its rigid sub-solver is an SolverMuJoCo instance that this PR's override doesn't currently reach.

Questions for you:

  1. Is the right path an upstream SolverVBD.reset(state, world_mask=...) (parallel to newton#2657 for MJWarp and the kernel-dtype work in newton#2932 for Kamino)? Happy to file that issue if so.
  2. Or do you prefer we ship a lab-side stopgap that reaches into solver.body_q_prev / solver.joint_sigma_prev / etc. with per-world masked clear kernels — same flavor of invasion as mujoco_warp.reset_data(solver.mjw_model, solver.mjw_data, …) already in this PR? I'd rather not, but it's an option if upstream timelines are tight.
  3. Anything in the buffer list above I've got wrong — e.g. buffers that recompute every step and don't actually need clearing, or buffers I missed?

Not blocking this PR — happy to keep it scoped to MJWarp and follow up with whatever you recommend.

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 solver.body_inertia_q is another thing that needs to be reset.

@AntoineRichard

AntoineRichard commented Jun 1, 2026 •

Copy link
Copy Markdown
Collaborator Author

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 SolverVBD to see whether the new _reset_solver_internals hook should be plumbed there too. Findings: VBD carries a non-trivial pile of per-world / per-body / per-joint state that survives IsaacLab's standard env reset, because env reset only writes joint_q / joint_qd / body_q and never touches solver internals.
Buffers in solver_vbd.py that look like they'd benefit from a per-world clear on env.reset(env_ids):
Buffer Where Why stale data matters
body_q_prev L637 Friction tangential displacement reads this; post-teleport it points at the pre-reset pose so friction sees a "jump" worth of velocity
particle_q_prev L465 Same problem for cloth/deformable verts
pos_prev_collision_detection L535 Drives accumulated-displacement collision retrigger; stale = missed / duplicated collisions
joint_lambda_lin / joint_lambda_ang L698-699 Augmented-Lagrangian state (hard mode)
joint_C0_lin / joint_C0_ang L700-701 Hard-mode constraint snapshot
joint_sigma_prev / joint_kappa_prev / joint_dkappa_prev L704-706 Dahl friction state — the code comment explicitly notes "persistent across timesteps"
_prev_contact_lambda / _prev_contact_stick_flag / … L800-805 Contact-slot-indexed; self-decays as contacts vanish/reappear after reset, so likely fine to ignore
There's also a smoking-gun comment at L636 that hints the authors already considered this:

"Dynamic teleportation: also set body_q_prev and body_qd."

… but that's a user-facing note — there's no public method on SolverVBD that does the per-world clear, so callers can't actually act on it cleanly.
For comparison, this PR fixes the same flavor of bug on the MJWarp side by calling mujoco_warp.reset_data(reset=mask) from a new _reset_solver_internals hook. The hook is the right contract for VBD too — NewtonCoupledMJWarpVBDManager in particular is currently silently carrying the same MJWarp NaN-warmstart bug because its rigid sub-solver is an SolverMuJoCo instance that this PR's override doesn't currently reach.
Questions for you:

  1. Is the right path an upstream SolverVBD.reset(state, world_mask=...) (parallel to newton#2657 for MJWarp and the kernel-dtype work in newton#2932 for Kamino)? Happy to file that issue if so.
  2. Or do you prefer we ship a lab-side stopgap that reaches into solver.body_q_prev / solver.joint_sigma_prev / etc. with per-world masked clear kernels — same flavor of invasion as mujoco_warp.reset_data(solver.mjw_model, solver.mjw_data, …) already in this PR? I'd rather not, but it's an option if upstream timelines are tight.
  3. Anything in the buffer list above I've got wrong — e.g. buffers that recompute every step and don't actually need clearing, or buffers I missed?

Not blocking this PR — happy to keep it scoped to MJWarp and follow up with whatever you recommend.

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 solver.body_inertia_q is another thing that needs to be reset.

Ok, so the current form of the PR is correct, and that's something you'll be able to leverage? @mmichelis

@AntoineRichard
AntoineRichard force-pushed the antoiner/mjwarp-reset-data branch from 33517a0 to cca3053 Compare June 8, 2026 07:12
@mmichelis

Copy link
Copy Markdown
Contributor

Ok, so the current form of the PR is correct, and that's something you'll be able to leverage? @mmichelis

@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.

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.
@AntoineRichard
AntoineRichard force-pushed the antoiner/mjwarp-reset-data branch from 0744b24 to ac10be7 Compare July 8, 2026 12:12
@AntoineRichard
AntoineRichard merged commit 05bdde8 into isaac-sim:develop Jul 8, 2026
37 checks passed
@github-project-automation github-project-automation Bot moved this from In review to Done in Isaac Lab Jul 8, 2026
hujc7 added a commit to hujc7/IsaacLab that referenced this pull request Jul 8, 2026
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.
matthewtrepte pushed a commit to matthewtrepte/IsaacLab that referenced this pull request Aug 4, 2026
# 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`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation infrastructure isaac-lab Related to Isaac Lab team

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants