Skip to content
Open
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
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ Guidelines for modifications:
* Kousheek Chakraborty
* Kris Wilson
* Krishna Lakhi
* Kunal Dabbe
* Lin He
* Lionel Gulich
* Lior Ben Horin
Expand Down
7 changes: 7 additions & 0 deletions docs/source/how-to/solver_tuning_mjwarp.rst
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ rows per environment; contacts can consume multiple rows, and joint limits,
drives, equality constraints, and mimic constraints also consume rows. Do not
derive ``njmax`` directly from ``nconmax``.

With ``NewtonCfg.debug_mode=True`` and the GPU MJWarp backend
(``MJWarpSolverCfg.use_mujoco_cpu=False``), the MJWarp driver reports capacity
overflow and names the exhausted buffer: ``nconmax``, ``njmax`` / ``njmax_nnz``,
the collision pipeline's ``rigid_contact_max``, and MuJoCo Warp's broadphase,
narrowphase, CCD, height-field, and related buffers. Each buffer is reported
once per solver instance.

Increase the relevant capacity when diagnostics show an overflow, contacts
disappear in dense states, or behavior changes with object count. Measure the
worst case across resets and randomized scenes, add task-specific headroom, and
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* Added MJWarp capacity-overflow diagnostics in ``NewtonCfg.debug_mode`` that name the exhausted
``nconmax``, ``njmax``, or collision-pipeline contact buffer, and each other MuJoCo Warp
overflow buffer, once per solver instance.
113 changes: 110 additions & 3 deletions source/isaaclab_newton/isaaclab_newton/physics/mjwarp_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@
from __future__ import annotations

import logging
from functools import cache
from typing import TYPE_CHECKING, Any

import numpy as np
import warp as wp
from newton import Contacts, Model, State
from newton.solvers import SolverMuJoCo
from newton import Contacts, Control, Model, State
from newton.solvers import SolverBase, SolverMuJoCo

from .newton_solver import NewtonSolver, solver_kwargs

Expand All @@ -25,6 +26,12 @@

_SENSORS_BY_STATE_ATTRIBUTE = {"body_qdd": "the IMU or PVA sensor", "body_parent_f": "the joint-wrench sensor"}

_OVERFLOW_LABEL_OVERRIDES = {
"SOLVER_NCONMAX": "solver contact buffer (nconmax)",
"CONTACT_PIPELINE": "collision pipeline contact buffer (rigid_contact_max)",
"NEFC": "constraint rows (njmax)",
}


@wp.func
def _nonfinite(values: wp.array2d(dtype=Any), world: int, column: int) -> bool:
Expand Down Expand Up @@ -68,6 +75,17 @@ class MJWarpSolver(NewtonSolver):
single_state = True
max_deterministic_mode = wp.DeterministicMode.RUN_TO_RUN

def __init__(
self,
cfg: MJWarpSolverCfg,
model: Model,
mode: wp.DeterministicMode,
env_template: str | None = None,
) -> None:
super().__init__(cfg, model, mode, env_template)
self._step_observables: SolverBase.Observables | None = None
self._warned_overflow_bits: int = 0

@classmethod
def applied_deterministic_mode(cls, cfg: MJWarpSolverCfg, mode: wp.DeterministicMode) -> wp.DeterministicMode:
"""MuJoCo on the CPU is reproducible on its own and Warp's mode does not reach it, so none applies."""
Expand Down Expand Up @@ -157,6 +175,20 @@ def mark_non_finite_worlds(self, state: State, faults: wp.array) -> None:
device=faults.device,
)

def step(
self,
state_in: State,
state_out: State,
control: Control,
contacts: Contacts | None,
dt: float,
*,
observables: SolverBase.Observables | None = None,
) -> None:
"""Advance one substep and retain the outputs inspected after the step."""
self._step_observables = observables
super().step(state_in, state_out, control, contacts, dt, observables=observables)

