Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/source/how-to/solver_tuning_mjwarp.rst
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ reporting, and sensors are verified; a larger interval reduces synchronization
work but can expose stale data. ``save_to_mjcf``, ``use_mujoco_cpu``, and
``disable_contacts`` are diagnostic tools, not production tuning targets.

``update_data_interval`` counts solver substeps, with
``decimation * num_substeps`` solver steps per control step. ``0`` disables
periodic imports. With MuJoCo Warp, state writes through Isaac Lab's asset APIs
still synchronize flagged worlds at the next ``forward()`` or physics-step
boundary, including environment resets. The native MuJoCo CPU backend only
synchronizes template world 0 when that world is flagged. Raw Newton state writes
must also flag the manager's reset masks through ``NewtonManager.invalidate_fk()``.

The diagnose-first order is: validate the model and fixed reproduction; choose
timestep and substeps; size capacities; validate convergence; tune contact
behavior and the contact pipeline; then optimize measured costs.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* Fixed MJWarp losing authored state writes and environment resets when the next solver substep
skipped its periodic Newton-state import. Flagged worlds were synchronized at forward and
physics-step boundaries even with sparse or disabled periodic imports, including CUDA graph replay.
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,15 @@ def _reset_solver_internals(cls, world_mask: wp.array | None) -> None:
solver substep warm-starts from the NaN — the world is then permanently
dead. See https://github.com/newton-physics/newton/issues/1266.

With ``use_mujoco_cpu=True`` the solver owns a single global ``MjData``
and its reset path is not mask-aware — it clears the buffers for every
world. Since this hook can fire with an all-``False`` mask (e.g. on
every forward boundary after a graph-captured write), the CPU path is
gated on at least one world actually being flagged so warm-starting is
not defeated on every step.
When state imports are sparse or disabled, also push the authored
joint state into MuJoCo for the flagged worlds. ``reset(flags=0)``
only clears history; otherwise the next substep can overwrite the
authored state before importing it.

With ``use_mujoco_cpu=True`` the solver owns a single ``MjData`` for
template world 0. Gate the CPU path on that world's mask entry so
other worlds' resets cannot clear its history or copy uninitialized
coordinate-conversion buffers into it.

Args:
world_mask: Per-world bool mask of shape ``(world_count + 1,)``.
Expand All @@ -128,11 +131,16 @@ def _reset_solver_internals(cls, world_mask: wp.array | None) -> None:
"""
if world_mask is None:
return
if cls._solver.use_mujoco_cpu and not world_mask.numpy().any():
if cls._solver.use_mujoco_cpu and not world_mask.numpy()[0]:
return
# flags=0 skips the joint-state reset to model defaults: IsaacLab owns
# joint_q/joint_qd and has already written the authored reset pose.
cls._solver.reset(cls.backend.state_0, world_mask=world_mask, flags=0)
if cls._solver.update_data_interval != 1:
# Newton has no public masked import. With sleeping disabled,
# reset(flags=0) skips it, so reuse the pinned solver's conversion.
data = cls._solver.mj_data if cls._solver.use_mujoco_cpu else cls._solver.mjw_data
cls._solver._update_mjc_data(data, cls.backend.model, cls.backend.state_0, world_mask=world_mask)
Comment thread
AntoineRichard marked this conversation as resolved.
Resolved

@classmethod
def _log_solver_debug(cls) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,12 @@ class MJWarpSolverCfg(NewtonSolverCfg):
"""Dictionary mapping joint names to specific gear ratios, overriding the `default_actuator_gear`."""

update_data_interval: int = 1
"""Frequency (in simulation steps) at which to update the MuJoCo Data object from the Newton state.
"""Frequency (in solver substeps) at which to update the MuJoCo Data object from the Newton state.

If 0, Data is never updated after initialization.
If 0, periodic state imports are disabled after initialization. With MuJoCo Warp, authored
state writes that flag the manager's reset mask are still synchronized for the affected
worlds at the next forward or physics-step boundary, independently of this interval.
The native MuJoCo CPU backend only synchronizes template world 0 when it is flagged.
"""

save_to_mjcf: str | None = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1458,6 +1458,97 @@ def clear_forces(self):
]


@pytest.fixture
def single_joint_world() -> ModelBuilder:
"""Build an unactuated revolute joint with no gravity or damping."""
world = ModelBuilder(gravity=(0.0, 0.0, 0.0))
body = world.add_link(mass=1.0, inertia=wp.mat33(np.eye(3)))
joint = world.add_joint_revolute(parent=-1, child=body, axis=(0, 0, 1))
world.add_articulation([joint])
return world


@pytest.mark.parametrize("device, use_cuda_graph", [(device, device != "cpu") for device in test_devices()])
@pytest.mark.parametrize("update_data_interval", [0, 2], ids=["disabled", "sparse"])
def test_mjwarp_authored_reset_survives_sparse_state_import(
single_joint_world, device, use_cuda_graph, update_data_interval
):
"""Sparse imports preserve authored resets and the motion of an unselected world."""
sim_cfg = SimulationCfg(
dt=1.0 / 120.0,
device=device,
gravity=(0.0, 0.0, 0.0),
physics=NewtonCfg(
solver_cfg=MJWarpSolverCfg(update_data_interval=update_data_interval, njmax=5, nconmax=5),
num_substeps=1,
use_cuda_graph=use_cuda_graph,
),
)
with build_simulation_context(sim_cfg=sim_cfg) as sim:
builder = sim.get_or_create_backend(NewtonBuilderCfg(physics_cfg=sim.cfg.physics))
single_joint_world.joint_qd[0] = 0.125
builder.add_world(single_joint_world)
builder.add_world(single_joint_world)
sim.reset()

# Warm up before the final graph capture so sparse imports start off cadence.
sim.step(render=False)
NewtonManager.activate_newton_actuator_path()
NewtonManager.set_decimation(1)
state = NewtonManager.get_state_0()
articulation_ids = ArticulationView(NewtonManager.backend.model, "*", verbose=False).articulation_ids
env_ids = wp.array([0], dtype=wp.int32, device=device)
other_position = state.joint_q.numpy()[1]

for call_forward, position, velocity in ((False, 0.25, 0.5), (True, -0.25, -0.5)):
state.joint_q[:1].fill_(position)
state.joint_qd[:1].fill_(velocity)
NewtonManager.invalidate_fk(env_ids=env_ids, articulation_ids=articulation_ids)
if call_forward:
# Distinct uncommitted inputs expose an import that ignores the reset mask.
state.joint_q[1:].fill_(1.25)
state.joint_qd[1:].fill_(-0.75)
sim.forward()
data = NewtonManager._solver.mjw_data
np.testing.assert_allclose(data.qpos.numpy()[1], other_position, atol=1e-6)
np.testing.assert_allclose(data.qvel.numpy()[1], 0.125, atol=1e-6)
# Restore these inputs before the next periodic, unmasked import.
state.joint_q[1:].fill_(other_position)
state.joint_qd[1:].fill_(0.125)
sim.step(render=False)

# Both unactuated joints move at constant velocity over one solver step.
expected_position = position + velocity * sim_cfg.dt
other_position += 0.125 * sim_cfg.dt
np.testing.assert_allclose(state.joint_q.numpy(), [expected_position, other_position], atol=1e-6)
np.testing.assert_allclose(state.joint_qd.numpy(), [velocity, 0.125], atol=1e-6)


@pytest.mark.parametrize("reset_world", [0, 1], ids=["template_world", "other_world"])
def test_mujoco_cpu_authored_reset_only_updates_selected_template_world(monkeypatch, single_joint_world, reset_world):
"""Native MuJoCo's single MjData preserves history unless template world 0 is reset."""
builder = ModelBuilder(gravity=(0.0, 0.0, 0.0))
builder.add_world(single_joint_world)
builder.add_world(single_joint_world)
model = builder.finalize(device="cpu")
solver = SolverMuJoCo(model, use_mujoco_cpu=True, separate_worlds=True, update_data_interval=2)
state = model.state()
state.joint_q.assign(np.array([0.25, 0.5], dtype=np.float32))
state.joint_qd.assign(np.array([0.5, 1.0], dtype=np.float32))
solver.mj_data.qpos[:] = 1.25
solver.mj_data.qvel[:] = -0.75
solver.mj_data.qacc_warmstart[:] = 13.0
monkeypatch.setattr(NewtonManager, "_solver", solver)
monkeypatch.setattr(NewtonManager, "backend", SimpleNamespace(model=model, state_0=state))
world_mask = wp.array(np.arange(model.world_count + 1) == reset_world, dtype=wp.bool, device="cpu")

NewtonMJWarpManager._reset_solver_internals(world_mask)

np.testing.assert_allclose(solver.mj_data.qpos, 0.25 if reset_world == 0 else 1.25)
np.testing.assert_allclose(solver.mj_data.qvel, 0.5 if reset_world == 0 else -0.75)
np.testing.assert_allclose(solver.mj_data.qacc_warmstart, 0.0 if reset_world == 0 else 13.0)


# ---------------------------------------------------------------------------
# Regression: an env reset written through the data layer must land in the
# manager's canonical _state_0 after an odd number of steps when CUDA graphs
Expand Down
Loading