def reset(self, state: State, world_mask: wp.array) -> None:
"""Clear solver history and synchronize authored joint state for masked worlds.

Expand All @@ -177,9 +209,10 @@ def reset(self, state: State, world_mask: wp.array) -> None:
solver._update_mjc_data(data, solver.model, state, world_mask=world_mask)

def check_step(self, captured: bool, debug: bool) -> None:
"""Log MuJoCo solver convergence statistics in debug mode."""
"""Log MuJoCo capacity-overflow and convergence diagnostics in debug mode."""
if not debug:
return
self._warn_overflow()
solver = self.native
niter = solver.mjw_data.solver_niter.numpy()
data = {"max": np.max(niter), "mean": np.mean(niter), "min": np.min(niter), "std": np.std(niter)}
Expand All @@ -193,3 +226,77 @@ def fixed_tendon_control(cls, cfg: MJWarpSolverCfg, articulation, model: Model)
from .mjwarp_tendon_control import create_mjwarp_tendon_control

return create_mjwarp_tendon_control(articulation, model)

def _diagnostic_observables(self) -> frozenset[str]:
"""Return the overflow observable needed for debug diagnostics, when the backend supports it."""
if self.cfg.use_mujoco_cpu:
return frozenset()
return frozenset({SolverMuJoCo.ObservableKind.OVERFLOW})

def _warn_overflow(self) -> None:
"""Warn once per newly observed capacity-overflow buffer."""
if self._step_observables is None or self._step_observables.overflow is None:
return
masks = self._step_observables.overflow.numpy()
if masks.size == 0:
return
all_bits = int(np.bitwise_or.reduce(masks))
if all_bits == 0:
return
capacity_bits = all_bits & ~_ignored_overflow_bits()
new_bits = capacity_bits & ~self._warned_overflow_bits
if new_bits == 0:
return
self._warned_overflow_bits |= new_bits

world_masks = masks[:-1]
global_mask = int(masks[-1])
affected_worlds = np.flatnonzero(world_masks & new_bits)
global_affected = bool(global_mask & new_bits)

labels = _overflow_labels()
names, known_bits = [], 0
for bit in sorted(labels):
if new_bits & bit:
names.append(labels[bit])
known_bits |= bit
unknown_bits = new_bits & ~known_bits
if unknown_bits:
names.append(f"unknown overflow bits 0x{unknown_bits:x}")

worlds = [str(int(index)) for index in affected_worlds[:8]]
if affected_worlds.size > len(worlds):
worlds.append(f"and {affected_worlds.size - len(worlds)} more")
scope = f"{affected_worlds.size} environment(s) ({', '.join(worlds)})" if affected_worlds.size else ""
if global_affected:
scope = f"{scope} and the global world" if scope else "the global world"
logger.warning(
"MJWarp capacity overflow in %s: %s. "
"Increase the named capacity; dropped contacts or constraints can invalidate the simulation.",
scope,
", ".join(names),
)


@cache
def _overflow_labels() -> dict[int, str]:
"""Return user-facing labels for Newton and MuJoCo Warp overflow bits."""
ignored_bits = _ignored_overflow_bits()
labels = {}
for flag in SolverMuJoCo.OverflowBits:
if int(flag) & ignored_bits:
continue
labels[int(flag)] = _OVERFLOW_LABEL_OVERRIDES.get(flag.name, flag.name.lower())
_, mujoco_warp = SolverMuJoCo.import_mujoco()
for flag in mujoco_warp.OverflowType:
if flag.name in {"NONE", "ALL"} or int(flag) & ignored_bits:
continue
labels[int(flag)] = _OVERFLOW_LABEL_OVERRIDES.get(flag.name, flag.name.lower())
return labels


@cache
def _ignored_overflow_bits() -> int:
"""Return MuJoCo Warp bits that report non-convergence rather than capacity overflow."""
_, mujoco_warp = SolverMuJoCo.import_mujoco()
return int(mujoco_warp.OverflowType.ITERATIONS | mujoco_warp.OverflowType.LS_ITERATIONS)
30 changes: 20 additions & 10 deletions source/isaaclab_newton/isaaclab_newton/physics/newton_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,11 @@ def __init__(
] = []
"""Run after each solve, before output-state swapping and force clearing."""
self.solver_observables: SolverBase.Observables | None = None
"""Requested solver outputs populated by every substep, or ``None``."""
"""Caller-requested solver outputs populated by every substep, or ``None``."""
self._diagnostic_observable_kinds: frozenset[str] = frozenset()
"""Solver-owned diagnostic output kinds allocated with the step observables."""
self._step_observables: SolverBase.Observables | None = None
"""Caller-requested and solver-owned outputs passed to every solver substep."""
self.post_step_callbacks: list[Callable[[], None]] = []
"""Run once after the last solver substep of a :meth:`step`."""
self.solver_init_callbacks: list[Callable[[], None]] = []
Expand All @@ -496,6 +500,8 @@ def close(self) -> None:
self.solver = self.solver_ops = self.collision_pipeline = self.contacts = self.contact_observables = None
self.actuators = None
self.staged_body_f = self.capture = self.solver_observables = None
self._diagnostic_observable_kinds = frozenset()
self._step_observables = None
self.post_solver_substep_callbacks = []
self.graphs = {}
self.contact_sensors, self.imu_sensors = {}, []
Expand Down Expand Up @@ -533,6 +539,8 @@ def init_solver(
solver = self.solver = ops.native
# A newly built solver already reflects the setup-time model. Subsequent changes remain queued.
self.model_changes.clear()
diagnostic = ops._diagnostic_observables() if self.cfg.debug_mode else frozenset()
Comment thread
KuNaL8103 marked this conversation as resolved.
Resolved
self._diagnostic_observable_kinds = diagnostic
if initial_body_variants:
# MuJoCo compiles one geom layout for all worlds, before their variants diverge.
bodies, variants = zip(*initial_body_variants, strict=True)
Expand All @@ -546,11 +554,14 @@ def init_solver(
if not ops.single_state:
ops.init_state(self.state_1)
self._allocate_contacts()
requested = set(observable_kinds or ())
caller_kinds = set(observable_kinds or ())
step_kinds = caller_kinds | diagnostic
requested = set(step_kinds)
if self.contact_sensors:
requested.update(SensorContact.solver_observable_kinds)
outputs = solver.observables(requested, contacts=self.contacts) if requested else None
self.solver_observables = outputs.select(observable_kinds) if observable_kinds else None
self.solver_observables = outputs.select(caller_kinds) if caller_kinds else None
self._step_observables = outputs.select(step_kinds) if step_kinds else None
self.contact_observables = outputs if self.contact_sensors else None
state_0 = self.state_0
self.staged_body_f = wp.zeros_like(state_0.body_f) if state_0.body_count else None
Expand Down Expand Up @@ -723,15 +734,14 @@ def add_contact_sensor(
if self.contacts is None:
self._allocate_contacts()
if self.contact_observables is None:
self.contact_observables = self.solver_observables
if self.contact_observables is None or not SensorContact.solver_observable_kinds.issubset(
self.contact_observables.kinds
):
existing = self.solver_observables
self.contact_observables = self.solver.observables(
existing = self._step_observables or self.solver_observables
self.contact_observables = existing
if existing is None or not SensorContact.solver_observable_kinds.issubset(existing.kinds):
outputs = self.solver.observables(
SensorContact.solver_observable_kinds | (existing.kinds if existing is not None else set()),
contacts=self.contacts,
)
self.contact_observables = outputs
if existing is not None:
# Keep arrays already bound by substep consumers while extending the final solve's outputs.
for name, value in vars(existing).items():
Expand Down Expand Up @@ -982,7 +992,7 @@ def _run_solver_substeps(self, contacts: Contacts | None, *, observables: Solver
callback(state)
state_out = state if ops.single_state else self.state_1
# Substep consumers need every solve; sensors alone need only the final one.
step_observables = self.solver_observables
step_observables = self._step_observables or self.solver_observables
if observables is not None and i == num_substeps - 1:
step_observables = observables
ops.step(state, state_out, control, contacts, dt, observables=step_observables)
Expand Down
17 changes: 11 additions & 6 deletions source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,20 +573,25 @@ def release_solver_observables(self, owner: object) -> None:
if self._requested_solver_observables.pop(owner, None) is None:
return
backend = self.backend
if backend is None or backend.solver_observables is None:
step_observables = None if backend is None else backend._step_observables
if step_observables is None:
return
kinds = set().union(*self._requested_solver_observables.values())
if kinds == backend.solver_observables.kinds:
caller_kinds = set().union(*self._requested_solver_observables.values())
step_kinds = caller_kinds | backend._diagnostic_observable_kinds
current_caller = backend.solver_observables.kinds if backend.solver_observables is not None else frozenset()
current_step = step_observables.kinds
if caller_kinds == current_caller and step_kinds == current_step:
return
backend.solver_observables = backend.solver_observables.select(kinds) if kinds else None
backend.solver_observables = step_observables.select(caller_kinds) if caller_kinds else None
backend._step_observables = step_observables.select(step_kinds) if step_kinds else None
if backend.contact_observables is not None:
backend.contact_observables = backend.contact_observables.select(
kinds | SensorContact.solver_observable_kinds
step_kinds | SensorContact.solver_observable_kinds
)
backend.invalidate_graph()

def get_solver_observables(self) -> SolverBase.Observables | None:
"""Return the outputs populated by each solver substep, or ``None`` when unrequested."""
"""Return the caller-requested outputs populated by each solver substep, or ``None``."""
return self.backend.solver_observables if self.backend is not None else None

def get_scene_data_provider(self) -> SceneDataProvider:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,3 +268,7 @@ def fixed_tendon_control(cls, cfg: NewtonSolverCfg, articulation: Any, model: Mo
"The configured solver does not drive fixed tendons. Fixed-tendon targets require a solver that transmits"
" to tendons, such as MJWarp."
)

def _diagnostic_observables(self) -> frozenset[str]:
"""Return solver outputs this driver consumes for its own diagnostics."""
return frozenset()
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ def backend_stub(**fields):
backend.contact_sensors = {}
backend.contact_observables = None
backend.solver_observables = None
backend._diagnostic_observable_kinds = frozenset()
backend._step_observables = None
backend.__dict__.update(fields)
return backend

Expand Down
32 changes: 32 additions & 0 deletions source/isaaclab_newton/test/physics/test_newton_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,38 @@ def test_hydroelastic_contacts_keep_per_contact_stiffness_when_nconmax_grows(dev
assert np.any(backend.contacts.rigid_contact_stiffness.numpy()[:contact_count] > 0.0)


@pytest.mark.kitless
@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA))
def test_mjwarp_reports_nconmax_overflow_in_debug(device: str, caplog) -> None:
"""Debug mode allocates the overflow observable and reports a solver contact-buffer overflow."""
builder = newton.ModelBuilder()
builder.add_ground_plane()
for i in range(4):
body = builder.add_body(xform=wp.transform((i * 0.1, 0.3, 0.0), wp.quat_identity()), mass=0.1)
builder.add_shape_sphere(body, radius=0.05)

cfg = NewtonCfg(
solver_cfg=MJWarpSolverCfg(use_mujoco_contacts=False, nconmax=1),
num_substeps=1,
debug_mode=True,
use_cuda_graph=False,
)
cfg.solver_cfg.class_type.prepare_builder(cfg.solver_cfg, builder)
backend = NewtonBackend(NewtonBackendCfg(physics_cfg=cfg, device=device), builder, dt=1.0 / 60.0)
backend.init_solver()
backend.actuators_active = True

with caplog.at_level(logging.WARNING, logger="isaaclab_newton.physics.mjwarp_solver"):
backend.step()

assert backend.solver_observables is None
overflow = backend._step_observables.overflow if backend._step_observables is not None else None
assert overflow is not None, "debug mode did not allocate the overflow observable"
assert int(overflow.numpy()[-1]) & int(SolverMuJoCo.OverflowBits.SOLVER_NCONMAX)
warnings = [record.getMessage() for record in caplog.records if record.levelno == logging.WARNING]
assert any("nconmax" in message for message in warnings)


def test_collision_cfg_is_rejected_when_the_solver_does_not_use_the_collision_pipeline():
backend = backend_stub(
cfg=NewtonCfg(solver_cfg=MJWarpSolverCfg(use_mujoco_contacts=True), collision_cfg=NewtonCollisionPipelineCfg()),
Expand Down
Loading